(*--------------------------------------------------------------------------- Copyright (c) 2026 Thomas Gazagnaire. All rights reserved. SPDX-License-Identifier: ISC ---------------------------------------------------------------------------*) type layout = (string * string list) list type key_source = | Const of Ast.expr | Outer of int * int | In_list of Ast.expr list | In_select of Ast.select type affinity = [ `Blob | `Integer | `Numeric | `Real | `Text ] type key = { column : string; value : key_source; affinity : affinity list; nulls : bool; answers : Ast.expr option; } type path = { descr : string; unique : bool; bound : int; rows_per_key : int option; covering : bool; index : string option; rowid_order : bool; } type access = | Scan | Ordered of { table : string; index : string option; covering : bool; reverse : bool; } | Seek of { table : string; path : path; keys : key list; range : range option; reverse : bool; } | Probe of { key : int; outer : (int * int) option; coll : Collation.t option; nulls : bool; rest : (int * int * int * Collation.t option) list; spill : access option; filter : (string * Ast.expr) option; auto : auto option; stands_for : access option; } and auto = { columns : string list; partial : bool; bloom : bool } and range = { lo : bound option; hi : bound option } and bound = { value : key_source; inclusive : bool; affinity : affinity list; answers : Ast.expr option; } type facts = { columns : string -> string list; seekable : Ast.table_ref -> string option; best_index : string -> (string * key_source) list -> path option; affinity : string -> string -> affinity option; collation : string -> string -> string option; row_count : string -> upto:int -> int; seek_answers_rowid : bool; const_subquery : bool; seek_lists : bool; ordered : string -> Ast.select -> access -> access * sort option * min_max option; join : Ast.select -> layout -> t option; } and sort = { terms : int; sorted : int } and min_max = Every_row | First_row and t = { accesses : access list; order : int list; sort : sort option; min_max : min_max option; grouping : [ `Loop | `Temp of [ `Group_by | `Distinct ] ] option; unmatched : (int * access) list; } let ident_equal = Ast.ident_equal (* Reading the query *) (* Every position of [layout] a reference to [col] under [qual] could name: a qualifier restricts the search to the source it names, a bare name to every source but a table joined from an EXISTS, and each is asked for a column of that name. [f i j] is called on each, in scan order; a reference costs no allocation, since every column reference of a statement asks it. The position of [col] among [cols] from [k] is -1 where there is none: an option would be that allocation. *) let rec column_index col k = function | [] -> -1 | c :: rest -> if ident_equal c col then k else column_index col (k + 1) rest let rec iter_positions_from layout qual col f i = match layout with | [] -> () | (alias, cols) :: rest -> (match qual with | Some q when not (ident_equal alias q) -> () | None when Resolve.is_semi_alias alias -> () | Some _ | None -> let j = column_index col 0 cols in if j >= 0 then f i j); iter_positions_from rest qual col f (i + 1) let iter_positions (layout : layout) qual col f = iter_positions_from layout qual col f 0 (* The one position of [layout] a reference names: [`One (i, j)], or [`None] or [`Several] where it names none or more than one. *) let rec unique_from layout qual col i found = match layout with | [] -> found | (alias, cols) :: rest -> ( let here = match qual with | Some q when not (ident_equal alias q) -> None | None when Resolve.is_semi_alias alias -> None | Some _ | None -> Catalog.Ident.index col cols in match (here, found) with | None, _ -> unique_from rest qual col (i + 1) found | Some j, `None -> unique_from rest qual col (i + 1) (`One (i, j)) | Some _, (`One _ | `Several) -> `Several) (* The scan position a column reference names, or [None] when it names no single one. A qualifier picks its source outright; a bare name is resolved against every source's columns and accepted only when exactly one has it, since resolving it against the wrong frame would silently drop rows. *) let column_position (layout : layout) qual col = match unique_from layout qual col 0 `None with | `One p -> Some p | `None | `Several -> None (* [column_position] for a seek key: a name no source declares that spells the rowid reaches the hidden rowid slot, as {!read_columns} charges it, so the rowid is sought under any of its spellings. *) let key_position (layout : layout) qual col = match unique_from layout qual col 0 `None with | `One p -> Some p | `None when Ast.is_rowid_name col -> column_position layout qual Resolve.rowid_sentinel | `None | `Several -> None (* What a query reads from each source. Charged from every position a reference could name rather than the one it does: this decides whether a cursor can be answered out of an index, so a reference nothing here can attribute has to be assumed of each source that could answer it. *) (* The names the FROM of the nested select [u] binds: each named table's alias with the columns [columns] gives it, a derived table's alias with none it can tell. *) let nested_scope ~columns (u : Ast.select) = let refs = (match u.Ast.from with | Ast.Table tr -> [ tr ] | Ast.Select _ | Ast.Values _ | Ast.Unit | Ast.Table_function _ -> []) @ List.map (fun (j : Ast.join) -> j.Ast.table) u.Ast.joins in List.map (fun (tr : Ast.table_ref) -> ( Option.value tr.Ast.alias ~default:tr.Ast.name, if tr.Ast.subquery = None then columns tr.Ast.name else [] )) refs (* Whether a nested select's FROM in [scopes] binds [qual.name] before the sources of [layout] do: sqlite3 resolves a name in the innermost select that has it (resolve.c, lookupName). *) let rec scope_binds qual name = function | [] -> false | (alias, cols) :: rest -> (match qual with | Some q -> ident_equal alias q | None -> column_index name 0 cols >= 0 || (cols <> [] && Ast.is_rowid_name name)) || scope_binds qual name rest let rec bound_inside scopes qual name = match scopes with | [] -> false | scope :: rest -> scope_binds qual name scope || bound_inside rest qual name let rec mem_int (j : int) = function | [] -> false | x :: rest -> x = j || mem_int j rest let read_projection_columns layout ~whole ~qualified cols = (* [*] and [t.*] name no column, so the walk does not report them; they are read off the projection [cols] instead. A nested select's star reads the sources of its own [FROM], none of which is in [layout], and a [*] standing as [count]'s argument is an argument, not a result column: neither reads anything here. *) List.iter (fun (rc : Ast.result_col) -> match rc.Ast.expr with | Ast.Star -> List.iteri (fun i (a, _) -> if not (Resolve.is_semi_alias a) then whole i) layout | Ast.Qualified_star q -> qualified q | _ -> ()) cols let read_columns ~columns (layout : layout) (s : Ast.select) = let n = List.length layout in let acc = Array.make n [] in let add i j = if not (mem_int j acc.(i)) then acc.(i) <- j :: acc.(i) in (* [*] never returns the hidden rowid slot, so it does not ask for it *) let whole i = List.iteri (fun j c -> if not (String.equal c Resolve.rowid_sentinel) then add i j) (snd (List.nth layout i)) in let qualified q = List.iteri (fun i (a, _) -> if ident_equal a q then whole i) layout in let found = ref false in let note i j = found := true; add i j in let col scopes qual name = if bound_inside scopes qual name then () else begin found := false; iter_positions layout qual name note; (* The declared columns are consulted first, so a real column named [rowid] shadows the implicit one -- and the hidden slot's own name cannot be written, so nothing else reaches it. *) if (not !found) && Ast.is_rowid_name name then iter_positions layout qual Resolve.rowid_sentinel add end in Resolve.walk_select ~table:(fun _ _ -> ()) ~col ~nest:(fun scopes u -> nested_scope ~columns u :: scopes) ~cte:(fun scopes _ -> Some scopes) [] s; read_projection_columns layout ~whole ~qualified s.Ast.cols; Array.map (List.sort_uniq Int.compare) acc let position = key_position (* A literal or a parameter, which a seek reads as it is, never failing to: a parameter left unbound is NULL, as sqlite3 binds it (vdbeapi.c). *) let read_as_is = function | Ast.Lit _ | Ast.Numeral _ | Ast.Unary_minus (Ast.Numeral _) | Ast.Param _ -> true | _ -> false let valued = function | Outer _ | In_select _ -> true | Const e -> read_as_is e | In_list es -> List.for_all read_as_is es (* The sequence a COLLATE on [e] names, if any. *) let sequence_of = function Ast.Collate (_, n) -> Some n | _ -> None (* The sequence of a comparison of [x] with [y]: the left operand's wins, as {!Resolve.collations} put it there. *) let left_sequence x y = match sequence_of x with Some _ as s -> s | None -> sequence_of y let seek_keys ~const ~closed (layout : layout) ~earlier i e = let mine qual col = match key_position layout qual col with | Some (k, _) when k = i -> true | _ -> false in (* a column of the source being planned, under the COLLATE the comparison put on it or not *) let column = function | (Ast.Col (q, c) | Ast.Collate (Ast.Col (q, c), _)) when mine q c -> Some c | _ -> None in (* [c] is a column of the source being planned, [other] what it is equated to; [None] when [other] is not a key this source can seek on *) let key ?(nulls = false) c other seq conj = match other with | Ast.Col (q, oc) | Ast.Collate (Ast.Col (q, oc), _) -> ( match key_position layout q oc with | Some (k, j) when earlier k -> Some (c, Outer (k, j), seq, conj, nulls) | _ -> None) | e when const e -> Some (c, Const e, seq, conj, nulls) | _ -> None in (* the key of a comparison of the column [x] alone *) let alone acc x k conj nulls = match column x with | Some c -> (c, k, sequence_of x, conj, nulls) :: acc | None -> acc in let rec go acc = function | Ast.Binary (Ast.And, a, b) -> go (go acc a) b (* an IS compares as an equality whose NULL matches NULL, and IS NULL is one with NULL (whereexpr.c, WO_IS and WO_ISNULL) *) | (Ast.Binary (Ast.Eq, x, y) | Ast.Is (x, y)) as conj -> ( let nulls = match conj with Ast.Is _ -> true | _ -> false in let seq = left_sequence x y in let keyed = function Some k -> k :: acc | None -> acc in match (column x, column y) with | Some c, _ -> keyed (key ~nulls c y seq conj) | None, Some c -> keyed (key ~nulls c x seq conj) | None, None -> acc) | Ast.Is_null x as conj -> alone acc x (Const (Ast.Lit Ast.Null)) conj true | Ast.In_list (x, values) as conj when List.for_all const values -> alone acc x (In_list values) conj false | Ast.In_select (x, sub) as conj when closed sub -> alone acc x (In_select sub) conj false | _ -> acc in go [] e (* [conjuncts acc e] is the top-level AND conjuncts of [e], last first, on [acc]. *) let rec conjuncts acc = function | Ast.Binary (Ast.And, a, b) -> conjuncts (conjuncts acc a) b | e -> e :: acc (* The equality classes the top-level AND conjuncts of [preds] sort the scan positions into, and the constant each position is directly equated to. Two positions are linked only where [comparable] holds. A class is merged one link at a time: a join names a handful of columns, so these lists stay shorter than the union-find that would replace them. *) let equality_classes (layout : layout) ~comparable preds = let const = function | (Ast.Lit _ | Ast.Numeral _ | Ast.Param _ | Ast.Named_param _) as e -> Some e | _ -> None in let pos = function | Ast.Col (q, c) -> column_position layout q c | _ -> None in let links = ref [] and consts = ref [] in let note x y = match (pos x, pos y) with | Some p, Some q -> if comparable p q then links := (p, q) :: !links | Some p, None -> ( match const y with Some v -> consts := (p, v) :: !consts | None -> ()) | None, (Some _ | None) -> () in List.iter (function | Ast.Binary (Ast.Eq, x, y) -> note x y; note y x | _ -> ()) (List.fold_left conjuncts [] preds); let merge classes (p, q) = let hit, rest = List.partition (fun cl -> List.mem p cl || List.mem q cl) classes in List.sort_uniq compare (p :: q :: List.concat hit) :: rest in (List.fold_left merge [] !links, !consts) let equality_closure (layout : layout) ~affinity preds = let comparable p q = match (affinity p, affinity q) with | Some a, Some b -> a = b | None, _ | _, None -> false in let classes, consts = equality_classes layout ~comparable preds in let column (i, j) = let alias, cols = List.nth layout i in Ast.Col (Some alias, List.nth cols j) in List.concat_map (fun cl -> (* two constants in one class contradict each other, so the query has no rows and either narrows to none of them; the first will do *) match List.find_map (fun p -> List.assoc_opt p consts) cl with | None -> [] | Some v -> List.filter_map (fun p -> if List.mem_assoc p consts then None else Some (Ast.Binary (Ast.Eq, column p, v))) cl) classes (* Every equality and IS of [e] between a column of the source at [i] and one of an earlier source, as (inner column, outer source, outer column, collation, whether an IS), in the order [e] states them. *) let probe_keys (layout : layout) ~earlier i e = let column = function | Ast.Col (q, c) -> Some (q, c, None) | Ast.Collate (Ast.Col (q, c), coll) -> Option.map (fun cl -> (q, c, Some cl)) (Collation.of_string coll) | _ -> None in let pair ~is (q1, c1, k1) (q2, c2, k2) = (* at most one operand carries a wrapper, and it names the whole comparison's sequence *) let coll = if k1 = None then k2 else k1 in match (column_position layout q1 c1, column_position layout q2 c2) with | Some (k, key), Some (src, pos) when k = i && earlier src -> Some (key, src, pos, coll, is) | _ -> None in let keys ~is x y = match (column x, column y) with | Some a, Some b -> ( match pair ~is a b with | Some k -> [ k ] | None -> Option.to_list (pair ~is b a)) | _ -> [] in let rec go = function | Ast.Binary (Ast.And, a, b) -> go a @ go b | Ast.Binary (Ast.Eq, x, y) -> keys ~is:false x y | Ast.Is (x, y) -> keys ~is:true x y | _ -> [] in go e (* The conjuncts of [preds] that read columns of the source at [i] and no other, with no subquery, no window and no call whose answer could change between two evaluations: the rows of that source a build may drop, as the joined row's WHERE would. *) let local_filter (layout : layout) i preds = let reads_here e = let ok = ref true and seen = ref false in let rec go e = match e with | Ast.Col (q, c) -> ( match key_position layout q c with | Some (k, _) when k = i -> seen := true | _ -> ok := false) | Ast.Func (n, args) when Func.deterministic n && not (Func.aggregate n ~nargs:(List.length args)) -> List.iter go args | Ast.Func _ | Ast.Window _ | Ast.Raise _ | Ast.Distinct_agg _ | Ast.Filter _ | Ast.Ordered_agg _ -> ok := false | e -> Ast.fold_expr ~select:(fun () _ -> ok := false) (fun () x -> go x) () e in go e; !ok && !seen in match List.filter reads_here (List.rev (List.fold_left conjuncts [] preds)) with | [] -> None | e :: es -> Some (List.fold_left (fun a b -> Ast.Binary (Ast.And, a, b)) e es) (* The hash on every equality [preds] offer the source at [i]: the first is the key the probe is built on, and each further one narrows its buckets. An equality stated twice is one key. An IS keys the hash where no equality does, and narrows none: the join's predicate tests it on each row. *) let probe_key ?filter layout ~earlier i preds = let keys = List.fold_left (fun acc k -> if List.mem k acc then acc else k :: acc) [] (List.concat_map (probe_keys layout ~earlier i) preds) in let is, eq = List.partition (fun (_, _, _, _, is) -> is) (List.rev keys) in match eq @ is with | [] -> None | (key, src, pos, coll, nulls) :: rest -> Some (Probe { key; outer = Some (src, pos); coll; nulls; rest = List.filter_map (fun (k, s, p, c, is) -> if is then None else Some (k, s, p, c)) rest; spill = None; filter; auto = None; stands_for = None; }) (* Whether a key compared under the sequence [seq] is one an index of a column declaring [declared] answers, either BINARY where [None]: an index orders the column under the column's own sequence, and serves a comparison only under it (where.c, whereScanNext). *) let same_sequence declared seq = let named = function | None -> Some Collation.default | Some n -> Collation.of_string n in match (named seq, named declared) with | Some a, Some b -> Collation.equal a b | _ -> false let numeric = function | `Integer | `Real | `Numeric -> true | `Text | `Blob -> false let key_affinity ~column (k : key_source) ~operand = match column with | None -> Some [] | Some (column : affinity) -> ( match (k, Value_ops.compare_affinity (Some column) operand) with (* an IN list's values take the column's affinity, as sqlite3 writes them into its ephemeral index (expr.c, sqlite3CodeRhsOfIN) *) | In_list _, _ -> Some (if column = `Blob then [] else [ column ]) (* a subquery's rows take the comparison's (sqlite3FindInIndex), which an index of any affinity answers where it converts nothing *) | In_select _, (None | Some `Blob) -> Some [] | In_select _, Some `Text -> if column = `Text then Some [ `Text ] else None | In_select _, Some (`Integer | `Real | `Numeric) -> if numeric column then Some [ `Numeric ] else None | (Const _ | Outer _), (None | Some `Blob) -> Some [] | (Const _ | Outer _), Some `Text -> if column = `Text then Some [ `Text ] else None | (Const _ | Outer _), Some (`Integer | `Real | `Numeric) -> if numeric column then Some [ column ] else None) (* sqlite3ExprAffinity of a constant key: a CAST's type, the one a key states, and none for anything else. *) let rec const_affinity = function | Ast.Cast (_, ty) -> Some (Value_ops.affinity_of_type ty) | Ast.Affinity (_, aff) -> Some aff | Ast.Collate (e, _) -> const_affinity e | _ -> None (* [keys] with the first key of each column alone: whichever case each equality spelled the column in, the predicate of a second still runs, so it only narrows further. *) let first_per_column keys = List.fold_left (fun acc (k : key) -> if List.exists (fun (a : key) -> ident_equal a.column k.column) acc then acc else acc @ [ k ]) [] keys (* [keys] answering the conjuncts they come from where the loop is a single source's and the seek reads every key whatever the parameters (wherecode.c, disableTerm), none otherwise: a join's keys answer what its planner says. *) let answering layout keys = if List.length layout = 1 && List.for_all (fun (k : key) -> valued k.value) keys then keys else List.map (fun (k : key) -> { k with answers = None }) keys (* The index seek for the source at scan position [i], from the keys [preds] offer it, or [None] when it has no table to address or no index covers the keys. Each key column is folded onto the schema's own spelling, so a backend that matches names byte for byte still finds the column the query meant. A key whose comparison the column's index cannot answer (sqlite3IndexAffinityOk) is none; each other one carries the affinity the seek applies to it ({!key_affinity}), [operand] giving the affinity of an outer column or a subquery's. *) let seek_path facts ~const ~closed ~operand layout ~earlier i (tr : Ast.table_ref option) preds = Option.bind (Option.bind tr facts.seekable) (fun table -> let declared = facts.columns table in let affinity = facts.affinity table and collation = facts.collation table in let spelled c = Option.value ~default:c (List.find_opt (ident_equal c) declared) in (* the rowid, under a name no column declares, holds integers *) let column c = match affinity c with | Some _ as a -> a | None -> if Ast.is_rowid_name c then Some `Integer else None in let key (c, k, conj, nulls) = let operand = match k with | Const e -> const_affinity e | Outer _ | In_select _ -> operand k | In_list _ -> None in Option.map (fun affinity -> { column = spelled c; value = k; affinity; nulls; answers = Some conj; }) (key_affinity ~column:(column c) k ~operand) in let keys = List.concat_map (seek_keys ~const ~closed layout ~earlier i) preds |> List.filter_map (fun (c, k, seq, conj, nulls) -> let listed = match k with | In_list _ | In_select _ -> facts.seek_lists | Const _ | Outer _ -> true in let ordered = same_sequence (collation c) seq in if listed && ordered then Some (c, k, conj, nulls) else None) |> List.filter_map key |> first_per_column |> answering layout in Option.map (fun path -> Seek { table; path; keys; range = None; reverse = false }) (facts.best_index table (List.map (fun k -> (k.column, k.value)) keys))) (* The outer kind {!Ir} names this join by, [None] for an inner one. *) let ir_kind = function | Ast.Inner | Ast.Cross | Ast.Semi _ -> None | Ast.Left -> Some Ir.Left | Ast.Right -> Some Ir.Right | Ast.Full -> Some Ir.Full let loop_order (s : Ast.select) k = if List.length s.Ast.joins <> k - 1 then List.init k Fun.id else Ir.cursor_order (List.map (fun (j : Ast.join) -> { Ir.kind = ir_kind j.Ast.type_; semi = (match j.Ast.type_ with Ast.Semi _ -> true | _ -> false); on = Ir.Always; }) s.Ast.joins) (* What each source costs *) let index_equality_rows = Join.index_equality_rows (* How far the rewinds a loop makes are tracked, past {!Join.max_rewinds}: a count beyond 100 000 rows is an estimate off a table's interior pages, so tracking further costs those pages and not the table's. *) let max_rewinds = 1 lsl 30 (* {!Join.count_bound} under {!max_rewinds}: as far as a source is counted to decide its own access, and, where a source follows, to estimate how often that one is rewound. *) let count_bound ~rewinds ~next = let decides = Join.count_bound ~rewinds ~next:false in if next then max (max_rewinds / max 1 rewinds) decides else decides (* How many keys a seek on [keys] looks up per rewind: the product of the lengths of its IN lists, a subquery's taken as 25 as sqlite3 takes it (where.c, whereLoopAddBtreeIndex), saturating at {!max_rewinds}. *) let key_count keys = List.fold_left (fun n (k : key) -> match k.value with | In_list es -> min max_rewinds (n * List.length es) | In_select _ -> min max_rewinds (n * 25) | Const _ | Outer _ -> n) 1 keys let answered = function | Seek { keys; range; _ } -> List.filter_map (fun (k : key) -> k.answers) keys @ Option.fold ~none:[] ~some:(fun r -> List.filter_map (fun b -> Option.bind b (fun (b : bound) -> b.answers)) [ r.lo; r.hi ]) range | Scan | Ordered _ | Probe _ -> [] (* The rows a source offers each time its cursor is rewound: a scan offers the whole relation, an access path offers what one key selects -- one row for a rowid or fully-bound unique index, what the backend counted where it can, sqlite3's default estimate otherwise -- for each key it looks up. *) let rewind_yield access rows = match access with | Scan | Ordered _ -> rows | Seek { path = { unique = true; _ }; keys; _ } -> min rows (key_count keys) | Seek { path = { rows_per_key = Some n; _ }; keys; _ } -> min rows (key_count keys * n) | Seek { keys; _ } -> min rows (key_count keys * index_equality_rows) | Probe _ -> min rows index_equality_rows (* How often the loop rewinds the source after [i], given [i] reads through [access] and holds [inner_rows] as far as it was counted. *) let rewinds_after ~access ~rewinds ~inner_rows = min max_rewinds (rewinds * rewind_yield access inner_rows) let source_rows facts ~upto (tr : Ast.table_ref option) = match tr with Some tr -> facts.row_count tr.Ast.name ~upto | None -> upto (* [tr] counted to [upto], first no further than [within], the bound {!Join.count_bound} sets: a source smaller than that is the count it always was, and only a table the store addresses, whose count past it is an estimate off its interior pages, is counted further. A derived source, a view and a table the store cannot seek keep the bound they had. *) let source_rows_past facts ~within ~upto tr = let n = source_rows facts ~upto:(min upto within) tr in let addressed = Option.bind tr facts.seekable <> None in if n < min upto within || upto <= within || not addressed then n else source_rows facts ~upto tr (* The access a source reads through, of the [seek] and the [hash] it is offered, for [inner_rows] read [rewinds] times. A seek with no hash to weigh it against is taken whatever the relation holds, so the relation is not counted for it. A scan offered neither is counted all the same: the count reads the table's root and first leaf before the scan reads them again, which keeps them in the page cache's hot ring for the next statement's scan ({!Btree.Pager}). *) let choose_access ~rewinds ~inner_rows seek hash = if Option.is_some seek && Option.is_none hash then Option.get seek else let inner_rows = Lazy.force inner_rows in (* what one of this seek's keys selects, which is how much of the relation it re-reads on every rewind, and whether reading one of those rows costs the relation a second look *) let seek_yield = match seek with Some a -> rewind_yield a inner_rows | None -> 1 in let covering = match seek with Some (Seek { path; _ }) -> path.covering | _ -> false in match Join.choose ~rewinds ~inner_rows ~seek_yield ~covering ~seek:(seek <> None) ~hash:(hash <> None) with | Join.Seek -> Option.get seek | Join.Hash -> ( (* the seek the ratio declined is where a build too large to hold goes, rather than back to the product *) match Option.get hash with | Probe p -> Probe { p with spill = seek } | a -> a) | Join.Scan -> Scan let probe ?constant layout ~earlier i (tr : Ast.table_ref option) preds = let filter = match tr with | Some tr -> Option.map (fun e -> (tr.Ast.name, e)) (local_filter layout i preds) | None -> None in match (probe_key ?filter layout ~earlier i preds, constant) with | None, Some key -> Some (Probe { key; outer = None; coll = None; nulls = false; rest = []; spill = None; filter; auto = None; stands_for = None; }) | probe, _ -> probe (* Counting a source reads it, so it is counted no further than an answer needs, and every answer is the one a count to [full] gives. The choice of an access reads the rows only through what a seek's key selects and the bound {!count_bound} sets for a bucket no wider than [index_equality_rows], and not where a seek has no hash to be weighed against: the first source entered, and the one source of a single-table select, is not counted for its own seek. Where a source follows, the rewinds it causes read the rows only as far as one rewind offers -- the whole relation for a scan, what one key selects for a seek. A relation past those bounds moves nothing, so the outer side of a join pinned to one key does not walk its table to be planned. *) let nested_loop facts ~const ~closed ~operand layout ~order ~keys refs = let n = List.length refs in let accesses = Array.make n Scan in let seen = Array.make n false in let earlier k = k >= 0 && k < n && seen.(k) in let last = List.nth order (List.length order - 1) in let rewinds = ref 1 in List.iter (fun i -> let tr = List.nth refs i in let preds = keys i in let seek = seek_path facts ~const ~closed ~operand layout ~earlier i tr preds in (* a hash keys on a source entered before this one, so the first one entered is offered none *) let hash = if Array.exists Fun.id seen then probe layout ~earlier i tr preds else None in let full = count_bound ~rewinds:!rewinds ~next:(i <> last) in let within = Join.count_bound ~rewinds:!rewinds ~next:(i <> last) in let decides = match seek with | None -> count_bound ~rewinds:!rewinds ~next:false | Some a -> let yield = rewind_yield a max_int in if yield <= index_equality_rows then max yield (count_bound ~rewinds:!rewinds ~next:false) else within in let inner_rows = lazy (source_rows facts ~upto:decides tr) in let a = choose_access ~rewinds:!rewinds ~inner_rows seek hash in accesses.(i) <- a; seen.(i) <- true; if i <> last then let upto = min full (rewind_yield a max_int) in let within = min within (rewind_yield a max_int) in let inner_rows = if upto > decides then source_rows_past facts ~within ~upto tr else Lazy.force inner_rows in rewinds := rewinds_after ~access:a ~rewinds:!rewinds ~inner_rows) order; Array.to_list accesses (* The plan *) (* Does [s] name the implicit rowid anywhere, under any alias? An index answers a key, not a row's identity, so a backend whose sought rows carry no rowid has to answer such a query from the relation. *) let references_rowid (s : Ast.select) = let found = ref false in let col () _ name = if Ast.is_rowid_name name then found := true in Resolve.walk_select ~table:(fun _ _ -> ()) ~col ~nest:(fun ctx _ -> ctx) ~cte:(fun ctx _ -> Some ctx) () s; !found (* The table each source of [s] addresses, in scan order, or [None] where it addresses none: a derived table, or a name the engine materialises for itself. The store does not have such a relation, and a table that happens to share its name is not it, so offering no reference leaves the source scanned and sized as the derived relation it is. *) let sources ~bound (s : Ast.select) = let source (tr : Ast.table_ref) = if tr.Ast.subquery <> None || List.exists (ident_equal tr.Ast.name) bound then None else Some tr in (match s.Ast.from with Ast.Table tr -> source tr | _ -> None) :: List.map (fun (j : Ast.join) -> source j.Ast.table) s.Ast.joins (* The select each source of [s] is a derived table of, in scan order, and [None] where the source is not one. A derived table has no schema to read, but its columns are the expressions of the select behind it, which is what sqlite3 types it from -- so this is what the affinity lookup follows. *) let derived (s : Ast.select) = let of_ref (tr : Ast.table_ref) = tr.Ast.subquery in (match s.Ast.from with | Ast.Table tr -> of_ref tr | Ast.Select { fs_select; _ } -> Some fs_select | Ast.Unit | Ast.Values _ | Ast.Table_function _ -> None) :: List.map (fun (j : Ast.join) -> of_ref j.Ast.table) s.Ast.joins (* [affinity] is applied to each table once, so a catalog that finds the table when applied to its name finds it once for every column asked. *) let column_affinity ~affinity env s (layout : layout) = let tables = List.map (Option.map (fun (tr : Ast.table_ref) -> affinity tr.Ast.name)) (sources ~bound:[] s) in let subs = derived s in fun (i, j) -> match List.nth_opt subs i with | Some (Some sub) -> Resolve.output_affinity env sub j | _ -> ( match (List.nth_opt tables i, List.nth_opt layout i) with | Some (Some of_column), Some (_, cols) -> ( match List.nth_opt cols j with (* the rowid is an integer, and a comparison reads it as one *) | Some c when String.equal c Resolve.rowid_sentinel -> Some `Integer | c -> Option.bind c of_column) | _ -> None) (* Which predicates the source at each scan position may take keys from, and the order the loop enters the cursors, for a chain of [k] sources whose trailing join is [trailing]. A RIGHT or FULL join keeps the rows of its source whatever the others hold, so the WHERE keys none of them (where.c, constraintCompatibleWithOuterJoin): a source left of it takes keys from the ON of its own join alone, and the source it keeps from none, its rows read whole, the same rows in the same order in each pass, which is what tells a row it matched from one it did not where the source has no rowid. *) let key_sets ~trailing ~k ~where ~ons = (* the ONs of the leading block, which are inner and so qualify the rows the trailing join preserves without ever padding one *) let leading_ons = List.filteri (fun i _ -> i < k - 2) ons in let forward = List.init k Fun.id in match trailing with | Ast.Inner | Ast.Cross | Ast.Semi _ -> (forward, fun _ -> where @ List.concat ons) | Ast.Left -> ( forward, fun i -> if i = k - 1 then List.nth ons (k - 2) else where @ List.concat leading_ons ) | Ast.Right | Ast.Full -> (forward, fun i -> if i = 0 || i = k - 1 then [] else List.nth ons (i - 1)) (* A closed subquery yields one value before the scan starts, which is all a lookup key has to be -- and sqlite3 plans that shape as a seek. Whether the backend can reach the value there is its own answer. So does an expression of literals and parameters through the unary and binary operators, which sqlite3 folds before it seeks ([rowid = 5 + 5] is SEARCH ... (rowid=?)), under a COLLATE too, as a correlated subquery's outer column is bound ([?1 COLLATE BINARY]); {!seek_path} keeps such a key where the index orders the column under that sequence. *) let rec const_key facts env = function | Ast.Lit _ | Ast.Numeral _ | Ast.Param _ | Ast.Named_param _ -> true | Ast.Unary_minus a | Ast.Unary_plus a | Ast.Collate (a, _) | Ast.Affinity (a, _) -> const_key facts env a | Ast.Binary (_, a, b) -> const_key facts env a && const_key facts env b | Ast.Scalar_select sub -> facts.const_subquery && not (Resolve.correlated env [] sub) | _ -> false (* The affinity of a key's value: an outer column's, or that of the column a subquery yields. *) let key_operand env ~affinity = function | Outer (k, j) -> affinity (k, j) | In_select sub -> ( match Resolve.in_select_affinity env sub with | a -> a | exception Catalog.Error _ -> None) | Const _ | In_list _ -> None let access_paths ?order facts env ~bound (s : Ast.select) (layout : layout) = let where = Option.to_list s.Ast.where in let refs = sources ~bound s in let k = List.length layout in (* a NATURAL / USING join is planned as the ON it stands for, as sqlite3 plans it (sqlite3ProcessJoin); a layout without its sources equates nothing *) let ons = List.mapi (fun p (j : Ast.join) -> if (j.Ast.natural || j.Ast.using <> []) && List.length refs = k then Option.to_list (Resolve.natural_on layout (p + 1) j) else Option.to_list j.Ast.on) s.joins in let scans = List.map (fun _ -> Scan) layout in let kinds = List.map (fun (j : Ast.join) -> j.Ast.type_) s.joins in (* the last join's kind, and whether every join before it is inner *) let trailing, leading_all_inner = match List.rev kinds with | [] -> (Ast.Inner, true) | last :: lead -> ( last, List.for_all (function Ast.Inner | Ast.Cross | Ast.Semi _ -> true | _ -> false) lead ) in let affinity = column_affinity ~affinity:facts.affinity env s layout in let const = const_key facts env in let closed sub = not (Resolve.correlated env [] sub) in let operand = key_operand env ~affinity in let facts = if facts.seek_answers_rowid || not (references_rowid s) then facts else { facts with seekable = (fun _ -> None) } in let nested ~order ~keys = let keys i = let preds = keys i in preds @ equality_closure layout ~affinity preds in nested_loop facts ~const ~closed ~operand layout ~order ~keys refs in if List.length refs <> k || not leading_all_inner then scans else let o, keys = key_sets ~trailing ~k ~where ~ons in nested ~order:(Option.value order ~default:o) ~keys (* The loop the store planned, with a hash in place of a seek where the engine's own weighing ({!choose_access}) finds one pass over the relation cheaper than a descent per rewind in that loop order. sqlite3 has no hash join, so the plan still names the seek: the hash keys the same columns and holds a key's rows in rowid order, which is the seek's order where [rowid_order] holds, so the rows and their order are the seek's. *) let hashed facts env ~bound s layout ~order accesses = let alternatives = access_paths ~order facts env ~bound s layout in let keyed i keys = let cols = snd (List.nth layout i) in let name c = String.lowercase_ascii c in let probed = List.filter_map (fun (key, src, pos) -> Option.map (fun c -> (name c, src, pos)) (List.nth_opt cols key)) in let sought = List.filter_map (function | { column = c; value = Outer (src, pos); _ } -> Some (name c, src, pos) | { value = Const _ | In_list _ | In_select _; _ } -> None) in fun (p : int * int * int * (int * int * int) list) -> let key, src, pos, rest = p in let probed = probed ((key, src, pos) :: rest) in List.length probed = List.length keys && List.sort compare probed = List.sort compare (sought keys) in if List.length alternatives <> List.length accesses then accesses else List.mapi (fun i (a, alt) -> match (a, alt) with | ( Seek { path = { rowid_order = true; _ }; range = None; keys; reverse = false; _; }, Probe ({ auto = None; outer = Some (src, pos); nulls = false; _ } as p) ) when keyed i keys ( p.key, src, pos, List.map (fun (k, s, q, _) -> (k, s, q)) p.rest ) -> Probe { p with spill = Some a; stands_for = Some a } | _ -> a) (List.combine accesses alternatives) (* Each source a RIGHT or FULL join of [s] keeps the rows of, its unmatched rows read whole. *) let unmatched_scans (s : Ast.select) = List.concat (List.mapi (fun p (j : Ast.join) -> match j.Ast.type_ with | Ast.Right | Ast.Full -> [ (p + 1, Scan) ] | Ast.Inner | Ast.Cross | Ast.Left | Ast.Semi _ -> []) s.Ast.joins) (* A single table is read the way its ORDER BY and its covering indexes make cheapest, which only the store can weigh: the access the planner chose for it is handed over, and the store answers with the access it reads through and what is left to sort, unless the store plans it itself. A join, or a table the store plans itself, is nested by the store ({!facts.join}) only when every source is a table it holds: a derived or WITH-bound relation is not one, whatever table shares its name. *) let of_sources facts env ~bound s layout = match match layout with | [] -> None | _ -> if List.for_all Option.is_some (sources ~bound s) then facts.join s layout else None with | Some p -> { p with accesses = hashed facts env ~bound s layout ~order:p.order p.accesses; } | None -> ( let accesses = access_paths facts env ~bound s layout in let order = loop_order s (List.length layout) in match (accesses, sources ~bound s) with | [ a ], [ Some tr ] -> ( match facts.seekable tr with | Some table -> let a, sort, min_max = facts.ordered table s a in { accesses = [ a ]; order; sort; min_max; grouping = None; unmatched = []; } | None -> { accesses; order; sort = None; min_max = None; grouping = None; unmatched = []; }) | _ -> { accesses; order; sort = None; min_max = None; grouping = None; unmatched = unmatched_scans s; }) (* A select with no FROM that joins an EXISTS's table is planned over the tables it joins, as sqlite3 appends that table to a FROM it leaves empty (select.c, existsToJoin): the constant row is no loop, entered first and read once. *) let v facts env ~bound (s : Ast.select) layout = match (s.from, s.joins, layout) with | Ast.Unit, ({ type_ = Semi _; _ } as j : Ast.join) :: joins, _ :: layout -> let p = of_sources facts env ~bound { s with from = Table j.table; joins } layout in { p with accesses = Scan :: p.accesses; order = 0 :: List.map succ p.order; unmatched = List.map (fun (i, a) -> (i + 1, a)) p.unmatched; } | _ -> of_sources facts env ~bound s layout let pp_key_source ppf = function | Const e -> Fmt.string ppf (Render.expr e) | Outer (i, j) -> Fmt.pf ppf "%d.%d" i j | In_list es -> Fmt.pf ppf "(%s)" (String.concat ", " (List.map Render.expr es)) | In_select s -> Fmt.pf ppf "(%s)" (Render.select s) let pp_access ppf = function | Scan -> Fmt.string ppf "scan" | Ordered { table; index; reverse; _ } -> Fmt.pf ppf "scan %s through %s%s" table (Option.value index ~default:"its own b-tree") (if reverse then " reversed" else "") | Seek { table; path; keys; reverse; _ } -> Fmt.pf ppf "seek %s using %s on %a%s" table path.descr Fmt.(list ~sep:(any ", ") (pair ~sep:(any "=") string pp_key_source)) (List.map (fun k -> (k.column, k.value)) keys) (if reverse then " reversed" else "") | Probe { key; outer; rest; _ } -> (match outer with | Some (src, pos) -> Fmt.pf ppf "probe %d on %d.%d" key src pos | None -> Fmt.pf ppf "probe %d on a constant" key); List.iter (fun (key, src, pos, _) -> Fmt.pf ppf ", %d on %d.%d" key src pos) rest let pp ppf t = Fmt.pf ppf "@[%a@,order: %a@]" Fmt.(list ~sep:cut (fun ppf (i, a) -> Fmt.pf ppf "%d: %a" i pp_access a)) (List.mapi (fun i a -> (i, a)) t.accesses) Fmt.(list ~sep:(any " ") int) t.order (* The sorter's line, as select.c words it: the whole ORDER BY, or the terms past the ones the loop yields in order. *) let sort_lines = function | Some { terms; sorted } when sorted < terms -> let what = match terms - sorted with | n when n = terms -> "ORDER BY" | 1 -> "LAST TERM OF ORDER BY" | n -> Fmt.str "LAST %d TERMS OF ORDER BY" n in [ "USE TEMP B-TREE FOR " ^ what ] | Some _ | None -> [] (* The lines the loop over source [i] through [access] prints, [scan] the word a walk of a whole relation prints. *) let loop_lines ~scan ~names ~joins i access = let keyed cols = String.concat " AND " (List.map (fun c -> c ^ "=?") cols) in let rec line what access = match (what, access) with | `Other d, _ -> "SCAN " ^ d | `Table _, Probe { stands_for = Some seek; _ } -> line what seek | `Table n, Probe { auto = Some a; _ } -> Fmt.str "SEARCH %s USING AUTOMATIC %sCOVERING INDEX (%s)" n (if a.partial then "PARTIAL " else "") (keyed a.columns) | `Table n, (Scan | Probe _) -> scan ^ n | `Table n, Ordered { index = None; _ } -> scan ^ n | `Table n, Ordered { index = Some index; covering; _ } -> Fmt.str "%s%s USING %sINDEX %s" scan n (if covering then "COVERING " else "") index | `Table n, Seek { path; _ } -> Fmt.str "SEARCH %s USING %s" n path.descr in (* a table joined from an EXISTS under the name its subquery gave it, its loop marked EXISTS (wherecode.c, sqlite3WhereExplainOneScan) *) let name, looped = match (names.(i), if i > 0 then Some joins.(i - 1) else None) with | `Table _, Some (Ast.Semi n) -> (`Table n, `Table (n ^ " EXISTS")) | what, _ -> (what, what) in let bloom = match (name, access) with | `Table n, Probe { auto = Some { bloom = true; columns; _ }; _ } -> [ Fmt.str "BLOOM FILTER ON %s (%s)" n (keyed columns) ] | _ -> [] in bloom @ [ line looped access ] let explain_loops t ~names ~joins = let joins = Array.of_list joins and names = Array.of_list names in let pads i = i > 0 && match joins.(i - 1) with Ast.Left | Full -> true | _ -> false in (* a min/max query's loop is a search, whatever it reads (wherecode.c, sqlite3WhereExplainOneScan) *) let scan = match t.min_max with None -> "SCAN " | Some _ -> "SEARCH " in let accesses = Array.of_list t.accesses in List.map (fun i -> let lines = loop_lines ~scan ~names ~joins i accesses.(i) in if pads i then ( i, List.mapi (fun n l -> if n = List.length lines - 1 then l ^ " LEFT-JOIN" else l) lines ) else (i, lines)) t.order let explain_unmatched t ~names ~joins = let joins = Array.of_list joins and names = Array.of_list names in List.map (fun (i, access) -> (i, loop_lines ~scan:"SCAN " ~names ~joins i access)) t.unmatched let temp_line t = match t.grouping with | Some (`Temp `Group_by) -> Some "USE TEMP B-TREE FOR GROUP BY" | Some (`Temp `Distinct) -> Some "USE TEMP B-TREE FOR DISTINCT" | Some `Loop | None -> None let explain t ~names ~joins = let named i = match List.nth names i with `Table n -> n | `Other d -> d in String.concat "\n" (List.concat_map snd (explain_loops t ~names ~joins) @ List.concat_map (fun (i, lines) -> ("RIGHT-JOIN " ^ named i) :: List.map (fun l -> " " ^ l) lines) (explain_unmatched t ~names ~joins) @ Option.to_list (temp_line t) @ sort_lines t.sort) (* The alias and column names each source publishes, enough to decide an access path without materialising anything: an access path needs them only to match a qualified column against the source it belongs to. *) let layout env ~bound (s : Ast.select) = let alias (tr : Ast.table_ref) = Option.value tr.Ast.alias ~default:tr.Ast.name in let cols (tr : Ast.table_ref) = match tr.Ast.subquery with | Some q -> Resolve.select_columns env q | None -> ( match List.find_opt (fun (n, _) -> ident_equal n tr.Ast.name) bound with | Some (_, cs) -> cs | None -> env.Resolve.columns tr.Ast.name) in let leading = match s.Ast.from with | Ast.Table tr -> (alias tr, cols tr) | Ast.Select { fs_select; fs_alias } -> (Option.value fs_alias ~default:"", Resolve.select_columns env fs_select) | Ast.Table_function { tf_name; tf_alias; _ } -> ( Option.value tf_alias ~default:tf_name, env.Resolve.table_function_columns tf_name ) | Ast.Values rows -> let n = match rows with r :: _ -> List.length r | [] -> 0 in ("", List.init n (fun i -> Ast.nth_column_name (i + 1))) | Ast.Unit -> ("", []) in leading :: List.map (fun (j : Ast.join) -> (alias j.Ast.table, cols j.Ast.table)) s.joins let last_kept (s : Ast.select) = List.fold_left (fun last (p, (j : Ast.join)) -> match j.Ast.type_ with Ast.Right | Ast.Full -> p | _ -> last) (-1) (List.mapi (fun p j -> (p + 1, j)) s.Ast.joins) let join_conjuncts (s : Ast.select) (layout : layout) = let rec conjuncts acc = function | Ast.Binary (Ast.And, a, b) -> conjuncts (conjuncts acc a) b | e -> e :: acc in let split e = List.rev (conjuncts [] e) in let on p (j : Ast.join) = if j.natural || j.using <> [] then Resolve.natural_on layout (p + 1) j else j.on in let kept = last_kept s >= 0 in let applies p (j : Ast.join) = match j.type_ with | Ast.Left | Ast.Right | Ast.Full -> `On (p + 1) | Ast.Inner | Ast.Cross | Ast.Semi _ -> if kept then `Inner_on (p + 1) else `Where in List.map (fun e -> (e, `Where)) (Option.fold ~none:[] ~some:split s.where) @ List.concat (List.mapi (fun p (j : Ast.join) -> List.map (fun e -> (e, applies p j)) (Option.fold ~none:[] ~some:split (on p j))) s.joins) let result_exprs (s : Ast.select) (layout : layout) = let cols (a, cs) = List.map (fun c -> Ast.Col (Some a, c)) cs in List.concat_map (fun (rc : Ast.result_col) -> match rc.expr with | Ast.Star -> List.concat_map cols (List.filter (fun (a, _) -> not (Resolve.is_semi_alias a)) layout) | Ast.Qualified_star q -> List.concat_map cols (List.filter (fun (a, _) -> Ast.ident_equal a q) layout) | e -> [ e ]) s.cols let outer_reads env layout e = let rec expr scope acc e = match e with | Ast.Col (q, c) when not (List.exists (fun sc -> Resolve.scope_binds sc q c) scope) -> ( match position layout q c with Some (i, _) -> i :: acc | None -> acc) | e -> Ast.fold_expr ~select:(select scope) (expr scope) acc e and select scope acc (sub : Ast.select) = let scope = Resolve.binding_scope env sub :: scope in let exprs = List.map (fun (rc : Ast.result_col) -> rc.expr) sub.cols @ List.filter_map (fun (j : Ast.join) -> j.on) sub.joins @ Option.to_list sub.where @ sub.group_by @ Option.to_list sub.having @ List.map fst sub.order_by in let acc = List.fold_left (expr scope) acc exprs in List.fold_left (fun acc (_, arm) -> select scope acc arm) acc sub.compound in expr [] [] e