(*--------------------------------------------------------------------------- Copyright (c) 2025 Thomas Gazagnaire. All rights reserved. SPDX-License-Identifier: ISC ---------------------------------------------------------------------------*) (** SQL query execution over any store. [Query] runs queries over a {!catalog}, which gives the columns and rows of each table, so comparisons, [LIKE], joins and ordering do not depend on the store and can be tested alone. The catalog uses {!Catalog.Value.t}, and [Query] converts to and from {!Ast.value}. *) include module type of Query_intf val default_recursion_cap : int (** [default_recursion_cap] is the cap on a recursive CTE a catalog takes when its caller names none, the one {!Connection.v} applies. *) val closed : encoding:Encoding.t -> string -> catalog (** [closed ~encoding what] is a catalog with no relation, over text stored in [encoding], for an expression that may read none: a [DEFAULT], a generated column, a [CHECK]. Every lookup of a relation raises [Catalog.Error (Runtime _)] naming [what]; it has no function of its own and takes {!default_recursion_cap}. *) val of_catalog : recursion_cap:int -> subquery: (catalog -> (string * (string * Catalog.Value.t) list) list -> Ast.select -> Catalog.Value.t array -> Catalog.Value.t list list) -> Catalog.t -> catalog (** [of_catalog ~recursion_cap ~subquery cat] is the catalog of [cat], with [subquery] as its runner, usually from {!Engine.run_select}, and the positive [recursion_cap] as its {!field-recursion_cap}. Its {!field-encoding} is UTF-8, the text a {!Catalog.Spi.S} backend holds. A backend such as Irmin or Parquet implements {!Catalog.Spi.S} and adapts it here. The catalog has no functions of its own. *) val table_function : catalog -> string -> Func.table_function (** [table_function cat name] is the table-valued function [name]: the one of the backend ({!field-table_function}) if it has one, and the one of {!Func} otherwise. @raise Catalog.Error if neither has [name]. *) val table_arguments : catalog -> Ast.value array -> Ast.select -> Ast.select (** [table_arguments cat params s] is [s] with the hidden columns of each table-valued function in a FROM read, in [s] and the selects it nests: an argument the call left out is the value a WHERE equality gives its hidden column, as sqlite3's xBestIndex takes it, and a reference to a hidden column is the value it holds ({!Func.type-table_function}). A name that no table holds and a table-valued function answers is that function, called with no argument. A function whose arguments read a column is left as it is. *) val call : catalog -> ?coll:Collation.t -> string -> Ast.value list -> Ast.value (** [call cat ~coll name args] is the scalar function [name] applied to [args]: the one of the backend ({!field-scalar_function}) if it has one, and [Func.apply ~coll name args] otherwise. Every evaluator calls functions through it. @raise Catalog.Error as {!Func.apply} does. *) val called_name : Ast.expr -> string option (** [called_name e] is the name of the function [e] calls, under its [FILTER], [ORDER BY] and [OVER] decorations, or [None] if [e] is no call. *) val check_calls : ?explain:bool -> catalog -> Ast.select -> unit (** [check_calls ~explain cat s] accepts [s] if its stars expand ({!Resolve.check_stars}) and every call in its select list, [WHERE], [GROUP BY], [HAVING], [ORDER BY] and join conditions names a function that {!val-call} accepts with that number of arguments, in a clause that admits it, or raises. As in sqlite3, stars and calls are checked when the statement is prepared, so a bad name fails even over an empty table. A function of the backend accepts any number of arguments. Subqueries are checked elsewhere. [explain] (defaults to [false]) accepts unknown names but still checks argument counts, as sqlite3 does for [EXPLAIN]. A clause admits what resolve.c lets it hold: the select list and the [ORDER BY] an aggregate and a window function, the [GROUP BY] and the [HAVING] an aggregate, a [WHERE] and a join condition an aggregate only where [s] folds groups ({!is_aggregate_query}), and neither in the arguments, [FILTER] or [ORDER BY] of an aggregate; the arguments and keys of a window admit no window. The rows of a VALUES list admit both, but one of several rows that holds an aggregate, in a list that leads no compound, is refused as select.c codes it, ["misuse of aggregate: f()"] naming the last such call. @raise Catalog.Error as {!Resolve.check_stars} does, then as {!Func.apply} does: ["no such function: f"] for an unknown name, and ["wrong number of arguments to function f()"] for a wrong count. A built-in scalar function at the head of a window fails with ["f() may not be used as a window function"], and a window function called without one, or where its clause admits none, with {!Func.window_misuse}'s sentence. An aggregate where its clause admits none fails with ["misuse of aggregate function f()"], and one in the [GROUP BY] with ["aggregate functions are not allowed in the GROUP BY clause"]. A subquery of [n] columns fails with ["row value misused"] as one side of a comparison whose other side differs in width, and with ["sub-select returns n columns - expected 1"] where one value is read. *) val check_select : catalog -> Ast.select -> unit (** [check_select cat s] is {!check_calls} over each arm of [s], and {!Resolve.check_subqueries} with {!check_calls} over every select each arm holds: what sqlite3 resolves of a top-level select before it reads a row, so that a subquery no row reaches, or whose select list an [EXISTS] never computes ({!exists_body}), is resolved all the same. @raise Catalog.Error as those do. *) val check_expr_calls : catalog -> Ast.expr -> unit (** [check_expr_calls cat e] is {!check_calls} over the calls of [e] and of every select [e] holds, as sqlite3 checks an [INSERT]'s, an [UPDATE]'s or a [DELETE]'s expressions when it prepares the statement: [e] itself admits neither an aggregate nor a window function. @raise Catalog.Error as {!check_calls} does. *) val resolve_env : catalog -> Resolve.env (** [resolve_env cat] is the schema of [cat] as {!Resolve} reads it, without rows, indexes or runner. *) val within_build_budget : Catalog.Value.t list list -> bool (** [within_build_budget rows] is [true] iff a hash over [rows] stays within {!Join.budget}. It stops counting at the first row past the budget. *) type binding = string * (string * Ast.value) list (** The type for named rows, [(alias, [(column, value); ...])]. A [scope] is an outer list of bindings, after those of the row, so an inner column hides an outer one of the same unqualified name, and [alias.col] still reaches it. It holds the enclosing row of a correlated subquery, or the [OLD] and [NEW] rows of a trigger. *) val reads_table : ?view:(string -> Ast.select option) -> string -> Ast.select -> bool (** [reads_table ~view name s] is [true] iff [s] reads the relation [name], without regard to case, in its [FROM], a join, a compound arm, a nested [WITH] body or a subquery, or in the body [view v] of a view [v] it reads. [view] defaults to no view. *) val counts : catalog -> Ast.value array -> Ast.select -> Ast.select (** [counts cat params s] is [s] with a [LIMIT] or an [OFFSET] that is neither a literal nor a bound parameter replaced by its value, computed once over [cat] as sqlite3 computes it before the select runs. A [WITH] table's own counts are {!materialize_ctes}'s. @raise Catalog.Error if one reads a column, which nothing binds there, or folds an aggregate. *) val materialize_ctes : catalog -> Ast.value array -> Ast.cte list -> catalog (** [materialize_ctes cat params ctes] is [cat] with the rows of each [WITH] table of [ctes] bound under its name, a recursive one computed by semi-naive evaluation. It serves the [WITH] of an [UPDATE] or a [DELETE]. *) val factor_disjunctions : Ast.select -> Ast.select (** [factor_disjunctions s] is [s] with each conjunct that every disjunct of an [OR] in its [WHERE] carries hoisted out of the [OR]: [(A AND B) OR (A AND C)] is [A AND (B OR C)], as sqlite3 rewrites it (whereOrInfo, src/where.c), so a join equality written into each disjunct is one the planner sees. Only a comparison of columns and literals is hoisted. *) val flatten_ctes : catalog -> Ast.select -> Ast.select (** [flatten_ctes cat s] is [s] with each [WITH] table that one [FROM] reads exactly once merged into that reader: the table of the body takes the name of the CTE, and the [WHERE] of the body joins the [WHERE] of the reader, so an index can serve it. As in sqlite3 ([flattenSubquery], src/select.c), the body must read one plain table and have no aggregate, [DISTINCT], compound, recursion, window, [LIMIT], [OFFSET] or [ORDER BY]. Other CTEs stay for {!materialize_ctes}. *) val flatten_subqueries : ?moved:(Ast.select -> Ast.select -> unit) -> catalog -> Ast.select -> Ast.select (** [flatten_subqueries ?moved cat s] is [s] as sqlite3 rewrites a select before coding it (select.c, sqlite3Select): - the subquery its [FROM] reads alone is merged into it (flattenSubquery): the subquery's tables become those of [s], its [WHERE] leads that of [s], and each name [s] gives a column of it is the expression the subquery computes the column by, a result column keeping its name. The subquery reads stored tables through inner or [LEFT] joins and has no aggregate, [DISTINCT], compound, [WITH], window, [LIMIT], [OFFSET] or [ORDER BY]; [s] has no compound or window, reads nothing but the subquery's columns outside its [FROM] and nests no select there, and no [COLLATE], written or declared, meets a moved expression; - each [FROM] subquery left loses an [ORDER BY] that does nothing there (tag-select-0230) and takes a copy of each term of [s] that constrains it alone, its columns replaced by the expressions computing them, in its [HAVING] where it is an aggregate, else its [WHERE] (pushDownWhereTerms); [moved] is told each subquery so rewritten, the new one first; - each [HAVING] term of [s] that reads nothing but constants and [GROUP BY] keys of BINARY sequence moves to its [WHERE] (havingToWhere). *) type membership = { states : Value_ops.affinity option; (** The affinity of the compared column, combined with the affinity of the left operand as for a comparison (src/expr.c). *) rows : Catalog.Value.t list option; (** The first column of the rows of an uncorrelated subquery, which the register VM compiles as a list. [None] for a correlated subquery, which runs for each outer row. *) } (** The type for the right-hand side of [x IN (SELECT ...)], from which {!Lower.query} builds the membership. *) val opaque_membership : membership (** [opaque_membership] states no affinity and holds no rows. *) val closed_rows : run:(Ast.select -> Ast.value list list) -> params:Ast.value array -> catalog -> Ast.select -> Ast.value list list (** [closed_rows ~run ~params cat s] is [run s], computed once for [cat] under [params] and kept in its {!field-subquery_memo}: the rows of a subquery that reads no outer row, which a statement runs once. *) val membership : run:(Ast.select -> Ast.value list list) -> params:Ast.value array -> catalog -> Ast.select -> membership (** [membership ~run ~params cat sub] is the affinity of the compared column of [sub] and, if [sub] is uncorrelated, the values of that column, computed with [run] under [params] and cached in [cat]. *) val lift_outer_aggregates : Resolve.env -> Ast.select -> Ast.select (** [lift_outer_aggregates env s] is [s] with each aggregate a subquery of its select list, [HAVING] or [ORDER BY] computes over [s]'s columns alone made [s]'s, as sqlite3 attributes it: [s] then reads its aggregates off a grouped select over its sources. A select with no such aggregate is [s] itself. @raise Catalog.Error on such an aggregate in [s]'s [WHERE], [GROUP BY] or a join condition, and, as not supported, in a compound select, beside a window function or beside a [*] over a [NATURAL] or [USING] join. *) val exists_body : Ast.select -> Ast.select (** [exists_body s] is the select an [EXISTS (s)] runs: [s] with each result column it does not compute replaced by a constant, and without its [ORDER BY] and [DISTINCT], as sqlite3 codes no result column of a select whose rows an [EXISTS] only counts (select.c, selectInnerLoop). A column under an aggregate, one the [WHERE] reads through its alias and a [*] stay, an [ORDER BY] holding an ordinal stays, and so does a compound whose operator compares its rows: [EXCEPT], [INTERSECT] and a [UNION] under an [OFFSET]. Its names are resolved before, by the statement's prepare. *) val exists_to_join : ?moved:(Ast.select -> Ast.select -> unit) -> table:(Ast.table_ref -> bool) -> Resolve.env -> Ast.select -> Ast.select (** [exists_to_join ?moved ~table env s] is [s] with each [EXISTS (SELECT ...)] that is a conjunct of its [WHERE] joined to it, as sqlite3 rewrites one (select.c, existsToJoin): where the subquery reads one table [table] accepts, a stored table rather than a view or a [WITH] table, and has no aggregate, no [LIMIT], no compound and no [WHERE] naming a [WITH] table of its own, and [s] has no [OFFSET], no compound and no [RIGHT] or [FULL] join. A select with no [FROM] joins it all the same. The table joins [s] as an {!Ast.constructor-Semi} source under a {!Resolve.semi_alias}, the subquery's [WHERE], its names bound as they were ({!Resolve.requalify}), joins the end of the [WHERE] of [s], and [1] stands where the [EXISTS] stood. Any other [s] is returned as it is. [moved] is told each select nested in a moved [WHERE] as it is rewritten, the new one first. *) val hoist_subqueries : run:(Ast.select -> Ast.value list list) -> params:Ast.value array -> catalog -> Ast.select -> Ast.select (** [hoist_subqueries ~run ~params cat s] is [s] with each uncorrelated scalar or [EXISTS] subquery in its select list, [WHERE], [GROUP BY], [HAVING], [ORDER BY] and join conditions replaced by its value, computed with [run] under [params], stating the affinity of its result column ({!Ast.constructor-Affinity}) as sqlite3 reads a subquery's. An uncorrelated subquery is constant, and the register VM, which has no subquery instruction, can then compile [s]. A literal [v IN (SELECT c ...)] over an uncorrelated subquery that only narrows its sources is replaced by true where a row with [c = v] exists, which an index on [c] answers with a seek. Correlated subqueries stay, and {!membership} handles the other [IN (SELECT ...)]. *) val is_aggregate_query : Ast.select -> bool (** [is_aggregate_query s] is [true] iff [s] has a [GROUP BY], a [HAVING] or an aggregate in its select list. Its [LIMIT] cannot move into the scan. *) val aggregate_compilable : Ast.select -> bool (** [aggregate_compilable s] is [true] iff [s] aggregates and has no window ({!select_windows}), so the register VM runs it as a grouped query. An aggregate over [rowid], such as [count(rowid)], compiles. *) val window_compilable : Ast.select -> bool (** [window_compilable s] is [true] iff [s] has a window function, does not aggregate and does not project [rowid], so the register VM scans it and {!Window.scan} computes the windows. *) val window_over_groups : Ast.select -> bool (** [window_over_groups s] is [true] iff [s] aggregates and has a window function, which runs over the grouped rows. {!Engine.run_select} runs such a select; a backend should pass it there. *) val is_agg_expr : Ast.expr -> bool (** [is_agg_expr e] is [true] iff [e] is an aggregate call, with or without [DISTINCT], [FILTER] or [ORDER BY] inside the call. It does not look into the operands of [e]. *) val window_exprs : Ast.result_col list -> Ast.expr list (** [window_exprs cols] is the distinct [Window] nodes of [cols], in order of first appearance. It does not look into a [Window] node. *) val min_max : Ast.select -> (Ast.expr * [ `Min | `Max ] * bool) option (** [min_max s] is the argument of the one aggregate of [s], which of min() and max() it is and whether it is DISTINCT, where [s] is a min/max query as sqlite3 plans one (select.c, minMaxQuery): an aggregate in its select list, no [GROUP BY], no [HAVING], no window, and one aggregate call in its select list and its [ORDER BY], a call spelled twice counting once, which is [min] or [max] of one argument with no [FILTER]. It is [None] for any other select. *) val select_windows : Ast.select -> Ast.expr list (** [select_windows s] is the distinct [Window] nodes [s] computes, in order of first appearance: those of its select list, then those only its [ORDER BY] names (lang_select.html section 2). *) val set_op : ?colls:Collation.t option list -> Ast.set_op -> Ast.value list list -> Ast.value list list -> Ast.value list list (** [set_op ~colls op left right] combines the rows of two compound arms. [UNION ALL] keeps every row in order. [UNION], [EXCEPT] and [INTERSECT] give distinct rows in key order, as sqlite3 does with an index on the row. [colls] is the collating sequence of each column ({!Resolve.compound_collations}); [None] or a missing entry is BINARY. Of rows with equal keys, the first one is kept. *) val facts : catalog -> Plan.facts (** [facts cat] is what the planner knows of [cat]: its columns and affinities, its best index for an equality, the size of a relation, and what its seeks can do. A seek key is a constant or a column of an outer row, and a row found by a seek has no rowid. *) val plan : catalog -> Ast.select -> Plan.t (** [plan cat s] is the access path of each source of [s] and the order of the loop, [Plan.v] of {!facts}. {!Engine.run_select} runs this plan and {!explain} prints it. It uses the query as written, without parameter values or subquery results. The [WITH] tables of [s] are bound ({!materialize_ctes}) for their columns only; their rows are not computed. *) val plan_sources : catalog -> Ast.select -> Plan.access list (** [plan_sources cat s] is the accesses of [plan cat s], in scan order: the [FROM] source, then each join operand. *) (** The type for the value a seek binds a key column to: a value known before the loop, or [Outer (i, j)], column [j] of the cursor at scan position [i] where the loop stands when the seek rewinds. *) type seek_key = Value of Ast.value | Outer of int * int val seek_keys : catalog -> Ast.value array -> Plan.access -> (string * seek_key) list option (** [seek_keys cat params access] is each key column of the seek [access] with the value it binds, a constant, parameter or closed subquery evaluated over [params]. It is [None], and the caller reads the whole relation, if [access] is not a seek or a key has no single value, such as an unbound parameter or an IN list. The rows {!field-index_scan} answers have no rowid, so {!plan} uses no seek for a query that reads one. *) val explain : catalog -> Ast.select -> string (** [explain cat select] is {!plan} of [select], after the rewrites the engine applies, as one line per source in scan order, such as [SCAN t] or [SEARCH t USING INDEX i]. It first checks the names with {!Resolve.check_columns} and with {!check_calls} under [~explain:true]. @raise Catalog.Error for a name that resolves to no column. @raise Catalog.Error for a source naming a relation the store has not got. *) val is_agg : string -> Ast.expr list -> bool (** [is_agg name args] is [true] iff [name] with the arguments [args] is an aggregate, such as [count], [sum] or [avg], or [min] and [max] with at most one argument. *) val is_rowid_name : string -> bool (** [is_rowid_name n] is [true] iff [n] is [rowid], [oid] or [_rowid_], without regard to case (lang_createtable.html section 2.6). A declared column of that name comes first. *)