Skip to main content

uqa_sql/
routines.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! SQL routine definitions and static signature lookup contracts.
8
9pub mod attributes;
10pub mod body_parameters;
11pub mod body_validation;
12pub mod compilation;
13pub mod configuration;
14pub mod declaration;
15mod defaults;
16pub mod definition_output;
17pub mod dependencies;
18pub mod diagnostics;
19pub mod inlining;
20pub mod lifecycle;
21pub mod merge_columns;
22pub mod privilege_inquiry;
23pub mod regclass;
24pub mod registration;
25pub mod resolution;
26pub mod result_check;
27pub mod security;
28
29use crate::ast::{
30    ColumnType, CreateFunction, FunctionBinding, FunctionReturns, RoutineInvocationBinding,
31};
32use crate::plan::UnifiedPlan;
33use crate::type_resolution::{
34    canonical_routine_type_name, BuiltinFunctionOverload, FunctionTypeResolver,
35    RankedFunctionMatch, ResolvedFunctionOverload,
36};
37use crate::SQLError;
38use std::sync::{Arc, OnceLock};
39
40/// A registered routine: the persistable definition and its body as the catalog keeps it.
41#[derive(Clone)]
42pub struct SQLUserFunction {
43    pub def: CreateFunction,
44    pub body: RoutineBody,
45    version: OnceLock<u64>,
46}
47
48impl SQLUserFunction {
49    #[must_use]
50    pub const fn new(def: CreateFunction, body: RoutineBody) -> Self {
51        Self {
52            def,
53            body,
54            version: OnceLock::new(),
55        }
56    }
57
58    /// The identity of this catalog tuple, preserved through reload and rollback. A legacy definition starts from its immutable object identity; publication assigns a new revision even when it keeps every SQL attribute unchanged.
59    #[must_use]
60    pub fn catalog_revision(&self) -> Option<[u8; 16]> {
61        self.def.catalog_revision.or(self.def.object_id)
62    }
63
64    /// A fingerprint for the compiled-body cache, including the published catalog revision so an identical replacement recompiles its body. Exact catalog dependency checks use `catalog_revision` instead of this hash.
65    pub fn definition_version(&self) -> Result<u64, SQLError> {
66        if let Some(version) = self.version.get() {
67            return Ok(*version);
68        }
69        let encoded = serde_json::to_vec(&self.def).map_err(|error| {
70            SQLError::Internal(format!(
71                "encode routine `{}` definition: {error}",
72                self.def.name
73            ))
74        })?;
75        // FNV-1a over the encoded definition.
76        let version = encoded
77            .iter()
78            .fold(0xcbf2_9ce4_8422_2325_u64, |hash, byte| {
79                (hash ^ u64::from(*byte)).wrapping_mul(0x0000_0100_0000_01b3)
80            });
81        Ok(*self.version.get_or_init(|| version))
82    }
83}
84
85/// A routine body as the catalog keeps it. A SQL-standard body is bound when the routine is defined, as `PostgreSQL` stores `prosqlbody` as parse trees that name objects by OID. A body given as a string is compiled by each session that uses the routine, as the backend function cache compiles `prosrc`, so its names resolve when that session first needs them.
86/// A routine body as the catalog keeps it.
87#[derive(Clone)]
88pub enum RoutineBody {
89    /// A SQL-standard body, which the statement that defines the routine analyzes and binds.
90    Bound(Arc<CompiledFunctionBody>),
91    /// A body given as a string, which the catalog keeps as text, as `PostgreSQL` keeps `prosrc`: `CREATE FUNCTION` validates it only under `check_function_bodies`, and each session compiles it when it first calls the routine, so a body that no longer compiles reports its error then.
92    Source,
93}
94
95/// The body a static analysis sees, or `None` when the body does not compile in this session. Such a routine cannot run in the session, and running it reports the compilation error, as `PostgreSQL` compiles a routine only when it runs; internal failures still propagate.
96pub fn analyzable_routine_body(
97    resolution: &(impl RoutineResolution + ?Sized),
98    function: &SQLUserFunction,
99) -> Result<Option<Arc<CompiledFunctionBody>>, SQLError> {
100    match resolution.routine_analysis_body(function) {
101        Ok(body) => Ok(Some(body)),
102        Err(error) if matches!(error.primary(), SQLError::Internal(_)) => Err(error),
103        Err(_) => Ok(None),
104    }
105}
106
107/// Executable form of a routine body.
108// The project naming convention spells the acronym as `SQL`.
109#[allow(clippy::upper_case_acronyms)]
110#[derive(Clone)]
111pub enum CompiledFunctionBody {
112    PLpgSQL(crate::plpgsql::PLpgSQLFunction),
113    SQL(Vec<UnifiedPlan>),
114}
115pub fn is_routine_namespace_lookup_error(error: &SQLError) -> bool {
116    matches!(
117        error,
118        SQLError::Routine { sqlstate, message }
119            if sqlstate == "3F000"
120                || (sqlstate == "42501"
121                    && message.starts_with("permission denied for schema "))
122    )
123}
124
125/// Function-catalog operations required by static query binding. The interface deliberately excludes storage, transaction, locking, and execution services so the binder can run against a deterministic catalog fixture.
126pub trait RoutineResolution: FunctionTypeResolver {
127    fn has_registered_scalar_function(&self, _name: &str) -> bool {
128        false
129    }
130
131    /// The compiled body of a routine as this session executes it: a bound body as defined, or a source body as this session compiled it. A resolver without a session holds only bound bodies.
132    fn routine_body(
133        &self,
134        function: &SQLUserFunction,
135    ) -> Result<Arc<CompiledFunctionBody>, SQLError> {
136        match &function.body {
137            RoutineBody::Bound(body) => Ok(Arc::clone(body)),
138            RoutineBody::Source => Err(SQLError::Internal(format!(
139                "routine `{}` has no session to compile its body",
140                function.def.name
141            ))),
142        }
143    }
144
145    /// Inspect a body for static effects and portal dependencies. A session may
146    /// compile source independently here without creating its execution cache
147    /// entry or issuing diagnostics for a body the query never reaches.
148    fn routine_analysis_body(
149        &self,
150        function: &SQLUserFunction,
151    ) -> Result<Arc<CompiledFunctionBody>, SQLError> {
152        self.routine_body(function)
153    }
154
155    fn has_registered_table_function(&self, _name: &str) -> bool {
156        false
157    }
158
159    /// A registered function's stable output names, available without calling
160    /// it. `None` means its result supplies the descriptor at execution.
161    fn registered_table_function_columns(&self, _name: &str) -> Option<Vec<String>> {
162        None
163    }
164
165    fn has_registered_aggregate_function(&self, _name: &str) -> bool {
166        false
167    }
168
169    fn lookup_visible_sql_functions(
170        &self,
171        _name: &str,
172    ) -> Result<Option<Vec<Arc<SQLUserFunction>>>, SQLError> {
173        Ok(None)
174    }
175
176    /// Resolve candidate metadata without refreshing session-visible function state during analysis.
177    fn lookup_visible_sql_functions_for_analysis(
178        &self,
179        name: &str,
180    ) -> Result<Option<Vec<Arc<SQLUserFunction>>>, SQLError> {
181        self.lookup_visible_sql_functions(name)
182    }
183
184    /// Resolve an exact stored routine name without repeating visible-name lookup.
185    fn lookup_bound_sql_functions(&self, _name: &str) -> Option<Vec<Arc<SQLUserFunction>>> {
186        None
187    }
188
189    fn lookup_bound_sql_functions_by_binding(
190        &self,
191        _binding: &FunctionBinding,
192    ) -> Option<Vec<Arc<SQLUserFunction>>> {
193        None
194    }
195
196    fn resolve_static_sql_function(
197        &self,
198        _name: &str,
199        _binding: Option<&FunctionBinding>,
200        _argument_names: &[Option<String>],
201        _argument_types: &[Option<ColumnType>],
202        _explicit_variadic: bool,
203    ) -> Result<Option<Arc<SQLUserFunction>>, SQLError> {
204        Ok(None)
205    }
206
207    fn resolve_static_sql_function_match(
208        &self,
209        _name: &str,
210        _binding: Option<&FunctionBinding>,
211        _argument_names: &[Option<String>],
212        _argument_types: &[Option<ColumnType>],
213        _explicit_variadic: bool,
214    ) -> Result<Option<StaticFunctionMatch>, SQLError> {
215        Ok(None)
216    }
217
218    fn resolve_table_function_overload_with_builtins(
219        &self,
220        _name: &str,
221        _binding: Option<&FunctionBinding>,
222        _argument_names: &[Option<String>],
223        _argument_types: &[Option<ColumnType>],
224        _explicit_variadic: bool,
225        _builtins: &[BuiltinFunctionOverload],
226    ) -> Result<Option<ResolvedFunctionOverload>, SQLError> {
227        Ok(None)
228    }
229}
230
231/// Select the exact retained routine identity and declared signature without rebinding its name or executing its body.
232pub fn selected_bound_function(
233    routines: &dyn RoutineResolution,
234    binding: &FunctionBinding,
235) -> Option<std::sync::Arc<SQLUserFunction>> {
236    if binding.builtin || binding.resolution_error.is_some() {
237        return None;
238    }
239    let identity = binding.object_id?;
240    routines
241        .lookup_bound_sql_functions_by_binding(binding)?
242        .into_iter()
243        .find(|function| {
244            !function.def.is_procedure
245                && function.def.object_id == Some(identity)
246                && routine_signature_types(&function.def) == binding.argument_types
247        })
248}
249
250pub fn routine_signature_types(def: &CreateFunction) -> Vec<String> {
251    def.identity_params()
252        .map(|parameter| canonical_routine_type_name(&parameter.type_name))
253        .collect()
254}
255
256pub fn routine_returns_anonymous_record(def: &CreateFunction) -> bool {
257    let mut outputs = def.output_params();
258    match (outputs.next(), outputs.next(), &def.returns) {
259        (Some(output), None, _) => canonical_routine_type_name(&output.type_name) == "record",
260        (
261            None,
262            None,
263            FunctionReturns::Scalar { type_name } | FunctionReturns::SetOf { type_name },
264        ) => canonical_routine_type_name(type_name) == "record",
265        _ => false,
266    }
267}
268
269pub struct StaticFunctionMatch {
270    pub function: Arc<SQLUserFunction>,
271    pub invocation: Box<RoutineInvocationBinding>,
272    pub argument_types: Vec<String>,
273    pub raw_exact_matches: usize,
274    pub exact_matches: usize,
275    pub preferred_matches: usize,
276    pub variadic_expansion: bool,
277    pub default_error: Option<crate::type_resolution::RoutineSignatureMatchError>,
278}
279
280impl StaticFunctionMatch {
281    pub fn binding(&self) -> FunctionBinding {
282        FunctionBinding {
283            object_id: self.function.def.object_id,
284            name: self.function.def.name.clone(),
285            argument_types: routine_signature_types(&self.function.def),
286            builtin: false,
287            dispatch: None,
288            invocation: Some(self.invocation.clone()),
289            value_binding: None,
290            resolution_error: None,
291            input_collation: None,
292        }
293    }
294}
295
296impl RankedFunctionMatch for StaticFunctionMatch {
297    fn argument_types(&self) -> &[String] {
298        &self.argument_types
299    }
300
301    fn raw_exact_matches(&self) -> usize {
302        self.raw_exact_matches
303    }
304
305    fn exact_matches(&self) -> usize {
306        self.exact_matches
307    }
308
309    fn preferred_matches(&self) -> usize {
310        self.preferred_matches
311    }
312
313    fn is_variadic_expansion(&self) -> bool {
314        self.variadic_expansion
315    }
316}
317
318pub fn builtin_routine_support_oid(name: &str) -> Option<i64> {
319    Some(match name.strip_prefix("pg_catalog.").unwrap_or(name) {
320        "textlike_support" => 1023,
321        "texticregexeq_support" => 1024,
322        "texticlike_support" => 1025,
323        "network_subset_support" => 1173,
324        "textregexeq_support" => 1364,
325        "varchar_support" => 3097,
326        "numeric_support" => 3157,
327        _ => return None,
328    })
329}
330
331pub fn function_binding_matches(binding: &FunctionBinding, target: &FunctionBinding) -> bool {
332    if binding.builtin || target.builtin {
333        return false;
334    }
335    match (binding.object_id, target.object_id) {
336        (Some(binding), Some(target)) => binding == target,
337        (None, None) => {
338            binding.name == target.name && binding.argument_types == target.argument_types
339        }
340        _ => false,
341    }
342}
343
344pub fn routine_local_name(name: &str) -> Result<String, SQLError> {
345    uqa_core::RelationIdentity::from_legacy_name(name)
346        .map(|relation| relation.name)
347        .map_err(|error| SQLError::Internal(format!("invalid routine name `{name}`: {error}")))
348}
349
350pub fn routine_kind(def: &CreateFunction) -> &'static str {
351    if def.is_procedure {
352        "procedure"
353    } else {
354        "function"
355    }
356}
357
358pub mod anonymous_block;
359pub mod call;
360pub mod invocation;