Skip to main content

uqa_sql/plan/
scalar.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! SQL AST to executable scalar IR lowering and aggregate classification.
8
9use super::{
10    AggregateClassifier, Expr, FrameBound, OrderBy, QueryPlan, ScalarExpr, ScalarFrameBound,
11    ScalarOrder, ScalarWindowFrame, ScalarWindowSpec, WindowSpec,
12};
13use crate::schema::retention::CatalogRetentionError;
14use resources::{Control, Lowering, Result};
15use source::{Node, Source};
16use uqa_core::{
17    memory::{Budgeted, MemoryBudget},
18    CancellationToken,
19};
20
21mod binding;
22mod copy;
23mod resources;
24mod source;
25mod window;
26
27impl super::ExpressionPlan {
28    /// Lower a borrowed, validated column expression directly into admitted scalar IR. Destination strings, value payloads, bindings, vector capacities and boxes acquire the supplied allowance before allocation, and the result retains those leases. Both the retained definition's original cancellation and the invoking reader's cancellation remain active during lowering. This controls AST-to-IR production only; subsequent type binding and evaluation require their own resource contracts. Query children violate the validated column-expression invariant.
29    pub fn lower_column_budgeted(
30        expression: &Expr,
31        budget: &MemoryBudget,
32        original: &CancellationToken,
33        invoking: &CancellationToken,
34    ) -> Result<Budgeted<ScalarExpr>> {
35        let mut lowering = Lowering {
36            control: Some(Control::new(budget, original, invoking)),
37        };
38        let scalar = lowering.expression(
39            Source::Borrowed(expression),
40            &super::NoRegisteredAggregates,
41            &mut Vec::new(),
42        )?;
43        lowering.finish(scalar)
44    }
45}
46
47pub(super) fn lower_scalar_expression(
48    expression: Expr,
49    aggregates: &dyn AggregateClassifier,
50    subqueries: &mut Vec<QueryPlan>,
51) -> ScalarExpr {
52    Lowering { control: None }
53        .expression(Source::Owned(expression), aggregates, subqueries)
54        .expect("owned lowering has no admission failure")
55}
56
57pub(super) fn lower_window_spec(
58    specification: WindowSpec,
59    aggregates: &dyn AggregateClassifier,
60    subqueries: &mut Vec<QueryPlan>,
61) -> ScalarWindowSpec {
62    Lowering { control: None }
63        .window(Source::Owned(specification), aggregates, subqueries)
64        .expect("owned lowering has no admission failure")
65}
66
67impl Lowering<'_> {
68    #[expect(
69        clippy::too_many_lines,
70        reason = "plan lowering preserves exhaustive variants and structural identities"
71    )]
72    fn expression(
73        &mut self,
74        expression: Source<'_, Expr>,
75        aggregates: &dyn AggregateClassifier,
76        subqueries: &mut Vec<QueryPlan>,
77    ) -> Result<ScalarExpr> {
78        self.check()?;
79        Ok(match expression.node() {
80            Node::Star => ScalarExpr::Star,
81            Node::QualifiedStar(name) => ScalarExpr::QualifiedStar(self.text(name)?),
82            Node::Default => ScalarExpr::Default,
83            Node::Column(name) => ScalarExpr::Column(self.text(name)?),
84            Node::QualifiedColumn { qualifier, column } => ScalarExpr::QualifiedColumn {
85                qualifier: self.text(qualifier)?,
86                column: self.text(column)?,
87            },
88            Node::InternalColumn(column) => ScalarExpr::InternalColumn(column),
89            Node::Literal(value) => ScalarExpr::Literal(self.value(value)?),
90            Node::RetainedLiteral(value) => match value {
91                Source::Owned(value) => ScalarExpr::RetainedLiteral(Box::new(value.0)),
92                Source::Borrowed(value) => {
93                    ScalarExpr::RetainedLiteral(self.copy_retained_literal(&value.0)?)
94                }
95            },
96            Node::TypedLiteral {
97                value,
98                ty,
99                collation_oid,
100                composite_source,
101            } => ScalarExpr::TypedLiteral {
102                collation_oid,
103                composite_source: self.composite_source(composite_source)?,
104                value: self.value(value)?,
105                ty: self.text(ty)?,
106                bound_type: None,
107                parameter_index: None,
108            },
109            Node::Param(index) => ScalarExpr::Param(index),
110            Node::Func {
111                name,
112                binding,
113                args,
114                distinct,
115                order_by,
116                order_syntax,
117                filter,
118            } => ScalarExpr::Func {
119                name: self.text(name)?,
120                binding: binding.map(|binding| self.binding(binding)).transpose()?,
121                args: self.map(args, |this, argument| {
122                    this.expression(argument, aggregates, subqueries)
123                })?,
124                distinct,
125                order_by: self.map(order_by, |this, order| {
126                    this.order(order, aggregates, subqueries)
127                })?,
128                order_syntax,
129                filter: filter
130                    .map(|filter| self.child(filter, aggregates, subqueries))
131                    .transpose()?,
132            },
133            Node::Array(items) => ScalarExpr::Array(self.map(items, |this, item| {
134                this.expression(item, aggregates, subqueries)
135            })?),
136            Node::CompositeRow { items, binding } => ScalarExpr::CompositeRow {
137                items: self.map(items, |this, item| {
138                    this.expression(item, aggregates, subqueries)
139                })?,
140                binding: self.composite_binding(binding)?,
141                bound_type: None,
142            },
143            Node::Row(items) => ScalarExpr::Row(self.map(items, |this, item| {
144                this.expression(item, aggregates, subqueries)
145            })?),
146            Node::Binary { op, lhs, rhs } => ScalarExpr::Binary {
147                op,
148                lhs: self.child(lhs, aggregates, subqueries)?,
149                rhs: self.child(rhs, aggregates, subqueries)?,
150            },
151            Node::UnaryMinus(expression) => {
152                ScalarExpr::UnaryMinus(self.child(expression, aggregates, subqueries)?)
153            }
154            Node::Not(expression) => {
155                ScalarExpr::Not(self.child(expression, aggregates, subqueries)?)
156            }
157            Node::And(items) => ScalarExpr::And(self.map(items, |this, item| {
158                this.expression(item, aggregates, subqueries)
159            })?),
160            Node::Or(items) => ScalarExpr::Or(self.map(items, |this, item| {
161                this.expression(item, aggregates, subqueries)
162            })?),
163            Node::IsNull { expr, negated } => ScalarExpr::IsNull {
164                expr: self.child(expr, aggregates, subqueries)?,
165                negated,
166            },
167            Node::Between { expr, low, high } => ScalarExpr::Between {
168                expr: self.child(expr, aggregates, subqueries)?,
169                low: self.child(low, aggregates, subqueries)?,
170                high: self.child(high, aggregates, subqueries)?,
171            },
172            Node::InList {
173                expr,
174                list,
175                negated,
176            } => ScalarExpr::InList {
177                expr: self.child(expr, aggregates, subqueries)?,
178                list: self.map(list, |this, item| {
179                    this.expression(item, aggregates, subqueries)
180                })?,
181                negated,
182            },
183            Node::WindowCall {
184                name,
185                args,
186                spec,
187                filter,
188                modifiers,
189            } => ScalarExpr::WindowCall {
190                modifiers,
191                name: self.text(name)?,
192                args: self.map(args, |this, argument| {
193                    this.expression(argument, aggregates, subqueries)
194                })?,
195                spec: self.window(spec, aggregates, subqueries)?,
196                filter: filter
197                    .map(|filter| self.child(filter, aggregates, subqueries))
198                    .transpose()?,
199            },
200            Node::Case {
201                base,
202                when,
203                else_branch,
204            } => ScalarExpr::Case {
205                base: base
206                    .map(|base| self.child(base, aggregates, subqueries))
207                    .transpose()?,
208                when: self.map(when, |this, pair| {
209                    let (condition, result) = pair.pair();
210                    Ok((
211                        this.expression(condition, aggregates, subqueries)?,
212                        this.expression(result, aggregates, subqueries)?,
213                    ))
214                })?,
215                else_branch: else_branch
216                    .map(|branch| self.child(branch, aggregates, subqueries))
217                    .transpose()?,
218            },
219            Node::Cast { expr, ty, implicit } => ScalarExpr::Cast {
220                implicit,
221                expr: self.child(expr, aggregates, subqueries)?,
222                ty: self.text(ty)?,
223            },
224            Node::ScalarSubquery(query) => {
225                ScalarExpr::ScalarSubquery(self.query(query, aggregates, subqueries)?)
226            }
227            Node::Exists { body, negated } => ScalarExpr::Exists {
228                subquery: self.query(body, aggregates, subqueries)?,
229                negated,
230            },
231            Node::InSubquery {
232                expr,
233                body,
234                negated,
235            } => {
236                let expr = self.child(expr, aggregates, subqueries)?;
237                ScalarExpr::InSubquery {
238                    expr,
239                    subquery: self.query(body, aggregates, subqueries)?,
240                    negated,
241                }
242            }
243        })
244    }
245
246    fn child(
247        &mut self,
248        expression: Source<'_, Box<Expr>>,
249        aggregates: &dyn AggregateClassifier,
250        subqueries: &mut Vec<QueryPlan>,
251    ) -> Result<Box<ScalarExpr>> {
252        self.boxed(|this| this.expression(expression.unbox(), aggregates, subqueries))
253    }
254
255    fn query(
256        &self,
257        query: Source<'_, Box<crate::ast::SelectStmt>>,
258        aggregates: &dyn AggregateClassifier,
259        subqueries: &mut Vec<QueryPlan>,
260    ) -> Result<usize> {
261        self.check()?;
262        let Source::Owned(query) = query else {
263            return Err(CatalogRetentionError::UnexpectedSubquery);
264        };
265        let id = subqueries.len();
266        subqueries.push(QueryPlan::lower_with(*query, aggregates));
267        Ok(id)
268    }
269}
270
271pub(crate) fn is_builtin_aggregate(name: &str) -> bool {
272    crate::ast::is_builtin_aggregate_function(name)
273}
274
275#[cfg(test)]
276mod tests;