Skip to main content

uqa_sql/plan/mutable/commands/
assignments.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Assignment bounds and values retain the traversal order of their independent scalar owners.
8
9use super::{
10    item, CommandPlan, MutableCommandPlan, OwnedScalarExpr, RewriteMemory, SQLError, ScalarExpr,
11};
12use crate::{
13    ast::{AssignmentStep, AssignmentTargets},
14    plan::{AssignmentPlan, ConflictActionPlan, MergeWhenPlan},
15};
16use uqa_core::{memory::ProductionControl, Value};
17
18#[derive(Clone, Copy, Debug)]
19pub enum CommandAssignmentSlot {
20    Update(usize),
21    Conflict(usize),
22    Merge { clause: usize, assignment: usize },
23}
24
25impl MutableCommandPlan {
26    /// Rewrite a selected INSERT target's bounds without moving its column name or the other targets.
27    pub fn map_insert_target(
28        mut self,
29        index: usize,
30        control: &ProductionControl<'_>,
31        mut map: impl FnMut(
32            OwnedScalarExpr,
33            &ProductionControl<'_>,
34        ) -> Result<OwnedScalarExpr, SQLError>,
35    ) -> Result<Self, SQLError> {
36        self.assert_owner(control);
37        control.check()?;
38        let CommandPlan::Insert(insert) = &mut self.command else {
39            return Err(SQLError::Internal("target bounds require INSERT".into()));
40        };
41        let memory = self.memory.as_mut().map(|memory| {
42            item(
43                memory.field_mut("value0").as_mut().expect("insert body"),
44                "columns",
45                index,
46            )
47        });
48        rewrite_target(
49            &mut insert.columns[index],
50            memory,
51            control,
52            &mut |expression| map(expression, control),
53        )?;
54        Ok(self)
55    }
56
57    /// Rewrite only the value of a selected assignment. Target bounds remain with their original execution boundary and are never visited by this operation.
58    pub fn map_assignment_value(
59        mut self,
60        slot: CommandAssignmentSlot,
61        control: &ProductionControl<'_>,
62        mut map: impl FnMut(OwnedScalarExpr) -> Result<OwnedScalarExpr, SQLError>,
63    ) -> Result<Self, SQLError> {
64        self.assert_owner(control);
65        control.check()?;
66        let assignment = slot.assignment_mut(&mut self.command);
67        let memory = self.memory.as_mut().map(|memory| {
68            slot.memory_mut(memory)
69                .field_mut("value")
70                .as_mut()
71                .expect("assignment value")
72                .scalar_mut()
73        });
74        rewrite_scalar(&mut assignment.value, memory, control, &mut map)?;
75        Ok(self)
76    }
77
78    /// Rewrite every bound followed by the value of one assignment, preserving grouped-target order and admitting each replacement independently.
79    pub fn map_assignment(
80        mut self,
81        slot: CommandAssignmentSlot,
82        control: &ProductionControl<'_>,
83        mut map: impl FnMut(OwnedScalarExpr) -> Result<OwnedScalarExpr, SQLError>,
84    ) -> Result<Self, SQLError> {
85        self.assert_owner(control);
86        control.check()?;
87        let assignment = slot.assignment_mut(&mut self.command);
88        let mut memory = self.memory.as_mut().map(|memory| slot.memory_mut(memory));
89        let target_memory = memory.as_mut().map(|memory| {
90            memory
91                .field_mut("target")
92                .as_mut()
93                .expect("assignment target")
94        });
95        match &mut assignment.target {
96            AssignmentTargets::Single(target) => {
97                rewrite_target(target, target_memory, control, &mut map)?;
98            }
99            AssignmentTargets::Multiple(group) => {
100                let mut target_memory = target_memory;
101                for (index, target) in group.targets.iter_mut().enumerate() {
102                    let memory = target_memory
103                        .as_mut()
104                        .map(|memory| item(memory, "targets", index));
105                    rewrite_target(target, memory, control, &mut map)?;
106                }
107            }
108        }
109        let memory = memory.map(|memory| {
110            memory
111                .field_mut("value")
112                .as_mut()
113                .expect("assignment value")
114                .scalar_mut()
115        });
116        rewrite_scalar(&mut assignment.value, memory, control, &mut map)?;
117        Ok(self)
118    }
119}
120
121fn rewrite_target(
122    target: &mut crate::ast::AssignmentTarget<ScalarExpr>,
123    mut memory: Option<&mut RewriteMemory>,
124    control: &ProductionControl<'_>,
125    map: &mut impl FnMut(OwnedScalarExpr) -> Result<OwnedScalarExpr, SQLError>,
126) -> Result<(), SQLError> {
127    for (index, step) in target.indirection.iter_mut().enumerate() {
128        let mut memory = memory
129            .as_mut()
130            .map(|memory| item(memory, "indirection", index));
131        match step {
132            AssignmentStep::Field(_) => {}
133            AssignmentStep::Index(expression) => rewrite_scalar(
134                expression,
135                memory.map(|memory| {
136                    memory
137                        .field_mut("index")
138                        .as_mut()
139                        .expect("index box")
140                        .scalar_mut()
141                }),
142                control,
143                map,
144            )?,
145            AssignmentStep::Slice { lower, upper } => {
146                if let Some(expression) = lower {
147                    rewrite_scalar(
148                        expression,
149                        memory.as_mut().map(|memory| {
150                            memory
151                                .field_mut("lower")
152                                .as_mut()
153                                .expect("lower bound")
154                                .scalar_mut()
155                        }),
156                        control,
157                        map,
158                    )?;
159                }
160                if let Some(expression) = upper {
161                    rewrite_scalar(
162                        expression,
163                        memory.map(|memory| {
164                            memory
165                                .field_mut("upper")
166                                .as_mut()
167                                .expect("upper bound")
168                                .scalar_mut()
169                        }),
170                        control,
171                        map,
172                    )?;
173                }
174            }
175        }
176    }
177    Ok(())
178}
179
180fn rewrite_scalar(
181    expression: &mut ScalarExpr,
182    mut memory: Option<&mut Option<crate::plan::scalar::ScalarMemory>>,
183    control: &ProductionControl<'_>,
184    map: &mut impl FnMut(OwnedScalarExpr) -> Result<OwnedScalarExpr, SQLError>,
185) -> Result<(), SQLError> {
186    control.check()?;
187    let retained = memory.as_mut().and_then(|memory| memory.take());
188    let input = OwnedScalarExpr::from_rewrite_parts(
189        std::mem::replace(expression, ScalarExpr::Literal(Value::Null)),
190        retained,
191    );
192    let output = input.rewrite(control, map)?;
193    let (output, owner) = output.into_rewrite_parts();
194    *expression = output;
195    if let Some(memory) = memory {
196        *memory = owner;
197    }
198    Ok(())
199}
200
201impl CommandAssignmentSlot {
202    fn assignment_mut(self, command: &mut CommandPlan) -> &mut AssignmentPlan {
203        match (self, command) {
204            (Self::Update(index), CommandPlan::Update(plan)) => &mut plan.assignments[index],
205            (Self::Conflict(index), CommandPlan::Insert(plan)) => {
206                let ConflictActionPlan::Update { assignments, .. } =
207                    &mut plan.on_conflict.as_mut().expect("conflict action").action
208                else {
209                    panic!("conflict has assignments");
210                };
211                &mut assignments[index]
212            }
213            (Self::Merge { clause, assignment }, CommandPlan::Merge(plan)) => {
214                match &mut plan.when_clauses[clause] {
215                    MergeWhenPlan::UpdateMatched { assignments, .. }
216                    | MergeWhenPlan::UpdateNotMatchedBySource { assignments, .. } => {
217                        &mut assignments[assignment]
218                    }
219                    _ => panic!("MERGE clause has assignments"),
220                }
221            }
222            _ => panic!("assignment selector matches command kind"),
223        }
224    }
225
226    fn memory_mut(self, memory: &mut RewriteMemory) -> &mut RewriteMemory {
227        let body = memory.field_mut("value0").as_mut().expect("mutation body");
228        match self {
229            Self::Update(index) => item(body, "assignments", index),
230            Self::Conflict(index) => item(
231                body.field_mut("on_conflict")
232                    .as_mut()
233                    .expect("conflict")
234                    .field_mut("action")
235                    .as_mut()
236                    .expect("conflict action"),
237                "assignments",
238                index,
239            ),
240            Self::Merge { clause, assignment } => item(
241                item(body, "when_clauses", clause),
242                "assignments",
243                assignment,
244            ),
245        }
246    }
247}
248
249impl MutableCommandPlan {
250    /// Retarget names independently of assignment bounds and values.
251    pub fn map_assignment_columns(
252        mut self,
253        slot: CommandAssignmentSlot,
254        control: &ProductionControl<'_>,
255        mut map: impl FnMut(&str) -> Result<uqa_core::memory::Produced<String>, SQLError>,
256    ) -> Result<Self, SQLError> {
257        self.assert_owner(control);
258        control.check()?;
259        let assignment = slot.assignment_mut(&mut self.command);
260        let memory = self.memory.as_mut().map(|memory| {
261            slot.memory_mut(memory)
262                .field_mut("target")
263                .as_mut()
264                .expect("assignment target")
265        });
266        match &mut assignment.target {
267            AssignmentTargets::Single(target) => rename_target(target, memory, control, &mut map)?,
268            AssignmentTargets::Multiple(group) => {
269                let mut memory = memory;
270                for (index, target) in group.targets.iter_mut().enumerate() {
271                    let memory = memory.as_mut().map(|memory| item(memory, "targets", index));
272                    rename_target(target, memory, control, &mut map)?;
273                }
274            }
275        }
276        Ok(self)
277    }
278}
279
280pub(super) fn rename_target(
281    target: &mut crate::ast::AssignmentTarget<ScalarExpr>,
282    memory: Option<&mut RewriteMemory>,
283    control: &ProductionControl<'_>,
284    map: &mut impl FnMut(&str) -> Result<uqa_core::memory::Produced<String>, SQLError>,
285) -> Result<(), SQLError> {
286    let name = map(&target.column)?;
287    let (name, reservation) = name.into_parts();
288    let replacement = control.finish(name, reservation)?;
289    let (name, reservation) = replacement.into_parts();
290    let previous_capacity = target.column.capacity();
291    target.column = name;
292    if let Some(memory) = memory {
293        let RewriteMemory::Fields { direct, .. } = memory else {
294            unreachable!("assignment target owner");
295        };
296        drop(direct.split(previous_capacity));
297        direct.absorb(reservation.expect("controlled target name"));
298    }
299    Ok(())
300}