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, Produced, ProductionControl},
18    CancellationToken,
19};
20
21mod binding;
22mod copy;
23mod lowering;
24pub(in crate::plan) use lowering::lower_scalar_with_arena;
25mod owned;
26pub(in crate::plan) use owned::windows::OwnedWindowSpec;
27pub(crate) use owned::ScalarMemory;
28pub use owned::{OwnedScalarChildren, OwnedScalarExpr, ScalarNodeTransform};
29mod resources;
30mod source;
31mod window;
32
33/// A scalar's query slots belong to its enclosing query owner. Scalar-only consumers keep the rejection boundary; complete plan lowering supplies an admitted arena.
34pub(in crate::plan) trait QueryLowering {
35    fn parameter(&self, _expression: &Expr) -> Option<usize> {
36        None
37    }
38
39    fn append_owned(
40        &mut self,
41        query: crate::ast::SelectStmt,
42        aggregates: &dyn AggregateClassifier,
43    ) -> Result<usize>;
44
45    fn append_borrowed(
46        &mut self,
47        _query: &crate::ast::SelectStmt,
48        _aggregates: &dyn AggregateClassifier,
49    ) -> Result<usize> {
50        Err(CatalogRetentionError::UnexpectedSubquery)
51    }
52}
53
54impl QueryLowering for Vec<QueryPlan> {
55    fn append_owned(
56        &mut self,
57        query: crate::ast::SelectStmt,
58        aggregates: &dyn AggregateClassifier,
59    ) -> Result<usize> {
60        let index = self.len();
61        self.push(QueryPlan::lower_with(query, aggregates));
62        Ok(index)
63    }
64}
65
66impl super::ExpressionPlan {
67    /// Lower a borrowed scalar-only expression with destination admission. A query child is reported before publication so callers can decline scalar-only transformations without constructing an unowned query arena.
68    pub fn lower_scalar_with_control(
69        expression: &Expr,
70        control: &ProductionControl<'_>,
71    ) -> Result<Produced<ScalarExpr>> {
72        control.check()?;
73        let mut lowering = Lowering {
74            control: control.budget().map(|_| Control::from_production(*control)),
75            owned_children: None,
76        };
77        let scalar = lowering.expression(
78            Source::Borrowed(expression),
79            &super::NoRegisteredAggregates,
80            &mut Vec::new(),
81        )?;
82        let memory = lowering.control.map(|control| control.memory);
83        Ok(control.finish(scalar, memory)?)
84    }
85
86    /// 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.
87    pub fn lower_column_budgeted(
88        expression: &Expr,
89        budget: &MemoryBudget,
90        original: &CancellationToken,
91        invoking: &CancellationToken,
92    ) -> Result<Budgeted<ScalarExpr>> {
93        let mut lowering = Lowering {
94            control: Some(Control::new(budget, original, invoking)),
95            owned_children: None,
96        };
97        let scalar = lowering.expression(
98            Source::Borrowed(expression),
99            &super::NoRegisteredAggregates,
100            &mut Vec::new(),
101        )?;
102        lowering.finish(scalar)
103    }
104}
105
106pub(super) fn lower_scalar_expression(
107    expression: Expr,
108    aggregates: &dyn AggregateClassifier,
109    subqueries: &mut Vec<QueryPlan>,
110) -> ScalarExpr {
111    Lowering {
112        control: None,
113        owned_children: None,
114    }
115    .expression(Source::Owned(expression), aggregates, subqueries)
116    .expect("owned lowering has no admission failure")
117}
118
119pub(super) fn lower_window_spec(
120    specification: WindowSpec,
121    aggregates: &dyn AggregateClassifier,
122    subqueries: &mut Vec<QueryPlan>,
123) -> ScalarWindowSpec {
124    Lowering {
125        control: None,
126        owned_children: None,
127    }
128    .window(Source::Owned(specification), aggregates, subqueries)
129    .expect("owned lowering has no admission failure")
130}
131
132impl Lowering<'_> {
133    #[expect(
134        clippy::too_many_lines,
135        reason = "plan lowering preserves exhaustive variants and structural identities"
136    )]
137    fn expression_node(
138        &mut self,
139        expression: Source<'_, Expr>,
140        aggregates: &dyn AggregateClassifier,
141        subqueries: &mut dyn QueryLowering,
142    ) -> Result<ScalarExpr> {
143        self.check()?;
144        if let Source::Borrowed(expression) = &expression {
145            if let Some(number) = subqueries.parameter(expression) {
146                return Ok(ScalarExpr::Param(number));
147            }
148        }
149        Ok(match expression.node() {
150            Node::Star => ScalarExpr::Star,
151            Node::QualifiedStar(name) => ScalarExpr::QualifiedStar(self.reference_name(name)?),
152            Node::Default => ScalarExpr::Default,
153            Node::Column(name) => ScalarExpr::Column(self.reference_name(name)?),
154            Node::QualifiedColumn { qualifier, column } => ScalarExpr::QualifiedColumn {
155                qualifier: self.text(qualifier)?,
156                column: self.reference_name(column)?,
157            },
158            Node::InternalColumn(column) => ScalarExpr::InternalColumn(column),
159            Node::Literal(value) => ScalarExpr::Literal(self.value(value)?),
160            Node::RetainedLiteral(value) => match value {
161                Source::Owned(value) => ScalarExpr::RetainedLiteral(value.0),
162                Source::Borrowed(value) => ScalarExpr::RetainedLiteral(value.0.clone()),
163            },
164            Node::TypedLiteral {
165                value,
166                ty,
167                collation_oid,
168                composite_source,
169            } => ScalarExpr::TypedLiteral {
170                collation_oid,
171                composite_source: self.composite_source(composite_source)?,
172                value: self.value(value)?,
173                ty: self.text(ty)?,
174                bound_type: None,
175                parameter_index: None,
176            },
177            Node::Param(index) => ScalarExpr::Param(index),
178            Node::Func {
179                name,
180                binding,
181                args,
182                distinct,
183                order_by,
184                order_syntax,
185                filter,
186            } => ScalarExpr::Func {
187                name: self.text(name)?,
188                binding: binding.map(|binding| self.binding(binding)).transpose()?,
189                args: self.map(args, |this, argument| {
190                    this.expression(argument, aggregates, subqueries)
191                })?,
192                distinct,
193                order_by: self.map(order_by, |this, order| {
194                    this.order(order, aggregates, subqueries)
195                })?,
196                order_syntax,
197                filter: filter
198                    .map(|filter| self.child(filter, aggregates, subqueries))
199                    .transpose()?,
200            },
201            Node::Array(items) => ScalarExpr::Array(self.map(items, |this, item| {
202                this.expression(item, aggregates, subqueries)
203            })?),
204            Node::CompositeRow { items, binding } => ScalarExpr::CompositeRow {
205                items: self.map(items, |this, item| {
206                    this.expression(item, aggregates, subqueries)
207                })?,
208                binding: self.composite_binding(binding)?,
209                bound_type: None,
210            },
211            Node::Row(items) => ScalarExpr::Row(self.map(items, |this, item| {
212                this.expression(item, aggregates, subqueries)
213            })?),
214            Node::Binary { op, lhs, rhs } => ScalarExpr::Binary {
215                op,
216                lhs: self.child(lhs, aggregates, subqueries)?,
217                rhs: self.child(rhs, aggregates, subqueries)?,
218            },
219            Node::UnaryMinus(expression) => {
220                ScalarExpr::UnaryMinus(self.child(expression, aggregates, subqueries)?)
221            }
222            Node::Not(expression) => {
223                ScalarExpr::Not(self.child(expression, aggregates, subqueries)?)
224            }
225            Node::And(items) => ScalarExpr::And(self.map(items, |this, item| {
226                this.expression(item, aggregates, subqueries)
227            })?),
228            Node::Or(items) => ScalarExpr::Or(self.map(items, |this, item| {
229                this.expression(item, aggregates, subqueries)
230            })?),
231            Node::IsNull { expr, negated } => ScalarExpr::IsNull {
232                expr: self.child(expr, aggregates, subqueries)?,
233                negated,
234            },
235            Node::Between { expr, low, high } => ScalarExpr::Between {
236                expr: self.child(expr, aggregates, subqueries)?,
237                low: self.child(low, aggregates, subqueries)?,
238                high: self.child(high, aggregates, subqueries)?,
239            },
240            Node::InList {
241                expr,
242                list,
243                negated,
244            } => ScalarExpr::InList {
245                expr: self.child(expr, aggregates, subqueries)?,
246                list: self.map(list, |this, item| {
247                    this.expression(item, aggregates, subqueries)
248                })?,
249                negated,
250            },
251            Node::WindowCall {
252                name,
253                args,
254                spec,
255                filter,
256                modifiers,
257            } => ScalarExpr::WindowCall {
258                modifiers,
259                name: self.text(name)?,
260                args: self.map(args, |this, argument| {
261                    this.expression(argument, aggregates, subqueries)
262                })?,
263                spec: self.window(spec, aggregates, subqueries)?,
264                filter: filter
265                    .map(|filter| self.child(filter, aggregates, subqueries))
266                    .transpose()?,
267            },
268            Node::Case {
269                base,
270                when,
271                else_branch,
272            } => ScalarExpr::Case {
273                base: base
274                    .map(|base| self.child(base, aggregates, subqueries))
275                    .transpose()?,
276                when: self.map(when, |this, pair| {
277                    let (condition, result) = pair.pair();
278                    Ok((
279                        this.expression(condition, aggregates, subqueries)?,
280                        this.expression(result, aggregates, subqueries)?,
281                    ))
282                })?,
283                else_branch: else_branch
284                    .map(|branch| self.child(branch, aggregates, subqueries))
285                    .transpose()?,
286            },
287            Node::Cast { expr, ty, implicit } => ScalarExpr::Cast {
288                implicit,
289                expr: self.child(expr, aggregates, subqueries)?,
290                ty: self.text(ty)?,
291            },
292            Node::ScalarSubquery(query) => {
293                ScalarExpr::ScalarSubquery(self.query(query, aggregates, subqueries)?)
294            }
295            Node::Exists { body, negated } => ScalarExpr::Exists {
296                subquery: self.query(body, aggregates, subqueries)?,
297                negated,
298            },
299            Node::InSubquery {
300                expr,
301                body,
302                negated,
303            } => {
304                let expr = self.child(expr, aggregates, subqueries)?;
305                ScalarExpr::InSubquery {
306                    expr,
307                    subquery: self.query(body, aggregates, subqueries)?,
308                    negated,
309                }
310            }
311        })
312    }
313
314    fn child(
315        &mut self,
316        expression: Source<'_, Box<Expr>>,
317        aggregates: &dyn AggregateClassifier,
318        subqueries: &mut dyn QueryLowering,
319    ) -> Result<Box<ScalarExpr>> {
320        self.boxed(|this| this.expression(expression.unbox(), aggregates, subqueries))
321    }
322
323    fn query(
324        &self,
325        query: Source<'_, Box<crate::ast::SelectStmt>>,
326        aggregates: &dyn AggregateClassifier,
327        subqueries: &mut dyn QueryLowering,
328    ) -> Result<usize> {
329        self.check()?;
330        match query {
331            Source::Owned(query) => subqueries.append_owned(*query, aggregates),
332            Source::Borrowed(query) => subqueries.append_borrowed(query, aggregates),
333        }
334    }
335}
336
337#[cfg(test)]
338mod tests;