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    /// Declaration initialization and assignment share the original per-value
153    /// conversion kernel; each callback and domain predicate still executes.
154    pub fn coerce_datum(
155        &self,
156        index: usize,
157        name: &str,
158        value: &Value,
159        source: Option<&ColumnType>,
160        environment: RoutineConversionEnvironment<'_>,
161    ) -> Result<Value, SQLError> {
162        self.coerce(
163            self.slots.datums.get(index),
164            name,
165            value,
166            source,
167            environment,
168        )
169    }
170
171    pub fn coerce_result(
172        &self,
173        name: &str,
174        value: &Value,
175        source: Option<&ColumnType>,
176        environment: RoutineConversionEnvironment<'_>,
177    ) -> Result<Value, SQLError> {
178        self.coerce(Some(&self.slots.result), name, value, source, environment)
179    }
180
181    fn coerce(
182        &self,
183        slot: Option<&OnceLock<Produced<NamedDatum>>>,
184        name: &str,
185        value: &Value,
186        source: Option<&ColumnType>,
187        environment: RoutineConversionEnvironment<'_>,
188    ) -> Result<Value, SQLError> {
189        match self.named(slot, name, environment)? {
190            Some(saved) => self
191                .call
192                .coerce(name, &saved.conversion, value, source, environment),
193            None => crate::assignment::routines::coerce_routine_value_from(
194                environment.values,
195                value,
196                name,
197                source,
198            ),
199        }
200    }
201}