(*--------------------------------------------------------------------------- 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 type value = Ast.value = | Null | Int of int64 | Float of float | Blob of string | Text of string module type S = Select_intf.S module Make (R : S) = struct (* The reads the executor makes of the handle, under the names this file has always read them by: the schema view {!R.catalog}, the cursor makers, and the fast-path recogniser. *) let catalog = R.catalog let gtable = R.gtable let plain_rowid_gtable = R.plain_rowid_gtable let table_column_names = R.column_names let view = R.view let view_columns = R.view_columns let master_rows = R.master_rows let catalog_affinity = R.affinity let schema_env = R.schema_env let seek_index = R.seek_index let table_row_count = R.row_count let access_cursors = R.accesses let seek_paths = R.seek_paths let is_master_name = Sql.Private.Schema_table.is_name let master_column_names = Sql.Private.Schema_table.columns let ident_equal = Ident.equal let mem_ident col cols = List.exists (ident_equal col) cols let materialised_cursor t rows = R.of_rows t Cursor.Materialised rows (* The [WITH] table of [s] its select may read as the table is made: a recursive one that select's lone source, which nothing else in [s] reads, as sqlite3 runs a recursive CTE as a co-routine of the select reading it where that select reads it once (select.c, the co-routine conditions of sqlite3Select). *) let streamed (s : Ast.select) = match (s.from, s.joins, s.compound) with | Ast.Table { name; subquery = None; _ }, [], [] -> ( match List.find_opt (fun (c : Ast.cte) -> ident_equal c.name name) s.ctes with | Some c when Resolve.count_table_refs name s - Resolve.count_table_refs name c.query = 1 -> Some name | Some _ | None -> None) | _ -> None (* A cursor over [rows] as they are produced: the first rewind reads them as they come, holding one at a time, and a later one reads [again ()], the relation whole. Counted as a materialised relation is, when it was made. *) let stream_cursor rows ~again () = let rest = ref rows and row = ref [] and first = ref true in let next () = match !rest () with | Seq.Nil -> false | Seq.Cons (r, more) -> row := r; rest := more; true in let rewind () = if not !first then rest := List.to_seq (again ()); first := false; next () in let column j m = Register.set_value m (match List.nth_opt !row j with Some v -> v | None -> Ast.Null) in { Catalog.Cursor.rewind; next; column; rowid = (fun () -> None); reader = Catalog.Cursor.column_reader column; push = None; } let synthetic_scan_cursor t rows = R.of_rows t Cursor.Synthetic rows let literal_cursor t rows = R.of_rows t Cursor.Literal rows (* The {!Cursor.source} for one VM-scanned base table, or [None] for the schema table, a view, or a name no table answers to. A secondary index does not divert the scan: a bare [SELECT] over an indexed table reads in table order. *) let vdbe_table_info t (tr : Ast.table_ref) = let name = tr.name in if is_master_name name || view t name <> None || not (List.exists (fun g -> ident_equal g.schema.tbl_name name) (R.all_tables t)) then None else Some (R.table_info t tr (gtable t name)) (* A storage cursor already is a {!Sql.Vdbe} register cursor, so the engine scans a source with no per-column value conversion. *) let cat_cursor (mk : unit -> Catalog.Cursor.t) : Catalog.Cursor.t = mk () (* Rebuild the named enclosing scope a correlated subquery sees from the flat column values the engine passes (every scanned column, in cursor order) and the [layout] that names them: one [(alias, [(column, value)])] frame per cursor. *) let scope_of_values layout values = let rec go vals = function | [] -> [] | (alias, cols) :: rest -> let n = List.length cols in let chunk = List.filteri (fun i _ -> i < n) vals in let tl = List.filteri (fun i _ -> i >= n) vals in (alias, List.combine cols chunk) :: go tl rest in go values layout (* The subquery runner the catalog engine calls by id: look the subquery up in [subs] (id-indexed), rebuild the scope, and run it through {!run_subquery_impl}. *) let catalog_subquery_runner run_subquery layout subs id left scope_vals = let kind, sub = List.nth subs id in let scope = scope_of_values layout scope_vals in match (kind : Lower.subkind) with | Scalar -> run_subquery `Scalar sub scope | Exists -> run_subquery `Exists sub scope | In c -> run_subquery (`In (c, Option.get left)) sub scope | Member held -> Value_op.in_set_mem held (Option.get left) (* The runner a program's subqueries go to: the one given, else the held answers of the memberships that need none. A correlated subquery with no runner refuses the compile, and the caller falls back. *) let subquery_hooks ?run_subquery (hooks : Sql.Ir.hooks) layout subs = match (subs, run_subquery) with | [], _ -> hooks | _, Some run -> { hooks with subquery = catalog_subquery_runner run layout subs } | _, None when not (Lower.needs_runner subs) -> { hooks with subquery = Lower.member subs } | _ :: _, None -> raise Sql.Ir.Unsupported (* A cached plan is valid only while the schema it compiled against is unchanged. Every DDL, schema reload, and rollback replaces these lists wholesale, so physical equality with the handle's current lists is exact and O(1). *) let schema_unchanged t (all_tables, extra) = all_tables == R.all_tables t && extra == R.extra_master t let cached_plan t s = match Handle.Plans.find_opt (R.plan_cache t) s with | Some e when schema_unchanged t e.Handle.snap -> Some e.Handle.plan | _ -> None let store_plan t s plan = (* Bounded so dynamically-built SQL cannot grow the cache without limit. *) if Handle.Plans.length (R.plan_cache t) >= 256 then Handle.Plans.clear (R.plan_cache t); Handle.Plans.replace (R.plan_cache t) s { Handle.snap = (R.all_tables t, R.extra_master t); plan } (* The handle, whose cache keeps the plan of a select run with [params], where that select may run again as it is: one reading a bound value, which its caller runs again with others, or a step of a trigger program, run for each row it fires on. Any other select holds its literals alone and meets its like only where its text runs again, and a text is prepared again at each run, as sqlite3_exec prepares it: looking such a select up and keeping it would hash it twice for nothing. *) let rerun_cache t params = if Array.length params > 0 || R.firing t then Some t else None (* [scan] is required, not optional: omitting it gives a correct answer from a full nested loop, silent quadratic behaviour nothing at the call site marks. Passing [None] is a decision; forgetting is a type error. *) (* What each scanned column can hold, for the lowering that gives every comparison its affinity: the declared type of the column on the table that position's cursor reads. A source with no schema to read -- a derived table, a VALUES list, a relation the caller bound itself -- answers for none, and a comparison against one converts neither operand. *) let infos_affinity t ?cat s infos = let layout = List.map (fun (a, c, _) -> (a, c)) infos in (* A [WITH] table expression's columns hold what its body's expressions produce, and its own catalog is what knows that -- so where the caller has one it is asked, and the open database answers only for the schema. *) let affinity, env = match cat with | Some cat -> (cat.Sql.Private.Query.affinity, Query.resolve_env cat) | None -> (catalog_affinity t, schema_env t) in Plan.column_affinity ~affinity env s layout (* What each [IN (SELECT ...)] compares against: the affinity the subquery's own result column states, and its rows where it reads nothing of the query around it. Not folded into the AST before the lowering sees it, because an [IN] over a value list states no affinity on the right and the membership has to read one from that end. *) let cat_membership cat params = Query.membership ~run:(fun sub -> cat.Sql.Private.Query.subquery cat [] sub params) ~params cat (* The scalar-call hook a compiled program applies its functions through. It goes through the catalog rather than straight to {!Sql.Private.Func}, so a builtin whose answer is the connection's rather than its arguments' -- [last_insert_rowid()] -- is answered on the way through the VM exactly as it is on the way through the expression evaluator. *) let cat_call cat name coll args = Query.call cat ?coll name args (* The value layer a statement over [cat] runs on: its scalar calls go through the catalog, and over a UTF-16 one the functions that read a value's bytes read the bytes it is stored as ({!Lower.stored_text}). *) let statement_hooks cat = let b = { Lower.hooks with call = cat_call cat } in match cat.Query.encoding with | Sql.Encoding.Utf8 -> b | e -> Lower.stored_text e b (* Rows another path computed, handed to a row consumer one at a time. *) let emit_values emit rows = List.iter (fun vs -> Sql.Row.with_values vs emit) rows (* The plan compiled for [s] that the statement, [kept] or the handle's cache holds, if it enters the cursors in [order]: one compiled for another order is no plan for these cursors. *) let compiled_for ?cache ?prepared ?kept ?order s = let plan = match (prepared, kept) with | Some (p : Handle.prepared), _ -> p.compiled | None, Some kept -> !kept | None, None -> Option.bind cache (fun t -> cached_plan t s) in match (plan, order) with | Some plan, Some o when Sql.Closure.order plan <> o -> None | plan, _ -> plan let catalog_run_with_infos t ?cache ?prepared ?kept ?run_subquery ?regs ?order ~cat ~scan ~affinity ~membership ~params infos (s : Ast.select) ~emit = let layout = List.map (fun (a, c, _) -> (a, c)) infos in let encoding = cat.Query.encoding in (* A membership over an uncorrelated subquery lowers to the rows that subquery returned, so a program holding one answers for those rows and no others. Recorded as the lowering asks, because only the lowering knows which memberships it folded. *) let folded = ref false in let membership sub = let m = membership sub in if m.Sql.Private.Query.rows <> None then folded := true; m in (* [scan] lets a caller that knows the store build the cursors itself -- to seek an inner join through an index instead of rescanning it per outer row. Without one, every source is scanned. *) let cursors () = match scan with | Some build -> build () | None -> Array.of_list (List.map (fun (_, _, mk) -> cat_cursor mk) infos) in (* Each row goes to [emit] as the VM produces it, so a select whose result clauses can be applied as the rows arrive holds one row rather than its answer. The clauses that cannot -- ORDER BY, DISTINCT, OFFSET -- are the buffer they describe, inside {!Sql.Ir.iter}. *) let run ?regs plan = Sql.Closure.iter_rows ~params ?regs plan (cursors ()) ~f:emit; true in (* The register file [regs] keeps for the plan [kept] keeps, made from its program at the first run that takes the VM. *) let kept_regs = Option.map (fun r program -> match !r with | Some file -> file | None -> let file = Sql.Vdbe.registers program in r := Some file; file) regs in (* Reuse a compiled plan across executions that differ only in their bound parameters: the statement's own where it has one, else the one [kept] holds, else the handle's, keyed by the select. A correlated subquery bakes a per-execution runner into the program, and a LIMIT or OFFSET read from a parameter bakes that parameter's value at lowering, so neither is cached; a literal one is the select's own. *) let cacheable = Lower.counts_fixed s in let cached = if not cacheable then None else compiled_for ?cache ?prepared ?kept ?order s in match cached with | Some plan when Option.is_none prepared && Option.is_some kept -> run ?regs:kept_regs plan | Some plan -> run plan | None -> ( (* [Lower.query] rejects an unsupported select shape; [Sql.Ir.precompile] rejects an unsupported expression, e.g. a wide literal. *) match let q, subs = Lower.query ~params ~affinity ~membership ?order ~env:(Query.resolve_env cat) ~encoding layout s in (* a correlated subquery needs a runner; without one (or with an unsupported shape) the compile raises and the caller falls back *) let hooks = statement_hooks cat in let hooks = subquery_hooks ?run_subquery hooks layout subs in let plan = Sql.Closure.plan ~hooks q in R.planned t; (if cacheable && subs = [] && not !folded then match (prepared, kept, cache) with | Some (p : Handle.prepared), _, _ -> p.compiled <- Some plan | None, Some kept, _ -> kept := Some plan | None, None, Some t -> store_plan t s plan | None, None, None -> ()); plan with | exception Sql.Ir.Unsupported -> false | plan -> run plan) (* Run an aggregate / GROUP BY [s] through the catalog engine: lower to an {!Sql.Ir.grouped}, scan / group / fold / project over the sources, and emit the rows. A correlated subquery in the scan filter (WHERE / ON) runs per row through [run_subquery]; without one (or for a shape the IR does not model) the select falls back ([false]). *) (* [scan] is required for the reason given on {!catalog_run_with_infos}. *) let catalog_aggregate t ?run_subquery ?first ?arrival ?order ~cat ~scan ~affinity ~membership ~params infos (s : Ast.select) ~emit = let layout = List.map (fun (a, c, _) -> (a, c)) infos in match let g, subs = Lower.aggregate_query ~params ~affinity ~membership ?order ~env:(Query.resolve_env cat) ~encoding:cat.Query.encoding layout s in let hooks = statement_hooks cat in let hooks = subquery_hooks ?run_subquery hooks layout subs in (* Same access path as a plain select: [scan] seeks the inner table of a join through an index instead of rewinding it once per outer row. Without it an aggregate over a join is the full product -- which is what made a 35k x 25k GROUP BY over two indexed tables take minutes. *) let cursors = match scan with | Some build -> build () | None -> Array.of_list (List.map (fun (_, _, mk) -> cat_cursor mk) infos) in let keep v = Value_ops.tri_of v = Value_ops.T in R.planned t; Sql.Closure.run_grouped ~hooks ?arrival ~params ?first ~keep ~affinity g cursors with | exception Sql.Ir.Unsupported -> false | out -> emit_values emit out; true (* A VALUES row source materialised into a cursor: each tuple's cells are constant expressions, bound under the unnamed alias [""] with columns [column1..columnN], the names {!Engine.run_select} gives them. *) let values_info t params tuples = let cat = catalog t in let n = match tuples with r :: _ -> List.length r | [] -> 0 in let cols = List.init n (fun i -> Ast.nth_column_name (i + 1)) in let rows = List.map (List.map (Engine.eval_const cat params)) tuples in ("", cols, literal_cursor t rows) (* The VM joins by rewinding each cursor in turn, walking the product of every source. Where an equality binds a source's indexed column to a known value, its cursor rewinds onto that index bucket; where it binds a column of an earlier source, the source is read once into a hash and probed per outer row. {!Sql.Private.Plan} decides which; this file supplies what only this store can answer ({!plan_facts}) and builds the cursors ({!access_cursors}). EXPLAIN renders the same answer, so a printed plan is the plan that runs. *) (* [alias] refers to a plain rowid table that can be sought: not a view, not [sqlite_master], not a derived table, and not WITHOUT ROWID (whose scan is laid out in PRIMARY KEY order, so index rows would arrive out of order). *) let seekable_source t (tr : Ast.table_ref) = if tr.Sql.Ast.subquery <> None then None else match plain_rowid_gtable t tr.Sql.Ast.name with | Some gt when view t tr.Sql.Ast.name = None && not (is_master_name tr.Sql.Ast.name) -> Some gt.schema.tbl_name | _ -> None (* [alias] refers to a table the planner may seek: a {!seekable_source}, or a WITHOUT ROWID table, whose only path is a seek down its PRIMARY KEY ({!Seek.Primary_key}), which reads the rows in the order a scan does. *) let plan_seekable t (tr : Ast.table_ref) = match seekable_source t tr with | Some _ as found -> found | None -> ( if tr.Sql.Ast.subquery <> None || view t tr.Sql.Ast.name <> None || is_master_name tr.Sql.Ast.name then None else match gtable t tr.Sql.Ast.name with | { store = Pk_index_rows _; _ } as gt -> Some gt.schema.tbl_name | { store = Rowid_rows _; _ } -> None | exception Catalog.Error _ -> None) (* What the planner may ask this store: the implementation of {!Sql.Private.Plan.facts}. A seek cursor resolves its key afresh per rewind ({!Cursor.Make.key_values}), and a row reached through an index is fetched from the table by rowid ({!Cursor.Make.seek}), so a seek answers the rowid. A seek on an IN list looks every value up and hands each rowid over once. A closed subquery is not a key here: {!Rowid_range.const_value} reads a literal or a parameter, not something to run, and the executed path folds an uncorrelated subquery before planning anyway. *) (* The columns [keys] equates, and each with its value. *) let columns keys = List.map (fun (k : Plan.key) -> k.column) keys let pairs keys = List.map (fun (k : Plan.key) -> (k.column, k.value)) keys (* The path an equality on [keys] of [table] seeks through, as the planner weighs it, through the index named [index] where given. *) let index_path t ?where ?index ~reads table keys : Plan.path option = let read = reads table in match seek_index t ?where ?index table (List.map fst keys) ~read with | None -> None | Some (Seek.Rowid _) -> Some { descr = "INTEGER PRIMARY KEY (rowid=?)"; unique = true; bound = 1; rows_per_key = Some 1; (* the descent lands on the row, so there is no second one *) covering = true; index = None; rowid_order = true; } | Some (Seek.Primary_key _ as pk) -> let path = Seek.access_path pk in Some { descr = path.path; unique = path.unique; bound = path.bound; rows_per_key = path.rows_per_key; (* the descent lands on the rows themselves *) covering = true; index = None; (* a WITHOUT ROWID table has no rowid to order by *) rowid_order = false; } | Some (Seek.Index ((idx : index), n, _)) -> let gt = gtable t table in let covering = Seek.covers gt idx ~read in Some { descr = (if covering then "COVERING INDEX " else "INDEX ") ^ idx.name ^ Fast_path.index_terms gt idx ~eq:n ~lo:false ~hi:false; unique = idx.unique && n = List.length idx.keys; bound = n; rows_per_key = Seek.rows_per_key gt keys; covering; index = Some idx.name; rowid_order = n = List.length idx.keys; } (* The affinity of the one column the subquery [sub] yields, where it reads nothing of the select around it, as the planner weighs an [IN (SELECT ...)]; [None] for a correlated one. *) let closed_subquery t sub = let env = Query.resolve_env (catalog t) in if Resolve.correlated env [] sub then None else Some (match Resolve.in_select_affinity env sub with | a -> a | exception Catalog.Error _ -> None) (* The loop the planner's access [a] over [table] is, as {!Where_loop} costs it, or [None] for one it does not model. *) let loop_of t ?where ~read table (a : Plan.access) = match a with | Plan.Scan -> Some Where_loop.Scan | Plan.Seek { keys; _ } -> ( let set c = List.exists (function | { Plan.column = k; value = Plan.In_list _ | Plan.In_select _; _; } -> ident_equal k c | _ -> false) keys in let ins cols = List.concat (List.mapi (fun j c -> if set c then [ j ] else []) cols) in match seek_index t ?where table (columns keys) ~read with | Some (Seek.Rowid c) -> Some (if set c then Where_loop.Rowid_in else Where_loop.One_row) | Some (Seek.Index ((idx : index), n, cols)) -> let ins = ins cols in if idx.unique && n = List.length idx.keys && ins = [] then Some Where_loop.One_row else Some (Where_loop.Search { index = idx; eq = n; ins; lo = false; hi = false }) | Some (Seek.Primary_key (_, n, cols) as pk) -> let path = Seek.access_path pk in let ins = ins cols in if path.unique && ins = [] then Some Where_loop.One_row else Some (Where_loop.Pk_search { eq = n; ins; lo = false; hi = false }) | None -> None) | Plan.Ordered _ | Plan.Probe _ -> None (* The name a seek key spells the column [col] of [gt] with, [names] its columns: the rowid under its INTEGER PRIMARY KEY's name, else as [rowid]. *) let key_name gt names col = if col < List.length names then List.nth names col else Option.value (Seek.rowid_alias_column gt) ~default:"rowid" (* The keys of a step over [s], by the names the schema spells their columns with. *) let named (s : Where_loop.source) keys = List.map (fun (c, (k : Where_loop.sought)) -> { Plan.column = key_name s.gt s.names c; value = k.value; affinity = k.affinity; nulls = k.nulls; answers = k.answers; }) keys (* The seek of [index] of [gt], whose entries hold every column read where [covers] says so: the equalities [keys], by the names the schema spells their columns with, binding the index's first [eq] columns and the others tested by the loop, then the range [lo] to [hi] of the next column, if any, or past its NULLs where [past_null], the x > NULL of an IS NOT NULL (TERM_VNULL), which a range with no lower bound seeks. *) let index_seek ?(past_null = false) gt ~covers ~(index : index) ~eq ~keys ~lo ~hi = let covering = covers index in let point = lo = None && hi = None && not past_null in let path = { Plan.descr = (if covering then "COVERING INDEX " else "INDEX ") ^ index.name ^ Fast_path.index_terms gt index ~eq ~lo:(lo <> None || past_null) ~hi:(hi <> None); unique = index.unique && point && eq = List.length index.keys; bound = eq; rows_per_key = Seek.rows_per_key gt (pairs keys); covering; index = Some index.name; rowid_order = point && eq = List.length index.keys; } in Plan.Seek { table = gt.schema.tbl_name; path; keys; range = (if point then None else Some { lo; hi }); reverse = false; } (* The bounds [lo] and [hi] of a range seek after [keys], answering their conjuncts where every key has a value whatever the parameters: one that may have none sends the seek to a scan, which must test them. A key the seek's index does not bind answers none ({!bound_keys}). *) let range_answers keys ~lo ~hi = let inert = Option.map (fun (b : Plan.bound) -> { b with answers = None }) in if List.for_all (fun (k : Plan.key) -> Plan.valued k.value) keys then (lo, hi) else (inert lo, inert hi) (* The seek of an index search over [s]. *) let index_search (s : Where_loop.source) ~index ~keys ~lo ~hi ~past_null = index_seek ~past_null s.gt ~covers:s.covers ~index ~eq:(List.length keys) ~keys:(named s keys) ~lo ~hi (* The seek of a rowid range over [table]. *) let rowid_range table lo hi = let op = match (lo, hi) with | Some _, Some _ -> "rowid>? AND rowid "rowid>?" | None, _ -> "rowid Plan.Seek { seek with reverse = o.reverse } | a -> a in let terms = Where_loop.terms q in (a, if terms = 0 then None else Some { Plan.terms; sorted = o.sorted }) (* The loop sqlite3 reads the one table of [s] through, which only this store's indexes and widths can weigh ({!Where_loop}): a walk of a whole index where sqlite3 takes one for the ORDER BY or for a narrower covering read, else the access the planner chose, through the index sqlite3 seeks where two serve the equalities alike and walked backwards where that is the ORDER BY's direction; and how many ORDER BY terms are left to sort. *) let ordered_loop t ?where ~reads table (s : Ast.select) (a : Plan.access) = let gt = gtable t table in let own = not (rowid_stored gt) in let alias = match s.Sql.Ast.from with | Ast.Table tr -> Option.value tr.alias ~default:tr.name | _ -> table in let read = reads table in let covers idx = Seek.covers gt idx ~read in match Where_loop.v gt ~names:(table_column_names t table) ~alias ~covers ~subquery:(closed_subquery t) s with | None -> (a, None) | Some q -> ( let current = loop_of t ?where ~read table a in let walk (idx : index option) best = let reverse = (Where_loop.order q best).reverse in let index, covering = match idx with | Some idx -> (Some idx.name, covers idx) | None -> (None, true) in (Plan.Ordered { table; index; covering; reverse }, Some best) in let seek_through (idx : index) eq best = match a with | Plan.Seek ({ table; keys; _ } as seek) -> ( match index_path t ?where ~index:idx.name ~reads table (pairs keys) with | Some path when path.bound = eq -> (Plan.Seek { seek with path }, Some best) | Some _ | None -> (a, current)) | Plan.Scan | Plan.Ordered _ | Plan.Probe _ -> (a, current) in (* whether [a]'s keys name each of [index]'s first [eq] columns, which a seek of [index] then binds; the keys it does not bind are made inert ({!bound_keys}) *) let leads (index : index) eq = match a with | Plan.Seek { keys; _ } -> let names = table_column_names t table in List.for_all (function | Column c -> List.exists (fun (k : Plan.key) -> ident_equal k.column (key_name gt names c)) keys | Expression _ -> false) (List.filteri (fun i _ -> i < eq) index.keys) | Plan.Scan | Plan.Ordered _ | Plan.Probe _ -> false in (* [a]'s equalities, binding [index]'s first [eq] columns, then the range sqlite3 reads of its next column *) let ranged (index : index) eq ~low best = let keys = match a with Plan.Seek { keys; _ } -> keys | _ -> [] in match Where_loop.range q with | None -> walk (Some index) best | Some (lo, hi) -> let lo, hi = range_answers keys ~lo ~hi in let past_null = low && lo = None in ( index_seek ~past_null gt ~covers ~index ~eq ~keys ~lo ~hi, Some best ) in (* the seek of [a] on its keys of the rowid alone *) let rowid_through best = match a with | Plan.Seek ({ table; keys; _ } as seek) -> ( let rowid (k : Plan.key) = match seek_index t ?where table [ k.column ] ~read with | Some (Seek.Rowid _) -> true | Some _ | None -> false in let keys = List.filter rowid keys in match index_path t ?where ~reads table (pairs keys) with | Some path when keys <> [] -> (Plan.Seek { seek with path; keys }, Some best) | Some _ | None -> (a, current)) | Plan.Scan | Plan.Ordered _ | Plan.Probe _ -> (a, current) in let a, kind = match (Where_loop.best q, current) with | (Where_loop.Full idx as best), _ -> walk (Some idx) best | ( (Where_loop.Search { index; eq; lo = false; hi = false; _ } as best), Some (Where_loop.Search { index = used; _ }) ) when used != index -> seek_through index eq best | ( (Where_loop.Search { index; eq; lo = false; hi = false; _ } as best), Some (Where_loop.Rowid_in | Where_loop.One_row) ) -> seek_through index eq best | (Where_loop.Rowid_in as best), Some (Where_loop.Search _) -> rowid_through best (* the range sqlite3 reads, after the equalities [a] seeks on, through the index it seeks or another its keys lead, or alone where [a] scans *) | ( (Where_loop.Search { index; eq; lo; hi; _ } as best), Some (Where_loop.Search { index = used; eq = n; _ }) ) when (lo || hi) && ((used == index && n = eq) || leads index eq) -> ranged index eq ~low:lo best | (Where_loop.Search { index; eq = 0; lo; hi; _ } as best), Some Scan when lo || hi -> ranged index 0 ~low:lo best | (Where_loop.Rowid_range _ as best), Some Where_loop.Scan -> ( match Where_loop.range q with | None -> (a, current) | Some (lo, hi) -> (rowid_range table lo hi, Some best)) (* a scan where the planner seeks a key sqlite3 does not, such as an IS NULL on a column that holds no NULL *) | ( (Where_loop.Scan as best), Some (Where_loop.Search _ | Where_loop.Rowid_in) ) when not own -> (Plan.Scan, Some best) (* a search this engine does not make, of a range it cannot bind, is in the order of a walk of its index the WHERE then filters *) | (Where_loop.Search { index; _ } as best), Some Where_loop.Scan -> walk (Some index) best | (Where_loop.Pk_search _ as best), Some Where_loop.Scan -> walk None best (* a WITHOUT ROWID table's own b-tree is walked by the plan, so its order, backwards too, is the one the rows come in *) | Where_loop.Scan, Some Where_loop.Scan when own -> walk None Where_loop.Scan | _ -> (a, current) in match kind with None -> (a, None) | Some kind -> sorted q a kind) (* Whether [a] seeks the values of an IN list, a loop of its own that a min/max query's first row stops once per value of (where.c, sqlite3WhereMinMaxOptEarlyOut: WHERE_COLUMN_IN). *) let keyed_by_list = function | Plan.Seek { keys; _ } -> List.exists (fun (k : Plan.key) -> match k.value with | Plan.In_list _ | Plan.In_select _ -> true | Plan.Const _ | Plan.Outer _ -> false) keys | Plan.Ordered _ | Plan.Scan | Plan.Probe _ -> false (* Whether [a] is a range of the rowid walked backwards, which the span cursor walks forwards: its rows come in ascending rowid order. *) let rowid_backwards = function | Plan.Seek { path = { index = None; _ }; range = Some _; reverse; _ } -> reverse | Plan.Seek _ | Plan.Ordered _ | Plan.Scan | Plan.Probe _ -> false (* Whether [a] is the seek sqlite3 plans a select of the one table [table] by without weighing a loop (where.c, whereShortCut): the rowid, or every column of a unique index that holds every row, bound by an equality to a value of no row of the table, so it reads one row, which is in every order. An IS key, whose NULL reaches every NULL entry, is weighed. A key on the rowid is sought on the rowid before any index ({!seek_index}), as sqlite3 tries it first. *) let one_row t table (a : Plan.access) = match a with | Plan.Seek { path = { unique = true; index; _ }; keys; range = None; _ } -> ( List.for_all (fun (k : Plan.key) -> match k.value with | Plan.Const _ -> not k.nulls | Plan.Outer _ | Plan.In_list _ | Plan.In_select _ -> false) keys && match index with | None -> true | Some name -> List.exists (fun (idx : index) -> ident_equal idx.name name && idx.where = None) (gtable t table).indexes) | _ -> false (* {!ordered_loop}, with a min/max query's order weighed for the loop it reads and none left to sort: the loop stops at its first row where it yields the argument's order, except through an IN list ({!keyed_by_list}). *) let ordered t ?where ~reads table (s : Ast.select) (a : Plan.access) = let a, sort = ordered_loop t ?where ~reads table s a in match Query.min_max s with | None -> (a, sort, None) | Some _ -> (* a scan, and a range of the rowid, walk the table forwards only, so the order they are said to yield backwards is no first row *) let stops = match a with | Plan.Seek _ -> not (keyed_by_list a || rowid_backwards a) | Plan.Ordered _ -> true | Plan.Scan | Plan.Probe _ -> false in let first = match sort with | Some { Plan.terms; sorted } -> sorted = terms && stops | None -> false in (a, None, Some (if first then Plan.First_row else Plan.Every_row)) (* The access the loop [step] over [s] is, [probe] the hash its automatic index stands for, keyed on the column [constant] where a constant keys it; [Exit] where it is none this store runs. *) let step_access t ?where ~reads ~probe (s : Where_loop.source) step = let table = s.gt.schema.tbl_name in match step with | Where_loop.Table_scan -> Plan.Scan | Index_scan idx -> Plan.Ordered { table; index = Some idx.name; covering = s.covers idx; reverse = false; } | Rowid_eq k -> ( let keys = named s [ (List.length s.names, k) ] in match index_path t ?where ~reads table (pairs keys) with | Some path -> Plan.Seek { table; path; keys; range = None; reverse = false } | None -> raise Exit) | Index_search { index; keys; lo; hi; past_null } -> index_search s ~index ~keys ~lo ~hi ~past_null | Rowid_range (lo, hi) -> rowid_range table lo hi | Auto_index { columns; partial; bloom; constant } -> ( let constant = match columns with | first :: _ when constant -> List.find_index (fun c -> String.equal c first) s.names | _ -> None in match probe ?constant () with | Some (Plan.Probe p) -> Plan.Probe { p with auto = Some { columns; partial; bloom } } | Some _ | None -> raise Exit) (* The last source a RIGHT or FULL join of [s] keeps the rows of, [-1] for none: every source before it is left of such a join (JT_LTORJ). *) let last_kept (s : Ast.select) = List.fold_left (fun last (p, (j : Ast.join)) -> match j.Sql.Ast.type_ with Ast.Right | Ast.Full -> p | _ -> last) (-1) (List.mapi (fun p j -> (p + 1, j)) s.Sql.Ast.joins) (* Whether {!Where_loop.join} weighs the join [s]: inner, outer and EXISTS joins, with no window; grouped by a GROUP BY, made distinct, or sorted by an ORDER BY of rows not folded into one, or neither. *) let modelled_join (s : Ast.select) = let aggregate = Query.is_aggregate_query s in s.compound = [] && Query.select_windows s = [] && if s.group_by <> [] then not s.distinct else s.having = None && ((s.order_by = [] && not s.distinct) || not aggregate) (* The columns of the table [name] where the store holds one by that name, and none otherwise, which {!Plan.read_columns} reads as binding nothing. *) let known_columns t name = match table_column_names t name with | cols -> cols | exception Catalog.Error _ -> [] (* The sources of the join [s] as {!Where_loop.join} weighs them, or [None] where one is not a rowid table this store addresses or the join is not one it weighs ({!modelled_join}). [read] is what each source is read for ({!reads}), as sqlite3 counts a cursor's columns: a table joined to itself is two sources and two answers. *) let join_sources t ~read (s : Ast.select) (layout : Plan.layout) refs = let modelled = modelled_join s && List.length refs = List.length layout in let kind i = if i = 0 then Ast.Inner else (List.nth s.joins (i - 1)).Sql.Ast.type_ in let kept = last_kept s in let source i (tr : Ast.table_ref option) = match tr with | Some tr when seekable_source t tr <> None -> ( match plain_rowid_gtable t tr.Sql.Ast.name with | Some gt -> let read = read.(i) in Some { Where_loop.gt; names = table_column_names t gt.schema.tbl_name; alias = Option.value tr.alias ~default:tr.name; covers = (fun idx -> Seek.covers gt idx ~read); left = (match kind i with Ast.Left | Full -> true | _ -> false); right = (match kind i with Ast.Right | Full -> true | _ -> false); ltorj = i < kept; cross = kind i = Ast.Cross; (* by its alias, which names the table an EXISTS joined wherever it stands, the FROM of a select that had none included ({!Plan.v}) *) exists = Resolve.is_semi_alias (Option.value tr.alias ~default:tr.name); } | None -> None) | Some _ | None -> None in if not modelled then None else let srcs = List.mapi source refs in if List.exists Option.is_none srcs then None else Some (Array.of_list srcs) (* The conjuncts of the WHERE of [s] and of its ONs, each with where it applies: an outer join's ON to its own source; where a RIGHT or FULL join is one of them, an inner join's ON to its own source too, which sqlite3 marks EP_InnerON; any other to the whole join. A NATURAL or USING join is planned as the ON it stands for, as sqlite3 plans it (sqlite3ProcessJoin). A written ON is a term whatever it holds, an ON 1 included, and a comma join adds none. *) let join_conjuncts (s : Ast.select) (layout : Plan.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) (* The columns of the result of [s] over [layout], a star counted as the columns it stands for, which whereSortingCost weighs. *) let result_width (s : Ast.select) (layout : Plan.layout) = List.fold_left (fun n (rc : Ast.result_col) -> match rc.expr with | Ast.Star -> n + List.fold_left (fun m (a, cols) -> if Resolve.is_semi_alias a then m else m + List.length cols) 0 layout | Ast.Qualified_star q -> ( match List.find_opt (fun (a, _) -> Ast.ident_equal a q) layout with | Some (_, cols) -> n + List.length cols | None -> n + 1) | _ -> n + 1) 0 s.cols (* [a] walking its relation backwards, as an ORDER BY a loop answers in descending order needs: a walk of the rowid answers a key no two rows share, so its rows come in the same order whichever way it goes. *) let backwards = function | Plan.Ordered o -> Plan.Ordered { o with reverse = true } | Plan.Seek ({ path = { index = Some _; _ }; _ } as k) -> Plan.Seek { k with reverse = true } | a -> a (* The result columns of [s] over [layout], a star standing for the columns it names. *) let result_exprs (s : Ast.select) (layout : Plan.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 (* How the rows of a join come out of its loop: the order the solver weighs, in its mode, the orders it rereads the chosen loops against, and what the plan then sorts, groups or keeps distinct (select.c: a GROUP BY or a DISTINCT whose ORDER BY is its result list groups through the loop or a sorter, the ORDER BY then needing no sort where it is the grouping's order; any other DISTINCT asks the loop for its result columns, or for its ORDER BY and then rereads them). *) type join_order = { keys : (Ast.expr * bool) list; mode : Where_loop.mode; want_distinct : bool; limit : int option; checks : ((Ast.expr * bool) list * Where_loop.mode) list; finish : Where_loop.nested -> Plan.sort option * [ `Loop | `Temp of [ `Group_by | `Distinct ] ] option * int list; } let order_by (s : Ast.select) = List.map (fun (e, d) -> (e, d = Ast.Desc)) s.order_by let sort_of (s : Ast.select) ~sorted = if s.order_by = [] then None else Some { Plan.terms = List.length s.order_by; sorted } (* A GROUP BY of [group], or a DISTINCT turned into one, labelled [temp] where a sorter groups the rows. *) let grouped_order (s : Ast.select) group ~mode ~temp = let ob = order_by s in let n = List.length group in let keys, by_group = if ob <> [] && List.length ob = n then ( List.map2 (fun e (_, d) -> (e, d)) group ob, List.for_all2 (fun e (o, _) -> Ast.equal_expr e o) group ob ) else (List.map (fun e -> (e, false)) group, false) in let finish (nested : Where_loop.nested) = let looped = nested.in_order = n in let rechecked = match nested.checked with c :: _ -> Some c | [] -> None in let sorted_by_loop = looped && match rechecked with Some (m, _) -> m = n | None -> false in let sorted = by_group && ((not looped) || sorted_by_loop) in ( (if sorted then None else sort_of s ~sorted:0), Some (if looped then `Loop else `Temp temp), if sorted_by_loop then snd (Option.get rechecked) else nested.backwards ) in { keys; mode; want_distinct = false; limit = None; checks = (if by_group then [ (keys, Where_loop.Sort) ] else []); finish; } let rows_order (s : Ast.select) (layout : Plan.layout) = let result = result_exprs s layout in let plain keys mode ~want_distinct ~checks finish = { keys; mode; want_distinct; limit = Where_loop.fixed_limit s; checks; finish; } in let ob = order_by s in if s.group_by <> [] then grouped_order s s.group_by ~mode:Group ~temp:`Group_by else if not s.distinct then plain ob Sort ~want_distinct:false ~checks:[] (fun n -> (sort_of s ~sorted:n.in_order, None, n.backwards)) else if ob <> [] && List.length ob = List.length result && List.for_all2 (fun e (o, _) -> Ast.equal_expr e o) result ob then grouped_order s result ~mode:Distinct ~temp:`Distinct else if ob = [] then plain (List.map (fun e -> (e, false)) result) Distinct ~want_distinct:true ~checks:[] (fun n -> ( None, Some (if n.in_order = List.length result then `Loop else `Temp `Distinct), n.backwards )) else plain ob Sort ~want_distinct:true ~checks:[ (List.map (fun e -> (e, false)) result, Distinct) ] (fun n -> let distinct_ok = match n.checked with | (m, _) :: _ -> m = List.length result | [] -> false in ( sort_of s ~sorted:n.in_order, Some (if distinct_ok then `Loop else `Temp `Distinct), n.backwards )) (* {!rows_order}, but for a min/max query, whose loop is asked for the order of its argument in place of an ORDER BY, under no LIMIT (select.c, minMaxQuery), and leaves nothing to sort. *) let join_order (s : Ast.select) (layout : Plan.layout) = match Query.min_max s with | Some (arg, kind, distinct) -> { keys = [ (arg, kind = `Max) ]; mode = Min_max; want_distinct = distinct; limit = None; checks = []; finish = (fun n -> (None, None, n.backwards)); } | None -> rows_order s layout (* The sources of [layout] [e] reads, through the subqueries it holds too: a column a subquery's own FROM does not bind is one of [layout]'s. *) 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 Plan.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 (* The join [s] nested as sqlite3's planner nests it ({!Where_loop.join}), each source read through the loop it chose, or [None] where the join is not one it models ({!join_sources}). *) let rec join_plan t ?where ~reads ~read (s : Ast.select) (layout : Plan.layout) = (* a select with no FROM that joins an EXISTS is planned over the tables it joins, without the constant row's slot ({!Plan.v}), while [read] holds a set for that slot too *) let read = let n = List.length layout in if Array.length read = n + 1 then Array.sub read 1 n else read in let refs = (match s.Sql.Ast.from with Ast.Table tr -> Some tr | _ -> None) :: List.map (fun (j : Ast.join) -> Some j.Sql.Ast.table) s.joins in (* one table is planned here where it is grouped or made distinct, which the single-table model ({!Where_loop.v}) does not weigh *) let grouped = s.group_by <> [] || s.distinct in if List.length refs = 1 && not grouped then None else Option.bind (join_sources t ~read s layout refs) @@ fun srcs -> let conjuncts = join_conjuncts s layout in let gt i = (Option.get srcs.(i)).Where_loop.gt in let column_affinity i j = let cols = (gt i).schema.columns in if j < List.length cols then Some (List.nth cols j).type_affinity else Some `Integer in let collation i j = Decl.declared_collation (gt i).schema.columns j in let subquery = closed_subquery t in let jo = join_order s layout in Option.bind (Where_loop.join ~order:jo.keys ~mode:jo.mode ~want_distinct:jo.want_distinct ~checks:jo.checks ~width:(result_width s layout) ?limit:jo.limit srcs ~position:(Plan.position layout) ~column_affinity ~collation ~subquery ~outer:(fun sub -> outer_reads (Query.resolve_env (catalog t)) layout (Ast.Exists sub)) conjuncts) @@ fun nested -> let kept = last_kept s >= 0 in (* a RIGHT or FULL join yields its rows in no order: what an ORDER BY, a GROUP BY or a DISTINCT asks is sorted (where.c, sqlite3WhereBegin, nOBSat and eDistinct) *) let ordered_rows = if not kept then nested else { nested with in_order = 0; checked = List.map (fun (_, b) -> (0, b)) nested.checked; } in let sort, grouping, backs = jo.finish ordered_rows in let steps = nested.nest in let inner = List.filter_map (function e, (`Where | `Inner_on _) -> Some e | _, `On _ -> None) conjuncts in let affinity = Plan.column_affinity ~affinity:(catalog_affinity t) (Query.resolve_env (catalog t)) s layout in let preds = inner @ Plan.equality_closure layout ~affinity inner in let n = Array.length srcs in let accesses = Array.make n Plan.Scan in let seen = Array.make n false in (* a table an outer join pads, or one left of a RIGHT or FULL join, is keyed and filtered by its own ON alone: a WHERE term on it is tested on the padded row too, so the rows it drops are no rows of a build (where.c, constraintCompatibleWithOuterJoin) *) (* the table a RIGHT or FULL join keeps is read through its own b-tree, where the rowid of each row its ON matched is recorded (where.c, sqlite3WhereBegin, WHERE_IDX_ONLY cleared) *) let kept_read (s : Where_loop.source) = if s.right then { s with covers = (fun _ -> false) } else s in let probe i ?constant () = let preds = match srcs.(i) with | Some s when Where_loop.restricted s -> List.filter_map (function | e, (`On j | `Inner_on j) when j = i -> Some e | _ -> None) conjuncts | Some _ | None -> preds in Plan.probe ?constant layout ~earlier:(fun k -> k >= 0 && k < n && seen.(k)) i (List.nth refs i) preds in match List.iter (fun (i, step) -> let a = step_access t ?where ~reads ~probe:(probe i) (kept_read (Option.get srcs.(i))) step in accesses.(i) <- (if List.mem i backs then backwards a else a); seen.(i) <- true) steps with | exception Exit -> None | () -> (* a min/max query's loop stops at its first row where the loops yield the argument in order (where.c, bOrderedInnerLoop), each loop asked to walk backwards able to, and none through an IN list *) let min_max = Option.map (fun _ -> let reversed i = match accesses.(i) with | Plan.Ordered { reverse; _ } | Plan.Seek { reverse; _ } -> reverse | Plan.Scan | Plan.Probe _ -> false in if nested.in_order = 1 && List.for_all reversed backs && not (Array.exists keyed_by_list accesses) then Plan.First_row else Plan.Every_row) (Query.min_max s) in Some { Plan.accesses = Array.to_list accesses; order = List.map fst steps; sort; min_max; grouping; unmatched = List.filter_map (fun i -> match srcs.(i) with | Some { Where_loop.right = true; ltorj; _ } -> Some ( i, unmatched_loop t ~read:read.(i) s layout i (Option.get (List.nth refs i)) ~ltorj ) | Some _ | None -> None) (List.init n Fun.id); } and plan_facts t ?where ~reads ~read () : Plan.facts = { columns = (fun name -> table_column_names t name); seekable = plan_seekable t; best_index = index_path t ?where ~reads; affinity = catalog_affinity t; collation = R.collation t; row_count = table_row_count t; seek_answers_rowid = true; const_subquery = false; seek_lists = true; ordered = (fun table s a -> if one_row t table a then (a, None, None) else ordered t ?where ~reads table s a); join = join_plan t ?where ~reads ~read; } (* The loop over the rows of the table [tr] at [i] a RIGHT or FULL join of [s] kept unmatched: that table alone, planned as one table under the conjuncts of the WHERE that read nothing past it, each table before it read as NULL, as every cursor before it stands on its NULL row; none where it is left of another such join (where.c, sqlite3WhereRightJoinLoop). *) and unmatched_loop t ~read (s : Ast.select) (layout : Plan.layout) i (tr : Ast.table_ref) ~ltorj = let env = Query.resolve_env (catalog t) in let before e = List.for_all (fun k -> k <= i) (outer_reads env layout e) in let rec nulled (e : Ast.expr) = match e with | Ast.Col (q, c) -> ( match Plan.position layout q c with | Some (k, _) when k < i -> Ast.Lit Ast.Null | _ -> e) | e -> Ast.map_expr ~select:Fun.id nulled e in let rec conjuncts acc = function | Ast.Binary (Ast.And, a, b) -> conjuncts (conjuncts acc a) b | e -> e :: acc in let sub = if ltorj then [] else List.rev (Option.fold ~none:[] ~some:(conjuncts []) s.Sql.Ast.where) |> List.filter (fun e -> before e && not (Ast.holds_select e)) |> List.map nulled in let where = match sub with | [] -> None | e :: es -> Some (List.fold_left (fun a b -> Ast.Binary (Ast.And, a, b)) e es) in let one : Ast.select = { Sql.Ast.ctes = []; distinct = false; cols = [ { Ast.expr = Ast.Lit (Ast.Int 1L); alias = None } ]; from = Ast.Table tr; joins = []; where; group_by = []; having = None; compound = []; order_by = []; limit = None; offset = None; } in let plan = Plan.v (plan_facts t ?where ~reads:(fun _ -> read) ~read:[| read |] ()) env ~bound:[] one [ List.nth layout i ] in List.hd plan.Plan.accesses (* The table each source of [s] reads, in scan order, [None] for a source that reads none the store addresses. *) let source_tables t (s : Ast.select) = (match s.Sql.Ast.from with Ast.Table tr -> plan_seekable t tr | _ -> None) :: List.map (fun (j : Ast.join) -> plan_seekable t j.Sql.Ast.table) s.Sql.Ast.joins (* What [s] reads from each source [layout] names, as positions in that source's own columns ({!Plan.read_columns}), and the table each source reads ({!source_tables}). A plan, its seeks and its cursors are all made from these, worked out once per plan: walking [s] for them is a name lookup per column reference. *) type reads = { read : int list array; tables : string option list } let reads t (s : Ast.select) layout = { read = Plan.read_columns ~columns:(known_columns t) layout s; tables = source_tables t s; } (* What the query reads from each table, as positions in that table's own columns. A path is offered per table and not per source, so two sources over one table share an answer: the union is what the index has to hold, which declines a covering read one of them alone could have had and never claims one neither can. *) let table_reads { read; tables } table = List.concat (List.filteri (fun i _ -> match List.nth_opt tables i with | Some (Some n) -> ident_equal n table | Some None | None -> false) (Array.to_list read)) (* The plan for [s] over the sources [layout] names. [bound] names the relations a WITH clause binds, which the engine materialises and which are therefore never asked of the store. *) (* [a] with the keys its path does not bind made inert, the path being the one the cursor reads ({!seek_index}): an IN key is dropped, since a seek walks the values of each IN it keys on and one it does not key on is a conjunct the loop tests, and a key answers no conjunct ({!Plan.key.answers}), since the rows the path yields need not satisfy it. *) let rec bound_keys t ?where ~reads (a : Plan.access) = let set (k : Plan.key) = match k.value with | Plan.In_list _ | Plan.In_select _ -> true | Plan.Const _ | Plan.Outer _ -> false in match a with | Plan.Seek ({ table; path; keys; _ } as k) when List.exists (fun (k : Plan.key) -> set k || k.answers <> None) keys -> let cols = match seek_index t ?where ?index:path.Plan.index table (columns keys) ~read:(reads table) with | Some (Seek.Rowid c) -> Some [ c ] | Some (Seek.Index (_, _, cols) | Seek.Primary_key (_, _, cols)) -> Some cols | None -> None in let bound (k : Plan.key) = match cols with Some cols -> mem_ident k.column cols | None -> false in Plan.Seek { k with keys = List.filter_map (fun (k : Plan.key) -> if bound k then Some k else if set k && cols <> None then None else Some { k with answers = None }) keys; } | Plan.Probe p -> Plan.Probe { p with spill = Option.map (bound_keys t ?where ~reads) p.spill; stands_for = Option.map (bound_keys t ?where ~reads) p.stands_for; } | a -> a (* The b-tree sqlite3 opens for each DISTINCT aggregate of [s] as it resets its accumulators, USE TEMP B-TREE FOR f(DISTINCT), in the order it analyses the aggregates, each once: the result columns', the ORDER BY's, the HAVING's (select.c, resetAccumulator). The lone aggregate of a select with no GROUP BY keeps none where the loop yields its argument unique or in order (fixDistinctOpenEph): the argument is the rowid of the one table read, or the next key of the index [plan] walks or seeks through. *) let distinct_lines t (s : Ast.select) ~(plan : Plan.t option) = let aggs = ref [] in let rec go e = if Query.is_agg_expr e then ( if not (List.exists (Ast.equal_expr e) !aggs) then aggs := !aggs @ [ e ]) else match e with | Ast.Window _ -> () | e -> Ast.fold_expr ~select:(fun () _ -> ()) (fun () x -> go x) () e in List.iter go (List.map (fun (rc : Ast.result_col) -> rc.expr) s.Sql.Ast.cols @ List.map fst s.order_by @ Option.to_list s.having); let rec distinct = function | Ast.Distinct_agg (n, a) -> Some (n, a) | Ast.Filter (f, _) | Ast.Ordered_agg (f, _) -> distinct f | _ -> None in let key_of (gt : generic_table) idx k = match List.find_opt (fun (i : index) -> i.name = idx) gt.indexes with | Some i -> ( match List.nth_opt i.keys k with | Some (Column cid) -> Some (List.nth gt.schema.columns cid).name | _ -> None) | None -> None in let in_order arg = match (s.from, s.joins, arg) with | Ast.Table { subquery = None; name; _ }, [], Ast.Col (_, c) -> ( match gtable t name with | exception Catalog.Error _ -> false | gt -> ( let names = List.map (fun (c : column) -> c.name) gt.schema.columns in let rowid = Ast.is_rowid_name c || match Decl.rowid_alias gt.schema with | Some p -> ident_equal (List.nth names p) c | None -> false in let next = match plan with | Some { Plan.accesses = [ Plan.Ordered { index = Some i; _ } ]; _; } -> key_of gt i 0 | Some { Plan.accesses = [ Plan.Seek { path = { index = Some i; bound; _ }; _ } ]; _; } -> key_of gt i bound | Some _ | None -> None in rowid || match next with Some k -> ident_equal k c | None -> false)) | _ -> false in let kept = match !aggs with | [ e ] when s.group_by = [] -> ( match distinct e with Some (_, a) -> not (in_order a) | None -> true) | _ -> true in List.filter_map (fun e -> match distinct e with | Some (n, _) when kept -> Some (Fmt.kstr Eqp.leaf "USE TEMP B-TREE FOR %s(DISTINCT)" (String.lowercase_ascii n)) | Some _ | None -> None) !aggs (* The subquery [sub] of a select whose WITH tables are [ctes], numbered from [first], with those tables as its own where it reads one it does not bind itself, as sqlite3 resolves a name against the WITH of each enclosing select (select.c, sqlite3WithPush): explained on its own, it would read an unknown table. The numbering starts that much earlier, so the subquery's own selects keep their numbers. *) let with_outer_ctes ctes ~first (sub : Ast.select) = let own (c : Ast.cte) = List.exists (fun (c' : Ast.cte) -> Catalog.Ident.equal c.name c'.name) sub.Sql.Ast.ctes in let outer = List.filter (fun c -> not (own c)) ctes in if not (List.exists (fun (c : Ast.cte) -> Query.reads_table c.Sql.Ast.name sub) outer) then (first, sub) else ( first - List.fold_left (fun n (c : Ast.cte) -> n + 1 + Eqp.count c.query) 0 outer, { sub with ctes = outer @ sub.ctes } ) (* The line sqlite3 scans a VALUES list of [rows] under: one row is a CONSTANT ROW, more a VALUES clause (parse.y, sqlite3MultiValues). *) let values_line = function | [ _ ] -> "CONSTANT ROW" | rows -> Fmt.str "%d-ROW VALUES CLAUSE" (List.length rows) (* The VALUES clause [q] is where it is a bare list of more than one row, which sqlite3 reads in place of a subquery of it. *) let values_clause (q : Ast.select) = match (q.from, q.cols, q.joins, q.compound) with | Ast.Values (_ :: _ :: _ as rows), [ { expr = Ast.Star; _ } ], [], [] when q.where = None && q.ctes = [] -> Some (values_line rows) | _ -> None (* The FROM subqueries of [s], each with its place among the items, the alias it is read under and its select; a table-valued function a join reads is held as a subquery of it and is none, and so is a VALUES clause the FROM reads. *) let from_subqueries (s : Ast.select) = let function_table (q : Ast.select) = match (q.from, q.cols, q.joins) with | Ast.Table_function _, [ { expr = Ast.Star; _ } ], [] -> true | _ -> false in (match s.Sql.Ast.from with | Ast.Select { fs_select; _ } when values_clause fs_select <> None -> [] | Ast.Select { fs_select; fs_alias } -> [ (0, fs_alias, fs_select) ] | _ -> []) @ List.concat (List.mapi (fun k (j : Ast.join) -> match j.Sql.Ast.table.subquery with | Some q when not (function_table q) -> [ (k + 1, j.table.alias, q) ] | Some _ | None -> []) s.joins) end