(*--------------------------------------------------------------------------- Copyright (c) 2026 Thomas Gazagnaire. All rights reserved. SPDX-License-Identifier: ISC ---------------------------------------------------------------------------*) module V = Catalog.Value let unsupported () = raise Ir.Unsupported (* The kind of a subquery a lowering registers: a correlated scalar value, an [EXISTS] test or an [IN (SELECT)] membership, or the held answer of an uncorrelated membership. *) type subkind = | Scalar | Exists | In of Ir.comparison | Member of Value_op.in_set type layout = (string * string list) list type lowering = { env : Resolve.env option; layout : layout; affinity : int * int -> Value_ops.affinity option; membership : Ast.select -> Query.membership; equated : (int * int) list; kind : Resolve.layout_kind; coalesced : ((int * int) * (int * int)) list; trigger : bool; binary : Collation.t option; (** what a text under BINARY is ordered under: [None], the VM's own byte order, over a UTF-8 catalog; the stored bytes' order ({!Collation.binary}) over a UTF-16 one *) mutable subs : (subkind * Ast.select) list; mutable nsubs : int; } (* [sub] as it runs beside the layout: each column of it reads states its affinity, which the value bound in its place keeps ({!Resolve.enclosing_affinity}). Without the names [sub] binds itself there is no telling which columns are the layout's, and [sub] is left as it is, which {!register_sub} refuses to run. *) let enclosing lw sub = match lw.env with | Some env -> Resolve.enclosing_affinity env lw.layout ~affinity:lw.affinity sub | None -> sub (* A subquery run at each row, as {!enclosing} gave it; a held membership reads no row. *) let register_sub lw kind sub = let id = lw.nsubs in (match (kind, lw.env) with | (Scalar | Exists | In _), None -> unsupported () | Member _, _ | (Scalar | Exists | In _), Some _ -> ()); lw.subs <- (kind, sub) :: lw.subs; lw.nsubs <- id + 1; id (* The sources of the layout a column name of [sub] may read, wherever in [sub] it stands, a name [sub] binds itself counted too: more than it reads rather than fewer, since the loop runs it once they are all in place. A table joined from an EXISTS answers its qualified names alone. *) let one_source = [ 0 ] let sub_reads lw (sub : Ast.select) = (* one source is read whatever the names, and placed nowhere else *) if List.compare_length_with lw.layout 1 <= 0 then one_source else let found = Array.make (List.length lw.layout) false in let col () qual name = List.iteri (fun i (a, cols) -> let bears = match qual with | None -> not (Resolve.is_semi_alias a) | Some q -> Ast.ident_equal q a in if bears && (List.exists (Ast.ident_equal name) cols || Ast.is_rowid_name name && List.mem Resolve.rowid_sentinel cols) then found.(i) <- true) lw.layout in Resolve.walk_select ~table:(fun () _ -> ()) ~col ~nest:(fun () _ -> ()) ~cte:(fun () _ -> Some ()) () sub; List.filter (fun i -> found.(i)) (List.init (Array.length found) Fun.id) let trigger_domains : Domain.id list Atomic.t = Atomic.make [] (* [Domain.id] is a private int, so one domain is another exactly where the integers are equal; spelling the comparison on the int says which equality this is rather than leaving it to the structural one. *) let same_domain (a : Domain.id) (b : Domain.id) = Int.equal (a :> int) (b :> int) let rec enter_program d = let held = Atomic.get trigger_domains in if not (Atomic.compare_and_set trigger_domains held (d :: held)) then enter_program d let rec leave_program d = let held = Atomic.get trigger_domains in (* one entry, not every entry: a program reached from inside another leaves the outer one running *) let rec drop = function | x :: t when same_domain x d -> t | x :: t -> x :: drop t | [] -> [] in if not (Atomic.compare_and_set trigger_domains held (drop held)) then leave_program d let in_trigger_program f = let d = Domain.self () in enter_program d; Fun.protect ~finally:(fun () -> leave_program d) f (* Whether this domain is running a trigger program. *) let in_program () = match Atomic.get trigger_domains with | [] -> false | held -> List.exists (same_domain (Domain.self ())) held (* The IR's per-run hooks are the frontend's own functions, called directly: the frontend and the engine share {!Catalog.Value.t}, so no value conversion sits between them, and a query the IR runs agrees with one the frontend evaluates by sharing the code. *) let hooks : Ir.hooks = { call = (fun name coll args -> Func.apply ?coll name args); cast = Value_ops.cast; op = Sqlite3_semantics.op_value; subquery = (fun _ _ _ -> unsupported ()); } (* The bytes a value is stored as in [e], where sqlite3 reads a value's bytes: a text's in the encoding, a number's rendering likewise, a blob's its own. *) let stored_bytes e : Catalog.Value.t -> string option = function | Text s -> Some (Encoding.of_utf8 e s) | Blob b -> Some b | Null -> None | v -> Some (Encoding.of_utf8 e (Value_ops.text_of_value v)) let stored_text e (b : Ir.hooks) : Ir.hooks = let call name coll (args : Catalog.Value.t list) = match (String.lowercase_ascii name, args) with | "hex", [ Text s ] -> b.call name coll [ Blob (Encoding.of_utf8 e s) ] | "octet_length", [ ((Text _ | Int _ | Float _) as v) ] -> b.call name coll [ Blob (Option.get (stored_bytes e v)) ] | _ -> b.call name coll args in let cast ty (v : Catalog.Value.t) : Catalog.Value.t = match (Value_ops.affinity_of_type ty, v) with | `Blob, (Text _ | Int _ | Float _) -> Blob (Option.get (stored_bytes e v)) | (`Text | `Numeric | `Integer | `Real), Blob x -> b.cast ty (Text (Encoding.to_utf8 e x 0 (String.length x))) | _ -> b.cast ty v in let op o (va : Catalog.Value.t) (vb : Catalog.Value.t) = match (o, va, vb) with | Ir.Concat, Blob _, (Text _ | Blob _ | Int _ | Float _) | Ir.Concat, (Text _ | Int _ | Float _), Blob _ -> (* sqlite3 joins the two as text in [e] and keeps an even count of bytes (vdbe.c, OP_Concat) *) let x = Option.get (stored_bytes e va) ^ Option.get (stored_bytes e vb) in Catalog.Value.Text (Encoding.to_utf8 e x 0 (String.length x land lnot 1)) | _ -> b.op o va vb in { b with call; cast; op } (* The comparison, opcode-free, and arithmetic operator groups of [Ast.binop]. *) let is_cmp : Ast.binop -> bool = function | Eq | Neq | Lt | Le | Gt | Ge -> true | _ -> false let is_logic : Ast.binop -> bool = function | And | Or | Like | Glob | Concat | Json_get | Json_get_text -> true | _ -> false let ir_cmp : Ast.binop -> Ir.binop = function | Eq -> Eq | Neq -> Ne | Lt -> Lt | Le -> Le | Gt -> Gt | Ge -> Ge | _ -> unsupported () let ir_logic : Ast.binop -> Ir.logicop = function | And -> And | Or -> Or | Like -> Op Like | Glob -> Op Glob | Concat -> Op Concat | Json_get -> Op Json_get | Json_get_text -> Op Json_get_text | _ -> unsupported () let ir_arith : Ast.binop -> Ir.binop = function | Add -> Add | Sub -> Sub | Mul -> Mul | Div -> Div | Mod -> Mod | Bit_and -> Band | Bit_or -> Bor | Shl -> Shl | Shr -> Shr | _ -> unsupported () (* The position of the column named [name] in [cols], matched as an identifier. *) let col_index name cols = Catalog.Ident.index name cols (* The test [a IS TRUE] for a [Truth w] spelling true, and [a IS FALSE] for one spelling false: [a <> 0] or [a = 0] with a NULL [a] false, so the answer is 0 or 1 and never NULL (resolve.c, the TK_IS case, which makes it TK_TRUTH). *) let truth_test a w = let zero = Ast.Lit (Int 0L) and one = Ast.Lit (Int 1L) in let op = if Ast.ident_equal w "true" then Ast.Neq else Eq in Ast.Case (None, [ (Binary (op, a, zero), one) ], Some zero) (* Where [alias.name] (or a bare [name]) reads its value in the layout, the rowid fallback included. {!Resolve.layout_slot} is the rule, and it is read from there rather than restated: the same reference is resolved by {!Resolve.check_columns} to decide whether the statement resolves at all, and a second copy of the rule is a statement described that cannot run. *) let col = Resolve.layout_slot let resolve_col lw alias name = (* a qualified reference is named in full, as sqlite3 names it: "no such column: t.nocol", not just the bare column *) match col lw.kind lw.layout alias name with | Some r -> r | None -> ( match alias with | Some a -> Catalog.Error.fail_prepare "no such column: %s.%s" a name | None -> Catalog.Error.fail_prepare "no such column: %s" name) let collation_of = Collate.sequence (* What a bare [true] or [false] reads: the column of that name where the scope publishes one, else the integer (resolve.c, lookupName, then sqlite3ExprIdToTrueFalse). *) let truth lw name = match col lw.kind lw.layout None name with | Some _ -> Ast.Col (None, name) | None -> Ast.Lit (Ast.truth_value name) (* [a IS true] tests truthiness where [true] names no column, and compares with the column where one does (resolve.c, the TK_IS case resolves its right operand first). *) let is_truth_test lw w = match truth lw w with Ast.Lit _ -> true | _ -> false (* Whether [e] is always true or always false as sqlite3 knows it at code generation (EP_IsTrue, EP_IsFalse): an integer literal an int holds, or TRUE or FALSE where it names no column. *) let constant_truth lw : Ast.expr -> bool option = function | Lit (Int n) when n >= 0L && n <= 0x7fff_ffffL -> Some (n <> 0L) | Truth w -> ( match truth lw w with Lit (Int n) -> Some (n <> 0L) | _ -> None) | _ -> None (* expr.c, sqlite3ExprSimplifiedAndOr: an AND or OR one of whose operands, once simplified, is always true or always false is coded as one operand alone, so the other is never coded -- a literal it holds is never refused. [e] itself when neither is. *) let rec simplified_and_or lw (e : Ast.expr) = match e with | Binary (((And | Or) as op), a, b) -> let a' = simplified_and_or lw a and b' = simplified_and_or lw b in let is v x = constant_truth lw x = Some v in if is true a' || is false b' then if op = And then b' else a' else if is true b' || is false a' then if op = And then a' else b' else e | e -> e let rec ast_affinity lw = function | Ast.Col (alias, name) -> lw.affinity (resolve_col lw alias name) | Ast.Truth name -> ( match truth lw name with Ast.Col _ as c -> ast_affinity lw c | _ -> None) | Ast.Collate (e, _) -> ast_affinity lw e | Ast.Cast (_, ty) -> Some (Value_ops.affinity_of_type ty) | Ast.Affinity (_, aff) -> Some aff (* a scalar subquery states its result column's, as a membership's right operand does (expr.c, sqlite3ExprAffinity of a TK_SELECT) *) | Ast.Scalar_select sub -> (lw.membership (enclosing lw sub)).Query.states | _ -> None (* The sequence a comparison compares text under: the left operand's if it names one, else the right's (datatype3.html sec.7.1 rule 1). BINARY is the default, so naming it is the same as naming none -- but only after the rule has picked a side, or a left [COLLATE BINARY] would lose to a right [COLLATE NOCASE] it is supposed to beat. *) let comparison_collation lw a b = match match collation_of a with Some _ as c -> c | None -> collation_of b with | Some Collation.Binary | None -> lw.binary | c -> c (* What a comparison of [a] and [b] applies to both operands: the one affinity {!Value_ops.compare_affinity} computes for the pair from the two operands' own, and the sequence the collation rule picks. *) let comparison_of lw a b : Ir.comparison = { aff = Value_ops.compare_affinity (ast_affinity lw a) (ast_affinity lw b); coll = comparison_collation lw a b; } (* The sequence an operand carries on its own -- a membership's left operand, a sort / group / dedup key. BINARY is the default, so naming it explicitly is the same as naming none. *) let nonbinary_collation lw e = match collation_of e with Some Collation.Binary | None -> lw.binary | c -> c (* The sequence a call that compares its argument values runs under ({!Collate.call_sequence}): the scalar [min]/[max]/[nullif] and the [min]/[max] aggregate fold make the same read. *) let arguments_collation lw args = match Collate.call_sequence args with None -> lw.binary | c -> c let strip_collate = Collate.strip (* A scalar call, with the sequence it compares its arguments under. [min], [max] and [nullif] compare theirs, so the call carries the sequence {!arguments_collation} reads, and the wrappers come off once read, exactly as a comparison's do. Every other function compares nothing and carries none. *) let func_call lw lower name args : Ir.expr = let args = Func.json_arguments name args in if not (Collate.compares_its_arguments name) then Func (name, None, List.map lower args) else Func ( name, arguments_collation lw args, List.map (fun a -> lower (strip_collate a)) args ) let join_column lw (c, j) = match List.assoc_opt (c, j) lw.coalesced with | None -> Ir.Col (c, j) | Some (jc, jj) -> Ir.Func ("coalesce", None, [ Ir.Col (c, j); Ir.Col (jc, jj) ]) let is_expr lw op_of a b : Ir.expr = Is (comparison_of lw a b, op_of (strip_collate a), op_of (strip_collate b)) (* A membership whose subquery reads nothing of the row is answered from its rows, which ran once. A short list is compared in place, as a written one is; past [held_membership] values the rows are held sorted ({!Value_op.in_set}) and each row's operand is looked up, so the outer scan costs a search per row rather than a pass over the inner rows. *) let held_membership = 8 let in_select lw op_of e sub : Ir.expr = let sub = enclosing lw sub in let rhs = lw.membership sub in let c : Ir.comparison = { aff = Value_ops.compare_affinity (ast_affinity lw e) rhs.Query.states; coll = nonbinary_collation lw e; } in let left = op_of (strip_collate e) in match rhs.Query.rows with | Some vs when List.compare_length_with vs held_membership > 0 -> let held = Value_op.in_set ?aff:c.aff ?coll:c.coll vs in Subquery (register_sub lw (Member held) sub, Some left, []) | Some vs -> In (left, c, List.map (fun v -> Ir.Lit v) vs) | None -> Subquery (register_sub lw (In c) sub, Some left, sub_reads lw sub) (* The action a [RAISE()] carries, as the IR spells it. The grammar's raisetype production admits exactly these four (parser.mly, [raise_arg]), so the two remaining conflict clauses -- the unspecified one and REPLACE -- name no raisetype and cannot be written here. *) let raise_action : Ast.insert_conflict -> Ir.raise_action = function | Ignore -> Ignore | Abort -> Abort | Fail -> Fail | Rollback -> Rollback | Unspecified | Replace -> Catalog.Error.fail_prepare "RAISE() takes ABORT, FAIL, ROLLBACK or IGNORE" let raise_expr lw lower action message : Ir.expr = if not lw.trigger then Catalog.Error.fail_prepare "RAISE() may only be used within a trigger-program" else Raise (raise_action action, Option.map lower message) let rec expr lw (e : Ast.expr) : Ir.expr = match e with | Lit v -> Lit v | Numeral s -> Lit (Ast.code_number s) | Param i -> Param i | Named_param _ -> Param Param_number.unnumbered | Col (alias, name) -> ( let c, j = resolve_col lw alias name in match alias with Some _ -> Col (c, j) | None -> join_column lw (c, j)) | Truth name -> expr lw (truth lw name) | Unop_not e -> Not (expr lw e) (* Unary [+] is a value no-op, so it lowers to nothing. What it does change -- the operand's affinity and its being a column -- is decided on the AST, by [is_col_ast] and [states_affinity], before the lowering gets here. *) | Unary_plus e -> expr lw e (* Unary [-] computes what a subtraction from zero computes, and is coded as one: sqlite3 keeps the operator only so a literal's text can be read with its sign (codeInteger, src/expr.c) and otherwise emits the same subtraction (OP_Subtract against a zero register). What the node buys is upstream of here -- the text a DEFAULT is stored and reported as. *) (* A minus over a numeral is its negated spelling: [-9223372036854775808] is [min_int], where [0 - 9223372036854775808] would be a real. *) | Unary_minus (Numeral s) -> Lit (Ast.code_number ~negative:true s) | Unary_minus e -> expr lw (Binary (Sub, Lit (Int 0L), e)) (* the operand left alone is coded as a truth value (OP_And r1, r1) *) | Binary ((And | Or), _, _) when simplified_and_or lw e != e -> Not (Not (expr lw (simplified_and_or lw e))) | Binary (op, a, b) -> if is_cmp op then cmp_expr lw op a b else if is_logic op then Logic (ir_logic op, expr lw a, expr lw b) else Arith (ir_arith op, expr lw a, expr lw b) | Is_null e -> Null_value (true, expr lw e) | Is_not_null e -> Null_value (false, expr lw e) | Is (a, Truth w) when is_truth_test lw w -> expr lw (truth_test a w) | Is (a, b) -> is_expr lw (expr lw) a b (* datatype3.html sec.7.1: "the collating sequence used for expressions of the form x IN (y, z, ...) is the collating sequence of x". A COLLATE among the candidates names nothing, so its wrapper is only the value no-op it always is and comes off. *) | In_list (e, cands) -> In ( expr lw (strip_collate e), { aff = ast_affinity lw e; coll = nonbinary_collation lw e }, List.map (fun c -> expr lw (strip_collate c)) cands ) | Func ("iif", [ c; t; f ]) -> expr lw (Case (None, [ (c, t) ], Some f)) | Func (name, args) when not (Query.is_agg name args) -> func_call lw (expr lw) name args (* An aggregate the select does not fold, which the resolver admitted: the ORDER BY of a query that folds no group, or the scan of one that does. sqlite3 refuses it as it codes the call (expr.c, TK_AGG_FUNCTION with no AggInfo). *) | Func (name, _) -> Catalog.Error.fail_prepare "misuse of aggregate: %s()" name | Case (base, branches, els) -> let branch (c, r) = let p = match base with | None -> predicate lw c (* the base against this branch's value is an ordinary comparison, so it reads a collating sequence and states its affinity like one *) | Some b -> cmp_pred lw Ast.Eq b c in (p, expr lw r) in Case (List.map branch branches, Option.map (expr lw) els) | Cast (e, ty) -> Cast (expr lw e, ty) (* the affinity it states is read off the AST, by [ast_affinity], before the lowering gets here *) | Affinity (e, _) -> expr lw e (* A correlated subquery becomes an opaque [Subquery] node: register the [Ast.select] and its kind, and (for [IN]) lower the left operand whose value the membership test reads. An uncorrelated one is already folded to a constant before lowering ([Query.hoist_subqueries]), so what reaches here is correlated, run per outer row by the injected runner. *) | Scalar_select sub -> Subquery (register_sub lw Scalar (enclosing lw sub), None, sub_reads lw sub) | Exists sub -> Subquery ( register_sub lw Exists (enclosing lw (Query.exists_body sub)), None, sub_reads lw sub ) (* [Resolve.collations] leaves the sequence the membership compares under on the left operand, whichever end supplied it, so the registration reads it from there exactly as an [In_list] does. *) | In_select (e, sub) -> in_select lw (expr lw) e sub (* A schema this database has not got holds no table and so no column. sqlite3 resolves the qualifier against the attached databases and names the whole reference when it places none; the two contexts that ignore the qualifier instead have dropped it at the parse, so what reaches here is a query's, and a query's is an error. *) | Schema_col (s, t, c) -> Catalog.Error.fail_prepare "no such column: %s.%s.%s" s t c | Raise (action, message) -> raise_expr lw (expr lw) action message | Star | Qualified_star _ | Distinct_agg _ | Filter _ | Ordered_agg _ | Window _ | Collate _ -> unsupported () and predicate lw (e : Ast.expr) : Ir.predicate = match e with | Binary ((And | Or), _, _) when simplified_and_or lw e != e -> predicate lw (simplified_and_or lw e) | Binary (And, a, b) -> And (predicate lw a, predicate lw b) | Binary (Or, a, b) -> Or (predicate lw a, predicate lw b) | Binary (op, a, b) when is_cmp op -> cmp_pred lw op a b | Is_null e -> Null_test (true, expr lw (strip_collate e)) | Is_not_null e -> Null_test (false, expr lw (strip_collate e)) (* a bare [WHERE expr] keeps the truthy rows; [expr] itself rejects a shape the IR cannot model (a subquery, a window), falling the whole predicate back *) | e -> Truthy (expr lw (strip_collate e)) and cmp_expr lw op a b : Ir.expr = Cmp ( ir_cmp op, comparison_of lw a b, expr lw (strip_collate a), expr lw (strip_collate b) ) and cmp_pred lw op a b : Ir.predicate = let c = comparison_of lw a b in match c.coll with | Some _ -> Truthy (cmp_expr lw op a b) | None -> Compare (ir_cmp op, c, expr lw (strip_collate a), expr lw (strip_collate b)) let ir_dir = function Ast.Asc -> Ir.Asc | Ast.Desc -> Ir.Desc (* Lower an [ORDER BY] key with [lower_key] (over the scan, or the synthetic group row): its expression, direction, and collation. *) let order_key lw lower_key (e, d) = (lower_key (strip_collate e), ir_dir d, nonbinary_collation lw e) (* Expand a select item into its projected expressions: [*] and [t.*] become one column reference per source column. *) let project_item ?(hidden = lazy []) lw (rc : Ast.result_col) : Ir.expr list = match rc.expr with | Star -> (* [*] lists every source column, except a column a NATURAL / USING join hides (the right source's copy of a common column). *) List.concat (List.mapi (fun ci (a, cols) -> if Resolve.is_semi_alias a then [] else List.filter_map (fun j -> if List.mem (ci, j) (Lazy.force hidden) then None else Some (join_column lw (ci, j))) (List.init (List.length cols) Fun.id)) lw.layout) | Qualified_star q -> (* [t.*] lists [t]'s columns, skipping the hidden rowid slot. *) let rec go ci = function | (al, cols) :: t -> if Ast.ident_equal al q then List.filter_map (fun j -> if List.mem (ci, j) (Lazy.force hidden) then None else Some (join_column lw (ci, j))) (List.init (List.length cols) Fun.id) else go (ci + 1) t | [] -> unsupported () in go 0 lw.layout (* A projected [COLLATE] (or unary plus) produces the bare value -- the collation governs only comparison/ordering/dedup, captured separately in the query's ORDER BY keys and [distinct_colls]. *) | e -> [ expr lw (strip_collate e) ] (* The projected expressions of [s], and the sequence each is deduplicated under where [s] is DISTINCT; a select that dedups nothing carries none. *) let projection lw expand (s : Ast.select) = if not s.distinct then (List.concat_map expand s.cols, []) else let of_col (rc : Ast.result_col) = let cols = expand rc in let c = nonbinary_collation lw rc.expr in (cols, List.map (fun _ -> c) cols) in let cols, colls = List.split (List.map of_col s.cols) in (List.concat cols, List.concat colls) let count_int64 params (e : Ast.expr) = let value = match e with | Ast.Lit v -> Some v | Numeral s -> Some (Ast.code_number s) | Unary_minus (Numeral s) -> Some (Ast.code_number ~negative:true s) | Param i when i >= 0 && i < Array.length params -> Some params.(i) | _ -> None in (* OP_MustBeInt: the value under NUMERIC affinity, which takes integer text and a whole real to an integer, or a datatype mismatch *) match value with | None -> None | Some v -> ( match Value_ops.apply_affinity `Numeric v with | Ast.Int n -> Some n | _ -> Catalog.Error.fail Mismatch) (* A non-negative row count clamped to a native int: a value beyond the native range exceeds any materialised row count, so [max_int] is exact (keep all for a limit, skip all for an offset) without truncating to a wrong small number. *) let clamp_count n = if Int64.compare n (Int64.of_int max_int) >= 0 then max_int else Int64.to_int n (* The hidden rowid slots: any {!Resolve.rowid_sentinel} column a scan published. [Star] drops these so [SELECT *] never returns the implicit rowid. *) let sentinel_columns (layout : layout) = List.concat (List.mapi (fun ci (_, cols) -> List.filter_map (fun (j, c) -> if c = Resolve.rowid_sentinel then Some (ci, j) else None) (List.mapi (fun j c -> (j, c)) cols)) layout) (* The [(cursor, column)] positions a [*] does not list: the hidden rowid slots, and the joined source's copy of each column a NATURAL / USING join equated, which the join publishes once (lang_select.html sec.3). What a star stands for is settled by the FROM clause, so the set is the same over the scan and over a group row. *) let hidden_columns lw = lw.equated @ sentinel_columns lw.layout (* The scan filter: the [WHERE] alone. Every [ON] is its own join's, applied at that join's level -- which is what keeps the [ON]s of the joins before an outer one from re-testing the rows it padded. *) let filter_of lw (s : Ast.select) = match s.where with Some w -> predicate lw w | None -> Ir.Always (* Whether [count_int64] reads [e] without the parameters. *) let fixed_count = function | None | Some (Ast.Lit _ | Numeral _ | Unary_minus (Numeral _)) -> true | Some _ -> false let counts_fixed (s : Ast.select) = fixed_count s.limit && fixed_count s.offset (* A negative LIMIT is unbounded ([None]); a huge one clamps to [max_int] (every row kept); a non-literal one falls back (sqlite3). *) let limit_of params (s : Ast.select) = match s.limit with | None -> None | Some e -> ( match count_int64 params e with | None -> unsupported () | Some n when n < 0L -> None | Some n -> Some (clamp_count n)) (* A negative OFFSET is zero; a huge one clamps to [max_int] (every row skipped); a non-literal one falls back (sqlite3). *) let offset_of params (s : Ast.select) = match s.offset with | None -> 0 | Some e -> ( match count_int64 params e with | None -> unsupported () | Some n when n < 0L -> 0 | Some n -> clamp_count n) let outer_kind_of : Ast.join_type -> Ir.outer_kind option = function | Left -> Some Ir.Left | Right -> Some Ir.Right | Full -> Some Ir.Full | Inner | Cross | Semi _ -> None (* The positions {!join_column} coalesces: for each common column of a NATURAL / USING level that preserves the source it takes, the owner's copy and the joined source's. A [Left] or inner level never pads the owner, so its copy is the answer there and no coalesce is called for. *) let coalesced_columns (layout : layout) (s : Ast.select) = let pairs_of p (j : Ast.join) = let ci = p + 1 in match (outer_kind_of j.Ast.type_, List.nth_opt layout ci) with | Some (Ir.Right | Ir.Full), Some (_, jcols) when j.Ast.natural || j.Ast.using <> [] -> let leading = Resolve.leading layout p in let pair c = match (Resolve.owner_of leading c, col_index c jcols) with | Some a, Some jj -> (* the owner's own copy, asked for a position and not for a name a statement wrote, so the first match is the answer *) Option.map (fun owner -> (owner, (ci, jj))) (col Resolve.Frames layout (Some a) c) | _ -> None in List.filter_map pair (Resolve.common_columns layout ci j) | _ -> [] in List.concat (List.mapi pairs_of s.joins) (* The predicate a join's level tests: its written [ON], or the implicit one a NATURAL / USING level stands for ({!Resolve.natural_on}). A level with no ON, and one whose ON is the constant [1], test nothing: {!Ir.Always} keeps the level from emitting a test. *) let join_pred lw p (j : Ast.join) = let on = if j.natural || j.using <> [] then Resolve.natural_on lw.layout (p + 1) j else j.on in match on with | None | Some (Ast.Lit (Ast.Int 1L)) -> Ir.Always | Some e -> predicate lw e let conj a b = match a with Ir.Always -> b | _ -> Ir.And (a, b) let scan_joins lw (s : Ast.select) = let level p (j : Ast.join) = let kind = outer_kind_of j.Ast.type_ in let semi = match j.Ast.type_ with Semi _ -> true | _ -> false in let on = join_pred lw p j in if kind = None && Ir.reach on > p + 1 then ({ Ir.kind; semi; on = Ir.Always }, on) else ({ Ir.kind; semi; on }, Ir.Always) in let joins, deferred = List.split (List.mapi level s.joins) in let unwritten = List.length lw.layout - 1 - List.length joins in let joins = joins @ List.init (max 0 unwritten) (fun _ -> Ir.inner) in (joins, List.fold_left conj (filter_of lw s) deferred) (* A select carrying nothing but a projection. {!query} reads the layout it is given and never the [FROM], so this is the vehicle for lowering a post-pass over rows the caller already holds: the caller adds the result clauses it wants ([ORDER BY], [DISTINCT], [LIMIT]) and supplies the rows as a cursor. *) let post_select cols : Ast.select = { ctes = []; distinct = false; cols; from = Ast.Unit; joins = []; where = None; group_by = []; having = None; compound = []; order_by = []; limit = None; offset = None; } (* What the layout handed to a lowering describes. A select's own FROM names one source per entry, and a name two of them publish is an ambiguity; a caller lowering a projection over rows it already holds ({!post_select}) writes no FROM at all, so its frames are not sources and the first match answers. *) let layout_kind_of equated (layout : layout) (s : Ast.select) = match s.Ast.from with | Ast.Unit -> Resolve.Frames | Table _ | Select _ | Values _ | Table_function _ -> if List.length layout = 1 + List.length s.Ast.joins then Resolve.Sources equated else Resolve.Frames let needs_runner subs = List.exists (function Member _, _ -> false | _ -> true) subs let member subs id left _scope = match (List.nth subs id, left) with | (Member held, _), Some v -> Value_op.in_set_mem held v | _ -> unsupported () let lowering ~env ~encoding ~affinity ~membership layout s = let equated = Resolve.equated_columns layout s in { env; binary = (match encoding with | Encoding.Utf8 -> None | e -> Some (Collation.binary e)); layout; affinity; membership; equated; kind = layout_kind_of equated layout s; coalesced = coalesced_columns layout s; trigger = in_program (); subs = []; nsubs = 0; } let query ?(params = [||]) ?(affinity = fun _ -> None) ?(membership = fun _ -> Query.opaque_membership) ?order ?env ~encoding (layout : layout) (s : Ast.select) : Ir.query * (subkind * Ast.select) list = if Query.is_aggregate_query s || s.compound <> [] then unsupported (); let lw = lowering ~env ~encoding ~affinity ~membership layout s in let arities = List.map (fun (_, cols) -> List.length cols) layout in let joins, filter = scan_joins lw s in let hidden = lazy (hidden_columns lw) in let project, distinct_colls = projection lw (project_item ~hidden lw) s in let order = match order with Some o -> o | None -> Ir.cursor_order joins in let select = { Ir.arities; joins; order; filter; project } in let order_by = List.map (order_key lw (expr lw)) s.order_by in let q = { Ir.select; order_by; distinct = s.distinct; distinct_colls; limit = limit_of params s; offset = offset_of params s; } in (q, List.rev lw.subs) (* The aggregate names this lowers: a star [count], the numeric aggregates, and the string aggregates (group_concat / string_agg). [DISTINCT], a [FILTER] and an in-call [ORDER BY] are decorations {!as_aggregate} peels off any of these, and the engine applies them to the argument stream, so they compile too; a window function does not, and falls back. *) let numeric_aggs = [ "count"; "sum"; "min"; "max"; "avg"; "total" ] let string_aggs = [ "group_concat"; "string_agg"; "json_group_array"; "jsonb_group_array"; "json_group_object"; "jsonb_group_object"; ] (* A plain aggregate call: a star [count], a numeric aggregate of an argument, or a string aggregate ([group_concat]/[string_agg], with an optional separator argument), optionally [DISTINCT] -- its name, distinctness, and argument expressions ([] for a star count). [None] for anything else. *) let core_aggregate : Ast.expr -> (string * bool * Ast.expr list) option = function | Func ("count", [ Star ]) -> Some ("count", false, []) | Func (name, args) when (List.mem name numeric_aggs || List.mem name string_aggs) && Query.is_agg name args -> Some (name, false, args) | Distinct_agg (name, arg) when List.mem name numeric_aggs || List.mem name string_aggs -> Some (name, true, [ arg ]) | _ -> None (* A plain aggregate call, peeling any [FILTER (WHERE p)] and [ORDER BY] around the core call: its name, distinctness, arguments, optional FILTER predicate, and ORDER BY keys. [None] for anything that is not an aggregate. *) let as_aggregate e = let rec peel filter order = function | Ast.Filter (inner, p) -> peel (Some p) order inner | Ast.Ordered_agg (inner, ob) -> peel filter ob inner | core -> ( match core_aggregate core with | Some (name, distinct, args) -> Some (name, distinct, args, filter, order) | None -> None) in peel None [] e let out_cmp ~lw ~op_of op a b : Ir.expr = Cmp ( ir_cmp op, comparison_of lw a b, op_of (strip_collate a), op_of (strip_collate b) ) let out_cmp_pred ~lw ~op_of op a b : Ir.predicate = let c = comparison_of lw a b in match c.coll with | Some _ -> Truthy (out_cmp ~lw ~op_of op a b) | None -> Compare (ir_cmp op, c, op_of (strip_collate a), op_of (strip_collate b)) (* Lower a HAVING, or a CASE branch's condition, to a filter over the group row. [op_of] is the operand lowering the caller resolves against that row. *) let rec out_pred ~lw ~op_of (e : Ast.expr) : Ir.predicate = match e with | Binary ((And | Or), _, _) when simplified_and_or lw e != e -> out_pred ~lw ~op_of (simplified_and_or lw e) | Binary (And, a, b) -> And (out_pred ~lw ~op_of a, out_pred ~lw ~op_of b) | Binary (Or, a, b) -> Or (out_pred ~lw ~op_of a, out_pred ~lw ~op_of b) | Binary (op, a, b) when is_cmp op -> out_cmp_pred ~lw ~op_of op a b | Is_null e -> Null_test (true, op_of (strip_collate e)) | Is_not_null e -> Null_test (false, op_of (strip_collate e)) | e -> Truthy (op_of (strip_collate e)) let rec out_operand ~lw ~nkeys ~ncols ~key_index ~collect ~resolve_bare (e : Ast.expr) : Ir.expr = let recur = out_operand ~lw ~nkeys ~ncols ~key_index ~collect ~resolve_bare in match key_index e with | Some i -> Col (0, i) | None -> ( match as_aggregate e with (* the synthetic row is [keys, representative columns, aggregate results], so an aggregate sits past the [ncols] representative columns *) | Some info -> Col (0, nkeys + ncols + collect e info) | None -> ( match e with | Lit v -> Lit v | Numeral s -> Lit (Ast.code_number s) | Param i -> Param i | Named_param _ -> Param Param_number.unnumbered | Unary_plus e -> recur e | Unary_minus (Numeral s) -> Lit (Ast.code_number ~negative:true s) | Unary_minus e -> recur (Binary (Sub, Lit (Int 0L), e)) | Unop_not e -> Not (recur e) | Binary ((And | Or), _, _) when simplified_and_or lw e != e -> Not (Not (recur (simplified_and_or lw e))) | Binary (op, a, b) -> if is_cmp op then out_cmp ~lw ~op_of:recur op a b else if is_logic op then Logic (ir_logic op, recur a, recur b) else Arith (ir_arith op, recur a, recur b) | Is_null e -> Null_value (true, recur e) | Is_not_null e -> Null_value (false, recur e) | Is (a, Truth w) when is_truth_test lw w -> recur (truth_test a w) | Is (a, b) -> is_expr lw recur a b | In_list (e, cands) -> In ( recur (strip_collate e), { aff = ast_affinity lw e; coll = nonbinary_collation lw e }, List.map (fun c -> recur (strip_collate c)) cands ) | In_select (e, sub) -> in_select lw recur e sub | Func ("iif", [ c; t; f ]) -> recur (Case (None, [ (c, t) ], Some f)) | Func (name, args) when not (Query.is_agg name args) -> func_call lw recur name args | Cast (e, ty) -> Cast (recur e, ty) | Affinity (e, _) -> recur e (* the branch conditions are predicates over the same group row, so they take the group row's filter lowering; the results are values on it, like every other operand here *) | Case (base, branches, els) -> let branch (c, r) = let p = match base with | None -> out_pred ~lw ~op_of:recur c (* the base against this branch's value is an ordinary comparison, and reads a sequence and states an affinity like one *) | Some b -> out_cmp_pred ~lw ~op_of:recur Ast.Eq b c in (p, recur r) in Case (List.map branch branches, Option.map recur els) (* a trigger program evaluates its output row like any other, so a RAISE() among a group's output columns raises where that group is emitted, its message read off the same row *) | Raise (action, message) -> raise_expr lw recur action message (* a bare (non-key) column reads from the group's representative row *) | Col _ -> resolve_bare e | _ -> unsupported ())) (* The position of [e] among the group keys (by structural expression, ignoring a [COLLATE] wrapper on either side: [GROUP BY a COLLATE NOCASE] groups by [a], so a projected bare [a] is that key). *) let key_index keys e = let e = strip_collate e in let rec go i = function | k :: _ when Ast.equal_expr (strip_collate k) e -> Some i | _ :: t -> go (i + 1) t | [] -> None in go 0 keys (* Whether [s]'s output (select list, HAVING, ORDER BY) reads a bare (non-key, non-aggregate) column or a [*] -- the cases that need a representative group row materialised. A column matching a group key (ignoring a [COLLATE] wrapper) or sitting inside an aggregate does not. *) let references_bare_or_star keys (s : Ast.select) = let is_key e = key_index keys e <> None in let rec bare (e : Ast.expr) = if is_key e then false else if as_aggregate e <> None then false else match e with | Star | Qualified_star _ | Col _ -> true (* Not a bare column of any relation here: it resolves nowhere. *) | Schema_col _ -> false | e -> Ast.fold_expr ~select:(fun acc _ -> acc) (fun acc x -> acc || bare x) false e in List.exists (fun (rc : Ast.result_col) -> bare rc.expr) s.cols || (match s.having with Some h -> bare h | None -> false) || List.exists (fun (e, _) -> bare e) s.order_by let representative_shape layout keys s = let arities = List.map (fun (_, cols) -> List.length cols) layout in let bases = Ir.column_bases arities in let needs_rep = references_bare_or_star keys s in let ncols = if needs_rep then List.fold_left ( + ) 0 arities else 0 in (arities, bases, needs_rep, ncols) (* The min/max aggregates of [s], each once, in the order sqlite3 lists its aggregates: the select list's, then the ORDER BY's, then the HAVING's (select.c, sqlite3ExprAnalyzeAggList), the latest first. A subquery's are its own, and a window function is no aggregate of [s], though its arguments and keys may hold some. *) let min_max_calls (s : Ast.select) = let rec go acc (e : Ast.expr) = match e with | Func (("min" | "max"), [ _ ]) -> if List.exists (Ast.equal_expr e) acc then acc else e :: acc | Window (f, w) -> let acc = Ast.fold_expr ~select:(fun acc _ -> acc) go acc f in let acc = List.fold_left go acc w.partition in List.fold_left (fun acc (k, _) -> go acc k) acc w.order | e -> Ast.fold_expr ~select:(fun acc _ -> acc) go acc e in let acc = List.fold_left (fun acc (rc : Ast.result_col) -> go acc rc.expr) [] s.cols in let acc = List.fold_left (fun acc (e, _) -> go acc e) acc s.order_by in Option.fold ~none:acc ~some:(go acc) s.having (* The aggregate whose row a bare column reads: the last min/max of the query, as sqlite3 resets one flag before each min/max step and loads the bare columns when the last of them took the row (func.c, minmaxStep; vdbe.c, OP_CollSeq). *) let representative_choice lw needs_rep (s : Ast.select) = if not needs_rep then None else match min_max_calls s with | Func (name, [ a ]) :: _ -> (* the row is picked under the sequence the fold compares under, read off the argument as {!aggregate_collector} reads it *) Some ( String.equal name "max", expr lw (strip_collate a), arguments_collation lw [ a ] ) | _ -> None let rec bare_resolver lw ~nkeys ~bases = function | Ast.Col (alias, name) -> let c, j = resolve_col lw alias name in Ir.Col (0, nkeys + bases.(c) + j) | Ast.Truth name -> ( match truth lw name with | Ast.Col _ as c -> bare_resolver lw ~nkeys ~bases c | _ -> unsupported ()) | _ -> unsupported () let aggregate_collector lw = let aggs = ref [] and nagg = ref 0 in let collect e info = let rec go i = function | (e', _) :: _ when e' = e -> Some i | _ :: t -> go (i + 1) t | [] -> None in match go 0 (List.rev !aggs) with | Some i -> i | None -> let name, distinct, args, filter, order = info in let agg = { Ir.name; distinct; distinct_colls = (if distinct then List.map (nonbinary_collation lw) args else []); (* the sequence is read off the arguments here, wherever in one it was written, so what the fold gets is the compared value with the wrapper spent -- as a comparison operand is lowered *) args = List.map (fun a -> expr lw (strip_collate a)) args; (* A fold that compares its arguments -- [min], [max] -- reads a sequence of its own, off the argument list as a scalar [min]/[max]/[nullif] does. Every other fold orders nothing, so its sequence is spent on the DISTINCT key alone and is carried in [distinct_colls]. *) coll = (if Collate.fold_compares name then arguments_collation lw args else None); (* the FILTER decides which rows the fold sees and compares nothing of its own, so a [COLLATE] over it is spent nowhere and comes off as it does in a WHERE *) filter = Option.map (fun p -> expr lw (strip_collate p)) filter; (* the in-call ORDER BY sorts the group's rows before the fold sees them, so its keys read a sequence exactly as the query's own ORDER BY keys do -- same key lowering, same wrapper stripped *) order = List.map (order_key lw (expr lw)) order; } in aggs := (e, agg) :: !aggs; let slot = !nagg in incr nagg; slot in (collect, (fun () -> !nagg), fun () -> List.rev_map snd !aggs) let aggregate_star_cols layout ~hidden ~nkeys ~bases qopt = List.concat (List.mapi (fun c (al, cols) -> match qopt with | Some q when String.uppercase_ascii q <> String.uppercase_ascii al -> [] | None when Resolve.is_semi_alias al -> [] | _ -> (* every column of the source is indexed and the hidden ones skipped, exactly as {!project_item} does over the scan: the position a column reads from is its own, and stays its own wherever in the source a hidden column sits *) List.filter_map (fun j -> if List.mem (c, j) hidden then None else Some (Ir.Col (0, nkeys + bases.(c) + j))) (List.init (List.length cols) Fun.id)) layout) (* {!project_item} over the group row: expand a select item into the expressions it projects there. *) let aggregate_item lw ~hidden ~nkeys ~bases op (rc : Ast.result_col) = let star_cols = aggregate_star_cols lw.layout ~hidden ~nkeys ~bases in match rc.Ast.expr with | Star -> star_cols None | Qualified_star q -> if List.exists (fun (al, _) -> String.uppercase_ascii al = String.uppercase_ascii q) lw.layout then star_cols (Some q) else unsupported () (* a projected COLLATE produces the bare value, as it does over the scan ({!project_item}): the sequence governs comparison, ordering and dedup, and this select's are carried in its ORDER BY keys and [distinct_colls] *) | e -> [ op (strip_collate e) ] (* The query run over the synthetic per-group row: its projection, the sequences a DISTINCT dedups that projection under, its HAVING and its ORDER BY. *) let aggregate_output ?(params = [||]) ~lw ~nkeys ~ncols ~bases ~nagg op (s : Ast.select) = let hidden = hidden_columns lw in let project, distinct_colls = projection lw (aggregate_item lw ~hidden ~nkeys ~bases op) s in (* the projection, HAVING and ORDER BY all register their aggregates through [op], so [nagg] (the live count) is read only after all three are lowered -- an aggregate that appears solely in HAVING / ORDER BY still gets a synthetic-row slot. *) let filter = match s.having with Some h -> out_pred ~lw ~op_of:op h | None -> Always in let order_by = List.map (order_key lw op) s.order_by in let arities = [ nkeys + ncols + nagg () ] in { Ir.select = { arities; joins = []; order = [ 0 ]; filter; project }; order_by; distinct = s.distinct; distinct_colls; limit = limit_of params s; offset = offset_of params s; } let aggregate_scan lw keys (s : Ast.select) = let joins, filter = scan_joins lw s in (joins, filter, List.map (fun e -> expr lw (strip_collate e)) keys) let aggregate_query ?(params = [||]) ?(affinity = fun _ -> None) ?(membership = fun _ -> Query.opaque_membership) ?order ?env ~encoding (layout : layout) (s : Ast.select) : Ir.grouped * (subkind * Ast.select) list = if s.compound <> [] then unsupported (); (* a correlated scalar / EXISTS / IN subquery in the scan filter (WHERE / ON) registers here, for the caller to wire a runner -- the per-source-row scope the engine passes matches what the grouped scan sees *) let lw = lowering ~env ~encoding ~affinity ~membership layout s in let keys = s.group_by in let nkeys = List.length keys in let key_index = key_index keys in let arities, bases, needs_rep, ncols = representative_shape layout keys s in (* sqlite3's companion rule: a bare column takes its value from the row the query's last min/max took (else an arbitrary, here the first, row) *) let rep = representative_choice lw needs_rep s in let resolve_bare = bare_resolver lw ~nkeys ~bases in (* aggregates in first-seen order, structurally deduped so a repeated aggregate shares one slot *) let collect, nagg, aggs = aggregate_collector lw in let op = out_operand ~lw ~nkeys ~ncols ~key_index ~collect ~resolve_bare in (* [*] (or [t.*]) expands to the representative row's scanned columns, of the matching cursor for a qualified star; an unmatched qualified star is refused, and the resolver reports "no such table". *) let output = aggregate_output ~params ~lw ~nkeys ~ncols ~bases ~nagg op s in (* A single trailing LEFT JOIN null-fills before grouping; its [ON] stays on its own level, the [WHERE] is the scan filter. Otherwise every [ON] folds into the filter, as for an inner join. *) let joins, filter, group_by = aggregate_scan lw keys s in let g = { Ir.arities; joins; order = (match order with Some o -> o | None -> Ir.cursor_order joins); filter; group_by; group_colls = List.map (nonbinary_collation lw) keys; ncols; rep; aggs = aggs (); output; } in (g, List.rev lw.subs)