(*--------------------------------------------------------------------------- Copyright (c) 2026 Thomas Gazagnaire. All rights reserved. SPDX-License-Identifier: ISC ---------------------------------------------------------------------------*) module Ast = Sql.Ast module Query = Sql.Private.Query module Engine = Sql.Private.Engine module Resolve = Sql.Private.Resolve module Plan = Sql.Private.Plan module Lower = Sql.Private.Lower module Value_ops = Sql.Value_ops module Value_op = Sql.Private.Value_op module Register = Catalog.Register module Ident = Catalog.Ident module Seek = Seek module Cursor = Cursor module Catalog_view = Catalog_view module Fast_path = Fast_path type value = Ast.value = | Null | Int of int64 | Float of float | Blob of string | Text of string module type S = Select_intf.S module Make (R : S) = struct include Select_source.Make (R) let plan_query t ~bound (rd : reads) (s : Ast.select) layout = let where = s.Sql.Ast.where and reads = table_reads rd in let plan = Plan.v (plan_facts t ?where ~reads ~read:rd.read ()) (Query.resolve_env (catalog t)) ~bound s layout in (* a select reading a subquery or a WITH table is not one the join planner plans, so no loop yields its rows in an order: a GROUP BY, DISTINCT or ORDER BY goes through a b-tree, as sqlite3's scan of a subquery that orders nothing leaves it *) let reads_with = List.exists (fun (tr : Ast.table_ref) -> tr.subquery = None && mem_ident tr.Sql.Ast.name bound) ((match s.Sql.Ast.from with Ast.Table tr -> [ tr ] | _ -> []) @ List.map (fun (j : Ast.join) -> j.Sql.Ast.table) s.joins) in let plan = if from_subqueries s = [] && not reads_with then plan else let jo = join_order s layout in let sort, grouping, _ = jo.finish { Where_loop.nest = []; in_order = 0; backwards = []; checked = List.map (fun _ -> (0, [])) jo.checks; } in { plan with sort; grouping } in { plan with accesses = List.map (bound_keys t ?where ~reads) plan.accesses; unmatched = List.map (fun (i, a) -> (i, bound_keys t ?where ~reads a)) plan.unmatched; } (* What the cursors of [s] are built from, all of it read off the statement, the schema and the counts the planner asked for, and none of it a bound value: the plan, and what each table and each source is read for. [None] when every source is a plain scan and the caller's own array of them will do. [bound] names the relations a WITH clause binds, which are materialised and so cannot be sought; a select that carries no WITH clause of its own binds nothing. *) type scan_plan = { plan : Plan.t; paths : R.seek_path option array; unmatched_paths : R.seek_path option array; read : int list array; tables : string option list; } let scan_plan t ~bound (s : Ast.select) infos = let layout = List.map (fun (a, c, _) -> (a, c)) infos in let rd = reads t s layout in let plan = plan_query t ~bound rd s layout in (* the same read sets the plan was made from, so a cursor reads through the index the printed plan named, and a hash holds what each source is read for *) { plan; paths = seek_paths t ?where:s.Sql.Ast.where plan.Plan.accesses ~reads:(table_reads rd); unmatched_paths = Array.of_list (List.map (fun (i, a) -> (seek_paths t ?where:s.Sql.Ast.where [ a ] ~reads:(fun _ -> rd.read.(i))).(0)) plan.Plan.unmatched); read = rd.read; tables = rd.tables; } (* The cursor builder of a scan plan, for one run's bound values, or [None] when every source is a plain scan and the caller's own array of them will do. *) let scan_cursors t params ~membership infos { plan; paths; unmatched_paths; read; tables } = if List.for_all (fun a -> a = Plan.Scan) plan.Plan.accesses && plan.Plan.unmatched = [] then None else Some (fun () -> access_cursors t params infos plan.Plan.accesses ~paths ~unmatched: (List.mapi (fun n (i, a) -> (i, a, unmatched_paths.(n))) plan.Plan.unmatched) ~held:(fun i -> read.(i)) ~relation:(fun i -> Option.join (List.nth_opt tables i)) ~set:(fun sub -> (membership sub).Query.rows) ~order:plan.Plan.order) (* [s] without the ORDER BY its plan's loop already yields in order, so the rows stream as they are read instead of filling a sorter. A scan, and a range of the rowid, walk the table forwards only, so the rowid order they yield backwards is still sorted, which a key that unique leaves as it was. *) let unsorted { plan; _ } (s : Ast.select) = match (plan.Plan.sort, plan.Plan.accesses) with | _, [ a ] when rowid_backwards a -> s | Some { terms; sorted }, [ (Plan.Ordered _ | Plan.Seek _) ] when sorted = terms -> { s with Ast.order_by = [] } | _ -> s (* [s] without the conjuncts of its WHERE and of its ONs the seeks of its plan answer ({!Plan.answered}): every row such a seek yields satisfies the equality, the IN or the bound it keys on, so the loop does not test it again, as sqlite3 disables the term it codes the seek from (wherecode.c, codeEqualityTerm, the range's start and end, and disableTerm). A conjunct is the plan's by identity; a hash standing for a seek answers none. An ON left with nothing to test is [1]. *) let unanswered { plan; _ } (s : Ast.select) = let answered = List.concat_map Plan.answered plan.Plan.accesses in if answered = [] then s else let rec strip = function | Ast.Binary (Ast.And, a, b) as e -> ( match (strip a, strip b) with | Some a', Some b' when a' == a && b' == b -> Some e | Some a, Some b -> Some (Ast.Binary (Ast.And, a, b)) | (Some _ as x), None | None, x -> x) | e -> if List.exists (( == ) e) answered then None else Some e in { s with Ast.where = Option.bind s.where strip; joins = List.map (fun (j : Ast.join) -> { j with on = Option.bind j.on strip }) s.joins; } (* A walk of an index the caller refused, found once the loop is planned and before its first row is read. *) exception Refused (* The cursor builder for [s], or [None] when every source is a plain scan, the order the loop enters the cursors in, [s] as it is then run, and how an aggregate over it folds: stopping at its first row ({!Plan.First_row}), its groups in the order the loop yields them ({!Plan.t.grouping}), or in key order. *) let join_scan ?(refused = fun _ -> false) t params ~membership ~bound (s : Ast.select) infos = let sp = scan_plan t ~bound s infos in (match sp.plan.Plan.accesses with | ( Plan.Seek { path = { index = Some i; _ }; _ } | Plan.Ordered { index = Some i; _ } ) :: _ when refused i -> raise Refused | _ -> ()); ( scan_cursors t params ~membership infos sp, sp.plan.Plan.order, unanswered sp (unsorted sp s), match (sp.plan.Plan.min_max, sp.plan.Plan.grouping) with | Some Plan.First_row, _ -> `First | _, Some `Loop when s.group_by <> [] -> `Arrival | _ -> `Key_order ) (* Whether [tr] names a table the database stores, which an EXISTS over it may join ({!Query.exists_to_join}): not a derived table, not a WITH table [bound] names, not a view. *) let stored_table t ~bound (tr : Ast.table_ref) = tr.Sql.Ast.subquery = None && (not (mem_ident tr.Sql.Ast.name bound)) && view t tr.Sql.Ast.name = None && match table_column_names t tr.Sql.Ast.name with | _ -> true | exception Catalog.Error _ -> false (* The schema read into a select that has no [WITH] and no compound arm: its ordinals, collations and aliases resolved, an aggregate of an enclosing query lifted out of its subqueries, and its EXISTS conjuncts joined. *) let resolve t cat (s : Ast.select) = let env = Query.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 Query.exists_to_join ~table:(stored_table t ~bound:[]) env (Query.lift_outer_aggregates env s) (* Whether [s] holds a [WITH] table or a select of its own anywhere: a subquery, a [FROM] subquery or a compound arm. One that holds none is rewritten by reading the schema alone. *) let nests (s : Ast.select) = let found = ref false in Resolve.walk_select ~table:(fun () _ -> ()) ~col:(fun () _ _ -> ()) ~nest:(fun () _ -> found := true) ~cte:(fun () _ -> found := true; None) () s; !found (* Run an aggregate/GROUP BY over [s]'s sources through the catalog engine, which groups, folds, filters by HAVING, orders, and limits. [false] if a source is not scannable or the select lowers to a shape the IR does not model, so the caller falls back to {!Engine.run_select}. *) (* Nothing worked out yet for the select [s] against the current schema. *) let fresh t cat (s : Ast.select) : Handle.prepared = { source = s; basis = (R.all_tables t, R.extra_master t); flat = Query.factor_disjunctions (Query.flatten_subqueries cat (Query.flatten_ctes cat s)); core = Unresolved; compiled = None; scan = Unplanned; } (* The resolved form of [p]'s select, worked out at the first run that asks. A select holding a [WITH], a compound arm or a nested select is [Nested]: its rewriting runs subqueries, so every run does it again. *) let core t (p : Handle.prepared) : Handle.core = match p.core with | (Nested | Plain _) as c -> c | Unresolved -> let c : Handle.core = if p.flat.ctes <> [] || p.flat.compound <> [] then Nested else let cat = catalog t in let s = resolve t cat p.flat in if nests s then Nested else (* with no subquery to fold, hoisting runs nothing *) Plain (Query.hoist_subqueries ~run:(fun _ -> invalid_arg "Select.core: a plain select ran a subquery") ~params:[||] cat s) in p.core <- c; c (* What the runs of the correlated subquery [u], bound to its outer row, keep on [t] for the next: the one select every outer row runs, resolved and its scan planned once, as sqlite3 codes a subquery once. Bounded as the plan cache is. *) let kept_subquery t cat (u : Ast.select) = let kept = R.subqueries t in match Handle.Plans.find_opt kept u with | Some p when schema_unchanged t p.basis -> p | Some _ | None -> if Handle.Plans.length kept >= 256 then Handle.Plans.clear kept; let p = fresh t cat u in Handle.Plans.replace kept u p; p (* A scalar or EXISTS subquery as sqlite3 runs it: under a LIMIT of one, or of whether its own LIMIT is not zero (expr.c, sqlite3CodeSubselect). *) let limited_to_one (s : Ast.select) = match s.limit with | None -> { s with limit = Some (Ast.Lit (Ast.Int 1L)) } | Some (Ast.Lit (Ast.Int (0L | 1L))) -> s | Some l -> { s with limit = Some (Ast.Binary (Ast.Neq, l, Ast.Lit (Ast.Int 0L))) } let rec try_vdbe_select ?refused t (s : Ast.select) (params : value array) ~emit = if s.ctes <> [] then cte_select t s params ~emit else if s.compound <> [] then compound_select t s params ~emit else let cat = catalog t in let s = resolve t cat (Query.table_arguments cat params (Query.counts cat params s)) in (* Fold uncorrelated scalar/IN/EXISTS subqueries to constants so the VM, which has no subquery opcode, can compile the outer query; a correlated one is evaluated per outer row by {!run_subquery_impl}. *) let run sub = let buf = ref [] in if try_vdbe_select t sub params ~emit:(fun r -> buf := Sql.Row.to_list r :: !buf) then List.rev !buf else Engine.run_select cat sub params in run_plain ?refused t (Query.hoist_subqueries ~run ~params cat s) params ~emit (* An aggregate / GROUP BY / window select scans the (joined) source rows through the VM then reuses {!Engine}'s grouping / window post-pass; a plain select scans, filters, projects, and orders directly. Both span any mix of named tables, derived tables, and a VALUES row source. [prepared] is the statement's, where the select is its [Plain] core. *) and run_plain ?refused ?prepared t (s : Ast.select) params ~emit = if Query.aggregate_compilable s then aggregate_select t s params ~emit else if Query.window_compilable s then catalog_window t s params ~emit else join_sources_scan ?refused ?prepared t s params ~emit (* A [WITH] select: materialise its CTEs into the catalog, then run the CTE-stripped select on the VM scanning every source from [cat.rows]. A compound one runs arm by arm and folds with {!Engine.combine_compound}. A source the cat-scan builder does not model still returns [false], decided per compound arm before anything is emitted. *) and cte_select t (s : Ast.select) params ~emit = let cat = Query.materialize_ctes (catalog t) params s.ctes in let with_ctes = (cat, List.map (fun (c : Ast.cte) -> c.Sql.Ast.name) s.ctes) in let stream = streamed s in let s = { s with Ast.ctes = [] } in if s.compound = [] then cte_core ?stream t ~cat ~with_ctes params s ~emit else if (* an arm with decorations of its own is {!compound_select}'s refusal too *) List.exists (fun (_, (a : Ast.select)) -> a.compound <> [] || a.order_by <> [] || a.limit <> None) s.compound then false else let arm (a : Ast.select) = let a = { a with Ast.order_by = []; limit = None; offset = None; compound = []; } in let buf = ref [] in if cte_core t ~cat ~with_ctes params a ~emit:(fun r -> buf := Sql.Row.to_list r :: !buf) then Some (List.rev !buf) else None in let rec arms acc = function | [] -> Some (List.rev acc) | (op, a) :: rest -> Option.bind (arm a) (fun rows -> arms ((op, rows) :: acc) rest) in (* every arm is buffered before anything is emitted, so an arm the builder cannot model leaves the caller free to fall back on the whole statement *) match Option.bind (arm s) (fun base -> Option.map (fun a -> (base, a)) (arms [] s.compound)) with | None -> false | Some (base, compound_rows) -> emit_values emit (Engine.combine_compound cat params s base compound_rows); true (* The scan-infos for a select some of whose sources [cat] answers for out of its own rows rather than the database. [bound] names the [WITH] names in force, which the engine materialised into [cat]. Every other named source is read through its own b-tree ({!ref_info}). [None] for a source the simple builder does not model. *) and cat_source_infos ?stream t ~bound (cat : Query.catalog) params (s : Ast.select) = let base_table ?(lead = false) (tr : Ast.table_ref) = match tr.Sql.Ast.subquery with | Some _ -> None | None when mem_ident tr.Sql.Ast.name bound -> let alias = Option.value tr.alias ~default:tr.name in let rows () = cat.Sql.Private.Query.rows tr.name in let cursor = match stream with | Some name when lead && ident_equal name tr.name -> ( match cat.Sql.Private.Query.stream tr.name with | Some seq -> stream_cursor seq ~again:rows | None -> fun () -> materialised_cursor t (rows ()) ()) | _ -> fun () -> materialised_cursor t (rows ()) () in Some (alias, cat.Sql.Private.Query.columns tr.name, cursor) | None -> ref_info t params tr in let leading = match s.Sql.Ast.from with | Ast.Table tr -> base_table ~lead:true tr | Ast.Unit -> Some ("", [], literal_cursor t [ [] ]) | 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 let rows = List.map (List.map (Engine.eval_const cat params)) tuples in Some ("", cols, literal_cursor t rows) | Ast.Select _ | Ast.Table_function _ -> None in let joins = List.map (fun (j : Ast.join) -> base_table j.Sql.Ast.table) s.joins in let all = leading :: joins in if List.exists Option.is_none all then None else Some (List.filter_map Fun.id all) (* One non-compound select over the catalog its [WITH] names are bound in: the resolution passes, then the same cat-scan the CTE-free path takes -- access paths included, for every source the clause does not bind. *) and cte_core ?stream t ~cat ~with_ctes params (s : Ast.select) ~emit = let s = Resolve.ordinals (Query.resolve_env cat) s in let s = Resolve.collations (Query.resolve_env cat) s in let s = Resolve.where_aliases (Query.resolve_env cat) s in let s = Resolve.reduce_outer_joins (Query.resolve_env cat) s in let bound = snd with_ctes in let s = Query.exists_to_join ~table:(stored_table t ~bound) (Query.resolve_env cat) s in match cat_source_infos ?stream t ~bound cat params s with | None -> false | Some infos -> let run_subquery kind sub scope = run_subquery_impl ~with_ctes t params kind sub scope in let membership = cat_membership cat params in let scan, order, s, fold = join_scan t params ~membership ~bound s infos in let first = fold = `First and arrival = fold = `Arrival in if Query.aggregate_compilable s || Query.window_compilable s then catalog_aggregate t ~run_subquery ~first ~arrival ~order ~cat ~scan ~affinity:(infos_affinity t ~cat s infos) ~membership ~params infos s ~emit else catalog_run_with_infos t ~run_subquery ~order ~cat ~scan ~affinity:(infos_affinity t ~cat s infos) ~membership ~params infos s ~emit (* Evaluate a correlated scalar / [EXISTS] / [IN] subquery for the outer row in [scope]. Binding [scope] as parameters makes it uncorrelated and the same select at every outer row, so it runs on the VM where it compiles, through the resolution, scan and plan the handle keeps for it ({!kept_subquery}). [~with_ctes] is the enclosing [WITH]'s catalog and names: a subquery reading one cannot take the VM path, which resolves from the database, and runs on {!Engine.run_select}. *) and run_subquery_impl ?with_ctes t params kind sub scope = let cat, bound = match with_ctes with | Some (cat, names) -> (cat, names) | None -> (catalog t, []) in let reads_cte = List.exists (fun n -> Query.reads_table n sub) bound in let sub = match kind with `Scalar | `Exists -> limited_to_one sub | `In _ -> sub in let rows = let u, params = Resolve.bind_scope (Query.resolve_env cat) scope sub ~params in if reads_cte then Engine.run_select cat u params else stored_rows t cat params u in match kind with | `Scalar -> ( match rows with (v :: _) :: _ -> v | _ -> Ast.Null) | `Exists -> Ast.Int (if rows = [] then 0L else 1L) | `In ((c : Sql.Ir.comparison), v) -> let col = List.filter_map (function c :: _ -> Some c | [] -> None) rows in Value_op.in_eval ?aff:c.aff ?coll:c.coll v col (* The rows of [u], a select with no outer row that reads the database's own relations, on the VM where it compiles, through the resolution, scan and plan the handle keeps for it ({!kept_subquery}), else {!Engine.run_select}: a select of its own, read through its access paths as the database stands now. *) and stored_rows t cat params u = let buf = ref [] in let emit r = buf := Sql.Row.to_list r :: !buf in let used = (* a table-valued function's arguments may read the row, and then the select differs from row to row and keeps nothing *) if Query.table_arguments cat params u != u then try_vdbe_select t u params ~emit else let p = kept_subquery t cat u in match core t p with | Plain c -> run_plain ~prepared:p t c params ~emit | Nested | Unresolved -> try_vdbe_select t u params ~emit in if used then List.rev !buf else Engine.run_select cat u params (* Materialise [q]'s rows through the engine -- the VM where it compiles, else {!Engine.run_select} -- as a cursor over column-named [cols] under [alias]. The one resolver for a relation the VM scans through an external cursor rather than a B-tree: a FROM-subquery, a join operand, or a view's stored SELECT. *) and materialized_info t params q cols alias = let rows = let buf = ref [] in if try_vdbe_select t q params ~emit:(fun r -> buf := Sql.Row.to_list r :: !buf) then List.rev !buf else Engine.run_select (catalog t) q params in (alias, cols, materialised_cursor t rows) (* The scan info for one join operand: a derived table (a subquery) or a view -- both materialised through the engine, the inner SELECT on the VM where it compiles, else {!Engine.run_select} -- or a named base table via {!vdbe_table_info}. [None] when a named base table is not VM-scannable, so the caller falls back. *) and ref_info t params (tr : Ast.table_ref) = let alias = match tr.alias with Some a -> a | None -> tr.name in match tr.subquery with | Some q -> Some (materialized_info t params q (Resolve.select_columns (Query.resolve_env (catalog t)) q) alias) | None -> ( if is_master_name tr.name then (* sqlite_master / sqlite_schema: a synthetic table of the schema rows, scanned from {!master_rows} like any materialised source, each row carrying its rowid in the hidden slot a plain table's scan appends; the temp database's has none. *) let rows = if Sql.Ast.is_temp_schema_table tr.name then [] else List.map (fun (rid, row) -> row @ [ Ast.Int rid ]) (master_rows t) in Some ( alias, master_column_names @ [ Resolve.rowid_sentinel ], synthetic_scan_cursor t rows ) else match view t tr.name with | Some cv -> (* A view takes no outer parameters: materialise its SELECT on its own, as the catalog does for {!Engine.run_select}. This door reaches a view's rows without going through the catalog's, so it carries the same mark against a body that names its own view ({!Sql.Private.View.expanding}). *) Some (Sql.Private.View.expanding tr.name (fun () -> materialized_info t [||] cv.select (view_columns t cv) alias)) | None -> ( match R.eponymous t tr.name with | Some (cols, rows) -> Some (alias, cols, synthetic_scan_cursor t (rows ())) | None -> vdbe_table_info t tr)) (* The scan infos for [s]'s leading FROM source and every join operand, in scan order. [None] if any source is not VM-scannable (a named table with no index, a derived table, or VALUES; not [Unit]/a table-valued function). *) and source_infos t params (s : Ast.select) = let leading = match s.from with | Ast.Table tr -> ref_info t params tr | Ast.Select { fs_select; fs_alias } -> ref_info t params { Ast.name = Option.value fs_alias ~default:""; schema = None; alias = None; subquery = Some fs_select; } | Ast.Values tuples -> Some (values_info t params tuples) (* A FROM-less select ([SELECT 1+1], [SELECT abs(-5)]) scans one synthetic empty row, so its constant / function projection runs on the engine like any other scan instead of falling back to {!Engine.run_select}. *) | Ast.Unit -> Some ("", [], literal_cursor t [ [] ]) (* A table-valued function ([FROM generate_series(1, 10)]) materialises to its columns and rows -- its arguments are constant -- and is scanned like any other source. *) | Ast.Table_function { tf_name; tf_args; tf_alias } -> let cat = catalog t in let argvals = List.map (Engine.eval_const cat params) tf_args in let f = Query.table_function cat tf_name in let alias = Option.value tf_alias ~default:tf_name in Some (alias, f.columns, synthetic_scan_cursor t (f.rows argvals)) in let joins = List.map (fun (j : Ast.join) -> ref_info t params j.table) s.joins in let all = leading :: joins in if List.exists Option.is_none all then None else Some (List.filter_map Fun.id all) (* Scan [s]'s sources as a nested-loop inner join, projecting / filtering / ordering through the catalog engine. [false] when any source is not scannable or the select lowers to a shape the IR does not model. *) (* What each [IN (SELECT ...)] of a statement on the database compares against: its subquery run as the select it is, through the cursors and the indexes its own plan names. The catalog would answer it from whole-table rows, every column of every row read and held for the few the subquery keeps. *) and db_membership t params = let run sub = let buf = ref [] in let emit r = buf := Sql.Row.to_list r :: !buf in if try_vdbe_select t sub params ~emit then List.rev !buf else Engine.run_select (catalog t) sub params in Query.membership ~run ~params (catalog t) (* A statement's [Plain] core runs through the scan it planned at its first run where that plan reads the schema alone: one base table, whose access is its seek wherever one exists and its scan otherwise, whatever the table holds. A plan over several sources weighs their counts, which move with the rows, and is made again at every run. *) and join_sources_scan ?refused ?prepared t (s : Ast.select) params ~emit = match (prepared : Handle.prepared option) with | Some ({ scan = Unplanned; _ } as p) -> p.scan <- planned_scan t p s; join_sources_scan ~prepared:p t s params ~emit | Some { scan = Planned run; _ } -> run params ~emit | Some { scan = Per_run; _ } | None -> ( match source_infos t params s with | None -> false | Some infos -> let membership = db_membership t params in let scan, order, s, _ = join_scan ?refused t params ~membership ~bound:[] s infos in catalog_run_with_infos t ?cache:(rerun_cache t params) ?prepared ~order ~run_subquery:(run_subquery_impl t params) ~cat:(catalog t) ~scan ~affinity:(infos_affinity t s infos) ~membership ~params infos s ~emit) and planned_scan t (p : Handle.prepared) (s : Ast.select) : Handle.scan = match (s.from, s.joins) with | Ast.Table tr, [] when tr.subquery = None -> ( match vdbe_table_info t tr with | None -> Per_run | Some info -> let infos = [ info ] in let sp = scan_plan t ~bound:[] s infos in let affinity = infos_affinity t s infos in let s = unsorted sp s in Planned (fun params ~emit -> let membership = db_membership t params in catalog_run_with_infos t ~prepared:p ~order:sp.plan.Plan.order ~run_subquery:(run_subquery_impl t params) ~cat:(catalog t) ~scan:(scan_cursors t params ~membership infos sp) ~affinity ~membership ~params infos s ~emit)) | _ -> Per_run and aggregate_select t (s : Ast.select) params ~emit = match source_infos t params s with | None -> false | Some infos -> let run_subquery kind sub scope = run_subquery_impl t params kind sub scope in let membership = db_membership t params in let scan, order, s, fold = join_scan t params ~membership ~bound:[] s infos in let first = fold = `First and arrival = fold = `Arrival in catalog_aggregate t ~run_subquery ~first ~arrival ~order ~cat:(catalog t) ~scan ~affinity:(infos_affinity t s infos) ~membership ~params infos s ~emit (* A window-function select: scan the filtered, joined source rows on the VM (a raw all-columns projection), then reuse {!Sql.Private.Window.scan} for the partitioning, framing, projection, ORDER BY, and LIMIT over those rows. [false] (fall back) when a source is not VM-scannable, or when the post-pass projection is outside the lowered subset. *) and catalog_window t (s : Ast.select) params ~emit = match source_infos t params s with | None -> false | Some infos -> let raw, segments = Sql.Private.Window.scan_select (List.map (fun (a, c, _) -> (a, c)) infos) s in let run_subquery kind sub scope = run_subquery_impl t params kind sub scope in let rows = ref [] in let membership = db_membership t params in (* An aggregate over a join scans exactly what a plain select scans, so it needs the same access path: without this the inner table is rescanned once per outer row, and a GROUP BY over two indexed tables degrades to the full product. *) let scan, order, raw, _ = join_scan t params ~membership ~bound:[] raw infos in let cat = catalog t in if catalog_run_with_infos t ~run_subquery ~order ~cat ~scan ~affinity:(infos_affinity t raw infos) ~membership ~params infos raw ~emit:(fun r -> rows := Sql.Row.to_list r :: !rows) then ( match Sql.Private.Window.scan ~params ~membership ~encoding:cat.Query.encoding segments s (List.rev !rows) with | exception Sql.Ir.Unsupported -> false | out -> emit_values emit out; true) else false (* A compound select: run the leading arm and each following arm, then hand the rows to {!Engine.combine_compound}, which folds the set operators and applies the outer ORDER BY and LIMIT. An arm with its own ORDER BY/LIMIT/nested compound forces a full fallback. *) and compound_select t (s : Ast.select) params ~emit = let nested (_, (arm : Ast.select)) = arm.compound <> [] || arm.order_by <> [] || arm.limit <> None in if List.exists nested s.compound then false else begin let cat = catalog t in let run_arm (arm : Ast.select) = let a = { arm with Ast.order_by = []; limit = None; offset = None; compound = []; } in let buf = ref [] in if try_vdbe_select t a params ~emit:(fun r -> buf := Sql.Row.to_list r :: !buf) then List.rev !buf else Engine.run_select cat a params in let base_rows = run_arm s in let compound_rows = List.map (fun (op, arm) -> (op, run_arm arm)) s.compound in emit_values emit (Engine.combine_compound cat params s base_rows compound_rows); true end (* The relations [s]'s own [WITH] clause binds, with the columns each publishes. The database has no such table, and where a real table shares the name the CTE is what the query reads. A body that cannot be resolved yet publishes no column. *) let cte_relations t (s : Ast.select) = let env = Query.resolve_env (catalog t) in List.map (fun (c : Ast.cte) -> ( c.Sql.Ast.name, try Resolve.cte_columns env c with Catalog.Error (Prepare _ | Runtime _) -> [] )) s.Sql.Ast.ctes (* The alias and column names each source of [s] publishes, enough to decide an access path without materialising anything. A plain rowid table's cursor carries a trailing hidden rowid slot, appended here so EXPLAIN plans over the same list the executed plan reads. *) let explain_layout t (s : Ast.select) = let bound = cte_relations t s in let layout = Plan.layout (Query.resolve_env (catalog t)) ~bound s in let hidden_rowid (tr : Ast.table_ref) = tr.Sql.Ast.subquery = None && (not (mem_ident tr.Sql.Ast.name (List.map fst bound))) && (is_master_name tr.Sql.Ast.name || plain_rowid_gtable t tr.Sql.Ast.name <> None) in let refs = (match s.Sql.Ast.from with Ast.Table tr -> Some tr | _ -> None) :: List.map (fun (j : Ast.join) -> Some j.Sql.Ast.table) s.joins in List.map2 (fun (alias, cols) tr -> match tr with | Some tr when hidden_rowid tr -> (alias, cols @ [ Resolve.rowid_sentinel ]) | Some _ | None -> (alias, cols)) layout refs (* The arms of the compound [s] checked as sqlite3 prepares the whole compound before any arm runs: each arm's names and calls, then their widths, so a later arm's refusal comes before an earlier arm's first row when the arms stream. Each arm reads the compound's WITH. A subquery inside an arm is checked as it runs. *) let check_compound t cat (s : Ast.select) = let env = Query.resolve_env cat in let arm (whole : Ast.select) = let a = { whole with ctes = s.ctes; compound = []; order_by = []; limit = None; offset = None; } in let a = Resolve.reduce_outer_joins env (Resolve.where_aliases env (Resolve.ordinals env a)) in Resolve.check_columns (explain_layout t a) a; (* the leading arm's calls are read with the compound it leads, which codes a VALUES list there arm by arm ({!Query.check_calls}) *) Query.check_calls cat whole; (* sqlite3 resolves every arm's subqueries too before the first row *) Resolve.check_subqueries ~select:(Query.check_calls cat) env a in if s.compound <> [] then begin List.iter arm (s :: List.map snd s.compound); Resolve.check_widths env s end (* What every run of [s] starts from, before it reads a value: [s] with each single-use [WITH] table expression spliced into the query that reads it, since every access path requires a plain named table in FROM and a CTE reference would otherwise force the whole relation into memory and hide the reader's predicate from the index. The calls of each of its arms, and the names and calls of every subquery they hold, are checked first, then its arms' names and widths ({!check_compound}), as sqlite3 resolves them before a row is read. *) let prepare t cat (s : Ast.select) : Handle.prepared = Query.check_select cat s; check_compound t cat s; fresh t cat s (* The work an earlier run of [s] left in [memo], where it was made of this select against this schema, else a fresh start, kept for the next run. *) let prepared ?memo t cat s = match memo with | None -> prepare t cat s | Some (m : Handle.memo) -> ( match m.prepared with | Some p when p.source == s && schema_unchanged t p.basis -> p | Some _ | None -> let p = prepare t cat s in m.prepared <- Some p; p) (* The arms of a compound of UNION ALL alone, with no ORDER BY, LIMIT or WITH over the whole, which sqlite3 runs one after the other, each row out as its arm yields it (select.c, multiSelect, the TK_ALL case); [None] for any other select. A WITH stays with the compound, whose arms read one evaluation of it. *) let union_all_arms (s : Ast.select) = if s.compound <> [] && List.for_all (fun (op, _) -> op = Ast.Union_all) s.compound && s.order_by = [] && s.limit = None && s.ctes = [] then Some ({ s with compound = [] } :: List.map snd s.compound) else None (* The three ways a select is answered, tried in order, each row handed to [f] as produced. Only the VM streams. Which answered is settled before [f] sees anything: a fast path is recognised reading no row, and the VM declines while compiling, before it has scanned. *) let vm_select_one ?memo t cat params s ~f = let p = prepared ?memo t cat (Query.table_arguments cat params s) in let s = p.flat in match Option.bind (R.fast_of_select t s params) (R.fast_run t s params) with | Some rows -> emit_values f rows | None -> let vm = match core t p with | Plain c -> run_plain ~prepared:p t c params ~emit:f | Nested | Unresolved -> try_vdbe_select t s params ~emit:f in if not vm then emit_values f (Engine.run_select cat s params) (* {!vm_select_one}, the arms of a compound of UNION ALL alone one after the other ({!union_all_arms}). *) let vm_select_iter ?memo t cat params s ~f = match union_all_arms s with | Some (_ :: _ as arms) -> check_compound t cat s; List.iter (fun a -> vm_select_one t cat params a ~f) arms | Some [] | None -> vm_select_one ?memo t cat params s ~f (* Whether the select a DELETE or an UPDATE finds its rows by is planned as it stands: one stored table, unaliased result columns and a WHERE, and no subquery. The statement resolved its names and made the declared sequences of its columns explicit ({!Resolve.collate_over}), and every pass of {!resolve}, the counts, the table arguments and the hoisting leaves such a select as it is, so the rows are found from the WHERE the statement resolved, as sqlite3 codes an UPDATE's loop from the WHERE it resolved once (update.c, sqlite3WhereBegin). A subquery is a select of its own the statement did not rewrite, and takes them all. *) let resolved_rows (s : Ast.select) = match s with | { from = Ast.Table { subquery = None; _ }; joins = []; ctes = []; compound = []; distinct = false; group_by = []; having = None; order_by = []; limit = None; offset = None; cols; where; } -> List.for_all (fun (rc : Ast.result_col) -> rc.alias = None && not (Ast.holds_select rc.expr)) cols && not (Option.fold ~none:false ~some:Ast.holds_select where) | _ -> false let dml_vm ?refused t s params ~emit = if resolved_rows s then run_plain ?refused t s params ~emit else try_vdbe_select ?refused t s params ~emit (* The rows of the select a DELETE or an UPDATE finds its rows by, taken as a query takes them: through its fast path, a rowid range the first, else on the VM; [None] where both decline. *) let dml_rows t s params = match Option.bind (R.fast_of_select t s params) (R.fast_run t s params) with | Some rows -> Some rows | None -> let buf = ref [] in if dml_vm t s params ~emit:(fun r -> buf := Sql.Row.to_list r :: !buf) then Some (List.rev !buf) else None (* The same rows handed to [f] as the VM produces them, for a statement that writes each where the scan stands. [false], having handed none, where a fast path takes the select -- it seeks a rowid range the VM would walk -- or the VM declines it. A walk of an index [refused] names, the indexes an UPDATE writes, is declined too, as sqlite3 turns its one-pass rewrite off where the index its loop walks is one the UPDATE writes (update.c, aiCurOnePass[1] against aToOpen). *) let dml_iter ?refused t s params ~f = Option.is_none (R.fast_of_select t s params) && try dml_vm ?refused t s params ~emit:(fun r -> f (Sql.Row.to_list r)) with Refused -> false (* The same answer to a caller that wants every row before the first one. The buffer is here and nowhere under it, so a caller that does not want it does not pay for it. *) let vm_select_rows ?memo t cat params s = let buf = ref [] in vm_select_iter ?memo t cat params s ~f:(fun row -> buf := Sql.Row.to_list row :: !buf); List.rev !buf (* What a prepared select works out from itself and its catalog alone, kept for its next run ({!cat_prepare}): the relations it names, its sources, each of whose cursors reads the relation's rows at that run, whether it aggregates, its plan, and the register file a run of the plan uses, as sqlite3 keeps a statement's registers across its runs. *) type kept = { mutable names : string list option; mutable infos : (string * string list * (unit -> Catalog.Cursor.t)) list option; mutable grouped : bool option; plan : Sql.Closure.plan option ref; regs : Catalog.Register.t array option ref; } (* Run a scalar / [IN] / [EXISTS] subquery over the enclosing-row [cat] on the catalog VM: substitute the outer [scope] in, build cursors from [cat.rows], and run; fall back to {!Engine.run_select} for a shape the VM cannot compile. The cursors are counted into [t], so a subquery's sources are as visible in [rows_scanned] as the enclosing query's. What only the compile reads -- the columns' affinities, the memberships' rows -- is worked out only for a compile. *) let cat_subquery_run_core ?kept t cat params u = let names = match kept with | Some { names = Some names; _ } -> names | Some k -> let names = Resolve.table_names u in k.names <- Some names; names | None -> Resolve.table_names u in (* Every relation this names is [cat]'s: it may be a WITH name, or the one row set a rowid fast path restricted a table to ({!Catalog_view.restrict}), and reading any of them from the database behind the catalog's back would answer from a relation the enclosing statement does not have. *) let infos = match kept with | Some { infos = Some infos; _ } -> Some infos | Some k -> let infos = cat_source_infos t ~bound:names cat params u in k.infos <- infos; infos | None -> cat_source_infos t ~bound:names cat params u in match infos with | None -> None | Some infos -> let buf = ref [] in let affinity = lazy (infos_affinity t ~cat u infos) in let affinity c = Lazy.force affinity c in let membership sub = cat_membership (catalog t) params sub in let grouped () = Query.aggregate_compilable u || Query.window_compilable u in let grouped = match kept with | Some { grouped = Some g; _ } -> g | Some k -> let g = grouped () in k.grouped <- Some g; g | None -> grouped () in let ok = if grouped then (* a compound arm scans its own sources. *) catalog_aggregate t ~cat ~scan:None ~affinity ~membership ~params infos u ~emit:(fun r -> buf := Sql.Row.to_list r :: !buf) else catalog_run_with_infos t ?kept:(Option.map (fun k -> k.plan) kept) ?regs:(Option.map (fun k -> k.regs) kept) ~cat ~scan:None ~affinity ~membership ~params infos u ~emit:(fun r -> buf := Sql.Row.to_list r :: !buf) in if ok then Some (List.rev !buf) else None let cat_subquery_strip (a : Ast.select) = { a with Ast.compound = []; order_by = []; limit = None; offset = None } let cat_subquery_has_nested_arm (_, (arm : Ast.select)) = arm.Sql.Ast.compound <> [] || arm.order_by <> [] || arm.limit <> None let cat_subquery_run_compound t cat params u = if List.exists cat_subquery_has_nested_arm u.Sql.Ast.compound then None else match cat_subquery_run_core t cat params (cat_subquery_strip u) with | None -> None | Some base -> let rec arms acc = function | [] -> Some (List.rev acc) | (op, arm) :: rest -> ( match cat_subquery_run_core t cat params (cat_subquery_strip arm) with | Some r -> arms ((op, r) :: acc) rest | None -> None) in Option.map (fun compound_rows -> Engine.combine_compound cat params u base compound_rows) (arms [] u.Sql.Ast.compound) let cat_subquery_run ?kept t cat params u = match if u.Sql.Ast.compound = [] then cat_subquery_run_core ?kept t cat params u else cat_subquery_run_compound t cat params u with | Some rows -> rows | None -> Engine.run_select cat u params (* A subquery over the outer row [scope], run as the VM runs one under a query of its own ({!run_subquery_impl}): the row bound as parameters, so every outer row runs the one select, and its plan kept on the catalog, compiled at the first run. Only what [s] and [cat] alone decide is kept: the sources are read again at every run, since a table-valued function may take its arguments from the row. A subquery that reads no relation of [cat]'s own ({!Query.binds}) reads the database's, and is a select of its own as sqlite3 codes it ({!stored_rows}): through its access paths, and as the database stands at each run, so a subquery correlated to a row an UPDATE rewrites reads the rows rewritten before it. One that reads no outer row runs once for the catalog, as sqlite3 runs an uncorrelated subquery once (expr.c, sqlite3CodeSubselect, OP_Once). *) let cat_subquery_rows t cat scope (s : Ast.select) params = let u, bound = Resolve.bind_scope (Query.resolve_env cat) scope s ~params in if not (List.exists cat.Sql.Private.Query.binds (Resolve.table_names u)) then if Array.length bound = Array.length params then Query.closed_rows ~params:bound cat u ~run:(stored_rows t cat bound) else stored_rows t cat bound u else let params = bound in let plans = match cat.Sql.Private.Query.subquery_plans with | Some plans -> plans | None -> let plans = Hashtbl.create 4 in cat.subquery_plans <- Some plans; plans in let plan = ref (Hashtbl.find_opt plans u) in let kept = { names = None; infos = None; grouped = None; plan; regs = ref None } in let rows = cat_subquery_run ~kept t cat params u in Option.iter (Hashtbl.replace plans u) !plan; rows (* A select with no outer row, made ready to run under [cat] round after round: checked against the catalog's names once, and compiled at its first run, as sqlite3 codes a recursive CTE's step once and runs it per row of its queue (select.c, generateWithRecursiveQuery). A run answers from what the relations hold then, so no answer is memoised. *) let cat_prepare t cat (s : Ast.select) params = let closed = lazy (Resolve.bind_scope (Query.resolve_env cat) [] s ~params) in let kept = { names = None; infos = None; grouped = None; plan = ref None; regs = ref None; } in fun () -> let u, params = Lazy.force closed in cat_subquery_run ~kept t cat params u (* The rows an INSERT...SELECT inserts, each handed to [f] as it is produced: on the VM for a top-level statement. With an outer [scope] (inside a trigger), binding it as parameters turns it into an ordinary select the VM runs. *) let insert_select_iter t cat params scope s ~f = let row r = f (Sql.Row.to_list r) in if scope = [] then vm_select_iter t cat params s ~f:row else let u, params = Resolve.bind_scope (Query.resolve_env cat) scope s ~params in vm_select_iter t cat params u ~f:row (* The view-materialisation forward reference {!CV} is built over: a view's stored SELECT (a view takes no parameters) runs on the VM where it compiles, else {!Engine.run_select}. *) let materialize_view t cat sel = vm_select_rows t cat [||] sel (* The subquery-runner forward reference {!CV} is built over. *) let cat_subquery = cat_subquery_rows end