(*--------------------------------------------------------------------------- Copyright (c) 2026 Thomas Gazagnaire. All rights reserved. SPDX-License-Identifier: ISC ---------------------------------------------------------------------------*) open Model include Where_terms (* What sqlite3 makes of the conjuncts of a join (whereexpr.c, exprAnalyze): each conjunct, with the sources it reads, and each comparison of a column of one source with a value the others give, under the affinity and collating sequence the comparison takes, as a term a loop over that source can key on -- either operand of an equality between two columns, the second as exprAnalyze's commuted copy. A table an outer join pads or keeps, or one left of a RIGHT or FULL join, keys on its own ON alone ({!keyable}, constraintCompatibleWithOuterJoin). select.c's constant propagation fixes a column a WHERE equates to a literal, and two columns an equality makes equivalent share their terms but an outer join's ON (whereScan's transitive terms), each term then keying the other column too as the conjunct it came from. *) let join_terms srcs ~position ~column_affinity ~collation ~subquery ~outer conjuncts = let env = { srcs; position; column_affinity; collation; subquery; outer } in let fixed = propagated env conjuncts in let c = { next = 0; conjs = []; direct = []; commuted = []; edges = [] } in List.iteri (analyze env fixed c) conjuncts; let own = List.rev c.direct @ c.commuted in (List.rev c.conjs, own @ transitive env c own) (* whereLoopOutputAdjust: each conjunct that reads the loop's source and only sources the loop has in place, and that the loop does not key on, costs a row; an unused equality caps the rows below the table's. *) let adjust_join conjs ~self (l : jloop) rows = let allowed = l.prereq lor self in let reduce = ref 0 and out = ref l.out in List.iter (fun c -> if c.reads land lnot allowed = 0 && c.reads land self <> 0 && not (List.exists (fun (t : uterm) -> t.conj = c.id) l.terms) then begin decr out; match c.eq with Some k -> reduce := max !reduce k | None -> () end) conjs; { l with out = min !out (rows - !reduce) } (* whereLoopCheaperProperSubset *) let proper_subset (x : jloop) (y : jloop) = if x.run > y.run && x.out > y.out then false else if x.neq < y.neq && x.index == y.index then true else if List.length x.terms >= List.length y.terms then false else List.for_all (fun (t : uterm) -> List.exists (fun (u : uterm) -> u.key = t.key) y.terms) x.terms && not (x.covering && not y.covering) (* whereLoopInsert over the loops of one source: [l]'s cost first moved past each index loop it is a cheaper proper subset of or that is one of it (whereLoopAdjustCost); then dropped where a loop needing no more sources costs no more, set up included, and yields no more rows; else written over the first loop it beats so -- an automatic index giving way to any equality through an index -- and over every later one it beats too (whereLoopFindLesser); else added last. *) let insert_join loops (l : jloop) = let l = if l.index = None then l else List.fold_left (fun (l : jloop) (p : jloop) -> if p.index = None then l else if proper_subset p l then { l with run = min p.run l.run; out = min (p.out - 1) l.out } else if proper_subset l p then { l with run = max p.run l.run; out = max (p.out + 1) l.out } else l) l loops in let replaces (p : jloop) = p.auto && l.index <> None && l.column_eq && p.prereq land l.prereq = l.prereq || (p.prereq land l.prereq = l.prereq && p.run >= l.run && p.out >= l.out) in let beaten_by (p : jloop) = p.prereq land l.prereq = p.prereq && p.setup <= l.setup && p.run <= l.run && p.out <= l.out in (* each later loop [l] also beats goes, up to one that beats [l] *) let rec rest = function | [] -> [] | p :: ps -> if p.sort_idx <> l.sort_idx then p :: rest ps else if p.auto && l.index <> None && l.column_eq && p.prereq land l.prereq = l.prereq then rest ps else if beaten_by p then p :: ps else if replaces p then rest ps else p :: rest ps in let rec find = function | [] -> Some [ l ] | p :: ps -> if p.sort_idx <> l.sort_idx then Option.map (fun r -> p :: r) (find ps) else if p.auto && l.index <> None && l.column_eq && p.prereq land l.prereq = l.prereq then Some (l :: rest ps) else if beaten_by p then None else if replaces p then Some (l :: rest ps) else Option.map (fun r -> p :: r) (find ps) in match find loops with Some loops -> loops | None -> loops (* The term [u] can key column [c] of an entry, the rowid or a column under the sequence [index_coll], whose affinity is [aff]: its collating sequence is the column's and its comparison one the index answers, which an IS NULL always is (whereScanNext checks neither for WO_ISNULL). *) let keys_column s (u : uterm) (c, _, index_coll) = u.col = c && (u.op = Is_null || let rowid = c = List.length s.names in let coll_ok = rowid || match index_coll with | None -> true | Some ic -> let declared = Option.value ~default:Sql.Collation.default (Decl.declared_collation s.gt.schema.columns c) in Sql.Collation.equal ic (Option.value u.coll ~default:declared) in let aff = if rowid then `Integer else (List.nth s.gt.schema.columns c).type_affinity in coll_ok && affinity_ok u.aff aff) (* columnIsGoodIndexCandidate: a column an automatic index is worth building on is the first key column of no index of its table. *) let auto_candidate s col = not (List.exists (fun (idx : index) -> match idx.keys with Column c :: _ -> c = col | _ -> false) s.gt.indexes) (* What whereLoopAddBtree builds the loops of source [i] from: the source, its terms, the sources [mprereq] it needs in place before it, and the loops kept so far. *) type builder = { i : int; self : int; s : source; t : t; nrows : Log_est.t; log_nrows : Log_est.t; mine : uterm list; mprereq : int; conjs : conjunct list; sorts_by : int list option; (** the columns of the source an ORDER BY sorts by, if it has one *) mutable loops : jloop list; } (* The affinities sqlite3 applies to the value of [u], keying a column of affinity [column], before the seek (wherecode.c, codeAllEqualityTerms): the fixed column's first, then the index column's, none where the comparison converts neither operand, the comparison's own for a subquery's rows. *) let key_affinity (column : Plan.affinity) (u : uterm) = let compared : Plan.affinity list = match (u.value, u.aff) with | Plan.In_list _, _ -> if column = `Blob then [] else [ column ] | Plan.In_select _, `Text -> [ `Text ] | Plan.In_select _, `Numeric -> [ `Numeric ] | (Plan.Const _ | Plan.Outer _), (`Text | `Numeric) -> if column = `Blob then [] else [ column ] | _, (`Blob | `None) -> [] in Option.to_list u.fixed @ compared (* Whether [u] is its conjunct's own comparison as written, neither fixed by the propagation nor copied from an equivalent column, with an outer column, a literal, a list of literals or an uncorrelated subquery, which a seek on it answers exactly. *) let written (u : uterm) = (not u.copied) && u.fixed = None && u.conj >= 0 && Plan.valued u.value (* The conjunct a loop over the source of [b] keyed or bounded by [u] answers, where disableTerm drops it: a {!written} comparison, every row the seek selects satisfying it; a LEFT JOIN's padded table keys on its own ON alone, whose rows it pads where none does. The table of an EXISTS keeps its terms, which its loop stops on. *) let answer b (u : uterm) = if written u && not b.s.exists then match List.find_opt (fun c -> c.id = u.conj) b.conjs with | Some c when keyable b.s b.i c.on -> Some c.written | Some _ | None -> None else None (* The key [u] gives a loop over the source of [b]: its {!key_affinity} and the conjunct it {!answer}s. *) let seek_key b (u : uterm) = let column : Plan.affinity = if u.col >= List.length b.s.names then `Integer else (List.nth b.s.gt.schema.columns u.col).type_affinity in { value = u.value; affinity = key_affinity column u; nulls = u.op = Is || u.op = Is_null; answers = answer b u; } (* The bound [u] gives a loop over the source of [b] on the side it bounds. *) let bound_of b (u : uterm) inclusive = let column : Plan.affinity = if u.col >= List.length b.s.names then `Integer else (List.nth b.s.gt.schema.columns u.col).type_affinity in let affinity = match (u.aff, column) with | (`Blob | `None), _ | _, `Blob -> [] | (`Text | `Numeric), column -> [ column ] in { value = u.value; inclusive; affinity; answers = answer b u } (* a loop over the table of an EXISTS yields one row at most to the loops inside it, which sqlite3 weighs as nOut 0 (where.c, whereLoopAddBtree and whereLoopAddBtreeIndex); its automatic index keeps its estimate *) let add b l = let l = adjust_join b.conjs ~self:b.self l b.nrows in b.loops <- insert_join b.loops (if b.s.exists then { l with out = 0 } else l) let add_raw b l = b.loops <- insert_join b.loops l let loop b ?index ?(covering = false) ?(auto = false) ?(setup = 0) ?(sort_idx = 0) ~terms ~neq step ~prereq ~run ~out = { src = b.i; step; sort_idx; prereq; run; out; setup; terms; neq; index; covering; auto; column_eq = List.exists (fun (u : uterm) -> u.op = Equal || u.op = Is) terms; } (* an automatic index on each equality or IS that may drive one, but on a table a RIGHT or FULL join keeps (where.c, whereLoopAddBtree): one the source's own conjunct states, never one an equivalence copied (termCanDriveIndex reads the clause's terms, not whereScan's) *) let auto_loops b = List.iter (fun (u : uterm) -> if (not b.s.right) && (u.op = Equal || u.op = Is) && (not u.copied) && u.col < rowid_column b.t && u.prereq land b.self = 0 && affinity_ok u.aff (List.nth b.s.gt.schema.columns u.col).type_affinity && auto_candidate b.s u.col then add_raw b (loop b ~auto:true ~setup:(max 0 (b.log_nrows + b.nrows + 28)) ~terms:[ u ] ~neq:1 (Auto_index { columns = []; partial = false; bloom = false; constant = false; }) ~prereq:(b.mprereq lor u.prereq) ~run:(Log_est.add b.log_nrows 43) ~out:43)) b.mine (* the rowid's iSortIdx: 1 where an ORDER BY term is the rowid *) let rowid_sort_idx b = match b.sorts_by with | Some cols when List.mem (rowid_column b.t) cols -> 1 | _ -> 0 let bound b (u : uterm) inclusive = Some (bound_of b u inclusive) (* the rowid ranges from the lower bound [u] *) let rowid_from b on_rowid (u : uterm) incl ~prereq = let out = range_out b.nrows ~lo:true ~hi:false in add b (loop b ~sort_idx:(rowid_sort_idx b) ~terms:[ u ] ~neq:0 (Rowid_range (bound b u incl, None)) ~prereq ~run:(Log_est.add b.log_nrows (out + 16)) ~out); List.iter (fun (v : uterm) -> match v.op with | Upper incl' when v.prereq land b.self = 0 -> let out = range_out b.nrows ~lo:true ~hi:true in add b (loop b ~sort_idx:(rowid_sort_idx b) ~terms:[ u; v ] ~neq:0 (Rowid_range (bound b u incl, bound b v incl')) ~prereq:(prereq lor v.prereq land lnot b.self) ~run:(Log_est.add b.log_nrows (out + 16)) ~out) | _ -> ()) on_rowid (* the table scan, then the rowid's equalities and ranges *) let rowid_loops b = add b (loop b ~sort_idx:(rowid_sort_idx b) ~terms:[] ~neq:0 Table_scan ~prereq:b.mprereq ~run:(b.nrows + 16) ~out:b.nrows); let on_rowid = List.filter (fun u -> keys_column b.s u (rowid_column b.t, false, None)) b.mine in List.iter (fun (u : uterm) -> if u.prereq land b.self = 0 then let prereq = b.mprereq lor u.prereq land lnot b.self in match u.op with (* the rowid holds no NULL: an IS keys it as an equality, an IS NULL and an IS NOT NULL not at all (indexColumnNotNull) *) | Is_null | Past_null -> () | Equal | Is -> add b (loop b ~sort_idx:(rowid_sort_idx b) ~terms:[ u ] ~neq:1 (Rowid_eq (seek_key b u)) ~prereq ~run:(Log_est.add b.log_nrows 16) ~out:0) | In_list n -> let nin = Log_est.v n in add b (loop b ~sort_idx:(rowid_sort_idx b) ~terms:[ u ] ~neq:1 (Rowid_eq (seek_key b u)) ~prereq ~run:(Log_est.add b.log_nrows 16 + nin) ~out:nin) | Lower incl -> rowid_from b on_rowid u incl ~prereq | Upper incl -> let out = range_out b.nrows ~lo:false ~hi:true in add b (loop b ~sort_idx:(rowid_sort_idx b) ~terms:[ u ] ~neq:0 (Rowid_range (None, bound b u incl)) ~prereq ~run:(Log_est.add b.log_nrows (out + 16)) ~out)) on_rowid (* One index's searches: its entries' columns, keys then rowid, and the cost of a search that yields a number of rows. *) type searched = { ix : index; holds : bool; sidx : int; entry : (int * bool * Sql.Collation.t option) array; price : Log_est.t -> Log_est.t; } (* A search so far: [equated] columns equated by [used] to [keyed], yielding [yields] rows, [fanout] times over for its IN lists, needing the sources [needs], and [floor] the lower bound of the next column, if any. *) type partial = { equated : int; yields : Log_est.t; needs : int; used : uterm list; keyed : (int * sought) list; fanout : Log_est.t; floor : (uterm * bool) option; } (* the search [p] with the upper bound [u] on its next column *) let search_upper b x p (u : uterm) incl ~prereq = let past_null = match p.floor with Some (l, _) -> l.op = Past_null | None -> false in let lo = if past_null then None else Option.map (fun ((l : uterm), i) -> bound_of b l i) p.floor in let out = range_out ~vnull:past_null p.yields ~lo:(p.floor <> None) ~hi:true in add b (loop b ~index:x.ix ~sort_idx:x.sidx ~covering:x.holds ~terms:(p.used @ [ u ]) ~neq:p.equated (Index_search { index = x.ix; keys = p.keyed; lo; hi = Some (bound_of b u incl); past_null; }) ~prereq ~run:(x.price out + p.fanout) ~out:(out + p.fanout)) (* whereLoopAddBtreeIndex: the search [p] extended by each term on its next column, an equality or IN after another and then a range *) let rec search b x p = if p.equated < Array.length x.entry then List.iter (fun (u : uterm) -> if keys_column b.s u x.entry.(p.equated) && u.prereq land b.self = 0 then extend b x p u) b.mine and extend b x p (u : uterm) = let prereq = p.needs lor u.prereq land lnot b.self in let c, _, _ = x.entry.(p.equated) in (* an IS NULL or an x > NULL on a column that holds no NULL is no key (indexColumnNotNull) *) match (u.op, p.floor) with | (Is_null | Past_null), _ when column_not_null b.s c -> () | (Equal | Is | Is_null | In_list _), None -> let nin = match u.op with In_list n -> Log_est.v n | _ -> 0 in (* an IS NULL is taken to match twice the rows of an equality *) let null = if u.op = Is_null then 10 else 0 in let out = p.yields + row_est b.nrows x.ix (p.equated + 1) - row_est b.nrows x.ix p.equated + null in let terms = p.used @ [ u ] and keys = p.keyed @ [ (c, seek_key b u) ] in add b (loop b ~index:x.ix ~sort_idx:x.sidx ~covering:x.holds ~terms ~neq:(p.equated + 1) (Index_search { index = x.ix; keys; lo = None; hi = None; past_null = false }) ~prereq ~run:(x.price out + p.fanout + nin) ~out:(out + p.fanout + nin)); search b x { p with equated = p.equated + 1; yields = out; needs = prereq; used = terms; keyed = keys; fanout = p.fanout + nin; } | (Lower _ | Past_null), None -> let past_null = u.op = Past_null in let incl = match u.op with Lower incl -> incl | _ -> false in let out = range_out ~vnull:past_null p.yields ~lo:true ~hi:false in let lo = if past_null then None else Some (bound_of b u incl) in add b (loop b ~index:x.ix ~sort_idx:x.sidx ~covering:x.holds ~terms:(p.used @ [ u ]) ~neq:p.equated (Index_search { index = x.ix; keys = p.keyed; lo; hi = None; past_null }) ~prereq ~run:(x.price out + p.fanout) ~out:(out + p.fanout)); search b x { p with needs = prereq; used = p.used @ [ u ]; floor = Some (u, incl) } | Upper incl, _ -> search_upper b x p u incl ~prereq | (Equal | Is | Is_null | In_list _ | Lower _ | Past_null), Some _ -> () (* indexMightHelpWithOrderBy: an ORDER BY term is the rowid or a key column of [idx] *) let helps_order b (idx : index) = match b.sorts_by with | None -> false | Some cols -> List.exists (fun c -> c = rowid_column b.t || List.exists (function Column k -> k = c | Expression _ -> false) idx.keys) cols (* The table lookups of a walk of [idx] that does not cover the query: one a row, less each one a term the index alone answers saves, the terms taken in turn, the copy exprAnalyze makes of an equality of two columns after them, until one the index does not answer. *) let index_lookups b (idx : index) irows = let held (i, j) = i <> b.i || j = rowid_column b.t || Decl.rowid_alias b.s.gt.schema = Some j || List.exists (function Column k -> k = j | Expression _ -> false) idx.keys in let terms = b.conjs @ List.filter (fun (c : conjunct) -> c.commutes) b.conjs in let rec go n = function | [] -> n | (c : conjunct) :: rest -> if List.for_all held c.cols then go (n - 1 - if c.eq <> None then 19 else 0) rest else n in go (irows + 16) terms (* an index's walk where it covers the query in narrower entries, and its searches *) let index_loops b ~wt place (idx : index) = let sidx = if helps_order b idx then place + 2 else 0 in let wi = index_width b.s.gt idx in let covering = b.s.covers idx in let step_cost = 15 * wi / wt in let irows = row_est b.nrows idx 0 in let log_irows = Log_est.est_log irows in if helps_order b idx || (covering && wi < wt) then begin let run = irows + 1 + step_cost in add b (loop b ~index:idx ~covering ~sort_idx:sidx ~terms:[] ~neq:0 (Index_scan idx) ~prereq:b.mprereq ~run: (if covering then run else Log_est.add run (index_lookups b idx irows)) ~out:irows) end; let cost out = let run = Log_est.add log_irows (out + 1 + step_cost) in if covering then run else Log_est.add run (out + 16) in let x = { ix = idx; holds = covering; sidx; entry = Array.of_list (entry_columns b.t idx); price = cost; } in search b x { equated = 0; yields = irows; needs = b.mprereq; used = []; keyed = []; fanout = 0; floor = None; } (* whereLoopAddBtree for source [i], the loops over it [prereq] and the sources its terms read allow: an automatic index on each equality that may drive one, the table scan and the rowid's equalities and ranges, then for each index, newest first, its walk where it covers the query in narrower entries, and its searches (whereLoopAddBtreeIndex), each through its entries' columns, keys then rowid, an equality or IN after another and then a range. *) let source_loops ?sorts_by conjs uterms i s ~prereq:mprereq = let t = model_of s in let b = { i; self = bit i; s; t; nrows = estimated_rows t; log_nrows = Log_est.est_log (estimated_rows t); mine = List.filter (fun (u : uterm) -> u.src = i) uterms; mprereq; sorts_by; conjs; loops = []; } in auto_loops b; rowid_loops b; let wt = table_width s.gt in List.iteri (index_loops b ~wt) (walkable t); b.loops (* The tables that join to [f] through inner joins and need it in place, as a set, and how many, a table joined to itself not counted: whether [f] is a star query's fact table. *) let dimensions (srcs : source option array) loops f = let outer i = match srcs.(i) with Some s -> s.left || s.right | None -> false in let table i = match srcs.(i) with Some s -> s.gt.schema.tbl_name | None -> "" in let m = bit f in let start = if outer f then f + 1 else 0 in let ndep = ref 0 and seen = ref 0 and selfjoin = ref 0 in let count (l : jloop) = if outer l.src then raise Exit; if l.prereq land m <> 0 && bit l.src land !seen = 0 && bit l.src land !selfjoin = 0 then if String.equal (table l.src) (table f) then selfjoin := !selfjoin lor m else begin incr ndep; seen := !seen lor bit l.src end in (try List.iter (fun (l : jloop) -> if l.src >= start then count l) loops with Exit -> ()); (!ndep, !seen) (* computeMxChoice: how many paths the solver keeps at each depth, 18 for a star query and 12 otherwise; a star query's dimension tables have their scans made dearer than the fact table's dearest loop, which keeps the fact table outermost. A fact table is one at least three tables join to through inner joins; a table joined to itself is not its dimension. *) let max_choice (srcs : source option array) loops = let n = Array.length srcs in if n < 4 then (12, loops) else let star = ref false in let loops = List.fold_left (fun loops f -> let ndep, seen = dimensions srcs loops f in if ndep <= 2 then loops else begin star := true; let mx = List.fold_left (fun mx (l : jloop) -> if l.src = f then max mx l.run else mx) min_int loops + 1 in List.map (fun (l : jloop) -> if bit l.src land seen <> 0 && l.terms = [] && l.run < mx then { l with run = mx } else l) loops end) loops (List.init n Fun.id) in ((if !star then 18 else 12), loops) (* An ORDER BY term of a join, as wherePathSatisfiesOrderBy reads it: a column of a source, by its model position, under the sequence the term compares by, its NULLs last where [bignull] (KEYINFO_ORDER_BIGNULL), or an expression reading the sources [reads], a constant reading none. *) type order_key = | Col_key of { src : int; col : int; desc : bool; coll : Sql.Collation.t; bignull : bool; } | Expr_key of { reads : int; constant : bool; desc : bool } (* What the terms are an order for (wctrlFlags): an ORDER BY, whose terms are met in turn in their directions; a GROUP BY (WHERE_GROUPBY), whose terms are met in any order and either direction; the result columns of a DISTINCT (WHERE_DISTINCTBY), met in any order; the argument of a min/max query (WHERE_ORDERBY_MIN or _MAX), met as an ORDER BY is. *) type mode = Sort | Group | Distinct | Min_max (* The ORDER BY a join is planned against: its terms, the result's width and its LIMIT, which whereSortingCost weighs. *) type ordering = { by : order_key array; mode : mode; result_width : int; row_limit : Log_est.t option; want_distinct : bool; } (* What wherePathSatisfiesOrderBy has found so far along a path: the terms in order, whether the rows so far are distinct, the sources whose rows are, the sources in place, and the loops that walk backwards. *) type satisfied = { sat : bool array; mutable distinct : bool; mutable dmask : int; mutable ready : int; mutable rev : int; } exception Ordered_by of int let rowid_of (s : source) = List.length s.names (* the sequence the WHERE term [u] compares its column by *) let term_coll (s : source) (u : uterm) = match u.coll with | Some c -> c | None -> Option.value ~default:Sql.Collation.default (Decl.declared_collation s.gt.schema.columns u.col) (* Each term on a column of [l]'s source that a WHERE equality pins to a value the loops in place give is in order, whatever the loop; for a min/max query, so is one an IN term [l] keys on pins (eqOpMask holds WO_IN). *) let pin sources uterms o st (l : jloop) = let s = sources.(l.src) in let pins col coll (u : uterm) = match u.op with | Equal | Is | Is_null -> col = rowid_of s || Sql.Collation.equal coll (term_coll s u) | In_list _ -> o.mode = Min_max && List.exists (fun (t : uterm) -> t.key = u.key) l.terms | Lower _ | Upper _ | Past_null -> false in Array.iteri (fun i k -> match k with | Col_key { src; col; coll; _ } when src = l.src && not st.sat.(i) -> if List.exists (fun (u : uterm) -> u.src = src && u.col = col && u.prereq land lnot st.ready = 0 && pins col coll u) uterms then st.sat.(i) <- true | Col_key _ | Expr_key _ -> ()) o.by let all_equal ops = List.for_all (fun op -> op = Equal) ops (* WHERE_ONEROW: a rowid equality, or every key of a UNIQUE index equated where it admits one row only: a key of NOT NULL columns, by equalities or IS, or of one column by an equality (whereLoopAddBtreeIndex: uniqNotNull, or nKeyCol 1 and WO_EQ). *) let one_row (s : source) (idx : index) ops = let not_null = List.for_all (function | Column c -> (List.nth s.gt.schema.columns c).not_null <> None | Expression _ -> false) idx.keys in idx.unique && List.length ops = List.length idx.keys && List.for_all (fun op -> op = Equal || op = Is) ops && ((List.length idx.keys = 1 && all_equal ops) || not_null) let first_ops n (l : jloop) = List.filteri (fun j _ -> j < n) (List.map (fun (u : uterm) -> u.op) l.terms) (* The columns [l] yields its rows in order of, the operators of the equalities on the first of them, its number of key columns and whether its index is UNIQUE; [None] for a loop of one row. *) let loop_columns (s : source) (l : jloop) = let rowid = [ (rowid_of s, false, None) ] in match l.step with | Auto_index _ -> raise (Ordered_by 0) | Table_scan | Rowid_range _ -> Some (rowid, [], 0, None) | Rowid_eq _ -> let ops = first_ops 1 l in if List.for_all (fun op -> op = Equal || op = Is) ops then None else Some (rowid, ops, 0, None) | Index_scan idx -> Some (entry_columns (model_of s) idx, [], List.length idx.keys, Some idx) | Index_search { index; keys; lo; hi; past_null } -> let ops = first_ops (List.length keys) l in if lo = None && hi = None && (not past_null) && one_row s index ops then None else Some ( entry_columns (model_of s) index, ops, List.length index.keys, Some index ) (* The first term not yet in order, which the next column of a loop has to yield (an ORDER BY's terms are matched in turn). *) let next_key st = let rec go i = if i >= Array.length st.sat then None else if st.sat.(i) then go (i + 1) else Some i in go 0 (* Whether the column [(c, desc, coll)] of [l]'s source yields the term [i] in order, the direction set so far [dir] agreeing; and the direction. A term with its NULLs last is yielded only by the column right after the equalities [at_eq], which a seek there can start past the NULLs of (WHERE_BIGNULL_SORT). *) let column_matches s o (l : jloop) (c, idesc, icoll) ~at_eq i dir = match o.by.(i) with | Col_key { bignull = true; _ } when not at_eq -> None | Col_key { src; col; desc; coll; _ } when src = l.src && col = c -> ( let coll_ok = c = rowid_of s || match icoll with | None -> true | Some ic -> Sql.Collation.equal ic coll in let rev = idesc <> desc in if not coll_ok then None else if o.mode = Group then Some false else match dir with Some d when d <> rev -> None | _ -> Some rev) | Col_key _ | Expr_key _ -> None (* The term the column [col] of [l] yields in order, the direction set so far [dir] agreeing, and the direction: for an ORDER BY the first term not yet in order alone, for a GROUP BY or a DISTINCT any (wherePathSatisfiesOrderBy keeps looking where WHERE_GROUPBY or WHERE_DISTINCTBY). *) let matching s o st l col ~at_eq dir = let n = Array.length st.sat in let rec any i = if i >= n then None else if st.sat.(i) then any (i + 1) else match column_matches s o l col ~at_eq i dir with | Some r -> Some (i, r) | None -> any (i + 1) in match o.mode with | Sort | Min_max -> Option.bind (next_key st) (fun i -> Option.map (fun r -> (i, r)) (column_matches s o l col ~at_eq i dir)) | Group | Distinct -> any 0 (* The columns of a loop that is not one row, matched against the terms not yet in order, until one does not match. *) let walk_columns s o st (l : jloop) (cols, ops, nkey, idx) = Option.iter (fun (i : index) -> st.distinct <- i.unique) idx; let neq = List.length ops in let rec go j dir distinct_cols = function | [] -> distinct_cols | ((c, _, _) as col) :: rest -> if j < neq && match List.nth ops j with | Equal -> true (* a key that may bind a NULL makes no order distinct *) | Is | Is_null -> st.distinct <- false; true | In_list _ -> o.mode = Min_max | Lower _ | Upper _ | Past_null -> false then go (j + 1) dir distinct_cols rest else begin if st.distinct && c >= 0 && c < rowid_of s && j >= neq && (List.nth s.gt.schema.columns c).not_null = None then st.distinct <- false; if c < 0 then st.distinct <- false; match matching s o st l col ~at_eq:(j = neq) dir with | Some (i, r) -> if dir = None && r then st.rev <- st.rev lor bit l.src; st.sat.(i) <- true; go (j + 1) (Some r) (distinct_cols || c = rowid_of s) rest | None -> if j = 0 || j < nkey then st.distinct <- false; distinct_cols end in if go 0 None false cols then st.distinct <- true (* Every term reading only sources whose rows are distinct is in order. *) let mark_distinct o st (l : jloop) = if st.distinct then begin st.dmask <- st.dmask lor bit l.src; Array.iteri (fun i k -> let reads = match k with | Col_key { src; _ } -> Some (bit src) | Expr_key { reads; constant; _ } -> if reads = 0 && not constant then None else Some reads in match reads with | Some m when (not st.sat.(i)) && m land lnot st.dmask = 0 -> st.sat.(i) <- true | _ -> ()) o.by end (* wherePathSatisfiesOrderBy for the path [path], outermost first, then [last]: how many of the ORDER BY's leading terms its rows come in, [-1] where more loops may yet order them; and the loops that walk backwards. *) let satisfies sources uterms o path last = let st = { sat = Array.make (Array.length o.by) false; distinct = true; dmask = 0; ready = 0; rev = 0; } in let step (l : jloop) = if st.distinct && not (Array.for_all Fun.id st.sat) then begin pin sources uterms o st l; Option.iter (walk_columns sources.(l.src) o st l) (loop_columns sources.(l.src) l); mark_distinct o st l; st.ready <- st.ready lor bit l.src end in match List.iter step (path @ [ last ]) with | exception Ordered_by n -> (n, st.rev) | () -> let n = Array.length st.sat in if Array.for_all Fun.id st.sat then (n, st.rev) else if not st.distinct then let rec prefix i = if i < n && st.sat.(i) then prefix (i + 1) else i in (prefix 0, st.rev) else (-1, st.rev) type path = { mask : int; rows : Log_est.t; cost : Log_est.t; unsorted : Log_est.t; steps : jloop list; (** outermost last *) ordered : int; (** how many leading ORDER BY terms its rows come in, [-1] for not known yet *) rev : int; (** the sources it walks backwards *) } (* whereLoopIsNoBetter: a tie goes to the index loop with narrower entries. *) let no_better s (c : jloop) (b : jloop) = match (c.index, b.index) with | Some ci, Some bi -> not (index_width s.(c.src).gt ci < index_width s.(b.src).gt bi) | _ -> true (* The paths kept at one depth of wherePathSolver, at most [mx], and the one the next to come would replace. *) type kept = { mx : int; into : path option array; mutable count : int; mutable worst : int; mutable worst_cost : Log_est.t; mutable worst_unsorted : Log_est.t; } (* Whether the kept path [q] holds its place against [cand], which the loop [l] ends over the same sources: cheaper, then fewer rows, then cheaper unsorted, then on a tie the narrower index. *) let holds sources q (l : jloop) cand = q.cost < cand.cost || (q.cost = cand.cost && q.rows < cand.rows) || (q.cost = cand.cost && q.rows = cand.rows && q.unsorted < cand.unsorted) || q.cost = cand.cost && q.rows = cand.rows && q.unsorted = cand.unsorted && no_better sources l (List.hd q.steps) (* Where [cand], the path a loop [l] ends, goes among [k]: over the path of its sources it beats, else in a free place or over the worst one it beats, else nowhere. *) let slot sources k (l : jloop) cand = let rec find j = if j >= k.count then None else match k.into.(j) with | Some q when q.mask = cand.mask && q.ordered < 0 = (cand.ordered < 0) -> Some j | _ -> find (j + 1) in match find 0 with | None -> if k.count >= k.mx && (cand.cost > k.worst_cost || (cand.cost = k.worst_cost && cand.unsorted >= k.worst_unsorted)) then None else if k.count < k.mx then begin k.count <- k.count + 1; Some (k.count - 1) end else Some k.worst | Some j -> if holds sources (Option.get k.into.(j)) l cand then None else Some j (* The worst of a full [k], as wherePathSolver finds it: its first path's rows stand for its unsorted cost until a later path is worse. *) let mark_worst k = let q0 = Option.get k.into.(0) in k.worst <- 0; k.worst_cost <- q0.cost; k.worst_unsorted <- q0.rows; for j = 1 to k.mx - 1 do let q = Option.get k.into.(j) in if q.cost > k.worst_cost || (q.cost = k.worst_cost && q.unsorted > k.worst_unsorted) then begin k.worst_cost <- q.cost; k.worst_unsorted <- q.unsorted; k.worst <- j end done (* The path [p] extended by the loop [l], kept in [k] where it earns a place. *) (* One pass of wherePathSolver: the sources, the ORDER BY it weighs and the rows it expects to sort, [None] for the first pass, which weighs none. *) type pass = { sources : source array; uterms : uterm list; order : (ordering * Log_est.t) option; } (* the cost of [unsorted] for a path whose rows come in [ordered] leading terms, with the sort it then needs *) let with_sort pass ~ordered unsorted = match pass.order with | Some (o, nrow) when ordered >= 0 && ordered < Array.length o.by -> let sort = sorting_cost ~width:o.result_width ~limit:o.row_limit ~distinct:o.want_distinct ~n:(Array.length o.by) ~rows:nrow ~sorted:ordered () in (Log_est.add unsorted sort + 3, unsorted) | _ -> (unsorted, unsorted - 2) let extend_path pass k p (l : jloop) = if l.prereq land lnot p.mask = 0 && bit l.src land p.mask = 0 && not (l.auto && p.rows < 3) then let unsorted = l.run + p.rows in let unsorted = if l.setup <> 0 then Log_est.add l.setup unsorted else unsorted in let unsorted = Log_est.add unsorted p.unsorted in let ordered, rev = match pass.order with | Some (o, _) when p.ordered < 0 -> satisfies pass.sources pass.uterms o (List.rev p.steps) l | _ -> (p.ordered, p.rev) in let cost, unsorted = with_sort pass ~ordered unsorted in let cand = { mask = p.mask lor bit l.src; rows = p.rows + l.out; cost; unsorted; steps = l :: p.steps; ordered; rev; } in match slot pass.sources k l cand with | None -> () | Some j -> k.into.(j) <- Some cand; if k.count >= k.mx then mark_worst k (* One pass over [n] depths: each extends each path kept at the one before by every loop whose sources are in place, and keeps the [mx] cheapest paths, one per set of sources and knowledge of its order; then the cheapest. *) let solve_pass pass ~n ~mx loops = let ordered = match pass.order with Some _ -> -1 | None -> 0 in let from = ref [ { mask = 0; rows = 0; cost = 0; unsorted = 0; steps = []; ordered; rev = 0; }; ] in for _ = 1 to n do let k = { mx; into = Array.make mx None; count = 0; worst = 0; worst_cost = 0; worst_unsorted = 0; } in List.iter (fun p -> List.iter (extend_path pass k p) loops) !from; from := List.filter_map Fun.id (Array.to_list (Array.sub k.into 0 k.count)) done; match !from with | [] -> raise Unmodelled_join | p :: ps -> List.fold_left (fun a b -> if a.cost > b.cost then b else a) p ps (* The sources whose whole reads the second pass of the solver drops, from the plan of the first pass [path] (where.c, whereInterstageHeuristic): from the outermost loop, each loop's source while the loop seeks an equality, an IS NULL or an IN (WHERE_COLUMN_EQ, WHERE_COLUMN_NULL, WHERE_COLUMN_IN), up to the first that seeks none -- a range, a scan or an automatic index, whose WHERE_AUTO_INDEX carries no such flag. *) let interstage path = let rec go = function | ({ step = Rowid_eq _ | Index_search { keys = _ :: _; _ }; src; _ } : jloop) :: rest -> bit src lor go rest | _ -> 0 in go (List.rev path.steps) (* A loop that reads its source whole: no constraint and no automatic index (WHERE_CONSTRAINT, WHERE_AUTO_INDEX). *) let whole (l : jloop) = match l.step with | Table_scan | Index_scan _ -> true | Rowid_eq _ | Rowid_range _ | Index_search _ | Auto_index _ -> false (* wherePathSolver: a first pass that weighs no order, then, for an ORDER BY, a second that weighs the sort the first pass's rows would need; each depth keeps the cheapest paths, then the fewer rows, then the cheaper unsorted, then on a tie the narrower index. *) let solve ?order (srcs : source option array) uterms loops = let n = Array.length srcs in let sources = Array.map (function Some s -> s | None -> raise Unmodelled_join) srcs in let mx, loops = if n <= 1 then (1, loops) else if n = 2 then (5, loops) else max_choice srcs loops in let first = solve_pass { sources; uterms; order = None } ~n ~mx loops in match order with | Some o when Array.length o.by > 0 -> let dropped = interstage first in let loops = List.filter (fun l -> not (whole l && bit l.src land dropped <> 0)) loops in solve_pass { sources; uterms; order = Some (o, first.rows + 1) } ~n ~mx loops | _ -> first (* Whether a conjunct that applies [on] and reads [reads] constrains the rows of the source [i], [s], alone, as an automatic index's condition: one that reads that source or none, but outside an outer join's ON; the conjuncts of its own ON alone where an outer join pads it; none where it is left of a RIGHT or FULL join (expr.c, sqlite3ExprIsSingleTableConstraint). *) let single_table s i on ~reads = if s.ltorj then false else if s.left then on = `On i && reads land lnot (bit i) = 0 else (match on with `On _ -> false | `Inner_on _ | `Where -> true) && reads land lnot (bit i) = 0 (* The automatic index sqlite3 builds for source [i] once the sources [ready] are in outer loops (constructAutomaticIndex): keyed on each column an equality or an IS of the WHERE may drive it on, as {!auto_loops} reads them, in the WHERE's order, each column once; partial where a conjunct constrains that source alone ({!single_table}), as the 1 an EXISTS joined leaves in the WHERE does; and filtered by a Bloom filter unless a key compares under a sequence other than BINARY. *) let auto_index srcs conjs uterms i ~ready = let s = Option.get srcs.(i) in let rowid = List.length s.names in let keys = List.fold_left (fun keys (u : uterm) -> if u.src = i && (u.op = Equal || u.op = Is) && (not u.copied) && u.conj >= 0 && u.col < rowid && u.prereq land lnot ready = 0 && affinity_ok u.aff (List.nth s.gt.schema.columns u.col).type_affinity && auto_candidate s u.col && not (List.exists (fun (v : uterm) -> v.col = u.col) keys) then keys @ [ u ] else keys) [] uterms in Auto_index { columns = List.map (fun (u : uterm) -> List.nth s.names u.col) keys; (* a conjunct holding a subquery is no single-table constraint (expr.c, sqlite3ExprIsSingleTableConstraint, bAllowSubq = 0) *) partial = List.exists (fun (c : conjunct) -> (not c.subquery) && single_table s i c.on ~reads:c.reads) conjs; bloom = List.for_all (fun (u : uterm) -> match u.coll with | None | Some (Sql.Collation.Binary | Binary_utf16le | Binary_utf16be) -> true | Some _ -> false) keys; constant = keys <> [] && List.for_all (fun (u : uterm) -> u.prereq = 0) keys; } type nested = { nest : (int * step) list; in_order : int; backwards : int list; checked : (int * int list) list; } (* The ORDER BY term [e], descending where [desc], as the solver reads it. *) let order_key env mode (e, desc) = match col_of env e with | Some (i, j) -> let s = Option.get env.srcs.(i) in let col = if Decl.rowid_alias s.gt.schema = Some j then rowid_of s else j in let coll = match explicit e with | Some c -> c | None -> Option.value ~default:Sql.Collation.default (declared env e) in (* min() sorts its argument's NULLs last where it can be NULL (select.c, minMaxQuery; expr.c, sqlite3ExprCanBeNull): a bare column declared NOT NULL, or the rowid, cannot be outside the padded table of a LEFT JOIN; a column under a COLLATE always can *) let bignull = mode = Min_max && (not desc) && match e with | Ast.Col _ -> s.left || s.ltorj || col <> rowid_of s && (List.nth s.gt.schema.columns col).not_null = None | _ -> true in Col_key { src = i; col; desc; coll; bignull } | None -> Expr_key { reads = reads env e; constant = const e; desc } (* The loops of [path], outermost first, each automatic index keyed on what the loops before it give. *) let with_auto_indexes srcs conjs uterms path = snd (List.fold_left_map (fun ready (l : jloop) -> let step = match l.step with | Auto_index _ -> auto_index srcs conjs uterms l.src ~ready | step -> step in (ready lor bit l.src, { l with step })) 0 path) (* The ordering [keys], each with whether it descends, is in [mode]. *) let ordering env ?(want_distinct = false) ?(width = 0) ?limit mode keys = { by = Array.of_list (List.map (order_key env mode) keys); mode; result_width = width; row_limit = limit; want_distinct; } (* The columns of source [i] an ordering sorts by, [None] for none. *) let sorts_by order i = if order.by = [||] then None else Some (List.filter_map (function | Col_key { src; col; _ } when src = i -> Some col | Col_key _ | Expr_key _ -> None) (Array.to_list order.by)) let backwards_of n rev = List.filter (fun i -> rev land bit i <> 0) (List.init n Fun.id) (* How many leading terms of [o] the loops [steps], outermost last, yield in order, and the loops that walk backwards for them, as sqlite3 rereads a chosen path for a DISTINCT or a GROUP BY's ORDER BY. *) let check sources uterms steps o = match List.rev steps with | [] -> (0, []) | path -> let last = List.nth path (List.length path - 1) in let init = List.filteri (fun i _ -> i < List.length path - 1) path in let n, rev = satisfies sources uterms o init last in (max 0 n, backwards_of (Array.length sources) rev) (* What fixes the order of the sources, read in [FROM] order (where.c, whereLoopAddAll): the sources the source before needed, whether it was a table a RIGHT or FULL join keeps (bFirstPastRJ), and whether a source left of such a join was met (hasRightCrossJoin). *) type carried = { needs : int; past_right : bool; right_cross : bool } let nothing_carried = { needs = 0; past_right = false; right_cross = false } (* The sources a loop over source [i] needs in outer loops, and what it carries to the next: an outer join's table, a CROSS JOIN's right operand, one left of a RIGHT or FULL join and the one after such a join's table every source before it; the table of an EXISTS, on top of what it carries, every source before it that a conjunct reading it reads, so it never runs before what its conjuncts test it against; any other none, or what it carries once a source left of a RIGHT join was met. *) let prereq_of conjs carried i s = if carried.past_right || s.left || s.right || s.ltorj || s.cross then let needs = carried.needs lor (bit i - 1) in ( needs, { needs; past_right = s.right; right_cross = carried.right_cross || s.ltorj; } ) else if s.exists then let needs = List.fold_left (fun m c -> if c.reads land bit i <> 0 then m lor (c.reads land (bit i - 1)) else m) carried.needs conjs in (needs, { carried with needs }) else if carried.right_cross then (carried.needs, carried) else (0, { carried with needs = 0 }) let join ?(order = []) ?(mode = Sort) ?want_distinct ?(checks = []) ?width ?limit srcs ~position ~column_affinity ~collation ~subquery ~outer conjuncts = let n = Array.length srcs in if n < 1 || n > 62 || Array.exists Option.is_none srcs then None else match let conjs, uterms = join_terms srcs ~position ~column_affinity ~collation ~subquery ~outer conjuncts in let env = { srcs; position; column_affinity; collation; subquery; outer } in let order = ordering env ?want_distinct ?width ?limit mode order in let loops = List.concat (snd (List.fold_left_map (fun carried (i, s) -> let s = Option.get s in let prereq, carried = prereq_of conjs carried i s in ( carried, source_loops ?sorts_by:(sorts_by order i) conjs uterms i s ~prereq )) nothing_carried (List.mapi (fun i s -> (i, s)) (Array.to_list srcs)))) in let best = solve ~order srcs uterms loops in let sources = Array.map Option.get srcs in let checked = List.map (fun (keys, mode) -> check sources uterms best.steps (ordering env mode keys)) checks in (with_auto_indexes srcs conjs uterms (List.rev best.steps), best, checked) with | exception Unmodelled_join -> None | path, best, checked -> Some { nest = List.map (fun (l : jloop) -> (l.src, l.step)) path; in_order = max 0 best.ordered; backwards = backwards_of n best.rev; checked; }