Skip to main content

uqa_sql/plan/mutable/
construction.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Generated projections and derived sources admit containers before moving existing constructor owners.
8
9use super::{
10    Copying, MutableQueryPlan, MutableSourcePlan, OwnedProjection, QueryPlan, RelationalPlan,
11    RewriteMemory,
12};
13use crate::{
14    plan::{AccessPathPlan, ComputePlan, QueryBlockPlan, SourcePlan},
15    SQLError,
16};
17use uqa_core::memory::{OwnedSet, Produced, ProductionControl};
18
19impl QueryBlockPlan {
20    /// Construct an independent mutable query root from a retained block, admitting every scalar and structural destination before copying. The enclosing query has no CTE or relation flags until its caller installs the root in its original scope.
21    pub fn copy_for_rewrite(
22        &self,
23        control: &ProductionControl<'_>,
24    ) -> Result<MutableQueryPlan, SQLError> {
25        control.check()?;
26        let Some(mut copying) = Copying::for_rewrite(*control) else {
27            let mut query = empty_projection_query();
28            query.root = RelationalPlan::QueryBlock(Box::new(self.clone()));
29            return Ok(MutableQueryPlan {
30                query,
31                memory: None,
32            });
33        };
34        let query = copying.query_block_root(self)?;
35        Ok(MutableQueryPlan {
36            query,
37            memory: Some(copying.into_rewrite_memory()),
38        })
39    }
40}
41
42impl MutableQueryPlan {
43    /// Detach WHERE with its independent scalar constructor. Its former field metadata remains with the query until another qualification is installed or the query is discarded.
44    pub fn take_where(
45        mut self,
46        control: &ProductionControl<'_>,
47    ) -> Result<(Self, Option<super::OwnedScalarExpr>), SQLError> {
48        self.assert_owner(control);
49        control.check()?;
50        let RelationalPlan::QueryBlock(block) = &mut self.query.root else {
51            return Err(SQLError::Internal(
52                "qualification extraction requires a query block".into(),
53            ));
54        };
55        let Some(expression) = block.r#where.take() else {
56            return Ok((self, None));
57        };
58        let memory = self.memory.as_mut().map(|memory| {
59            super::QueryScalarSlot::Where
60                .memory_mut(memory)
61                .take()
62                .expect("qualification owner")
63        });
64        Ok((
65            self,
66            Some(super::OwnedScalarExpr::from_rewrite_parts(
67                expression, memory,
68            )),
69        ))
70    }
71
72    pub(crate) fn into_rewrite_parts(
73        self,
74        control: &ProductionControl<'_>,
75    ) -> Result<(QueryPlan, Option<RewriteMemory>), SQLError> {
76        self.assert_owner(control);
77        control.check()?;
78        Ok((self.query, self.memory))
79    }
80
81    /// Build a projection query from independently admitted scalar/name inputs. The query starts without FROM; callers attach a unit or relational source through the same owning boundary.
82    pub fn projected(
83        projections: impl ExactSizeIterator<Item = OwnedProjection>,
84        control: &ProductionControl<'_>,
85    ) -> Result<Self, SQLError> {
86        control.check()?;
87        let query = if let Some(mut copying) = Copying::for_rewrite(*control) {
88            let query = copying.projected_query()?;
89            Self {
90                query,
91                memory: Some(copying.into_rewrite_memory()),
92            }
93        } else {
94            let mut query = empty_projection_query();
95            query.root = RelationalPlan::QueryBlock(Box::new(empty_projection_block()));
96            Self {
97                query,
98                memory: None,
99            }
100        };
101        query.replace_projections(projections, control)
102    }
103
104    /// Replace an optional qualification, transferring the selected scalar owner even when the query previously had no WHERE clause.
105    pub fn replace_where(
106        mut self,
107        expression: Option<super::OwnedScalarExpr>,
108        control: &ProductionControl<'_>,
109    ) -> Result<Self, SQLError> {
110        self.assert_owner(control);
111        control.check()?;
112        let RelationalPlan::QueryBlock(block) = &mut self.query.root else {
113            return Err(SQLError::Internal(
114                "qualification replacement requires a query block".into(),
115            ));
116        };
117        let (expression, replacement) = match Copying::for_rewrite(*control) {
118            Some(mut copying) => {
119                let expression = expression
120                    .map(|expression| copying.take_scalar(expression))
121                    .transpose()?;
122                (expression, Some(copying.into_rewrite_memory()))
123            }
124            None => (
125                expression
126                    .map(|expression| {
127                        expression.finish(control).map(|expression| {
128                            expression
129                                .into_uncontrolled()
130                                .expect("ordinary qualification")
131                        })
132                    })
133                    .transpose()?,
134                None,
135            ),
136        };
137        block.r#where = expression;
138        if let Some(memory) = &mut self.memory {
139            *memory
140                .field_mut("root")
141                .as_mut()
142                .expect("query root")
143                .field_mut("block")
144                .as_mut()
145                .expect("query block")
146                .field_mut("where") = replacement;
147        }
148        Ok(self)
149    }
150
151    /// Move FROM out of the query while retaining every sibling field and its exact owner.
152    pub fn take_source(
153        mut self,
154        control: &ProductionControl<'_>,
155    ) -> Result<(Self, Option<MutableSourcePlan>), SQLError> {
156        self.assert_owner(control);
157        control.check()?;
158        let RelationalPlan::QueryBlock(block) = &mut self.query.root else {
159            return Err(SQLError::Internal(
160                "source extraction requires a query block".into(),
161            ));
162        };
163        let Some(source) = block.from.take() else {
164            return Ok((self, None));
165        };
166        let memory = self
167            .memory
168            .as_mut()
169            .and_then(|memory| super::sources::query_source_memory(memory).take());
170        Ok((self, Some(MutableSourcePlan { source, memory })))
171    }
172
173    /// Replace FROM after admitting its new field records. The old source is destroyed before its constructor leases are retired.
174    pub fn replace_source(
175        mut self,
176        source: Option<MutableSourcePlan>,
177        control: &ProductionControl<'_>,
178    ) -> Result<Self, SQLError> {
179        self.assert_owner(control);
180        control.check()?;
181        let RelationalPlan::QueryBlock(block) = &mut self.query.root else {
182            return Err(SQLError::Internal(
183                "source replacement requires a query block".into(),
184            ));
185        };
186        let (source, replacement) = match Copying::for_rewrite(*control) {
187            Some(mut copying) => {
188                let source = source
189                    .map(|source| copying.take_source(source))
190                    .transpose()?;
191                (source, Some(copying.into_rewrite_memory()))
192            }
193            None => (
194                source
195                    .map(|source| source.into_rewrite_parts(control).map(|parts| parts.0))
196                    .transpose()?,
197                None,
198            ),
199        };
200        block.from = source;
201        if let Some(memory) = &mut self.memory {
202            *memory
203                .field_mut("root")
204                .as_mut()
205                .expect("query root")
206                .field_mut("block")
207                .as_mut()
208                .expect("query block")
209                .field_mut("from") = replacement;
210        }
211        Ok(self)
212    }
213}
214
215impl SourcePlan {
216    pub fn copy_for_rewrite(
217        &self,
218        control: &ProductionControl<'_>,
219    ) -> Result<MutableSourcePlan, SQLError> {
220        control.check()?;
221        let Some(mut copying) = Copying::for_rewrite(*control) else {
222            return Ok(MutableSourcePlan {
223                source: self.clone(),
224                memory: None,
225            });
226        };
227        let source = copying.source_fields(self)?;
228        let output = MutableSourcePlan {
229            source,
230            memory: Some(copying.into_rewrite_memory()),
231        };
232        control.check()?;
233        Ok(output)
234    }
235}
236
237impl MutableSourcePlan {
238    pub(crate) fn into_rewrite_parts(
239        self,
240        control: &ProductionControl<'_>,
241    ) -> Result<(SourcePlan, Option<RewriteMemory>), SQLError> {
242        self.assert_owner(control);
243        control.check()?;
244        Ok((self.source, self.memory))
245    }
246
247    /// Construct the one-row zero-column relation used by a scalar projection.
248    pub fn unit(control: &ProductionControl<'_>) -> Result<Self, SQLError> {
249        control.check()?;
250        let Some(mut copying) = Copying::for_rewrite(*control) else {
251            return Ok(Self {
252                source: SourcePlan::Values {
253                    lateral: false,
254                    rows: vec![Vec::new()],
255                    alias: None,
256                    column_aliases: Vec::new(),
257                    internal_relation: None,
258                    internal_column_types: Vec::new(),
259                    internal_column_collations: Vec::new(),
260                },
261                memory: None,
262            });
263        };
264        let source = copying.unit_source()?;
265        Ok(Self {
266            source,
267            memory: Some(copying.into_rewrite_memory()),
268        })
269    }
270
271    /// Attach a query beneath a newly admitted source box, transferring the query's own constructor records unchanged.
272    pub fn subquery(
273        query: MutableQueryPlan,
274        alias: Option<Produced<String>>,
275        columns: Produced<Vec<String>>,
276        captured_output: Option<crate::ast::InternalRelationId>,
277        lateral: bool,
278        control: &ProductionControl<'_>,
279    ) -> Result<Self, SQLError> {
280        control.check()?;
281        if let Some(mut copying) = Copying::for_rewrite(*control) {
282            let source =
283                copying.subquery_source(query, alias, columns, captured_output, lateral)?;
284            return Ok(Self {
285                source,
286                memory: Some(copying.into_rewrite_memory()),
287            });
288        }
289        let (query, _) = query.into_rewrite_parts(control)?;
290        Ok(Self {
291            source: SourcePlan::Subquery {
292                captured_output,
293                lateral,
294                body: Box::new(query),
295                alias: alias.map(|alias| alias.into_uncontrolled().expect("ordinary source alias")),
296                column_aliases: columns
297                    .into_uncontrolled()
298                    .expect("ordinary source columns"),
299            },
300            memory: None,
301        })
302    }
303}
304
305pub(crate) fn empty_projection_query() -> QueryPlan {
306    super::queries::empty_query()
307}
308
309pub(crate) fn empty_projection_block() -> QueryBlockPlan {
310    QueryBlockPlan {
311        deferred_outer_rewrites: Vec::new(),
312        windows: Vec::new(),
313        projections: Vec::new(),
314        privilege_columns: OwnedSet::new(),
315        from: None,
316        r#where: None,
317        compute: ComputePlan::Project,
318        group_by: Vec::new(),
319        grouping_sets: Vec::new(),
320        group_distinct: false,
321        having: None,
322        order_by: Vec::new(),
323        limit: None,
324        with_ties: false,
325        offset: None,
326        distinct: false,
327        distinct_on: Vec::new(),
328        subqueries: Vec::new(),
329        access: AccessPathPlan::Row,
330        locking: Vec::new(),
331    }
332}