(*--------------------------------------------------------------------------- Copyright (c) 2025 Thomas Gazagnaire. All rights reserved. SPDX-License-Identifier: ISC ---------------------------------------------------------------------------*) open Ast open Value_ops include Query_model (* Whether [e] references a [rowid] column. A subquery / [EXISTS] reads as [true] (its scan is separate). A [Window] descends into its function, partition and order keys: the window node itself is what the window post-pass compiles, not a rowid reference, but a rowid inside its scanned components still matters. *) let rec expr_references_rowid e = let r = expr_references_rowid in match e with | Col (_, name) -> is_rowid_name name (* A membership's left operand is read in this scan; its subquery's own columns are resolved in the subquery's scan, which has its own layout and its own rowid slot. *) | In_select (x, _) -> r x (* Every other subquery reads as [true]: its scan is separate, and this answer decides whether {e this} scan can go without a rowid slot. *) | e -> Ast.fold_expr ~select:(fun _ _ -> true) (fun acc x -> acc || r x) false e (* The windows [s] has to compute: those its select list holds, and those reachable only from its ORDER BY. lang_select.html sec.2 runs the result-column expressions before the ORDER BY sorts what they produced, so a sort key may name a window nothing projects -- its value is computed, sorted on, and dropped. *) let select_windows (s : select) = window_exprs (s.cols @ List.map (fun (e, _) : result_col -> { expr = e; alias = None }) s.order_by) (* Whether [s] is an aggregate/GROUP BY select the register VM's grouped path can run: it groups or aggregates or has HAVING and uses no window function. The scan carries the implicit rowid column ({!Resolve.rowid_sentinel}) like any base-table scan, so an aggregate over [rowid] (e.g. [count(rowid)]) compiles too. *) let aggregate_compilable (s : select) = (s.group_by <> [] || s.having <> None || List.exists is_aggregate s.cols) && select_windows s = [] (* sqlite3's min/max query (select.c, minMaxQuery and its caller in sqlite3Select): an aggregate select list, no GROUP BY, no HAVING, no window, and one aggregate call in the select list and the ORDER BY -- a call spelled twice is one -- which is min() or max() of one argument, DISTINCT or not, with no FILTER. A select that aggregates nothing is answered before any list is built. *) let min_max (s : select) = if s.group_by <> [] || s.having <> None || (not (List.exists is_aggregate s.cols)) || select_windows s <> [] then None else let rec calls acc e = let found () = if List.exists (Ast.equal_expr e) acc then acc else e :: acc in match e with | Func (n, args) when is_agg n args -> found () | Distinct_agg _ | Filter _ | Ordered_agg _ -> found () | e -> Ast.fold_expr ~select:(fun acc _ -> acc) calls acc e in let acc = List.fold_left (fun acc (rc : result_col) -> calls acc rc.expr) [] s.cols in match List.fold_left (fun acc (e, _) -> calls acc e) acc s.order_by with | [ Func ("min", [ a ]) ] -> Some (a, `Min, false) | [ Distinct_agg ("min", a) ] -> Some (a, `Min, true) | [ Func ("max", [ a ]) ] -> Some (a, `Max, false) | [ Distinct_agg ("max", a) ] -> Some (a, `Max, true) | _ -> None (* Whether [s]'s window functions read a [rowid]. Windows over groups read the grouped rows, which carry no rowid, so such a select has nowhere to resolve it and is refused rather than answered wrongly. A window over the rows of a scan reads the rowid the scan appends ({!Window.scan_select}). *) let window_reads_rowid (s : select) = List.exists (fun (rc : Ast.result_col) -> expr_references_rowid rc.expr) s.cols || List.exists (fun (e, _) -> expr_references_rowid e) s.order_by let window_compilable (s : select) = select_windows s <> [] && not (is_aggregate_query s) let window_over_groups (s : select) = select_windows s <> [] && is_aggregate_query s && not (window_reads_rowid s) (* Is [rc] a projection the flattener can re-alias rather than substitute -- a column under its own name, or a [*]? Anything else (an expression, a rename) names an output the base table does not carry. *) let plain_projection (rc : result_col) = match rc.expr with | Star -> rc.alias = None | Col (_, n) -> ( match rc.alias with None -> true | Some a -> ident_equal a n) | _ -> false (* The body constraints, all of them sqlite3's: not an aggregate, not DISTINCT, no LIMIT/OFFSET, no ORDER BY, not compound, no window, no nested WITH, and a FROM that is one plain named table (so the flattened query scans exactly what the body scanned). *) let cte_body_flattenable (q : select) = List.for_all Fun.id [ q.ctes = []; q.compound = []; q.joins = []; not q.distinct; q.group_by = []; q.having = None; q.order_by = []; q.limit = None; q.offset = None; not (is_aggregate_query q); window_exprs q.cols = []; (match q.from with Table { subquery = None; _ } -> true | _ -> false); List.for_all plain_projection q.cols; ] let published cat siblings name = let cols f = try f () with Catalog.Error (Prepare _ | Runtime _) -> [] in match List.find_opt (fun (c : cte) -> ident_equal c.name name) siblings with | Some c -> cols (fun () -> Resolve.cte_columns (resolve_env cat) c) | None -> cols (fun () -> cat.columns name) let body_resolves bound cols (q : select) = cols = [] || let ok = ref true in let col nested qual name = let here = match qual with None -> true | Some q -> ident_equal q bound in let known = is_rowid_name name || List.exists (ident_equal name) cols in if (not nested) && not (here && known) then ok := false in Resolve.walk_select ~table:(fun _ _ -> ()) ~col ~nest:(fun _ _ -> true) ~cte:(fun _ _ -> Some true) false q; !ok let reads_resolve cat alias exposed base_cols (host : select) = let env = resolve_env cat in let ok = ref true in let captured n = (not (List.exists (ident_equal n) exposed)) && (is_rowid_name n || List.exists (ident_equal n) base_cols) in let col scope qual name = let elsewhere = match qual with | Some q -> not (ident_equal q alias) | None -> List.exists (fun (_, cols) -> List.exists (ident_equal name) cols) scope in if (not elsewhere) && captured name then ok := false in let nest scope u = scope @ Resolve.from_scope env u in Resolve.walk_select ~table:(fun _ _ -> ()) ~col ~nest ~cte:(fun scope c -> Some (nest scope c.query)) [] host; !ok let expand_alias_stars cat alias exposed (host : select) = let scope = List.map (fun (a, cols) -> if ident_equal a alias then (a, exposed) else (a, cols)) (Resolve.from_scope (resolve_env cat) host) in let cols_of (a, cols) = List.map (fun n : result_col -> { expr = Col (Some a, n); alias = None }) cols in let bare (rc : result_col) = rc.expr = Star in if List.exists bare host.cols && List.exists (fun (a, _) -> a = "") scope then None else Some (List.concat_map (fun (rc : result_col) -> match rc.expr with | Star -> List.concat_map cols_of (List.filter (fun (a, _) -> not (Resolve.is_semi_alias a)) scope) | Qualified_star q when ident_equal q alias -> cols_of (alias, exposed) | _ -> [ rc ]) host.cols) (* Does [host] use a window function in its select list or its ORDER BY? sqlite3's constraint (25) refuses flattening on either side of one. *) let has_window (host : select) = select_windows host <> [] (* Where in [host]'s FROM the reference stands: the leading source, or the operand of the [i]th join. The reference is matched as an identifier, so a CTE the query names in another case is spliced like any other and not left materialised for a spelling. *) type slot = Leading | Joined of int let cte_slots name (host : select) = let rebound = List.exists (fun (c : cte) -> ident_equal c.name name) host.ctes in let is_it (tr : table_ref) = (not rebound) && tr.subquery = None && ident_equal tr.name name in let leading = match host.from with | Table tr when is_it tr -> [ (Leading, tr) ] | Unit | Table _ | Select _ | Values _ | Table_function _ -> [] in leading @ List.filter_map (fun (i, (j : join)) -> if is_it j.table then Some (Joined i, j.table) else None) (List.mapi (fun i j -> (i, j)) host.joins) (* The table reference at [slot], replaced by [tr]. *) let put_slot slot tr (host : select) = match slot with | Leading -> { host with from = Table tr } | Joined i -> let at k (j : join) = if k = i then { j with table = tr } else j in { host with joins = List.mapi at host.joins } let flatten_candidate (c : cte) (host : select) slot = let padded = match slot with | Leading -> false | Joined i -> (List.nth host.joins i).type_ = Left in List.for_all Fun.id [ c.columns = []; (* a body that reads its own name is a fixpoint or an error, and neither is a subquery that can be spliced into its reader *) not (reads_table c.name c.query); cte_body_flattenable c.query; not (has_window host); List.for_all (fun (j : join) -> match j.type_ with Inner | Cross | Left -> true | _ -> false) host.joins; (not padded) || not host.distinct; ] (* [host] with the body's predicate [p] placed where the position demands: in the ON of the join that pads the spliced operand, since an outer join's ON decides which rows of the padded side match while its WHERE runs after the null-fill and would drop a padded row; in the reader's own WHERE anywhere else, where an inner join's ON lands too. *) let place_predicate slot p (host : select) = match slot with | Joined i when (List.nth host.joins i).type_ = Left -> ( match p with | None -> host | Some p -> let at k (j : join) = if k = i then let on = match j.on with None -> p | Some on -> Binary (And, on, p) in { j with on = Some on } else j in { host with joins = List.mapi at host.joins }) | Leading | Joined _ -> let where = match (p, host.where) with | None, w | w, None -> w | Some a, Some b -> Some (Binary (And, a, b)) in { host with where } let requalify ealias bound e = Resolve.subst_expr e ~replace:(fun qual name e -> match qual with | None -> Col (Some ealias, name) | Some q when ident_equal q bound -> Col (Some ealias, name) | Some _ -> e) let flatten_slot cat ~siblings (c : cte) (host : select) (slot, (tr : table_ref)) = match ((slot, tr), c.query.from) with | (slot, tr), Table base when flatten_candidate c host slot -> ( let ealias = Option.value tr.alias ~default:c.name in let bound = Option.value base.alias ~default:base.name in let exposed = Resolve.select_columns (resolve_env cat) c.query in let base_cols = published cat siblings base.name in (* Does the CTE expose exactly what the base table does? Then the re-aliased table publishes the same column list and the reader needs no rewriting at all -- not even a [*] expansion, and a NATURAL or USING join still equates the columns it equated. Narrower, both have to be answered for. *) let exposes_all = List.length exposed = List.length base_cols && List.for_all2 ident_equal exposed base_cols in let common_columns_kept = exposes_all || List.for_all (fun (j : join) -> (not j.natural) && j.using = []) host.joins in let cols = if exposes_all then Some host.cols else expand_alias_stars cat ealias exposed host in if (not common_columns_kept) || (not (body_resolves bound base_cols c.query)) || (not (reads_resolve cat ealias exposed base_cols host)) || cols = None then None else match Option.map (requalify ealias bound) c.query.where with | exception Resolve.Subst_hard -> None | body_where -> let spliced : table_ref = { schema = None; name = base.name; alias = Some ealias; subquery = None; } in let host = put_slot slot spliced host in let host = { host with cols = Option.get cols } in Some (place_predicate slot body_where host)) | _, (Unit | Table _ | Select _ | Values _ | Table_function _) -> None let flatten_into cat ~siblings (c : cte) (host : select) = let rec go host any = match List.find_map (flatten_slot cat ~siblings c host) (cte_slots c.name host) with | Some host -> go host true | None -> if any then Some host else None in go host false (* [c]'s body spliced into the first member of [later] that takes it, [None] where none does. A member written after [c] reads it exactly as the outer query does, so it is a position for the body too. *) let rec into_first cat ~siblings c = function | [] -> None | (l : cte) :: rest -> ( match flatten_into cat ~siblings c l.query with | Some q -> Some ({ l with query = q } :: rest) | None -> Option.map (fun rest -> l :: rest) (into_first cat ~siblings c rest)) (* A conjunct every disjunct of an OR carries is a conjunct of the OR: (A AND B) OR (A AND C) is A AND (B OR C), and (A) OR (A AND C) is A, both under three-valued logic. sqlite3 does the same (whereOrInfo, where.c), so TPC-H Q19's join equality, written into each of its three disjuncts, is one the join planner sees. Only a comparison of columns and literals is hoisted: it is the same wherever it is evaluated, raises nothing, and is the shape a join or a seek can use. *) let rec and_terms acc = function | Binary (And, a, b) -> and_terms (and_terms acc b) a | e -> e :: acc let rec or_terms acc = function | Binary (Or, a, b) -> or_terms (or_terms acc b) a | e -> e :: acc let hoistable = function | Binary ( (Eq | Neq | Lt | Le | Gt | Ge), (Col _ | Lit _ | Numeral _), (Col _ | Lit _ | Numeral _) ) -> true | _ -> false let rec remove_first e = function | [] -> [] | x :: xs -> if equal_expr x e then xs else x :: remove_first e xs let join op = function | [] -> None | x :: xs -> Some (List.fold_left (fun acc y -> Binary (op, acc, y)) x xs) (* The OR [e] of the disjuncts [ds], each a list of its conjuncts, with the terms all of them carry hoisted. *) let factor_terms e = function | [] | [ _ ] -> e | first :: rest as ds -> ( let shared c = hoistable c && List.for_all (List.exists (equal_expr c)) rest in let common = List.filter shared first in let left = List.map (fun d -> List.fold_right remove_first common d) ds in match join And common with | None -> e | Some hoisted when List.exists (( = ) []) left -> hoisted | Some hoisted -> ( match join Or (List.filter_map (join And) left) with | None -> hoisted | Some rest -> Binary (And, hoisted, rest))) let rec factor_or (e : expr) = match e with | Binary (And, a, b) -> Binary (And, factor_or a, factor_or b) | Binary (Or, _, _) -> factor_terms e (List.map (and_terms []) (or_terms [] e)) | e -> e let factor_disjunctions (s : select) = match s.where with | None -> s | Some w -> { s with where = Some (factor_or w) } let flatten_ctes cat (s : select) = if s.ctes = [] || ctes_are_cyclic s.ctes then s else (* Later CTEs read earlier ones, so walking the list backwards lets a chain collapse in one pass: flattening the last into the outer query leaves the one before it single-use at the outer query's FROM. *) let rec go (outer : select) later = function | [] -> { outer with ctes = later } | (c : cte) :: earlier -> ( let survives (outer : select) later = reads_table c.name outer || List.exists (fun (l : cte) -> reads_table c.name l.query) (later @ earlier) in let keep () = go outer (c :: later) earlier in if c.materialized = Materialized then keep () else (* the members before [c] are what its own body reads a relation from, so they are what its base table publishes through *) let siblings = earlier in match ( flatten_into cat ~siblings c outer, into_first cat ~siblings c later ) with (* nothing took the body, so the relation is still the answer -- and a CTE nobody reads is left exactly as written rather than quietly deleted *) | None, None -> keep () (* a reader the body could not be spliced into -- a later compound arm, a subquery -- still needs the relation, and once it is built every reader reads it: splicing the others would read the base table again for rows the relation holds *) | spliced_outer, spliced_later -> let outer' = Option.value spliced_outer ~default:outer in let later' = Option.value spliced_later ~default:later in if survives outer' later' then keep () else go outer' later' earlier) in go { s with ctes = [] } [] (List.rev s.ctes) (* ── A FROM subquery flattened into its reader ───────────────────── *) (* [e] holds a COLLATE outside any select nested in it. *) let rec holds_collate e = match e with | Collate _ -> true | e -> Ast.fold_expr ~select:(fun found _ -> found) (fun found x -> found || holds_collate x) false e (* The expressions of [s] outside its FROM. *) let clause_exprs (s : select) = List.map (fun (rc : result_col) -> rc.expr) s.cols @ Option.to_list s.where @ s.group_by @ Option.to_list s.having @ List.map fst s.order_by @ Option.to_list s.limit @ Option.to_list s.offset (* The stored table [tr], no derived table or WITH table, none of whose columns declares a sequence. *) let plain_stored env (tr : table_ref) = tr.subquery = None && match env.Resolve.columns tr.name with | cols -> List.for_all (fun c -> env.collation tr.name c = None) cols | exception Catalog.Error _ -> false (* What sqlite3 asks of a FROM subquery [sub] it merges (select.c, flattenSubquery): no aggregate (the caller's tag-select-0230 test), not DISTINCT (4), a FROM (7) of tables joined by inner or LEFT joins (27), no OFFSET (14), no compound (17) and no window (25); and here no WITH, tables {!plain_stored}, and no star, bare true or COLLATE among its results. *) let mergeable_subquery env (sub : select) = let sources = (match sub.from with | Table tr -> Some tr | Unit | Select _ | Values _ | Table_function _ -> None) :: List.map (fun (j : join) -> Some j.table) sub.joins in sub.compound = [] && sub.ctes = [] && (not sub.distinct) && (not (is_aggregate_query sub)) && select_windows sub = [] && sub.offset = None && List.for_all (function Some tr -> plain_stored env tr | None -> false) sources && List.for_all (fun (j : join) -> match j.type_ with Inner | Cross | Left -> true | _ -> false) sub.joins && List.for_all (fun (rc : result_col) -> match rc.expr with | Star | Qualified_star _ | Truth _ -> false | e -> not (holds_collate e)) sub.cols (* Whether every name [s] reads outside its FROM is a column of [own], its one source, or in an ORDER BY or GROUP BY the alias of a result column that no column of [own] shares, which binds before one would in an ORDER BY; and [s] nests no select and writes no COLLATE there. A name the merged tables publish can then capture none of them. *) let reads_only own (s : select) = let rec bound_only e = match e with | Col (q, n) -> Resolve.scope_binds own q n | e -> Ast.fold_expr ~select:(fun _ _ -> false) (fun ok x -> ok && bound_only x) true e in let aliases = List.filter_map (fun (rc : result_col) -> rc.alias) s.cols in let key e = match e with | Col (None, n) when List.exists (ident_equal n) aliases -> not (Resolve.scope_binds own None n) | e -> bound_only e in List.for_all (fun (rc : result_col) -> match rc.expr with Star | Qualified_star _ -> false | _ -> true) s.cols && List.for_all (fun e -> (not (holds_collate e)) && not (Ast.holds_select e)) (clause_exprs s) && List.for_all bound_only (List.map (fun (rc : result_col) -> rc.expr) s.cols @ Option.to_list s.where @ Option.to_list s.having) && List.for_all key (s.group_by @ List.map fst s.order_by) (* The FROM subquery [sub] of [s], read under [alias], that sqlite3 merges into [s], which reads it alone: {!mergeable_subquery}, with no LIMIT unless [s] has no LIMIT, WHERE or DISTINCT and is no aggregate (8, 9, 13, 19, 21), [s] no compound arm (15) and with no window (25), and {!reads_only} of it. Its ORDER BY is {!moved_order}'s to decide. *) let flattenable env ~alias (s : select) (sub : select) = let own = [ (alias, Resolve.select_columns env sub) ] in s.compound = [] && select_windows s = [] && mergeable_subquery env sub && (sub.limit = None || s.limit = None && s.where = None && (not s.distinct) && not (is_aggregate_query s)) && reads_only own s (* What becomes of the ORDER BY of the FROM subquery [sub] of [s] that [s] absorbs: [Some []] where it has none, or where it does nothing, under no LIMIT and with [s] ordering rows of its own that no aggregate reads (tag-select-0230); [Some keys] for the keys [s] takes as its own ORDER BY, where [s] is no aggregate (16), has no ORDER BY (11) and calls no function in its result (SF_ComplexResult), and no key names a result column of [sub] by its place or its alias, which would read [s]'s; [None] where [s] cannot absorb [sub]. *) let moved_order (s : select) (sub : select) = let aggregate = is_aggregate_query s in let rec calls e = match e with | Func _ -> true | e -> Ast.fold_expr ~select:(fun _ _ -> true) (fun found x -> found || calls x) false e in let aliases = List.filter_map (fun (rc : result_col) -> rc.alias) sub.cols in let by_result = function | Lit (Int _) -> true | Col (None, n) -> List.exists (ident_equal n) aliases | _ -> false in if sub.order_by = [] then Some [] else if sub.limit = None && s.order_by <> [] && not aggregate then Some [] else if aggregate || s.order_by <> [] || List.exists (fun (rc : result_col) -> calls rc.expr) s.cols || List.exists (fun (e, _) -> by_result e) sub.order_by then None else Some sub.order_by (* [s] with the FROM subquery it reads alone merged into it where sqlite3 merges one ({!flattenable}): the subquery's tables become [s]'s, its WHERE leads [s]'s, its ORDER BY and LIMIT become [s]'s where [s] has none, and each of [s]'s names of a column of it is the expression the subquery computes the column by (substExpr), a result column keeping the name it had. *) let merge_subquery cat (s : select) = match (s.from, s.joins) with | Select { fs_select = sub; fs_alias }, [] -> ( let env = resolve_env cat in let alias = Option.value fs_alias ~default:"" in match moved_order s sub with | Some order when flattenable env ~alias s sub -> let names = Resolve.select_columns env sub in let exprs = List.map (fun (rc : result_col) -> rc.expr) sub.cols in let by name = match List.find_index (ident_equal name) names with | Some i -> List.nth exprs i | None -> Col (None, name) in let subst = Resolve.substitute env ~own:[ (alias, names) ] ~by in let col (rc : result_col) = let alias = match rc.alias with | Some _ as a -> a | None -> Resolve.named_column rc.expr in { expr = subst rc.expr; alias } in let where = match (sub.where, Option.map subst s.where) with | w, None | None, w -> w | Some a, Some b -> Some (Binary (And, a, b)) in { s with cols = List.map col s.cols; from = sub.from; joins = sub.joins; where; group_by = List.map subst s.group_by; having = Option.map subst s.having; order_by = (if s.order_by = [] then order else List.map (fun (e, d) -> (subst e, d)) s.order_by); limit = (if sub.limit = None then s.limit else sub.limit); } | Some _ | None -> s) | _ -> s (* ── A FROM subquery coded on its own ────────────────────────────── *) let anyorder name = List.exists (ident_equal name) [ "count"; "min"; "max" ] (* [s] folds an aggregate whose value can depend on the order of its rows: any but count(), min() and max(), the ones sqlite3 flags SQLITE_FUNC_ANYORDER; another sets SF_OrderByReqd (resolve.c). *) let orders_aggregate (s : select) = let rec go e = match e with | Func (n, args) when is_agg n args -> (not (anyorder n)) || List.exists go args | Distinct_agg (n, a) -> (not (anyorder n)) || go a | Window (_, w) -> List.exists go (w.partition @ List.map fst w.order) | e -> Ast.fold_expr ~select:(fun acc _ -> acc) (fun acc x -> acc || go x) false e in List.exists go (List.map (fun (rc : result_col) -> rc.expr) s.cols @ Option.to_list s.having @ List.map fst s.order_by) (* The FROM subquery [sub] of [s], whose FROM has [nsrc] items, without an ORDER BY that does nothing there (select.c, tag-select-0230): [s] orders its rows itself or joins [sub] with another item, [sub] has no LIMIT and is no aggregate, and [s] folds no aggregate that reads its rows in order. *) let omit_order (s : select) ~nsrc (sub : select) = if sub.order_by <> [] && (s.order_by <> [] || nsrc > 1) && sub.limit = None && (not (is_aggregate_query sub)) && not (orders_aggregate s) then { sub with order_by = [] } else sub (* Whether the term [e] of a select whose items are [layout] constrains its item [i] alone (expr.c, sqlite3ExprIsTableConstant): each column it names is one [i] binds, and it calls deterministic scalar functions alone. A term holding a select is not pushed: the copy would be a second coding of the same numbered subquery. *) let single_item_term layout i e = let item q n = List.find_index (fun src -> Resolve.scope_binds [ src ] q n) layout in let rec ok e = match e with | Col (q, n) -> item q n = Some i | Truth n -> ( match item None n with None -> true | Some j -> j = i) | In_select _ | Scalar_select _ | Exists _ -> false | Func (n, args) -> Func.deterministic n && (not (is_agg n args)) && List.for_all ok args | Distinct_agg _ | Filter _ | Ordered_agg _ | Window _ -> false | e -> Ast.fold_expr ~select:(fun _ _ -> false) (fun acc x -> acc && ok x) true e in ok e let binary_collation = function | None -> true | Some c -> Option.fold ~none:false ~some:Collation.is_binary (Collation.of_string c) (* [sub], read as the item [alias] of a select, with [e] copied into it, each name of a column of [sub] in [e] the expression each arm computes the column by (substExpr): into its HAVING where the arm is an aggregate, else its WHERE. [None] where a sequence would then decide a comparison: sqlite3 gives a computed column the sequence the column had, a COLLATE no comparison sees as written, which this tree cannot spell, so a term pushed through a computed column is pushed only where every sequence it meets is BINARY. *) let push_term env ~alias (sub : select) e = let names = Resolve.select_columns env sub in let arms = sub :: List.map snd sub.compound in let collations = List.mapi (fun j _ -> Resolve.output_collation env sub j) names in let used = ref [] in let rec reads e = match e with | Col (q, n) when Resolve.scope_binds [ (alias, names) ] q n -> used := Catalog.Ident.index n names :: !used | e -> Ast.fold_expr ~select:(fun () _ -> ()) (fun () x -> reads x) () e in reads e; let computed (arm : select) = let exprs = Resolve.output_exprs env arm in List.exists (function | Some j -> ( match List.nth_opt exprs j with | Some (Col _) -> not (Option.equal String.equal (Resolve.expr_collation env arm (List.nth exprs j)) (List.nth collations j)) | Some _ | None -> true) | None -> false) !used in let binary_only = (not (holds_collate e)) && List.for_all (function | Some j -> binary_collation (List.nth collations j) | None -> true) !used in if List.exists computed arms && not binary_only then None else let into (arm : select) = let exprs = Resolve.output_exprs env arm in let by name = match Catalog.Ident.index name names with | Some j -> List.nth exprs j | None -> Col (None, name) in let e = Resolve.substitute env ~own:[ (alias, names) ] ~by e in let add = function | None -> Some e | Some w -> Some (Binary (And, w, e)) in if is_aggregate_query arm then { arm with having = add arm.having } else { arm with where = add arm.where } in let base = into sub in Some { base with compound = List.map (fun (op, arm) -> (op, into arm)) sub.compound; } (* Whether terms may be pushed into [sub] at all (pushDownWhereTerms): no LIMIT (3), no window (6, whose PARTITION BY check this does not make), and in a compound joined by more than UNION ALL, BINARY result columns (8). *) let pushable env (sub : select) = let arms = sub :: List.map snd sub.compound in sub.limit = None && List.for_all (fun arm -> select_windows arm = []) arms && (List.for_all (fun (op, _) -> op = Union_all) sub.compound || List.for_all (fun arm -> List.for_all (fun j -> binary_collation (Resolve.output_collation env arm j)) (List.init (List.length (Resolve.output_exprs env arm)) Fun.id)) arms) (* The FROM subquery [sub], item [i] of [s] read as [alias], with the terms of [s] that constrain it alone copied into it (select.c, pushDownWhereTerms): the WHERE's and an inner join's ON's, or for the right side of a LEFT JOIN its own ON's, taken last first as sqlite3 walks the AND tree. A select with a RIGHT or FULL join pushes nothing (restrictions 3, 6, 9 and 10). *) let push_down env (s : select) layout i ~alias (sub : select) = let joins = Array.of_list s.joins in let outer = function Right | Full -> true | _ -> false in if Array.exists (fun (j : join) -> outer j.type_) joins || not (pushable env sub) then sub else let terms = let on (j : join) = Option.fold ~none:[] ~some:conjuncts j.on in if i > 0 && joins.(i - 1).type_ = Left then on joins.(i - 1) else Option.fold ~none:[] ~some:conjuncts s.where @ List.concat_map (fun (j : join) -> match j.type_ with Inner | Cross -> on j | _ -> []) s.joins in List.fold_left (fun sub e -> if single_item_term layout i e then Option.value ~default:sub (push_term env ~alias sub e) else sub) sub (List.rev terms) (* Whether [e], a HAVING term of [s], reads nothing but constants and GROUP BY keys of BINARY sequence (expr.c, sqlite3ExprIsConstantOrGroupBy). *) let constant_or_group_by env layout (s : select) e = let rec strip = function Collate (e, _) -> strip e | e -> e in let same a b = match (strip a, strip b) with | Col (q, n), Col (q', n') -> ( match (Plan.position layout q n, Plan.position layout q' n') with | Some p, Some p' -> p = p' | _ -> false) | a, b -> Ast.equal_expr a b in let key e = List.exists (fun k -> same e k && binary_collation (Resolve.expr_collation env s k)) s.group_by in let rec ok e = key e || match e with | In_select _ | Scalar_select _ | Exists _ | Col _ | Truth _ -> false | Func (n, args) -> Func.deterministic n && (not (is_agg n args)) && List.for_all ok args | Distinct_agg _ | Filter _ | Ordered_agg _ | Window _ -> false | e -> Ast.fold_expr ~select:(fun _ _ -> false) (fun acc x -> acc && ok x) true e in ok e (* [s] with each term of its HAVING that reads nothing but constants and GROUP BY keys moved to the end of its WHERE (select.c, havingToWhere), but one that is a literal false. *) let having_to_where env layout (s : select) = match (s.group_by, s.having) with | [], _ | _, None -> s | _, Some h -> let false_lit = function Lit (Int 0L) -> true | _ -> false in let moved, kept = List.partition (fun e -> (not (false_lit e)) && constant_or_group_by env layout s e) (conjuncts h) in if moved = [] then s else let conj w e = match w with None -> Some e | Some w -> Some (Binary (And, w, e)) in { s with where = List.fold_left conj s.where moved; having = List.fold_left conj None kept; } let flatten_subqueries ?(moved = fun _ _ -> ()) cat (s : select) = let s = merge_subquery cat s in let env = resolve_env cat in match Plan.layout env ~bound: (List.map (fun (c : cte) -> (c.name, Resolve.cte_columns env c)) s.ctes) s with | exception Catalog.Error _ -> s | layout -> let nsrc = 1 + List.length s.joins in let code i ~alias sub = let sub' = push_down env s layout i ~alias (omit_order s ~nsrc sub) in if sub' != sub then moved sub' sub; sub' in let s = if s.compound <> [] then s else { s with from = (match s.from with | Select { fs_select; fs_alias } -> Select { fs_select = code 0 ~alias:(Option.value fs_alias ~default:"") fs_select; fs_alias; } | f -> f); joins = List.mapi (fun k (j : join) -> match j.table.subquery with | Some sub -> let alias = Option.value j.table.alias ~default:j.table.name in { j with table = { j.table with subquery = Some (code (k + 1) ~alias sub); }; } | None -> j) s.joins; } in having_to_where env layout s let closed_rows ~run ~params cat s = match Hashtbl.find_opt cat.subquery_memo (s, params) with | Some rows -> rows | None -> let rows = run s in Hashtbl.replace cat.subquery_memo (s, params) rows; rows type membership = { states : Value_ops.affinity option; rows : Catalog.Value.t list option; } let opaque_membership = { states = None; rows = None } let membership ~run ~params cat sub = let env = resolve_env cat in let first_col = function v :: _ -> v | [] -> Null in { states = Resolve.in_select_affinity env sub; rows = (if Resolve.correlated env [] sub then None else Some (List.map first_col (closed_rows ~run ~params cat sub))); } (* ── Aggregates of an enclosing query ───────────────────────────── *) (* An aggregate inside a subquery whose arguments read columns of [s] and of no source of the subquery is [s]'s aggregate, not the subquery's: sqlite3 attributes it to the query whose columns it reads (resolve.c, the aggregate's NC_MinMaxAgg / op2 level), which makes [s] an aggregate query. [s] is rewritten so its own engine computes it: a grouped select [g] over [s]'s sources computes every aggregate of [s] -- its own and those it lifts out of its subqueries -- and every column of [s] they and the rest of [s] read, then [s] reads those values off [g] as columns. [s]'s HAVING becomes the WHERE over [g], and the subqueries read the lifted values as columns of the enclosing row, which is how a correlated subquery is already run. The names [g] publishes cannot be spelled in SQL. *) let lifted_source = "\000outer" let lifted_agg i = Fmt.str "\000agg%d" i let lifted_col i = Fmt.str "\000col%d" i (* The column references [e] reads outside any subquery, and whether it holds one. *) let rec plain_refs e = match e with | Col (q, n) -> ([ (q, n) ], false) | e -> Ast.fold_expr ~select:(fun (rs, _) _ -> (rs, true)) (fun (rs, sub) x -> let rs', sub' = plain_refs x in (rs @ rs', sub || sub')) ([], false) e (* What a lifting has named so far: the aggregates [g] computes and the columns of [s] it publishes, each under its unspellable name, and how many aggregates it has taken out of a subquery. The columns [s] binds are read at the first subquery that names one. *) type lifting = { env : Resolve.env; own : (string * string list) list Lazy.t; mutable aggs : (expr * string) list; mutable cols : ((string option * string) * string) list; mutable lifted : int; mutable late : (unit -> unit) option; (* the first refusal sqlite3 makes only once every name is resolved *) } (* The clause of [s] a subquery sits in: one that folds [s]'s group (its select list, HAVING, ORDER BY), one where [s] has no group yet (its WHERE, an ON), or the GROUP BY that makes it. *) type clause = Folding | Rowless | Grouping let binds_own lf q n = Resolve.scope_binds (Lazy.force lf.own) q n let agg_ref lf e = let name = match List.find_opt (fun (e', _) -> Ast.equal_expr e e') lf.aggs with | Some (_, n) -> n | None -> let n = lifted_agg (List.length lf.aggs) in lf.aggs <- lf.aggs @ [ (e, n) ]; n in Col (Some lifted_source, name) let same_ref (q, n) (q', n') = ident_equal n n' && match (q, q') with | None, None -> true | Some a, Some b -> ident_equal a b | _ -> false let col_ref lf q n = let name = match List.find_opt (fun (k, _) -> same_ref (q, n) k) lf.cols with | Some (_, a) -> a | None -> let a = lifted_col (List.length lf.cols) in lf.cols <- lf.cols @ [ ((q, n), a) ]; a in Col (Some lifted_source, name) (* [e] reads columns of [s], none of [inner]'s, and holds no subquery. *) let liftable lf inner e = let rs, sub = plain_refs e in rs <> [] && (not sub) && List.for_all (fun (q, n) -> (not (Resolve.scope_binds inner q n)) && binds_own lf q n) rs let agg_name e = match e with | Func (n, _) | Distinct_agg (n, _) -> n | Filter (Func (n, _), _) | Ordered_agg (Func (n, _), _) -> n | _ -> "aggregate" let misuse_of e = Catalog.Error.fail_prepare "misuse of aggregate function %s()" (agg_name e) (* The refusals sqlite3 makes as it codes [s] (select.c), after every name is resolved, so a resolver's refusal anywhere in the statement comes first. *) let refuse_late lf f = if lf.late = None then lf.late <- Some f let late_misuse lf clause e = match clause with | Folding -> () | Rowless -> refuse_late lf (fun () -> Catalog.Error.fail_prepare "misuse of aggregate: %s()" (agg_name e)) | Grouping -> refuse_late lf (fun () -> Catalog.Error.fail_prepare "aggregate functions are not allowed in the GROUP BY clause") (* Whether [q] folds groups of its own: it groups, or its select list holds an aggregate that is [q]'s and not one of [s]'s it would lift. *) let aggregates_itself lf inner (q : select) = let rec own e = match e with | e when is_agg_expr e -> not (liftable lf inner e) | Window (f, _) -> Ast.fold_expr ~select:(fun acc _ -> acc) (fun acc x -> acc || own x) false f | e -> Ast.fold_expr ~select:(fun acc _ -> acc) (fun acc x -> acc || own x) false e in q.group_by <> [] || List.exists (fun (rc : result_col) -> own rc.expr) q.cols (* The subquery [q], under the scopes [outer] of the subqueries around it, in the [clause] of [s] the outermost of them sits in, with each aggregate of [s] it holds and each column of [s] it reads replaced by [g]'s. sqlite3's resolver refuses such an aggregate where the select it is written in takes none: its WHERE, HAVING or ON when it does not aggregate itself (resolve.c, NC_AllowAgg). *) let rec lift_sub lf ~clause outer (q : select) = let inner = outer @ Resolve.binding_scope lf.env q in let rec ex ~allowed e = match e with | e when is_agg_expr e && liftable lf inner e -> if not allowed then misuse_of e; late_misuse lf clause e; lf.lifted <- lf.lifted + 1; agg_ref lf e | Col (cq, n) when (not (Resolve.scope_binds inner cq n)) && binds_own lf cq n -> col_ref lf cq n | e -> Ast.map_expr ~select:(lift_sub lf ~clause inner) (ex ~allowed) e in let out = ex ~allowed:true and filter = ex ~allowed:(aggregates_itself lf inner q) in { q with cols = List.map (fun (rc : result_col) -> { rc with expr = out rc.expr }) q.cols; where = Option.map filter q.where; group_by = List.map out q.group_by; having = Option.map filter q.having; order_by = List.map (fun (e, d) -> (out e, d)) q.order_by; joins = List.map (fun (j : join) -> { j with on = Option.map filter j.on }) q.joins; compound = List.map (fun (op, arm) -> (op, lift_sub lf ~clause outer arm)) q.compound; } (* The subqueries of an expression of [s], rewritten; [s]'s own aggregates and columns are left as they are. *) let rec in_subqueries lf ~clause e = Ast.map_expr ~select:(lift_sub lf ~clause []) (in_subqueries lf ~clause) e (* An expression of [s]'s output, reading every aggregate and column of [s] off [g]. *) let rec lift_top lf e = match e with | e when is_agg_expr e -> agg_ref lf e | Col (q, n) when binds_own lf q n -> col_ref lf q n | e -> Ast.map_expr ~select:(lift_sub lf ~clause:Folding []) (lift_top lf) e let refuse_lift what = Catalog.Error.fail_prepare "an aggregate of an enclosing query's columns in a subquery is not \ supported %s" what (* [s]'s select list with each [*] spelled out as the columns it names. *) let expand_stars env (s : select) = let natural = List.exists (fun (j : join) -> j.natural || j.using <> []) s.joins in let star alias_ok = if natural then refuse_lift "beside a * over a NATURAL or USING join"; List.concat_map (fun (a, cs) -> if not (alias_ok a) then [] else List.filter_map (fun c -> if String.equal c Resolve.rowid_sentinel then None else let qual = if a = "" then None else Some a in Some { expr = Col (qual, c); alias = Some c }) cs) (Resolve.from_scope env s) in List.concat_map (fun (rc : result_col) -> match rc.expr with | Star -> star (fun a -> not (Resolve.is_semi_alias a)) | Qualified_star q -> star (ident_equal q) | _ -> [ rc ]) s.cols (* [s] reading its output off [g], the grouped select over its sources. *) let lifted_select lf (s : select) = let names = Resolve.select_columns lf.env s in let cols = List.map2 (fun (rc : result_col) name -> { expr = lift_top lf rc.expr; alias = Some (Option.value rc.alias ~default:name); }) (expand_stars lf.env s) names in let where = Option.map (lift_top lf) s.having in let order_by = List.map (fun (e, d) -> (lift_top lf e, d)) s.order_by in let published = List.map (fun ((q, n), a) -> { expr = Col (q, n); alias = Some a }) lf.cols @ List.map (fun (e, a) -> { expr = e; alias = Some a }) lf.aggs in let g = { s with ctes = []; compound = []; distinct = false; order_by = []; limit = None; offset = None; having = None; cols = published; } in { s with cols; from = Select { fs_select = g; fs_alias = Some lifted_source }; joins = []; where; group_by = []; having = None; order_by; } let lift_outer_aggregates env (s : select) : select = let lf = { env; own = lazy (Resolve.binding_scope env s); aggs = []; cols = []; lifted = 0; late = None; } in let look ~clause e = ignore (in_subqueries lf ~clause e) in Option.iter (look ~clause:Rowless) s.where; List.iter (look ~clause:Grouping) s.group_by; List.iter (fun (j : join) -> Option.iter (look ~clause:Rowless) j.on) s.joins; List.iter (fun (rc : result_col) -> look ~clause:Folding rc.expr) s.cols; Option.iter (look ~clause:Folding) s.having; List.iter (fun (e, _) -> look ~clause:Folding e) s.order_by; Option.iter (fun refuse -> refuse ()) lf.late; if lf.lifted = 0 then s else begin if s.compound <> [] then refuse_lift "in a compound select"; if select_windows s <> [] then refuse_lift "beside a window function"; lifted_select { lf with aggs = []; cols = []; lifted = 0 } s end (* The select that answers whether the column of [sub] holds the value [v]: [sub] with [col = v] in its WHERE, no order and a row at most, which an index on the column answers with a seek. The equality compares as the membership does: the column's affinity applies to [v], which has none, and the column orders text under BINARY. [None] where [sub]'s rows are not its sources' rows narrowed by its WHERE (an aggregate, a group, a compound, a window, a limit), where its column is not a column reference, and where that column has another sequence, which the membership does not compare under. *) let holds_value env (sub : select) v = let binary = match Resolve.output_collation env sub 0 with | None -> true | Some c -> String.equal (String.uppercase_ascii c) "BINARY" in match sub with | { ctes = []; compound = []; group_by = []; having = None; limit = None; offset = None; cols = [ { expr = Col _ as col; _ } ]; _; } when binary && (not (is_aggregate_query sub)) && select_windows sub = [] -> let eq = Binary (Eq, col, Lit v) in Some { sub with where = Some (match sub.where with | None -> eq | Some w -> Binary (And, w, eq)); order_by = []; limit = Some (Lit (Int 1L)); } | _ -> None (* The select an EXISTS runs for [s]: sqlite3 codes no result column of a select whose rows it only counts (select.c, selectInnerLoop: eDest!=SRT_Exists) and drops its ORDER BY and DISTINCT, whose names it has resolved. A column stays where it is computed all the same: under an aggregate, read by the WHERE through its alias, or a [*], whose width a compound arm is checked against; and so does an ORDER BY with an ordinal, which resolution checks against the columns. A compound is counted arm by arm unless its operator compares the rows: EXCEPT, INTERSECT, and a UNION under an OFFSET. *) let exists_body (s : select) = let plain (a : select) = if List.exists is_aggregate a.cols || a.having <> None then a else let rec reads alias e = match e with | Col (None, n) -> ident_equal n alias | e -> Ast.fold_expr ~select:(fun found _ -> found) (fun found x -> found || reads alias x) false e in let kept (rc : result_col) = match rc.expr with | Star | Qualified_star _ -> true | _ -> ( match rc.alias with | None -> false | Some n -> Option.fold ~none:false ~some:(reads n) a.where) in let constant (rc : result_col) = if kept rc then rc else { rc with expr = Lit (Int 1L) } in (* an ordinal key reads a column by its place, which resolution checks *) let rec ordinal = function | Collate (e, _) -> ordinal e | e -> Resolve.integer_term e <> None in let order_by = if List.exists (fun (e, _) -> ordinal e) a.order_by then a.order_by else [] in { a with cols = List.map constant a.cols; distinct = false; order_by } in let counted (op, _) = match (op : set_op) with | Union_all -> true | Union -> s.offset = None | Except | Intersect -> false in if s.compound = [] then plain s else if List.for_all counted s.compound then { (plain { s with compound = [] }) with compound = List.map (fun (op, arm) -> (op, plain arm)) s.compound; } else s (* The one stored table an EXISTS's subquery [sub] reads, where sqlite3 joins it (select.c, existsToJoin): one source and not a subquery, which a view or a WITH table is, no aggregate, no LIMIT and no compound. A WITH of the subquery's own is no reason to keep it, as sqlite3 has bound every name of it by then (sqlite3SelectExpand); here the moved WHERE would lose the tables it names, so a subquery whose WHERE names one stays. *) let semi_table ~table (sub : select) = let own name = List.exists (fun (c : cte) -> ident_equal c.name name) sub.ctes in let names_own e = let found = ref false in Resolve.walk_expr ~table:(fun () (tr : table_ref) -> if own tr.name then found := true) ~col:(fun () _ _ -> ()) ~nest:(fun () _ -> ()) ~cte:(fun () _ -> Some ()) () e; !found in match sub.from with | Table tr when tr.subquery = None && table tr && sub.joins = [] && sub.compound = [] && sub.limit = None && (not (is_aggregate_query sub)) && (sub.ctes = [] || (not (own tr.name)) && not (Option.fold ~none:false ~some:names_own sub.where)) -> Some tr | _ -> None (* The join of the [k]th table [tr] an EXISTS over [sub] gives, and the WHERE of [sub] it moves to the select, its names qualified by the join's alias. *) let semi_join ?moved env k (tr : table_ref) (sub : select) = let alias = Resolve.semi_alias k in let own = Resolve.binding_scope env sub in ( { table = { tr with alias = Some alias }; on = None; type_ = Semi (Option.value tr.alias ~default:tr.name); natural = false; using = []; }, Option.map (Resolve.requalify ?moved env ~own ~alias) sub.where ) (* Whether an EXISTS is a conjunct of [e], under its ANDs alone. *) let rec exists_conjunct = function | Binary (And, a, b) -> exists_conjunct a || exists_conjunct b | Exists _ -> true | _ -> false let exists_to_join ?moved ~table env (s : select) = let driven = List.exists (fun (j : join) -> match j.type_ with Right | Full -> true | _ -> false) s.joins in match s.where with | Some where when exists_conjunct where && s.offset = None && s.compound = [] && not driven -> let added = ref [] in let sources () = 1 + List.length s.joins + List.length !added in (* left to right, under the ANDs of the WHERE alone *) let rec conjunct e = match e with | Binary (And, a, b) -> let a = conjunct a in Binary (And, a, conjunct b) | Exists sub when sources () < 64 -> ( match semi_table ~table sub with | None -> e | Some tr -> added := semi_join ?moved env (List.length !added) tr sub :: !added; Lit (Int 1L)) | e -> e in let where = conjunct where in if !added = [] then s else let added = List.rev !added in let and_ w = function | _, Some w' -> Binary (And, w, w') | _, None -> w in { s with joins = s.joins @ List.map fst added; where = Some (List.fold_left and_ where added); } | Some _ | None -> s let hoist_subqueries ~run ~params cat (s : select) : select = let env = resolve_env cat in let run sub = closed_rows ~run ~params cat sub in (* the value keeps the affinity of the subquery's result column, which a comparison reads as it reads a column's (expr.c, sqlite3ExprAffinity of a TK_SELECT) *) let scalar sub = let v = match run sub with (v :: _) :: _ -> v | _ -> Null in match Resolve.in_select_affinity env sub with | Some aff -> Affinity (Lit v, aff) | None -> Lit v in let rec go e = match e with | Scalar_select sub when not (Resolve.correlated env [] sub) -> scalar sub | Exists sub -> let sub = exists_body sub in if Resolve.correlated env [] sub then Exists sub else Lit (bool (run sub <> [])) (* A literal on the left of an uncorrelated IN is one key: a row of the subquery equal to it makes the IN true, NULLs or not, and finding one is a seek where the column is indexed. Without one the IN is false or NULL as the subquery's NULLs say, which its rows decide as written. *) | In_select (Lit v, sub) when v <> Null && not (Resolve.correlated env [] sub) -> ( match holds_value env sub v with | Some probe when run probe <> [] -> Lit (bool true) | Some _ | None -> Ast.map_expr ~select:Fun.id go e) (* An OR whose left side folded to true is true, whatever the right side is, NULL included, so the subqueries on the right are not run. *) | Binary (Or, a, b) -> ( match go a with Lit (Int 1L) as t -> t | a -> Binary (Or, a, go b)) (* A correlated subquery, and the subquery of an [IN], are handed back as written: the first is not closed and the second states the affinity the membership compares under. *) | e -> Ast.map_expr ~select:Fun.id go e in { s with cols = List.map (fun (rc : result_col) -> { rc with expr = go rc.expr }) s.cols; where = Option.map go s.where; group_by = List.map go s.group_by; having = Option.map go s.having; order_by = List.map (fun (e, d) -> (go e, d)) s.order_by; joins = List.map (fun (j : join) -> { j with on = Option.map go j.on }) s.joins; } let within_build_budget rows = let rec go cells bytes = function | [] -> true | r :: rest -> let cells = cells + max 1 (List.length r) in let bytes = bytes + Join.row_bytes r in if Join.over Join.budget ~cells ~bytes then false else go cells bytes rest in go 0 0 rows let bind_ctes cat (s : select) = if s.ctes = [] then cat else materialize_ctes cat [||] s.ctes let cte_relations cat (s : select) = List.map (fun (c : cte) -> ( c.name, try cat.columns c.name with Catalog.Error (Prepare _ | Runtime _) -> [] )) s.ctes let facts cat : Plan.facts = { columns = cat.columns; seekable = (fun tr -> if tr.subquery = None then Some tr.name else None); best_index = (* The key values are of no use here: a catalog answers an index by the columns it binds, and the rows one key selects is a count only the store can make. *) (fun table keys -> Option.map (fun (p : Catalog.Spi.access_path) : Plan.path -> { descr = p.Catalog.Spi.path; unique = p.unique; bound = p.bound; rows_per_key = p.rows_per_key; (* A catalog answers an index by naming it and hands back rows of the relation, so a path here is never the answer itself. *) covering = false; index = None; rowid_order = p.unique; }) (cat.best_index_for table (List.map fst keys))); affinity = cat.affinity; collation = cat.collation; row_count = cat.row_count; seek_answers_rowid = false; const_subquery = true; (* [index_scan] answers rows without their identity, so the rows two values of a list both select could not be told from two equal rows *) seek_lists = false; (* a catalog's relations are lists, which sort as their ORDER BY says *) ordered = (fun _ _ a -> (a, None, None)); (* a catalog's relations have no loops to weigh *) join = (fun _ _ -> None); } (* The plan over a catalog that already binds [s]'s own [WITH] relations. *) let plan_bound cat (s : select) = let env = resolve_env cat in let bound = cte_relations cat s in Plan.v (facts cat) env ~bound:(List.map fst bound) s (Plan.layout env ~bound s) let plan cat (s : select) = plan_bound (bind_ctes cat s) s let plan_sources cat s = (plan cat s).Plan.accesses type seek_key = Value of Ast.value | Outer of int * int (* The binding of each key of [access], or [None] to read the relation: the path is not a seek or a key's value is not bound. *) let seek_keys cat params (access : Plan.access) = match access with | Plan.Scan | Plan.Ordered _ | Plan.Probe _ -> None | Plan.Seek { keys; _ } -> let rec key = function | Plan.Outer (i, j) -> Some (Outer (i, j)) (* the affinity a key states is the seek's to apply, and leaves its value as it is *) | Plan.Const (Affinity (e, _)) -> key (Plan.Const e) | Plan.Const ((Lit _ | Numeral _) as e) -> Option.map (fun v -> Value v) (literal e) | Plan.Const (Param i) when i >= 0 && i < Array.length params -> Some (Value params.(i)) (* The planner accepted this key because the subquery is closed, so it has one value and the memo already holds it: the fold that turned the same subquery into a literal for the residual predicate ran first, through the same catalog. *) | Plan.Const (Scalar_select sub) -> let run s = cat.subquery cat [] s params in Some (Value (match closed_rows ~run ~params cat sub with | (v :: _) :: _ -> v | [] :: _ | [] -> Null)) | Plan.Const _ -> None (* declined: [index_scan] cannot return each row a list selects once *) | Plan.In_list _ | Plan.In_select _ -> None in (* an IS key seeks a NULL as a value, which a lookup by equality does not: the relation is read and the WHERE tests it *) let bind (k : Plan.key) = if k.nulls then None else Option.map (fun v -> (k.column, v)) (key k.value) in let bound = List.filter_map bind keys in if List.length bound <> List.length keys then None else Some bound let resolved_layout cat (s : Ast.select) = let bound = cte_relations cat s in let names = List.map fst bound in let slot (tr : table_ref) = tr.subquery = None && (not (List.exists (Catalog.Ident.equal tr.name) names)) && cat.has_rowid tr.name in let refs = (match s.from with Table tr -> Some tr | _ -> None) :: List.map (fun (j : join) -> Some j.table) s.joins in List.map2 (fun (alias, cols) tr -> match tr with | Some tr when slot tr -> (alias, cols @ [ Resolve.rowid_sentinel ]) | Some _ | None -> (alias, cols)) (Plan.layout (resolve_env cat) ~bound s) refs (* The access path, one line per source in the order the engine reads them. *) let explain cat (s : Ast.select) = (* The engine flattens and resolves before it plans, so describing anything else would describe a query it does not run. *) let s = flatten_subqueries cat (flatten_ctes cat s) in let cat = bind_ctes cat s in let env = 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 Resolve.check_columns (resolved_layout cat s) s; check_calls ~explain:true cat s; let named (tr : table_ref) = if tr.subquery = None then `Table tr.name else `Other "(subquery)" in let leading = match s.from with | Unit -> `Other "CONSTANT ROW" | Table tr -> named tr | Select _ -> `Other "(subquery)" | Values _ -> `Other "(values)" | Table_function { tf_name; _ } -> `Other (Fmt.str "(%s)" tf_name) in let names = leading :: List.map (fun (j : join) -> named j.table) s.joins in Plan.explain (plan_bound cat s) ~names ~joins:(List.map (fun (j : join) -> j.type_) s.joins)