Skip to main content

uqa_sql/plan/scalar/
copy.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Admission-aware copies of already analyzed scalar expressions. Query children remain references into their enclosing plan, as in an ordinary scalar clone.
8
9use super::{
10    resources::{Control, Lowering, Result},
11    source::Source,
12    ScalarExpr, ScalarFrameBound, ScalarOrder, ScalarWindowFrame, ScalarWindowSpec,
13};
14use uqa_core::memory::{Produced, ProductionControl};
15
16impl ScalarExpr {
17    /// Copy a scalar tree, admitting every destination allocation before creating it and retaining the complete reservation. Subquery identities still refer to the enclosing plan's query arena.
18    pub fn clone_with_control(&self, control: &ProductionControl<'_>) -> Result<Produced<Self>> {
19        control.check()?;
20        if control.budget().is_none() {
21            return Ok(control.finish(self.clone(), None)?);
22        }
23        let mut copying = Lowering {
24            control: Some(Control::from_production(*control)),
25        };
26        let expression = copying.scalar_copy(self)?;
27        Ok(copying.finish(expression)?.into())
28    }
29}
30
31impl Lowering<'_> {
32    pub(super) fn copy_retained_literal(
33        &mut self,
34        literal: &crate::ir::RetainedScalarLiteral,
35    ) -> Result<Box<crate::ir::RetainedScalarLiteral>> {
36        self.boxed(|this| {
37            Ok(crate::ir::RetainedScalarLiteral {
38                value: literal.value.clone(),
39                declaration: literal
40                    .declaration
41                    .as_deref()
42                    .map(|name| this.copy_text(name))
43                    .transpose()?,
44                ty: this
45                    .scalar_type_copy(Some(&literal.ty))?
46                    .expect("selected retained literal type"),
47                collation_oid: literal.collation_oid,
48            })
49        })
50    }
51
52    pub(super) fn scalar_type_copy(
53        &mut self,
54        ty: Option<&crate::ast::ColumnType>,
55    ) -> Result<Option<crate::ast::ColumnType>> {
56        ty.map(|ty| {
57            let control = self.control.as_mut().expect("controlled scalar copy");
58            let (ty, memory) = ty.clone_with_control(&control.production)?.into_parts();
59            control.memory.absorb(memory.expect("controlled type copy"));
60            Ok(ty)
61        })
62        .transpose()
63    }
64
65    #[expect(
66        clippy::too_many_lines,
67        reason = "exhaustive scalar copying shares the lowerer's destination admission"
68    )]
69    fn scalar_copy(&mut self, expression: &ScalarExpr) -> Result<ScalarExpr> {
70        self.check()?;
71        Ok(match expression {
72            ScalarExpr::Star => ScalarExpr::Star,
73            ScalarExpr::QualifiedStar(name) => {
74                ScalarExpr::QualifiedStar(self.copy_reference_name(name)?)
75            }
76            ScalarExpr::Default => ScalarExpr::Default,
77            ScalarExpr::Column(name) => ScalarExpr::Column(self.copy_reference_name(name)?),
78            ScalarExpr::Position(position) => ScalarExpr::Position(*position),
79            ScalarExpr::InternalColumn(column) => ScalarExpr::InternalColumn(*column),
80            ScalarExpr::QualifiedColumn { qualifier, column } => ScalarExpr::QualifiedColumn {
81                qualifier: self.copy_text(qualifier)?,
82                column: self.copy_reference_name(column)?,
83            },
84            ScalarExpr::Literal(value) => ScalarExpr::Literal(self.value(Source::Borrowed(value))?),
85            ScalarExpr::RetainedLiteral(literal) => {
86                ScalarExpr::RetainedLiteral(self.copy_retained_literal(literal)?)
87            }
88            ScalarExpr::TypedLiteral {
89                value,
90                ty,
91                bound_type,
92                parameter_index,
93                collation_oid,
94                composite_source,
95            } => {
96                let bound_type = self.scalar_type_copy(bound_type.as_ref())?;
97                ScalarExpr::TypedLiteral {
98                    composite_source: self
99                        .composite_source(composite_source.as_ref().map(Source::Borrowed))?,
100                    value: self.value(Source::Borrowed(value))?,
101                    ty: self.copy_text(ty)?,
102                    bound_type,
103                    parameter_index: *parameter_index,
104                    collation_oid: *collation_oid,
105                }
106            }
107            ScalarExpr::Param(index) => ScalarExpr::Param(*index),
108            ScalarExpr::Func {
109                name,
110                binding,
111                args,
112                distinct,
113                order_by,
114                order_syntax,
115                filter,
116            } => ScalarExpr::Func {
117                name: self.copy_text(name)?,
118                binding: binding
119                    .as_ref()
120                    .map(|binding| self.binding(Source::Borrowed(binding)))
121                    .transpose()?,
122                args: self.map(args.iter(), Self::scalar_copy)?,
123                distinct: *distinct,
124                order_by: self.map(order_by.iter(), Self::scalar_order_copy)?,
125                order_syntax: *order_syntax,
126                filter: self.scalar_optional_copy(filter.as_deref())?,
127            },
128            ScalarExpr::Array(items) => {
129                ScalarExpr::Array(self.map(items.iter(), Self::scalar_copy)?)
130            }
131            ScalarExpr::CompositeRow {
132                items,
133                binding,
134                bound_type,
135            } => ScalarExpr::CompositeRow {
136                bound_type: self.scalar_type_copy(bound_type.as_ref())?,
137                items: self.map(items.iter(), Self::scalar_copy)?,
138                binding: self.composite_binding(Source::Borrowed(binding))?,
139            },
140            ScalarExpr::Row(items) => ScalarExpr::Row(self.map(items.iter(), Self::scalar_copy)?),
141            ScalarExpr::Binary { op, lhs, rhs } => ScalarExpr::Binary {
142                op: *op,
143                lhs: self.scalar_box_copy(lhs)?,
144                rhs: self.scalar_box_copy(rhs)?,
145            },
146            ScalarExpr::UnaryMinus(expression) => {
147                ScalarExpr::UnaryMinus(self.scalar_box_copy(expression)?)
148            }
149            ScalarExpr::Not(expression) => ScalarExpr::Not(self.scalar_box_copy(expression)?),
150            ScalarExpr::And(items) => ScalarExpr::And(self.map(items.iter(), Self::scalar_copy)?),
151            ScalarExpr::Or(items) => ScalarExpr::Or(self.map(items.iter(), Self::scalar_copy)?),
152            ScalarExpr::IsNull { expr, negated } => ScalarExpr::IsNull {
153                expr: self.scalar_box_copy(expr)?,
154                negated: *negated,
155            },
156            ScalarExpr::Between { expr, low, high } => ScalarExpr::Between {
157                expr: self.scalar_box_copy(expr)?,
158                low: self.scalar_box_copy(low)?,
159                high: self.scalar_box_copy(high)?,
160            },
161            ScalarExpr::InList {
162                expr,
163                list,
164                negated,
165            } => ScalarExpr::InList {
166                expr: self.scalar_box_copy(expr)?,
167                list: self.map(list.iter(), Self::scalar_copy)?,
168                negated: *negated,
169            },
170            ScalarExpr::WindowCall {
171                name,
172                args,
173                spec,
174                filter,
175                modifiers,
176            } => ScalarExpr::WindowCall {
177                name: self.copy_text(name)?,
178                args: self.map(args.iter(), Self::scalar_copy)?,
179                spec: ScalarWindowSpec {
180                    definition: spec.definition,
181                    partition_by: self.map(spec.partition_by.iter(), Self::scalar_copy)?,
182                    order_by: self.map(spec.order_by.iter(), Self::scalar_order_copy)?,
183                    frame: spec
184                        .frame
185                        .as_ref()
186                        .map(|frame| {
187                            Ok::<_, crate::schema::retention::CatalogRetentionError>(
188                                ScalarWindowFrame {
189                                    mode: frame.mode,
190                                    start: self.scalar_bound_copy(&frame.start)?,
191                                    end: self.scalar_bound_copy(&frame.end)?,
192                                    between: frame.between,
193                                    exclusion: frame.exclusion,
194                                },
195                            )
196                        })
197                        .transpose()?,
198                },
199                filter: self.scalar_optional_copy(filter.as_deref())?,
200                modifiers: *modifiers,
201            },
202            ScalarExpr::Case {
203                base,
204                when,
205                else_branch,
206            } => ScalarExpr::Case {
207                base: self.scalar_optional_copy(base.as_deref())?,
208                when: self.map(when.iter(), |this, (condition, value)| {
209                    Ok((this.scalar_copy(condition)?, this.scalar_copy(value)?))
210                })?,
211                else_branch: self.scalar_optional_copy(else_branch.as_deref())?,
212            },
213            ScalarExpr::Collated {
214                expr,
215                ty,
216                collation,
217            } => ScalarExpr::Collated {
218                expr: self.scalar_box_copy(expr)?,
219                ty: self
220                    .scalar_type_copy(Some(ty))?
221                    .expect("retained result type"),
222                collation: *collation,
223            },
224            ScalarExpr::Cast { implicit, expr, ty } => ScalarExpr::Cast {
225                implicit: *implicit,
226                expr: self.scalar_box_copy(expr)?,
227                ty: self.copy_text(ty)?,
228            },
229            ScalarExpr::ScalarSubquery(query) => ScalarExpr::ScalarSubquery(*query),
230            ScalarExpr::Exists { subquery, negated } => ScalarExpr::Exists {
231                subquery: *subquery,
232                negated: *negated,
233            },
234            ScalarExpr::InSubquery {
235                expr,
236                subquery,
237                negated,
238            } => ScalarExpr::InSubquery {
239                expr: self.scalar_box_copy(expr)?,
240                subquery: *subquery,
241                negated: *negated,
242            },
243        })
244    }
245
246    fn scalar_box_copy(&mut self, expression: &ScalarExpr) -> Result<Box<ScalarExpr>> {
247        self.boxed(|this| this.scalar_copy(expression))
248    }
249
250    fn scalar_optional_copy(
251        &mut self,
252        expression: Option<&ScalarExpr>,
253    ) -> Result<Option<Box<ScalarExpr>>> {
254        expression
255            .map(|expression| self.scalar_box_copy(expression))
256            .transpose()
257    }
258
259    fn scalar_order_copy(&mut self, order: &ScalarOrder) -> Result<ScalarOrder> {
260        Ok(ScalarOrder {
261            expr: self.scalar_copy(&order.expr)?,
262            descending: order.descending,
263            nulls: order.nulls,
264        })
265    }
266
267    fn scalar_bound_copy(&mut self, bound: &ScalarFrameBound) -> Result<ScalarFrameBound> {
268        Ok(match bound {
269            ScalarFrameBound::UnboundedPreceding => ScalarFrameBound::UnboundedPreceding,
270            ScalarFrameBound::UnboundedFollowing => ScalarFrameBound::UnboundedFollowing,
271            ScalarFrameBound::CurrentRow => ScalarFrameBound::CurrentRow,
272            ScalarFrameBound::Preceding(expression) => {
273                ScalarFrameBound::Preceding(self.scalar_box_copy(expression)?)
274            }
275            ScalarFrameBound::Following(expression) => {
276                ScalarFrameBound::Following(self.scalar_box_copy(expression)?)
277            }
278        })
279    }
280}
281
282#[cfg(test)]
283mod tests;