Skip to main content

uqa_sql/plan/scalar/owned/
edit.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Structural edits move child reservations with their slots and retire discarded payloads immediately.
8
9use super::{children, OwnedScalarExpr, Result, ScalarExpr};
10use uqa_core::{memory::ProductionControl, Value};
11
12impl OwnedScalarExpr {
13    /// Replace one immediate child and return the previous child with its complete independent owner. The parent retains the same box or vector slot; neither child is copied or implicitly discarded.
14    pub fn replace_child(
15        mut self,
16        index: usize,
17        replacement: Self,
18        control: &ProductionControl<'_>,
19    ) -> Result<(Self, Self)> {
20        self.assert_owner(control);
21        replacement.assert_owner(control);
22        control.check()?;
23        let previous = self.take_child(index);
24        let Self { expression, memory } = replacement;
25        *children::get_mut(&mut self.expression, index).expect("scalar child index") = expression;
26        if let Some(parent) = &mut self.memory {
27            parent.children[index] = memory;
28        }
29        control.check()?;
30        Ok((self, previous))
31    }
32
33    /// Exchange two immediate children without changing either container or payload ownership. Both indices use the same ordering as `map_child`.
34    pub fn swap_children(
35        mut self,
36        left: usize,
37        right: usize,
38        control: &ProductionControl<'_>,
39    ) -> Result<Self> {
40        self.assert_owner(control);
41        control.check()?;
42        let count = self.child_count();
43        assert!(left < count && right < count, "scalar child index");
44        if left != right {
45            let first = std::mem::replace(
46                children::get_mut(&mut self.expression, left).expect("scalar child index"),
47                ScalarExpr::Literal(Value::Null),
48            );
49            let second = std::mem::replace(
50                children::get_mut(&mut self.expression, right).expect("scalar child index"),
51                first,
52            );
53            *children::get_mut(&mut self.expression, left).expect("scalar child index") = second;
54            if let Some(memory) = &mut self.memory {
55                memory.children.swap(left, right);
56            }
57        }
58        control.check()?;
59        Ok(self)
60    }
61
62    /// Retain at most `count` arguments of a function call. Ordering expressions and the filter retain their original owners; argument and metadata capacities remain with the parent.
63    pub fn truncate_call_arguments(
64        mut self,
65        count: usize,
66        control: &ProductionControl<'_>,
67    ) -> Result<Self> {
68        self.assert_owner(control);
69        control.check()?;
70        let ScalarExpr::Func { args, .. } = &mut self.expression else {
71            panic!("function argument edit requires a function call");
72        };
73        let removed = count.min(args.len())..args.len();
74        args.truncate(count);
75        self.remove_child_owners(removed);
76        control.check()?;
77        Ok(self)
78    }
79
80    /// Retain at most `count` CASE arms. The base and ELSE remain in their original boxes, and the original arm vector retains its capacity.
81    pub fn truncate_case_arms(
82        mut self,
83        count: usize,
84        control: &ProductionControl<'_>,
85    ) -> Result<Self> {
86        self.assert_owner(control);
87        control.check()?;
88        let ScalarExpr::Case { base, when, .. } = &mut self.expression else {
89            panic!("CASE arm edit requires a CASE expression");
90        };
91        let base_count = usize::from(base.is_some());
92        let removed = base_count + 2 * count.min(when.len())..base_count + 2 * when.len();
93        when.truncate(count);
94        self.remove_child_owners(removed);
95        control.check()?;
96        Ok(self)
97    }
98
99    /// Retain at most `count` AND/OR children after selection or permutation. This storage operation performs no boolean simplification.
100    pub fn truncate_boolean_children(
101        mut self,
102        count: usize,
103        control: &ProductionControl<'_>,
104    ) -> Result<Self> {
105        self.assert_owner(control);
106        control.check()?;
107        let (ScalarExpr::And(items) | ScalarExpr::Or(items)) = &mut self.expression else {
108            panic!("boolean child edit requires AND or OR");
109        };
110        let removed = count.min(items.len())..items.len();
111        items.truncate(count);
112        self.remove_child_owners(removed);
113        control.check()?;
114        Ok(self)
115    }
116
117    /// Install an already owned CASE fallback. An existing ELSE box is reused; an absent box and its child-metadata slot are admitted before allocation. A failed edit destroys both private input owners.
118    pub fn set_case_else(
119        mut self,
120        replacement: Self,
121        control: &ProductionControl<'_>,
122    ) -> Result<Self> {
123        self.assert_owner(control);
124        replacement.assert_owner(control);
125        control.check()?;
126        let ScalarExpr::Case { else_branch, .. } = &mut self.expression else {
127            panic!("CASE fallback edit requires a CASE expression");
128        };
129        if let Some(branch) = else_branch {
130            let Self { expression, memory } = replacement;
131            **branch = expression;
132            if let Some(parent) = &mut self.memory {
133                *parent.children.last_mut().expect("CASE fallback owner") = memory;
134            }
135        } else {
136            if let Some(parent) = &mut self.memory {
137                parent.reserve_children(1)?;
138            }
139            let boxed = control.reserve(size_of::<ScalarExpr>())?;
140            let Self { expression, memory } = replacement;
141            *else_branch = Some(Box::new(expression));
142            if let Some(parent) = &mut self.memory {
143                parent
144                    .push_child(memory)
145                    .expect("CASE fallback slot was admitted");
146                parent
147                    .direct
148                    .absorb(boxed.expect("controlled CASE fallback box"));
149            }
150        }
151        control.check()?;
152        Ok(self)
153    }
154
155    // The corresponding IR children have already been destroyed. Move later owners over the removed range before retiring its reservations; do not shrink the parent's still-live metadata buffer.
156    pub(super) fn remove_child_owners(&mut self, removed: std::ops::Range<usize>) {
157        if let Some(memory) = &mut self.memory {
158            let count = removed.len();
159            let retained = memory.children.len() - count;
160            memory.children[removed.start..].rotate_left(count);
161            memory.children.truncate(retained);
162        }
163    }
164}