Skip to main content

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` permits the explicit right input to reference preceding sources; actual references determine whether execution needs each left row.
36    Join {
37        /// Preserve separate FROM/USING list entries when their Cartesian product is represented by a join.
38        #[serde(default, skip_serializing_if = "std::ops::Not::not")]
39        comma: bool,
40        left: Box<FromClause>,
41        right: Box<FromClause>,
42        kind: JoinKind,
43        /// Boolean qualification supplied by `ON`. This is mutually
44        /// exclusive with `using` and `natural` in parser-produced trees.
45        on: Option<Expr>,
46        /// `PostgreSQL` `USING (column, ...) [AS alias]` metadata. The column
47        /// list must remain explicit until both input row types are known so
48        /// binding can validate each side and construct the merged output.
49        #[serde(default, skip_serializing_if = "Option::is_none")]
50        using: Option<JoinUsing>,
51        /// `NATURAL` derives its `USING` list from the visible columns of both
52        /// input row types at binding time.
53        #[serde(default)]
54        natural: bool,
55        /// Alias applied to the complete parenthesized JOIN result. When
56        /// present, the input relation names are hidden from the enclosing
57        /// query level.
58        #[serde(default, skip_serializing_if = "Option::is_none")]
59        alias: Option<String>,
60        /// Positional aliases for the JOIN output after USING/NATURAL shaping.
61        #[serde(default, skip_serializing_if = "Vec::is_empty")]
62        column_aliases: Vec<String>,
63        #[allow(dead_code)]
64        lateral: bool,
65    },
66    /// `FROM (VALUES (...)...) [AS <alias>(<col_aliases>)]`.
67    Values {
68        /// Whether this range item may read preceding FROM items at its query level.
69        #[serde(default, skip_serializing_if = "std::ops::Not::not")]
70        lateral: bool,
71        rows: Vec<Vec<Expr>>,
72        alias: Option<String>,
73        column_aliases: Vec<String>,
74        /// Opaque identity for an engine-injected, SQL-invisible VALUES row
75        /// carrier. Parser-produced VALUES sources always leave this unset.
76        #[serde(default, skip_serializing_if = "Option::is_none")]
77        #[doc(hidden)]
78        internal_relation: Option<InternalRelationId>,
79        /// Declared physical attribute types for an internal VALUES carrier;
80        /// needed even when the carrier has zero rows.
81        #[serde(default, skip_serializing_if = "Vec::is_empty")]
82        #[doc(hidden)]
83        internal_column_types: Vec<Option<super::ColumnType>>,
84        /// Implicit collation identities of internal attributes, independent of row presence. An absent legacy vector uses each declared type's default.
85        #[serde(default, skip_serializing_if = "Vec::is_empty")]
86        #[doc(hidden)]
87        internal_column_collations: Vec<Option<u32>>,
88    },
89    /// `FROM <fn>(<args>) [AS <alias>(<col_aliases>)]` -- e.g.
90    /// `generate_series(1, 5)`, `unnest(arr)`, `regexp_split_to_table`,
91    /// `json_each(...)`, `cypher(...) AS (col agtype, ...)`. The engine
92    /// dispatches by name.
93    Function {
94        name: String,
95        /// Exact catalog routine identity for a stored expression tree. Parser-produced trees leave this unset and catalog owners bind it before persistence.
96        #[serde(default, skip_serializing_if = "Option::is_none")]
97        binding: Option<FunctionBinding>,
98        /// 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.
99        output_name: String,
100        /// 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.
101        #[serde(default, skip_serializing_if = "Option::is_none")]
102        relations: Option<OperatorJoinRelations>,
103        args: Vec<Expr>,
104        alias: Option<String>,
105        column_aliases: Vec<String>,
106        /// Append `PostgreSQL`'s one-based `bigint` ordinality column after the function's ordinary output columns.
107        #[serde(default, skip_serializing_if = "std::ops::Not::not")]
108        ordinality: bool,
109        /// Declared column types when the alias used a column
110        /// definition list (`AS (col agtype, n int)`); empty when the
111        /// alias only renamed columns. Type names are lowercased
112        /// `PostgreSQL` internal names (`agtype`, `int4`, `text`, ...).
113        #[serde(default)]
114        column_types: Vec<String>,
115    },
116    /// One `PostgreSQL` range-function group. This represents explicit
117    /// `ROWS FROM (...)` syntax and the parser transform of an unqualified
118    /// multi-argument `unnest(a, b, ...)` into independent unary
119    /// `pg_catalog.unnest` members. Members are evaluated independently and
120    /// their result columns are concatenated in declaration order.
121    FunctionGroup {
122        functions: Vec<TableFunction>,
123        /// Alias applied to the complete group rather than to an individual
124        /// member.
125        alias: Option<String>,
126        /// Positional aliases for the concatenated group output.
127        column_aliases: Vec<String>,
128        /// Append one group-wide, one-based `bigint` ordinality column after
129        /// every member's ordinary output columns.
130        #[serde(default, skip_serializing_if = "std::ops::Not::not")]
131        ordinality: bool,
132    },
133    /// `FROM (SELECT ...) AS <alias>` -- subquery as a relation.
134    /// The body re-runs as if a CTE; the alias renames the result
135    /// columns when supplied.
136    Subquery {
137        /// Whether this range item may read preceding FROM items at its query level.
138        #[serde(default, skip_serializing_if = "std::ops::Not::not")]
139        lateral: bool,
140        body: Box<SelectStmt>,
141        alias: Option<String>,
142        column_aliases: Vec<String>,
143    },
144}
145
146const fn default_include_descendants() -> bool {
147    true
148}
149
150/// One function inside a [`FromClause::FunctionGroup`].
151///
152/// A member owns its column definition list because `ROWS FROM` permits a
153/// distinct `AS (name type, ...)` clause after each call. The range item's
154/// relation alias, positional aliases, and ordinality remain on the enclosing
155/// group.
156#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
157pub struct TableFunction {
158    pub name: String,
159    /// Exact catalog routine identity for a stored expression tree. Parser-produced trees leave this unset and catalog owners bind it before persistence.
160    #[serde(default, skip_serializing_if = "Option::is_none")]
161    pub binding: Option<FunctionBinding>,
162    pub output_name: String,
163    #[serde(default, skip_serializing_if = "Option::is_none")]
164    pub relations: Option<OperatorJoinRelations>,
165    pub args: Vec<Expr>,
166    #[serde(default, skip_serializing_if = "Vec::is_empty")]
167    pub column_aliases: Vec<String>,
168    #[serde(default, skip_serializing_if = "Vec::is_empty")]
169    pub column_types: Vec<String>,
170}
171
172/// The two independently bound catalog relations consumed by an operator-join table function.
173#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
174pub struct OperatorJoinRelations {
175    pub left: String,
176    pub right: String,
177}
178
179#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
180pub struct JoinUsing {
181    pub columns: Vec<String>,
182    #[serde(default, skip_serializing_if = "Option::is_none")]
183    pub alias: Option<String>,
184}
185
186impl FromClause {
187    /// Explicit LATERAL permission belongs to the range item, including a left operand inside a nested join.
188    pub fn is_explicitly_lateral(&self) -> bool {
189        matches!(
190            self,
191            Self::Values { lateral: true, .. } | Self::Subquery { lateral: true, .. }
192        )
193    }
194
195    /// All table names referenced under this clause, in declaration
196    /// order. Used by the compiler to resolve unqualified column refs.
197    pub fn collect_tables(&self, out: &mut Vec<(String, Option<String>)>) {
198        match self {
199            FromClause::RetainedRows(_) => {}
200            FromClause::Table {
201                name,
202                qualifier,
203                alias,
204                ..
205            } => out.push((
206                name.clone(),
207                Some(alias.as_ref().unwrap_or(qualifier).clone()),
208            )),
209            FromClause::Join { left, right, .. } => {
210                left.collect_tables(out);
211                right.collect_tables(out);
212            }
213            FromClause::Values { alias, .. }
214            | FromClause::Function { alias, .. }
215            | FromClause::FunctionGroup { alias, .. }
216            | FromClause::Subquery { alias, .. } => {
217                if let Some(a) = alias {
218                    out.push((a.clone(), Some(a.clone())));
219                }
220            }
221        }
222    }
223}
224
225#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
226pub enum JoinKind {
227    Inner,
228    Left,
229    Right,
230    Full,
231    Cross,
232}