Skip to main content

uqa_sql/plan/mutable/
sources.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Source edits preserve parent containers and independently owned descendants.
8
9use super::{memory::RewriteMemory, MutableQueryPlan, RelationalPlan};
10use crate::{
11    plan::{OwnedScalarExpr, SourcePlan},
12    SQLError, ScalarExpr,
13};
14use uqa_core::{memory::ProductionControl, Value};
15
16mod bindings;
17mod functions;
18mod generated;
19mod joins;
20mod metadata;
21mod parents;
22mod references;
23pub use joins::{MutableJoinParts, MutableJoinShell};
24
25/// A source whose child and scalar constructor records follow consuming edits.
26#[derive(Debug)]
27pub struct MutableSourcePlan {
28    pub(super) source: SourcePlan,
29    pub(super) memory: Option<RewriteMemory>,
30}
31
32#[derive(Clone, Copy, Debug)]
33pub enum SourceScalarSlot {
34    JoinOn,
35    Value { row: usize, column: usize },
36    Argument(usize),
37    GroupArgument { function: usize, argument: usize },
38}
39
40#[derive(Clone, Copy, Debug)]
41pub enum SourceChildSlot {
42    Left,
43    Right,
44}
45
46impl MutableQueryPlan {
47    /// Rewrite the complete FROM source without exposing a mutable query or separating a source from its constructor ownership.
48    pub fn map_source(
49        mut self,
50        control: &ProductionControl<'_>,
51        map: impl FnOnce(MutableSourcePlan) -> Result<MutableSourcePlan, SQLError>,
52    ) -> Result<Self, SQLError> {
53        self.assert_owner(control);
54        control.check()?;
55        let RelationalPlan::QueryBlock(block) = &mut self.query.root else {
56            return Err(SQLError::Internal(
57                "source rewrite requires a query block".into(),
58            ));
59        };
60        let Some(source) = block.from.take() else {
61            return Ok(self);
62        };
63        let memory = self
64            .memory
65            .as_mut()
66            .and_then(|memory| query_source_memory(memory).take());
67        let output = map(MutableSourcePlan { source, memory })?;
68        output.assert_owner(control);
69        control.check()?;
70        block.from = Some(output.source);
71        if let Some(memory) = &mut self.memory {
72            *query_source_memory(memory) = output.memory;
73        }
74        Ok(self)
75    }
76}
77
78impl MutableSourcePlan {
79    pub fn reserved_bytes(&self) -> usize {
80        self.memory
81            .as_ref()
82            .map_or(0, RewriteMemory::reserved_bytes)
83    }
84
85    /// Rewrite a derived or attached table query while keeping its original source box and namespace metadata.
86    pub fn map_query(
87        mut self,
88        control: &ProductionControl<'_>,
89        map: impl FnOnce(MutableQueryPlan) -> Result<MutableQueryPlan, SQLError>,
90    ) -> Result<Self, SQLError> {
91        self.assert_owner(control);
92        control.check()?;
93        let (query, field) = match &mut self.source {
94            SourcePlan::Subquery { body, .. } => (body, "body"),
95            SourcePlan::Table {
96                executable_query: Some(query),
97                ..
98            } => (query, "executable_query"),
99            SourcePlan::Table {
100                executable_query: None,
101                ..
102            } => return Ok(self),
103            _ => {
104                return Err(SQLError::Internal(
105                    "source has no directly retained query".into(),
106                ));
107            }
108        };
109        let input = MutableQueryPlan {
110            query: std::mem::replace(query.as_mut(), super::queries::empty_query()),
111            memory: self.memory.as_mut().and_then(|memory| {
112                memory
113                    .field_mut(field)
114                    .as_mut()
115                    .expect("source query box")
116                    .field_mut("query")
117                    .take()
118            }),
119        };
120        let output = map(input)?;
121        output.assert_owner(control);
122        control.check()?;
123        **query = output.query;
124        if let Some(memory) = &mut self.memory {
125            *memory
126                .field_mut(field)
127                .as_mut()
128                .expect("source query box")
129                .field_mut("query") = output.memory;
130        }
131        Ok(self)
132    }
133
134    pub fn map_scalar(
135        mut self,
136        slot: SourceScalarSlot,
137        control: &ProductionControl<'_>,
138        map: impl FnOnce(OwnedScalarExpr) -> Result<OwnedScalarExpr, SQLError>,
139    ) -> Result<Self, SQLError> {
140        self.assert_owner(control);
141        control.check()?;
142        let Some(expression) = slot.expression_mut(&mut self.source) else {
143            return Ok(self);
144        };
145        let memory = self
146            .memory
147            .as_mut()
148            .and_then(|memory| slot.memory_mut(memory).take());
149        let input = OwnedScalarExpr::from_rewrite_parts(
150            std::mem::replace(expression, ScalarExpr::Literal(Value::Null)),
151            memory,
152        );
153        let output = input.rewrite(control, map)?;
154        let (expression, memory) = output.into_rewrite_parts();
155        *slot
156            .expression_mut(&mut self.source)
157            .expect("original scalar slot") = expression;
158        if let Some(owner) = &mut self.memory {
159            *slot.memory_mut(owner) = memory;
160        }
161        Ok(self)
162    }
163
164    pub fn map_child(
165        mut self,
166        slot: SourceChildSlot,
167        control: &ProductionControl<'_>,
168        map: impl FnOnce(Self) -> Result<Self, SQLError>,
169    ) -> Result<Self, SQLError> {
170        self.assert_owner(control);
171        control.check()?;
172        let input = Self {
173            source: std::mem::replace(slot.source_mut(&mut self.source), empty_source()),
174            memory: self
175                .memory
176                .as_mut()
177                .and_then(|memory| slot.memory_mut(memory).take()),
178        };
179        let output = map(input)?;
180        output.assert_owner(control);
181        control.check()?;
182        *slot.source_mut(&mut self.source) = output.source;
183        if let Some(memory) = &mut self.memory {
184            *slot.memory_mut(memory) = output.memory;
185        }
186        Ok(self)
187    }
188
189    /// Select one join child and destroy the former parent, including the child's old enclosing box. The selected child's own allocations retain their separate constructor records.
190    pub fn select_child(
191        mut self,
192        slot: SourceChildSlot,
193        control: &ProductionControl<'_>,
194    ) -> Result<Self, SQLError> {
195        self.assert_owner(control);
196        control.check()?;
197        let source = std::mem::replace(slot.source_mut(&mut self.source), empty_source());
198        let memory = self
199            .memory
200            .as_mut()
201            .and_then(|memory| slot.memory_mut(memory).take());
202        drop(self);
203        Ok(Self { source, memory })
204    }
205
206    pub(super) fn assert_owner(&self, control: &ProductionControl<'_>) {
207        match (&self.memory, control.budget()) {
208            (Some(RewriteMemory::Fields { direct, .. }), Some(budget)) => assert!(
209                direct.budget().shares_allowance(budget),
210                "source rewrite preserves its constructor allowance"
211            ),
212            (None, None) => {}
213            _ => panic!("controlled and ordinary source ownership must not be mixed"),
214        }
215    }
216}
217
218impl std::ops::Deref for MutableSourcePlan {
219    type Target = SourcePlan;
220    fn deref(&self) -> &SourcePlan {
221        &self.source
222    }
223}
224
225impl SourceChildSlot {
226    fn source_mut(self, source: &mut SourcePlan) -> &mut SourcePlan {
227        let SourcePlan::Join { left, right, .. } = source else {
228            panic!("join source child");
229        };
230        if matches!(self, Self::Left) {
231            left
232        } else {
233            right
234        }
235    }
236
237    pub(super) fn memory_mut(self, memory: &mut RewriteMemory) -> &mut Option<RewriteMemory> {
238        memory
239            .field_mut(if matches!(self, Self::Left) {
240                "left"
241            } else {
242                "right"
243            })
244            .as_mut()
245            .expect("source box owner")
246            .field_mut("source")
247    }
248}
249
250impl SourceScalarSlot {
251    pub(super) fn expression_mut(self, source: &mut SourcePlan) -> Option<&mut ScalarExpr> {
252        match (self, source) {
253            (Self::JoinOn, SourcePlan::Join { on, .. }) => on.as_mut(),
254            (Self::Value { row, column }, SourcePlan::Values { rows, .. }) => {
255                Some(&mut rows[row][column])
256            }
257            (Self::Argument(index), SourcePlan::Function { args, .. }) => Some(&mut args[index]),
258            (
259                Self::GroupArgument { function, argument },
260                SourcePlan::FunctionGroup { functions, .. },
261            ) => Some(&mut functions[function].args[argument]),
262            _ => panic!("source scalar selector matches its source kind"),
263        }
264    }
265
266    pub(super) fn memory_mut(
267        self,
268        memory: &mut RewriteMemory,
269    ) -> &mut Option<crate::plan::scalar::ScalarMemory> {
270        match self {
271            Self::JoinOn => memory
272                .field_mut("on")
273                .as_mut()
274                .expect("join predicate")
275                .scalar_mut(),
276            Self::Value { row, column } => item(memory, "rows", row).scalar_item_mut(column),
277            Self::Argument(index) => item(memory, "args", index).scalar_mut(),
278            Self::GroupArgument { function, argument } => {
279                item(item(memory, "functions", function), "args", argument).scalar_mut()
280            }
281        }
282    }
283}
284
285pub(super) fn query_source_memory(memory: &mut RewriteMemory) -> &mut Option<RewriteMemory> {
286    memory
287        .field_mut("root")
288        .as_mut()
289        .expect("query root")
290        .field_mut("block")
291        .as_mut()
292        .expect("query block")
293        .field_mut("from")
294        .as_mut()
295        .expect("FROM field")
296        .field_mut("source")
297}
298
299fn item<'a>(memory: &'a mut RewriteMemory, name: &str, index: usize) -> &'a mut RewriteMemory {
300    memory
301        .field_mut(name)
302        .as_mut()
303        .expect("source vector")
304        .item_mut(index)
305        .as_mut()
306        .expect("source vector item")
307}
308
309pub(super) fn empty_source() -> SourcePlan {
310    SourcePlan::Values {
311        lateral: false,
312        rows: Vec::new(),
313        alias: None,
314        column_aliases: Vec::new(),
315        internal_relation: None,
316        internal_column_types: Vec::new(),
317        internal_column_collations: Vec::new(),
318    }
319}