(*--------------------------------------------------------------------------- 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 open Model module type S = Select_intf.S module Make (R : S) = struct include Select_execute.Make (R) (* The name EXPLAIN gives a table [s] reads, once its common table expressions are flattened: the alias the query wrote, or else the table's own name. A CTE read in place of a table is flattened into the query, and sqlite3 names the table of its body as the body does, not by the name the query read the CTE under (select.c, flattenSubquery); one that is materialised keeps that name. *) let explain_name (s : Ast.select) = let cte name = List.exists (fun (c : Ast.cte) -> Catalog.Ident.equal c.name name) s.ctes in let read (tr : Ast.table_ref) = if cte tr.name then Some (Option.value tr.alias ~default:tr.name) else None in let spliced = (match s.from with Ast.Table tr -> Option.to_list (read tr) | _ -> []) @ List.filter_map (fun (j : Ast.join) -> read j.table) s.joins in fun (tr : Ast.table_ref) -> match tr.alias with | Some a when cte tr.name || not (List.exists (Catalog.Ident.equal a) spliced) -> a | Some _ | None -> tr.name (* The column [e] is in [s], its table and position there, where [e] is one of a table of [s] the store holds. *) let operand_column t (s : Ast.select) layout e = 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 let col = function | Ast.Col (q, c) | Ast.Collate (Ast.Col (q, c), _) -> Plan.position layout q c | _ -> None in Option.bind (col e) (fun (i, j) -> match List.nth_opt refs i with | Some (Some tr) when tr.Sql.Ast.subquery = None -> ( match gtable t tr.Sql.Ast.name with | gt when j < List.length gt.schema.columns -> Some (gt, j) | _ -> None | exception Catalog.Error _ -> None) | Some _ | None -> None) (* [s] reads its sources and nothing else: no join, filter, grouping, compound, LIMIT or WITH; a DISTINCT does not matter to a set. *) let bare (s : Ast.select) = List.for_all Fun.id [ s.joins = []; Option.is_none s.where; s.group_by = []; Option.is_none s.having; s.compound = []; Option.is_none s.limit; s.ctes = []; ] (* The table of [sub] and the column it reads, where [sub] is one column of one table and nothing else (expr.c, isCandidateForInOpt). *) let in_candidate t (sub : Ast.select) = match (sub.from, sub.cols) with | Ast.Table ({ subquery = None; _ } as tr), [ { expr = Ast.Col (_, c); _ } ] when bare sub && view t tr.name = None && not (is_master_name tr.name) -> ( match gtable t tr.name with | gt -> Some (gt, c) | exception Catalog.Error _ -> None) | _ -> None (* Whether the comparison of the IN's left operand, of affinity [lhs], with a column of affinity [col] is one an index of that column answers: none where either is numeric and the column is not (expr.c, sqlite3FindInIndex). *) let in_affinity_ok lhs col = let numeric = function | `Integer | `Real | `Numeric -> true | `Text | `Blob -> false in match lhs with None -> true | Some a -> numeric col || not (numeric a) (* The line of an index of [gt] whose first key is its column [p] and serves the IN of [lhs] in [s]: under the sequence the comparison takes, not partial, and UNIQUE of that column alone where the IN is a seek's key, the newest first. *) let in_index_line t (s : Ast.select) layout ~loop lhs (gt : generic_table) p = let columns = gt.schema.columns in let lhs_col = operand_column t s layout lhs in let lhs_aff = match lhs with | Ast.Cast (_, ty) -> Some (Sql.Value_ops.affinity_of_type ty) | _ -> Option.map (fun ((g : generic_table), j) -> (List.nth g.schema.columns j).type_affinity) lhs_col in let declared columns j = Option.value ~default:Sql.Collation.default (Decl.declared_collation columns j) in let required = match (lhs, lhs_col) with | Ast.Collate (_, n), _ -> Sql.Collation.of_string n | _, Some ((g : generic_table), j) -> Some (declared g.schema.columns j) | _, None -> Some (declared columns p) in let serves (idx : index) = idx.where = None && (match (idx.keys, idx.orders) with | Column k :: _, o :: _ -> k = p && Option.fold ~none:true ~some:(Sql.Collation.equal o.Sql.Order.collation) required | _ -> false) && ((not loop) || (idx.unique && List.length idx.keys = 1)) in if not (in_affinity_ok lhs_aff (List.nth columns p).type_affinity) then None else Option.map (fun (idx : index) -> Fmt.str "USING INDEX %s FOR IN-OPERATOR" idx.name) (List.find_opt serves (List.rev gt.indexes)) (* The line sqlite3 prints where an [IN (SELECT ...)] reads an existing b-tree rather than an ephemeral index of its rows: the subquery is one column of one table, and that column the rowid or the first key of an index that serves the comparison (expr.c, sqlite3FindInIndex). *) let in_operator_line t (s : Ast.select) layout ~loop lhs (sub : Ast.select) = Option.bind (in_candidate t sub) (fun ((gt : generic_table), c) -> let columns = gt.schema.columns in let rowid = Fmt.str "USING ROWID SEARCH ON TABLE %s FOR IN-OPERATOR" gt.schema.tbl_name in match List.find_index (fun (k : column) -> ident_equal k.name c) columns with | Some p when Decl.rowid_alias gt.schema = Some p -> Some rowid | Some p -> in_index_line t s layout ~loop lhs gt p | None -> if rowid_stored gt && Decl.written_rowid columns ~has_rowid:true c then Some rowid else None) (* Whether the IN of [lhs] over [sub] in [s] compares under BINARY, the only sequence sqlite3 fills a Bloom filter of the list under (expr.c, sqlite3CodeRhsOfIN): the left operand's explicit sequence, else the subquery column's, else the left column's own, else the subquery's. *) let in_binary t (s : Ast.select) layout lhs (sub : Ast.select) = let named n = Sql.Collation.of_string n in let coll = match (lhs, sub.cols) with | Ast.Collate (_, n), _ | _, { expr = Ast.Collate (_, n); _ } :: _ -> named n | _ -> ( match operand_column t s layout lhs with | Some ((g : generic_table), j) -> Decl.declared_collation g.schema.columns j | None -> Option.bind (Resolve.output_collation (Query.resolve_env (catalog t)) sub 0) named) in match coll with | None | Some (Sql.Collation.Binary | Binary_utf16le | Binary_utf16be) -> true | Some _ -> false (* The plan [s] is run through, as the trees EXPLAIN QUERY PLAN prints: a line per loop in the order the loop enters the sources, each followed by the subqueries coded at its level -- the one a seek takes its key from, then those of the conjuncts the level can test, a correlated one's last (wherecode.c, codeOneLoopStart) --, then the b-tree of a GROUP BY, the subqueries of the result columns, [extra], the b-tree of a DISTINCT and the sorter. Each subquery is the plan of its select, numbered as the parser numbers it from [first], its outer columns bound from [scope]; a select holding a window function is the co-routine of its rewrite ({!window_subquery}), numbered by [nselect], the count of the selects the statement holds and its rewrites made before (pParse->nSelect). Rendered from the same {!plan_query} the cursors are built from, so what is printed is what runs. A single-table shape a fast path answers is described by that path ({!Fast_path.explain}). The names are resolved first, so an unresolvable statement is refused rather than described. *) (* The FROM subqueries of [s], whose selects [id] numbers, and the name EXPLAIN gives each item: a FROM subquery its alias, else its number (printf.c, the %!S of a SrcItem), a table the name [alias] gives it, a VALUES list its scan, as sqlite3 prints them. *) let item_names ~alias ~id (s : Ast.select) = let subs = from_subqueries s in let sub_name i = let name (k, a, sub) = if k <> i then None else Some (Option.value a ~default: (Fmt.str "(subquery-%d)" (Option.value ~default:0 (id sub)))) in List.find_map name subs in let named = (match s.Sql.Ast.from with | Ast.Table tr -> `Table (alias tr) | Ast.Select { fs_select; _ } -> `Other (Option.value (sub_name 0) ~default:(Option.value ~default:"" (values_clause fs_select))) | Ast.Values rows -> `Other (values_line rows) | Ast.Unit -> `Other "CONSTANT ROW" | Ast.Table_function { tf_name; _ } -> `Other (Fmt.str "(%s)" tf_name)) :: List.mapi (fun k (j : Ast.join) -> `Table (Option.value (sub_name (k + 1)) ~default:(alias j.Sql.Ast.table))) s.joins in (subs, sub_name, named) (* The ORDER BY a merge under [op] sorts each arm by: [order], else the first column, which any operator but UNION ALL extends with every other of the [ncols] result columns (select.c, multiSelectByMerge). *) let merge_order ~ncols op order = let order = Option.value order ~default:[ (0, Ast.Asc) ] in let missing i = not (List.exists (fun (j, _) -> j = i) order) in if op = Ast.Union_all then order else order @ List.map (fun i -> (i, Ast.Asc)) (List.filter missing (List.init ncols Fun.id)) (* The plan of the arms [left] of a compound, with [next] after them: in the COMPOUND QUERY block [left] ends with where it is [open_], else beside it. *) let after_arms (left, open_) next = match (open_, List.rev left) with | true, (last : Eqp.t) :: before -> ( List.rev ({ last with children = last.children @ [ next ] } :: before), true ) | _ -> (left @ [ next ], false) (* The subquery sqlite3 moves the select [s] holding a window function into, and whether [s] keeps its ORDER BY (window.c, sqlite3WindowRewrite). The windows of the first one's definition are computed by [s]; the subquery holds the FROM, WHERE, GROUP BY and HAVING of [s] over every column, aggregate and other window its result columns and ORDER BY read, and the arguments of those windows, sorted by the PARTITION BY and ORDER BY of the definition, an integer read as NULL (exprListAppendList). An ORDER BY term equal to a result column is a copy of it (resolve.c, resolveOrderGroupBy) whose windows are linked to no definition (sqlite3WindowLink), so the subquery computes them. [s] drops an ORDER BY that is a prefix of the sort. [None] where [s] holds no window. *) let window_subquery (s : Ast.select) = let copy e = List.exists (fun (rc : Ast.result_col) -> Ast.equal_expr e rc.expr) s.Sql.Ast.cols in let in_place = s.cols @ List.filter_map (fun (e, _) : Ast.result_col option -> if copy e then None else Some { expr = e; alias = None }) s.order_by in match Query.window_exprs in_place with | Ast.Window (_, first) :: _ -> let same (w : Ast.window) = Ast.equal_expr (Ast.Window (Star, w)) (Ast.Window (Star, first)) in let rec args = function | Ast.Func (_, a) -> a | Distinct_agg (_, a) -> [ a ] | Filter (f, p) -> args f @ [ p ] | Ordered_agg (f, keys) -> args f @ List.map fst keys | e -> [ e ] in let acc = ref [] in let add e = if not (List.exists (Ast.equal_expr e) !acc) then acc := e :: !acc in let rec read ~linked e = match e with | Ast.Window (f, w) when linked && same w -> List.iter (read ~linked) (args f) | Ast.Window _ | Col _ -> add e | e when Query.is_agg_expr e -> add e | e -> Ast.fold_expr ~select:(fun () _ -> ()) (fun () x -> read ~linked x) () e in List.iter (fun (rc : Ast.result_col) -> read ~linked:true rc.expr) s.cols; List.iter (fun (e, _) -> read ~linked:(not (copy e)) e) s.order_by; let null = function | Ast.Lit (Ast.Int _) -> Ast.Lit Ast.Null | e -> e in let sort = List.map (fun e -> (null e, Ast.Asc)) first.partition @ List.map (fun (e, d) -> (null e, d)) first.order in List.iter (fun (e, _) -> add e) sort; let cols = match List.rev !acc with [] -> [ Ast.Lit (Ast.Int 0L) ] | l -> l in let n = List.length s.order_by in let prefix = n > 0 && n <= List.length sort && List.for_all2 (fun (a, d) (b, d') -> d = d' && Ast.equal_expr a b) s.order_by (List.filteri (fun i _ -> i < n) sort) in Some ( { s with cols = List.map (fun e -> { Ast.expr = e; alias = None }) cols; distinct = false; order_by = sort; limit = None; offset = None; }, s.order_by <> [] && not prefix ) | _ -> None let seek_subqueries plan layout i = match List.nth_opt plan.Plan.accesses i with | Some (Plan.Seek { keys; _ }) -> let source = fst (List.nth layout i) in List.filter_map (function | { Plan.column = c; value = Plan.In_select sub; _ } -> Some (Eqp.List (Ast.Col (Some source, c)), sub) | { Plan.value = Plan.Const (Ast.Scalar_select sub); _ } -> Some (Eqp.Scalar, sub) | _ -> None) keys | _ -> [] let subquery_in_other_source conjuncts layout i sub = List.exists (fun (e, _) -> match e with | Ast.In_select ((Ast.Col (q, c) | Ast.Collate (Ast.Col (q, c), _)), s') when s' == sub -> ( match Plan.position layout q c with | Some (k, _) -> k <> i | None -> false) | _ -> false) conjuncts let visible_loops (s : Ast.select) loops = match (s.Sql.Ast.from, s.joins) with | Ast.Unit, _ :: _ -> List.filter (fun (i, _) -> i <> 0) loops | _ -> loops let rec explain_tree ?(extra = []) ~scope ~first ~nselect t (s : Ast.select) = match s.Sql.Ast.compound with | _ :: _ -> ( match compound_tree ~scope ~first ~nselect t s with | Some nodes -> nodes | None -> select_tree ~extra ~scope ~first ~nselect t s) | [] -> select_tree ~extra ~scope ~first ~nselect t s (* The plan of the compound [s] as multiSelect codes it (select.c): with an ORDER BY, or under any operator but UNION ALL, a MERGE of its last arm with the compound of the arms before it, each sorted by the ORDER BY, which an operator other than UNION ALL extends with every other result column (multiSelectByMerge); else the arms one after the other under COMPOUND QUERY, the first as its LEFT-MOST SUBQUERY and each next under UNION ALL, a UNION under a LIMIT of 1 and no OFFSET included. [None] where an ORDER BY term names no result column. *) and compound_tree ~scope ~first ~nselect t (s : Ast.select) = let env = Query.resolve_env (catalog t) in let lead = { s with compound = []; order_by = []; limit = None; offset = None } in let arms = Array.of_list (lead :: List.map snd s.Sql.Ast.compound) in let ops = Array.of_list (List.map fst s.compound) in let n = Array.length arms - 1 in let names = Resolve.select_columns env lead in let outputs = Resolve.output_exprs env lead in let ncols = List.length names in let column e = match e with | Ast.Lit (Ast.Int k) when k >= 1L && Int64.to_int k <= ncols -> Some (Int64.to_int k - 1) | Ast.Col (None, c) when Catalog.Ident.index c names <> None -> Catalog.Ident.index c names | e -> List.find_index (Ast.equal_expr e) outputs in let explicit = List.map (fun (e, d) -> Option.map (fun i -> (i, d)) (column e)) s.order_by in if List.exists Option.is_none explicit then None else let explicit = List.filter_map Fun.id explicit in let collations = Resolve.compound_collations env s ncols in let parsed = Eqp.ids ~first s in let id k = if k = 0 then first + Eqp.count lead else Option.value ~default:0 (parsed arms.(k)) in let plan k order = let arm = { (arms.(k)) with ctes = s.ctes } in let exprs = Resolve.output_exprs env arm in let key (i, d) = let e = List.nth exprs i in let e = match List.nth collations i with | Some c when not (Option.fold ~none:false ~some:Sql.Collation.is_binary (Sql.Collation.of_string c)) -> Ast.Collate (e, c) | _ -> e in (e, d) in let arm = { arm with order_by = List.map key order } in try explain_tree ~scope ~first:(id k - Eqp.count arm) ~nselect t arm with Catalog.Error _ -> [] in let limit_one = s.order_by = [] && s.offset = None && (match s.limit with | Some (Ast.Lit (Ast.Int 1L)) -> true | _ -> false) && ops.(n - 1) = Ast.Union in let node line children = { Eqp.line; children } in let rec chain k order = if k = 0 then (plan 0 (Option.value order ~default:[]), false) else let op = ops.(k - 1) in if order <> None || (op <> Ast.Union_all && not (k = n && limit_one)) then let order = merge_order ~ncols op order in let left, _ = chain (k - 1) (Some order) in ( [ node (Fmt.str "MERGE (%s)" (Ast.set_op_keyword op)) [ node "LEFT" left; node "RIGHT" (plan k order) ]; ], false ) else let next = node "UNION ALL" (plan k []) in if k = 1 then ( [ node "COMPOUND QUERY" [ node "LEFT-MOST SUBQUERY" (plan 0 []); next ]; ], true ) else after_arms (chain (k - 1) None) next in Some (fst (chain n (match explicit with [] -> None | order -> Some order))) (* The blocks sqlite3 codes before the loops of [s], whose FROM subqueries are [subs], named by [sub_name], and whose selects [id] numbers: each FROM subquery and each WITH table read as a FROM item and not merged, as a co-routine where the loop over it can drive it, else materialised (select.c, fromClauseTermCanBeCoroutine), in FROM order; and the WITH tables the statement reads once, which a subquery of [s] reads as its own. *) and coded_blocks t ~scope ~nselect ~id ~sub_name ~subs (s : Ast.select) = let joins = Array.of_list s.Sql.Ast.joins in let outer i = i > 0 && match joins.(i - 1).Sql.Ast.type_ with | Ast.Left | Right | Full -> true | Inner | Cross | Semi _ -> false in (* the WITH tables of [s] read as FROM items, each with its place and the name it is read under, and how often the statement reads each: sqlite3 materialises one read twice and codes it once (select.c, fromClauseTermCanBeCoroutine (2); the CteUse of sqlite3WithAdd) *) let cte_uses name = let n = ref 0 in Resolve.walk_select ~table:(fun () (tr : Ast.table_ref) -> if tr.subquery = None && Catalog.Ident.equal tr.name name then incr n) ~col:(fun () _ _ -> ()) ~nest:(fun () _ -> ()) ~cte:(fun () _ -> Some ()) () s; !n in let cte_items = List.filter_map (fun (i, (tr : Ast.table_ref option)) -> match tr with | Some ({ subquery = None; _ } as tr) -> Option.map (fun c -> (i, tr, c)) (List.find_opt (fun (c : Ast.cte) -> Catalog.Ident.equal c.name tr.name) s.Sql.Ast.ctes) | Some _ | None -> None) (List.mapi (fun i r -> (i, r)) ((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 let coded k = List.exists (fun (k', _, _) -> k' = k) subs || List.exists (fun (k', _, _) -> k' = k) cte_items in let coroutine i = (not (Array.exists (fun (j : Ast.join) -> match j.type_ with Ast.Right | Full -> true | _ -> false) joins)) && List.for_all (fun k -> (not (outer k)) && (k = i || not (coded k))) (List.init (i + 1) Fun.id) in (* a WITH table read once in the statement is read by a subquery of [s] as its own; one read twice is materialised where [s] reads it *) let ctes_once = List.filter (fun (c : Ast.cte) -> cte_uses c.name = 1) s.Sql.Ast.ctes in let block i name ~first sub ~materialized = ( i, { Eqp.line = (if (not materialized) && coroutine i then "CO-ROUTINE " else "MATERIALIZE ") ^ name; children = (try explain_tree ~scope ~first ~nselect t sub with Catalog.Error _ -> []); } ) in let sub_blocks = List.map (fun (i, _, sub) -> let n = Option.value ~default:0 (id sub) in let first, sub = with_outer_ctes ctes_once ~first:(n - Eqp.count sub) sub in block i (Option.get (sub_name i)) ~first sub ~materialized:false) subs in let cte_blocks = List.rev (snd (List.fold_left (fun (seen, acc) (i, (tr : Ast.table_ref), (c : Ast.cte)) -> if List.exists (Catalog.Ident.equal c.name) seen then (seen, acc) else let earlier = List.filter (fun (c' : Ast.cte) -> not (c' == c)) s.Sql.Ast.ctes in let n = Option.value ~default:0 (id c.query) in let first, body = with_outer_ctes earlier ~first:(n - Eqp.count c.query) c.query in let materialized = c.materialized = Ast.Materialized || cte_uses c.name >= 2 && c.materialized <> Ast.Not_materialized in (* a WITH table is named by its own name (the %!S of its SrcItem, which skips the alias), and the VALUES list of a statement with a WITH is a compound of its rows (sqlite3MultiValues) *) let i, b = block i tr.name ~first body ~materialized in let b = match body with | { from = Ast.Values (_ :: _ :: _ as rows); _ } when values_clause body <> None -> { b with Eqp.children = [ Fmt.kstr Eqp.leaf "SCAN %d CONSTANT ROWS" (List.length rows); ]; } | _ -> b in (c.name :: seen, (i, b) :: acc)) ([], []) cte_items)) in let from_blocks = List.map snd (List.stable_sort (fun (i, _) (j, _) -> compare i j) (sub_blocks @ cte_blocks)) in (from_blocks, ctes_once) (* [prepared] holds the numbering and the names of [s] where [s] is the subquery of a window rewrite, already resolved as its select was; else [s] is resolved, and its selects numbered as [number] of it holds them, where the parser read them in another order than [s] holds them. *) and select_tree ?(extra = []) ?prepared ?(number = Fun.id) ~scope ~first ~nselect t (s : Ast.select) = let cat = catalog t in let env = Query.resolve_env cat in let s, parsed, alias = match prepared with | Some (parsed, alias) -> (Query.flatten_ctes cat s, parsed, alias) | None -> let alias = explain_name s in (* Flatten first: a single-use CTE is described by the scan it flattens to, not by a relation the engine no longer builds. *) let s = Query.flatten_ctes cat (Query.table_arguments cat [||] s) in let s = Resolve.reduce_outer_joins env (Resolve.where_aliases env (Resolve.collations env (Resolve.ordinals env s))) in (* sqlite3 numbers the selects as it parses them, an EXISTS it then joins among them *) (s, Eqp.ids ~first (number s), alias) in let moved = ref [] in let window = window_subquery s in let s = Query.flatten_subqueries ~moved:(fun q q' -> moved := (q, q') :: !moved) cat s in let bound = List.map (fun (c : Ast.cte) -> c.Sql.Ast.name) s.Sql.Ast.ctes in let s = Query.exists_to_join ~moved:(fun q q' -> moved := (q, q') :: !moved) ~table:(stored_table t ~bound) env s in let id sub = match parsed sub with | Some _ as n -> n | None -> Option.bind (List.assq_opt sub !moved) parsed in let layout = explain_layout t s in Resolve.check_columns layout s; let subs, sub_name, named = item_names ~alias ~id s in let from_blocks, ctes_once = coded_blocks t ~scope ~nselect ~id ~sub_name ~subs s in (* the enclosing rows of a subquery of [s]: its sources, then [s]'s own enclosing ones, each column NULL as no row is read yet *) let inner_scope = List.map (fun (a, cols) -> ( a, List.filter_map (fun c -> if String.equal c Resolve.rowid_sentinel then None else Some (c, Ast.Null)) cols )) layout @ scope in (* each column of [layout] a correlated subquery reads states its affinity, as the lowering registers it ({!Lower.query}) *) let outer = let affinity = Plan.column_affinity ~affinity:cat.Query.affinity env s layout in Resolve.enclosing_affinity env layout ~affinity in let block ~loop (kind, sub) = subquery_block t ~nselect ~scope:inner_scope ~outer ~ctes:ctes_once ~id ~loop ~in_line:(fun lhs -> in_operator_line t s layout ~loop lhs sub) ~binary:(fun lhs -> in_binary t s layout lhs sub) (kind, sub) in let blocks ~loop e = List.map (block ~loop) (Eqp.subqueries e) in let results () = List.concat_map (fun (rc : Ast.result_col) -> blocks ~loop:false rc.expr) s.cols in (* a HAVING is tested as each group is output, before its result columns are computed (select.c, the HAVING jump ahead of selectInnerLoop) *) let having () = Option.fold ~none:[] ~some:(blocks ~loop:false) s.Sql.Ast.having in let window_tree sub ordered = (* the subquery runs as a co-routine numbered after every select the statement holds and those made before it, which [s] scans; [s] sorts its rows for a DISTINCT, then for an ORDER BY the subquery leaves unsorted *) incr nselect; let name = Fmt.str "(subquery-%d)" !nselect in { Eqp.line = "CO-ROUTINE " ^ name; children = select_tree ~prepared:(parsed, alias) ~scope ~first ~nselect t sub; } :: Eqp.leaf ("SCAN " ^ name) :: results () @ (if s.distinct then [ Eqp.leaf "USE TEMP B-TREE FOR DISTINCT" ] else []) @ extra @ if ordered then [ Eqp.leaf "USE TEMP B-TREE FOR ORDER BY" ] else [] in let fast_tree fp = let name = match s.Sql.Ast.from with Ast.Table tr -> alias tr | _ -> "" in from_blocks @ distinct_lines t s ~plan:None @ (Eqp.leaf (Fast_path.explain ~name fp) :: results ()) @ extra @ List.map Eqp.leaf (Plan.sort_lines (R.fast_sort t s fp)) in let planned_tree () = let plan = plan_query t ~bound (reads t s layout) s layout in let joins = List.map (fun (j : Ast.join) -> j.Sql.Ast.type_) s.Sql.Ast.joins in let loops = Plan.explain_loops plan ~names:named ~joins in (* the constant row of a select with no FROM is no loop once it joins an EXISTS's table ({!Plan.v}) *) let loops = visible_loops s loops in let place i = Option.value ~default:0 (List.find_index (fun (k, _) -> k = i) loops) in (* the subqueries the seek of each source takes a key from *) let key_subs = seek_subqueries plan layout in (* the blocks of the subqueries the seek of source [i] keys on: an IN it reaches through an equivalence, on a column of another source, runs the list again where its own column's loop tests it, which sqlite3 prints as a reuse of the list after it *) let conjuncts = join_conjuncts s layout in let elsewhere = subquery_in_other_source conjuncts layout in let key_blocks i = List.concat_map (fun (kind, sub) -> let b = block ~loop:true (kind, sub) in match kind with | Eqp.List _ when elsewhere i sub -> [ b; Fmt.kstr Eqp.leaf "REUSE LIST SUBQUERY %d" (Option.value ~default:0 (id sub)); ] | Eqp.List _ | Eqp.Scalar | Eqp.Exists -> [ b ]) (key_subs i) in let keyed = List.concat_map (fun (i, _) -> List.map snd (key_subs i)) loops in (* each conjunct holding a subquery no seek keys on, with the level whose loop tests it: the innermost source it reads, a LEFT JOIN's ON at least its own *) let tested = List.filter_map (fun (e, on) -> match List.filter (fun (_, sub) -> not (List.memq sub keyed)) (Eqp.subqueries e) with | [] -> None | subs -> let reads = outer_reads env layout e @ match on with `On j | `Inner_on j -> [ j ] | `Where -> [] in let level = List.fold_left (fun m i -> max m (place i)) 0 reads in let correlated = List.exists (fun (_, sub) -> Resolve.correlated env [] sub) subs in Some (level, correlated, subs)) conjuncts in let level_blocks n = let at c = List.concat_map (fun (l, corr, subs) -> if l = n && corr = c then List.map (block ~loop:false) subs else []) tested in at false @ at true in let converted = s.distinct && s.group_by = [] && s.order_by <> [] && List.length s.order_by = List.length (result_exprs s layout) && List.for_all2 (fun e (o, _) -> Ast.equal_expr e o) (result_exprs s layout) s.order_by in let temp = Option.map Eqp.leaf (Plan.temp_line plan) in let early, late = match plan.Plan.grouping with | Some (`Temp `Group_by) -> (temp, None) | Some (`Temp `Distinct) when converted -> (temp, None) | _ -> (None, temp) in let accumulators = distinct_lines t s ~plan:(Some plan) in (* the loop over the rows each RIGHT or FULL join kept unmatched, under the name of its table, once the loop is done: after what the loop codes, the rows of an aggregate after it (where.c, sqlite3WhereRightJoinLoop) *) let right_joins = List.map (fun (i, lines) -> let table = if i = 0 then match s.Sql.Ast.from with | Ast.Table tr -> tr.Sql.Ast.name | _ -> fst (List.nth layout i) else (List.nth s.joins (i - 1)).Sql.Ast.table.Sql.Ast.name in { Eqp.line = "RIGHT-JOIN " ^ table; children = List.map Eqp.leaf lines; }) (Plan.explain_unmatched plan ~names:named ~joins) in let aggregate = Query.is_aggregate_query s in from_blocks @ (if s.group_by = [] then accumulators else []) @ List.concat (List.mapi (fun n (i, lines) -> List.map Eqp.leaf lines @ key_blocks i @ level_blocks n) loops) @ Option.to_list early @ (if aggregate then right_joins else []) @ having () @ results () @ (if aggregate then [] else right_joins) @ (if s.group_by = [] then [] else accumulators) @ extra @ Option.to_list late @ List.map Eqp.leaf (Plan.sort_lines plan.Plan.sort) in match window with | Some (sub, ordered) -> window_tree sub ordered | None -> ( (* No parameters: EXPLAIN answers before any value is bound, so a path whose recognition needs one is not one this can claim. *) match R.fast_of_select t s [||] with | Some fp -> fast_tree fp | None -> planned_tree ()) (* The block of the subquery [sub], of [kind], under the select whose subqueries [id] numbers, tested for membership or, where [loop], looped over as a seek's keys: [LIST SUBQUERY n] or [SCALAR SUBQUERY n], marked [CORRELATED] where it reads its enclosing rows, over the plan of its select -- a scalar one's under a LIMIT of one, a membership's list followed by the Bloom filter sqlite3 builds of its rows where it keeps no sorter and [binary] of its left operand says it compares under BINARY (select.c, SRT_Set) -- or the one line [in_line] gives where the IN reads an existing b-tree instead (expr.c, sqlite3CodeRhsOfIN, sqlite3CodeSubselect). *) and subquery_block t ~nselect ~scope ~outer ~ctes ~id ~loop ~in_line ~binary (kind, sub) = let env = Query.resolve_env (catalog t) in let n = Option.value ~default:0 (id sub) in let first, sub = with_outer_ctes ctes ~first:(n - Eqp.count sub) sub in let correlated = Resolve.correlated env [] sub in let body = match kind with | Eqp.List _ -> sub | Eqp.Scalar -> limited_to_one sub | Eqp.Exists -> limited_to_one (Query.exists_body sub) in let body = if not correlated then body else match Resolve.bind_scope env scope (outer body) ~params:[||] with | u, _ -> u | exception Catalog.Error _ -> body in let tree ?extra () = match explain_tree ?extra ~scope ~first ~nselect t body with | nodes -> nodes | exception Catalog.Error _ -> [] in let prefix = if correlated then "CORRELATED " else "" in match kind with | Eqp.List lhs -> ( match if correlated then None else in_line lhs with | Some line -> Eqp.leaf line | None -> let bloom = not (loop || correlated || not (binary lhs)) in { Eqp.line = Fmt.str "%sLIST SUBQUERY %d" prefix n; children = list_children ~bloom tree; }) | Eqp.Scalar | Eqp.Exists -> { Eqp.line = Fmt.str "%sSCALAR SUBQUERY %d" prefix n; children = tree (); } (* The plan of an IN's list, [tree] of the lines to place before its DISTINCT and its sorter, the Bloom filter sqlite3 fills of its rows where [bloom] and no sorter keeps them (select.c, SRT_Set). *) and list_children ~bloom tree = if not bloom then tree () else let filter = "CREATE BLOOM FILTER" in let nodes = tree ~extra:[ Eqp.leaf filter ] () in let sorts (e : Eqp.t) = String.starts_with ~prefix:"USE TEMP B-TREE FOR ORDER BY" e.line || String.starts_with ~prefix:"USE TEMP B-TREE FOR LAST" e.line in if List.exists sorts nodes then List.filter (fun (e : Eqp.t) -> e.line <> filter) nodes else nodes (* The plan of [s] as EXPLAIN QUERY PLAN prints it, each subquery's plan nested under its line ({!explain_tree}). *) let explain_nodes t (s : Ast.select) = explain_tree ~scope:[] ~first:1 ~nselect:(ref (1 + Eqp.count s)) t s (* The access path [s] is run through, one line per loop, sorter and subquery, a subquery's own plan indented under its line. *) let explain_select t (s : Ast.select) = String.concat "\n" (Eqp.indented (explain_nodes t s)) (* [EXPLAIN QUERY PLAN]'s output, as the sqlite3 shell prints it: the header line, then the plan's tree ({!Eqp.render}). The bare [EXPLAIN] is refused: sqlite3 prints its VDBE program, and this engine's register VM is a different machine, so a listing under that verb invites a diff between two programs that were never the same. *) let plan_rows nodes = [ Ast.Text "QUERY PLAN" ] :: List.map (fun l -> [ Ast.Text l ]) (Eqp.render nodes) (* The loop an UPDATE or a DELETE finds its rows by, as the SELECT of them it is planned as: the WHERE over the target, then an UPDATE's FROM joined after it (where.c, sqlite3WhereBegin from update.c and delete.c). Every column is read, as the row's rewrite or removal reads it. *) let dml_loop ~ctes ~table ~alias ~from where = let star = [ { Ast.expr = Star; alias = None } ] in let join (tr : Ast.table_ref) : Ast.join = { table = tr; on = None; type_ = Inner; natural = false; using = [] } in let source : Ast.from_clause -> Ast.table_ref = function | Table tr -> tr | Select { fs_select; fs_alias } -> { name = Option.value fs_alias ~default:""; schema = None; alias = fs_alias; subquery = Some fs_select; } | f -> { name = ""; schema = None; alias = None; subquery = Some { (Lower.post_select star) with from = f }; } in let joins = match from with None -> [] | Some (f, js) -> join (source f) :: js in { (Lower.post_select star) with ctes; from = Table { name = table; schema = None; alias; subquery = None }; joins; where; } (* The values of the SET of [u] in the order update.c codes them: the new rowid's first, then each other column's in the table's column order, the last assignment of a column alone (sqlite3Update, pRowidExpr and aXRef); an UPDATE ... FROM codes each as written, the result columns of the select it runs (updateFromSelect). *) let set_values t (u : Ast.update) = match (u.from, R.plain_rowid_gtable t u.table) with | Some _, _ -> List.map snd u.sets | None, gt -> let columns = R.column_names t u.table in let alias = Option.bind gt (fun (gt : Model.generic_table) -> Option.map (List.nth columns) (Decl.rowid_alias gt.schema)) in let last p = List.find_map (fun (c, e) -> if p c then Some e else None) (List.rev u.sets) in let rowid c = gt <> None && (Sql.Ast.is_rowid_name c && not (List.exists (ident_equal c) columns) || Option.fold ~none:false ~some:(ident_equal c) alias) in Option.to_list (last rowid) @ List.filter_map (fun c -> if rowid c then None else last (ident_equal c)) columns let explain_rows t (e : Ast.explain) = if not e.query_plan then Catalog.Error.fail_prepare "EXPLAIN: this engine runs a register VM of its own, whose program is \ not sqlite3's VDBE listing; use EXPLAIN QUERY PLAN"; match e.explained with | Ast.Select s -> plan_rows (explain_nodes t s) | Ast.Update u -> (* the SET values are coded as the loop's result columns, after its WHERE, and numbered as written, before it; the foreign keys' loops follow the target's (fkey.c, sqlite3FkCheck) *) let changed = Some (List.map fst u.sets) in let loop = dml_loop ~ctes:u.ctes ~table:u.table ~alias:u.alias ~from:u.from u.where in let coded = set_values t u in let col e = { Ast.expr = e; alias = None } in let written values = List.map (fun (_, e) -> match List.find_index (fun c -> c == e) coded with | Some k -> List.nth values k | None -> col e) u.sets in let number (s : Ast.select) = match s.cols with | star :: values -> { s with cols = star :: written values } | [] -> s in let s = { loop with cols = loop.cols @ List.map col coded } in plan_rows (select_tree ~number ~scope:[] ~first:1 ~nselect:(ref (Eqp.count (number s))) t s @ List.map Eqp.leaf (R.foreign_key_plan t u.table ~changed)) (* A table cleared whole is no loop, and sqlite3 prints no plan. *) | Ast.Delete { where = None; returning = []; table; _ } when R.clears t table -> [] | Ast.Delete d -> let s = dml_loop ~ctes:d.ctes ~table:d.table ~alias:d.alias ~from:None d.where in plan_rows (select_tree ~scope:[] ~first:1 ~nselect:(ref (Eqp.count s)) t s @ List.map Eqp.leaf (R.foreign_key_plan t d.table ~changed:None)) | _ -> Catalog.Error.fail_prepare "EXPLAIN QUERY PLAN: expected a SELECT, an UPDATE or a DELETE" end