uqa_sql/plan/mutable/commands/
namespaces.rs1use super::{CommandAssignmentSlot, CommandPlan, CommandScalarSlot, MutableCommandPlan, SQLError};
10use crate::plan::{OwnedScalarExpr, ScalarQueryArena};
11use uqa_core::memory::ProductionControl;
12
13impl MutableCommandPlan {
14 pub fn map_scalar_input(
15 mut self,
16 slot: CommandScalarSlot,
17 control: &ProductionControl<'_>,
18 map: impl FnOnce(OwnedScalarExpr, &mut ScalarQueryArena) -> Result<OwnedScalarExpr, SQLError>,
19 ) -> Result<Self, SQLError> {
20 self.assert_owner(control);
21 control.check()?;
22 let mut arena = self.take_mutation_arena()?;
23 self = self.map_scalar(slot, control, |input| map(input, &mut arena))?;
24 self.restore_mutation_arena(arena)?;
25 Ok(self)
26 }
27
28 pub fn map_assignment_input(
29 mut self,
30 slot: CommandAssignmentSlot,
31 control: &ProductionControl<'_>,
32 mut map: impl FnMut(OwnedScalarExpr, &mut ScalarQueryArena) -> Result<OwnedScalarExpr, SQLError>,
33 ) -> Result<Self, SQLError> {
34 self.assert_owner(control);
35 control.check()?;
36 let mut arena = self.take_mutation_arena()?;
37 self = self.map_assignment(slot, control, |input| map(input, &mut arena))?;
38 self.restore_mutation_arena(arena)?;
39 Ok(self)
40 }
41
42 pub fn map_mutation_arena(
43 mut self,
44 control: &ProductionControl<'_>,
45 map: impl FnOnce(&CommandPlan, &mut ScalarQueryArena) -> Result<(), SQLError>,
46 ) -> Result<Self, SQLError> {
47 self.assert_owner(control);
48 control.check()?;
49 let mut arena = self.take_mutation_arena()?;
50 map(&self.command, &mut arena)?;
51 control.check()?;
52 self.restore_mutation_arena(arena)?;
53 Ok(self)
54 }
55
56 pub(super) fn take_mutation_arena(&mut self) -> Result<ScalarQueryArena, SQLError> {
57 let queries = std::mem::take(mutation_queries(&mut self.command)?);
58 let memory = self.memory.as_mut().and_then(|memory| {
59 memory
60 .field_mut("value0")
61 .as_mut()
62 .expect("mutation body")
63 .field_mut("subqueries")
64 .take()
65 });
66 Ok(ScalarQueryArena { queries, memory })
67 }
68
69 pub(super) fn restore_mutation_arena(
70 &mut self,
71 arena: ScalarQueryArena,
72 ) -> Result<(), SQLError> {
73 *mutation_queries(&mut self.command)? = arena.queries;
74 if let Some(memory) = &mut self.memory {
75 *memory
76 .field_mut("value0")
77 .as_mut()
78 .expect("mutation body")
79 .field_mut("subqueries") = arena.memory;
80 }
81 Ok(())
82 }
83}
84
85fn mutation_queries(
86 command: &mut CommandPlan,
87) -> Result<&mut Vec<crate::plan::QueryPlan>, SQLError> {
88 match command {
89 CommandPlan::Insert(plan) => Ok(&mut plan.subqueries),
90 CommandPlan::Update(plan) => Ok(&mut plan.subqueries),
91 CommandPlan::Delete(plan) => Ok(&mut plan.subqueries),
92 CommandPlan::Merge(plan) => Ok(&mut plan.subqueries),
93 _ => Err(SQLError::Internal(
94 "scalar query namespace requires a mutation".into(),
95 )),
96 }
97}