(*--------------------------------------------------------------------------- Copyright (c) 2025 Thomas Gazagnaire. All rights reserved. SPDX-License-Identifier: ISC ---------------------------------------------------------------------------*) open Ast (* SQLite's value-level semantics (comparison order, collation, text conversion, aggregate folds) live in {!Value_ops}, shared with the register-VM paths; open it so what this module folds and orders by is the same rule. *) open Value_ops include Query_intf let default_recursion_cap = 1_000_000 (* A catalog for an expression that may not reach a relation: it answers none and says which expression asked, carrying no per-table state so one value serves every evaluation. *) let closed ~encoding what = let no_table kind name = Catalog.Error.fail_runtime "%s cannot read %s %S" what kind name in { columns = (fun n -> no_table "the columns of" n); rows = (fun n -> no_table "the rows of" n); rows_rowid = (fun n -> no_table "the rows of" n); has_rowid = (fun n -> no_table "the rows of" n); holds = (fun _ -> false); binds = (fun _ -> false); index_scan = (fun n _ -> no_table "an index on" n); best_index_for = (fun n _ -> no_table "an index on" n); affinity = (fun n _ -> no_table "the affinity of" n); decl_type = (fun n _ -> no_table "the declared type of" n); row_count = (fun n ~upto:_ -> no_table "the rows of" n); collation = (fun n _ -> no_table "the collation of" n); table_function = (fun _ -> None); scalar_function = (fun _ -> None); subquery = (fun _ _ _ _ -> no_table "a subquery over" ""); prepare = (fun _ _ _ -> no_table "a subquery over" ""); stream = (fun _ -> None); subquery_memo = Hashtbl.create 1; subquery_plans = None; recursion_cap = default_recursion_cap; encoding; } let of_catalog ~recursion_cap ~subquery cat = { columns = Catalog.Spi.columns cat; rows = Catalog.Spi.rows cat; rows_rowid = Catalog.Spi.rows_rowid cat; (* A backend that states a schema states whether the table keeps a rowid; one that states none describes a plain relation, which does. *) has_rowid = (fun n -> match Catalog.Spi.schema cat n with | Some s -> not s.Catalog.Spi.Schema.without_rowid | None -> true); holds = (fun n -> List.exists (Ast.ident_equal n) (Catalog.Spi.tables cat)); binds = (fun _ -> false); index_scan = Catalog.Spi.index_scan cat; best_index_for = Catalog.Spi.best_index_for cat; (* A backend that states a schema states each column's declared type, and the affinity is that type read the way sqlite3 reads it; one that states none describes columns nothing can be assumed about. *) affinity = Value_ops.column_affinity cat; decl_type = Catalog.Spi.decl_type cat; row_count = (fun table ~upto -> match (Catalog.Spi.stats cat table).Catalog.Spi.row_count with | Some n -> min (Int64.to_int n) upto | None -> upto); collation = Catalog.Spi.collation cat; table_function = (fun _ -> None); scalar_function = (fun _ -> None); subquery; prepare = (fun cat s params () -> cat.subquery cat [] s params); stream = (fun _ -> None); subquery_memo = Hashtbl.create 16; subquery_plans = None; recursion_cap; encoding = Encoding.Utf8; } (* A table-valued function: the backend's own takes precedence over the built-ins in {!Func}. Every FROM position resolves one through here, so a backend function scans like a built-in wherever it appears. *) let table_function cat name = match cat.table_function name with | Some f -> f | None -> Func.table_function name (* A scalar call's value: the backend's own function where it provides one, the built-in otherwise. Every call an evaluator reaches goes through here, so a backend function is applied wherever a built-in is -- and a name {!Func} has without an answer, because the answer is the connection's rather than the arguments', is answered where the connection is. *) let call cat ?coll name args = match cat.scalar_function name with | Some f -> f args | None -> Func.apply ?coll name args (* The schema lookups {!Resolve} runs on, taken out of the ones a catalog carries. Name resolution happens before any row is read, so it is given what it needs to answer and none of the rest. *) let resolve_env cat : Resolve.env = { columns = cat.columns; collation = cat.collation; affinity = cat.affinity; decl_type = cat.decl_type; table_function_columns = (fun name -> (table_function cat name).columns); has_rowid = cat.has_rowid; holds = cat.holds; } (* ── Named rows ──────────────────────────────────────────────── *) (* A [binding] is one named row fragment: an (alias, [(column, value)]) pair -- the form an outer [scope] takes (a correlated subquery's enclosing row, a trigger's OLD/NEW rows, an [UPDATE ... FROM] join row). *) type binding = string * (string * value) list let is_rowid_name = Ast.is_rowid_name (* Which builtin names, at which arity, fold a group is a fact about SQLite's function table, so it is read off {!Func.aggregate} rather than restated here; this is only the AST spelling of the argument count. *) let is_agg name args = Func.aggregate name ~nargs:(List.length args) (* Is [e] an aggregate call, possibly wrapped in FILTER/ORDER BY decorations? *) let rec is_agg_expr = function | Func (n, a) -> is_agg n a | Distinct_agg _ -> true | Filter (e, _) | Ordered_agg (e, _) -> is_agg_expr e | _ -> false (* Does [e] contain an aggregate of {e this} query anywhere? Unlike {!is_agg_expr} this looks inside ordinary sub-expressions ([f(a, max(b))], [a + count(c)]) but NOT into a subquery -- an aggregate there is the inner query's, so it does not make the enclosing query an aggregate query. *) let rec contains_agg e = match e with | Func (n, args) -> is_agg n args || List.exists contains_agg args | Distinct_agg _ | Filter _ | Ordered_agg _ -> true (* A window function folds no group of this query: it is computed over the rows the query has already produced, so a select carrying one is not an aggregate select for carrying it. Its arguments and keys are expressions over those rows, so an aggregate in them is one of the query (resolve.c resolves them in the select's own name context). *) | Window (f, w) -> let rec head = function | Func (_, args) -> args | Distinct_agg (_, a) -> [ a ] | Filter (f, p) -> p :: head f | Ordered_agg (f, keys) -> List.map fst keys @ head f | e -> [ e ] in List.exists contains_agg (head f @ w.partition @ List.map fst w.order) (* A subquery's aggregates are its own, so the fold hands one back unchanged; the left operand of a membership is this query's and is looked into. *) | e -> Ast.fold_expr ~select:(fun acc _ -> acc) (fun acc x -> acc || contains_agg x) false e let is_aggregate (rc : Ast.result_col) = contains_agg rc.expr (* Does [s] aggregate at all -- it groups, has HAVING, or a select column folds an aggregate? A LIMIT/OFFSET cannot be pushed into the scan of such a query (the aggregate folds every row first), so a fast path must recognise and skip it. *) let is_aggregate_query (s : select) = s.group_by <> [] || s.having <> None || List.exists is_aggregate s.cols let refuse_call ~explain name args = let nargs = List.length args in if Func.exists name then ( if not (Func.takes name ~nargs) then Func.unresolved name) else if not explain then Func.unresolved name (* The head of a window names a function of one of two tables: a built-in window function, resolved at the counts window.c registers it at ({!Func.window}), or an aggregate, folded over the frame instead of over a group and resolved exactly as a fold is. A built-in scalar is refused at any count, as resolve.c refuses it, and a name of no function earns that sentence. *) let refuse_window_head ~explain ~answered name args = if Func.window_name name then ( if not (Func.window name ~nargs:(List.length args)) then Func.unresolved name) else if (not (is_agg name args)) && not (answered name) then if Func.exists name then Catalog.Error.fail_prepare "%s() may not be used as a window function" name else refuse_call ~explain name args (* A call with no window: a window function at a count it takes is misused there, as resolve.c says. *) let refuse_plain_call ~explain ~answered name args = if (not (is_agg name args)) && not (answered name) then if Func.window name ~nargs:(List.length args) then Catalog.Error.fail_prepare "%s" (Func.window_misuse name) else refuse_call ~explain name args (* The name of the call inside an expression that is one: a call wears FILTER, ORDER BY and OVER decorations that are not the call. *) let rec called_name = function | Func (n, _) | Distinct_agg (n, _) -> Some n | Filter (e, _) | Ordered_agg (e, _) | Window (e, _) -> called_name e | _ -> None (* What a clause admits, as resolve.c's NC_AllowAgg and NC_AllowWin say: an aggregate of the query, and a window function. *) type admits = { agg : bool; win : bool } let anything = { agg = true; win = true } let nothing = { agg = false; win = false } let misused_aggregate name = Catalog.Error.fail_prepare "misuse of aggregate function %s()" name (* A window's calls: its head is resolved against the window table, its arguments are ordinary expressions, and the node is descended with the head standing in as a [*] so the window's own keys and frame offsets are still read. [own] and [descend] are {!own_calls}'s walk. *) let window_calls ~explain ~answered ~own ~descend admits f w = (match f with | Func (name, args) -> refuse_window_head ~explain ~answered name args | _ -> ()); if not admits.win then Option.iter (fun n -> Catalog.Error.fail_prepare "%s" (Func.window_misuse n)) (called_name f); let inner = { admits with win = false } in let rec head ~top = function | Func (name, args) -> if not top then refuse_plain_call ~explain ~answered name args; List.iter (own inner) args | Distinct_agg (_, a) -> own inner a | Filter (e, c) -> head ~top:false e; own inner c | Ordered_agg (e, keys) -> head ~top:false e; List.iter (fun (k, _) -> own inner k) keys | e -> own inner e in head ~top:true f; descend inner (Window (Star, w)) (* The calls of [e] outside the selects it holds, in a clause that admits [admits]. resolve.c refuses an aggregate or a window function the clause does not admit at the call, once its name is found; an aggregate's own arguments admit neither, and a window's arguments and keys admit no window. *) let own_calls ~explain ~answered ~admits e = (* the walk hands [admits] down as the fold's accumulator, so a node costs no closure *) let rec visit admits x = own admits x; admits and descend admits e = ignore (Ast.fold_expr ~select:(fun admits _ -> admits) visit admits e) and own admits e = match e with | Window (f, w) -> window_calls ~explain ~answered ~own ~descend admits f w | Func (name, args) when is_agg name args -> if not admits.agg then misused_aggregate name; List.iter (own nothing) args | Func (name, args) -> refuse_plain_call ~explain ~answered name args; List.iter (own admits) args | Distinct_agg (name, arg) -> if not admits.agg then misused_aggregate name; own nothing arg (* an aggregate's FILTER and ORDER BY are read as its arguments are *) | Filter (f, c) when is_agg_expr f -> own admits f; own nothing c | Ordered_agg (f, keys) when is_agg_expr f -> own admits f; List.iter (fun (k, _) -> own nothing k) keys | e -> descend admits e in own admits e (* Whether [e] holds an aggregate that folds the rows of the select whose own sources are [own]: one whose arguments read a column of [own], or none at all. One that reads only an enclosing select's columns folds that select's rows (resolve.c walks the name contexts outward to the first whose sources it reads). *) let rec folds_own own e = let rec refs acc = function | Col (q, n) -> (q, n) :: acc | x -> Ast.fold_expr ~select:(fun acc _ -> acc) refs acc x in let call args = match List.fold_left refs [] args with | [] -> true | rs -> List.exists (fun (q, n) -> Resolve.scope_binds own q n) rs in match e with | Func (n, args) when is_agg n args && call args -> true | Distinct_agg (_, a) when call [ a ] -> true | Window _ -> false | e -> Ast.fold_expr ~select:(fun acc _ -> acc) (fun acc x -> acc || folds_own own x) false e (* The number of values [e] stands for: a subquery's columns, else one. A subquery whose columns the schema cannot say is taken as one, and refused for what it reads where it runs. *) let width env = function | Scalar_select q -> ( match Resolve.select_columns env q with | cols -> List.length cols | exception Catalog.Error _ -> 1) | _ -> 1 let sub_select n = Catalog.Error.fail_prepare "sub-select returns %d columns - expected 1" n (* The subqueries of [e] outside the selects it holds that stand for a number of values their place does not take. The two sides of a comparison, an IS and a CASE's base against each value it is compared with have one width, or are a row value misused (resolve.c); any other subquery, and the right of an IN, is one value, and one of N columns is refused as sqlite3 codes it (expr.c, sqlite3CodeSubselect, sqlite3ExprCheckIN). Two sides of one width above one are a row value, which this engine does not compare. *) let rec widths env ~operand e = let value = widths env ~operand:false and side = widths env ~operand:true in let pair a b = match (width env a, width env b) with | 1, 1 -> () | n, m when n = m -> Catalog.Error.fail_unsupported "engine: a row value is not supported" | _ -> Catalog.Error.fail_prepare "row value misused" in match e with | Scalar_select _ -> let n = width env e in if n <> 1 && not operand then sub_select n | In_select (l, q) -> value l; let n = width env (Scalar_select q) in if n <> 1 then sub_select n | Binary ((Eq | Neq | Lt | Le | Gt | Ge), a, b) | Is (a, b) -> pair a b; side a; side b | Case (Some base, arms, els) -> List.iter (fun (w, _) -> pair base w) arms; side base; List.iter (fun (w, r) -> side w; value r) arms; Option.iter value els | e -> Ast.fold_expr ~select:(fun () _ -> ()) (fun () x -> value x) () e (* select.c codes the rows of a VALUES list of several as a co-routine of expression lists, which no group folds, so an aggregate there is refused as it is coded (expr.c, TK_AGG_FUNCTION), the last one coded naming the refusal; a single row is a select of its own expressions. A VALUES list that leads a compound is coded arm by arm, each row a select, so nothing is refused there. *) let values_aggregate rows = let rec last acc = function | Window _ -> acc | Func (n, args) when is_agg n args -> Some n | Distinct_agg (n, _) -> Some n | (Filter (f, _) | Ordered_agg (f, _)) when is_agg_expr f -> last acc f | e -> Ast.fold_expr ~select:(fun acc _ -> acc) last acc e in match rows with | [] | [ _ ] -> () | rows -> ( match List.fold_left (List.fold_left last) None rows with | Some n -> Catalog.Error.fail_prepare "misuse of aggregate: %s()" n | None -> ()) (* The clauses of [s], each with what resolveSelectStep admits there: a WHERE or an ON admits an aggregate only in a query that folds groups, where select.c refuses it as it codes the scan ({!Lower}), and a GROUP BY admits one only to refuse it once its keys are resolved, if it folds [s]'s own rows. Its stars are expanded first, as sqlite3SelectPrep expands them before it resolves a name. *) let select_calls ~explain ~answered env (s : select) = Resolve.check_stars s; let check admits = own_calls ~explain ~answered ~admits in let scan = { agg = is_aggregate_query s; win = false } in let grouping = { agg = true; win = false } in List.iter (fun (rc : result_col) -> check anything rc.expr) s.cols; Option.iter (check scan) s.where; List.iter (check grouping) s.group_by; if List.exists (folds_own (Resolve.binding_scope env s)) s.group_by then Catalog.Error.fail_prepare "aggregate functions are not allowed in the GROUP BY clause"; Option.iter (check grouping) s.having; List.iter (fun (e, _) -> check anything e) s.order_by; List.iter (fun (j : join) -> Option.iter (check scan) j.on) s.joins; List.iter (widths env ~operand:false) (List.map (fun (rc : result_col) -> rc.expr) s.cols @ Option.to_list s.where @ s.group_by @ Option.to_list s.having @ List.map fst s.order_by @ List.filter_map (fun (j : join) -> j.on) s.joins); match s.from with | Values rows -> List.iter (List.iter (check anything)) rows; if s.compound = [] then values_aggregate rows | Unit | Table _ | Select _ | Table_function _ -> () let check_calls ?(explain = false) cat (s : select) = select_calls ~explain (resolve_env cat) ~answered:(fun name -> cat.scalar_function name <> None) s let check_select cat (s : select) = let env = resolve_env cat in List.iter (fun (a : select) -> check_calls cat a; (* every arm reads the WITH over the whole compound *) Resolve.check_subqueries ~select:(check_calls cat) env (if a == s then a else { a with ctes = s.ctes })) (s :: List.map snd s.compound) (* [e]'s calls and those of every select it holds: sqlite3 resolves a subquery, a FROM operand, a WITH body and a compound arm as it prepares the statement holding them, whether a row ever reaches them. An expression that holds no select has no width to check and no select to walk into. *) let check_expr_calls cat e = let explain = false and answered name = cat.scalar_function name <> None in own_calls ~explain ~answered ~admits:nothing e; if Ast.holds_select e then begin let env = resolve_env cat in let each u = select_calls ~explain ~answered env u in widths env ~operand:false e; Resolve.walk_expr ~table:(fun () _ -> ()) ~col:(fun () _ _ -> ()) ~nest:(fun () u -> each u) ~cte:(fun () (c : cte) -> each c.query; Some ()) () e end let unseen () = let seen = Hashtbl.create 64 in fun row -> if Hashtbl.mem seen row then false else ( Hashtbl.add seen row (); true) let reads_relations ?(view = fun _ -> None) (s : select) = let acc = ref [] in let push scopes (u : select) = if u.ctes = [] then scopes else u.ctes :: scopes in let rec expand scopes visiting (u : select) = Resolve.walk_select ~table:(fun scopes (tr : Ast.table_ref) -> source scopes visiting tr.name) ~col:(fun _ _ _ -> ()) ~nest:push ~cte:(fun _ _ -> None) (push scopes u) u and source scopes visiting name = match scopes with | [] -> ( let seen = List.exists (ident_equal name) !acc in acc := name :: !acc; (* a view's body reads the schema's own relations, outside every WITH of the query that names it *) match view name with | Some body when not seen -> expand [] visiting body | Some _ | None -> ()) | list :: outer -> ( match List.find_opt (fun (c : cte) -> ident_equal c.name name) list with | None -> source outer visiting name | Some c -> if not (List.memq c visiting) then expand (list :: outer) (c :: visiting) c.query) in expand [] [] s; List.rev !acc let reads_table ?view name (s : select) = List.exists (ident_equal name) (reads_relations ?view s) type cte_shape = Plain | Recursive | Circular let cte_shape (c : cte) = if reads_table c.name { c.query with compound = [] } then Circular else if List.exists (fun (_, arm) -> reads_table c.name arm) c.query.compound then Recursive else Plain let ctes_are_cyclic ctes = let members = Array.of_list ctes in let index name = Array.find_index (fun (c : cte) -> ident_equal c.name name) members in (* [Grey] is on the current path, [Black] is explored and acyclic. *) let state = Array.make (Array.length members) `White in let rec visit i = match state.(i) with | `Grey -> true | `Black -> false | `White -> let c = members.(i) in (* a recursive CTE's own arms name it by design, and that self-reference is the one that has a fixpoint *) let self_ok = cte_shape c = Recursive in let edge n = (not (self_ok && ident_equal n c.name)) && Option.fold ~none:false ~some:visit (index n) in state.(i) <- `Grey; let cyclic = List.exists edge (reads_relations c.query) in state.(i) <- `Black; cyclic in List.exists (fun i -> visit i) (List.init (Array.length members) Fun.id) let set_op ?(colls = []) op left right = let coll i = match List.nth_opt colls i with Some c -> c | None -> None in (* what a row is keyed by: each column reduced to its collated form, so two rows that collate equal have equal keys *) let key row = List.mapi (fun i v -> match coll i with Some c -> collation_key c v | None -> v) row in let rec compare_keys a b = match (a, b) with | [], [] -> 0 | [], _ -> -1 | _, [] -> 1 | x :: xs, y :: ys -> let c = compare_values x y in if c <> 0 then c else compare_keys xs ys in let keyed rows = List.map (fun r -> (key r, r)) rows in (* into key order, then the first row of each run of equal keys *) let ordered_distinct krows = let rec run last = function | (k, r) :: rest -> if compare_keys k last = 0 then run last rest else r :: run k rest | [] -> [] in match List.stable_sort (fun (a, _) (b, _) -> compare_keys a b) krows with | [] -> [] | (k, r) :: rest -> r :: run k rest in (* membership of a side, asked once per row of the other: the side's keys sorted once and searched by halving, so EXCEPT and INTERSECT cost (|left| + |right|) log |right| comparisons rather than |left| * |right| -- the one ephemeral index sqlite3 answers both through *) let member rows = let keys = Array.of_list (List.sort compare_keys (List.map key rows)) in fun k -> let rec search lo hi = if lo >= hi then false else let mid = lo + ((hi - lo) / 2) in let c = compare_keys k keys.(mid) in if c = 0 then true else if c < 0 then search lo mid else search (mid + 1) hi in search 0 (Array.length keys) in match op with | Union_all -> left @ right | Union -> ordered_distinct (keyed (left @ right)) | Except -> let inside = member right in ordered_distinct (List.filter (fun (k, _) -> not (inside k)) (keyed left)) | Intersect -> let inside = member right in ordered_distinct (List.filter (fun (k, _) -> inside k) (keyed left)) (* The distinct [Window] nodes appearing anywhere in [cols] (window functions do not nest, so a Window is not descended into). Pure syntax -- no executor dependencies, so it sits outside the evaluation rec group. *) let window_exprs cols = let rec go acc e = match e with | Window _ -> if List.mem e acc then acc else acc @ [ e ] (* A window inside a subquery is the subquery's to compute, over its own rows; every other part of the expression is this select's. *) | e -> Ast.fold_expr ~select:(fun acc _ -> acc) go acc e in List.fold_left (fun acc (rc : Ast.result_col) -> go acc rc.expr) [] cols let memo f = let answer = ref None in fun () -> match !answer with | Some v -> v | None -> let v = f () in answer := Some v; v let bind_relation ?(holds = fun _ -> None) ?stream cat name cols rows = (* The bound relation is reached by name like any other, so the question every entry point asks is the identifier one: a query spelling the CTE or derived table in another case must find the binding rather than fall through to the store, where the relation does not exist. *) let same n = ident_equal n name in { columns = (fun n -> if same n then cols () else cat.columns n); rows = (fun n -> if same n then rows () else cat.rows n); rows_rowid = (fun n -> if same n then List.map (fun r -> (None, r)) (rows ()) else cat.rows_rowid n); (* A materialised relation is rows, not storage: it has no identity to publish, so [rowid] over it names nothing. *) has_rowid = (fun n -> (not (same n)) && cat.has_rowid n); holds = (fun n -> same n || cat.holds n); binds = (fun n -> same n || cat.binds n); index_scan = (fun n eqs -> if same n then None else cat.index_scan n eqs); best_index_for = (fun n cs -> if same n then None else cat.best_index_for n cs); (* A materialised relation has no schema, but it does have the select that produced it, which is what its columns' affinities are read off ({!Resolve.output_affinity}); [holds] is that reading, and answers for none where the caller has no select to offer. *) affinity = (fun n c -> if same n then holds c else cat.affinity n c); decl_type = (fun n c -> if same n then None else cat.decl_type n c); (* Counting the bound relation would force it, and a plan must not run the query it plans; unsized, it reads as large, which is what a relation with no access path should cost anyway. *) row_count = (fun n ~upto -> if same n then upto else cat.row_count n ~upto); collation = (fun n c -> if same n then None else cat.collation n c); table_function = cat.table_function; scalar_function = cat.scalar_function; subquery = cat.subquery; prepare = cat.prepare; stream = (fun n -> if same n then stream else cat.stream n); (* Not [cat]'s: shadowing [name] changes what a subquery over it returns and the columns it reads, so neither the enclosing catalog's answers nor its plans carry over. *) subquery_memo = Hashtbl.create 16; subquery_plans = None; recursion_cap = cat.recursion_cap; encoding = cat.encoding; } let guard_relation name cat = let resolving = ref false in let through f n = if not (ident_equal n name) then f n else if !resolving then Catalog.Error.fail_prepare "circular reference: %s" (Ast.written_name name) else ( resolving := true; Fun.protect ~finally:(fun () -> resolving := false) (fun () -> f n)) in { cat with columns = through cat.columns; rows = through cat.rows; stream = through cat.stream; rows_rowid = through cat.rows_rowid; } let recursive_count params name what (e : expr) = let of_value = function | Int n -> Some n | Float f when Float.is_integer f && Float.abs f < 9.2e18 -> Some (Int64.of_float f) | Null | Float _ | Text _ | Blob _ -> Catalog.Error.fail Mismatch in match e with | Lit v -> of_value v | Param i when i >= 0 && i < Array.length params -> of_value params.(i) | _ -> Catalog.Error.fail_prepare "engine: %s in the recursive select of %s must be a literal or a bound \ parameter" what (Ast.written_name name) (* The offset and the total the recursive select bounds its table by, read off its OFFSET and LIMIT: [offset] rows dropped off the front, [bound] the rows the table holds in all (offset included), [None] where nothing bounds it -- which a negative LIMIT also means (lang_select.html sec.5). A count past the native range is held at [max_int], and so is their sum. *) let recursive_bounds params name query = let count what = function | None -> None | Some e -> recursive_count params name what e in let native n = if Int64.compare n (Int64.of_int max_int) > 0 then max_int else Int64.to_int n in let limit = count "LIMIT" query.limit and offset = count "OFFSET" query.offset in let offset = match offset with Some n when Int64.compare n 0L > 0 -> native n | _ -> 0 in let bound = match limit with | Some n when Int64.compare n 0L >= 0 -> let n = native n in Some (if n > max_int - offset then max_int else offset + n) | Some _ | None -> None in (offset, bound) (* The first [n] of [rows], and how many that was. *) let first_n n rows = let rec go n acc = function | r :: rest when n > 0 -> go (n - 1) (r :: acc) rest | _ -> (List.rev acc, List.length acc) in go n [] rows (* A LIMIT or OFFSET as sqlite3 reads it: resolved in no name context, so a column there is no such column, even one an enclosing query has, and an aggregate is misused (resolve.c, resolveSelectStep); then computed once, over [cat], before the select runs. A literal or a bound parameter is its own value already. *) let count cat params (e : expr) = match e with | Lit _ | Param _ | Named_param _ -> e | Numeral s -> Lit (Ast.code_number s) | Unary_minus (Numeral s) -> Lit (Ast.code_number ~negative:true s) | e -> ( let rec refuse (e : expr) = match e with | Col (q, n) -> Catalog.Error.fail_prepare "no such column: %s" (match q with Some q -> q ^ "." ^ n | None -> n) | (Func (n, _) | Distinct_agg (n, _)) when is_agg_expr e -> Catalog.Error.fail_prepare "misuse of aggregate function %s()" n | e -> Ast.fold_expr ~select:(fun () _ -> ()) (fun () x -> refuse x) () e in refuse e; let one = { ctes = []; distinct = false; cols = [ { expr = e; alias = None } ]; from = Unit; joins = []; where = None; group_by = []; having = None; compound = []; order_by = []; limit = None; offset = None; } in match cat.subquery cat [] one params with | [ [ v ] ] -> Lit v | _ -> Lit Null) let counts cat params (s : select) = let count = count cat params in { s with limit = Option.map count s.limit; offset = Option.map count s.offset; } (* The table-valued function [name] names, if a source of that name reads one: no common table expression of the select is called [name], and the catalog either has no relation of that name or answers the function's own columns for it, as an eponymous table reads (build.c, sqlite3LocateTable, which tries the schema first). *) let eponymous cat (s : select) (tr : table_ref) = let named = Catalog.Ident.equal tr.name in let f = match cat.table_function tr.name with | Some f -> Some f | None -> Func.find_table_function tr.name in match f with | Some f when tr.subquery = None && (match tr.schema with | None -> true | Some sc -> Catalog.Ident.equal sc "main") && (not (List.exists (fun (c : cte) -> named c.name) s.ctes)) && match cat.columns tr.name with | cols -> List.equal Catalog.Ident.equal cols f.columns | exception Catalog.Error _ -> true -> Some f | _ -> None let rec constant (e : expr) = match e with | Col _ | Schema_col _ -> false | e -> Ast.fold_expr ~select:(fun _ _ -> false) (fun ok x -> ok && constant x) true e (* [e] as an equality that sets the hidden column [name] of the source [alias] to a value no column reads, the term sqlite3's xBestIndex takes as that argument. *) let argument_term alias name (e : expr) = let names = function | Col (q, n) -> ( Catalog.Ident.equal n name && match q with None -> true | Some q -> Catalog.Ident.equal q alias) | _ -> false in match e with | Binary (Eq, c, v) when names c && constant v -> Some v | Binary (Eq, v, c) when names c && constant v -> Some v | _ -> None let rec conjuncts = function | Binary (And, a, b) -> conjuncts a @ conjuncts b | e -> [ e ] (* [s] reading the hidden columns of the table-valued function [alias] as the values [hidden]: a reference to one, qualified by [alias] or bound by no other source, is its value, down every nested select that does not bind the name itself. *) let substitute_hidden env alias visible hidden (s : select) = let hidden_value qual name = match List.find_opt (fun (n, _) -> Catalog.Ident.equal n name) hidden with | Some (_, v) when not (List.exists (Catalog.Ident.equal name) visible) -> ( match qual with | Some q when Catalog.Ident.equal q alias -> Some v | Some _ -> None | None -> Some v) | _ -> None in let rec expr own e = match e with | Col (qual, name) -> ( let bound = match qual with | Some q -> List.exists (fun (a, _) -> Catalog.Ident.equal a q) own | None -> Resolve.scope_binds own None name in match hidden_value qual name with | Some v when not bound -> Lit v | _ -> e) | e -> Ast.map_expr ~select:(nested own) (expr own) e and nested _ (u : select) = let own = Resolve.binding_scope env u in select own u and select own (u : select) = let ex = expr own in { u with cols = List.map (fun (rc : result_col) -> { rc with expr = ex rc.expr }) u.cols; where = Option.map ex u.where; group_by = List.map ex u.group_by; having = Option.map ex u.having; order_by = List.map (fun (e, d) -> (ex e, d)) u.order_by; joins = List.map (fun (j : join) -> { j with on = Option.map ex j.on }) u.joins; compound = List.map (fun (op, arm) -> (op, nested own arm)) u.compound; } in let own = List.filter (fun (a, _) -> not (Catalog.Ident.equal a alias)) (Resolve.binding_scope env s) in select own s let values_of cat params = function | [] -> [] | args -> ( let one = { ctes = []; distinct = false; cols = List.map (fun e -> { expr = e; alias = None }) args; from = Unit; joins = []; where = None; group_by = []; having = None; compound = []; order_by = []; limit = None; offset = None; } in match cat.subquery cat [] one params with | [ vs ] -> vs | _ -> List.map (fun _ -> Null) args) (* The expressions of [s] itself, not those of the selects it nests. *) let own_exprs (s : select) = List.map (fun (rc : result_col) -> rc.expr) s.cols @ Option.to_list s.where @ s.group_by @ Option.to_list s.having @ List.map fst s.order_by @ List.filter_map (fun (j : join) -> j.on) s.joins let map_own_exprs f (s : select) = { s with cols = List.map (fun (rc : result_col) -> { rc with expr = f rc.expr }) s.cols; where = Option.map f s.where; group_by = List.map f s.group_by; having = Option.map f s.having; order_by = List.map (fun (e, d) -> (f e, d)) s.order_by; joins = List.map (fun (j : join) -> { j with on = Option.map f j.on }) s.joins; } (* The table-valued function [f] in [s]'s FROM, called [name] under [alias] with [args]: the arguments it left out that a WHERE equality on their hidden columns sets, in argument order (where.c, the virtual table's xBestIndex), and every reference to a hidden column read as its value. *) let hidden_columns cat params (s : select) ~name ~args ~alias (f : Func.table_function) = if not (List.for_all constant args) then s else let env = resolve_env cat in let terms = match s.where with Some w -> conjuncts w | None -> [] in let rec fill args = function | [] -> args | h :: rest -> ( match List.find_map (argument_term alias h) terms with | Some v -> fill (args @ [ v ]) rest | None -> args) in let args = fill args (List.filteri (fun i _ -> i >= List.length args) f.hidden) in let values = f.arguments (values_of cat params args) in let hidden = List.combine f.hidden values in let s = substitute_hidden env alias f.columns hidden s in { s with from = Table_function { tf_name = name; tf_args = args; tf_alias = (if Catalog.Ident.equal alias name then None else Some alias); }; } (* Whether [s] or a select it nests reads a table-valued function. *) let rec reads_function cat (s : select) = (match s.from with | Table_function _ -> true | Table tr -> Option.is_some (cat.table_function tr.name) || List.exists (Catalog.Ident.equal tr.name) Func.table_functions | Select { fs_select; _ } -> reads_function cat fs_select | Values _ | Unit -> false) || List.exists (fun (c : cte) -> reads_function cat c.query) s.ctes || List.exists (fun (_, arm) -> reads_function cat arm) s.compound || List.exists (Ast.fold_expr ~select:(fun found u -> found || reads_function cat u) (fun found e -> found || expr_reads_function cat e) false) (own_exprs s) and expr_reads_function cat e = Ast.fold_expr ~select:(fun found u -> found || reads_function cat u) (fun found x -> found || expr_reads_function cat x) false e let rec table_arguments cat params (s : select) = if not (reads_function cat s) then s else rewrite_arguments cat params s and rewrite_arguments cat params (s : select) = let s = match s.from with | Table_function { tf_name; tf_args; tf_alias } -> ( (* a name no function has is refused where the source is read *) match table_function cat tf_name with | f -> hidden_columns cat params s ~name:tf_name ~args:tf_args ~alias:(Option.value tf_alias ~default:tf_name) f | exception Catalog.Error _ -> s) | Table tr -> ( match eponymous cat s tr with | Some f when f.hidden <> [] -> hidden_columns cat params s ~name:tr.name ~args:[] ~alias:(Option.value tr.alias ~default:tr.name) f | _ -> s) | Select _ | Values _ | Unit -> s in let nested u = table_arguments cat params u in let rec expr e = Ast.map_expr ~select:nested expr e in let from : from_clause = match s.from with | Select { fs_select; fs_alias } -> Select { fs_select = nested fs_select; fs_alias } | f -> f in map_own_exprs expr { s with from; ctes = List.map (fun (c : cte) -> { c with query = nested c.query }) s.ctes; compound = List.map (fun (op, arm) -> (op, nested arm)) s.compound; } (* A recursive select's seed and arms, each a stripped non-compound core, whether its UNION drops duplicates, and the offset and bound its OFFSET and LIMIT set ({!recursive_bounds}). *) let recursive_parts cat name params query = let query = counts cat params query in let op = match query.compound with (op, _) :: _ -> op | [] -> Union_all in if query.order_by <> [] then Catalog.Error.fail_prepare "engine: ORDER BY in the recursive select of %s is not supported yet" (Ast.written_name name); let strip s = { s with compound = []; order_by = []; limit = None; offset = None } in ( strip query, List.map (fun (_, arm) -> strip arm) query.compound, op = Union, recursive_bounds params name query ) (* One catalog for every round of the recursive CTE [name], [name] reading the rows of the round before, and the function that sets those rows: the runner sees the same catalog and the same arm each round, so what it works out from the two alone it may keep, as sqlite3 codes the recursive step once and runs it per row of its queue. An answer kept against the catalog is of the rows a round read, so each round starts with none. *) let round_catalog cat name cols = let working = ref [] in let cat' = bind_relation cat name cols (fun () -> !working) in let rebind rows = working := rows; if Hashtbl.length cat'.subquery_memo > 0 then Hashtbl.reset cat'.subquery_memo in (cat', rebind) (* The rows of the recursive CTE [name], produced as they are read: the seed, then each round's rows, the arms run over the rows of the round before, so that a reader that stops early stops the recursion, as sqlite3 hands each row of its queue to the select reading the CTE before it makes the next (select.c, generateWithRecursiveQuery). The rows come in that queue's order, past the OFFSET and up to the LIMIT of the recursive select. *) let recursive_seq cat name cols params query () = let initial, arms, dedup_union, (offset, bound) = recursive_parts cat name params query in let cat', rebind = round_catalog cat name cols in (* The seed and each recursive arm are stripped non-compound cores, run through the catalog's runner, so a recursive CTE is evaluated by whatever runs the rest of the statement rather than by a path of its own. Each arm is prepared once, when the first round reaches it. *) let steps = lazy (List.map (fun arm -> cat'.prepare cat' arm params) arms) in let fresh = if dedup_union then unseen () else fun _ -> true in (* the delta a round contributes: its fresh rows, cut at the bound *) let admit total delta = let delta = List.filter fresh delta in match bound with | None -> (delta, List.length delta) | Some b -> first_n (b - total) delta in (* [rows] of the round [round] handed out, then the round after it; [total] counts every row admitted so far *) let rec emit rows ~total round () = match rows with | r :: rest -> Seq.Cons (r, emit rest ~total round) | [] -> next ~total round () and next ~total round () = if round = [] || bound = Some total then Seq.Nil else begin rebind round; let delta = List.concat_map (fun step -> step ()) (Lazy.force steps) in let delta, n = admit total delta in if delta = [] then Seq.Nil else if total + n > cat.recursion_cap then Catalog.Error.fail_runtime "recursive CTE exceeded %d rows" cat.recursion_cap else emit delta ~total:(total + n) delta () end in rebind []; let seed, n = admit 0 (cat'.subquery cat' [] initial params) in Seq.drop offset (emit seed ~total:n seed) () let materialize_ctes cat params ctes = let scope = ref cat in let bind acc (c : cte) = let cols = memo (fun () -> Resolve.cte_columns (resolve_env !scope) c) in let rows = memo (fun () -> match cte_shape c with | Circular -> Catalog.Error.fail_prepare "circular reference: %s" (Ast.written_name c.name) | Recursive -> List.of_seq (recursive_seq !scope c.name cols params c.query) | Plain -> !scope.subquery !scope [] c.query params) in let holds = let reading = ref false in fun col -> if !reading then None else Fun.protect ~finally:(fun () -> reading := false) (fun () -> reading := true; let published = try !scope.columns c.name with Catalog.Error (Prepare _ | Runtime _) -> [] in Option.bind (Catalog.Ident.index col published) (Resolve.output_affinity (resolve_env !scope) c.query)) in (* A recursive CTE's rows can also be read as the recursion makes them, which a reader that stops early stops ({!recursive_seq}). *) let stream = match cte_shape c with | Recursive -> Some (fun () -> recursive_seq !scope c.name cols params c.query ()) | Circular | Plain -> None in guard_relation c.name (bind_relation ~holds ?stream acc c.name cols rows) in scope := List.fold_left bind cat ctes; !scope