Skip to main content

uqa_sql/plan/scalar/owned/
selection.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Selected child rewrites retain parent metadata and transfer only constructor-owned buffers.
8
9use super::{children, OwnedScalarExpr, Result, ScalarExpr, ScalarMemory};
10use crate::schema::retention::CatalogRetentionError;
11use uqa_core::memory::ProductionControl;
12
13impl OwnedScalarExpr {
14    /// Remove validated call-argument markers by transferring their value child and immediately retiring marker metadata and containers.
15    pub fn into_call_argument(
16        mut self,
17        control: &ProductionControl<'_>,
18    ) -> std::result::Result<Self, crate::SQLError> {
19        self.assert_owner(control);
20        control.check()?;
21        crate::scalar_call_argument(&self)?;
22        while let ScalarExpr::Func { binding, args, .. } = &self.expression {
23            if !binding
24                .as_ref()
25                .and_then(|binding| binding.dispatch)
26                .is_some_and(crate::ast::FunctionDispatch::is_call_argument_marker)
27            {
28                break;
29            }
30            let index = args.len() - 1;
31            self = self.select_child(index);
32        }
33        control.check()?;
34        Ok(self)
35    }
36
37    /// Rewrite one child while borrowing its parent's metadata. The selected child slot contains a NULL placeholder during the callback; all other parent fields remain unchanged and read-only.
38    pub fn map_child_with_parent<E>(
39        mut self,
40        index: usize,
41        control: &ProductionControl<'_>,
42        map: impl FnOnce(&ScalarExpr, Self) -> std::result::Result<Self, E>,
43    ) -> std::result::Result<Self, E>
44    where
45        E: From<CatalogRetentionError>,
46    {
47        self.assert_owner(control);
48        control.check().map_err(CatalogRetentionError::from)?;
49        let child = self.take_child(index);
50        let replacement = map(&self.expression, child)?;
51        replacement.assert_owner(control);
52        control.check().map_err(CatalogRetentionError::from)?;
53        let Self { expression, memory } = replacement;
54        *children::get_mut(&mut self.expression, index).expect("scalar child index") = expression;
55        if let Some(parent) = &mut self.memory {
56            parent.children[index] = memory;
57        }
58        Ok(self)
59    }
60
61    /// Move a call's argument vector into an OR container while retaining its call metadata, ordering expressions and filter in the returned parent. The vector's exact constructor capacity transfers with it; no argument payload is copied.
62    pub fn take_call_arguments(mut self, control: &ProductionControl<'_>) -> Result<(Self, Self)> {
63        self.assert_owner(control);
64        control.check()?;
65        let ScalarExpr::Func { args, .. } = &mut self.expression else {
66            panic!("argument selection requires a function call");
67        };
68        let count = args.len();
69        let mut selected_memory = self.memory.as_ref().map(|parent| ScalarMemory {
70            direct: parent.direct.budget().empty_reservation(),
71            children: Vec::new(),
72        });
73        if let Some(selected) = &mut selected_memory {
74            selected.reserve_children(count)?;
75        }
76        let arguments = std::mem::take(args);
77        let selected = Self {
78            expression: ScalarExpr::Or(arguments),
79            memory: selected_memory,
80        };
81        let mut selected = selected;
82        if let (Some(parent), Some(output)) = (&mut self.memory, &mut selected.memory) {
83            let ScalarExpr::Or(arguments) = &selected.expression else {
84                unreachable!();
85            };
86            output.direct.absorb(
87                parent
88                    .direct
89                    .split(arguments.capacity() * size_of::<ScalarExpr>()),
90            );
91            for child in &mut parent.children[..count] {
92                output
93                    .push_child(child.take())
94                    .expect("admitted selected argument slot");
95            }
96            parent.children.rotate_left(count);
97            let remaining = parent.children.len() - count;
98            parent.children.truncate(remaining);
99        }
100        control.check()?;
101        Ok((self, selected))
102    }
103
104    /// Replace a call's argument vector with an independently owned AND/OR vector. The boolean container's children become call arguments without evaluation; the old argument storage is destroyed before its exact lease is released.
105    pub fn replace_call_arguments(
106        mut self,
107        replacement: Self,
108        control: &ProductionControl<'_>,
109    ) -> Result<Self> {
110        self.assert_owner(control);
111        replacement.assert_owner(control);
112        control.check()?;
113        let (ScalarExpr::And(items) | ScalarExpr::Or(items)) = &replacement.expression else {
114            panic!("argument replacement requires a boolean container");
115        };
116        let count = items.len();
117        let ScalarExpr::Func { args, .. } = &mut self.expression else {
118            panic!("argument replacement requires a function call");
119        };
120        let previous_count = args.len();
121        if let Some(parent) = &mut self.memory {
122            parent.reserve_children(count.saturating_sub(previous_count))?;
123        }
124        let previous_bytes = args.capacity() * size_of::<ScalarExpr>();
125        let Self { expression, memory } = replacement;
126        let (ScalarExpr::And(items) | ScalarExpr::Or(items)) = expression else {
127            unreachable!();
128        };
129        *args = items;
130        if let (Some(parent), Some(mut replacement)) = (&mut self.memory, memory) {
131            drop(parent.direct.split(previous_bytes));
132            for child in &mut parent.children[..previous_count] {
133                *child = None;
134            }
135            parent.children.rotate_left(previous_count);
136            let retained = parent.children.len() - previous_count;
137            parent.children.truncate(retained);
138            for child in &mut *replacement.children {
139                parent
140                    .push_child(child.take())
141                    .expect("admitted replacement argument slot");
142            }
143            parent.children.rotate_right(count);
144            let (direct, children) = replacement.into_parts();
145            drop(children);
146            parent.direct.absorb(direct);
147        }
148        control.check()?;
149        Ok(self)
150    }
151}
152
153#[cfg(test)]
154mod tests;