Skip to main content

uqa_sql/plan/mutable/
commands.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Complete command copies retain private field ownership through consuming edits.
8
9use super::{memory::RewriteMemory, MutableQueryPlan};
10use crate::{
11    plan::{copy::Copying, CommandPlan, OwnedScalarExpr},
12    SQLError, ScalarExpr,
13};
14use uqa_core::{
15    memory::{Produced, ProductionControl},
16    Value,
17};
18
19mod assignments;
20pub(in crate::plan::mutable) mod children;
21mod conflict;
22mod construction;
23mod executable;
24mod inputs;
25mod insert;
26mod metadata;
27mod namespaces;
28mod projections;
29pub(in crate::plan) mod rule_inputs;
30pub(in crate::plan::mutable) mod transformation;
31mod view_columns;
32mod view_metadata;
33pub use assignments::CommandAssignmentSlot;
34pub use children::CommandQuerySlot;
35
36#[derive(Debug)]
37pub struct MutableCommandPlan {
38    pub(super) command: CommandPlan,
39    pub(super) memory: Option<RewriteMemory>,
40}
41
42#[derive(Clone, Copy, Debug)]
43pub enum CommandScalarSlot {
44    Assignment(usize),
45    Predicate,
46    Returning(usize),
47    InsertValue { row: usize, column: usize },
48    MergeJoin,
49    ViewCheck(usize),
50    MergeCondition(usize),
51    MergeValue { clause: usize, value: usize },
52    ConflictExpression(usize),
53    ConflictInferencePredicate,
54    ConflictPredicate,
55    CallArgument(usize),
56    ExecuteParameter(usize),
57}
58
59impl CommandPlan {
60    /// Copy complete command syntax while retaining independently replaceable executable fields. Utility syntax remains with this command owner and is not evaluated by copying.
61    pub fn copy_for_rewrite(
62        &self,
63        control: &ProductionControl<'_>,
64    ) -> Result<MutableCommandPlan, SQLError> {
65        control.check()?;
66        let Some(mut copying) = Copying::for_rewrite(*control) else {
67            return Ok(MutableCommandPlan {
68                command: self.clone(),
69                memory: None,
70            });
71        };
72        let command = copying.command_syntax(self)?;
73        let output = MutableCommandPlan {
74            command,
75            memory: Some(copying.into_rewrite_memory()),
76        };
77        control.check()?;
78        Ok(output)
79    }
80}
81
82impl MutableCommandPlan {
83    pub(crate) fn from_ordinary(command: CommandPlan) -> Self {
84        Self {
85            command,
86            memory: None,
87        }
88    }
89
90    pub(in crate::plan) fn from_rewrite_parts(
91        command: CommandPlan,
92        memory: Option<RewriteMemory>,
93    ) -> Self {
94        Self { command, memory }
95    }
96
97    pub fn reserved_bytes(&self) -> usize {
98        self.memory
99            .as_ref()
100            .map_or(0, RewriteMemory::reserved_bytes)
101    }
102
103    /// Rewrite one scalar root without changing the statement's other inputs or its diagnostic order.
104    pub fn map_scalar(
105        mut self,
106        slot: CommandScalarSlot,
107        control: &ProductionControl<'_>,
108        map: impl FnOnce(OwnedScalarExpr) -> Result<OwnedScalarExpr, SQLError>,
109    ) -> Result<Self, SQLError> {
110        self.assert_owner(control);
111        control.check()?;
112        let Some(expression) = slot.expression_mut(&mut self.command) else {
113            return Ok(self);
114        };
115        let memory = self
116            .memory
117            .as_mut()
118            .and_then(|memory| slot.memory_mut(memory).take());
119        let input = OwnedScalarExpr::from_rewrite_parts(
120            std::mem::replace(expression, ScalarExpr::Literal(Value::Null)),
121            memory,
122        );
123        let output = input.rewrite(control, map)?;
124        let (expression, memory) = output.into_rewrite_parts();
125        *slot
126            .expression_mut(&mut self.command)
127            .expect("original command scalar") = expression;
128        if let Some(owner) = &mut self.memory {
129            *slot.memory_mut(owner) = memory;
130        }
131        Ok(self)
132    }
133
134    /// Rewrite a retained query body while preserving its original enclosing box. EXPLAIN option interpretation and utility execution remain with their existing owners.
135    pub fn map_query_body(
136        mut self,
137        control: &ProductionControl<'_>,
138        map: impl FnOnce(MutableQueryPlan) -> Result<MutableQueryPlan, SQLError>,
139    ) -> Result<Self, SQLError> {
140        self.assert_owner(control);
141        control.check()?;
142        let query = match &mut self.command {
143            CommandPlan::DeclareCursor { query, .. }
144            | CommandPlan::CreateTableAs { query, .. }
145            | CommandPlan::CreateMaterializedView { query, .. }
146            | CommandPlan::CreateView { query, .. } => query,
147            _ => {
148                return Err(SQLError::Internal(
149                    "command has no directly retained query body".into(),
150                ));
151            }
152        };
153        let input = MutableQueryPlan {
154            query: std::mem::replace(query.as_mut(), super::queries::empty_query()),
155            memory: self.memory.as_mut().and_then(|memory| {
156                memory
157                    .field_mut("query")
158                    .as_mut()
159                    .expect("command query field")
160                    .field_mut("query")
161                    .take()
162            }),
163        };
164        let output = map(input)?;
165        output.assert_owner(control);
166        control.check()?;
167        **query = output.query;
168        if let Some(memory) = &mut self.memory {
169            *memory
170                .field_mut("query")
171                .as_mut()
172                .expect("command query field")
173                .field_mut("query") = output.memory;
174        }
175        Ok(self)
176    }
177
178    pub fn finish(
179        self,
180        control: &ProductionControl<'_>,
181    ) -> Result<Produced<CommandPlan>, SQLError> {
182        self.assert_owner(control);
183        control.check()?;
184        let Self { command, memory } = self;
185        Ok(control.finish(command, memory.and_then(RewriteMemory::into_reservation))?)
186    }
187
188    pub(super) fn assert_owner(&self, control: &ProductionControl<'_>) {
189        match (&self.memory, control.budget()) {
190            (Some(RewriteMemory::Fields { direct, .. }), Some(budget)) => assert!(
191                direct.budget().shares_allowance(budget),
192                "command rewrite preserves its constructor allowance"
193            ),
194            (None, None) => {}
195            _ => panic!("controlled and ordinary command ownership must not be mixed"),
196        }
197    }
198}
199
200impl std::ops::Deref for MutableCommandPlan {
201    type Target = CommandPlan;
202    fn deref(&self) -> &CommandPlan {
203        &self.command
204    }
205}
206
207impl CommandScalarSlot {
208    fn expression_mut(self, command: &mut CommandPlan) -> Option<&mut ScalarExpr> {
209        match (self, command) {
210            (Self::Assignment(index), CommandPlan::Update(plan)) => {
211                Some(&mut plan.assignments[index].value)
212            }
213            (Self::Predicate, CommandPlan::Update(plan)) => plan.predicate.as_mut(),
214            (Self::Predicate, CommandPlan::Delete(plan)) => plan.predicate.as_mut(),
215            (Self::Returning(index), CommandPlan::Insert(plan)) => {
216                Some(&mut plan.returning[index].expr)
217            }
218            (Self::Returning(index), CommandPlan::Update(plan)) => {
219                Some(&mut plan.returning[index].expr)
220            }
221            (Self::Returning(index), CommandPlan::Delete(plan)) => {
222                Some(&mut plan.returning[index].expr)
223            }
224            (Self::Returning(index), CommandPlan::Merge(plan)) => {
225                Some(&mut plan.returning[index].expr)
226            }
227            (Self::InsertValue { row, column }, CommandPlan::Insert(plan)) => {
228                Some(&mut plan.rows[row][column])
229            }
230            (Self::ViewCheck(index), CommandPlan::Insert(plan)) => {
231                Some(&mut plan.view_checks[index].predicate)
232            }
233            (Self::ViewCheck(index), CommandPlan::Update(plan)) => {
234                Some(&mut plan.view_checks[index].predicate)
235            }
236            (Self::ViewCheck(index), CommandPlan::Merge(plan)) => {
237                Some(&mut plan.view_checks[index].predicate)
238            }
239            (Self::MergeJoin, CommandPlan::Merge(plan)) => Some(&mut plan.join_condition),
240            (Self::MergeCondition(index), CommandPlan::Merge(plan)) => {
241                use crate::plan::MergeWhenPlan;
242                match &mut plan.when_clauses[index] {
243                    MergeWhenPlan::UpdateMatched { condition, .. }
244                    | MergeWhenPlan::UpdateNotMatchedBySource { condition, .. }
245                    | MergeWhenPlan::DeleteMatched { condition }
246                    | MergeWhenPlan::DeleteNotMatchedBySource { condition }
247                    | MergeWhenPlan::InsertNotMatched { condition, .. }
248                    | MergeWhenPlan::NothingMatched { condition }
249                    | MergeWhenPlan::NothingNotMatched { condition }
250                    | MergeWhenPlan::NothingNotMatchedBySource { condition } => condition.as_mut(),
251                }
252            }
253            (Self::MergeValue { clause, value }, CommandPlan::Merge(plan)) => {
254                let crate::plan::MergeWhenPlan::InsertNotMatched { values, .. } =
255                    &mut plan.when_clauses[clause]
256                else {
257                    panic!("MERGE clause has insertion values");
258                };
259                Some(&mut values[value])
260            }
261            (Self::ConflictExpression(index), CommandPlan::Insert(plan)) => {
262                Some(&mut plan.on_conflict.as_mut().expect("conflict").expressions[index])
263            }
264            (Self::ConflictInferencePredicate, CommandPlan::Insert(plan)) => {
265                plan.on_conflict.as_mut()?.predicate.as_deref_mut()
266            }
267            (Self::ConflictPredicate, CommandPlan::Insert(plan)) => {
268                let conflict = plan.on_conflict.as_mut()?;
269                let crate::plan::ConflictActionPlan::Update { predicate, .. } =
270                    &mut conflict.action
271                else {
272                    return None;
273                };
274                predicate.as_deref_mut()
275            }
276            (Self::CallArgument(index), CommandPlan::Call { args, .. }) => {
277                Some(&mut args[index].scalar)
278            }
279            (Self::ExecuteParameter(index), CommandPlan::Execute { params, .. }) => {
280                Some(&mut params[index].scalar)
281            }
282            _ => panic!("command scalar selector matches its command kind"),
283        }
284    }
285
286    fn memory_mut(
287        self,
288        memory: &mut RewriteMemory,
289    ) -> &mut Option<crate::plan::scalar::ScalarMemory> {
290        let input = match self {
291            Self::CallArgument(index) => return item(memory, "args", index).scalar_mut(),
292            Self::ExecuteParameter(index) => return item(memory, "params", index).scalar_mut(),
293            _ => memory.field_mut("value0").as_mut().expect("mutation body"),
294        };
295        match self {
296            Self::Assignment(index) => item(input, "assignments", index)
297                .field_mut("value")
298                .as_mut()
299                .expect("assignment value")
300                .scalar_mut(),
301            Self::Predicate => input
302                .field_mut("predicate")
303                .as_mut()
304                .expect("mutation predicate")
305                .scalar_mut(),
306            Self::Returning(index) => item(input, "returning", index).scalar_mut(),
307            Self::InsertValue { row, column } => item(input, "rows", row).scalar_item_mut(column),
308            Self::ViewCheck(index) => item(input, "view_checks", index)
309                .field_mut("predicate")
310                .as_mut()
311                .expect("view check predicate")
312                .scalar_mut(),
313            Self::MergeJoin => input
314                .field_mut("join_condition")
315                .as_mut()
316                .expect("MERGE join")
317                .scalar_mut(),
318            Self::MergeCondition(index) => item(input, "when_clauses", index)
319                .field_mut("condition")
320                .as_mut()
321                .expect("MERGE condition")
322                .scalar_mut(),
323            Self::MergeValue { clause, value } => {
324                item(item(input, "when_clauses", clause), "values", value).scalar_mut()
325            }
326            Self::ConflictExpression(index) => item(
327                input.field_mut("on_conflict").as_mut().expect("conflict"),
328                "expressions",
329                index,
330            )
331            .scalar_mut(),
332            Self::ConflictInferencePredicate => input
333                .field_mut("on_conflict")
334                .as_mut()
335                .expect("conflict")
336                .field_mut("predicate")
337                .as_mut()
338                .expect("conflict inference predicate")
339                .scalar_mut(),
340            Self::ConflictPredicate => input
341                .field_mut("on_conflict")
342                .as_mut()
343                .expect("conflict")
344                .field_mut("action")
345                .as_mut()
346                .expect("conflict action")
347                .field_mut("predicate")
348                .as_mut()
349                .expect("conflict predicate")
350                .scalar_mut(),
351            Self::CallArgument(_) | Self::ExecuteParameter(_) => {
352                unreachable!("utility argument selected above")
353            }
354        }
355    }
356}
357
358fn item<'a>(memory: &'a mut RewriteMemory, name: &str, index: usize) -> &'a mut RewriteMemory {
359    memory
360        .field_mut(name)
361        .as_mut()
362        .expect("command vector")
363        .item_mut(index)
364        .as_mut()
365        .expect("command vector item")
366}
367
368#[cfg(test)]
369mod tests;