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 executable query and mutation plan copies.
8
9use super::{CommandPlan, ExpressionPlan, QueryPlan, UnifiedPlan};
10use crate::{catalog::roles::RoleReference, SQLError, ScalarExpr};
11use uqa_core::memory::{BudgetedVec, MemoryReservation, OwnedSet, Produced, ProductionControl};
12
13mod command;
14mod query;
15mod source;
16#[cfg(test)]
17mod tests;
18
19type Result<T> = std::result::Result<T, SQLError>;
20
21impl super::CtePlan {
22    /// Copy a complete CTE declaration under the selected allowance and cancellation scopes.
23    pub fn clone_with_control(&self, control: &ProductionControl<'_>) -> Result<Produced<Self>> {
24        control.check()?;
25        let Some(mut copying) = Copying::new(*control) else {
26            return Ok(control.finish(self.clone(), None)?);
27        };
28        let plan = copying.cte(self)?;
29        copying.finish(plan)
30    }
31}
32
33impl QueryPlan {
34    /// 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.
35    pub fn clone_with_control(&self, control: &ProductionControl<'_>) -> Result<Produced<Self>> {
36        control.check()?;
37        let Some(mut copying) = Copying::new(*control) else {
38            return Ok(control.finish(self.clone(), None)?);
39        };
40        let plan = copying.query(self)?;
41        copying.finish(plan)
42    }
43}
44
45impl ExpressionPlan {
46    /// Copy a scalar expression and its owned query arena under the same production allowance.
47    pub fn clone_with_control(&self, control: &ProductionControl<'_>) -> Result<Produced<Self>> {
48        control.check()?;
49        let Some(mut copying) = Copying::new(*control) else {
50            return Ok(control.finish(self.clone(), None)?);
51        };
52        let expression = copying.expression(self)?;
53        copying.finish(expression)
54    }
55}
56
57impl UnifiedPlan {
58    /// 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.
59    pub fn clone_executable_with_control(
60        &self,
61        control: &ProductionControl<'_>,
62    ) -> Result<Produced<Self>> {
63        control.check()?;
64        let Some(mut copying) = Copying::new(*control) else {
65            if let Self::Command(command) = self {
66                require_mutation(command)?;
67            }
68            return Ok(control.finish(self.clone(), None)?);
69        };
70        let plan = match self {
71            Self::Query(query) => Self::Query(copying.boxed(|copying| copying.query(query))?),
72            Self::Command(command) => {
73                Self::Command(copying.boxed(|copying| copying.command(command))?)
74            }
75        };
76        copying.finish(plan)
77    }
78}
79
80fn require_mutation(command: &CommandPlan) -> Result<()> {
81    if matches!(
82        command,
83        CommandPlan::Insert(_)
84            | CommandPlan::Update(_)
85            | CommandPlan::Delete(_)
86            | CommandPlan::Merge(_)
87    ) {
88        Ok(())
89    } else {
90        Err(SQLError::Internal(
91            "utility command has no query execution copy".into(),
92        ))
93    }
94}
95
96pub(crate) struct Copying<'a> {
97    control: ProductionControl<'a>,
98    memory: MemoryReservation,
99}
100
101impl<'a> Copying<'a> {
102    fn new(control: ProductionControl<'a>) -> Option<Self> {
103        control
104            .empty_reservation()
105            .map(|memory| Self { control, memory })
106    }
107
108    fn check(&self) -> Result<()> {
109        Ok(self.control.check()?)
110    }
111
112    fn finish<T>(self, value: T) -> Result<Produced<T>> {
113        Ok(self.control.finish(value, Some(self.memory))?)
114    }
115
116    fn take<T>(&mut self, output: Produced<T>) -> T {
117        let (value, memory) = output.into_parts();
118        self.memory.absorb(memory.expect("controlled plan copy"));
119        value
120    }
121
122    pub(crate) fn map<I: ExactSizeIterator, T>(
123        &mut self,
124        items: I,
125        mut copy: impl FnMut(&mut Self, I::Item) -> Result<T>,
126    ) -> Result<Vec<T>> {
127        self.check()?;
128        let mut output = BudgetedVec::new(self.control.budget().expect("controlled plan copy"));
129        output.reserve(items.len())?;
130        for item in items {
131            self.check()?;
132            output.push(copy(self, item)?)?;
133        }
134        let (output, memory) = output.into_parts();
135        self.memory.absorb(memory);
136        Ok(output)
137    }
138
139    pub(crate) fn set<K: Ord>(
140        &mut self,
141        keys: &OwnedSet<K>,
142        mut copy: impl FnMut(&mut Self, &K) -> Result<K>,
143    ) -> Result<OwnedSet<K>> {
144        let mut output = OwnedSet::new();
145        for key in keys {
146            self.check()?;
147            self.memory.grow(OwnedSet::<K>::entry_bytes())?;
148            output.insert(copy(self, key)?);
149        }
150        Ok(output)
151    }
152
153    fn boxed<T>(&mut self, copy: impl FnOnce(&mut Self) -> Result<T>) -> Result<Box<T>> {
154        self.check()?;
155        self.memory.grow(size_of::<T>())?;
156        let value = copy(self)?;
157        self.check()?;
158        Ok(Box::new(value))
159    }
160
161    pub(crate) fn text(&mut self, value: &str) -> Result<String> {
162        let output = self.control.copy_text(value)?;
163        Ok(self.take(output))
164    }
165
166    fn optional_text(&mut self, value: Option<&str>) -> Result<Option<String>> {
167        value.map(|value| self.text(value)).transpose()
168    }
169
170    fn texts(&mut self, values: &[String]) -> Result<Vec<String>> {
171        self.map(values.iter(), |copying, value| copying.text(value))
172    }
173
174    fn scalar(&mut self, expression: &ScalarExpr) -> Result<ScalarExpr> {
175        let output = expression.clone_with_control(&self.control)?;
176        Ok(self.take(output))
177    }
178
179    fn optional_scalar(&mut self, expression: Option<&ScalarExpr>) -> Result<Option<ScalarExpr>> {
180        expression
181            .map(|expression| self.scalar(expression))
182            .transpose()
183    }
184
185    fn scalar_box(&mut self, expression: &ScalarExpr) -> Result<Box<ScalarExpr>> {
186        self.boxed(|copying| copying.scalar(expression))
187    }
188
189    fn optional_scalar_box(
190        &mut self,
191        expression: Option<&ScalarExpr>,
192    ) -> Result<Option<Box<ScalarExpr>>> {
193        expression
194            .map(|expression| self.scalar_box(expression))
195            .transpose()
196    }
197
198    fn expression(&mut self, expression: &ExpressionPlan) -> Result<ExpressionPlan> {
199        Ok(ExpressionPlan {
200            scalar: self.scalar(&expression.scalar)?,
201            subqueries: self.map(expression.subqueries.iter(), Self::query)?,
202        })
203    }
204
205    fn ty(&mut self, ty: &crate::ColumnType) -> Result<crate::ColumnType> {
206        let output = ty.clone_with_control(&self.control)?;
207        Ok(self.take(output))
208    }
209
210    fn role(&mut self, role: Option<&RoleReference>) -> Result<Option<RoleReference>> {
211        role.map(|role| match role {
212            RoleReference::Named(name) => Ok(RoleReference::Named(self.text(name)?)),
213            RoleReference::Bound(binding) => {
214                Ok(RoleReference::Bound(std::sync::Arc::clone(binding)))
215            }
216        })
217        .transpose()
218    }
219
220    fn identity(&mut self, identity: &crate::ColumnIdentity) -> Result<crate::ColumnIdentity> {
221        let output = identity.clone_with_control(&self.control)?;
222        Ok(self.take(output))
223    }
224}