Skip to main content

uqa_sql/plan/
mutable.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Consuming query edits retain each constructor's independent allocation ownership.
8
9use super::{copy::Copying, OwnedScalarExpr, QueryPlan, RelationalPlan};
10use crate::{SQLError, ScalarExpr};
11use uqa_core::{
12    memory::{Produced, ProductionControl},
13    Value,
14};
15
16mod analysis;
17mod arenas;
18pub(crate) use analysis::{QueryMetadataUpdate, SourceMetadataUpdate};
19pub use arenas::{ScalarArenaTransform, ScalarQueryArena};
20pub(crate) mod commands;
21pub(crate) mod construction;
22mod ctes;
23mod deferred;
24pub use deferred::OwnedDeferredRewriteIter;
25mod executable;
26mod expression;
27pub(in crate::plan) mod field_vectors;
28pub(in crate::plan) mod values;
29pub use expression::MutableExpressionPlan;
30pub use values::OwnedValueRow;
31mod grouping;
32pub(crate) mod memory;
33mod metadata;
34pub(crate) mod nodes;
35mod parents;
36pub(crate) mod projections;
37mod queries;
38mod scoped;
39mod slots;
40pub use scoped::OwnedScopedPlanVisitor;
41mod sources;
42mod traversal;
43mod vectors;
44mod windows;
45pub use commands::{
46    CommandAssignmentSlot, CommandQuerySlot, CommandScalarSlot, MutableCommandPlan,
47};
48pub use executable::MutableExecutablePlan;
49use memory::RewriteMemory;
50pub use projections::{OwnedProjection, OwnedProjectionIter};
51pub use queries::QueryChildSlot;
52pub use slots::QueryScalarSlot;
53pub use sources::{
54    MutableJoinParts, MutableJoinShell, MutableSourcePlan, SourceChildSlot, SourceScalarSlot,
55};
56
57/// A private query destination with independently owned scalar fields and query children. Observation is read-only; consuming edits transfer or destroy the corresponding constructor records together with their IR.
58#[derive(Debug)]
59pub struct MutableQueryPlan {
60    query: QueryPlan,
61    memory: Option<RewriteMemory>,
62}
63
64impl QueryPlan {
65    /// Copy a complete query while keeping mutable constructor ownership separate. Every destination and ownership-record buffer is admitted before allocation; published immutable schemas retain their original shared owners.
66    pub fn copy_for_rewrite(
67        &self,
68        control: &ProductionControl<'_>,
69    ) -> Result<MutableQueryPlan, SQLError> {
70        control.check()?;
71        let Some(mut copying) = Copying::for_rewrite(*control) else {
72            return Ok(MutableQueryPlan {
73                query: self.clone(),
74                memory: None,
75            });
76        };
77        let query = copying.query_fields(self)?;
78        let output = MutableQueryPlan {
79            query,
80            memory: Some(copying.into_rewrite_memory()),
81        };
82        control.check()?;
83        Ok(output)
84    }
85}
86
87impl MutableQueryPlan {
88    pub(in crate::plan) fn from_rewrite_parts(
89        query: QueryPlan,
90        memory: Option<RewriteMemory>,
91    ) -> Self {
92        Self { query, memory }
93    }
94
95    pub fn reserved_bytes(&self) -> usize {
96        self.memory
97            .as_ref()
98            .map_or(0, RewriteMemory::reserved_bytes)
99    }
100
101    /// Rewrite one selected scalar root without copying parent containers or siblings. An absent optional scalar is left absent. Error or unwind destroys the complete private query.
102    pub fn map_scalar(
103        mut self,
104        slot: QueryScalarSlot,
105        control: &ProductionControl<'_>,
106        map: impl FnOnce(OwnedScalarExpr) -> Result<OwnedScalarExpr, SQLError>,
107    ) -> Result<Self, SQLError> {
108        self.assert_owner(control);
109        control.check()?;
110        let Some(expression) = slot.expression_mut(&mut self.query) else {
111            return Ok(self);
112        };
113        let memory_slot = self.memory.as_mut().map(|memory| slot.memory_mut(memory));
114        let scalar_memory = memory_slot.and_then(Option::take);
115        let input = OwnedScalarExpr::from_rewrite_parts(
116            std::mem::replace(expression, ScalarExpr::Literal(Value::Null)),
117            scalar_memory,
118        );
119        let output = input.rewrite(control, map)?;
120        let (output, memory) = output.into_rewrite_parts();
121        *expression = output;
122        if let Some(owner) = &mut self.memory {
123            *slot.memory_mut(owner) = memory;
124        }
125        Ok(self)
126    }
127
128    /// Keep selected projection entries in their original vector. Removed expression and alias storage is destroyed before its own constructor records; surviving aliases and scalar children keep their addresses and allowance.
129    pub fn retain_projections(
130        mut self,
131        control: &ProductionControl<'_>,
132        mut keep: impl FnMut(usize, &super::ProjectionPlan) -> Result<bool, SQLError>,
133    ) -> Result<Self, SQLError> {
134        self.assert_owner(control);
135        control.check()?;
136        let RelationalPlan::QueryBlock(block) = &mut self.query.root else {
137            return Err(SQLError::Internal(
138                "projection retention requires a query block".into(),
139            ));
140        };
141        let mut fields = self.memory.as_mut().map(|memory| {
142            let node = memory.field_mut("root").as_mut().expect("query root");
143            let node = node.field_mut("block").as_mut().expect("query block");
144            match node
145                .field_mut("projections")
146                .as_mut()
147                .expect("projection vector")
148            {
149                RewriteMemory::Fields { fields, .. } => fields,
150                RewriteMemory::Scalar(_) | RewriteMemory::Scalars { .. } => {
151                    unreachable!("projection vector owner")
152                }
153            }
154        });
155        let mut retained = 0;
156        for index in 0..block.projections.len() {
157            control.check()?;
158            if keep(index, &block.projections[index])? {
159                block.projections.swap(retained, index);
160                if let Some(fields) = &mut fields {
161                    fields.swap(retained, index);
162                }
163                retained += 1;
164            }
165        }
166        block.projections.truncate(retained);
167        if let Some(fields) = fields {
168            fields.truncate(retained);
169        }
170        control.check()?;
171        Ok(self)
172    }
173
174    /// Freeze only the surviving query storage. Temporary constructor records release before publication; no size observation or retrospective reservation split is used.
175    pub fn finish(self, control: &ProductionControl<'_>) -> Result<Produced<QueryPlan>, SQLError> {
176        self.assert_owner(control);
177        control.check()?;
178        let Self { query, memory } = self;
179        Ok(control.finish(query, memory.and_then(RewriteMemory::into_reservation))?)
180    }
181
182    fn assert_owner(&self, control: &ProductionControl<'_>) {
183        match (&self.memory, control.budget()) {
184            (Some(RewriteMemory::Fields { direct, .. }), Some(budget)) => assert!(
185                direct.budget().shares_allowance(budget),
186                "query rewrite preserves its constructor allowance"
187            ),
188            (None, None) => {}
189            _ => panic!("controlled and ordinary query ownership must not be mixed"),
190        }
191    }
192}
193
194impl std::ops::Deref for MutableQueryPlan {
195    type Target = QueryPlan;
196    fn deref(&self) -> &QueryPlan {
197        &self.query
198    }
199}
200
201#[cfg(test)]
202mod tests;