Skip to main content

uqa_sql/routines/invocation/descriptions/
procedural.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Concrete procedural declarations retain metadata, never activation values.
8
9use super::{
10    conversion_slots, fixed_name, ColumnType, Produced, ProductionControl, RoutineCallDescription,
11    RoutineConversionEnvironment, RoutineValueDescription, SQLError, Value, ValueRetentionError,
12};
13use crate::plpgsql::{PLpgSQLCompilationIdentity, PLpgSQLFunction};
14use std::sync::OnceLock;
15use uqa_core::memory::MemoryReservation;
16
17pub(super) struct ProceduralSlots {
18    compilation: PLpgSQLCompilationIdentity,
19    datums: Produced<Vec<OnceLock<Produced<NamedDatum>>>>,
20    result: OnceLock<Produced<NamedDatum>>,
21    _memory: Option<MemoryReservation>,
22}
23
24struct NamedDatum {
25    name: Produced<String>,
26    ty: OnceLock<Produced<ColumnType>>,
27    conversion: OnceLock<Produced<RoutineValueDescription>>,
28}
29
30/// A view of one retained compilation's slots. Every read still checks the call's
31/// current scope and exact declared spelling; record fields do not use these slots.
32#[derive(Clone, Copy)]
33pub struct ProceduralRoutineDescription<'a> {
34    call: &'a RoutineCallDescription,
35    slots: &'a ProceduralSlots,
36}
37
38impl RoutineCallDescription {
39    /// Admit at most one compilation's datum table for this bound call. Resolving
40    /// declarations remains lazy at the interpreter's original read/conversion sites.
41    pub fn procedural_body(
42        &self,
43        parsed: &PLpgSQLFunction,
44        environment: RoutineConversionEnvironment<'_>,
45    ) -> Result<Option<ProceduralRoutineDescription<'_>>, SQLError> {
46        environment.control.check()?;
47        if !self.is_current((environment.scope)().as_ref()) {
48            return Ok(None);
49        }
50        if self.procedural.get().is_none() {
51            match ProceduralSlots::new(parsed, &environment.control) {
52                Ok(slots) => {
53                    let _ = self.procedural.set(slots);
54                }
55                Err(ValueRetentionError::Memory(_)) => return Ok(None),
56                Err(error) => return Err(error.into()),
57            }
58        }
59        Ok(self
60            .procedural
61            .get()
62            .filter(|slots| {
63                slots.compilation.same(&parsed.compilation)
64                    && slots.datums.len() == parsed.datums.len()
65            })
66            .map(|slots| ProceduralRoutineDescription { call: self, slots }))
67    }
68}
69
70impl ProceduralSlots {
71    fn new(
72        parsed: &PLpgSQLFunction,
73        control: &ProductionControl<'_>,
74    ) -> Result<Box<Self>, ValueRetentionError> {
75        let memory = control.reserve(size_of::<Self>())?;
76        let datums = conversion_slots(parsed.datums.len(), control)?;
77        Ok(Box::new(Self {
78            compilation: parsed.compilation.clone(),
79            datums,
80            result: OnceLock::new(),
81            _memory: memory,
82        }))
83    }
84}
85
86impl ProceduralRoutineDescription<'_> {
87    fn named<'a>(
88        &self,
89        slot: Option<&'a OnceLock<Produced<NamedDatum>>>,
90        name: &str,
91        environment: RoutineConversionEnvironment<'_>,
92    ) -> Result<Option<&'a NamedDatum>, SQLError> {
93        environment.control.check()?;
94        if !self.call.is_current((environment.scope)().as_ref()) {
95            return Ok(None);
96        }
97        let Some(slot) = slot else { return Ok(None) };
98        if let Some(saved) = slot.get() {
99            return Ok((saved.name.as_str() == name).then_some(saved));
100        }
101        if !fixed_name(name) {
102            return Ok(None);
103        }
104        match environment.control.copy_text(name) {
105            Ok(copied_name) => {
106                let saved = environment.control.finish(
107                    NamedDatum {
108                        name: copied_name,
109                        ty: OnceLock::new(),
110                        conversion: OnceLock::new(),
111                    },
112                    environment.control.empty_reservation(),
113                )?;
114                let _ = slot.set(saved);
115                Ok(slot
116                    .get()
117                    .filter(|saved| saved.name.as_str() == name)
118                    .map(|s| &**s))
119            }
120            Err(ValueRetentionError::Memory(_)) => Ok(None),
121            Err(error) => Err(error.into()),
122        }
123    }
124
125    /// Preserve the catalog-only declaration lookup and unresolved/pseudo-type
126    /// fallback. Successful concrete metadata is reusable only in the same scope.
127    pub fn datum_type(
128        &self,
129        index: usize,
130        name: &str,
131        environment: RoutineConversionEnvironment<'_>,
132    ) -> Result<Option<ColumnType>, SQLError> {
133        let saved = self.named(self.slots.datums.get(index), name, environment)?;
134        if let Some(ty) = saved.and_then(|saved| saved.ty.get()) {
135            return Ok(Some((**ty).clone()));
136        }
137        let ty = environment.values.catalog_column_type(name);
138        if self.call.is_current((environment.scope)().as_ref()) {
139            if let (Some(saved), Some(ty)) = (saved, &ty) {
140                match ty.clone_with_control(&environment.control) {
141                    Ok(copied) => {
142                        let _ = saved.ty.set(copied);
143                    }
144                    Err(ValueRetentionError::Memory(_)) => {}
145                    Err(error) => return Err(error.into()),
146                }
147            }
148        }
149        Ok(ty)
150    }
151
152    /// Produce the selected declaration in the invoking request while retaining the existing scope validation and advisory description cache.
153    pub fn datum_type_with_control(
154        &self,
155        index: usize,
156        name: &str,
157        environment: RoutineConversionEnvironment<'_>,
158        control: &ProductionControl<'_>,
159    ) -> Result<Option<Produced<ColumnType>>, SQLError> {
160        let environment = RoutineConversionEnvironment {
161            control: *control,
162            ..environment
163        };
164        let saved = self.named(self.slots.datums.get(index), name, environment)?;
165        if let Some(ty) = saved.and_then(|saved| saved.ty.get()) {
166            return Ok(Some(ty.clone_with_control(control)?));
167        }
168        let ty = environment
169            .values
170            .catalog_column_type_with_control(name, control)?;
171        if self.call.is_current((environment.scope)().as_ref()) {
172            if let (Some(saved), Some(ty)) = (saved, &ty) {
173                match ty.clone_with_control(control) {
174                    Ok(copied) => {
175                        let _ = saved.ty.set(copied);
176                    }
177                    Err(ValueRetentionError::Memory(_)) => {}
178                    Err(error) => return Err(error.into()),
179                }
180            }
181        }
182        Ok(ty)
183    }
184
185    /// Declaration initialization and assignment share the original per-value
186    /// conversion kernel; each callback and domain predicate still executes.
187    pub fn coerce_datum(
188        &self,
189        index: usize,
190        name: &str,
191        value: &Value,
192        source: Option<&ColumnType>,
193        environment: RoutineConversionEnvironment<'_>,
194    ) -> Result<Value, SQLError> {
195        self.coerce(
196            self.slots.datums.get(index),
197            name,
198            value,
199            source,
200            environment,
201        )
202    }
203
204    pub fn coerce_result(
205        &self,
206        name: &str,
207        value: &Value,
208        source: Option<&ColumnType>,
209        environment: RoutineConversionEnvironment<'_>,
210    ) -> Result<Value, SQLError> {
211        self.coerce(Some(&self.slots.result), name, value, source, environment)
212    }
213
214    fn coerce(
215        &self,
216        slot: Option<&OnceLock<Produced<NamedDatum>>>,
217        name: &str,
218        value: &Value,
219        source: Option<&ColumnType>,
220        environment: RoutineConversionEnvironment<'_>,
221    ) -> Result<Value, SQLError> {
222        match self.named(slot, name, environment)? {
223            Some(saved) => self
224                .call
225                .coerce(name, &saved.conversion, value, source, environment),
226            None => crate::assignment::routines::coerce_routine_value_from(
227                environment.values,
228                value,
229                name,
230                source,
231            ),
232        }
233    }
234}