Skip to main content

uqa_sql/plan/mutable/commands/
children.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Command children retain their enclosing command boxes and local query arenas.
8
9use super::super::{sources::empty_source, MutableSourcePlan};
10use super::{item, CommandPlan, MutableCommandPlan, MutableQueryPlan, RewriteMemory, SQLError};
11use crate::plan::QueryPlan;
12use uqa_core::memory::ProductionControl;
13
14#[derive(Clone, Copy, Debug)]
15pub enum CommandQuerySlot {
16    Body,
17    InsertSource,
18    Subquery(usize),
19    CallArgumentSubquery { argument: usize, query: usize },
20    ExecuteParameterSubquery { parameter: usize, query: usize },
21}
22
23impl MutableCommandPlan {
24    pub fn map_query_child(
25        self,
26        slot: CommandQuerySlot,
27        control: &ProductionControl<'_>,
28        map: impl FnOnce(MutableQueryPlan) -> Result<MutableQueryPlan, SQLError>,
29    ) -> Result<Self, SQLError> {
30        self.map_query_child_with_parent(slot, control, |_, child| map(child))
31    }
32
33    /// Rewrite a command-owned query while observing the command's unchanged namespace. The selected query temporarily becomes empty in its original container.
34    pub fn map_query_child_with_parent(
35        mut self,
36        slot: CommandQuerySlot,
37        control: &ProductionControl<'_>,
38        map: impl FnOnce(&CommandPlan, MutableQueryPlan) -> Result<MutableQueryPlan, SQLError>,
39    ) -> Result<Self, SQLError> {
40        self.assert_owner(control);
41        control.check()?;
42        let Some(query) = slot.query_mut(&mut self.command) else {
43            return Ok(self);
44        };
45        let input = MutableQueryPlan {
46            query: std::mem::replace(query, super::super::queries::empty_query()),
47            memory: self
48                .memory
49                .as_mut()
50                .and_then(|memory| slot.memory_mut(memory).take()),
51        };
52        let output = map(&self.command, input)?;
53        output.assert_owner(control);
54        control.check()?;
55        *slot
56            .query_mut(&mut self.command)
57            .expect("original command query") = output.query;
58        if let Some(memory) = &mut self.memory {
59            *slot.memory_mut(memory) = output.memory;
60        }
61        Ok(self)
62    }
63
64    pub fn map_source(
65        self,
66        control: &ProductionControl<'_>,
67        map: impl FnOnce(MutableSourcePlan) -> Result<MutableSourcePlan, SQLError>,
68    ) -> Result<Self, SQLError> {
69        self.map_source_with_parent(control, |_, source| map(source))
70    }
71
72    /// Rewrite UPDATE/DELETE/MERGE's source without copying its command-owned box or scalar siblings.
73    pub fn map_source_with_parent(
74        mut self,
75        control: &ProductionControl<'_>,
76        map: impl FnOnce(&CommandPlan, MutableSourcePlan) -> Result<MutableSourcePlan, SQLError>,
77    ) -> Result<Self, SQLError> {
78        self.assert_owner(control);
79        control.check()?;
80        let Some(source) = self.command.source_input_mut() else {
81            return Ok(self);
82        };
83        let source = std::mem::replace(source, empty_source());
84        let memory = self
85            .memory
86            .as_mut()
87            .and_then(|memory| source_memory(memory).take());
88        let output = map(&self.command, MutableSourcePlan { source, memory })?;
89        output.assert_owner(control);
90        control.check()?;
91        *self
92            .command
93            .source_input_mut()
94            .expect("original command source") = output.source;
95        if let Some(memory) = &mut self.memory {
96            *source_memory(memory) = output.memory;
97        }
98        Ok(self)
99    }
100}
101
102impl CommandQuerySlot {
103    pub(in crate::plan::mutable) fn query_mut(
104        self,
105        command: &mut CommandPlan,
106    ) -> Option<&mut QueryPlan> {
107        match (self, command) {
108            (
109                Self::Body,
110                CommandPlan::DeclareCursor { query, .. }
111                | CommandPlan::CreateTableAs { query, .. }
112                | CommandPlan::CreateMaterializedView { query, .. }
113                | CommandPlan::CreateView { query, .. },
114            ) => Some(query),
115            (Self::InsertSource, CommandPlan::Insert(plan)) => plan.source.as_deref_mut(),
116            (Self::Subquery(index), CommandPlan::Insert(plan)) => Some(&mut plan.subqueries[index]),
117            (Self::Subquery(index), CommandPlan::Update(plan)) => Some(&mut plan.subqueries[index]),
118            (Self::Subquery(index), CommandPlan::Delete(plan)) => Some(&mut plan.subqueries[index]),
119            (Self::Subquery(index), CommandPlan::Merge(plan)) => Some(&mut plan.subqueries[index]),
120            (Self::CallArgumentSubquery { argument, query }, CommandPlan::Call { args, .. }) => {
121                Some(&mut args[argument].subqueries[query])
122            }
123            (
124                Self::ExecuteParameterSubquery { parameter, query },
125                CommandPlan::Execute { params, .. },
126            ) => Some(&mut params[parameter].subqueries[query]),
127            _ => panic!("command query selector matches its command kind"),
128        }
129    }
130
131    pub(in crate::plan::mutable) fn memory_mut(
132        self,
133        memory: &mut RewriteMemory,
134    ) -> &mut Option<RewriteMemory> {
135        let field = match self {
136            Self::Body => memory
137                .field_mut("query")
138                .as_mut()
139                .expect("command query body"),
140            Self::InsertSource => memory
141                .field_mut("value0")
142                .as_mut()
143                .expect("INSERT body")
144                .field_mut("source")
145                .as_mut()
146                .expect("INSERT source"),
147            Self::Subquery(index) => item(
148                memory.field_mut("value0").as_mut().expect("mutation body"),
149                "subqueries",
150                index,
151            ),
152            Self::CallArgumentSubquery { argument, query } => {
153                item(item(memory, "args", argument), "subqueries", query)
154            }
155            Self::ExecuteParameterSubquery { parameter, query } => {
156                item(item(memory, "params", parameter), "subqueries", query)
157            }
158        };
159        field.field_mut("query")
160    }
161}
162
163pub(in crate::plan::mutable) fn source_memory(
164    memory: &mut RewriteMemory,
165) -> &mut Option<RewriteMemory> {
166    memory
167        .field_mut("value0")
168        .as_mut()
169        .expect("mutation body")
170        .field_mut("source")
171        .as_mut()
172        .expect("mutation source box")
173        .field_mut("source")
174}