Skip to main content

uqa_sql/plan/scalar/
owned.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Mutable scalar ownership follows constructor provenance instead of estimating a rewritten tree.
8
9use super::{resources::Result, ScalarExpr};
10use crate::schema::retention::CatalogRetentionError;
11use uqa_core::{
12    memory::{BudgetedVec, MemoryReservation, Produced, ProductionControl},
13    Value,
14};
15
16mod call;
17mod children;
18mod composite;
19mod composites;
20mod construction;
21mod constructors;
22mod edit;
23mod generated;
24mod iteration;
25mod literals;
26mod metadata;
27mod query_ids;
28mod references;
29mod replacement;
30mod selection;
31pub(in crate::plan) mod windows;
32pub use iteration::OwnedScalarChildren;
33pub use replacement::ScalarNodeTransform;
34
35/// A scalar expression whose child allocations can be transferred or discarded independently. The expression is read-only outside this owner's consuming operations; replacing raw IR through a mutable dereference would separate allocations from their reservations.
36#[derive(Debug)]
37pub struct OwnedScalarExpr {
38    // Drop the complete expression before returning any of its allowances.
39    pub(super) expression: ScalarExpr,
40    pub(super) memory: Option<ScalarMemory>,
41}
42
43/// Direct allocations include this node's names, types, values, child boxes and child-vector buffers. Each child's payload has its own owner; the metadata vector also admits its actual capacity before allocation.
44#[derive(Debug)]
45pub(crate) struct ScalarMemory {
46    // The direct lease includes this metadata buffer; destroy it before releasing the lease.
47    pub(super) children: Vec<Option<Self>>,
48    pub(super) direct: MemoryReservation,
49}
50
51impl ScalarMemory {
52    pub(super) fn from_parts(
53        mut direct: MemoryReservation,
54        children: BudgetedVec<Option<Self>>,
55    ) -> Self {
56        let (children, memory) = children.into_parts();
57        direct.absorb(memory);
58        Self { children, direct }
59    }
60
61    fn into_parts(self) -> (MemoryReservation, BudgetedVec<Option<Self>>) {
62        let Self {
63            children,
64            mut direct,
65        } = self;
66        let memory = direct.split(children.capacity() * size_of::<Option<Self>>());
67        (direct, BudgetedVec::from_parts(children, memory))
68    }
69
70    fn child_buffer(&mut self) -> ScalarChildren<'_> {
71        let children = std::mem::take(&mut self.children);
72        let memory = self
73            .direct
74            .split(children.capacity() * size_of::<Option<Self>>());
75        ScalarChildren {
76            parent: self,
77            buffer: Some(BudgetedVec::from_parts(children, memory)),
78        }
79    }
80
81    pub(super) fn reserve_children(&mut self, count: usize) -> Result<()> {
82        self.child_buffer()
83            .buffer
84            .as_mut()
85            .expect("child buffer")
86            .reserve(count)?;
87        Ok(())
88    }
89
90    pub(super) fn push_child(&mut self, child: Option<Self>) -> Result<()> {
91        self.child_buffer()
92            .buffer
93            .as_mut()
94            .expect("child buffer")
95            .push(child)?;
96        Ok(())
97    }
98
99    pub(crate) fn reserved_bytes(&self) -> usize {
100        self.direct.bytes()
101            + self
102                .children
103                .iter()
104                .flatten()
105                .map(Self::reserved_bytes)
106                .sum::<usize>()
107    }
108
109    pub(crate) fn into_reservation(self) -> MemoryReservation {
110        let (mut direct, mut children) = self.into_parts();
111        while let Some(child) = children.pop() {
112            direct.absorb(child.expect("owned scalar child").into_reservation());
113        }
114        // Ownership metadata is temporary, not part of the immutable scalar allocation.
115        drop(children);
116        direct
117    }
118}
119
120/// Reattach metadata on success, rejection and unwinding before the parent can release its payloads.
121struct ScalarChildren<'a> {
122    parent: &'a mut ScalarMemory,
123    buffer: Option<BudgetedVec<Option<ScalarMemory>>>,
124}
125
126impl Drop for ScalarChildren<'_> {
127    fn drop(&mut self) {
128        let (children, memory) = self.buffer.take().expect("child buffer").into_parts();
129        self.parent.children = children;
130        self.parent.direct.absorb(memory);
131    }
132}
133
134impl OwnedScalarExpr {
135    pub(crate) fn into_rewrite_parts(self) -> (ScalarExpr, Option<ScalarMemory>) {
136        (self.expression, self.memory)
137    }
138
139    pub(crate) fn from_rewrite_parts(expression: ScalarExpr, memory: Option<ScalarMemory>) -> Self {
140        Self { expression, memory }
141    }
142
143    /// Move an ordinary scalar without claiming that its existing allocations were admitted. Controlled construction uses `ScalarExpr::copy_for_rewrite` instead.
144    pub fn uncontrolled(expression: ScalarExpr) -> Self {
145        Self {
146            expression,
147            memory: None,
148        }
149    }
150
151    /// Construct a scalar leaf from a value whose producer already owns its payload allowance.
152    pub fn literal(value: Produced<Value>, control: &ProductionControl<'_>) -> Result<Self> {
153        let (value, memory) = value.into_parts();
154        let output = Self {
155            expression: ScalarExpr::Literal(value),
156            memory: memory.map(|direct| ScalarMemory {
157                children: Vec::new(),
158                direct,
159            }),
160        };
161        output.assert_owner(control);
162        control.check()?;
163        Ok(output)
164    }
165
166    pub fn reserved_bytes(&self) -> usize {
167        self.memory.as_ref().map_or(0, ScalarMemory::reserved_bytes)
168    }
169
170    /// Rewrite a complete scalar owner. The callback may replace or select the root, but both its input and output must retain this production scope. Failure destroys all private inputs before returning.
171    pub fn rewrite<E>(
172        self,
173        control: &ProductionControl<'_>,
174        rewrite: impl FnOnce(Self) -> std::result::Result<Self, E>,
175    ) -> std::result::Result<Self, E>
176    where
177        E: From<CatalogRetentionError>,
178    {
179        self.assert_owner(control);
180        control.check().map_err(CatalogRetentionError::from)?;
181        let output = rewrite(self)?;
182        output.assert_owner(control);
183        control.check().map_err(CatalogRetentionError::from)?;
184        Ok(output)
185    }
186
187    /// Number of immediate scalar children, in copy order: call arguments, ordering keys and filter; window arguments, partition keys, ordering keys, frame bounds and filter; CASE base, condition/result pairs and ELSE.
188    pub fn child_count(&self) -> usize {
189        children::count(&self.expression)
190    }
191
192    /// Move one child out and destroy the parent and its other children. The child's former box or vector slot belongs to the discarded parent, so only the selected child's own allocations survive.
193    pub fn select_child(mut self, index: usize) -> Self {
194        let child = self.take_child(index);
195        drop(self);
196        child
197    }
198
199    fn take_child(&mut self, index: usize) -> Self {
200        Self {
201            expression: std::mem::replace(
202                children::get_mut(&mut self.expression, index).expect("scalar child index"),
203                ScalarExpr::Literal(Value::Null),
204            ),
205            memory: self
206                .memory
207                .as_mut()
208                .map(|memory| memory.children[index].take().expect("owned scalar child")),
209        }
210    }
211
212    /// Rewrite immediate children without reallocating the parent's boxes or vectors. Each callback consumes one complete owner and must return an owner from the same production scope. Error or unwind destroys the private rewrite, including unvisited children; no partly rewritten tree escapes.
213    pub fn map_children<E>(
214        mut self,
215        control: &ProductionControl<'_>,
216        mut map: impl FnMut(usize, Self) -> std::result::Result<Self, E>,
217    ) -> std::result::Result<Self, E>
218    where
219        E: From<CatalogRetentionError>,
220    {
221        self.assert_owner(control);
222        control.check().map_err(CatalogRetentionError::from)?;
223        for ordinal in 0..self.child_count() {
224            control.check().map_err(CatalogRetentionError::from)?;
225            let child = self.take_child(ordinal);
226            let replacement = map(ordinal, child)?;
227            replacement.assert_owner(control);
228            control.check().map_err(CatalogRetentionError::from)?;
229            let Self { expression, memory } = replacement;
230            *children::get_mut(&mut self.expression, ordinal).expect("scalar child index") =
231                expression;
232            if let Some(parent) = &mut self.memory {
233                parent.children[ordinal] = memory;
234            }
235        }
236        control.check().map_err(CatalogRetentionError::from)?;
237        Ok(self)
238    }
239
240    /// Rewrite one immediate child while retaining all parent containers and sibling owners.
241    pub fn map_child<E>(
242        mut self,
243        index: usize,
244        control: &ProductionControl<'_>,
245        map: impl FnOnce(Self) -> std::result::Result<Self, E>,
246    ) -> std::result::Result<Self, E>
247    where
248        E: From<CatalogRetentionError>,
249    {
250        self.assert_owner(control);
251        control.check().map_err(CatalogRetentionError::from)?;
252        let replacement = map(self.take_child(index))?;
253        replacement.assert_owner(control);
254        control.check().map_err(CatalogRetentionError::from)?;
255        let Self { expression, memory } = replacement;
256        *children::get_mut(&mut self.expression, index).expect("scalar child index") = expression;
257        if let Some(parent) = &mut self.memory {
258            parent.children[index] = memory;
259        }
260        Ok(self)
261    }
262
263    /// Freeze a completed rewrite. Surviving IR reservations become one immutable lease, while the temporary ownership metadata is destroyed and its capacity released.
264    pub fn finish(self, control: &ProductionControl<'_>) -> Result<Produced<ScalarExpr>> {
265        self.assert_owner(control);
266        control.check()?;
267        let Self { expression, memory } = self;
268        let memory = memory.map(ScalarMemory::into_reservation);
269        Ok(control.finish(expression, memory)?)
270    }
271
272    fn assert_owner(&self, control: &ProductionControl<'_>) {
273        match (&self.memory, control.budget()) {
274            (Some(memory), Some(budget)) => assert!(
275                memory.direct.budget().shares_allowance(budget),
276                "different scalar production allowance"
277            ),
278            (None, None) => {}
279            _ => panic!("controlled and ordinary scalar ownership must not be mixed"),
280        }
281    }
282}
283
284impl std::ops::Deref for OwnedScalarExpr {
285    type Target = ScalarExpr;
286
287    fn deref(&self) -> &Self::Target {
288        &self.expression
289    }
290}
291
292#[cfg(test)]
293mod tests;