Skip to main content

uqa_sql/plan/
copy.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Destination admission for complete SQL syntax and executable query/mutation copies.
8
9use super::mutable::memory::{RewriteField, RewriteMemory};
10use super::{CommandPlan, ExpressionPlan, PlanRef, QueryPlan, UnifiedPlan};
11use crate::{catalog::roles::RoleReference, SQLError, ScalarExpr};
12use uqa_core::memory::{BudgetedVec, MemoryReservation, OwnedSet, Produced, ProductionControl};
13
14mod attached_queries;
15mod command;
16mod generated_sources;
17mod lowering;
18mod owned_mutation;
19mod production;
20mod query;
21mod retained;
22mod source;
23mod specialization;
24mod syntax;
25pub(crate) use production::{CollectSyntax, SyntaxProduction, SyntaxVector};
26pub(crate) use specialization::copy_specialized_function;
27#[cfg(test)]
28mod tests;
29
30type Result<T> = std::result::Result<T, SQLError>;
31
32/// Copy retained SQL syntax through its owning constructors, admitting each destination before allocation.
33pub(crate) fn copy_syntax_with_control<T: syntax::SyntaxCopy + Clone>(
34    value: &T,
35    control: &ProductionControl<'_>,
36) -> Result<Produced<T>> {
37    control.check()?;
38    let Some(mut copying) = Copying::new(*control) else {
39        return Ok(control.finish(value.clone(), None)?);
40    };
41    let value = value.copy_syntax(&mut copying)?;
42    copying.finish(value)
43}
44
45impl super::CtePlan {
46    /// Copy only a declaration's scheduling metadata and transfer an independently admitted query body. The replaced body is never copied; the selected root retains its original allocation and lease.
47    pub fn copy_with_query(
48        &self,
49        query: super::OwnedQueryPlan,
50        control: &ProductionControl<'_>,
51    ) -> Result<Produced<Self>> {
52        let query = query.into_produced_box(control)?;
53        let Some(mut copying) = Copying::new(*control) else {
54            return Ok(control.finish(
55                Self {
56                    name: self.name.clone(),
57                    columns: self.columns.clone(),
58                    recursive: self.recursive,
59                    materialization: self.materialization,
60                    search: self.search.clone(),
61                    cycle: self.cycle.clone(),
62                    body: super::CtePlanBody::Query(
63                        query.into_uncontrolled().expect("ordinary CTE query"),
64                    ),
65                },
66                None,
67            )?);
68        };
69        let plan = copying.cte_using(self, |copying| {
70            Ok(super::CtePlanBody::Query(copying.take(query)))
71        })?;
72        copying.finish(plan)
73    }
74
75    /// Copy a complete CTE declaration under the selected allowance and cancellation scopes.
76    pub fn clone_with_control(&self, control: &ProductionControl<'_>) -> Result<Produced<Self>> {
77        control.check()?;
78        let Some(mut copying) = Copying::new(*control) else {
79            return Ok(control.finish(self.clone(), None)?);
80        };
81        let plan = copying.cte(self)?;
82        copying.finish(plan)
83    }
84}
85
86impl super::QueryBlockPlan {
87    /// Retain an immutable physical recheck input under the invoking request's allowance.
88    pub fn clone_with_control(&self, control: &ProductionControl<'_>) -> Result<Produced<Self>> {
89        control.check()?;
90        let Some(mut copying) = Copying::new(*control) else {
91            return Ok(control.finish(self.clone(), None)?);
92        };
93        let block = copying.block(self)?;
94        copying.finish(block)
95    }
96}
97
98impl super::InsertPlan {
99    /// Capture a retained INSERT executable before scheduling its source, admitting each private destination without evaluating expressions.
100    pub fn clone_with_control(&self, control: &ProductionControl<'_>) -> Result<Produced<Self>> {
101        copy_syntax_with_control(self, control)
102    }
103}
104
105impl QueryPlan {
106    /// Copy a relational executable and its query/mutation CTEs, admitting destination capacities and owned payloads before allocation. Immutable analysis descriptors and retained row/literal identities remain shared.
107    pub fn clone_with_control(&self, control: &ProductionControl<'_>) -> Result<Produced<Self>> {
108        control.check()?;
109        let Some(mut copying) = Copying::new(*control) else {
110            return Ok(control.finish(self.clone(), None)?);
111        };
112        let plan = copying.query(self)?;
113        copying.finish(plan)
114    }
115}
116
117impl ExpressionPlan {
118    /// Copy a scalar expression and its owned query arena under the same production allowance.
119    pub fn clone_with_control(&self, control: &ProductionControl<'_>) -> Result<Produced<Self>> {
120        control.check()?;
121        let Some(mut copying) = Copying::new(*control) else {
122            return Ok(control.finish(self.clone(), None)?);
123        };
124        let expression = copying.expression(self)?;
125        copying.finish(expression)
126    }
127}
128
129impl UnifiedPlan {
130    /// Copy complete analyzed syntax, including utility commands, admitting each owned destination before construction. Transient bindings and shared immutable input owners preserve their original identities.
131    pub fn clone_with_control(&self, control: &ProductionControl<'_>) -> Result<Produced<Self>> {
132        control.check()?;
133        let Some(mut copying) = Copying::new(*control) else {
134            return Ok(control.finish(self.clone(), None)?);
135        };
136        let plan = syntax::SyntaxCopy::copy_syntax(self, &mut copying)?;
137        copying.finish(plan)
138    }
139
140    /// Copy a query or INSERT/UPDATE/DELETE/MERGE executable. Utility commands have separate preparation and lifetime owners and are rejected by this executable-only operation.
141    pub fn clone_executable_with_control(
142        &self,
143        control: &ProductionControl<'_>,
144    ) -> Result<Produced<Self>> {
145        PlanRef::from(self).clone_executable_with_control(control)
146    }
147}
148
149impl PlanRef<'_> {
150    /// Copy the complete borrowed plan, including utility syntax, into admitted storage.
151    pub fn clone_with_control(
152        self,
153        control: &ProductionControl<'_>,
154    ) -> Result<Produced<UnifiedPlan>> {
155        control.check()?;
156        let Some(mut copying) = Copying::new(*control) else {
157            return Ok(control.finish(self.to_owned(), None)?);
158        };
159        let plan = match self {
160            Self::Query(query) => {
161                UnifiedPlan::Query(copying.boxed(|copying| copying.query(query))?)
162            }
163            Self::Command(command) => {
164                UnifiedPlan::Command(copying.boxed(|copying| copying.command_syntax(command))?)
165            }
166        };
167        copying.finish(plan)
168    }
169
170    /// Copy a borrowed query or mutation directly into its admitted executable owner, without first constructing a temporary statement wrapper.
171    pub fn clone_executable_with_control(
172        self,
173        control: &ProductionControl<'_>,
174    ) -> Result<Produced<UnifiedPlan>> {
175        control.check()?;
176        let Some(mut copying) = Copying::new(*control) else {
177            if let Self::Command(command) = self {
178                require_mutation(command)?;
179            }
180            return Ok(control.finish(self.to_owned(), None)?);
181        };
182        let plan = match self {
183            Self::Query(query) => {
184                UnifiedPlan::Query(copying.boxed(|copying| copying.query(query))?)
185            }
186            Self::Command(command) => {
187                UnifiedPlan::Command(copying.boxed(|copying| copying.command(command))?)
188            }
189        };
190        copying.finish(plan)
191    }
192}
193
194fn require_mutation(command: &CommandPlan) -> Result<()> {
195    if matches!(
196        command,
197        CommandPlan::Insert(_)
198            | CommandPlan::Update(_)
199            | CommandPlan::Delete(_)
200            | CommandPlan::Merge(_)
201    ) {
202        Ok(())
203    } else {
204        Err(SQLError::Internal(
205            "utility command has no query execution copy".into(),
206        ))
207    }
208}
209
210type ParameterLookup<'a> = dyn Fn(&crate::ast::Expr) -> Option<usize> + 'a;
211
212pub(crate) struct Copying<'a> {
213    control: ProductionControl<'a>,
214    memory: MemoryReservation,
215    fields: Option<BudgetedVec<RewriteField>>,
216    scalar_items: Option<BudgetedVec<Option<super::scalar::ScalarMemory>>>,
217    parameters: Option<&'a ParameterLookup<'a>>,
218}
219
220mod owned_assignments;
221pub(crate) use owned_assignments::{assignment_vector, null_assignment};
222mod owned_deferred;
223mod owned_projection;
224mod owned_query;
225mod owned_scalar;
226
227impl<'a> Copying<'a> {
228    fn new(control: ProductionControl<'a>) -> Option<Self> {
229        control.empty_reservation().map(|memory| Self {
230            control,
231            memory,
232            fields: None,
233            scalar_items: None,
234            parameters: None,
235        })
236    }
237
238    pub(super) fn for_rewrite(control: ProductionControl<'a>) -> Option<Self> {
239        let mut copying = Self::new(control)?;
240        copying.fields = Some(BudgetedVec::new(
241            control.budget().expect("controlled rewrite"),
242        ));
243        Some(copying)
244    }
245
246    pub(super) fn into_rewrite_memory(self) -> RewriteMemory {
247        let mut fields = self.fields.expect("mutable copy records fields");
248        if let Some(items) = self.scalar_items {
249            assert!(fields.is_empty(), "scalar vectors have indexed ownership");
250            return RewriteMemory::Scalars {
251                direct: self.memory,
252                items,
253            };
254        }
255        // A scalar-only field already owns its complete payload. Keep that owner directly instead of retaining a second one-element field vector for every cell.
256        if self.memory.bytes() == 0 && fields.len() == 1 && fields[0].name == "scalar" {
257            return fields
258                .pop()
259                .expect("single scalar field")
260                .memory
261                .expect("scalar owner");
262        }
263        RewriteMemory::Fields {
264            direct: self.memory,
265            fields,
266        }
267    }
268
269    fn field<T>(
270        &mut self,
271        name: &'static str,
272        copy: impl FnOnce(&mut Self) -> Result<T>,
273    ) -> Result<T> {
274        let Some(fields) = &mut self.fields else {
275            return copy(self);
276        };
277        self.control.check()?;
278        fields.reserve(1)?;
279        let mut child = Self::for_rewrite(self.control).expect("controlled rewrite");
280        child.parameters = self.parameters;
281        let value = copy(&mut child)?;
282        self.fields
283            .as_mut()
284            .expect("mutable copy")
285            .push(RewriteField {
286                name,
287                memory: Some(child.into_rewrite_memory()),
288            })?;
289        Ok(value)
290    }
291
292    pub(super) fn command_syntax(&mut self, command: &CommandPlan) -> Result<CommandPlan> {
293        syntax::SyntaxCopy::copy_syntax(command, self)
294    }
295
296    fn check(&self) -> Result<()> {
297        Ok(self.control.check()?)
298    }
299
300    fn finish<T>(self, value: T) -> Result<Produced<T>> {
301        Ok(self.control.finish(value, Some(self.memory))?)
302    }
303
304    pub(in crate::plan) fn take<T>(&mut self, output: Produced<T>) -> T {
305        let (value, memory) = output.into_parts();
306        self.memory.absorb(memory.expect("controlled plan copy"));
307        value
308    }
309
310    pub(crate) fn map<I: ExactSizeIterator, T>(
311        &mut self,
312        items: I,
313        mut copy: impl FnMut(&mut Self, I::Item) -> Result<T>,
314    ) -> Result<Vec<T>> {
315        self.check()?;
316        let mut output = BudgetedVec::new(self.control.budget().expect("controlled plan copy"));
317        output.reserve(items.len())?;
318        if let Some(fields) = &mut self.fields {
319            fields.reserve(items.len())?;
320        }
321        for item in items {
322            self.check()?;
323            output.push(self.field("item", |copying| copy(copying, item))?)?;
324        }
325        let (output, memory) = output.into_parts();
326        self.memory.absorb(memory);
327        Ok(output)
328    }
329
330    pub(crate) fn set<K: Ord>(
331        &mut self,
332        keys: &OwnedSet<K>,
333        mut copy: impl FnMut(&mut Self, &K) -> Result<K>,
334    ) -> Result<OwnedSet<K>> {
335        let mut output = OwnedSet::new();
336        for key in keys {
337            self.check()?;
338            self.memory.grow(OwnedSet::<K>::entry_bytes())?;
339            output.insert(copy(self, key)?);
340        }
341        Ok(output)
342    }
343
344    fn boxed<T>(&mut self, copy: impl FnOnce(&mut Self) -> Result<T>) -> Result<Box<T>> {
345        self.check()?;
346        self.memory.grow(size_of::<T>())?;
347        let value = copy(self)?;
348        self.check()?;
349        Ok(Box::new(value))
350    }
351
352    pub(crate) fn text(&mut self, value: &str) -> Result<String> {
353        let output = self.control.copy_text(value)?;
354        Ok(self.take(output))
355    }
356
357    fn optional_text(&mut self, value: Option<&str>) -> Result<Option<String>> {
358        value.map(|value| self.text(value)).transpose()
359    }
360
361    pub(in crate::plan) fn texts(&mut self, values: &[String]) -> Result<Vec<String>> {
362        self.map(values.iter(), |copying, value| copying.text(value))
363    }
364
365    fn scalar(&mut self, expression: &ScalarExpr) -> Result<ScalarExpr> {
366        if let Some(fields) = &mut self.fields {
367            self.control.check()?;
368            fields.reserve(1)?;
369            let copied = expression.copy_for_rewrite(&self.control)?;
370            let (expression, memory) = copied.into_rewrite_parts();
371            self.fields
372                .as_mut()
373                .expect("mutable copy")
374                .push(RewriteField {
375                    name: "scalar",
376                    memory: Some(RewriteMemory::Scalar(memory)),
377                })?;
378            return Ok(expression);
379        }
380        let output = expression.clone_with_control(&self.control)?;
381        Ok(self.take(output))
382    }
383
384    fn optional_scalar(&mut self, expression: Option<&ScalarExpr>) -> Result<Option<ScalarExpr>> {
385        expression
386            .map(|expression| self.scalar(expression))
387            .transpose()
388    }
389
390    fn scalar_box(&mut self, expression: &ScalarExpr) -> Result<Box<ScalarExpr>> {
391        self.boxed(|copying| copying.scalar(expression))
392    }
393
394    fn optional_scalar_box(
395        &mut self,
396        expression: Option<&ScalarExpr>,
397    ) -> Result<Option<Box<ScalarExpr>>> {
398        expression
399            .map(|expression| self.scalar_box(expression))
400            .transpose()
401    }
402
403    fn expression(&mut self, expression: &ExpressionPlan) -> Result<ExpressionPlan> {
404        Ok(ExpressionPlan {
405            scalar: self.scalar(&expression.scalar)?,
406            subqueries: self.field("subqueries", |copying| {
407                copying.map(expression.subqueries.iter(), Self::query)
408            })?,
409        })
410    }
411
412    fn ty(&mut self, ty: &crate::ColumnType) -> Result<crate::ColumnType> {
413        let output = ty.clone_with_control(&self.control)?;
414        Ok(self.take(output))
415    }
416
417    fn role(&mut self, role: Option<&RoleReference>) -> Result<Option<RoleReference>> {
418        role.map(|role| match role {
419            RoleReference::Named(name) => Ok(RoleReference::Named(self.text(name)?)),
420            RoleReference::Bound(binding) => {
421                Ok(RoleReference::Bound(std::sync::Arc::clone(binding)))
422            }
423        })
424        .transpose()
425    }
426
427    fn identity(&mut self, identity: &crate::ColumnIdentity) -> Result<crate::ColumnIdentity> {
428        let output = identity.clone_with_control(&self.control)?;
429        Ok(self.take(output))
430    }
431}