(*--------------------------------------------------------------------------- Copyright (c) 2026 Thomas Gazagnaire. All rights reserved. SPDX-License-Identifier: ISC ---------------------------------------------------------------------------*) open Ast (* Everything below asks the schema four questions and nothing else: which columns a relation publishes, which collating sequence a column declares, what a column can hold, and which columns a table-valued function produces. A rewrite that answered the name of a relation from its rows could not run before the rows exist, and every one of these runs first. *) type env = { columns : string -> string list; collation : string -> string -> string option; affinity : string -> string -> Value_ops.affinity option; decl_type : string -> string -> string option; table_function_columns : string -> string list; has_rowid : string -> bool; holds : string -> bool; } let explicit_collation = Collate.explicit (* The hidden layout slot a scan publishes for its integer rowid. A scan that exposes its rowid appends a column with this name; the spellings above resolve to it when no real column shadows them, and [Star] drops it. The NUL byte keeps it unspellable, so no user column ever collides -- which is what lets a layout carry it beside the relation's own columns. *) let rowid_sentinel = "\000rowid" (* The alias of a table joined from an EXISTS: unspellable, as the rowid slot is, and never bound by a bare name. *) let semi_alias k = Fmt.str "\000exists%d" k let is_semi_alias a = String.length a > 0 && Char.equal a.[0] '\000' (* A walk carries its callbacks and the context of the select it stands in as one value, which the fold hands from node to node unchanged: a node costs no closure and no allocation, and only a nested select makes a walker of its own. *) type 'ctx walker = { table : 'ctx -> table_ref -> unit; col : 'ctx -> string option -> string -> unit; nest : 'ctx -> select -> 'ctx; cte : 'ctx -> cte -> 'ctx option; ctx : 'ctx; } let rec walk_e w x = match x with | Col (qual, name) -> w.col w.ctx qual name; w | x -> fold_expr ~select:walk_nested walk_e w x and walk_nested w u = walk_s { w with ctx = w.nest w.ctx u } u; w and walk_operand w (tr : table_ref) = match tr.subquery with | Some q -> ignore (walk_nested w q) | None -> w.table w.ctx tr and walk_s w (s : select) = let ex e = ignore (walk_e w e) in List.iter (fun (c : cte) -> match w.cte w.ctx c with | Some ctx -> walk_s { w with ctx } c.query | None -> ()) s.ctes; List.iter (fun (rc : result_col) -> ex rc.expr) s.cols; (match s.from with | Unit -> () | Table tr -> walk_operand w tr | Select { fs_select; _ } -> ignore (walk_nested w fs_select) | Values rows -> List.iter (List.iter ex) rows | Table_function { tf_args; _ } -> List.iter ex tf_args); List.iter (fun (j : join) -> walk_operand w j.table; Option.iter ex j.on) s.joins; Option.iter ex s.where; List.iter ex s.group_by; Option.iter ex s.having; List.iter (fun (e, _) -> ex e) s.order_by; Option.iter ex s.limit; Option.iter ex s.offset; List.iter (fun (_, arm) -> ignore (walk_nested w arm)) s.compound let walk_select ~table ~col ~nest ~cte ctx s = walk_s { table; col; nest; cte; ctx } s let walk_expr ~table ~col ~nest ~cte ctx x = ignore (walk_e { table; col; nest; cte; ctx } x) (* Every table [s] names, in source order: its FROM clause, each join operand, each compound arm, each nested [WITH] body, and each subquery expression. *) let table_names (s : select) = let acc = ref [] in let table _ (tr : table_ref) = acc := tr.name :: !acc in walk_select ~table ~col:(fun _ _ _ -> ()) ~nest:(fun ctx _ -> ctx) ~cte:(fun ctx _ -> Some ctx) () s; List.rev !acc (* Every reference to a table named [name] in [s]. Matching is case-insensitive, so a query that spells the name two ways counts both and the caller refuses rather than inlining one of them. *) let count_table_refs name (s : select) = List.length (List.filter (ident_equal name) (table_names s)) (* The column a result expression names, for the implicit name a derived table publishes it under: the reference itself, or one under a [COLLATE]. sqlite3 skips a COLLATE here (sqlite3ColumnsFromExprList, src/select.c) because the wrapper names a sequence and not a column, so [x COLLATE NOCASE] publishes [x] and a reader of the derived table finds it there. *) let rec named_column = function | Col (_, c) -> Some c | Collate (e, _) -> named_column e | _ -> None (* The output column names of a select, for use as a derived table's columns: the explicit alias, else the bare column name, else a positional name. A [SELECT *] expands to every column in scope -- the FROM table plus each joined table, recursing into a derived (subquery) operand. *) (* The source the FROM clause of [s] binds as [q], which [q.*] reads: a table under its alias or its own name, or an aliased derived table. [None] where neither binds it: a table-valued function, whose name is then looked up as a relation's. *) let bound_source (s : select) q = let refs = (match s.from with Table tr -> [ tr ] | _ -> []) @ List.map (fun (j : join) -> j.table) s.joins in let binds (tr : table_ref) = ident_equal (Option.value tr.alias ~default:tr.name) q in match (List.find_opt binds refs, s.from) with | Some tr, _ -> Some (`Table tr) | None, Select { fs_select; fs_alias = Some a } when ident_equal a q -> Some (`Select fs_select) | None, _ -> None (* The names [q.*] can expand under: each source of [s]'s FROM under its alias, else its own name, as selectExpander matches them (select.c). A derived table and a VALUES list without an alias have no name to match. *) let source_names (s : select) = let of_ref (tr : table_ref) = Option.value tr.alias ~default:tr.name in let leading = match s.from with | Table tr -> [ of_ref tr ] | Select { fs_alias; _ } -> Option.to_list fs_alias | Table_function { tf_name; tf_alias; _ } -> [ Option.value tf_alias ~default:tf_name ] | Values _ | Unit -> [] in leading @ List.map (fun (j : join) -> of_ref j.table) s.joins let check_stars (s : select) = let star (rc : result_col) = match rc.expr with | Star when s.from = Unit -> Catalog.Error.fail_prepare "no tables specified" | Qualified_star q when not (List.exists (ident_equal q) (source_names s)) -> Catalog.Error.fail_prepare "no such table: %s" q | _ -> () in List.iter star s.cols let rec select_columns env0 s = check_stars s; (* every select carries its own [WITH] into its own resolution, so a caller hands over the scope the select sits in and not one it has extended *) let env = with_ctes env0 s in let table_cols (tr : table_ref) = match tr.subquery with | Some q -> select_columns env q | None -> env.columns tr.name in let star_cols () = let from_cols = match s.from with | Unit -> [] | Table tr -> table_cols tr | Select { fs_select; _ } -> select_columns env fs_select | Values (r :: _) -> List.mapi (fun j _ -> Ast.nth_column_name (j + 1)) r | Values [] -> [] | Table_function { tf_name; _ } -> env.table_function_columns tf_name in from_cols @ List.concat_map (fun (j : join) -> match j.type_ with Semi _ -> [] | _ -> table_cols j.table) s.joins in let qualified_cols q = match bound_source s q with | Some (`Table tr) -> table_cols tr | Some (`Select sub) -> select_columns env sub | None -> env.columns q in List.concat (List.mapi (fun i (rc : result_col) -> match rc.expr with | Star -> star_cols () | Qualified_star q -> qualified_cols q | _ -> ( match rc.alias with | Some a -> [ a ] | None -> ( match named_column rc.expr with | Some c -> [ c ] | None -> [ Ast.nth_column_name (i + 1) ]))) s.cols) (* The column names a [WITH] table expression publishes: the list its declaration names, else the output columns of its body. @raise Catalog.Error when the body reads a relation [env] does not have. *) and cte_columns env (c : cte) = match c.columns with [] -> select_columns env c.query | cs -> cs and with_ctes env (q : select) = if q.ctes = [] then env else let self = ref env in let resolving = ref [] in let columns name = match List.find_opt (fun (c : cte) -> ident_equal c.name name) q.ctes with | None -> env.columns name | Some c -> if List.exists (ident_equal c.name) !resolving then Catalog.Error.fail_prepare "circular reference: %s" (Ast.written_name c.name) else ( resolving := c.name :: !resolving; Fun.protect ~finally:(fun () -> resolving := List.tl !resolving) (fun () -> cte_columns !self c)) in let holds name = List.exists (fun (c : cte) -> ident_equal c.name name) q.ctes || env.holds name in self := { env with columns; holds }; !self (* The columns a source of [s] publishes, for a caller that only needs to know which names are real ones. A source naming one of [s]'s own [WITH] table expressions publishes that relation's columns: the catalog has it only once the CTE is materialised, and this is read before that. A name neither has -- a derived table, or a body reading an earlier CTE -- publishes none. *) let source_columns env (s : select) (tr : table_ref) = match tr.subquery with | Some _ -> [] | None -> ( match List.find_opt (fun (c : cte) -> ident_equal c.name tr.name) s.ctes with | Some c -> ( try cte_columns env c with Catalog.Error (Prepare _ | Runtime _) -> []) | None -> env.columns tr.name) (* Each FROM source of [s] as (alias, its column names) -- the column scope a subquery body resolves against. A name that does not resolve (e.g. a CTE absent from the base catalog) contributes no columns, so a subquery using it reads as correlated and is left to run per outer row rather than wrongly hoisted. *) let from_scope env (s : select) : (string * string list) list = let cols_of name = try env.columns name with Catalog.Error (Prepare _ | Runtime _) -> [] in let alias_or_name (tr : table_ref) = match tr.alias with Some a -> a | None -> tr.name in let of_ref (tr : table_ref) = match tr.subquery with | Some q -> (alias_or_name tr, select_columns env q) | None -> (alias_or_name tr, cols_of tr.name) in let leading = match s.from with | Table tr -> [ of_ref tr ] | Select { fs_select; fs_alias } -> [ (Option.value fs_alias ~default:"", select_columns env fs_select) ] | Values tuples -> let n = match tuples with r :: _ -> List.length r | [] -> 0 in [ ("", List.init n (fun i -> Ast.nth_column_name (i + 1))) ] (* A table-valued function binds its output columns under its alias, else its own name -- the same names the scan publishes them under. Missing them would read every one as free, making any subquery over a function look correlated. *) | Table_function { tf_name; tf_alias; _ } -> let cols = try env.table_function_columns tf_name with Catalog.Error (Prepare _ | Runtime _) -> [] in [ (Option.value tf_alias ~default:tf_name, cols) ] | Unit -> [] in leading @ List.map (fun (j : join) -> of_ref j.table) s.joins (* Every column name [s]'s own FROM binds. {!from_scope} reads a derived table, a VALUES list and a table-valued function; {!source_columns} reads a source naming one of [s]'s own [WITH] table expressions, which the catalog has not got until the CTE is materialised. Neither answers for the other's sources, so a caller asking which names are already taken here asks both. *) let bound_columns env (s : select) = let named (tr : table_ref) = if tr.subquery = None then source_columns env s tr else [] in List.concat_map snd (from_scope env s) @ (match s.from with Table tr -> named tr | _ -> []) @ List.concat_map (fun (j : join) -> named j.table) s.joins (* [s]'s own [WITH] is in scope for every arm of its compound and every subquery under it, none of which carries the clause itself, so it extends [env] before anything is resolved. *) let rec alias_rewrite env inherited (s : select) = let env = with_ctes env s in let own = List.filter_map (fun (rc : result_col) -> match rc.alias with Some a -> Some (a, rc.expr) | None -> None) s.cols in (* What an expression of this select sees: the inherited bindings this select's FROM does not rebind, and -- in a clause a select's own alias may stand in -- its own aliases before them. The FROM's columns are read only where there is a binding for them to shadow. *) let own, outer = if own = [] && inherited = [] then ([], []) else let real_cols = bound_columns env s in let unshadowed (a, _) = not (List.exists (ident_equal a) real_cols) in (List.filter unshadowed own, List.filter unshadowed inherited) in let keys = own @ List.filter (fun (a, _) -> Catalog.Ident.assoc_opt a own = None) outer in (* one walker per binding set, not one per node *) let sub bindings = let select = alias_rewrite env bindings in let rec sub e = match e with | Col (None, name) -> ( match Catalog.Ident.assoc_opt name bindings with | Some e' -> e' | None -> e) | e -> Ast.map_expr ~select sub e in sub in let sub_outer = sub outer and sub_keys = sub keys in { s with cols = List.map (fun (rc : result_col) -> { rc with expr = sub_outer rc.expr }) s.cols; where = Option.map sub_keys s.where; order_by = List.map (fun (e, d) -> (sub_keys e, d)) s.order_by; group_by = List.map sub_outer s.group_by; having = Option.map sub_keys s.having; joins = List.map (fun (j : join) -> { j with on = Option.map sub_outer j.on }) s.joins; compound = List.map (fun (op, arm) -> (op, alias_rewrite env outer arm)) s.compound; } let where_aliases env (s : select) = alias_rewrite env [] s (* sqlite3ExprImpliesNonNullRow: [e] is never true on a row whose columns of the source [mine] names are all NULL. A conjunct of the top-level AND chain implies it alone; a column of the source under a comparison, an arithmetic, a NOT or the left of an IN list implies it, as each answers NULL for a NULL operand; under an AND or an OR nested in it both sides must; IS, IS NULL, IS NOT NULL, a function call (LIKE and GLOB among them), a CASE and a subquery imply nothing. *) let implies_non_null ~mine e = let rec walk = function | Col (q, c) -> mine q c | Binary ((And | Or), a, b) -> walk a && walk b | Binary ((Like | Glob), _, _) -> false | Binary (_, a, b) -> walk a || walk b | Unop_not a | Unary_minus a | Unary_plus a | Collate (a, _) | Cast (a, _) -> walk a | In_list (a, _ :: _) -> walk a | _ -> false in let rec top = function | Binary (And, a, b) -> top a || top b | Is_not_null a -> walk a | e -> walk e in top e (* Whether column [c], qualified by [q], is one of the source [i] of [refs], whose columns are [cols]: a bare name names the one source that has a column of that name. *) let owns refs cols i q c = let alias (tr : table_ref) = Option.value tr.alias ~default:tr.name in match (q, List.nth refs i) with | Some q, Some tr -> ident_equal q (alias tr) | Some _, None -> false | None, _ -> List.for_all Option.is_some cols && List.length (List.filter (fun cs -> List.exists (ident_equal c) (Option.get cs)) cols) = 1 && List.exists (ident_equal c) (Option.value ~default:[] (List.nth cols i)) (* What sqlite3's flags of a join's source say of it: padded where nothing on its left matches (JT_LEFT), its own rows kept where nothing on its left matches them (JT_RIGHT). *) let pads = function | Left | Full -> true | Inner | Cross | Right | Semi _ -> false let keeps = function | Right | Full -> true | Inner | Cross | Left | Semi _ -> false let joined ~pads ~keeps : join_type = match (pads, keeps) with | false, false -> Inner | true, false -> Left | false, true -> Right | true, true -> Full (* Whether each source of [s] may read the column [q.c]: the sources' names and the columns each publishes. *) let source_owns env (s : select) = let leading = match s.from with Table tr -> Some tr | _ -> None in let refs = leading :: List.map (fun (j : join) -> Some j.table) s.joins in let columns = function | Some ({ subquery = None; _ } as tr : table_ref) -> ( match env.columns tr.name with | cols -> Some cols | exception Catalog.Error _ -> None) | Some { subquery = Some q; _ } -> Some (select_columns env q) | None -> None in owns refs (List.map columns refs) (* The type of the join that takes source [i], [Inner] for the first. *) let kind joins i = if i = 0 then Inner else joins.(i - 1).type_ (* JT_LTORJ: whether source [i] stands left of the last join of [joins] that keeps its own rows (sqlite3SrcListShiftJoinType). *) let left_of_keeper joins = let last = ref (-1) in Array.iteri (fun p (j : join) -> if keeps j.type_ then last := p + 1) joins; fun i -> i < !last (* The WHERE of [s] with the ONs sqlite3 moves into it as an inner join's (sqlite3ProcessJoin, EP_InnerON): an inner join's own, and that of a join made inner here (unsetJoinExpr), [inner] saying which; left of a join that keeps its own rows ([right_join]), the WHERE alone. *) let inner_where (s : select) joins inner ~right_join = let ons = if right_join then [] else List.filter_map (fun p -> let j = joins.(p) in if inner.(p + 1) && (not j.natural) && j.using = [] then j.on else None) (List.init (Array.length joins) Fun.id) in match (s.where, ons) with | None, [] -> None | w, ons -> Some (List.fold_left (fun a b -> Binary (And, a, b)) (Option.value w ~default:(Lit (Int 1L))) ons) (* [joins] once the source [i] is known never all NULL (select.c, sqlite3Select): a LEFT JOIN of it is an inner join and a FULL one keeps its own rows alone; and, where it stands left of a join that keeps its own rows ([ltorj]), it is matched by every row of that join, a RIGHT JOIN of which is then an inner join and a FULL one a LEFT JOIN. *) let never_null joins inner ~ltorj i = let set i type_ = joins.(i - 1) <- { (joins.(i - 1)) with type_ }; if type_ = Inner then inner.(i) <- true in let k = kind joins i in if pads k then set i (joined ~pads:false ~keeps:(keeps k)); if ltorj then for j = i + 1 to Array.length joins do let kj = kind joins j in if keeps kj then set j (joined ~pads:(pads kj) ~keeps:false) done let reduce_outer_joins env (s : select) = let outer = List.exists (fun (j : join) -> pads j.type_ || keeps j.type_) in if s.compound <> [] || not (outer s.joins) then s else let mine = source_owns env s in let joins = Array.of_list s.joins in let inner = Array.init (Array.length joins + 1) (fun i -> i > 0 && match kind joins i with Inner | Cross -> true | _ -> false) in (* each source in turn, as sqlite3Select tests them, the joins it simplified read by the next *) for i = 0 to Array.length joins do let ltorj = left_of_keeper joins i in if (pads (kind joins i) || ltorj) && match inner_where s joins inner ~right_join:ltorj with | Some w -> implies_non_null ~mine:(mine i) w | None -> false then never_null joins inner ~ltorj i done; { s with joins = Array.to_list joins } (* The output expressions of [s] in order, expanding [*]/[t.*] to a column reference per underlying column. Used to resolve an ORDER BY ordinal to the expression of that output column. *) let output_exprs env (s : select) = let columns expr = select_columns env { s with cols = [ { expr; alias = None } ] } in List.concat_map (fun (rc : result_col) -> match rc.expr with | Star -> List.map (fun c -> Col (None, c)) (columns Star) | Qualified_star q as e -> List.map (fun c -> Col (Some q, c)) (columns e) | e -> [ e ]) s.cols (* [1st], [2nd], [3rd], [4th]: sqlite3's [%r] conversion. *) let ordinal n = let suffix = match (n mod 10, n mod 100) with | 1, t when t <> 11 -> "st" | 2, t when t <> 12 -> "nd" | 3, t when t <> 13 -> "rd" | _ -> "th" in Fmt.str "%d%s" n suffix (* sqlite3ExprIsInteger (src/expr.c:2901) with no parse context: a literal a 32-bit int holds, through unary [+] and [-]. A bound parameter is not one. *) let rec integer_term = function | Lit (Int i) when Int64.compare i (Int64.of_int32 Int32.min_int) >= 0 && Int64.compare i (Int64.of_int32 Int32.max_int) <= 0 -> Some (Int64.to_int i) | Unary_plus e -> integer_term e | Unary_minus e -> Option.map Int.neg (integer_term e) | _ -> None (* resolveOutOfRangeError (src/resolve.c:1589). *) let out_of_range ~kind ~nth ~width = let kind = match kind with `Order -> "ORDER" | `Group -> "GROUP" in Catalog.Error.fail_prepare "%s %s BY term out of range - should be between 1 and %d" (ordinal nth) kind width let rec skip_collate = function Collate (e, _) -> skip_collate e | e -> e (* The terms of one [kind] BY clause over the output expressions [outs], each integer one replaced by the output it names (under its COLLATE, which stays) and each other one given to [key]. A term outside 1..0xffff is refused as it is read (resolveOrderGroupBy, src/resolve.c:1836-1843) and one past the result width once every term is (sqlite3ResolveOrderGroupBy, 1747-1750). *) let ordinal_clause ~kind outs key terms = let width = Array.length outs in let rec replace out = function | Collate (e, c) -> Collate (replace out e, c) | _ -> out in let terms, past = List.fold_left (fun (acc, past) (nth, e) -> match integer_term (skip_collate e) with | None -> (key e :: acc, past) | Some k when k < 1 || k > 0xffff -> out_of_range ~kind ~nth ~width | Some k when k > width -> (e :: acc, if past = None then Some nth else past) | Some k -> (replace outs.(k - 1) e :: acc, past)) ([], None) (List.mapi (fun i e -> (i + 1, e)) terms) in match past with | Some nth -> out_of_range ~kind ~nth ~width | None -> List.rev terms (* sqlite3 lets ORDER BY and GROUP BY use a 1-based output-column ordinal ([ORDER BY 2] / [GROUP BY 2] use the second result column). Replace each integer key with the expression of that output column, so the normal machinery uses it, and refuse one that names no output column, the ORDER BY clause before the GROUP BY one (src/resolve.c:2068-2086). *) let ordinals env (s : select) = if s.order_by = [] && s.group_by = [] then s else let outs = Array.of_list (output_exprs env s) in (* An ORDER BY key may name an explicit output-column alias; the alias takes precedence over an input column (sqlite3), so resolve it to that output expression -- this is how [ORDER BY n] reaches an aggregate aliased [n]. *) let alias_expr name = List.find_map (fun (rc : result_col) -> match rc.alias with | Some a when ident_equal a name -> Some rc.expr | _ -> None) s.cols in let rec order_key = function | Collate (e, c) -> Collate (order_key e, c) | Unary_plus e -> Unary_plus (order_key e) | (Col (None, name) | Truth name) as e -> ( match alias_expr name with Some x -> x | None -> e) | e -> e in (* GROUP BY also accepts an output-column alias, but with the opposite precedence to ORDER BY: sqlite3 resolves the bare name against the input columns first and only falls back to the select-list alias when no input column carries it. [SELECT y AS x ... GROUP BY x] therefore groups by the input [x], while [SELECT y AS g ... GROUP BY g] groups by [y]. *) let input_cols = lazy (try select_columns env { s with cols = [ { expr = Star; alias = None } ] } with Catalog.Error (Prepare _ | Runtime _) -> []) in let group_key = function | (Col (None, name) | Truth name) as e when not (List.mem name (Lazy.force input_cols)) -> ( match alias_expr name with Some x -> x | None -> e) | e -> e in let directions = List.map snd s.order_by in let order_by = ordinal_clause ~kind:`Order outs order_key (List.map fst s.order_by) in let group_by = ordinal_clause ~kind:`Group outs group_key s.group_by in { s with order_by = List.combine order_by directions; group_by } type source = { bound_as : string; (** the name the source is in scope under *) publishes : string list Lazy.t; (** its columns, matched by an unqualified reference *) declares : string -> string option; (** a column's declared sequence *) holds : string -> Value_ops.affinity option; (** what a column can hold -- its affinity *) types : string -> string option; (** a column's declared type *) } (* The source a column reference reads, and the column's name in it. A bare rowid no source declares reads the first source's, as it resolves. *) let column_source sources e = match e with | Col (Some q, name) -> Option.map (fun s -> (s, name)) (List.find_opt (fun s -> ident_equal s.bound_as q) sources) | Col (None, name) -> ( let holds s = List.exists (ident_equal name) (Lazy.force s.publishes) in match (List.find_opt holds sources, sources) with | Some s, _ -> Some (s, name) | None, s :: _ when is_rowid_name name -> Some (s, name) | None, _ -> None) (* a bare true or false reads the column of that name where one is *) | Truth name -> let holds s = List.exists (ident_equal name) (Lazy.force s.publishes) in Option.map (fun s -> (s, name)) (List.find_opt holds sources) | _ -> None let rec collation_for sources e = match e with | Col _ -> Option.bind (column_source sources e) (fun (s, n) -> s.declares n) | Cast (e, _) | Unary_plus e -> collation_for sources e | _ -> None (* The affinity a column reference carries, read off the source it names. Unlike the collating sequence, no spine is looked through: sec.3.2 leaves any operator applied to a column name -- the no-op unary [+] included -- with no affinity at all, and a CAST takes its target type's, so {!expr_affinity} answers both rather than walking past them to a column here. *) let affinity_for sources e = Option.bind (column_source sources e) (fun (s, n) -> s.holds n) (* The relation [name] of [env]'s schema, in scope as [bound_as]. *) let named_source env (bound_as, name) = { bound_as; publishes = lazy (try env.columns name with Catalog.Error (Prepare _ | Runtime _) -> []); declares = env.collation name; holds = env.affinity name; types = env.decl_type name; } let rec from_sources env (s : select) : source list = let derived bound_as sub = { bound_as; publishes = lazy (try select_columns env sub with Catalog.Error (Prepare _ | Runtime _) -> []); declares = column_collation env sub; holds = column_affinity env sub; types = column_type env sub; } in let of_ref (tr : table_ref) = let bound_as = Option.value tr.alias ~default:tr.name in match tr.subquery with | None -> [ named_source env (bound_as, tr.name) ] | Some sub -> [ derived bound_as sub ] in (match s.from with | Table tr -> of_ref tr | Select { fs_select; fs_alias } -> [ derived (Option.value fs_alias ~default:"") fs_select ] | Unit | Values _ | Table_function _ -> []) @ List.concat_map (fun (j : join) -> of_ref j.table) s.joins (* The sequence the output column named [name] of [s] carries. *) and column_collation env (s : select) name = let published = try select_columns env s with Catalog.Error (Prepare _ | Runtime _) -> [] in Option.bind (Catalog.Ident.index name published) (output_collation env s) (* The declared type the output column named [name] of [s] carries. *) and column_type env (s : select) name = let published = try select_columns env s with Catalog.Error (Prepare _ | Runtime _) -> [] in Option.bind (Catalog.Ident.index name published) (output_type env s) (* select.c, columnType: the declared type of a column reference, read off its source, and of a scalar subquery's first column; no other expression has one. A compound is read off its first arm, [s] itself, as sqlite3ResultSetOfSelect reads the leftmost select. *) and output_type env (s : select) i = match List.nth_opt (try output_exprs env s with Catalog.Error (Prepare _ | Runtime _) -> []) i with | Some (Col _ as e) -> Option.bind (column_source (from_sources env s) e) (fun (src, n) -> src.types n) | Some (Scalar_select sub) -> output_type env sub 0 | Some _ | None -> None (* The affinity the output column named [name] of [s] carries. *) and column_affinity env (s : select) name = let published = try select_columns env s with Catalog.Error (Prepare _ | Runtime _) -> [] in Option.bind (Catalog.Ident.index name published) (output_affinity env s) and output_collation env (s : select) i = match List.nth_opt (try output_exprs env s with Catalog.Error (Prepare _ | Runtime _) -> []) i with | None -> None | Some e -> expr_collation env s e and expr_collation env (s : select) e = match explicit_collation e with | Some _ as c -> c | None -> collation_for (from_sources env s) e and expr_affinity env sources e = match e with | Col _ -> affinity_for sources e | Collate (e, _) -> expr_affinity env sources e | Affinity (_, aff) -> Some aff | Cast (_, ty) -> Some (Value_ops.affinity_of_type ty) | Scalar_select sub -> output_affinity env sub 0 | _ -> None and expr_data_type env sources e = match e with | Collate (e, _) | Unary_plus e -> expr_data_type env sources e | Lit Null -> 0x00 | Lit (Text _) -> 0x02 | Lit (Blob _) -> 0x04 | Binary (Concat, _, _) -> 0x06 | Param _ | Named_param _ | Func _ | Distinct_agg _ | Ordered_agg _ | Filter _ -> 0x07 | Col _ | Cast _ | Scalar_select _ | Affinity _ -> ( match expr_affinity env sources e with | Some (`Numeric | `Integer | `Real) -> 0x05 | Some `Text -> 0x06 | Some `Blob | None -> 0x07) | Case (_, branches, els) -> List.fold_left (fun acc (_, r) -> acc lor expr_data_type env sources r) (match els with Some e -> expr_data_type env sources e | None -> 0x00) branches | _ -> 0x01 and output_affinity env (s : select) i = let arms = s :: List.map snd s.compound in let item (a : select) = List.nth_opt (try output_exprs env a with Catalog.Error (Prepare _ | Runtime _) -> []) i in let arm_affinity a = Option.bind (item a) (expr_affinity env (from_sources env a)) in let arm_data_type a = match item a with | Some e -> expr_data_type env (from_sources env a) e | None -> 0x00 in let rec pick k = function | [] -> (None, k) | a :: rest -> ( match arm_affinity a with None -> pick (k + 1) rest | aff -> (aff, k)) in let chosen, k = pick 0 arms in match chosen with | Some (`Text | `Numeric | `Integer | `Real) as aff when List.length arms > 1 -> let others = List.fold_left (fun acc a -> acc lor arm_data_type a) 0x00 (List.filteri (fun j _ -> j <> k) arms) in if chosen = Some `Text && others land 0x01 <> 0 then Some `Blob else if chosen <> Some `Text && others land 0x02 <> 0 then Some `Blob else aff | aff -> aff (* Whether [e] counts as a column for rule 2 above -- a reference, or a CAST or a unary [+] of one. *) let rec is_col_expr = function | Col _ -> true | Cast (e, _) | Unary_plus e -> is_col_expr e | _ -> false (* [e] with the sequence it already assigns hoisted to its outermost node, so every later reader finds it there rather than having to walk for it. *) let hoist_collation e c = match e with Collate _ -> e | e -> Collate (e, c) let collation_cmp_operands col_coll ~written:(wa, wb) a b = match (explicit_collation wa, explicit_collation wb) with (* rule 1: an explicit assignment wins wherever it sits, the left operand's first *) | Some c, _ -> (hoist_collation a c, b) | None, Some c -> (a, hoist_collation b c) (* rule 2: else a column operand's declared sequence, the left one's first *) | None, None -> if is_col_expr wa then match col_coll wa with Some c -> (Collate (a, c), b) | None -> (a, b) else if is_col_expr wb then match col_coll wb with Some c -> (a, Collate (b, c)) | None -> (a, b) else (a, b) let collation_lhs col_coll ~written e = match explicit_collation written with | Some c -> hoist_collation e c | None -> ( match col_coll written with Some c -> Collate (e, c) | None -> e) let arm_collation env (s : select) i = match List.nth_opt (try output_exprs env s with Catalog.Error (Prepare _ | Runtime _) -> []) i with | None -> None | Some e -> ( match output_collation env s i with | Some _ as c -> c | None -> if is_col_expr e then Some "BINARY" else None) let compound_collations env (s : select) ncols = let arms = s :: List.map snd s.compound in List.init ncols (fun i -> List.find_map (fun a -> arm_collation env a i) arms) (* The arm of a compound whose result columns an [IN (SELECT ...)] compares against: the last one. sqlite3 builds a compound with its rightmost arm as the head of the chain and reads the result list off it here without walking [pPrior] back (src/expr.c, sqlite3CodeRhsOfIN) -- the opposite end from the one that types a derived table. *) let in_select_arm (sub : select) = match List.rev sub.compound with [] -> sub | (_, arm) :: _ -> arm let in_select_lhs env col_coll ~written a sub = match explicit_collation written with | Some c -> hoist_collation a c | None -> ( let arm = in_select_arm sub in let rhs = match try output_exprs env arm with Catalog.Error (Prepare _ | Runtime _) -> [] with | e :: _ -> Some e | [] -> None in let seq = match Option.bind rhs explicit_collation with | Some _ as c -> c | None -> if is_col_expr written then col_coll written else output_collation env arm 0 in match seq with Some c -> Collate (a, c) | None -> a) let in_select_affinity env sub = output_affinity env (in_select_arm sub) 0 let sort_keys col_coll e = let lhs k = collation_lhs col_coll ~written:k k in let key (k, dir) = (lhs k, dir) in match e with | Ordered_agg (agg, keys) -> Ordered_agg (agg, List.map key keys) | Window (f, w) -> Window ( f, { w with partition = List.map lhs w.partition; order = List.map key w.order; } ) | e -> e (* One walk per expression, not one per node: [rw] is made once, and a node none of whose operands changed is handed back as it was. *) let collation_expr ?(select = Fun.id) env col_coll e = let rec rw e = match e with | Binary (((Eq | Neq | Lt | Le | Gt | Ge) as op), a, b) -> let a', b' = collation_cmp_operands col_coll ~written:(a, b) (rw a) (rw b) in if a' == a && b' == b then e else Binary (op, a', b') | Binary (op, a, b) -> let b' = rw b in let a' = rw a in if a' == a && b' == b then e else Binary (op, a', b') (* [a IS b] is a comparison and reads a sequence exactly as [a = b] does (sqlite3 routes both through sqlite3BinaryCompareCollSeq, src/expr.c); only its answer differs, being 1/0 where a comparison's is NULL. *) | Is (a, b) -> let a, b = collation_cmp_operands col_coll ~written:(a, b) (rw a) (rw b) in Is (a, b) (* [x IN ..] uses the left operand's collation, like [x = ..]. *) | In_list (a, l) -> In_list (collation_lhs col_coll ~written:a (rw a), List.map rw l) | In_select (a, sub) -> In_select (in_select_lhs env col_coll ~written:a (rw a) sub, select sub) (* A DISTINCT aggregate folds each argument tuple once, and which tuples are one is decided under a sequence -- sqlite3 keys the dedup on the argument list's own sequences (sqlite3KeyInfoFromExprList, src/select.c). *) | Distinct_agg (name, a) -> Distinct_agg (name, collation_lhs col_coll ~written:a (rw a)) | Func (name, [ a ]) when Collate.fold_compares name -> Func (name, [ collation_lhs col_coll ~written:a (rw a) ]) | Func (name, args) when Collate.compares_its_arguments name -> Func ( name, List.map (fun a -> collation_lhs col_coll ~written:a (rw a)) args ) | Ordered_agg _ | Window _ -> sort_keys col_coll (Ast.map_expr ~select rw e) | Case (Some base, branches, els) -> let rbase = rw base in let branch (c, r) = let l, c = collation_cmp_operands col_coll ~written:(base, c) rbase (rw c) in (Binary (Eq, l, c), rw r) in Case (None, List.map branch branches, Option.map rw els) | e -> Ast.map_expr ~select rw e in rw e (* [e] with each bare true or false a source publishes read as that column, so every rewrite after this one, and the lowering, take it for the column it is: its sequence, its affinity, and IS comparing with it. One no source publishes stays a {!Ast.Truth}, for an enclosing query's column or the integer. *) let truth_columns sources e = let rec go e = match e with | Truth name when Option.is_some (column_source sources e) -> Col (None, name) | e -> Ast.map_expr ~select:Fun.id go e in go e (* [from_scope] with the hidden rowid slot appended to each source that has one: a table, not a view, a derived table or a [WITHOUT ROWID] table. A correlated subquery's names are bound here before they are looked for outside, so an unqualified [rowid] names the innermost source that has one, as sqlite3's lookupName does, and only a subquery whose sources have none reads an enclosing row's. *) let binding_scope env (s : select) = let has_rowid (tr : table_ref) = tr.subquery = None && env.has_rowid tr.name in let rowid_sources = (match s.from with | Table tr -> [ has_rowid tr ] | Select _ | Values _ | Table_function _ -> [ false ] | Unit -> []) @ List.map (fun (j : join) -> has_rowid j.table) s.joins in List.map2 (fun (alias, cols) rowid -> (alias, if rowid then cols @ [ rowid_sentinel ] else cols)) (from_scope env s) rowid_sources (* Whether a source binds the column [name] under [qual]. A declared column comes first, so a column named [rowid] is that column; a rowid name no column declares binds the hidden slot. A source named [qual] that has no such column binds nothing, so the name is looked up further out, as lookupName (resolve.c) moves to the enclosing name context. *) let binder qual name = let declares (_, cols) = List.exists (ident_equal name) cols in let hidden (_, cols) = List.mem rowid_sentinel cols in let binds src = declares src || (is_rowid_name name && hidden src) in match qual with | Some q -> fun src -> ident_equal q (fst src) && binds src | None -> (* a table joined from an EXISTS is no bare name's *) fun ((a, _) as src) -> (not (is_semi_alias a)) && binds src (* The sources of [own] that bind the column [name] under [qual]. *) let scope_binders own qual name = List.filter (binder qual name) own (* Whether a source of [own] binds the column [name] under [qual], asked of each source until one does. *) let scope_binds own qual name = List.exists (binder qual name) own (* A select with the given WITH and FROM and nothing else, the shape an UPDATE's or a DELETE's own sources are rewritten in. *) let sources_select ctes from joins = { ctes; distinct = false; cols = []; from; joins; where = None; group_by = []; having = None; compound = []; order_by = []; limit = None; offset = None; } (* The rewrite {!collations} makes of a select's own columns, made inside a nested select of the columns a scope outside it publishes: a trigger's NEW and OLD, or the sources of the query a correlated subquery sits in. [coll own e] is the sequence such a column operand [e] compares under, BINARY where none is declared, or [None] for any other operand: one the nested select's own sources [own] bind, which is left to the rewrite of its own select and blocks the right operand as it does there (TK_TRIGGER and TK_COLUMN in sqlite3ExprCollSeq, src/expr.c). The sequence is fixed before the scope substitutes its value in, since a value has none. *) let rec outer_expr env coll own e = let rec col_coll = function | Col _ as e -> coll own e | Cast (e, _) | Unary_plus e -> col_coll e | _ -> None in collation_expr ~select:(outer_select env coll own) env col_coll e and outer_from env coll own (s : select) : from_clause = let select = outer_select env coll own in let expr = outer_expr env coll own in match s.from with | Table tr -> Table { tr with subquery = Option.map select tr.subquery } | Select fs -> Select { fs with fs_select = select fs.fs_select } | Values rows -> Values (List.map (List.map expr) rows) | Table_function tf -> Table_function { tf with tf_args = List.map expr tf.tf_args } | Unit -> Unit and outer_select env coll own (s : select) = let env = with_ctes env s in let select = outer_select env coll own in let e = outer_expr env coll (binding_scope env s @ own) in let table_ref (tr : table_ref) = { tr with subquery = Option.map select tr.subquery } in { s with ctes = List.map (fun (c : cte) -> { c with query = select c.query }) s.ctes; cols = List.map (fun (rc : result_col) -> { rc with expr = e rc.expr }) s.cols; from = outer_from env coll own s; joins = List.map (fun (j : join) -> { j with table = table_ref j.table; on = Option.map e j.on }) s.joins; where = Option.map e s.where; group_by = List.map e s.group_by; having = Option.map e s.having; compound = List.map (fun (op, arm) -> (op, select arm)) s.compound; order_by = List.map (fun (k, d) -> (e k, d)) s.order_by; limit = Option.map e s.limit; offset = Option.map e s.offset; } (* The sequence of a trigger's NEW.x or OLD.x, where no source of [own] is named new or old: sqlite3's lookupName tries a trigger's rows only once no source of the name context has matched (resolve.c). A bare name never reads them. [declared] is the trigger table's sequences. *) let trigger_row declared own = function | Col (Some q, name) when (ident_equal q "new" || ident_equal q "old") && not (List.exists (fun (a, _) -> ident_equal a q) own) -> Some (Option.value (declared name) ~default:"BINARY") | _ -> None (* An INSERT of a trigger's body: its rows, and its upsert, under which the target and [excluded] are sources. *) let row_insert env coll (i : insert) = let expr own = outer_expr env coll own in let source : insert_source = match i.source with | Values rows -> Values (List.map (List.map (expr [])) rows) | Select s -> Select (outer_select env coll [] s) | Default_values -> Default_values in let on = [ (i.table, []); ("excluded", []) ] in let upsert (u : upsert) = let action : upsert_action = match u.action with | Update (sets, w) -> Update ( List.map (fun (c, v) -> (c, expr on v)) sets, Option.map (expr on) w ) | Nothing -> Nothing in { u with target_where = Option.map (expr on) u.target_where; action } in { i with source; upsert = Option.map upsert i.upsert } let row_stmt env coll : stmt -> stmt = function | Select s -> Select (outer_select env coll [] s) | Insert i -> Insert (row_insert env coll i) | Update u -> let f, joins = Option.value u.from ~default:(Unit, []) in let s = outer_select env coll [] (sources_select u.ctes f joins) in let env = with_ctes env s in let expr = outer_expr env coll in let target = Option.value u.alias ~default:u.table in let on = (target, []) :: binding_scope env s in Update { u with ctes = s.ctes; sets = List.map (fun (c, v) -> (c, expr on v)) u.sets; from = Option.map (fun _ -> (s.from, s.joins)) u.from; where = Option.map (expr on) u.where; } | Delete d -> let s = outer_select env coll [] (sources_select d.ctes Unit []) in let env = with_ctes env s in let on = [ (Option.value d.alias ~default:d.table, []) ] in Delete { d with ctes = s.ctes; where = Option.map (outer_expr env coll on) d.where; } | st -> st (* The sequence of a column of the enclosing query's [sources] that a correlated subquery reads, where no source of the subquery's own [own] binds the name first (resolve.c, lookupName, which tries each name context from the innermost out). *) let enclosing sources own = function | Col (q, n) as e when not (scope_binds own q n) -> Option.map (fun ((src : source), n) -> Option.value (src.declares n) ~default:"BINARY") (column_source sources e) | _ -> None let trigger_collations env (tg : create_trigger) = let coll = trigger_row (env.collation tg.table) in { tg with when_ = Option.map (outer_expr env coll []) tg.when_; body = List.map (row_stmt env coll) tg.body; } let collations env (s : select) = (* The rewrite runs even for a select with no source of its own to read a declared sequence from: an [IN (SELECT ...)] takes one from the subquery, so [SELECT 'x' IN (SELECT c FROM t)] has a sequence to find though its own FROM offers none. *) let sources = from_sources env s in let col_coll = collation_for sources in let select = outer_select env (enclosing sources) [] in let rw e = collation_expr ~select env col_coll (truth_columns sources e) in let lhs_coll e = let e = truth_columns sources e in collation_lhs col_coll ~written:e (collation_expr ~select env col_coll e) in let order_key (e, dir) = (lhs_coll e, dir) in (* A DISTINCT dedups its output columns under the sequences they carry, so each result expression is a key like a GROUP BY's and takes the same rewrite. It stays the same column to a reader: {!named_column} looks through the wrapper this puts on. *) let result_col (rc : result_col) = { rc with expr = (if s.distinct then lhs_coll rc.expr else rw rc.expr) } in { s with cols = List.map result_col s.cols; where = Option.map rw s.where; having = Option.map rw s.having; group_by = List.map lhs_coll s.group_by; order_by = List.map order_key s.order_by; joins = List.map (fun (j : join) -> { j with on = Option.map rw j.on }) s.joins; } (* The same rewrite over a bare expression, for a statement that has no FROM to read its sources from: a DELETE's or an UPDATE's WHERE, whose one row is in scope under the name the statement gives it. [bases] pairs that name with the table the row came from, which is what carries the declared sequence. *) let collate_over env bases = let sources = List.map (named_source env) bases in let select = outer_select env (enclosing sources) [] in let col_coll = collation_for sources in fun e -> collation_expr ~select env col_coll (truth_columns sources e) let rec correlated env bound (s : select) = let env = with_ctes env s in let scope = bound @ binding_scope env s in let col_free = function | Col (qual, name) -> not (scope_binds scope qual name) | _ -> false in (* A nested subquery extends the scope rather than closing it, so it is asked the same question under [scope]; everything else is an expression of this select and is looked into. *) let rec free e = match e with | Col _ -> col_free e | e -> Ast.fold_expr ~select:(fun acc sub -> acc || correlated env scope sub) (fun acc x -> acc || free x) false e in (* A FROM operand and a WITH body are resolved with the enclosing name contexts outside their own and without the sources beside them (resolve.c, resolveSelectStep), so they are asked under [bound]; a table-valued function's arguments may also read the sources to their left, and are asked under [scope]. *) let operand (tr : table_ref) = Option.fold ~none:false ~some:(correlated env bound) tr.subquery in let from = match s.from with | Table tr -> operand tr | Select { fs_select; _ } -> correlated env bound fs_select | Values rows -> List.exists (List.exists (free_in env bound)) rows | Table_function { tf_args; _ } -> List.exists free tf_args | Unit -> false in List.exists (fun (rc : result_col) -> free rc.expr) s.cols || Option.fold ~none:false ~some:free s.where || Option.fold ~none:false ~some:free s.having || List.exists free s.group_by || List.exists (fun (e, _) -> free e) s.order_by || List.exists (fun (j : join) -> Option.fold ~none:false ~some:free j.on || operand j.table) s.joins || from || List.exists (fun (c : cte) -> correlated env bound c.query) s.ctes || List.exists (fun (_, arm) -> correlated env bound arm) s.compound (* Whether [e], an expression read outside any source of its own, reads a column [bound] does not bind. *) and free_in env bound e = match e with | Col (qual, name) -> not (scope_binds bound qual name) | e -> Ast.fold_expr ~select:(fun acc sub -> acc || correlated env bound sub) (fun acc x -> acc || free_in env bound x) false e exception Subst_hard (** Raised by {!subst_expr} on a node the simple substituter does not descend into (a nested subquery or a window), so the caller falls back. *) (* Rebuild [e], applying [replace qual name e] to each column reference and recursing structurally everywhere else. A nested subquery / window raises {!Subst_hard}. *) let rec subst_expr ~replace e = match e with | Col (qual, name) -> replace qual name e | Window _ -> raise Subst_hard | e -> Ast.map_expr ~select:(fun _ -> raise Subst_hard) (subst_expr ~replace) e let rec scope_value scope qual name = match scope with | [] -> None | (alias, cols) :: rest -> ( match qual with | Some q when not (ident_equal q alias) -> scope_value rest qual name | None when is_semi_alias alias -> scope_value rest qual name | _ -> ( match Catalog.Ident.assoc_opt name cols with | Some v -> Some v | None -> ( match if is_rowid_name name then List.assoc_opt rowid_sentinel cols else None with | Some v -> Some v | None -> scope_value rest qual name))) (* The refusal of a column reference no name context binds, worded with its qualifier as written. *) let no_such_column qual name = match qual with | Some q -> Catalog.Error.fail_prepare "no such column: %s.%s" q name | None -> Catalog.Error.fail_prepare "no such column: %s" name (* [q]'s FROM with [operand] applied to a derived table, [outside] to the expressions of a VALUES and [inside] to a table-valued function's arguments, which may read the sources to their left. *) let map_from ~operand ~outside ~inside (q : select) : from_clause = match q.from with | Table tr -> Table { tr with subquery = Option.map operand tr.subquery } | Select fs -> Select { fs with fs_select = operand fs.fs_select } | Values rows -> Values (List.map (List.map outside) rows) | Table_function tf -> Table_function { tf with tf_args = List.map inside tf.tf_args } | Unit -> Unit (* [q] with [expr] applied to its own expressions, [operand] to the selects of its WITH and its join operands, [arm] to its compound arms, and [from] in place of its FROM. *) let map_select ~expr ~operand ~arm ~from (q : select) = let table_ref (tr : table_ref) = { tr with subquery = Option.map operand tr.subquery } in { q with ctes = List.map (fun (c : cte) -> { c with query = operand c.query }) q.ctes; from; cols = List.map (fun (rc : Ast.result_col) -> { rc with expr = expr rc.expr }) q.cols; where = Option.map expr q.where; group_by = List.map expr q.group_by; having = Option.map expr q.having; order_by = List.map (fun (e, d) -> (expr e, d)) q.order_by; joins = List.map (fun (j : join) -> { j with table = table_ref j.table; on = Option.map expr j.on }) q.joins; compound = List.map (fun (op, a) -> (op, arm a)) q.compound; } (* [s] with [free qual name e] in place of each column reference [e] that neither the [FROM] of [s] nor that of a nested select binds; one in a [FROM] operand or a [WITH] body is free of the sources beside it, which it does not see. *) let map_free env ~free (s : select) = let rec sub env own e = match e with | Col (qual, name) when not (scope_binds own qual name) -> free qual name e | e -> Ast.map_expr ~select:(sub_select env own) (sub env own) e (* Each arm of a compound binds its own FROM over the scope the compound sits in, never over an earlier arm's sources (resolve.c, resolveSelectStep resolves each p->pPrior in a name context of its own). *) and sub_select env bound (q : select) = let env = with_ctes env q in let own = bound @ binding_scope env q in (* A FROM operand and a WITH body see the enclosing rows and not the sources beside them, so they are rewritten under [bound]. *) let operand = sub_select env bound in let from = map_from ~operand ~outside:(sub env bound) ~inside:(sub env own) q in map_select ~expr:(sub env own) ~operand ~arm:(sub_select env bound) ~from q in sub_select env [] s let bind_scope env scope (s : select) ~params = let next = ref (Array.length params) and values = ref [] in (* the value as the parameter after the last one: a bound value is a constant, never the column ordinal an integer GROUP BY or ORDER BY term written as one would be (resolve.c, resolveOrderGroupBy) *) let bind v = values := v :: !values; incr next; Param (!next - 1) in let free qual name _ = match scope_value scope qual name with | Some v -> bind v (* no name context out to the enclosing rows binds it either *) | None -> no_such_column qual name in let s = map_free env ~free s in (s, Array.append params (Array.of_list (List.rev !values))) (* The affinity of the column [qual.name] of [layout], found as {!scope_value} finds its value: [None] where no source of [layout] has it, and [Some aff] where one does, the hidden rowid's INTEGER. *) let rec layout_affinity ~affinity i layout qual name = match layout with | [] -> None | (alias, cols) :: rest -> ( let next () = layout_affinity ~affinity (i + 1) rest qual name in match qual with | Some q when not (ident_equal q alias) -> next () | None when is_semi_alias alias -> next () | _ -> ( match Catalog.Ident.index name cols with | Some j -> Some (affinity (i, j)) | None -> if is_rowid_name name && List.mem rowid_sentinel cols then Some (Some `Integer) else next ())) let enclosing_affinity env layout ~affinity (s : select) = let free qual name e = match layout_affinity ~affinity 0 layout qual name with | Some (Some aff) -> Affinity (e, aff) | Some None | None -> e in map_free env ~free s let substitute ?(moved = fun _ _ -> ()) env ~own ~by e = let rec sub env inner e = match e with | Col (qual, name) when (not (scope_binds inner qual name)) && scope_binds own qual name -> by name | e -> Ast.map_expr ~select:(sub_select env inner) (sub env inner) e (* a nested select's own FROM binds before [own] does, its operands and WITH bodies seeing only the scope outside it, as in {!bind_scope} *) and sub_select env bound (q : select) = let env = with_ctes env q in let inner = bound @ binding_scope env q in let operand = sub_select env bound in let from = map_from ~operand ~outside:(sub env bound) ~inside:(sub env inner) q in let q' = map_select ~expr:(sub env inner) ~operand ~arm:(sub_select env bound) ~from q in moved q' q; q' in sub env [] e let requalify ?moved env ~own ~alias e = substitute ?moved env ~own ~by:(fun name -> Col (Some alias, name)) e (* The [FROM] list is left-associative, so the join at position [p] takes source [p + 1] against the sources before it: [leading layout p] is what a NATURAL or USING join at that position may equate against. *) let leading (layout : (string * string list) list) p = List.filteri (fun ci _ -> ci <= p) layout (* The source of [leading] that owns the column [c] -- the left-most one that has it, which is the rule sqlite3 reads a common column by (lang_select.html sec.3). The hidden rowid slot is not a user column: every source carries one, so it would otherwise match them all spuriously. *) let owner_of leading c = if c = rowid_sentinel then None else List.find_map (fun (a, cs) -> if List.exists (ident_equal c) cs then Some a else None) leading (* A NATURAL join's match columns (or the [USING] list): the columns of the source at [p] that some earlier source already has. A layout with no source there describes a scan the [FROM] list does not, and equates nothing. *) let common_columns (layout : (string * string list) list) p (j : Ast.join) = if j.using <> [] then j.using else let leading = leading layout (p - 1) in match List.nth_opt layout p with | None -> [] | Some (_, jcols) -> List.filter (fun c -> owner_of leading c <> None) jcols (* The equality a NATURAL / USING join stands for, as the ON it equals: each common column of the source at [p] against the leftmost earlier source with it (lang_select.html sec.3). *) let natural_on (layout : (string * string list) list) p (j : join) = let jalias, jcols = match List.nth_opt layout p with | Some s -> s | None -> raise Ir.Unsupported in let leading = leading layout (p - 1) in let eq c = let owner = owner_of leading c in if j.using <> [] && (Option.is_none owner || Option.is_none (Catalog.Ident.index c jcols)) then Catalog.Error.fail_prepare "cannot join using column %s - column not present in both tables" c; Option.map (fun a -> Binary (Eq, Col (Some a, c), Col (Some jalias, c))) owner in match List.filter_map eq (common_columns layout p j) with | [] -> None | e :: rest -> Some (List.fold_left (fun acc x -> Binary (And, acc, x)) e rest) let equated_columns (layout : (string * string list) list) (s : select) = let equated_of p (j : join) = if not (j.natural || j.using <> []) then [] else let ci = p + 1 in match List.nth_opt layout ci with | None -> [] | Some (_, jcols) -> List.filter_map (fun c -> Option.map (fun i -> (ci, i)) (Catalog.Ident.index c jcols)) (common_columns layout ci j) in List.concat (List.mapi equated_of s.joins) type layout_kind = Sources of (int * int) list | Frames (* The refusal a name two sources publish earns, by the name as written: a qualified reference carries its qualifier into the message and a bare one does not. *) let ambiguous qual name = match qual with | Some q -> Catalog.Error.fail_prepare "ambiguous column name: %s.%s" q name | None -> Catalog.Error.fail_prepare "ambiguous column name: %s" name let layout_slot kind (layout : (string * string list) list) qual name = let bears a = match qual with None -> not (is_semi_alias a) | Some q -> ident_equal q a in (* The first slot publishing [col] at or past relation [ci], [found] the one an earlier relation published. Frames take the first; sources go on to the end, a second slot being an ambiguity unless it is a copy a join equated. *) let rec published col ci found = function | [] -> found | (a, cols) :: t -> ( match if bears a then Catalog.Ident.index col cols else None with | None -> published col (ci + 1) found t | Some j -> ( match (found, kind) with | None, Frames -> Some (ci, j) | None, Sources _ -> published col (ci + 1) (Some (ci, j)) t | Some _, Sources equated when List.mem (ci, j) equated -> published col (ci + 1) found t | Some _, (Sources _ | Frames) -> ambiguous qual name)) in match published name 0 None layout with | None when is_rowid_name name -> published rowid_sentinel 0 None layout | found -> found (* Whether [layout] has a place for the column reference [qual].[name]: the same lookup, asked for an answer rather than for a position. *) let layout_publishes kind layout qual name = Option.is_some (layout_slot kind layout qual name) let check_columns layout (s : select) = let kind = Sources (equated_columns layout s) in let rec check e = match e with | Col (qual, name) -> if not (layout_publishes kind layout qual name) then no_such_column qual name (* A subquery reads sources of its own, which [layout] does not describe, and a column free in it is the enclosing query's rather than an unknown one. Neither question can be settled from here, so both are left to the lowering, which has the whole scope. *) | e -> Ast.fold_expr ~select:(fun () _ -> ()) (fun () x -> check x) () e in List.iter (fun (rc : result_col) -> check rc.expr) s.cols; Option.iter check s.where; List.iter check s.group_by; Option.iter check s.having; List.iter (fun (e, _) -> check e) s.order_by; List.iter (fun (j : join) -> Option.iter check j.on) s.joins (* resolve.c compares each arm with the one to its right, from the rightmost pair leftward, and names the operator between the first pair that differs. *) let check_widths env (s : select) = if s.compound <> [] then begin let env = with_ctes env s in let width q = List.length (select_columns env q) in let rec rightmost w = function | [] -> None | (op, arm) :: rest -> ( let w' = width arm in match rightmost w' rest with | Some _ as found -> found | None -> if w <> w' then Some op else None) in match rightmost (width s) s.compound with | None -> () | Some op -> Catalog.Error.fail_prepare "SELECTs to the left and right of %s do not have the same number of \ result columns" (set_op_keyword op) end (* The expressions a select reads in its own name context: its select list and clauses. Its FROM operands, WITH bodies and compound arms are selects of their own. *) let clause_exprs (q : select) = List.map (fun (rc : result_col) -> rc.expr) q.cols @ Option.to_list q.where @ q.group_by @ Option.to_list q.having @ List.map fst q.order_by @ List.filter_map (fun (j : join) -> j.on) q.joins (* Whether a source of [scope] has the column [qual].[name]: a qualified name needs the source it names to have the column, or sqlite3's lookupName goes on to the next name context out (resolve.c). A source whose columns are not known here (none listed) is taken to have it, qualified or not: it is a table the database does not hold, refused when the statement locates it. *) let scope_has scope qual name = let unknown (_, cols) = cols = [] in let has src = unknown src || List.exists (ident_equal name) (snd src) || (is_rowid_name name && List.mem rowid_sentinel (snd src)) in match qual with | Some q -> List.exists (fun ((a, _) as src) -> ident_equal q a && has src) scope | None -> scope_binds scope None name || List.exists unknown scope let unknown_column qual name = match qual with | Some q -> Catalog.Error.fail_prepare "no such column: %s.%s" q name | None -> Catalog.Error.fail_prepare "no such column: %s" name (* sqlite3LocateTable: a table the schema does not hold, nor a WITH in scope, is no such table. *) let locate (env : env) (tr : table_ref) = if not (env.holds tr.name) then match tr.schema with | Some s -> Catalog.Error.fail_prepare "no such table: %s.%s" s tr.name | None -> Catalog.Error.fail_prepare "no such table: %s" tr.name (* The WITH tables of [q] that [q] reads, directly or through the body of another it reads, in the order [q] declares them: sqlite3 expands a WITH table where a FROM names it (select.c, resolveFromTermToCte), so one nothing reads is never resolved. *) let read_ctes (q : select) = if q.ctes = [] then [] else let reads names (c : cte) = List.exists (ident_equal c.name) names in let rec close read = let names = List.concat_map (fun (c : cte) -> table_names c.query) read in let more = List.filter (fun c -> (not (List.memq c read)) && reads names c) q.ctes in if more = [] then read else close (read @ more) in let read = close (List.filter (reads (table_names { q with ctes = [] })) q.ctes) in List.filter (fun c -> List.memq c read) q.ctes (* [e]'s names under [own], the name contexts around it from the innermost out, [alias] saying which bare names are a result alias of the select [e] belongs to; [select] is called on each select [e] holds, and [frame qual name] answers for a name no source binds: a trigger's NEW and OLD. *) let rec expr_names ~select ~frame env ?(alias = fun _ -> false) own e = match e with | Col (qual, name) -> if not (scope_has own qual name || (qual = None && alias name) || frame qual name) then unknown_column qual name | e -> Ast.fold_expr ~select:(fun () q -> select_names ~select ~frame env own q) (fun () x -> expr_names ~select ~frame env ~alias own x) () e (* A select of its own: its names resolve against its sources, then a result alias, then [bound], as sqlite3's lookupName tries each name context outward (resolve.c). *) and select_names ~select ~frame env bound (q : select) = select q; let env = with_ctes env q in let own = bound @ binding_scope env q in let alias name = List.exists (fun (rc : result_col) -> match rc.alias with Some a -> ident_equal a name | None -> false) q.cols in from_names ~select ~frame env bound own q; List.iter (expr_names ~select ~frame env ~alias own) (clause_exprs q); List.iter (fun (_, arm) -> select_names ~select ~frame env bound arm) q.compound; check_widths env q (* [q]'s FROM operands and the WITH bodies it reads, which see [bound] and not the sources beside them (resolveSelectStep), and its table-valued function arguments, which see those too. Each table a FROM names is located first, as selectExpander locates it before a name of [q] is resolved. *) and from_names ~select ~frame env bound own (q : select) = let table (tr : table_ref) = match tr.subquery with | Some sub -> select_names ~select ~frame env bound sub | None -> locate env tr in List.iter (fun (c : cte) -> select_names ~select ~frame env bound c.query) (read_ctes q); (match q.from with | Table tr -> table tr | Select fs -> select_names ~select ~frame env bound fs.fs_select | Values rows -> List.iter (List.iter (expr_names ~select ~frame env bound)) rows | Table_function tf -> List.iter (expr_names ~select ~frame env own) tf.tf_args | Unit -> ()); List.iter (fun (j : join) -> table j.table) q.joins let check_subqueries ?(select = ignore) env (s : select) = let frame _ _ = false in let env = with_ctes env s in let own = binding_scope env s in let rec subqueries e = Ast.fold_expr ~select:(fun () q -> select_names ~select ~frame env own q) (fun () x -> subqueries x) () e in from_names ~select ~frame env [] own s; List.iter subqueries (clause_exprs s) (* The one source a DML statement writes, as its WHERE and SET read it. *) let target_scope env ?alias table = binding_scope env (sources_select [] (Table { name = table; schema = None; alias; subquery = None }) []) let table_columns env table = try env.columns table with Catalog.Error (Prepare _ | Runtime _) -> [] (* [src] with the expressions a DML statement evaluates over it, so the WITH tables its sources read include those its SET, WHERE and RETURNING read. *) let reading src exprs where returning = { src with cols = List.map (fun expr : result_col -> { expr; alias = None }) exprs @ returning; where; } (* A step's names: each statement's own sources, then NEW or OLD under their qualifier alone. *) (* An upsert's sources: its target, and the row the INSERT would have written, under [excluded]. *) let upsert_scope env table = target_scope env table @ [ ("excluded", table_columns env table) ] (* A bare name of [e] that more than one source of [context] binds, refused as ambiguous: [context] is one name context, an UPDATE ... FROM's target and FROM sources, and a select [e] holds reads it only for a name its own sources do not bind (resolve.c, lookupName). A context of one source binds no name twice, so it is not walked. *) let single_binder env context e = if List.compare_length_with context 1 > 0 then let rec expr inner e = match e with | Col (None, name) -> if (not (scope_binds inner None name)) && List.compare_length_with (scope_binders context None name) 1 > 0 then ambiguous None name | e -> Ast.fold_expr ~select:(fun () q -> select inner q) (fun () x -> expr inner x) () e and select inner q = let own = inner @ binding_scope (with_ctes env q) q in List.iter (expr own) (clause_exprs q); List.iter (fun (_, arm) -> select inner arm) q.compound in expr [] e let step_names ~frame env (st : stmt) = let select = ignore in let expr own e = expr_names ~select ~frame env own e in match st with | Select s -> select_names ~select ~frame env [] s | Insert i -> ( (match i.source with | Values rows -> List.iter (List.iter (expr [])) rows | Select s -> select_names ~select ~frame env [] s | Default_values -> ()); match i.upsert with | None -> () | Some u -> ( let own = upsert_scope env i.table in Option.iter (expr own) u.target_where; match u.action with | Nothing -> () | Update (sets, w) -> List.iter (fun (_, e) -> expr own e) sets; Option.iter (expr own) w)) | Update u -> let f, joins = Option.value u.from ~default:(Unit, []) in let src = sources_select u.ctes f joins in let env = with_ctes env src in let own = target_scope env ?alias:u.alias u.table @ binding_scope env src in from_names ~select ~frame env [] own (reading src (List.map snd u.sets) u.where u.returning); let checked e = single_binder env own e; expr own e in List.iter (fun (_, e) -> checked e) u.sets; Option.iter checked u.where | Delete d -> let src = sources_select d.ctes Unit [] in let env = with_ctes env src in from_names ~select ~frame env [] [] (reading src [] d.where d.returning); Option.iter (expr (target_scope env ?alias:d.alias d.table)) d.where | _ -> () let check_statement env st = step_names ~frame:(fun _ _ -> false) env st let check_upsert_expr env ~table e = expr_names ~select:ignore ~frame:(fun _ _ -> false) env (upsert_scope env table) e let check_returning env ~table returning = let own = target_scope env table in List.iter (fun (rc : result_col) -> expr_names ~select:ignore ~frame:(fun _ _ -> false) env own rc.expr) returning (* sqlite3 locates no table of a trigger's body as it creates the trigger, only as a statement that fires it is prepared. *) let check_trigger env (tg : create_trigger) = let env = { (env : env) with holds = (fun _ -> true) } in let cols = table_columns env tg.table in (* lookupName reads the trigger's row only under a new or old qualifier, for a column of its table or a rowid name (resolve.c, TK_TRIGGER) *) let frame qual name = match qual with | Some q when ident_equal q "new" || ident_equal q "old" -> cols = [] || List.exists (ident_equal name) cols || is_rowid_name name | _ -> false in Option.iter (expr_names ~select:ignore ~frame env []) tg.when_; List.iter (step_names ~frame env) tg.body