Skip to main content

uqa_sql/plan/mutable/commands/
rule_inputs.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Rule input retirement removes data before its constructor ownership and moves surviving assignment targets unchanged.
8
9use super::{CommandPlan, MutableCommandPlan, RewriteMemory, SQLError};
10use crate::{
11    ast::{AssignmentTarget, AssignmentTargets},
12    plan::{AssignmentPlan, ScalarExpr},
13    production::Buffer,
14};
15use uqa_core::{memory::ProductionControl, Value};
16
17pub(crate) struct OwnedAssignment {
18    pub(crate) value: AssignmentPlan,
19    pub(crate) memory: Option<RewriteMemory>,
20}
21pub(crate) struct OwnedTarget {
22    pub(crate) value: AssignmentTarget<ScalarExpr>,
23    pub(crate) memory: Option<RewriteMemory>,
24}
25struct Assignments {
26    values: std::vec::IntoIter<AssignmentPlan>,
27    memory: Option<RewriteMemory>,
28    index: usize,
29}
30impl Iterator for Assignments {
31    type Item = OwnedAssignment;
32    fn next(&mut self) -> Option<Self::Item> {
33        let value = self.values.next()?;
34        let memory = self
35            .memory
36            .as_mut()
37            .and_then(|memory| memory.item_mut(self.index).take());
38        self.index += 1;
39        Some(OwnedAssignment { value, memory })
40    }
41}
42struct Targets {
43    values: std::vec::IntoIter<AssignmentTarget<ScalarExpr>>,
44    _positions: Vec<usize>,
45    memory: Option<RewriteMemory>,
46    index: usize,
47}
48impl Iterator for Targets {
49    type Item = OwnedTarget;
50    fn next(&mut self) -> Option<Self::Item> {
51        let value = self.values.next()?;
52        let memory = self.memory.as_mut().and_then(|memory| {
53            memory
54                .field_mut("targets")
55                .as_mut()
56                .expect("group targets")
57                .item_mut(self.index)
58                .take()
59        });
60        self.index += 1;
61        Some(OwnedTarget { value, memory })
62    }
63}
64
65impl MutableCommandPlan {
66    /// Remove a suppressed mutation's row source and query dependencies while retaining the capacities of cleared inline vectors.
67    pub fn discard_rule_rows(mut self, control: &ProductionControl<'_>) -> Result<Self, SQLError> {
68        self.assert_owner(control);
69        control.check()?;
70        let body = self
71            .memory
72            .as_mut()
73            .map(|memory| memory.field_mut("value0").as_mut().expect("mutation body"));
74        match &mut self.command {
75            CommandPlan::Insert(plan) => {
76                plan.source = None;
77                plan.ctes.clear();
78                plan.subqueries.clear();
79                if let Some(body) = body {
80                    *body.field_mut("source") = None;
81                    clear_items(body, "ctes");
82                    clear_items(body, "subqueries");
83                }
84            }
85            CommandPlan::Update(plan) => {
86                plan.source = None;
87                plan.predicate = None;
88                plan.ctes.clear();
89                plan.subqueries.clear();
90                if let Some(body) = body {
91                    *body.field_mut("source") = None;
92                    *body.field_mut("predicate") = None;
93                    clear_items(body, "ctes");
94                    clear_items(body, "subqueries");
95                }
96            }
97            CommandPlan::Delete(plan) => {
98                plan.source = None;
99                plan.predicate = None;
100                plan.ctes.clear();
101                plan.subqueries.clear();
102                if let Some(body) = body {
103                    *body.field_mut("source") = None;
104                    *body.field_mut("predicate") = None;
105                    clear_items(body, "ctes");
106                    clear_items(body, "subqueries");
107                }
108            }
109            _ => {
110                return Err(SQLError::Internal(
111                    "rule row retirement requires INSERT, UPDATE or DELETE".into(),
112                ))
113            }
114        }
115        Ok(self)
116    }
117
118    /// Split wholly unused grouped assignments into their surviving single target descriptors and replace every discarded bound/value with NULL.
119    pub fn prune_rule_assignments(
120        mut self,
121        required: &dyn Fn(&str) -> bool,
122        control: &ProductionControl<'_>,
123    ) -> Result<Self, SQLError> {
124        self.assert_owner(control);
125        control.check()?;
126        let CommandPlan::Update(update) = &self.command else {
127            return Err(SQLError::Internal("rule assignments require UPDATE".into()));
128        };
129        let count = update.assignments.len();
130        for index in 0..count {
131            let CommandPlan::Update(update) = &self.command else {
132                unreachable!()
133            };
134            if update.assignments[index]
135                .target
136                .column_names()
137                .all(|name| !required(name))
138            {
139                self = self.map_assignment(
140                    super::CommandAssignmentSlot::Update(index),
141                    control,
142                    |old| {
143                        drop(old);
144                        Ok(ScalarExpr::Literal(Value::Null).copy_for_rewrite(control)?)
145                    },
146                )?;
147            }
148        }
149        let CommandPlan::Update(update) = &mut self.command else {
150            unreachable!()
151        };
152        let values = std::mem::take(&mut update.assignments);
153        let memory = self.memory.as_mut().and_then(|memory| {
154            memory
155                .field_mut("value0")
156                .as_mut()
157                .expect("update body")
158                .field_mut("assignments")
159                .take()
160        });
161        let values = Assignments {
162            values: values.into_iter(),
163            memory,
164            index: 0,
165        };
166        let mut output = Buffer::new(control);
167        for mut assignment in values {
168            control.check()?;
169            if assignment.value.target.column_names().any(required)
170                || matches!(assignment.value.target, AssignmentTargets::Single(_))
171            {
172                output.push(assignment, control)?;
173                continue;
174            }
175            let AssignmentTargets::Multiple(group) = assignment.value.target else {
176                unreachable!()
177            };
178            let memory = assignment
179                .memory
180                .as_mut()
181                .and_then(|memory| memory.field_mut("target").take());
182            let targets = Targets {
183                values: group.targets.into_iter(),
184                _positions: group.source_positions,
185                memory,
186                index: 0,
187            };
188            drop(assignment.value.value);
189            drop(assignment.memory);
190            for target in targets {
191                output.push(
192                    crate::plan::copy::null_assignment(target, control)?,
193                    control,
194                )?;
195            }
196        }
197        let (values, memory) = crate::plan::copy::assignment_vector(output.into_iter(), control)?;
198        let CommandPlan::Update(update) = &mut self.command else {
199            unreachable!()
200        };
201        update.assignments = values;
202        if let Some(owner) = &mut self.memory {
203            *owner
204                .field_mut("value0")
205                .as_mut()
206                .expect("update body")
207                .field_mut("assignments") = memory;
208        }
209        Ok(self)
210    }
211}
212fn clear_items(memory: &mut RewriteMemory, field: &str) {
213    let RewriteMemory::Fields { fields, .. } =
214        memory.field_mut(field).as_mut().expect("retained vector")
215    else {
216        unreachable!("vector owner")
217    };
218    fields.clear();
219}