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(SQLError::Internal(message)) => Err(SQLError::Internal(message)),
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    fn has_registered_aggregate_function(&self, _name: &str) -> bool {
160        false
161    }
162
163    fn lookup_visible_sql_functions(
164        &self,
165        _name: &str,
166    ) -> Result<Option<Vec<Arc<SQLUserFunction>>>, SQLError> {
167        Ok(None)
168    }
169
170    /// Resolve candidate metadata without refreshing session-visible function state during analysis.
171    fn lookup_visible_sql_functions_for_analysis(
172        &self,
173        name: &str,
174    ) -> Result<Option<Vec<Arc<SQLUserFunction>>>, SQLError> {
175        self.lookup_visible_sql_functions(name)
176    }
177
178    /// Resolve an exact stored routine name without repeating visible-name lookup.
179    fn lookup_bound_sql_functions(&self, _name: &str) -> Option<Vec<Arc<SQLUserFunction>>> {
180        None
181    }
182
183    fn lookup_bound_sql_functions_by_binding(
184        &self,
185        _binding: &FunctionBinding,
186    ) -> Option<Vec<Arc<SQLUserFunction>>> {
187        None
188    }
189
190    fn resolve_static_sql_function(
191        &self,
192        _name: &str,
193        _binding: Option<&FunctionBinding>,
194        _argument_names: &[Option<String>],
195        _argument_types: &[Option<ColumnType>],
196        _explicit_variadic: bool,
197    ) -> Result<Option<Arc<SQLUserFunction>>, SQLError> {
198        Ok(None)
199    }
200
201    fn resolve_static_sql_function_match(
202        &self,
203        _name: &str,
204        _binding: Option<&FunctionBinding>,
205        _argument_names: &[Option<String>],
206        _argument_types: &[Option<ColumnType>],
207        _explicit_variadic: bool,
208    ) -> Result<Option<StaticFunctionMatch>, SQLError> {
209        Ok(None)
210    }
211
212    fn resolve_table_function_overload_with_builtins(
213        &self,
214        _name: &str,
215        _binding: Option<&FunctionBinding>,
216        _argument_names: &[Option<String>],
217        _argument_types: &[Option<ColumnType>],
218        _explicit_variadic: bool,
219        _builtins: &[BuiltinFunctionOverload],
220    ) -> Result<Option<ResolvedFunctionOverload>, SQLError> {
221        Ok(None)
222    }
223}
224
225pub fn routine_signature_types(def: &CreateFunction) -> Vec<String> {
226    def.identity_params()
227        .iter()
228        .map(|parameter| canonical_routine_type_name(&parameter.type_name))
229        .collect()
230}
231
232pub fn routine_returns_anonymous_record(def: &CreateFunction) -> bool {
233    let outputs = def.output_params();
234    match (outputs.as_slice(), &def.returns) {
235        ([output], _) => canonical_routine_type_name(&output.type_name) == "record",
236        ([], FunctionReturns::Scalar { type_name } | FunctionReturns::SetOf { type_name }) => {
237            canonical_routine_type_name(type_name) == "record"
238        }
239        _ => false,
240    }
241}
242
243pub struct StaticFunctionMatch {
244    pub function: Arc<SQLUserFunction>,
245    pub invocation: Box<RoutineInvocationBinding>,
246    pub argument_types: Vec<String>,
247    pub raw_exact_matches: usize,
248    pub exact_matches: usize,
249    pub preferred_matches: usize,
250    pub variadic_expansion: bool,
251    pub default_error: Option<crate::type_resolution::RoutineSignatureMatchError>,
252}
253
254impl StaticFunctionMatch {
255    pub fn binding(&self) -> FunctionBinding {
256        FunctionBinding {
257            object_id: self.function.def.object_id,
258            name: self.function.def.name.clone(),
259            argument_types: routine_signature_types(&self.function.def),
260            builtin: false,
261            dispatch: None,
262            invocation: Some(self.invocation.clone()),
263            composite_field: None,
264            resolution_error: None,
265            input_collation: None,
266        }
267    }
268}
269
270impl RankedFunctionMatch for StaticFunctionMatch {
271    fn argument_types(&self) -> &[String] {
272        &self.argument_types
273    }
274
275    fn raw_exact_matches(&self) -> usize {
276        self.raw_exact_matches
277    }
278
279    fn exact_matches(&self) -> usize {
280        self.exact_matches
281    }
282
283    fn preferred_matches(&self) -> usize {
284        self.preferred_matches
285    }
286
287    fn is_variadic_expansion(&self) -> bool {
288        self.variadic_expansion
289    }
290}
291
292pub fn builtin_routine_support_oid(name: &str) -> Option<i64> {
293    Some(match name.strip_prefix("pg_catalog.").unwrap_or(name) {
294        "textlike_support" => 1023,
295        "texticregexeq_support" => 1024,
296        "texticlike_support" => 1025,
297        "network_subset_support" => 1173,
298        "textregexeq_support" => 1364,
299        "varchar_support" => 3097,
300        "numeric_support" => 3157,
301        _ => return None,
302    })
303}
304
305pub fn function_binding_matches(binding: &FunctionBinding, target: &FunctionBinding) -> bool {
306    if binding.builtin || target.builtin {
307        return false;
308    }
309    match (binding.object_id, target.object_id) {
310        (Some(binding), Some(target)) => binding == target,
311        (None, None) => {
312            binding.name == target.name && binding.argument_types == target.argument_types
313        }
314        _ => false,
315    }
316}
317
318pub fn routine_local_name(name: &str) -> Result<String, SQLError> {
319    uqa_core::RelationIdentity::from_legacy_name(name)
320        .map(|relation| relation.name)
321        .map_err(|error| SQLError::Internal(format!("invalid routine name `{name}`: {error}")))
322}
323
324pub fn routine_kind(def: &CreateFunction) -> &'static str {
325    if def.is_procedure {
326        "procedure"
327    } else {
328        "function"
329    }
330}
331
332pub mod anonymous_block;
333pub mod call;
334pub mod invocation;