uqa_sql/ast/from.rs
1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7use serde::{Deserialize, Serialize};
8
9use super::{Expr, FunctionBinding, InternalRelationId, SelectStmt};
10
11#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
12pub enum FromClause {
13 /// Execution-scoped rows with an opaque identity and no SQL-visible names.
14 #[serde(skip)]
15 #[doc(hidden)]
16 RetainedRows(super::RetainedRowSource),
17 /// `FROM <table> [AS <alias>]`.
18 Table {
19 /// Durable catalog identity, including an explicit schema when present.
20 name: String,
21 /// Relation name visible to SQL column binding before an alias is applied.
22 qualifier: String,
23 alias: Option<String>,
24 /// Positional names exposed by the range-table alias.
25 #[serde(default, skip_serializing_if = "Vec::is_empty")]
26 column_aliases: Vec<String>,
27 /// Creation-bound physical columns of a stored table source, before positional aliases. Column deletion and renaming update this list; later additions do not change its shape.
28 #[serde(default, skip_serializing_if = "Option::is_none")]
29 bound_columns: Option<Vec<String>>,
30 /// Ordinary references include inheritance children; `ONLY table`
31 /// clears this flag.
32 #[serde(default = "default_include_descendants")]
33 include_descendants: bool,
34 },
35 /// `FROM left <kind> right ON predicate`. `lateral` is true when
36 /// the right side is a LATERAL subquery / function -- the engine
37 /// re-evaluates it for every left row.
38 Join {
39 left: Box<FromClause>,
40 right: Box<FromClause>,
41 kind: JoinKind,
42 /// Boolean qualification supplied by `ON`. This is mutually
43 /// exclusive with `using` and `natural` in parser-produced trees.
44 on: Option<Expr>,
45 /// `PostgreSQL` `USING (column, ...) [AS alias]` metadata. The column
46 /// list must remain explicit until both input row types are known so
47 /// binding can validate each side and construct the merged output.
48 #[serde(default, skip_serializing_if = "Option::is_none")]
49 using: Option<JoinUsing>,
50 /// `NATURAL` derives its `USING` list from the visible columns of both
51 /// input row types at binding time.
52 #[serde(default)]
53 natural: bool,
54 /// Alias applied to the complete parenthesized JOIN result. When
55 /// present, the input relation names are hidden from the enclosing
56 /// query level.
57 #[serde(default, skip_serializing_if = "Option::is_none")]
58 alias: Option<String>,
59 /// Positional aliases for the JOIN output after USING/NATURAL shaping.
60 #[serde(default, skip_serializing_if = "Vec::is_empty")]
61 column_aliases: Vec<String>,
62 #[allow(dead_code)]
63 lateral: bool,
64 },
65 /// `FROM (VALUES (...)...) [AS <alias>(<col_aliases>)]`.
66 Values {
67 rows: Vec<Vec<Expr>>,
68 alias: Option<String>,
69 column_aliases: Vec<String>,
70 /// Opaque identity for an engine-injected, SQL-invisible VALUES row
71 /// carrier. Parser-produced VALUES sources always leave this unset.
72 #[serde(default, skip_serializing_if = "Option::is_none")]
73 #[doc(hidden)]
74 internal_relation: Option<InternalRelationId>,
75 /// Declared physical attribute types for an internal VALUES carrier;
76 /// needed even when the carrier has zero rows.
77 #[serde(default, skip_serializing_if = "Vec::is_empty")]
78 #[doc(hidden)]
79 internal_column_types: Vec<Option<super::ColumnType>>,
80 /// Implicit collation identities of internal attributes, independent of row presence. An absent legacy vector uses each declared type's default.
81 #[serde(default, skip_serializing_if = "Vec::is_empty")]
82 #[doc(hidden)]
83 internal_column_collations: Vec<Option<u32>>,
84 },
85 /// `FROM <fn>(<args>) [AS <alias>(<col_aliases>)]` -- e.g.
86 /// `generate_series(1, 5)`, `unnest(arr)`, `regexp_split_to_table`,
87 /// `json_each(...)`, `cypher(...) AS (col agtype, ...)`. The engine
88 /// dispatches by name.
89 Function {
90 name: String,
91 /// Exact catalog routine identity for a stored expression tree. Parser-produced trees leave this unset and catalog owners bind it before persistence.
92 #[serde(default, skip_serializing_if = "Option::is_none")]
93 binding: Option<FunctionBinding>,
94 /// Local function identifier used as `PostgreSQL`'s default output column label. Kept separate from the catalog-qualified lookup name so quoted identifiers containing `.` remain indivisible.
95 output_name: String,
96 /// Catalog relations bound to a tuple-producing operator join, kept separate from scalar arguments so each operand retains its own name-resolution, dependency, planning, and execution context.
97 #[serde(default, skip_serializing_if = "Option::is_none")]
98 relations: Option<OperatorJoinRelations>,
99 args: Vec<Expr>,
100 alias: Option<String>,
101 column_aliases: Vec<String>,
102 /// Append `PostgreSQL`'s one-based `bigint` ordinality column after the function's ordinary output columns.
103 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
104 ordinality: bool,
105 /// Declared column types when the alias used a column
106 /// definition list (`AS (col agtype, n int)`); empty when the
107 /// alias only renamed columns. Type names are lowercased
108 /// `PostgreSQL` internal names (`agtype`, `int4`, `text`, ...).
109 #[serde(default)]
110 column_types: Vec<String>,
111 },
112 /// One `PostgreSQL` range-function group. This represents explicit
113 /// `ROWS FROM (...)` syntax and the parser transform of an unqualified
114 /// multi-argument `unnest(a, b, ...)` into independent unary
115 /// `pg_catalog.unnest` members. Members are evaluated independently and
116 /// their result columns are concatenated in declaration order.
117 FunctionGroup {
118 functions: Vec<TableFunction>,
119 /// Alias applied to the complete group rather than to an individual
120 /// member.
121 alias: Option<String>,
122 /// Positional aliases for the concatenated group output.
123 column_aliases: Vec<String>,
124 /// Append one group-wide, one-based `bigint` ordinality column after
125 /// every member's ordinary output columns.
126 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
127 ordinality: bool,
128 },
129 /// `FROM (SELECT ...) AS <alias>` -- subquery as a relation.
130 /// The body re-runs as if a CTE; the alias renames the result
131 /// columns when supplied.
132 Subquery {
133 body: Box<SelectStmt>,
134 alias: Option<String>,
135 column_aliases: Vec<String>,
136 },
137}
138
139const fn default_include_descendants() -> bool {
140 true
141}
142
143/// One function inside a [`FromClause::FunctionGroup`].
144///
145/// A member owns its column definition list because `ROWS FROM` permits a
146/// distinct `AS (name type, ...)` clause after each call. The range item's
147/// relation alias, positional aliases, and ordinality remain on the enclosing
148/// group.
149#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
150pub struct TableFunction {
151 pub name: String,
152 /// Exact catalog routine identity for a stored expression tree. Parser-produced trees leave this unset and catalog owners bind it before persistence.
153 #[serde(default, skip_serializing_if = "Option::is_none")]
154 pub binding: Option<FunctionBinding>,
155 pub output_name: String,
156 #[serde(default, skip_serializing_if = "Option::is_none")]
157 pub relations: Option<OperatorJoinRelations>,
158 pub args: Vec<Expr>,
159 #[serde(default, skip_serializing_if = "Vec::is_empty")]
160 pub column_aliases: Vec<String>,
161 #[serde(default, skip_serializing_if = "Vec::is_empty")]
162 pub column_types: Vec<String>,
163}
164
165/// The two independently bound catalog relations consumed by an operator-join table function.
166#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
167pub struct OperatorJoinRelations {
168 pub left: String,
169 pub right: String,
170}
171
172#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
173pub struct JoinUsing {
174 pub columns: Vec<String>,
175 #[serde(default, skip_serializing_if = "Option::is_none")]
176 pub alias: Option<String>,
177}
178
179impl FromClause {
180 /// All table names referenced under this clause, in declaration
181 /// order. Used by the compiler to resolve unqualified column refs.
182 pub fn collect_tables(&self, out: &mut Vec<(String, Option<String>)>) {
183 match self {
184 FromClause::RetainedRows(_) => {}
185 FromClause::Table {
186 name,
187 qualifier,
188 alias,
189 ..
190 } => out.push((
191 name.clone(),
192 Some(alias.as_ref().unwrap_or(qualifier).clone()),
193 )),
194 FromClause::Join { left, right, .. } => {
195 left.collect_tables(out);
196 right.collect_tables(out);
197 }
198 FromClause::Values { alias, .. }
199 | FromClause::Function { alias, .. }
200 | FromClause::FunctionGroup { alias, .. }
201 | FromClause::Subquery { alias, .. } => {
202 if let Some(a) = alias {
203 out.push((a.clone(), Some(a.clone())));
204 }
205 }
206 }
207 }
208}
209
210#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
211pub enum JoinKind {
212 Inner,
213 Left,
214 Right,
215 Full,
216 Cross,
217}