Skip to main content

uqa_sql/routines/invocation/
descriptions.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Successful routine descriptions belong to one immutable binding and catalog scope.
8
9use crate::{
10    assignment::routines::{
11        coerce_routine_value_from, RoutineValueContext, RoutineValueDescription,
12    },
13    ast::{ColumnType, FunctionBinding},
14    routines::SQLUserFunction,
15    schema::retention::CatalogRetentionError,
16    SQLError,
17};
18use std::sync::{Arc, OnceLock, Weak};
19use uqa_core::{
20    memory::{MemoryReservation, Produced, ProductionControl, ProductionVec},
21    Value, ValueRetentionError,
22};
23
24mod body;
25mod procedural;
26mod table;
27pub use procedural::ProceduralRoutineDescription;
28
29/// Identity of the native routine registry and type-resolution environment. Adapters must decline or replace it whenever a bound routine or type can resolve differently.
30#[derive(Clone, Default)]
31pub struct RoutineDescriptionScope(Arc<()>);
32
33impl RoutineDescriptionScope {
34    pub fn matches(&self, other: &Self) -> bool {
35        Arc::ptr_eq(&self.0, &other.0)
36    }
37}
38
39/// One optional description for an immutable prepared call, never one entry per input row.
40#[derive(Default)]
41pub struct RoutineCallDescriptions {
42    description: OnceLock<Box<RoutineCallDescription>>,
43}
44
45impl std::fmt::Debug for RoutineCallDescriptions {
46    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
47        formatter
48            .debug_struct("RoutineCallDescriptions")
49            .field("retained", &self.description.get().is_some())
50            .finish()
51    }
52}
53
54pub struct RoutineCallDescription {
55    scope: RoutineDescriptionScope,
56    binding: Produced<FunctionBinding>,
57    function: Weak<SQLUserFunction>,
58    sources: Produced<Vec<Option<ColumnType>>>,
59    arguments: Produced<Vec<OnceLock<Produced<RoutineValueDescription>>>>,
60    parameters: Produced<Vec<OnceLock<Produced<RoutineValueDescription>>>>,
61    body_parameters: Produced<Vec<OnceLock<Produced<ColumnType>>>>,
62    body_result: OnceLock<Box<body::ResultDescription>>,
63    table_result: OnceLock<Box<Produced<crate::routines::result_check::SQLFunctionResultLayout>>>,
64    procedural: OnceLock<Box<procedural::ProceduralSlots>>,
65    _memory: Option<MemoryReservation>,
66}
67
68#[derive(Clone, Copy)]
69pub struct RoutineConversionEnvironment<'a> {
70    pub values: &'a dyn RoutineValueContext,
71    pub scope: &'a dyn Fn() -> Option<RoutineDescriptionScope>,
72    pub control: ProductionControl<'a>,
73}
74
75impl RoutineCallDescriptions {
76    /// The entire binding and current scope must agree before any saved metadata is read.
77    pub fn get(
78        &self,
79        binding: &FunctionBinding,
80        scope: &RoutineDescriptionScope,
81    ) -> Option<&RoutineCallDescription> {
82        self.description
83            .get()
84            .filter(|saved| *saved.binding == *binding && saved.scope.matches(scope))
85            .map(Box::as_ref)
86    }
87
88    /// Retain only a successful bound selection. Optional allocation failure leaves the live path intact; cancellation and malformed metadata are still errors.
89    pub fn remember(
90        &self,
91        binding: &FunctionBinding,
92        function: &Arc<SQLUserFunction>,
93        sources: &[Option<ColumnType>],
94        scope: RoutineDescriptionScope,
95        control: &ProductionControl<'_>,
96    ) -> Result<(), SQLError> {
97        control.check()?;
98        if self.description.get().is_some() || !eligible(binding, sources.len()) {
99            return Ok(());
100        }
101        match RoutineCallDescription::new(binding, function, sources, scope, control) {
102            Ok(saved) => {
103                let _ = self.description.set(saved);
104                Ok(())
105            }
106            Err(CatalogRetentionError::Memory(_)) => Ok(()),
107            Err(error) => Err(error.into()),
108        }
109    }
110}
111
112fn eligible(binding: &FunctionBinding, count: usize) -> bool {
113    !binding.builtin
114        && binding.object_id.is_some()
115        && binding.invocation.as_ref().is_some_and(|invocation| {
116            invocation.argument_sources.len() == count
117                && invocation.argument_positions.len() == count
118                && invocation.argument_targets.len() == count
119                && invocation
120                    .argument_sources
121                    .iter()
122                    .all(|name| name.as_deref().is_none_or(fixed_name))
123                && invocation
124                    .argument_targets
125                    .iter()
126                    .all(|name| fixed_name(name))
127                && invocation
128                    .parameter_types
129                    .iter()
130                    .all(|name| fixed_name(name))
131        })
132}
133
134fn fixed_name(name: &str) -> bool {
135    crate::ast::UserTypeIdentity::parse(name).is_some()
136        || crate::parse_regtype_name(name)
137            .ok()
138            .flatten()
139            .is_some_and(|name| name.names.len() == 2)
140}
141
142fn conversion_slots<T>(
143    count: usize,
144    control: &ProductionControl<'_>,
145) -> Result<Produced<Vec<OnceLock<Produced<T>>>>, ValueRetentionError> {
146    let mut slots = ProductionVec::new(*control);
147    slots.reserve(count)?;
148    for _ in 0..count {
149        slots.push_produced(control.finish(OnceLock::new(), control.empty_reservation())?)?;
150    }
151    slots.finish()
152}
153
154impl RoutineCallDescription {
155    fn new(
156        binding: &FunctionBinding,
157        function: &Arc<SQLUserFunction>,
158        sources: &[Option<ColumnType>],
159        scope: RoutineDescriptionScope,
160        control: &ProductionControl<'_>,
161    ) -> Result<Box<Self>, CatalogRetentionError> {
162        let memory = control.reserve(std::mem::size_of::<Self>())?;
163        let binding = binding.clone_with_control(control)?;
164        let invocation = binding.invocation.as_ref().expect("eligible bound call");
165        let arguments = conversion_slots(invocation.argument_targets.len(), control)?;
166        let parameters = conversion_slots(invocation.parameter_types.len(), control)?;
167        let body_parameters = conversion_slots(invocation.parameter_types.len(), control)?;
168        let mut copied = ProductionVec::new(*control);
169        copied.reserve(sources.len())?;
170        for source in sources {
171            let (source, lease) = match source {
172                Some(source) => {
173                    let (source, lease) = source.clone_with_control(control)?.into_parts();
174                    (Some(source), lease)
175                }
176                None => (None, control.empty_reservation()),
177            };
178            copied.push_produced(control.finish(source, lease)?)?;
179        }
180        Ok(Box::new(Self {
181            scope,
182            binding,
183            function: Arc::downgrade(function),
184            sources: copied.finish()?,
185            arguments,
186            parameters,
187            body_parameters,
188            body_result: OnceLock::new(),
189            table_result: OnceLock::new(),
190            procedural: OnceLock::new(),
191            _memory: memory,
192        }))
193    }
194
195    pub fn function(&self) -> Option<Arc<SQLUserFunction>> {
196        self.function.upgrade()
197    }
198
199    pub fn sources(&self) -> &[Option<ColumnType>] {
200        &self.sources
201    }
202
203    pub fn is_current(&self, current: Option<&RoutineDescriptionScope>) -> bool {
204        current.is_some_and(|current| self.scope.matches(current))
205    }
206
207    /// Each source/target read follows preceding value callbacks, and successful conversions publish descriptions only if that scope is still current afterward.
208    pub fn coerce_argument(
209        &self,
210        index: usize,
211        value: &Value,
212        source: Option<&ColumnType>,
213        environment: RoutineConversionEnvironment<'_>,
214    ) -> Result<Value, SQLError> {
215        let invocation = self
216            .binding
217            .invocation
218            .as_ref()
219            .expect("retained bound call");
220        self.coerce(
221            &invocation.argument_targets[index],
222            &self.arguments[index],
223            value,
224            source,
225            environment,
226        )
227    }
228
229    pub fn coerce_parameter(
230        &self,
231        index: usize,
232        value: &Value,
233        source: Option<&ColumnType>,
234        environment: RoutineConversionEnvironment<'_>,
235    ) -> Result<Value, SQLError> {
236        let invocation = self
237            .binding
238            .invocation
239            .as_ref()
240            .expect("retained bound call");
241        self.coerce(
242            &invocation.parameter_types[index],
243            &self.parameters[index],
244            value,
245            source,
246            environment,
247        )
248    }
249
250    fn coerce(
251        &self,
252        name: &str,
253        slot: &OnceLock<Produced<RoutineValueDescription>>,
254        value: &Value,
255        source: Option<&ColumnType>,
256        environment: RoutineConversionEnvironment<'_>,
257    ) -> Result<Value, SQLError> {
258        let RoutineConversionEnvironment {
259            values: context,
260            scope,
261            control,
262        } = environment;
263        control.check()?;
264        if !self.is_current(scope().as_ref()) {
265            return coerce_routine_value_from(context, value, name, source);
266        }
267        if let Some(description) = slot.get() {
268            return description.coerce(context, value, source);
269        }
270        let Some(description) = RoutineValueDescription::resolve(context, name) else {
271            return crate::expr::cast_value(value, name);
272        };
273        let result = description.coerce(context, value, source)?;
274        if self.is_current(scope().as_ref()) {
275            match description.clone_with_control(&control) {
276                Ok(description) => {
277                    let _ = slot.set(description);
278                }
279                Err(ValueRetentionError::Memory(_)) => {}
280                Err(error) => return Err(error.into()),
281            }
282        }
283        Ok(result)
284    }
285}