(*--------------------------------------------------------------------------- Copyright (c) 2026 Thomas Gazagnaire. All rights reserved. SPDX-License-Identifier: ISC ---------------------------------------------------------------------------*) module Spi = Catalog.Spi module Value = Catalog.Value module Cursor = Catalog.Cursor module Register = Catalog.Register module Q = Query let unsupported what = Catalog.Error.fail_unsupported "engine: %s is not supported yet" what let conflict : Ast.insert_conflict -> Spi.Schema.conflict option = function | Unspecified -> None | Rollback -> Some `Rollback | Abort -> Some `Abort | Fail -> Some `Fail | Ignore -> Some `Ignore | Replace -> Some `Replace let action : Ast.fk_action -> Spi.Schema.action = function | No_action -> `No_action | Restrict -> `Restrict | Cascade -> `Cascade | Set_null -> `Set_null | Set_default -> `Set_default let order desc = if desc then Some `Desc else None let indexed_key (c : Ast.indexed_column) = Spi.Schema.key ?order:(order c.desc) ?collation:c.collation c.column (* The primary key of [ct], in either spelling: on a column or as a table constraint. *) let primary_key_of (ct : Ast.create_table) = List.filter_map (fun (c : Ast.column_def) -> Option.map (fun _ -> Spi.Schema.key ?order:(order c.pk_desc) c.name) c.primary_key) ct.columns @ List.concat_map (function | Ast.Primary_key (cs, _) -> List.map indexed_key cs | Ast.Unique _ | Ast.Other -> []) ct.table_constraints (* sqlite3's refusals of a table it cannot build, in its words and order: a name declared twice, its constraints and stored expressions, then a WITHOUT ROWID table's key (build.c, sqlite3EndTable). What it decides only of a statement, an unknown COLLATE or a DEFAULT that is no constant, is the statement's ({!Create_table.check_columns}). *) let refuse_table (ct : Ast.create_table) primary_key = Create_table.check_names ct; Create_table.check ct; if ct.ct_without_rowid && primary_key = [] then Catalog.Error.fail_prepare "PRIMARY KEY missing on table %s" ct.tbl_name (* The resolution of [ct]'s PRIMARY KEY and whether it is written on its column. A DESC alias is the table constraint folded into its column, which the column form can never be. *) let primary_key_form (ct : Ast.create_table) = match List.find_opt (fun (c : Ast.column_def) -> c.primary_key <> None) ct.columns with | Some c -> (Option.bind c.primary_key conflict, not (c.is_rowid_alias && c.pk_desc)) | None -> ( List.find_map (function | Ast.Primary_key (_, res) -> Some (conflict res) | _ -> None) ct.table_constraints |> Option.join, false ) (* An expression of [ct] as SQL text: the text [source], [ct]'s statement, holds between [start] and [stop] where it is given, else [e] printed. *) let text ?source e ~start ~stop = match source with | Some sql when start >= 0 && stop <= String.length sql && start < stop -> String.sub sql start (stop - start) | Some _ | None -> Render.expr e let column_schema ?source (ct : Ast.create_table) (c : Ast.column_def) = let default = Option.map (fun (d : Ast.column_default) -> match d.expr with | Lit v -> `Value v | e -> ( match source with | Some sql -> `Expression (Ast.default_text sql d) | None -> `Expression (Render.expr e))) (Catalog.Ident.assoc_opt c.name ct.defaults) in let generated = Option.map (fun (g : Ast.generated_column) -> ( (match g.kind with Virtual -> `Virtual | Stored -> `Stored), Render.expr g.expr )) (Catalog.Ident.assoc_opt c.name ct.generated) in Spi.Schema.column ~decl_type:c.affinity ~not_null:(c.not_null <> None) ?on_not_null:(Option.bind c.not_null conflict) ~unique:(c.unique <> None) ?on_unique:(Option.bind c.unique conflict) ?default ?collation:c.collation ?generated c.name let table_schema ?source ?indexes (ct : Ast.create_table) : Spi.Schema.t = let primary_key = primary_key_of ct in refuse_table ct primary_key; let autoincrement = List.exists (fun (c : Ast.column_def) -> c.autoincrement) ct.columns in if autoincrement && ct.ct_without_rowid then Catalog.Error.fail_prepare "AUTOINCREMENT not allowed on WITHOUT ROWID tables"; let on_primary_key, primary_key_on_column = primary_key_form ct in let uniques = List.filter_map (function | Ast.Unique (cols, res) -> Some (Spi.Schema.unique ?on_conflict:(conflict res) (List.map indexed_key cols)) | Ast.Primary_key _ | Ast.Other -> None) ct.table_constraints in let checks = List.map (fun (k : Ast.check_constraint) -> text ?source k.expr ~start:k.start ~stop:k.stop) ct.checks in let foreign_keys = List.map (fun (f : Ast.foreign_key) -> Spi.Schema.foreign_key ~parent_columns:f.parent_cols ~on_delete:(action f.on_delete) ~on_update:(action f.on_update) ~deferred:f.deferred f.cols f.parent) ct.foreign_keys in Spi.Schema.v ~primary_key ?on_primary_key ~primary_key_on_column:(primary_key_on_column && primary_key <> []) ~uniques ~checks ~foreign_keys ~autoincrement ~without_rowid:ct.ct_without_rowid ~strict:ct.ct_strict ?indexes ct.tbl_name (List.map (column_schema ?source ct) ct.columns) let index_schema (ci : Ast.create_index) = Spi.Schema.index ~unique:ci.unique ?where:(Option.map Render.expr ci.where) ci.name (List.map (function | Ast.Column c -> Spi.Schema.Column (indexed_key c) | Ast.Expression { expr; desc } -> Spi.Schema.expression ?order:(order desc) (Render.expr expr)) ci.keys) (* Rebuild the named scope a correlated subquery sees from the flat per-row values the VM passes (every scanned column, in cursor order) and the [layout] that names them: one [(alias, [(column, value)])] frame per cursor. *) let scope_of_values layout values = let rec go vals = function | [] -> [] | (alias, cols) :: rest -> let n = List.length cols in (alias, List.combine cols (List.filteri (fun i _ -> i < n) vals)) :: go (List.filteri (fun i _ -> i >= n) vals) rest in go values layout (* The aggregate FILTER / HAVING truthiness gate: a non-NULL, non-zero value. *) let keep_truthy v = Value_ops.tri_of v = Value_ops.T let post_select = Lower.post_select let star_col : Ast.result_col = { expr = Ast.Star; alias = None } let window_segments layout = List.map (fun (a, c) -> (a, List.filter (fun n -> n <> Resolve.rowid_sentinel) c)) layout (* A further key of a probe, read from the cursor its source already has: the loop builds sources in its own order, so an earlier source's is in place. *) let equi_key cursors (inner_key, src, outer_key, collation) = { Join.outer = cursors.(src); outer_key; inner_key; collation; nulls = false } (* A source's rows: read before the loop, or sought on every rewind through a key an outer row binds, from the cursors of the sources before it. *) type rows = Read of Value.t list list | Sought of (Cursor.t array -> Cursor.t) let scan_cursors (plan : Plan.t) sources = let arr = Array.of_list (List.map (fun (_, _, rows) -> rows) sources) in (* only a seek is sought, so a hash only ever reads rows already read *) let read i = match arr.(i) with Read rows -> rows | Sought _ -> [] in let cursors = Array.init (Array.length arr) (fun i -> Spi.list_cursor (read i)) in let acc = Array.of_list plan.Plan.accesses in let built = Array.make (Array.length arr) false in let holds i = Q.within_build_budget (read i) in let build i = if (not built.(i)) && i < Array.length acc then begin built.(i) <- true; match acc.(i) with | Plan.Scan | Plan.Ordered _ | Plan.Seek _ -> ( (* the loop builds in its own order, so every cursor a key reads is in place *) match arr.(i) with | Sought seek -> cursors.(i) <- seek cursors | Read _ -> ()) (* the one bucket a constant selects is every row read *) | Plan.Probe { outer = None; _ } -> () | Plan.Probe { key; outer = Some (src, pos); coll; nulls; rest; _ } -> if holds i then cursors.(i) <- Join.probe ?collation:coll ~nulls ~rest:(List.map (equi_key cursors) rest) ~outer:cursors.(src) ~outer_key:pos ~inner:(read i) ~inner_key:key () end in List.iter build plan.Plan.order; (* the loop over the rows a RIGHT or FULL join kept unmatched reads them whole, through a cursor of its own after the sources' *) Array.append cursors (Array.of_list (List.map (fun (i, _) -> Spi.list_cursor (read i)) plan.Plan.unmatched)) (* The synthetic column an aggregate's value is carried in. The NUL byte keeps the name unspellable, so no user column collides with it. *) let agg_column i = Fmt.str "\000agg%d" i (* Replace every aggregate [s] folds by a reference to its column in the grouped relation, registering it through [slot]. Every node is descended into but a subquery, whose aggregates are its own: the left of an IN, a RAISE's message, and a [Window] node's arguments, FILTER predicate, partition keys, order keys and frame bounds -- an aggregate there is the group's, as in [rank() OVER (ORDER BY sum(x))] -- but never the window function itself, which folds over the grouped rows. *) let rec hoist_aggs slot (e : Ast.expr) : Ast.expr = let go = hoist_aggs slot in if Q.is_agg_expr e then Ast.Col (None, slot e) else match e with | Window (f, w) -> let f = match f with | Ast.Func (n, args) -> Ast.Func (n, List.map go args) | Ast.Distinct_agg (n, a) -> Ast.Distinct_agg (n, go a) | Ast.Filter (Ast.Func (n, args), p) -> Ast.Filter (Ast.Func (n, List.map go args), go p) | f -> f in let bound : Ast.frame_bound -> Ast.frame_bound = function | Preceding e -> Preceding (go e) | Following e -> Following (go e) | b -> b in let frame = Option.map (fun (fr : Ast.frame) -> { fr with Ast.start = bound fr.start; end_ = bound fr.end_ }) w.frame in Window ( f, { Ast.partition = List.map go w.partition; order = List.map (fun (e, d) -> (go e, d)) w.order; frame; } ) | e -> Ast.map_expr ~select:Fun.id go e (* Split [s] into the two passes' halves: the aggregates the grouped relation has to carry, each with the column it is carried in, and the select list and ORDER BY with every one of them replaced by a reference to that column. Rewriting is what discovers them, so the list is read back afterwards. *) let split_group_window (s : Ast.select) = let aggs = ref [] in let slot e = match List.find_opt (fun (e', _) -> Ast.equal_expr e' e) !aggs with | Some (_, name) -> name | None -> let name = agg_column (List.length !aggs) in aggs := !aggs @ [ (e, name) ]; name in let cols = List.map (fun (rc : Ast.result_col) -> { rc with Ast.expr = hoist_aggs slot rc.expr }) s.cols in let order_by = List.map (fun (e, d) -> (hoist_aggs slot e, d)) s.order_by in (!aggs, cols, order_by) (* The result column the [nth] ORDER BY term of compound [s] names, over the output column [names], as resolveCompoundOrderBy reads it (src/resolve.c 1641-1700): an integer term is that column and refused outside 1..width, a name is the column of that name, and any other term is the column whose expression it equals in some arm. *) let compound_order_column cat (s : Ast.select) names ~nth term = let position eq x xs = let rec go i = function | [] -> None | y :: rest -> if eq y x then Some i else go (i + 1) rest in go 0 xs in let arms = s :: List.map snd s.Ast.compound in match Resolve.integer_term term with | Some k -> let width = List.length names in if k >= 1 && k <= width then k - 1 else Resolve.out_of_range ~kind:`Order ~nth ~width | None -> ( match term with | Ast.Col (_, name) when position Ast.ident_equal name names <> None -> Option.get (position Ast.ident_equal name names) | e -> ( let env = Q.resolve_env cat in let in_arm a = position Ast.equal_expr e (Resolve.output_exprs env a) in match List.find_map in_arm arms with | Some i -> i | None -> Catalog.Error.fail_prepare "%s ORDER BY term does not match any column in the result set" (Resolve.ordinal nth))) (* The combined relation's layout. A compound's output names can repeat, and its sort keys are positions, so each slot is named by its index: unspellable, so nothing else can resolve to it, and unambiguous, which a repeated output name would not be. *) let combined_slot i = Fmt.str "\000col%d" i (* Does [s] have to read the enclosing row [scope] offers? A scope binding no column has nothing to offer -- a FROM-less outer select builds one -- and a subquery with no free column reads none, so neither needs substituting. Only a subquery that really is correlated does, and only that one can be refused for a substitution the rewriter cannot perform. *) let needs_scope cat scope (s : Ast.select) = List.exists (fun (_, cols) -> cols <> []) scope && Resolve.correlated (Q.resolve_env cat) [] s let stored_call cat ctx name coll args = if Func.reads_the_clock name args then Catalog.Error.fail_runtime "non-deterministic use of %s() in %s" (String.lowercase_ascii name) (Self_ref.in_ ctx) else Q.call cat ?coll name args (* The sequence each column of the compound [s] dedups and orders under, as the arms name them, BINARY's being the catalog's ({!Collation.binary} of its encoding). *) let compound_collations cat (s : Ast.select) width = List.map (fun c -> match (Option.map Collate.resolve c, cat.Q.encoding) with | (None | Some Collation.Binary), (Utf16le | Utf16be) -> Some (Collation.binary cat.Q.encoding) | c, _ -> c) (Resolve.compound_collations (Q.resolve_env cat) s width) let subquery_runner cat params layout subs id left scope_vals = let kind, sub = List.nth subs id in let rows () = cat.Q.subquery cat (scope_of_values layout scope_vals) sub params in match (kind : Lower.subkind) with | Scalar -> ( match rows () with (v :: _) :: _ -> v | _ -> Value.Null) | Exists -> Value.Int (if rows () = [] then 0L else 1L) | In (c : Ir.comparison) -> let col = List.filter_map (function c :: _ -> Some c | [] -> None) (rows ()) in Value_op.in_eval ?aff:c.aff ?coll:c.coll (Option.get left) col | Member held -> Value_op.in_set_mem held (Option.get left) let hooks ?stored cat params layout subs = (* The call goes through the catalog, not straight to {!Func}: a scalar builtin whose answer is the connection's rather than its arguments' is the backend's to answer, and this is every path that applies one. *) let b = { Lower.hooks with call = (fun n coll args -> Q.call cat ?coll n args) } in let b = if subs = [] then b else { b with subquery = subquery_runner cat params layout subs } in let b = match stored with | None -> b | Some ctx -> { b with call = stored_call cat ctx } in match cat.Q.encoding with Utf8 -> b | e -> Lower.stored_text e b let run_group_window cat params (s : Ast.select) ~affinity ~membership layout cursors = let aggs, cols, order_by = split_group_window s in let grouped = let agg_cols = List.map (fun (e, _) : Ast.result_col -> { expr = e; alias = None }) aggs in let s_agg = { s with Ast.cols = star_col :: agg_cols; order_by = []; limit = None; offset = None; distinct = false; } in let g, subs = Lower.aggregate_query ~env:(Q.resolve_env cat) ~encoding:cat.Q.encoding ~params ~affinity ~membership layout s_agg in Closure.run_grouped ~hooks:(hooks cat params layout subs) ~params ~keep:keep_truthy ~affinity g cursors in let segments = window_segments layout @ if aggs = [] then [] else [ ("", List.map snd aggs) ] in let s_win = { s with Ast.cols; order_by } in Window.scan ~encoding:cat.Q.encoding ~params ~affinity ~membership ~grouped:true segments s_win grouped (* One non-compound core: resolve, hoist uncorrelated subqueries to constants, build the source cursors, and run the lowered query on the VM. *) (* The key [(c, v)] of the seek [access] under the affinities its comparison applies, as sqlite3 codes them before a seek (wherecode.c, codeAllEqualityTerms), so the store compares values as they are. *) let seek_key (access : Plan.access) (c, v) = match access with | Plan.Seek { keys; _ } -> ( match List.find_opt (fun (k : Plan.key) -> String.equal k.column c) keys with | Some k -> (c, Value_ops.key_value k.affinity v) | None -> (c, v)) | Plan.Scan | Plan.Ordered _ | Plan.Probe _ -> (c, v) (* How the rows of a select come out of its last stage: computed whole, or the query the VM runs, which can hand them over one at a time. *) type last_stage = | Whole of Value.t list list | Query of Ir.query * Ir.hooks * Catalog.Cursor.t array (* An arm of a compound, run on its own: the compound's ORDER BY, LIMIT and OFFSET are the whole compound's. *) let arm (a : Ast.select) = { a with Ast.compound = []; order_by = []; limit = None; offset = None } (* [s] made ready to run: its counts and table arguments read, the enclosing row [scope] substituted, its CTEs flattened or materialised. *) let prepared ~scope cat s params = let s = Q.table_arguments cat params (Q.counts cat params s) in let s, params = if not (needs_scope cat scope s) then (s, params) else Resolve.bind_scope (Q.resolve_env cat) scope s ~params in let s = Q.flatten_subqueries cat (Q.flatten_ctes cat s) in let cat = if s.Ast.ctes = [] then cat else Q.materialize_ctes cat params s.ctes in (cat, s, params) let rec run ?(scope = []) cat (s : Ast.select) params : Value.t list list = let cat, s, params = prepared ~scope cat s params in if s.Ast.compound = [] then run_core cat params s else compound cat params s and compound cat params s = let base = run_core cat params (arm s) in let arms = List.map (fun (op, a) -> (op, run_core cat params (arm a))) s.Ast.compound in Resolve.check_widths (Q.resolve_env cat) s; combine_compound cat params s base arms and combine_compound cat params (s : Ast.select) base_rows compound_rows = let s = Q.counts cat params s in (* The width is read off the rows rather than the schema: the arms have run, so it is already known, and a compound of no rows needs no sequences. *) let width = let first = function r :: _ -> Some (List.length r) | [] -> None in match first base_rows with | Some n -> n | None -> ( match List.find_map (fun (_, rows) -> first rows) compound_rows with | Some n -> n | None -> 0) in (* the arms name their sequences as the schema spells them; resolve each once here, so the fold's key comparison carries the sequence and not a name *) let colls = compound_collations cat s width in let combined = List.fold_left (fun acc (op, rows) -> Q.set_op ~colls op acc rows) base_rows compound_rows in if s.Ast.order_by = [] && s.limit = None && s.offset = None then combined else let names = Resolve.select_columns (Q.resolve_env cat) s in (* the cursor holds the rows the arms produced, so the layout is their width; [names] answers the ORDER BY terms that name a column *) let width = match combined with r :: _ -> List.length r | [] -> List.length names in let layout = [ ("", List.init width combined_slot) ] in (* [ORDER BY 1 COLLATE nocase COLLATE binary] chains wrappers around the term: the outermost names the sequence and the innermost expression is the one that resolves to a column. Unary [+] is peeled off with them and does not come back: it changes neither the value sorted nor the sequence sorted under. *) let rec bare = function | Ast.Collate (e, _) | Ast.Unary_plus e -> bare e | e -> e in let key ~nth term = let i = compound_order_column cat s names ~nth (bare term) in let col = Ast.Col (None, combined_slot i) in match term with Ast.Collate (_, c) -> Ast.Collate (col, c) | _ -> col in let out = { (post_select [ star_col ]) with Ast.order_by = List.mapi (fun i (e, d) -> (key ~nth:(i + 1) e, d)) s.order_by; limit = s.limit; offset = s.offset; } in let q, subs = Lower.query ~env:(Q.resolve_env cat) ~encoding:cat.Q.encoding ~params layout out in Ir.run ~hooks:(hooks cat params layout subs) ~params q [| Spi.list_cursor combined |] and run_window_core cat params s ~affinity ~membership layout cursors = let raw, segments = Window.scan_select layout s in let q, subs = Lower.query ~env:(Q.resolve_env cat) ~encoding:cat.Q.encoding ~params ~affinity ~membership layout raw in let raw_rows = Ir.run ~hooks:(hooks cat params layout subs) ~params q cursors in Window.scan ~encoding:cat.Q.encoding ~params ~affinity ~membership segments s raw_rows and run_core cat params s = match last_stage cat params s with | Whole rows -> rows | Query (q, hooks, cursors) -> Ir.run ~hooks ~params q cursors and last_stage cat params (s : Ast.select) = let env = Q.resolve_env cat in let s = Resolve.ordinals env s in let s = Resolve.collations env s in let s = Resolve.where_aliases env s in let s = Resolve.reduce_outer_joins env s in let s = Q.lift_outer_aggregates env s in Q.check_calls cat s; (* Plan before folding a subquery to its value, so the path taken is the one EXPLAIN prints for the same query -- it answers before any value exists. *) let plan = Q.plan cat s in let s = Q.hoist_subqueries ~run:(fun sub -> run cat sub params) ~params cat s in let sources = from_sources ~accesses:plan.Plan.accesses cat params s in let layout = List.map (fun (a, c, _) -> (a, c)) sources in let affinity = Plan.column_affinity ~affinity:cat.Q.affinity env s layout in (* What each [IN (SELECT ...)] compares against: the subquery's own affinity, and its rows where it is closed. Answered here rather than folded into the AST because a value list states no affinity, which is what the membership has to read off the other end. *) let membership = Q.membership ~run:(fun sub -> run cat sub params) ~params cat in let cursors = scan_cursors plan sources in if Q.window_compilable s then Whole (run_window_core cat params s ~affinity ~membership layout cursors) else if Q.aggregate_compilable s then let g, subs = Lower.aggregate_query ~env:(Q.resolve_env cat) ~encoding:cat.Q.encoding ~params ~affinity ~membership ~order:plan.Plan.order layout s in Whole (Closure.run_grouped ~hooks:(hooks cat params layout subs) ~params ~keep:keep_truthy ~affinity g cursors) else if Q.window_over_groups s then Whole (run_group_window cat params s ~affinity ~membership layout cursors) else let q, subs = Lower.query ~env:(Q.resolve_env cat) ~encoding:cat.Q.encoding ~params ~affinity ~membership ~order:plan.Plan.order layout s in Query (q, hooks cat params layout subs, cursors) and from_sources ?(accesses = []) cat params (s : Ast.select) = let access i = match List.nth_opt accesses i with Some a -> a | None -> Plan.Scan in let leading = match s.Ast.from with | Ast.Table tr -> source ~access:(access 0) cat params tr | Ast.Unit -> ("", [], Read [ [] ]) | Ast.Values tuples -> let n = match tuples with r :: _ -> List.length r | [] -> 0 in let cols = List.init n (fun i -> Ast.nth_column_name (i + 1)) in ("", cols, Read (List.map (constants cat params) tuples)) | Ast.Select { fs_select; fs_alias } -> let alias = Option.value fs_alias ~default:"" in ( alias, Resolve.select_columns (Q.resolve_env cat) fs_select, Read (run cat fs_select params) ) | Ast.Table_function { tf_name; tf_args; tf_alias } -> let alias = Option.value tf_alias ~default:tf_name in let f = Q.table_function cat tf_name in (alias, f.columns, Read (f.rows (constants cat params tf_args))) in leading :: List.mapi (fun i (j : Ast.join) -> source ~access:(access (i + 1)) cat params j.Ast.table) s.Ast.joins (* Row-independent expressions -- a [VALUES] tuple in a FROM clause or in an INSERT, a table function's arguments -- as values, projected on the register VM over the one empty row they see. That row is what they resolve against, so the scope a subquery among them reads is empty and not the (zero-column) cursor. *) and constants cat params exprs = let cols = List.map (fun e : Ast.result_col -> { expr = e; alias = None }) exprs in let q, subs = Lower.query ~env:(Q.resolve_env cat) ~encoding:cat.Q.encoding ~params [ ("", []) ] (post_select cols) in match Ir.run ~hooks:(hooks cat params [] subs) ~params q [| Spi.list_cursor [ [] ] |] with | [ values ] -> values | _ -> [] and source ?(access = Plan.Scan) cat params (tr : Ast.table_ref) = match tr.Ast.subquery with | Some q -> (* a source is named by its alias, else its own name, as {!Resolve} names it: a table-valued function joined with none is qualified by its name *) let alias = Option.value tr.alias ~default:tr.name in ( alias, Resolve.select_columns (Q.resolve_env cat) q, Read (run cat q params) ) | None -> let alias = Option.value tr.alias ~default:tr.name in (* Only a relation that has an identity publishes the slot: over a view, a WITHOUT ROWID table or a materialised CTE the name [rowid] resolves to nothing, which is what sqlite3 says of it. *) let has_rowid = cat.Q.has_rowid tr.name in let cols = cat.Q.columns tr.name @ if has_rowid then [ Resolve.rowid_sentinel ] else [] in let slot v = if has_rowid then [ v ] else [] in (* A sought row comes from an index, which addresses a key and not a row's identity, so its rowid slot is empty. Nothing reads it: the plan refuses a seek for a query that names the rowid at all. *) let sought rows = List.map (fun vs -> vs @ slot Value.Null) rows in let whole () = List.map (fun (rid, vs) -> vs @ slot (match rid with Some r -> Value.Int r | None -> Value.Null)) (cat.Q.rows_rowid tr.name) in let lookup eqs = Option.map (fun (_, rows) -> sought rows) (cat.Q.index_scan tr.name (List.map (seek_key access) eqs)) in let value = function | c, Q.Value v -> Some (c, v) | _, Q.Outer _ -> None in let rows = match Q.seek_keys cat params access with | None -> Read (whole ()) | Some keys -> ( match List.filter_map value keys with | eqs when List.length eqs = List.length keys -> ( match lookup eqs with | Some rows -> Read rows | None -> Read (whole ())) | _ -> (* a key moves with the outer row, so the index is asked on every rewind and the relation is read only if it declines *) let key cursors = function | c, Q.Value v -> (c, Join.Bound v) | c, Q.Outer (i, j) -> (c, Join.Column (cursors.(i), j)) in Sought (fun cursors -> Join.seek ~lookup ~scan:(lazy (whole ())) (List.map (key cursors) keys))) in (alias, cols, rows) let run_select ?(scope = []) cat s params = try run ~scope cat s params with Ir.Unsupported -> unsupported (Render.select s) (* A select's rows handed over as the VM produces them, as sqlite3 runs an INSERT's source as a co-routine (insert.c, sqlite3Insert). The arms of a UNION ALL with no ORDER BY, LIMIT or OFFSET of its own run one after the other, each handing its rows over (select.c, multiSelect, TK_ALL); every other compound, and a last stage that folds groups or windows, is computed whole first, as its sorter is. *) let iter_select ?(scope = []) cat s params ~f = let each cat params s = match last_stage cat params s with | Whole rows -> List.iter f rows | Query (q, hooks, cursors) -> Ir.iter ~params q (Ir.precompile ~hooks q) cursors ~f in try let cat, s, params = prepared ~scope cat s params in if s.Ast.compound = [] then each cat params s else if s.order_by = [] && s.limit = None && s.offset = None && List.for_all (fun (op, _) -> op = Ast.Union_all) s.compound then begin Resolve.check_widths (Q.resolve_env cat) s; each cat params (arm s); List.iter (fun (_, a) -> each cat params (arm a)) s.compound end else List.iter f (compound cat params s) with Ir.Unsupported -> unsupported (Render.select s) (* The runner a catalog carries: every SELECT the evaluator reaches -- a scalar / IN / EXISTS subquery, a FROM-subquery, a CTE body, a recursive arm -- comes back through this engine, over whichever catalog the caller hands it. *) let select_runner cat scope s params = run ~scope cat s params (* A name no table, view or schema table holds that names a table-valued function of the connection is that function read with no argument: sqlite3's eponymous virtual tables (build.c, sqlite3LocateTable, which registers a pragma's module on the first miss, sqlite3PragmaVtabRegister). *) let eponymous conn (base : Q.catalog) = let fn name = if base.holds name then None else match Connection.table_function conn name with | Some f -> Some f | None -> Func.find_table_function name in let rows name = match fn name with | Some (f : Func.table_function) -> List.map (fun r -> (None, r)) (f.rows []) | None -> base.rows_rowid name in let unless_function name f = match fn name with Some _ -> None | None -> f () in { base with columns = (fun name -> match fn name with Some f -> f.columns | None -> base.columns name); rows = (fun name -> List.map snd (rows name)); rows_rowid = rows; has_rowid = (fun name -> Option.is_none (fn name) && base.has_rowid name); holds = (fun name -> base.holds name || Option.is_some (fn name)); index_scan = (fun name eqs -> unless_function name (fun () -> base.index_scan name eqs)); best_index_for = (fun name cols -> unless_function name (fun () -> base.best_index_for name cols)); affinity = (fun name col -> unless_function name (fun () -> base.affinity name col)); decl_type = (fun name col -> unless_function name (fun () -> base.decl_type name col)); collation = (fun name col -> unless_function name (fun () -> base.collation name col)); row_count = (fun name ~upto -> match fn name with Some _ -> upto | None -> base.row_count name ~upto); } let catalog conn = let cat = Q.of_catalog ~recursion_cap:(Connection.recursion_cap conn) ~subquery:select_runner (Connection.catalog conn) in eponymous conn (Schema_table.over (Connection.catalog conn) (View.over (Connection.catalog conn) { cat with scalar_function = Connection.call conn; table_function = Connection.table_function conn; })) let unlowerable f what = try what () with Ir.Unsupported -> unsupported f (* One named row in scope: its alias, its column names, and its values. *) type frame = string * string list * Value.t list (* A row short of its column list reads as trailing NULLs. A record written before an [ALTER TABLE ADD COLUMN] is short, and a cursor addresses its cells by position, so the padding has to happen before the row becomes one. *) let rec pad cols vals = match (cols, vals) with | [], _ -> [] | _ :: cs, v :: vs -> v :: pad cs vs | _ :: cs, [] -> Value.Null :: pad cs [] (* A table row as a frame. A rowid is published in the scan's hidden slot, so a bare [rowid] resolves as it does in a scan; with none to give, the slot is absent and [rowid] does not resolve there -- which is what a caller holding no rowid means. *) let table_frame ?rowid alias cols vals : frame = match rowid with | None -> (alias, cols, pad cols vals) | Some r -> (alias, cols @ [ Resolve.rowid_sentinel ], pad cols vals @ [ Value.Int r ]) (* The outer bindings a write's expressions see -- a trigger's OLD/NEW rows, an [UPDATE ... FROM] join row -- as frames, in order. *) let scope_frames (scope : Q.binding list) : frame list = List.map (fun (alias, row) -> (alias, List.map fst row, List.map snd row)) scope let lower_cols cat params (frames : frame list) cols = let frames = match frames with [] -> [ ("", [], []) ] | fs -> fs in let layout = List.map (fun (a, c, _) -> (a, c)) frames in let affinity (i, j) = match List.nth_opt frames i with | Some (name, fcols, _) -> Option.bind (List.nth_opt fcols j) (cat.Q.affinity name) | None -> None in ( frames, layout, Lower.query ~env:(Q.resolve_env cat) ~encoding:cat.Q.encoding ~params ~affinity layout (post_select cols) ) (* [cols] projected over [frames]: the lowering above, run over the one row each frame holds. *) let project_cols ?stored cat params (frames : frame list) cols = let frames, layout, (q, subs) = lower_cols cat params frames cols in let cursors = Array.of_list (List.map (fun (_, _, vals) -> Spi.list_cursor [ vals ]) frames) in match Ir.run ~hooks:(hooks ?stored cat params layout subs) ~params q cursors with | [ values ] -> values | _ -> [] let project ?stored cat params frames exprs = project_cols ?stored cat params frames (List.map (fun e : Ast.result_col -> { expr = e; alias = None }) exprs) (* The one value [e] projects to. A projection is one column wide unless [e] is a star, which none of these callers writes. *) let project_one ?stored cat params frames e = match project ?stored cat params frames [ e ] with | [ v ] -> v | _ -> Value.Null | exception Ir.Unsupported -> unsupported (Render.expr e) (* A literal or a placeholder is its own value, as the program {!project_one} compiles would load it: an unbound placeholder reads NULL. Every other expression is lowered and run. *) let eval_const ?(scope = []) cat params (e : Ast.expr) = match e with | Lit v -> v | Numeral s -> Ast.code_number s | Param i -> if i >= 0 && i < Array.length params then params.(i) else Null | _ -> project_one cat params (scope_frames scope) e let eval_in_row ?(scope = []) ?rowid ?stored cat params table cols vals e = project_one ?stored cat params (table_frame ?rowid table cols vals :: scope_frames scope) e (* lang_upsert.html sec.2: the [DO UPDATE] expressions see the conflicting row under the table's name and the row that would have been inserted under the [excluded] pseudo-table, both aligned to the table's columns. *) let eval_upsert ?(scope = []) cat params ~table ~cols ~current ~excluded e = project_one cat params (table_frame table cols current :: table_frame "excluded" cols excluded :: scope_frames scope) e (* One lowering and one compiled program for every row: the expressions are resolved against the layout alone, which the row's table, its columns, whether it carries a rowid and the outer frames fix, so the rows of a statement all run through one program. It is lowered at the first row, so a statement that reaches none refuses nothing. *) (* A row's run of the program [prog] of width [width] over [outer]: the row the program reads, its cursor, its register file and its bound values, made once and refilled for each row, as sqlite3 runs a statement's one program over its registers again. A projection takes one row and gives one, so nothing of a run outlives it but its answer. [running] is set while a run is under way. *) let kept_run ~running params ~ncols ~rowid (prog, width) outer = let row = Array.make (if rowid then ncols + 1 else ncols) Value.Null in let cursors = Array.of_list (Cursor.of_rows [| row |] :: outer) in let regs = Vdbe.registers prog and params = Ir.mems_of_params params in fun ?rowid vals -> let rec fill i = function | v :: rest when i < ncols -> row.(i) <- v; fill (i + 1) rest | _ -> for j = i to ncols - 1 do row.(j) <- Value.Null done in fill 0 vals; if ncols < Array.length row then row.(ncols) <- (match rowid with Some r -> Value.Int r | None -> Value.Null); let answer = ref [] in running := true; match Vdbe.run ~params ~regs prog cursors ~on_row:(fun regs base _ -> answer := List.init width (fun k -> Register.to_value regs.(base + k))) with | () -> running := false; !answer | exception e -> running := false; raise e (* sqlite3 codes a statement's expressions as it prepares it, so what the lowering refuses is refused here, before any row. A shape the IR does not model is no refusal of sqlite3's: it is reported where a row reaches it. *) let row_values ?(scope = []) ?stored cat params table cols ~rowid exprs = let outer = scope_frames scope in let program = let rowid = if rowid then Some 0L else None in let frames = table_frame ?rowid table cols [] :: outer in match let _, layout, (q, subs) = lower_cols cat params frames (List.map (fun e : Ast.result_col -> { expr = e; alias = None }) exprs) in (q, Ir.precompile ~hooks:(hooks ?stored cat params layout subs) q) with | p -> Ok p | exception Ir.Unsupported -> Error () in let outer = List.map (fun (_, _, vals) -> Spi.list_cursor [ vals ]) outer in (* a run the program's own evaluation starts again takes the general path *) let running = ref false in let run = Result.map (fun (_, program) -> kept_run ~running params ~ncols:(List.length cols) ~rowid program outer) program in fun ?rowid vals -> let q, program, run = match (program, run) with | Ok (q, p), Ok run -> (q, p, run) | Error (), _ | _, Error () -> unsupported (String.concat ", " (List.map Render.expr exprs)) in if q.Ir.order_by = [] && (not q.distinct) && q.limit = None && q.offset = 0 && not !running then run ?rowid vals else let _, _, vals = table_frame ?rowid table cols vals in match Ir.run_precompiled ~params q program (Array.of_list (Spi.list_cursor [ vals ] :: outer)) with | [ values ] -> values | _ -> [] let row_filter ?scope cat params table cols ~rowid where = match where with | None -> fun ?rowid:_ _ -> true | Some w -> ( let f = row_values ?scope cat params table cols ~rowid [ w ] in fun ?rowid vals -> match f ?rowid vals with [ v ] -> keep_truthy v | _ -> false) let row_matches ?(scope = []) ?rowid cat params table cols where vals = match where with | None -> true | Some w -> keep_truthy (eval_in_row ~scope ?rowid cat params table cols vals w) (* lang_returning.html sec.3: a [RETURNING] item is an expression over the row the statement affected, and [*] there "expands to all columns of the row", which is the projection [*] already means over that one frame. The row arrives with the rowid it was stored under where its table has one, because sqlite3 answers [RETURNING rowid] and the rowid is not among the columns. *) let returning_rows cat params ~table ~cols returning rows = Fmt.kstr unlowerable "this RETURNING over %s" table @@ fun () -> match rows with | [] -> [] | (rowid, _) :: _ -> (* One lowering for every affected row: the list is resolved against the layout alone and the values play no part, and whether a row carries a rowid is the relation's answer rather than one row's, so the rows of a write all project through the same program. *) let frame (rowid, row) = table_frame ?rowid table cols row in let _, layout, (q, subs) = lower_cols cat params [ frame (rowid, []) ] returning in let hooks = hooks cat params layout subs in let project row = let _, _, vals = frame row in match Ir.run ~hooks ~params q [| Spi.list_cursor [ vals ] |] with | [ values ] -> values | _ -> [] in List.map project rows let check_returning cat params ~table ~cols ~rowid returning = Fmt.kstr unlowerable "this RETURNING over %s" table @@ fun () -> let rowid = if rowid then Some 0L else None in ignore (lower_cols cat params [ table_frame ?rowid table cols [] ] returning) let written_joins (layout : Lower.layout) joins = (* the FROM list is left-associative, so the join at [p] takes the source at [p + 1] against the ones before it -- {!Resolve.natural_on}'s own numbering *) List.mapi (fun p (j : Ast.join) -> if (not j.Ast.natural) && j.Ast.using = [] then j else { j with Ast.natural = false; using = []; on = Resolve.natural_on layout (p + 1) j; }) joins let project_source_rowids source_layout (s : Ast.select) = (* [*] leaves the rowid out, so each source that has one also projects it, after the columns, for the scope to bind its [rowid], [oid] and [_rowid_] *) let with_rowid = List.map (fun (_, c) -> List.mem Resolve.rowid_sentinel c) source_layout in let rowid_col (alias, _) has = if has then Some { Ast.expr = Ast.Col (Some alias, Resolve.rowid_sentinel); alias = None; } else None in let s = { s with Ast.cols = star_col :: List.filter_map Fun.id (List.map2 rowid_col source_layout with_rowid); joins = written_joins source_layout s.joins; } in (s, with_rowid) let from_bindings ?(scope = []) cat params from joins = Fmt.kstr unlowerable "this UPDATE ... FROM" @@ fun () -> let s = { (post_select [ star_col ]) with Ast.from; joins } in let s = Resolve.collations (Q.resolve_env cat) s in let plan = Q.plan cat s in let s = Q.hoist_subqueries ~run:(fun sub -> run cat sub params) ~params cat s in let sources = from_sources ~accesses:plan.Plan.accesses cat params s in let source_layout = List.map (fun (a, c, _) -> (a, c)) sources in let s, with_rowid = project_source_rowids source_layout s in (* The outer scope joins as one more source of exactly one row, placed after the query's own, so an auxiliary column shadows an outer name for an unqualified reference and a qualified outer one still resolves. *) let outer = scope_frames scope in let layout = source_layout @ List.map (fun (a, c, _) -> (a, c)) outer in let cursors = Array.append (scan_cursors plan sources) (Array.of_list (List.map (fun (_, _, vals) -> Spi.list_cursor [ vals ]) outer)) in let q, subs = Lower.query ~env:(Q.resolve_env cat) ~encoding:cat.Q.encoding ~params layout s in let rows = Ir.run ~hooks:(hooks cat params layout subs) ~params q cursors in let visible = window_segments layout in let width = List.fold_left (fun n (_, c) -> n + List.length c) 0 visible in let rec rowids frames has vs = match (frames, has, vs) with | (alias, cols) :: frames, true :: has, v :: vs -> (alias, cols @ [ (Resolve.rowid_sentinel, v) ]) :: rowids frames has vs | frame :: frames, _ :: has, vs -> frame :: rowids frames has vs | frames, _, _ -> frames in List.map (fun row -> let frames = scope_of_values visible row in rowids frames with_rowid (List.filteri (fun i _ -> i >= width) row)) rows