Skip to main content

uqa_sql/plan/mutable/commands/
insert.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! INSERT input edits retain the command's query box and move VALUES payloads into their new relational owner.
8
9use super::{CommandPlan, MutableCommandPlan, MutableQueryPlan, RewriteMemory, SQLError};
10use crate::plan::{copy::Copying, InsertPlan, QueryPlan, RelationalPlan, RuleValuesInput};
11use uqa_core::memory::{BudgetedVec, Produced, ProductionControl};
12
13impl InsertPlan {
14    /// Copy one rule relation without a source or nested view schedule. The first VALUES layer alone retains rows; later layers receive an independently owned input query.
15    pub fn copy_rule_layer_for_rewrite(
16        &self,
17        layer: Option<&crate::plan::ViewRuleInsertPlan>,
18        rows: bool,
19        control: &ProductionControl<'_>,
20    ) -> Result<MutableCommandPlan, SQLError> {
21        control.check()?;
22        if let Some(mut copying) = Copying::for_rewrite(*control) {
23            let command = copying.insert_rule_layer_command(self, layer, rows)?;
24            return Ok(MutableCommandPlan::from_rewrite_parts(
25                command,
26                Some(copying.into_rewrite_memory()),
27            ));
28        }
29        let mut plan = self.clone();
30        plan.source = None;
31        if !rows {
32            plan.rows.clear();
33        }
34        plan.view_rule_insert_plans.clear();
35        plan.view_rule_relations.clear();
36        if let Some(layer) = layer {
37            plan.table.clone_from(&layer.relation);
38            plan.target_qualifier.clone_from(&layer.relation);
39            plan.columns = layer
40                .supplied_columns
41                .iter()
42                .zip(&self.columns)
43                .map(|(name, target)| {
44                    let mut target = target.clone();
45                    target.column.clone_from(name);
46                    target
47                })
48                .collect();
49            plan.returning.clear();
50            if let Some(returning) = self
51                .view_rule_returning
52                .as_ref()
53                .filter(|returning| returning.relation == layer.relation)
54            {
55                plan.target_qualifier
56                    .clone_from(&returning.target_qualifier);
57                plan.returning.clone_from(&returning.returning);
58                plan.returning_aliases.clone_from(&returning.aliases);
59                plan.subqueries.clone_from(&returning.subqueries);
60            }
61        }
62        Ok(MutableCommandPlan::from_rewrite_parts(
63            CommandPlan::Insert(Box::new(plan)),
64            None,
65        ))
66    }
67}
68
69impl MutableCommandPlan {
70    pub fn map_insert_source(
71        mut self,
72        control: &ProductionControl<'_>,
73        map: impl FnOnce(&InsertPlan, Option<MutableQueryPlan>) -> Result<MutableQueryPlan, SQLError>,
74    ) -> Result<Self, SQLError> {
75        self.assert_owner(control);
76        control.check()?;
77        let CommandPlan::Insert(plan) = &mut self.command else {
78            return Err(SQLError::Internal(
79                "INSERT source edit requires INSERT".into(),
80            ));
81        };
82        let source = plan.source.as_mut().map(|query| MutableQueryPlan {
83            query: std::mem::replace(query.as_mut(), super::super::queries::empty_query()),
84            memory: self.memory.as_mut().and_then(|memory| {
85                body(memory)
86                    .field_mut("source")
87                    .as_mut()
88                    .expect("INSERT source box")
89                    .field_mut("query")
90                    .take()
91            }),
92        });
93        let query = map(plan, source)?;
94        query.assert_owner(control);
95        control.check()?;
96        if let Some(source) = &mut plan.source {
97            **source = query.query;
98            if let Some(memory) = &mut self.memory {
99                *body(memory)
100                    .field_mut("source")
101                    .as_mut()
102                    .expect("INSERT source box")
103                    .field_mut("query") = query.memory;
104            }
105        } else {
106            let (source, memory) = if let Some(mut copying) = Copying::for_rewrite(*control) {
107                let source = copying.boxed_query(query)?;
108                (source, Some(copying.into_rewrite_memory()))
109            } else {
110                (Box::new(query.query), None)
111            };
112            plan.source = Some(source);
113            if let Some(owner) = &mut self.memory {
114                *body(owner).field_mut("source") = memory;
115            }
116        }
117        Ok(self)
118    }
119
120    pub fn set_implicit_insert_columns<'a>(
121        mut self,
122        names: impl ExactSizeIterator<Item = &'a str>,
123        control: &ProductionControl<'_>,
124    ) -> Result<Self, SQLError> {
125        self.assert_owner(control);
126        control.check()?;
127        let CommandPlan::Insert(plan) = &mut self.command else {
128            return Err(SQLError::Internal("implicit columns require INSERT".into()));
129        };
130        if !plan.columns.is_empty() {
131            return Ok(self);
132        }
133        let (columns, memory) = if let Some(mut copying) = Copying::for_rewrite(*control) {
134            let columns = copying.implicit_insert_columns(names)?;
135            (columns, Some(copying.into_rewrite_memory()))
136        } else {
137            (
138                names
139                    .map(|name| crate::ast::AssignmentTarget::from(name.to_owned()))
140                    .collect(),
141                None,
142            )
143        };
144        plan.columns = columns;
145        if let Some(owner) = &mut self.memory {
146            *body(owner).field_mut("columns") = memory;
147        }
148        Ok(self)
149    }
150
151    pub fn set_rule_values_input(
152        mut self,
153        input: Produced<RuleValuesInput>,
154        control: &ProductionControl<'_>,
155    ) -> Result<Self, SQLError> {
156        self.assert_owner(control);
157        control.check()?;
158        let CommandPlan::Insert(plan) = &mut self.command else {
159            return Err(SQLError::Internal(
160                "VALUES provenance requires INSERT".into(),
161            ));
162        };
163        let (input, memory) = input.into_parts();
164        let (input, memory) = control.finish(input, memory)?.into_parts();
165        plan.rule_values_input = Some(input);
166        if let Some(owner) = &mut self.memory {
167            *body(owner).field_mut("rule_values_input") =
168                memory.map(|direct| RewriteMemory::Fields {
169                    fields: BudgetedVec::new(direct.budget()),
170                    direct,
171                });
172        }
173        Ok(self)
174    }
175
176    /// Keep selected target columns in their original buffer, moving each indirection owner with its name and retiring only removed payloads.
177    pub fn retain_insert_columns(
178        mut self,
179        control: &ProductionControl<'_>,
180        mut keep: impl FnMut(
181            usize,
182            &crate::ast::AssignmentTarget<crate::ScalarExpr>,
183        ) -> Result<bool, SQLError>,
184    ) -> Result<Self, SQLError> {
185        self.assert_owner(control);
186        control.check()?;
187        let CommandPlan::Insert(plan) = &mut self.command else {
188            return Err(SQLError::Internal(
189                "target column retention requires INSERT".into(),
190            ));
191        };
192        let mut fields = self.memory.as_mut().map(|memory| {
193            match body(memory)
194                .field_mut("columns")
195                .as_mut()
196                .expect("INSERT column vector")
197            {
198                RewriteMemory::Fields { fields, .. } => fields,
199                RewriteMemory::Scalar(_) | RewriteMemory::Scalars { .. } => {
200                    unreachable!("INSERT column vector owner")
201                }
202            }
203        });
204        let mut retained = 0;
205        for index in 0..plan.columns.len() {
206            control.check()?;
207            if keep(index, &plan.columns[index])? {
208                plan.columns.swap(retained, index);
209                if let Some(fields) = &mut fields {
210                    fields.swap(retained, index);
211                }
212                retained += 1;
213            }
214        }
215        plan.columns.truncate(retained);
216        if let Some(fields) = fields {
217            fields.truncate(retained);
218        }
219        control.check()?;
220        Ok(self)
221    }
222
223    /// VALUES leave the command without a payload copy. The command retains its own scalar-query namespace for RETURNING and assignment targets; the new query admits its independent namespace copy.
224    pub fn take_insert_rows_query(
225        mut self,
226        control: &ProductionControl<'_>,
227    ) -> Result<(Self, MutableQueryPlan), SQLError> {
228        self.assert_owner(control);
229        control.check()?;
230        let CommandPlan::Insert(plan) = &mut self.command else {
231            return Err(SQLError::Internal(
232                "VALUES extraction requires INSERT".into(),
233            ));
234        };
235        let rows = super::super::values::OwnedRows {
236            rows: std::mem::take(&mut plan.rows),
237            memory: self
238                .memory
239                .as_mut()
240                .and_then(|memory| body(memory).field_mut("rows").take()),
241        };
242        let query = if let Some(mut copying) = Copying::for_rewrite(*control) {
243            let query =
244                copying.insert_values_query(rows, &plan.subqueries, plan.relations_bound)?;
245            MutableQueryPlan::from_rewrite_parts(query, Some(copying.into_rewrite_memory()))
246        } else {
247            MutableQueryPlan::from_rewrite_parts(
248                QueryPlan {
249                    analyzed_output: None,
250                    analyzed_source: None,
251                    analyzed_grouping: None,
252                    relation_privilege_subject: None,
253                    relations_bound: plan.relations_bound,
254                    ctes: Vec::new(),
255                    root: RelationalPlan::Values {
256                        rows: rows.rows,
257                        subqueries: plan.subqueries.clone(),
258                    },
259                },
260                None,
261            )
262        };
263        Ok((self, query))
264    }
265}
266
267fn body(memory: &mut RewriteMemory) -> &mut RewriteMemory {
268    memory.field_mut("value0").as_mut().expect("INSERT body")
269}