uqa_sql/plan/mutable/commands/
metadata.rs1use super::{CommandPlan, MutableCommandPlan, RewriteMemory, SQLError};
10use crate::{catalog::roles::RoleReference, plan::copy::Copying};
11use uqa_core::memory::{BudgetedVec, Produced, ProductionControl};
12
13impl MutableCommandPlan {
14 pub fn set_target_privilege_subject(
15 mut self,
16 subject: Produced<RoleReference>,
17 control: &ProductionControl<'_>,
18 ) -> Result<Self, SQLError> {
19 self.assert_owner(control);
20 control.check()?;
21 let (subject, owner) = field_owner(subject, control)?;
22 let target = match &mut self.command {
23 CommandPlan::Insert(plan) => &mut plan.target_privilege_subject,
24 CommandPlan::Update(plan) => &mut plan.target_privilege_subject,
25 CommandPlan::Delete(plan) => &mut plan.target_privilege_subject,
26 CommandPlan::Merge(plan) => &mut plan.target_privilege_subject,
27 _ => {
28 return Err(SQLError::Internal(
29 "target authority requires a mutation".into(),
30 ))
31 }
32 };
33 *target = Some(subject);
34 if let Some(memory) = &mut self.memory {
35 *body(memory).field_mut("target_privilege_subject") = owner;
36 }
37 Ok(self)
38 }
39
40 pub fn retarget_mutation(
41 mut self,
42 target: Produced<String>,
43 include_descendants: bool,
44 control: &ProductionControl<'_>,
45 ) -> Result<Self, SQLError> {
46 self.assert_owner(control);
47 control.check()?;
48 let (target, owner) = field_owner(target, control)?;
49 let (name, descendants, field) = match &mut self.command {
50 CommandPlan::Insert(plan) => (&mut plan.table, &mut plan.include_descendants, "table"),
51 CommandPlan::Update(plan) => (&mut plan.table, &mut plan.include_descendants, "table"),
52 CommandPlan::Delete(plan) => (&mut plan.table, &mut plan.include_descendants, "table"),
53 CommandPlan::Merge(plan) => (&mut plan.target, &mut plan.include_descendants, "target"),
54 _ => return Err(SQLError::Internal("retargeting requires a mutation".into())),
55 };
56 *name = target;
57 *descendants = include_descendants;
58 if let Some(memory) = &mut self.memory {
59 *body(memory).field_mut(field) = owner;
60 }
61 Ok(self)
62 }
63
64 pub fn clear_mutation_ctes(
65 mut self,
66 control: &ProductionControl<'_>,
67 ) -> Result<Self, SQLError> {
68 self.assert_owner(control);
69 control.check()?;
70 let ctes = match &mut self.command {
71 CommandPlan::Insert(plan) => &mut plan.ctes,
72 CommandPlan::Update(plan) => &mut plan.ctes,
73 CommandPlan::Delete(plan) => &mut plan.ctes,
74 CommandPlan::Merge(plan) => &mut plan.ctes,
75 _ => {
76 return Err(SQLError::Internal(
77 "CTE retirement requires a mutation".into(),
78 ))
79 }
80 };
81 ctes.clear();
82 if let Some(memory) = &mut self.memory {
83 let RewriteMemory::Fields { fields, .. } =
84 body(memory).field_mut("ctes").as_mut().expect("CTE vector")
85 else {
86 unreachable!("CTE vector constructor")
87 };
88 fields.clear();
89 }
90 Ok(self)
91 }
92
93 pub fn record_view_rule_relation(
94 mut self,
95 relation: &str,
96 control: &ProductionControl<'_>,
97 ) -> Result<Self, SQLError> {
98 self.assert_owner(control);
99 control.check()?;
100 let relations = match &mut self.command {
101 CommandPlan::Insert(plan) => &mut plan.view_rule_relations,
102 CommandPlan::Update(plan) => &mut plan.view_rule_relations,
103 CommandPlan::Delete(plan) => &mut plan.view_rule_relations,
104 _ => {
105 return Err(SQLError::Internal(
106 "view rules require INSERT, UPDATE or DELETE".into(),
107 ))
108 }
109 };
110 if relations.iter().any(|name| name == relation) {
111 return Ok(self);
112 }
113 let old = std::mem::take(relations);
114 let memory = self
115 .memory
116 .as_mut()
117 .and_then(|memory| body(memory).field_mut("view_rule_relations").take());
118 let (names, owner) = append_rule_relation(old, memory, relation, control)?;
119 let relations = match &mut self.command {
120 CommandPlan::Insert(plan) => &mut plan.view_rule_relations,
121 CommandPlan::Update(plan) => &mut plan.view_rule_relations,
122 CommandPlan::Delete(plan) => &mut plan.view_rule_relations,
123 _ => unreachable!(),
124 };
125 *relations = names;
126 if let Some(memory) = &mut self.memory {
127 *body(memory).field_mut("view_rule_relations") = owner;
128 }
129 Ok(self)
130 }
131
132 pub fn preserve_view_rule_returning(
133 mut self,
134 relation: &str,
135 control: &ProductionControl<'_>,
136 ) -> Result<Self, SQLError> {
137 self.assert_owner(control);
138 control.check()?;
139 let (retained, qualifier, projections, aliases, queries) = match &mut self.command {
140 CommandPlan::Insert(plan) => (
141 &mut plan.view_rule_returning,
142 &plan.target_qualifier,
143 &plan.returning,
144 &plan.returning_aliases,
145 &plan.subqueries,
146 ),
147 CommandPlan::Update(plan) => (
148 &mut plan.view_rule_returning,
149 &plan.target_qualifier,
150 &plan.returning,
151 &plan.returning_aliases,
152 &plan.subqueries,
153 ),
154 CommandPlan::Delete(plan) => (
155 &mut plan.view_rule_returning,
156 &plan.target_qualifier,
157 &plan.returning,
158 &plan.returning_aliases,
159 &plan.subqueries,
160 ),
161 _ => {
162 return Err(SQLError::Internal(
163 "view rules require INSERT, UPDATE or DELETE".into(),
164 ))
165 }
166 };
167 if retained.is_some() {
168 return Ok(self);
169 }
170 let (returning, owner) = if let Some(mut copying) = Copying::for_rewrite(*control) {
171 let returning = copying.rule_returning_inputs(
172 relation,
173 qualifier,
174 projections,
175 aliases,
176 queries,
177 )?;
178 (returning, Some(copying.into_rewrite_memory()))
179 } else {
180 (
181 crate::plan::ViewRuleReturningPlan {
182 relation: relation.to_owned(),
183 target_qualifier: qualifier.clone(),
184 returning: projections.clone(),
185 aliases: aliases.clone(),
186 subqueries: queries.clone(),
187 },
188 None,
189 )
190 };
191 *retained = Some(returning);
192 if let Some(memory) = &mut self.memory {
193 *body(memory).field_mut("view_rule_returning") = owner;
194 }
195 control.check()?;
196 Ok(self)
197 }
198}
199
200fn body(memory: &mut RewriteMemory) -> &mut RewriteMemory {
201 memory.field_mut("value0").as_mut().expect("mutation body")
202}
203
204fn field_owner<T>(
205 value: Produced<T>,
206 control: &ProductionControl<'_>,
207) -> Result<(T, Option<RewriteMemory>), SQLError> {
208 let (value, owner) = value.into_parts();
209 let (value, owner) = control.finish(value, owner)?.into_parts();
210 Ok((
211 value,
212 owner.map(|direct| RewriteMemory::Fields {
213 fields: BudgetedVec::new(direct.budget()),
214 direct,
215 }),
216 ))
217}
218
219fn append_rule_relation(
220 values: Vec<String>,
221 owner: Option<crate::plan::mutable::memory::RewriteMemory>,
222 relation: &str,
223 control: &uqa_core::memory::ProductionControl<'_>,
224) -> Result<(Vec<String>, Option<RewriteMemory>), SQLError> {
225 let Some(mut copying) = Copying::for_rewrite(*control) else {
226 let mut values = values;
227 values.push(relation.to_owned());
228 return Ok((values, None));
229 };
230 let mut previous = RelationNames {
231 values: values.into_iter(),
232 memory: owner.expect("rule relation vector owner"),
233 index: 0,
234 };
235 let mut new = Some(control.copy_text(relation)?);
236 let count = previous.values.len();
237 let total = count
238 .checked_add(1)
239 .ok_or_else(|| SQLError::Internal("rule relation count overflow".into()))?;
240 let items = (0..total).map(|index| {
241 if index == count {
242 new.take().expect("appended relation")
243 } else {
244 previous.take_name()
245 }
246 });
247 let values = copying.map(items, |copying, value| Ok(copying.take(value)))?;
248 drop(previous);
249 Ok((values, Some(copying.into_rewrite_memory())))
250}
251
252struct RelationNames {
253 values: std::vec::IntoIter<String>,
254 memory: RewriteMemory,
255 index: usize,
256}
257
258impl RelationNames {
259 fn take_name(&mut self) -> Produced<String> {
260 let value = self.values.next().expect("original relation");
261 let memory = self
262 .memory
263 .item_mut(self.index)
264 .take()
265 .expect("rule relation name")
266 .into_reservation()
267 .expect("rule relation payload owner");
268 self.index += 1;
269 Produced::from(uqa_core::memory::Budgeted::new(value, memory))
270 }
271}