Skip to main content

uqa_sql/plan/scalar/owned/
generated.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Generated operators admit their containers before moving existing scalar owners.
8
9use super::{OwnedScalarExpr, Result, ScalarExpr, ScalarMemory};
10use crate::{
11    ast::{BinaryOp, FunctionBinding, FunctionOrderSyntax},
12    plan::scalar::resources::{Control, Lowering},
13};
14use uqa_core::memory::{BudgetedVec, Produced, ProductionControl};
15
16impl OwnedScalarExpr {
17    /// Construct CASE from independent scalar owners, admitting branch storage before moving any child.
18    pub fn case(
19        base: Option<Self>,
20        branches: impl ExactSizeIterator<Item = (Self, Self)>,
21        fallback: Option<Self>,
22        control: &ProductionControl<'_>,
23    ) -> Result<Self> {
24        control.check()?;
25        let mut lowering = owned_lowering(control);
26        let base = base
27            .map(|base| lowering.boxed(|lowering| Self::attach_child(lowering, base)))
28            .transpose()?;
29        let when = lowering.map(branches, |lowering, (condition, value)| {
30            Ok((
31                Self::attach_child(lowering, condition)?,
32                Self::attach_child(lowering, value)?,
33            ))
34        })?;
35        let else_branch = fallback
36            .map(|fallback| lowering.boxed(|lowering| Self::attach_child(lowering, fallback)))
37            .transpose()?;
38        finish(
39            ScalarExpr::Case {
40                base,
41                when,
42                else_branch,
43            },
44            lowering,
45            control,
46        )
47    }
48
49    /// Replace a named row constructor's resolved type while moving its scalar fields into admitted destination slots. Binding metadata is copied through its existing owner before the old constructor is retired.
50    pub fn replace_composite_type(
51        mut self,
52        bound_type: Option<Produced<crate::ColumnType>>,
53        control: &ProductionControl<'_>,
54    ) -> Result<Self> {
55        self.assert_owner(control);
56        control.check()?;
57        let ScalarExpr::CompositeRow { items, binding, .. } = &self.expression else {
58            panic!("composite type replacement requires a named row constructor");
59        };
60        let count = items.len();
61        let mut lowering = owned_lowering(control);
62        let binding =
63            lowering.composite_binding(crate::plan::scalar::source::Source::Borrowed(binding))?;
64        let (bound_type, memory) = match bound_type {
65            Some(bound_type) => {
66                let (bound_type, memory) = bound_type.into_parts();
67                (Some(bound_type), memory)
68            }
69            None => (None, control.empty_reservation()),
70        };
71        let memory = control.combine(control.empty_reservation(), memory);
72        if let Some(owner) = &mut lowering.control {
73            owner
74                .memory
75                .absorb(memory.expect("admitted composite type"));
76        }
77        let items = lowering.map(0..count, |lowering, index| {
78            Self::attach_child(lowering, self.take_child(index))
79        })?;
80        let output = finish(
81            ScalarExpr::CompositeRow {
82                items,
83                binding,
84                bound_type,
85            },
86            lowering,
87            control,
88        )?;
89        drop(self);
90        Ok(output)
91    }
92
93    /// Construct an array expression from independently owned scalar elements.
94    pub fn array(
95        children: impl ExactSizeIterator<Item = Self>,
96        control: &ProductionControl<'_>,
97    ) -> Result<Self> {
98        control.check()?;
99        let mut lowering = owned_lowering(control);
100        let items = lowering.map(children, Self::attach_child)?;
101        finish(ScalarExpr::Array(items), lowering, control)
102    }
103
104    /// Construct a ROW from independently owned fields, admitting its vector and ownership slots before moving children.
105    pub fn row(
106        children: impl ExactSizeIterator<Item = Self>,
107        control: &ProductionControl<'_>,
108    ) -> Result<Self> {
109        control.check()?;
110        let mut lowering = owned_lowering(control);
111        let items = lowering.map(children, Self::attach_child)?;
112        finish(ScalarExpr::Row(items), lowering, control)
113    }
114
115    /// Construct a binary operator without copying either operand. The two boxes and mutable child slots are admitted before allocation.
116    pub fn binary(
117        op: BinaryOp,
118        left: Self,
119        right: Self,
120        control: &ProductionControl<'_>,
121    ) -> Result<Self> {
122        control.check()?;
123        let mut lowering = owned_lowering(control);
124        let lhs = lowering.boxed(|lowering| Self::attach_child(lowering, left))?;
125        let rhs = lowering.boxed(|lowering| Self::attach_child(lowering, right))?;
126        finish(ScalarExpr::Binary { op, lhs, rhs }, lowering, control)
127    }
128
129    /// Construct an undecorated selected call from admitted metadata and movable arguments. Overload selection and argument evaluation remain with the caller.
130    pub fn call(
131        name: Produced<String>,
132        binding: Option<Produced<FunctionBinding>>,
133        arguments: impl ExactSizeIterator<Item = Self>,
134        control: &ProductionControl<'_>,
135    ) -> Result<Self> {
136        control.check()?;
137        let mut lowering = owned_lowering(control);
138        let (name, name_memory) = name.into_parts();
139        let (binding, binding_memory) = match binding {
140            Some(binding) => {
141                let (binding, memory) = binding.into_parts();
142                (Some(binding), memory)
143            }
144            None => (None, control.empty_reservation()),
145        };
146        let metadata = control.combine(name_memory, binding_memory);
147        if let Some(owner) = &mut lowering.control {
148            owner
149                .memory
150                .absorb(metadata.expect("admitted call metadata"));
151        }
152        let args = lowering.map(arguments, Self::attach_child)?;
153        finish(
154            ScalarExpr::Func {
155                name,
156                binding,
157                args,
158                distinct: false,
159                order_by: Vec::new(),
160                order_syntax: FunctionOrderSyntax::Ordinary,
161                filter: None,
162            },
163            lowering,
164            control,
165        )
166    }
167}
168
169pub(super) fn owned_lowering<'a>(control: &ProductionControl<'a>) -> Lowering<'a> {
170    Lowering {
171        control: control.budget().map(|_| Control::from_production(*control)),
172        owned_children: control.budget().map(BudgetedVec::new),
173    }
174}
175
176pub(super) fn finish(
177    expression: ScalarExpr,
178    lowering: Lowering<'_>,
179    control: &ProductionControl<'_>,
180) -> Result<OwnedScalarExpr> {
181    let output = OwnedScalarExpr {
182        expression,
183        memory: lowering.control.map(|control| {
184            ScalarMemory::from_parts(
185                control.memory,
186                lowering
187                    .owned_children
188                    .expect("mutable generated expression"),
189            )
190        }),
191    };
192    control.check()?;
193    Ok(output)
194}