(*--------------------------------------------------------------------------- Copyright (c) 2026 Thomas Gazagnaire. All rights reserved. SPDX-License-Identifier: ISC ---------------------------------------------------------------------------*) module Where_loop = Sql.Private.Where_loop (* The shapes answered before the planner: a handful of single-table selects are answered by seeking a b-tree directly -- an edge for MIN/MAX(rowid), a bounded walk for a LIMIT, an index range for a comparison. An equality is the planner's seek. Recognising one reads no row, so EXPLAIN asks which path a select takes without taking it. *) open Model open Decl open Rowid_range module Engine = Sql.Private.Engine module Plan = Sql.Private.Plan type row = int64 option * Sql.Ast.value list type range_read = { idx : index; read : int list; prefix : Sql.Ast.value list; reverse : bool; } (* The column [e] names, bare or under the COLLATE {!Sql.Private.Resolve} puts on a comparison's operand. *) let column_operand = function | Sql.Ast.Col (_, c) | Sql.Ast.Collate (Sql.Ast.Col (_, c), _) -> Some c | _ -> None let sequence_of = function Sql.Ast.Collate (_, n) -> Some n | _ -> None (* Whether the comparison of [x] with [y] on column [c] of a table declaring [columns] compares under [c]'s declared sequence, the one a bare reference to [c] compares under and an index orders [c] by: a COLLATE on an operand, the left one's first, names that sequence or none does (sqlite3BinaryCompareCollSeq). *) let declared_sequence columns c x y = match match sequence_of x with Some _ as s -> s | None -> sequence_of y with | None -> true | Some n -> ( match List.find_index (fun (col : column) -> Catalog.Ident.equal col.name c) columns with | None -> false | Some pos -> ( match (declared_collation columns pos, Sql.Collation.of_string n) with | Some d, Some n -> Sql.Collation.equal d n | _ -> false)) (* The value of the constant [v] a comparison with an indexed column reads under the column's affinity, which these paths convert it to: none for a CAST or an operand stating an affinity, whose own may make the comparison one the index cannot answer (sqlite3IndexAffinityOk), and which the planner's seeks weigh. *) let bare_value params = function | Sql.Ast.Cast _ | Sql.Ast.Affinity _ | Sql.Ast.Collate ((Sql.Ast.Cast _ | Sql.Ast.Affinity _), _) -> None | v -> const_value params v (* [col = const] equalities among the top-level AND conjuncts of [e] that compare under the column's declared sequence, as (column name, value). Non-equality conjuncts are ignored -- they stay in the WHERE for the engine to re-apply -- so the result is a sound superset filter even under a top-level OR (which yields no conjuncts). *) let rec and_eqs columns params (e : Sql.Ast.expr) acc = match e with | Binary (And, a, b) -> and_eqs columns params a (and_eqs columns params b acc) | Binary (Eq, x, y) -> ( let key = match column_operand x with | Some c -> Some (c, y) | None -> Option.map (fun c -> (c, x)) (column_operand y) in match key with | Some (c, v) when declared_sequence columns c x y -> ( match bare_value params v with | Some value -> (c, value) :: acc | None -> acc) | Some _ | None -> acc) | _ -> acc let equalities columns params e = and_eqs columns params e [] (* The value range (lower/upper bound, each an inclusive flag + value, or [None]) the top-level AND conjuncts of [e] place on column [col] of a table declaring [columns], under its declared sequence. Only range comparisons (< <= > >=) against a constant count; other conjuncts stay in the WHERE for the engine to re-apply, so the indexed rows are a superset. *) let column_range columns params col e = let same c = Catalog.Ident.equal c col in let rec go (lo, hi) e = match e with | Sql.Ast.Binary (And, a, b) -> go (go (lo, hi) a) b | Binary (((Gt | Ge | Lt | Le) as op), x, y) -> ( let oriented = if not (declared_sequence columns col x y) then None else match (column_operand x, column_operand y) with | Some c, _ when same c -> Some (op, y) | _, Some c when same c -> Some (flip_cmp op, x) | _ -> None in match Option.bind oriented (fun (op, v) -> Option.map (fun value -> (op, value)) (bare_value params v)) with | Some (Gt, v) -> (Some (v, false), hi) | Some (Ge, v) -> (Some (v, true), hi) | Some (Lt, v) -> (lo, Some (v, false)) | Some (Le, v) -> (lo, Some (v, true)) | _ -> (lo, hi)) | _ -> (lo, hi) in go (None, None) e (* The ORDER BY a bounded rowid scan can serve: none (ascending scan order) or a single rowid key. [Some reverse] (DESC -> [true]) when servable, else [None]. *) let order_is_rowid columns name alias = function | [] -> Some false | [ (e, dir) ] when names_rowid columns name alias e -> Some (dir = Sql.Ast.Desc) | _ -> None (* The clauses a rowid LIMIT scan can serve, apart from the LIMIT/ORDER BY and a rowid-range WHERE (handled separately): one source, no JOIN, GROUP BY, HAVING, DISTINCT, compound arm, or CTE, and a projection that does not fold the whole table (aggregate/window/subquery). *) let limit_pushable (s : Sql.Ast.select) = List.for_all Fun.id [ s.joins = []; s.compound = []; s.ctes = []; not s.distinct; not (Sql.Private.Query.is_aggregate_query s); List.for_all (fun (rc : Sql.Ast.result_col) -> pushdown_safe rc.expr) s.cols; ] let expr_opt_safe = Option.fold ~none:true ~some:pushdown_safe (* Every expression in [s] is pushdown-safe (no subquery or window referencing the restricted table); aggregates, GROUP BY, HAVING, ORDER BY, and LIMIT are fine -- they fold the exact result set the engine derives. *) let select_pushdown_safe (s : Sql.Ast.select) = List.for_all (fun (rc : Sql.Ast.result_col) -> pushdown_safe rc.expr) s.cols && expr_opt_safe s.where && expr_opt_safe s.having && List.for_all pushdown_safe s.group_by && List.for_all (fun (e, _) -> pushdown_safe e) s.order_by let indexable (s : Sql.Ast.select) = List.for_all Fun.id [ s.joins = []; s.compound = []; s.ctes = []; select_pushdown_safe s ] (* Is [p] a top-level AND conjunct of [e], written the same way? *) let rec conjunct_of p (e : Sql.Ast.expr) = match e with | Binary (And, a, b) -> conjunct_of p a || conjunct_of p b | e -> Sql.Ast.equal_expr e p (* Does [idx] hold an entry for every row [where] admits? A full index holds one for every row; a partial one holds only the rows its predicate admits, so it answers only where [where] implies that predicate. The implication proved here is the predicate written back verbatim as a conjunct of the query's WHERE; sqlite3 proves more and reading more rows is never wrong. *) let holds_every_row ?where (idx : index) = match idx.where with | None -> true | Some p -> ( match where with None -> false | Some w -> conjunct_of p w) (* Can a read written as a bare column reference be answered through the first [keys] key columns of [idx]? Only an index reaching every row the query admits, only one whose entries name a row by its rowid, and only key columns ordered the way the comparison compares: a bare column compares under its declared COLLATE, so a key naming another sequence would seek to the wrong place. The key columns past those the seek compares only order the entries it reads, whatever their sequence: sqlite3 matches a term's collation with the key column it binds alone (where.c, whereScanInit). *) let seekable_index columns ?where ~keys (idx : index) = holds_every_row ?where idx && (match idx.trailing with Rowid_ref -> true | Pk_ref _ -> false) && List.length idx.keys >= keys && List.for_all2 (fun k (o : Sql.Order.t) -> match k with | Expression _ -> false | Column pos -> ( match declared_collation columns pos with | Some declared -> Sql.Collation.equal o.collation declared | None -> false)) (List.filteri (fun i _ -> i < keys) idx.keys) (List.filteri (fun i _ -> i < keys) idx.orders) (* Where an entry of [idx] holds what a read of column position [pos] answers ({!Sql.Private.Where_table.entry_slot}). *) let entry_slot (gt : generic_table) (idx : index) = Sql.Private.Where_table.entry_slot (Decl.where_table gt) (Decl.where_index idx) (* Does [idx] hold everything the query reads from a source over [gt]? Then the entry a seek lands on is the answer and the row need never be fetched -- sqlite3 calls such a path a covering index, and it is the difference between one b-tree descent per rewind and one per row returned. *) let covers gt idx ~read = Sql.Private.Where_table.covers (Decl.where_table gt) (Decl.where_index idx) ~read (* The index sqlite3 counts a whole table through (isSimpleCount, select.c): the narrowest full index narrower than the table, the first of equal ones in sqlite3's list of the table's indexes, which holds them newest first. *) let count_index (gt : generic_table) = let table = Where_loop.table_width (Decl.where_table gt) in List.fold_left (fun best (idx : index) -> if idx.where <> None then best else let w = Where_loop.index_width (Decl.where_table gt) (Decl.where_index idx) in if w >= table then best else match best with | Some (_, bw) when bw <= w -> best | _ -> Some (idx, w)) None (List.rev gt.indexes) |> Option.map fst type t = | Rowid_count of { table : string; gt : generic_table; lo : int64; hi : int64; ranged : bool; via : index option; (** the index a whole-table count walks instead of the table *) terms : string; (** what EXPLAIN prints of the rowid terms *) } | Rowid_minmax of { table : string; gt : generic_table; want : [ `Max | `Min ]; lo : int64; hi : int64; terms : string; (** what EXPLAIN prints of the rowid terms *) } | Rowid_limit of { table : string; gt : generic_table; reverse : bool; offset : int; limit : int; lo : int64; hi : int64; ranged : bool; (* the WHERE bounded the walk, rather than the LIMIT *) terms : string; (** what EXPLAIN prints of the rowid terms *) } | Rowid_range of { table : string; gt : generic_table; lo : int64; hi : int64; low : bool; high : bool; } | Indexed_range of { table : string; gt : generic_table; idx : index; covering : bool; read : int list; lo : (Sql.Ast.value * bool) option; hi : (Sql.Ast.value * bool) option; prefix : Sql.Ast.value list; reverse : bool; (** the ORDER BY walks the range backwards *) } | Pk_range of { table : string; gt : generic_table; keys : string list; (** the PRIMARY KEY's columns, in key order *) prefix : Sql.Ast.value list; lo : (Sql.Ast.value * bool) option; hi : (Sql.Ast.value * bool) option; reverse : bool; (** the ORDER BY walks the range backwards *) } | Ordered_projection of { table : string; gt : generic_table; projection : int list; order_pos : int; } (* An index path, under the covering word where the entries it reads are themselves the answer: sqlite3 writes that as "COVERING INDEX i" where it writes "INDEX i" for a path that goes on to fetch each row. *) let using ~covering descr = if covering then "COVERING " ^ descr else descr (* What each column of an entry of [idx] holds, in entry order, with the collating sequence the entry orders it by: its key columns, then the rowid or the PRIMARY KEY columns it trails. *) let entry_keys (idx : index) = List.map2 (fun k (o : Sql.Order.t) -> match k with | Column pos -> (`Column pos, Some o.collation) | Expression _ -> (`Expression, None)) idx.keys idx.orders @ match idx.trailing with | Rowid_ref -> [ (`Rowid, None) ] | Pk_ref cols -> List.map (fun (c : index_column) -> (`Column c.cid, Some c.order.collation)) cols (* The rowid terms of [where], as explainIndexRange writes them: [rowid=?] for an equality, else the edges it bounds. *) let rowid_terms columns name alias params = function | None -> "" | Some where -> ( match Rowid_range.bounds columns name alias params where with | None -> " USING INTEGER PRIMARY KEY (rowid=?)" | Some (_, _, low, high) -> " USING INTEGER PRIMARY KEY (" ^ String.concat " AND " ((if low then [ "rowid>?" ] else []) @ if high then [ "rowid Fmt.str "SCAN %s USING COVERING INDEX %s" table idx.name | Rowid_count { table; ranged = false; via = None; _ } -> Fmt.str "SCAN %s" table | Rowid_count { ranged = true; terms; _ } -> Fmt.str "SEARCH %s%s" name terms | Rowid_minmax { terms; _ } -> Fmt.str "SEARCH %s%s" name terms | Rowid_limit { ranged = false; _ } -> Fmt.str "SCAN %s" name | Rowid_limit { ranged = true; terms; _ } -> Fmt.str "SEARCH %s%s" name terms | Rowid_range { low; high; _ } -> Fmt.str "SEARCH %s USING INTEGER PRIMARY KEY (%s)" name (match (low, high) with | true, true -> "rowid>? AND rowid "rowid>?" | false, _ -> "rowid Fmt.str "SEARCH %s USING %s%s" name (using ~covering ("INDEX " ^ idx.name)) (Sql.Private.Where_table.range_terms (Decl.where_table gt) (Decl.where_index idx) ~eq:(List.length prefix) ~lo:(lo <> None) ~hi:(hi <> None)) | Pk_range { keys; prefix; lo; hi; _ } -> let eq = List.length prefix in let ranged = List.nth keys eq in Fmt.str "SEARCH %s USING PRIMARY KEY (%s)" name (String.concat " AND " ( List.filteri (fun i _ -> i < eq) keys |> List.map (fun c -> c ^ "=?") |> fun eqs -> eqs @ (if lo <> None then [ ranged ^ ">?" ] else []) @ if hi <> None then [ ranged ^ " Fmt.str "SCAN %s" name module type S = sig type t val table : t -> string -> generic_table option val column_names : t -> string -> string list val index_for : t -> ?where:Sql.Ast.expr -> string -> string list -> Catalog.Spi.access_path option val index_range_rows : t -> generic_table -> range_read -> lo:(Sql.Ast.value * bool) option -> hi:(Sql.Ast.value * bool) option -> row list option val without_rowid : t -> string -> generic_table option val pk_range_rows : t -> generic_table -> prefix:Sql.Ast.value list -> reverse:bool -> lo:(Sql.Ast.value * bool) option -> hi:(Sql.Ast.value * bool) option -> row list option val ordered_project : t -> generic_table -> order_pos:int -> projection:int list -> Sql.Ast.value list list val count : t -> generic_table -> lo:int64 -> hi:int64 -> int val count_index : t -> index -> int val extreme : t -> generic_table -> [ `Max | `Min ] -> lo:int64 -> hi:int64 -> int64 option val span : t -> generic_table -> scan:bool -> reverse:bool -> offset:int -> limit:int -> lo:int64 -> hi:int64 -> row list val restricted : t -> string -> row list -> Sql.Private.Query.catalog end module Make (R : S) = struct (* What [s] reads of the one source it names, as the positions that source's cursor publishes: the table's declared columns then the hidden rowid slot. It is a question about the query and the schema, so a path answers it while recognising itself. The layout names the source as the query does, alias included. *) let read_columns db (tr : Sql.Ast.table_ref) (s : Sql.Ast.select) = let cols = R.column_names db tr.name @ [ Sql.Private.Resolve.rowid_sentinel ] in let layout = [ (Option.value ~default:tr.name tr.alias, cols) ] in let columns name = match R.column_names db name with | cols -> cols | exception Catalog.Error _ -> [] in (Plan.read_columns ~columns layout s).(0) (* [s] as sqlite3's planner weighs it, where it reads one table and its WHERE holds no IN, which a path here does not seek on. *) let where_loop db (s : Sql.Ast.select) = let rec has_in = function | Sql.Ast.In_list _ | Sql.Ast.In_select _ -> true | e -> Sql.Ast.fold_expr ~select:(fun f _ -> f) (fun f x -> f || has_in x) false e in match s.from with | Sql.Ast.Table ({ name; alias; subquery = None; _ } as tr) when not (Option.fold ~none:false ~some:has_in s.where) -> let gt = match R.table db name with | Some _ as gt -> gt | None -> R.without_rowid db name in Option.bind gt (fun gt -> let read = read_columns db tr s in Where_loop.v (Decl.where_table gt) ~names:(R.column_names db name) ~alias:(Option.value alias ~default:name) ~covers:(fun idx -> covers gt (Decl.where_named gt idx) ~read) ~subquery:(fun _ -> None) s) | _ -> None (* Counting a rowid range needs cell counts, not decoded rows. *) let rowid_count db (s : Sql.Ast.select) params = match (s.cols, s.from) with | ( [ { Sql.Ast.expr = Sql.Ast.Func ("count", [ Sql.Ast.Star ]); _ } ], Sql.Ast.Table { schema = _; name; alias; subquery = None } ) when bare s -> ( match R.table db name with | None -> None | Some gt -> Option.map (fun (lo, hi) -> let ranged = s.where <> None in let via = if ranged then None else count_index gt in let terms = rowid_terms gt.schema.columns name alias params s.where in Rowid_count { table = name; gt; lo; hi; ranged; via; terms }) (of_where gt.schema.columns name alias params s.where)) | _ -> None (* SELECT min|max(rowid) FROM t [WHERE ]: the answer is one edge of the span, found by a descent rather than by folding every row. *) let rowid_minmax db (s : Sql.Ast.select) params = match (s.Sql.Ast.cols, s.from) with | ( [ { Sql.Ast.expr = Sql.Ast.Func (fn, [ arg ]); _ } ], Sql.Ast.Table { schema = _; name; alias; subquery = None } ) when (fn = "min" || fn = "max") && bare s -> ( match R.table db name with | Some gt when names_rowid gt.schema.columns name alias arg -> ( match of_where gt.schema.columns name alias params s.where with | Some (lo, hi) -> Some (Rowid_minmax { table = name; gt; want = (if fn = "max" then `Max else `Min); lo; hi; terms = rowid_terms gt.schema.columns name alias params s.where; }) | None -> None) | _ -> None) | _ -> None (* SELECT ... FROM t [WHERE ] [ORDER BY rowid] LIMIT n: the walk is bounded at both ends, so it steps as far as the LIMIT and no further. *) let rowid_limit db (s : Sql.Ast.select) params = match (s.Sql.Ast.from, s.limit) with | Sql.Ast.Table { schema = _; name; alias; subquery = None }, Some lim when limit_pushable s -> ( match ( R.table db name, const_int params lim, Option.fold ~none:(Some 0) ~some:(const_int params) s.offset ) with | Some gt, Some limit, Some offset when limit >= 0 && offset >= 0 -> ( match ( order_is_rowid gt.schema.columns name alias s.order_by, of_where gt.schema.columns name alias params s.where ) with | Some reverse, Some (lo, hi) -> Some (Rowid_limit { table = name; gt; reverse; offset; limit; lo; hi; ranged = s.where <> None; terms = rowid_terms gt.schema.columns name alias params s.where; }) | _ -> None) | _ -> None) | _ -> None (* The search loop [Search {eq; lo; hi}] of [q] makes through [idx], over the table [gt] the source [tr] of [s] reads, as a path: the equalities of [where] bind the first [eq] columns of an entry and its comparisons bracket the next, each value read as its comparison reads it ({!Sql.Value_ops.compared}). [None] where a column it binds is ordered under another collating sequence than its comparison uses, or the WHERE writes a term the loop weighed in a form this path does not read: the plan then walks the index. *) let search db (s : Sql.Ast.select) (tr : Sql.Ast.table_ref) gt params where q ~idx ~eq ~lo ~hi = let columns = gt.schema.columns in let entry = Array.of_list (entry_keys idx) in let width = if lo || hi then eq + 1 else eq in let ordered = function | `Rowid, _ -> true | `Column pos, Some coll -> ( match declared_collation columns pos with | Some declared -> Sql.Collation.equal coll declared | None -> false) | (`Column _ | `Expression), _ -> false in let eqs = equalities columns params where in let bound = function | `Column pos, _ -> let c = List.nth columns pos in List.find_map (fun (n, v) -> if Catalog.Ident.equal n c.name then Some (Sql.Value_ops.compared c.type_affinity v) else None) eqs | (`Rowid | `Expression), _ -> None in let range = function | `Rowid, _ -> ( match Rowid_range.bounds columns tr.name tr.alias params where with | Some (l, h, low, high) -> ( (if low then Some (Sql.Ast.Int l, true) else None), if high then Some (Sql.Ast.Int h, true) else None ) | None -> (None, None)) | `Column pos, _ -> let c = List.nth columns pos in let read = Option.map (fun (v, incl) -> (Sql.Value_ops.compared c.type_affinity v, incl)) in let l, h = column_range columns params c.name where in (read l, read h) | `Expression, _ -> (None, None) in if width > Array.length entry || (not (holds_every_row ~where idx)) || not (List.for_all ordered (Array.to_list (Array.sub entry 0 width))) then None else let prefix = List.filter_map bound (Array.to_list (Array.sub entry 0 eq)) in let l, h = if lo || hi then range entry.(eq) else (None, None) in if List.length prefix <> eq || l <> None <> lo || h <> None <> hi then None else let read = read_columns db tr s in Some (Indexed_range { table = tr.name; gt; idx; covering = covers gt idx ~read; read; lo = l; hi = h; prefix; reverse = (Where_loop.order q (Search { index = Decl.where_index idx; eq; ins = []; lo; hi })) .reverse; }) (* The search sqlite3 makes of [q]'s best loop, where that is one: a range or an equality, the one row of a UNIQUE key included. *) let best_search db s tr gt params where q = match Where_loop.best q with | Search { index; eq; ins = []; lo; hi } -> search db s tr gt params where q ~idx:(Decl.where_named gt index) ~eq ~lo ~hi | One_row -> Option.bind (Where_loop.unique_index q) (fun idx -> let idx = Decl.where_named gt idx in search db s tr gt params where q ~idx ~eq:(List.length idx.keys) ~lo:false ~hi:false) | Search _ | Scan | Rowid_in | Rowid_range _ | Full _ | Pk_search _ -> None (* A search through an index of a WITHOUT ROWID table, wherever sqlite3 searches one, as no other path reads such an index by its key. A rowid table's index is the planner's, whose cursor steps a range in place. *) let indexed_range db (s : Sql.Ast.select) params = match (s.Sql.Ast.from, s.where) with | Sql.Ast.Table ({ name; subquery = None; _ } as tr), Some where when indexable s -> ( let without_rowid gt = Option.bind (where_loop db s) (fun q -> best_search db s tr gt params where q) in match R.table db name with | Some ({ store = Pk_index_rows _; _ } as gt) -> without_rowid gt | Some _ -> None | None -> Option.bind (R.without_rowid db name) without_rowid) | _ -> None (* The search of loop [kind] of [q] over the PRIMARY KEY [key] (its first [n] columns) of the WITHOUT ROWID table [gt]: the equalities of [where] bind the first [eq] key columns and its comparisons bracket the next. A key column compared under another collation than the one the b-tree is ordered by is not searched. *) let pk_search ~name ~gt ~key ~n ~where params q kind ~eq ~low ~high = let key = List.filteri (fun i _ -> i < n) key in let names = List.map (fun (c : index_column) -> (List.nth gt.schema.columns c.cid).name) key in let ordered (c : index_column) = match declared_collation gt.schema.columns c.cid with | Some declared -> Sql.Collation.equal c.order.collation declared | None -> false in let eqs = equalities gt.schema.columns params where in let affinity col = match List.find_opt (fun (c : column) -> Catalog.Ident.equal c.name col) gt.schema.columns with | Some c -> c.type_affinity | None -> `Blob in let bound col = List.find_map (fun (c, v) -> if Catalog.Ident.equal c col then Some (Sql.Value_ops.compared (affinity col) v) else None) eqs in let prefix = List.filter_map bound (List.filteri (fun i _ -> i < eq) names) in let range col = let read = Option.map (fun (v, incl) -> (Sql.Value_ops.compared (affinity col) v, incl)) in match column_range gt.schema.columns params col where with | lo, hi when lo <> None = low && hi <> None = high -> Some (Pk_range { table = name; gt; keys = names; prefix; lo = read lo; hi = read hi; reverse = (Where_loop.order q kind).reverse; }) | _ -> None in if List.length prefix <> eq || not (List.for_all ordered (List.filteri (fun i _ -> i <= eq) key)) then None else Option.bind (List.nth_opt names eq) range (* A range of a WITHOUT ROWID table's PRIMARY KEY after equalities on its leading columns, where sqlite3 searches the b-tree that holds the rows ({!Where_loop.Pk_search}) and walks it backwards for a descending ORDER BY. The complete predicate is reapplied to the rows the range yields, as for an index range. *) let pk_range db (s : Sql.Ast.select) params = match (s.Sql.Ast.from, s.where) with | Sql.Ast.Table { name; subquery = None; _ }, Some where -> ( match R.without_rowid db name with | Some ({ store = Pk_index_rows { key = Some (key, n); _ }; _ } as gt) when indexable s -> ( match Option.map (fun q -> (q, Where_loop.best q)) (where_loop db s) with | Some (q, (Pk_search { eq; ins = []; lo = low; hi = high } as kind)) when low || high -> pk_search ~name ~gt ~key ~n ~where params q kind ~eq ~low ~high | _ -> None) | _ -> None) | _ -> None (* A plain SELECT over one table with no filter, grouping or limit, ordered ascending by one column: its table, alias and order column. *) let plain_ordered (s : Sql.Ast.select) = match (s.from, s.order_by) with | ( Sql.Ast.Table { schema = _; name; alias; subquery = None }, [ (Sql.Ast.Col (order_qual, order_col), Sql.Ast.Asc) ] ) when s.where = None && s.joins = [] && s.compound = [] && s.ctes = [] && s.group_by = [] && s.having = None && (not s.distinct) && s.limit = None && s.offset = None -> Some (name, alias, order_qual, order_col) | _ -> None (* The positions of the projected columns, when each is a bare column of the table. *) let projected ~qualified ~position (cols : Sql.Ast.result_col list) = List.fold_right (fun (rc : Sql.Ast.result_col) acc -> match (rc.expr, acc) with | Sql.Ast.Col (qual, col), Some positions when qualified qual && rc.alias = None -> Option.map (fun pos -> pos :: positions) (position col) | _ -> None) cols (Some []) let ordered_plan ~name gt ~projection ~order_pos = if not (Option.equal Sql.Collation.equal (declared_collation gt.schema.columns order_pos) (Some Sql.Collation.default)) then None else match projection with | _ :: _ :: _ -> Some (Ordered_projection { table = name; gt; projection; order_pos }) | [] | [ _ ] -> None (* For a wide, unfiltered projection, walking table rows once and sorting the projected values avoids the VM's per-column cursor calls. Only a plain BINARY column order is handled here; all richer SQL stays in the planner. *) let ordered_projection db (s : Sql.Ast.select) _params = match plain_ordered s with | None -> None | Some (name, alias, order_qual, order_col) -> ( let source = Option.value ~default:name alias in let qualified = function | None -> true | Some q -> Catalog.Ident.equal q source in match R.table db name with | Some gt when qualified order_qual -> let names = R.column_names db name in let position col = List.find_index (Catalog.Ident.equal col) names in Option.bind (position order_col) (fun order_pos -> Option.bind (projected ~qualified ~position s.cols) (fun projection -> ordered_plan ~name gt ~projection ~order_pos)) | _ -> None) (* SELECT ... FROM t WHERE AND ...: every row the WHERE admits lies in the span the rowid inequalities leave, so the walk seeks the low edge and stops past the high one, and the full select runs over the rows found. A rowid equality is left to the general planner's seek, and so is an equality an index serves, which narrows further than the span. *) let rowid_range db (s : Sql.Ast.select) params = match (s.Sql.Ast.from, s.where) with | Sql.Ast.Table { schema = _; name; alias; subquery = None }, Some where when indexable s -> Option.bind (R.table db name) (fun gt -> let seeks = match equalities gt.schema.columns params where with | [] -> false | eqs -> R.index_for db ~where gt.schema.tbl_name (List.map fst eqs) <> None in if seeks then None else Option.map (fun (lo, hi, low, high) -> Rowid_range { table = name; gt; lo; hi; low; high }) (bounds gt.schema.columns name alias params where)) | _ -> None (* What every path above asks of the statement before it reads a value or the schema: a count or an edge of the rowid is the one call of the select list, a bounded walk has a LIMIT, an ordered read an ORDER BY, and a range on an index or on the rowid is a range comparison among the top-level conjuncts of the WHERE. A select with none of them takes no path whatever its values, and is not asked further. *) let rec ranges (e : Sql.Ast.expr) = match e with | Binary (And, a, b) -> ranges a || ranges b | Binary ((Gt | Ge | Lt | Le), _, _) -> true | _ -> false let possible (s : Sql.Ast.select) = (match s.cols with [ { expr = Func _; _ } ] -> true | _ -> false) || s.limit <> None || s.order_by <> [] || Option.fold ~none:false ~some:ranges s.where (* A path that reads the table in rowid order gives way where sqlite3 reads it through an index, whose order the rows then come in: a walk of the whole index, for the ORDER BY or for a narrower covering read, or a search of it, which {!indexed_range} answers through the index sqlite3 searches. A count or an edge of the rowid returns one row. *) let in_rowid_order db s = match where_loop db s with | Some q -> ( match Where_loop.best q with | Full _ | Search _ | Pk_search _ -> false | Scan | One_row | Rowid_in | Rowid_range _ -> true) | None -> true (* A WITHOUT ROWID table with an index is the exception: an equality on a column the index keys is a search of it that no other path makes, so a select over one with an equality among the conjuncts of its WHERE is asked further too. *) let rec equality (e : Sql.Ast.expr) = match e with | Binary (And, a, b) -> equality a || equality b | Binary (Eq, _, _) -> true | _ -> false let searches_without_rowid db (s : Sql.Ast.select) = match (s.from, s.where) with | Sql.Ast.Table { name; subquery = None; _ }, Some where when equality where -> ( match R.without_rowid db name with | Some gt -> gt.indexes <> [] | None -> false) | _ -> false let of_select db s params = if not (possible s || searches_without_rowid db s) then None else List.find_map (fun f -> f db s params) [ rowid_count; rowid_minmax; indexed_range; pk_range ] |> function | Some _ as p -> p | None -> if not (in_rowid_order db s) then None else List.find_map (fun f -> f db s params) [ rowid_limit; ordered_projection; rowid_range ] (* The loop each path is, as sqlite3 costs it. *) let loop = function | Rowid_count _ | Rowid_minmax _ -> None | Rowid_limit _ | Ordered_projection _ -> Some Where_loop.Scan | Rowid_range { low; high; _ } -> Some (Where_loop.Rowid_range { lo = low; hi = high }) | Pk_range { prefix; lo; hi; _ } -> Some (Where_loop.Pk_search { eq = List.length prefix; ins = []; lo = lo <> None; hi = hi <> None; }) | Indexed_range { idx; prefix; lo; hi; _ } -> Some (Where_loop.Search { index = Decl.where_index idx; eq = List.length prefix; ins = []; lo = lo <> None; hi = hi <> None; }) let sort db s p = match (where_loop db s, loop p) with | Some q, Some kind when Where_loop.terms q > 0 -> Some { Plan.terms = Where_loop.terms q; sorted = (Where_loop.order q kind).sorted; } | _ -> None let run db (s : Sql.Ast.select) params = function | Rowid_count { via = Some idx; _ } -> Some [ [ Sql.Ast.Int (Int64.of_int (R.count_index db idx)) ] ] | Rowid_count { gt; lo; hi; via = None; _ } -> Some [ [ Sql.Ast.Int (Int64.of_int (R.count db gt ~lo ~hi)) ] ] | Rowid_minmax { gt; want; lo; hi; _ } -> let extreme = R.extreme db gt want ~lo ~hi in Some [ [ (match extreme with | Some r -> Sql.Ast.Int r | None -> Sql.Ast.Null); ]; ] | Rowid_limit { gt; reverse; offset; limit; lo; hi; ranged; _ } -> let bounded = R.span db gt ~scan:(not ranged) ~reverse ~offset ~limit ~lo ~hi in let cat = R.restricted db gt.schema.tbl_name bounded in Some (Engine.run_select cat { s with Sql.Ast.limit = None; offset = None } params) | Rowid_range { gt; lo; hi; _ } -> let rows = R.span db gt ~scan:false ~reverse:false ~offset:0 ~limit:max_int ~lo ~hi in Some (Engine.run_select (R.restricted db gt.schema.tbl_name rows) s params) | Indexed_range { gt; idx; read; prefix; lo; hi; reverse; _ } -> Option.map (fun rows -> Engine.run_select (R.restricted db gt.schema.tbl_name rows) s params) (R.index_range_rows db gt { idx; read; prefix; reverse } ~lo ~hi) | Pk_range { gt; prefix; lo; hi; reverse; _ } -> Option.map (fun rows -> Engine.run_select (R.restricted db gt.schema.tbl_name rows) s params) (R.pk_range_rows db gt ~prefix ~reverse ~lo ~hi) | Ordered_projection { gt; order_pos; projection; _ } -> Some (R.ordered_project db gt ~order_pos ~projection) end