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) => ScalarExpr::QualifiedStar(self.copy_text(name)?),
74            ScalarExpr::Default => ScalarExpr::Default,
75            ScalarExpr::Column(name) => ScalarExpr::Column(self.copy_text(name)?),
76            ScalarExpr::Position(position) => ScalarExpr::Position(*position),
77            ScalarExpr::InternalColumn(column) => ScalarExpr::InternalColumn(*column),
78            ScalarExpr::QualifiedColumn { qualifier, column } => ScalarExpr::QualifiedColumn {
79                qualifier: self.copy_text(qualifier)?,
80                column: self.copy_text(column)?,
81            },
82            ScalarExpr::Literal(value) => ScalarExpr::Literal(self.value(Source::Borrowed(value))?),
83            ScalarExpr::RetainedLiteral(literal) => {
84                ScalarExpr::RetainedLiteral(self.copy_retained_literal(literal)?)
85            }
86            ScalarExpr::TypedLiteral {
87                value,
88                ty,
89                bound_type,
90                parameter_index,
91                collation_oid,
92                composite_source,
93            } => {
94                let bound_type = self.scalar_type_copy(bound_type.as_ref())?;
95                ScalarExpr::TypedLiteral {
96                    composite_source: self
97                        .composite_source(composite_source.as_ref().map(Source::Borrowed))?,
98                    value: self.value(Source::Borrowed(value))?,
99                    ty: self.copy_text(ty)?,
100                    bound_type,
101                    parameter_index: *parameter_index,
102                    collation_oid: *collation_oid,
103                }
104            }
105            ScalarExpr::Param(index) => ScalarExpr::Param(*index),
106            ScalarExpr::Func {
107                name,
108                binding,
109                args,
110                distinct,
111                order_by,
112                order_syntax,
113                filter,
114            } => ScalarExpr::Func {
115                name: self.copy_text(name)?,
116                binding: binding
117                    .as_ref()
118                    .map(|binding| self.binding(Source::Borrowed(binding)))
119                    .transpose()?,
120                args: self.map(args.iter(), Self::scalar_copy)?,
121                distinct: *distinct,
122                order_by: self.map(order_by.iter(), Self::scalar_order_copy)?,
123                order_syntax: *order_syntax,
124                filter: self.scalar_optional_copy(filter.as_deref())?,
125            },
126            ScalarExpr::Array(items) => {
127                ScalarExpr::Array(self.map(items.iter(), Self::scalar_copy)?)
128            }
129            ScalarExpr::CompositeRow {
130                items,
131                binding,
132                bound_type,
133            } => ScalarExpr::CompositeRow {
134                bound_type: self.scalar_type_copy(bound_type.as_ref())?,
135                items: self.map(items.iter(), Self::scalar_copy)?,
136                binding: self.composite_binding(Source::Borrowed(binding))?,
137            },
138            ScalarExpr::Row(items) => ScalarExpr::Row(self.map(items.iter(), Self::scalar_copy)?),
139            ScalarExpr::Binary { op, lhs, rhs } => ScalarExpr::Binary {
140                op: *op,
141                lhs: self.scalar_box_copy(lhs)?,
142                rhs: self.scalar_box_copy(rhs)?,
143            },
144            ScalarExpr::UnaryMinus(expression) => {
145                ScalarExpr::UnaryMinus(self.scalar_box_copy(expression)?)
146            }
147            ScalarExpr::Not(expression) => ScalarExpr::Not(self.scalar_box_copy(expression)?),
148            ScalarExpr::And(items) => ScalarExpr::And(self.map(items.iter(), Self::scalar_copy)?),
149            ScalarExpr::Or(items) => ScalarExpr::Or(self.map(items.iter(), Self::scalar_copy)?),
150            ScalarExpr::IsNull { expr, negated } => ScalarExpr::IsNull {
151                expr: self.scalar_box_copy(expr)?,
152                negated: *negated,
153            },
154            ScalarExpr::Between { expr, low, high } => ScalarExpr::Between {
155                expr: self.scalar_box_copy(expr)?,
156                low: self.scalar_box_copy(low)?,
157                high: self.scalar_box_copy(high)?,
158            },
159            ScalarExpr::InList {
160                expr,
161                list,
162                negated,
163            } => ScalarExpr::InList {
164                expr: self.scalar_box_copy(expr)?,
165                list: self.map(list.iter(), Self::scalar_copy)?,
166                negated: *negated,
167            },
168            ScalarExpr::WindowCall {
169                name,
170                args,
171                spec,
172                filter,
173                modifiers,
174            } => ScalarExpr::WindowCall {
175                name: self.copy_text(name)?,
176                args: self.map(args.iter(), Self::scalar_copy)?,
177                spec: ScalarWindowSpec {
178                    definition: spec.definition,
179                    partition_by: self.map(spec.partition_by.iter(), Self::scalar_copy)?,
180                    order_by: self.map(spec.order_by.iter(), Self::scalar_order_copy)?,
181                    frame: spec
182                        .frame
183                        .as_ref()
184                        .map(|frame| {
185                            Ok::<_, crate::schema::retention::CatalogRetentionError>(
186                                ScalarWindowFrame {
187                                    mode: frame.mode,
188                                    start: self.scalar_bound_copy(&frame.start)?,
189                                    end: self.scalar_bound_copy(&frame.end)?,
190                                    between: frame.between,
191                                    exclusion: frame.exclusion,
192                                },
193                            )
194                        })
195                        .transpose()?,
196                },
197                filter: self.scalar_optional_copy(filter.as_deref())?,
198                modifiers: *modifiers,
199            },
200            ScalarExpr::Case {
201                base,
202                when,
203                else_branch,
204            } => ScalarExpr::Case {
205                base: self.scalar_optional_copy(base.as_deref())?,
206                when: self.map(when.iter(), |this, (condition, value)| {
207                    Ok((this.scalar_copy(condition)?, this.scalar_copy(value)?))
208                })?,
209                else_branch: self.scalar_optional_copy(else_branch.as_deref())?,
210            },
211            ScalarExpr::Collated {
212                expr,
213                ty,
214                collation,
215            } => ScalarExpr::Collated {
216                expr: self.scalar_box_copy(expr)?,
217                ty: self
218                    .scalar_type_copy(Some(ty))?
219                    .expect("retained result type"),
220                collation: *collation,
221            },
222            ScalarExpr::Cast { implicit, expr, ty } => ScalarExpr::Cast {
223                implicit: *implicit,
224                expr: self.scalar_box_copy(expr)?,
225                ty: self.copy_text(ty)?,
226            },
227            ScalarExpr::ScalarSubquery(query) => ScalarExpr::ScalarSubquery(*query),
228            ScalarExpr::Exists { subquery, negated } => ScalarExpr::Exists {
229                subquery: *subquery,
230                negated: *negated,
231            },
232            ScalarExpr::InSubquery {
233                expr,
234                subquery,
235                negated,
236            } => ScalarExpr::InSubquery {
237                expr: self.scalar_box_copy(expr)?,
238                subquery: *subquery,
239                negated: *negated,
240            },
241        })
242    }
243
244    fn scalar_box_copy(&mut self, expression: &ScalarExpr) -> Result<Box<ScalarExpr>> {
245        self.boxed(|this| this.scalar_copy(expression))
246    }
247
248    fn scalar_optional_copy(
249        &mut self,
250        expression: Option<&ScalarExpr>,
251    ) -> Result<Option<Box<ScalarExpr>>> {
252        expression
253            .map(|expression| self.scalar_box_copy(expression))
254            .transpose()
255    }
256
257    fn scalar_order_copy(&mut self, order: &ScalarOrder) -> Result<ScalarOrder> {
258        Ok(ScalarOrder {
259            expr: self.scalar_copy(&order.expr)?,
260            descending: order.descending,
261            nulls: order.nulls,
262        })
263    }
264
265    fn scalar_bound_copy(&mut self, bound: &ScalarFrameBound) -> Result<ScalarFrameBound> {
266        Ok(match bound {
267            ScalarFrameBound::UnboundedPreceding => ScalarFrameBound::UnboundedPreceding,
268            ScalarFrameBound::UnboundedFollowing => ScalarFrameBound::UnboundedFollowing,
269            ScalarFrameBound::CurrentRow => ScalarFrameBound::CurrentRow,
270            ScalarFrameBound::Preceding(expression) => {
271                ScalarFrameBound::Preceding(self.scalar_box_copy(expression)?)
272            }
273            ScalarFrameBound::Following(expression) => {
274                ScalarFrameBound::Following(self.scalar_box_copy(expression)?)
275            }
276        })
277    }
278}
279
280#[cfg(test)]
281mod tests;