Skip to main content

uqa_sql/plan/scalar/owned/
call.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Call metadata replacement transfers children while old constructor storage remains owned.
8
9use super::{OwnedScalarExpr, Result, ScalarExpr, ScalarMemory};
10use crate::{
11    ast::FunctionBinding,
12    plan::scalar::resources::{Control, Lowering},
13    ScalarOrder,
14};
15use uqa_core::memory::{BudgetedVec, Produced, ProductionControl};
16
17impl OwnedScalarExpr {
18    /// Canonicalize a grouping identity's built-in spelling in its existing string buffer. Removing a prefix changes length, never retained capacity.
19    pub(crate) fn canonicalize_call_name(
20        mut self,
21        control: &ProductionControl<'_>,
22    ) -> Result<Self> {
23        self.assert_owner(control);
24        control.check()?;
25        let (ScalarExpr::Func { name, .. } | ScalarExpr::WindowCall { name, .. }) =
26            &mut self.expression
27        else {
28            panic!("call spelling requires a function or window call")
29        };
30        let mut start = 0;
31        while start < name.len() {
32            control.check()?;
33            let mut end = (start + 4096).min(name.len());
34            while !name.is_char_boundary(end) {
35                end -= 1;
36            }
37            name[start..end].make_ascii_lowercase();
38            start = end;
39        }
40        if name.starts_with("pg_catalog.") {
41            name.drain(.."pg_catalog.".len());
42        }
43        control.check()?;
44        Ok(self)
45    }
46
47    /// Preserve the parser's inline ordering-syntax identity without rebuilding any call storage.
48    pub fn set_call_order_syntax(
49        mut self,
50        syntax: crate::ast::FunctionOrderSyntax,
51        control: &ProductionControl<'_>,
52    ) -> Result<Self> {
53        self.assert_owner(control);
54        control.check()?;
55        let ScalarExpr::Func { order_syntax, .. } = &mut self.expression else {
56            panic!("ordering syntax requires a function call")
57        };
58        *order_syntax = syntax;
59        Ok(self)
60    }
61
62    /// Change an inline call dispatch without moving or replacing any allocating field.
63    pub fn set_call_dispatch(
64        mut self,
65        dispatch: Option<crate::ast::FunctionDispatch>,
66        control: &ProductionControl<'_>,
67    ) -> Result<Self> {
68        self.assert_owner(control);
69        control.check()?;
70        let ScalarExpr::Func {
71            binding: Some(binding),
72            ..
73        } = &mut self.expression
74        else {
75            panic!("dispatch mutation requires a bound function call")
76        };
77        binding.dispatch = dispatch;
78        Ok(self)
79    }
80
81    /// Replace a call's selected binding without changing its name, arguments, ordering or filter. The old metadata and containers remain owned until the replacement's admitted containers hold all surviving children.
82    pub fn replace_call_binding(
83        self,
84        binding: Option<Produced<FunctionBinding>>,
85        control: &ProductionControl<'_>,
86    ) -> Result<Self> {
87        let ScalarExpr::Func { name, .. } = &self.expression else {
88            panic!("binding replacement requires a function call");
89        };
90        let name = control.copy_text(name)?;
91        self.replace_call_metadata(name, binding, control)
92    }
93
94    /// Install an independently produced call name and binding. This storage operation retains scalar payload identity and performs no overload selection or expression evaluation.
95    pub fn replace_call_metadata(
96        mut self,
97        name: Produced<String>,
98        binding: Option<Produced<FunctionBinding>>,
99        control: &ProductionControl<'_>,
100    ) -> Result<Self> {
101        self.assert_owner(control);
102        control.check()?;
103        let ScalarExpr::Func {
104            args,
105            order_by,
106            filter,
107            distinct,
108            order_syntax,
109            ..
110        } = &self.expression
111        else {
112            panic!("metadata replacement requires a function call");
113        };
114        let (argument_count, order_count, has_filter, distinct, order_syntax) = (
115            args.len(),
116            order_by.len(),
117            filter.is_some(),
118            *distinct,
119            *order_syntax,
120        );
121        let mut lowering = Lowering {
122            control: control.budget().map(|_| Control::from_production(*control)),
123            owned_children: control.budget().map(BudgetedVec::new),
124        };
125        let (name, name_memory) = name.into_parts();
126        let (binding, binding_memory) = match binding {
127            Some(binding) => {
128                let (binding, memory) = binding.into_parts();
129                (Some(binding), memory)
130            }
131            None => (None, control.empty_reservation()),
132        };
133        let metadata = control.combine(name_memory, binding_memory);
134        if let Some(owner) = &mut lowering.control {
135            owner
136                .memory
137                .absorb(metadata.expect("admitted call metadata"));
138        }
139        let args = lowering.map(0..argument_count, |lowering, index| {
140            Self::attach_child(lowering, self.take_child(index))
141        })?;
142        let order_by = lowering.map(0..order_count, |lowering, index| {
143            let ScalarExpr::Func { order_by, .. } = &self.expression else {
144                unreachable!();
145            };
146            let (descending, nulls) = (order_by[index].descending, order_by[index].nulls);
147            Ok(ScalarOrder {
148                expr: Self::attach_child(lowering, self.take_child(argument_count + index))?,
149                descending,
150                nulls,
151            })
152        })?;
153        let filter = has_filter
154            .then(|| {
155                lowering.boxed(|lowering| {
156                    Self::attach_child(lowering, self.take_child(argument_count + order_count))
157                })
158            })
159            .transpose()?;
160        let output = Self {
161            expression: ScalarExpr::Func {
162                order_syntax,
163                name,
164                binding,
165                args,
166                distinct,
167                order_by,
168                filter,
169            },
170            memory: lowering.control.map(|control| {
171                ScalarMemory::from_parts(
172                    control.memory,
173                    lowering.owned_children.expect("mutable call construction"),
174                )
175            }),
176        };
177        drop(self);
178        control.check()?;
179        Ok(output)
180    }
181}