Skip to main content

uqa_sql/routines/
resolution.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Static routine signature matching, invocation binding, and declared return-type resolution.
8
9mod catalog;
10pub use catalog::{RoutineOverloadCatalog, RoutineTypeSnapshot};
11mod combined_overloads;
12mod production;
13pub(crate) use production::selected_binding;
14pub use production::{search_path_precedes_pg_catalog, OwnedStaticFunctionMatch};
15
16use super::{
17    declaration::RoutineTypeCatalog, routine_signature_types, SQLUserFunction, StaticFunctionMatch,
18};
19use crate::type_resolution::{
20    canonical_routine_type_name, rank_function_matches, BuiltinFunctionOverload,
21    FunctionTypeResolver, ResolvedFunctionOverload, RoutineCallDescriptor,
22    RoutineSignatureMatchError,
23};
24use crate::{
25    ast::{ColumnType, CreateFunction, FunctionBinding, RoutineVariadicMode},
26    SQLError,
27};
28use std::sync::Arc;
29use uqa_core::RelationIdentity;
30
31#[derive(Clone, Copy)]
32pub struct RoutineOverloadContext<'a> {
33    pub catalog: &'a dyn RoutineOverloadCatalog,
34}
35
36impl FunctionTypeResolver for RoutineOverloadContext<'_> {
37    fn format_type_name(&self, ty: &ColumnType) -> Result<String, SQLError> {
38        self.catalog.format_type(ty)
39    }
40
41    fn format_type_name_with_control(
42        &self,
43        ty: &ColumnType,
44        control: &uqa_core::memory::ProductionControl<'_>,
45    ) -> Result<uqa_core::memory::Produced<String>, SQLError> {
46        self.catalog.format_type_with_control(ty, control)
47    }
48
49    fn composite_types(&self) -> Option<&dyn crate::expr::composites::CompositeTypeCatalog> {
50        self.catalog.composite_types()
51    }
52
53    fn has_untyped_function_with_control(
54        &self,
55        name: &str,
56        control: &uqa_core::memory::ProductionControl<'_>,
57    ) -> Result<bool, SQLError> {
58        self.catalog
59            .has_registered_scalar_function_with_control(name, control)
60    }
61
62    fn has_untyped_function(&self, name: &str) -> bool {
63        self.catalog.has_registered_scalar_function(name)
64    }
65
66    fn resolve_type_name(&self, name: &str) -> Result<Option<ColumnType>, SQLError> {
67        self.catalog
68            .resolve_catalog_column_type_name(name)
69            .map(Some)
70    }
71
72    fn resolve_type_name_with_control(
73        &self,
74        name: &str,
75        control: &uqa_core::memory::ProductionControl<'_>,
76    ) -> Result<Option<uqa_core::memory::Produced<ColumnType>>, SQLError> {
77        self.catalog
78            .resolve_catalog_column_type_name_with_control(name, control)
79            .map(Some)
80    }
81
82    fn require_type_usage(&self, ty: &ColumnType) -> Result<(), SQLError> {
83        self.catalog.require_type_usage(ty)
84    }
85
86    fn resolve_function_type(
87        &self,
88        name: &str,
89        binding: Option<&FunctionBinding>,
90        argument_names: &[Option<String>],
91        argument_types: &[Option<ColumnType>],
92        explicit_variadic: bool,
93    ) -> Result<Option<ColumnType>, SQLError> {
94        self.resolve_function_overload(
95            name,
96            binding,
97            argument_names,
98            argument_types,
99            explicit_variadic,
100        )
101        .map(|resolved| resolved.map(|resolved| resolved.return_type))
102    }
103
104    fn resolve_function_type_with_control(
105        &self,
106        name: &str,
107        binding: Option<&FunctionBinding>,
108        argument_names: &[Option<String>],
109        argument_types: &[Option<ColumnType>],
110        explicit_variadic: bool,
111        control: &uqa_core::memory::ProductionControl<'_>,
112    ) -> Result<Option<uqa_core::memory::Produced<ColumnType>>, SQLError> {
113        self.resolve_function_overload_with_control(
114            name,
115            binding,
116            argument_names,
117            argument_types,
118            explicit_variadic,
119            control,
120        )?
121        .map(|result| {
122            result
123                .return_type
124                .clone_with_control(control)
125                .map_err(Into::into)
126        })
127        .transpose()
128    }
129
130    fn resolve_function_overload_with_control(
131        &self,
132        name: &str,
133        binding: Option<&FunctionBinding>,
134        argument_names: &[Option<String>],
135        argument_types: &[Option<ColumnType>],
136        explicit_variadic: bool,
137        control: &uqa_core::memory::ProductionControl<'_>,
138    ) -> Result<Option<uqa_core::memory::Produced<ResolvedFunctionOverload>>, SQLError> {
139        production::selection::resolve(
140            self,
141            name,
142            binding,
143            RoutineCallDescriptor {
144                argument_names,
145                argument_types,
146                explicit_variadic,
147            },
148            control,
149        )
150    }
151
152    fn resolve_function_overload_with_builtins_and_control(
153        &self,
154        name: &str,
155        binding: Option<&FunctionBinding>,
156        argument_names: &[Option<String>],
157        argument_types: &[Option<ColumnType>],
158        explicit_variadic: bool,
159        builtins: &[BuiltinFunctionOverload],
160        control: &uqa_core::memory::ProductionControl<'_>,
161    ) -> Result<Option<uqa_core::memory::Produced<ResolvedFunctionOverload>>, SQLError> {
162        production::combined::resolve(
163            self,
164            name,
165            binding,
166            RoutineCallDescriptor {
167                argument_names,
168                argument_types,
169                explicit_variadic,
170            },
171            builtins,
172            control,
173        )
174        .map(Some)
175    }
176
177    fn resolve_function_overload(
178        &self,
179        name: &str,
180        binding: Option<&FunctionBinding>,
181        argument_names: &[Option<String>],
182        argument_types: &[Option<ColumnType>],
183        explicit_variadic: bool,
184    ) -> Result<Option<ResolvedFunctionOverload>, SQLError> {
185        self.resolve_function_overload_with_control(
186            name,
187            binding,
188            argument_names,
189            argument_types,
190            explicit_variadic,
191            &uqa_core::memory::ProductionControl::uncontrolled(),
192        )
193        .map(|result| {
194            result.map(|result| {
195                result
196                    .into_uncontrolled()
197                    .expect("ordinary routine resolution")
198            })
199        })
200    }
201
202    fn is_scalar_function_binding(&self, binding: &FunctionBinding) -> Result<bool, SQLError> {
203        if binding.builtin {
204            return Ok(false);
205        }
206        let function = self
207            .catalog
208            .lookup_bound_sql_functions_by_binding(binding)
209            .and_then(|overloads| {
210                overloads.into_iter().find(|function| {
211                    !function.def.is_procedure
212                        && routine_signature_types(&function.def) == binding.argument_types
213                })
214            });
215        Ok(function.is_some_and(|function| !function.def.returns_set()))
216    }
217
218    fn is_scalar_function_binding_with_control(
219        &self,
220        binding: &FunctionBinding,
221        control: &uqa_core::memory::ProductionControl<'_>,
222    ) -> Result<bool, SQLError> {
223        control.check()?;
224        if binding.builtin {
225            return Ok(false);
226        }
227        Ok(self
228            .catalog
229            .select_bound_routine_with_control(binding, RoutineCallKind::Function, control)?
230            .is_some_and(|function| !function.def.returns_set()))
231    }
232
233    fn resolve_function_overload_with_builtins(
234        &self,
235        name: &str,
236        binding: Option<&FunctionBinding>,
237        argument_names: &[Option<String>],
238        argument_types: &[Option<ColumnType>],
239        explicit_variadic: bool,
240        builtins: &[BuiltinFunctionOverload],
241    ) -> Result<Option<ResolvedFunctionOverload>, SQLError> {
242        combined_overloads::resolve(
243            self,
244            name,
245            binding,
246            argument_names,
247            argument_types,
248            explicit_variadic,
249            builtins,
250        )
251        .map(Some)
252    }
253}
254
255#[derive(Debug, Clone, Copy, PartialEq, Eq)]
256pub enum RoutineCallKind {
257    Function,
258    Procedure,
259}
260
261impl RoutineCallKind {
262    fn is_procedure(self) -> bool {
263        self == Self::Procedure
264    }
265
266    fn name(self) -> &'static str {
267        match self {
268            Self::Function => "function",
269            Self::Procedure => "procedure",
270        }
271    }
272}
273
274impl RoutineOverloadContext<'_> {
275    pub fn resolve_static_sql_function(
276        &self,
277        name: &str,
278        binding: Option<&FunctionBinding>,
279        argument_names: &[Option<String>],
280        argument_types: &[Option<ColumnType>],
281        explicit_variadic: bool,
282    ) -> Result<Option<Arc<SQLUserFunction>>, SQLError> {
283        self.resolve_static_sql_function_match(
284            name,
285            binding,
286            argument_names,
287            argument_types,
288            explicit_variadic,
289        )
290        .map(|matched| matched.map(|matched| matched.function))
291    }
292
293    pub fn resolve_static_sql_function_match(
294        &self,
295        name: &str,
296        binding: Option<&FunctionBinding>,
297        argument_names: &[Option<String>],
298        argument_types: &[Option<ColumnType>],
299        explicit_variadic: bool,
300    ) -> Result<Option<StaticFunctionMatch>, SQLError> {
301        self.resolve_static_sql_routine_match(
302            name,
303            binding,
304            argument_names,
305            argument_types,
306            explicit_variadic,
307            RoutineCallKind::Function,
308        )
309    }
310
311    pub fn resolve_table_function_overload_with_builtins(
312        &self,
313        name: &str,
314        binding: Option<&FunctionBinding>,
315        argument_names: &[Option<String>],
316        argument_types: &[Option<ColumnType>],
317        explicit_variadic: bool,
318        builtins: &[BuiltinFunctionOverload],
319    ) -> Result<Option<ResolvedFunctionOverload>, SQLError> {
320        combined_overloads::resolve_table(
321            self,
322            name,
323            binding,
324            argument_names,
325            argument_types,
326            explicit_variadic,
327            builtins,
328        )
329        .map(Some)
330    }
331
332    pub fn resolve_static_sql_routine_match(
333        &self,
334        name: &str,
335        binding: Option<&FunctionBinding>,
336        argument_names: &[Option<String>],
337        argument_types: &[Option<ColumnType>],
338        explicit_variadic: bool,
339        kind: RoutineCallKind,
340    ) -> Result<Option<StaticFunctionMatch>, SQLError> {
341        if let Some(binding) = binding {
342            if binding.builtin {
343                return Ok(None);
344            }
345            let function = self
346                .catalog
347                .lookup_bound_sql_routine_candidates_by_binding(binding)
348                .and_then(|overloads| {
349                    overloads.into_iter().find(|function| {
350                        function.def.is_procedure == kind.is_procedure()
351                            && routine_signature_types(&function.def) == binding.argument_types
352                    })
353                })
354                .ok_or_else(|| static_bound_routine_error(kind, binding))?;
355            let matched = if let Some(invocation) = &binding.invocation {
356                let invocation_is_explicit = matches!(
357                    invocation.variadic_mode,
358                    RoutineVariadicMode::Explicit { .. }
359                );
360                if invocation.argument_positions.len() != argument_types.len()
361                    || invocation_is_explicit != explicit_variadic
362                {
363                    return Err(static_bound_routine_error(kind, binding));
364                }
365                StaticFunctionMatch {
366                    function,
367                    default_error: None,
368                    invocation: invocation.clone(),
369                    argument_types: invocation.argument_targets.clone(),
370                    raw_exact_matches: 0,
371                    exact_matches: 0,
372                    preferred_matches: 0,
373                    variadic_expansion: matches!(
374                        invocation.variadic_mode,
375                        RoutineVariadicMode::Expanded { .. }
376                    ),
377                }
378            } else {
379                static_routine_match(
380                    &self.catalog.routine_type_snapshot(),
381                    function,
382                    argument_names,
383                    argument_types,
384                    explicit_variadic,
385                    kind,
386                )
387                .map_err(|error| static_signature_error(kind, name, error))?
388                .ok_or_else(|| static_bound_routine_error(kind, binding))?
389            };
390            ensure_routine_kind(
391                name,
392                argument_names,
393                argument_types,
394                kind,
395                &matched.function.def,
396            )?;
397            check_selected_default_types(self.catalog, kind, name, &matched)?;
398            return Ok(Some(matched));
399        }
400        let Some(overloads) = self.catalog.lookup_sql_routine_candidates(name)? else {
401            return Ok(None);
402        };
403        resolve_static_routine_overload(
404            self.catalog,
405            name,
406            overloads,
407            argument_names,
408            argument_types,
409            explicit_variadic,
410            kind,
411        )
412        .map(Some)
413    }
414}
415
416fn resolve_static_routine_overload(
417    catalog: &dyn RoutineOverloadCatalog,
418    name: &str,
419    overloads: Vec<Arc<SQLUserFunction>>,
420    argument_names: &[Option<String>],
421    argument_types: &[Option<ColumnType>],
422    explicit_variadic: bool,
423    kind: RoutineCallKind,
424) -> Result<StaticFunctionMatch, SQLError> {
425    let snapshot = catalog.routine_type_snapshot();
426    let mut candidates = Vec::new();
427    let mut match_error = None;
428    for function in overloads {
429        match static_routine_match(
430            &snapshot,
431            function,
432            argument_names,
433            argument_types,
434            explicit_variadic,
435            kind,
436        ) {
437            Ok(Some(candidate)) => candidates.push(candidate),
438            Ok(None) => {}
439            Err(error) => {
440                match_error.get_or_insert(error);
441            }
442        }
443    }
444    retain_earliest_effective_signatures(&mut candidates);
445    if candidates.is_empty() {
446        if let Some(error) = match_error {
447            return Err(static_signature_error(kind, name, error));
448        }
449        return Err(static_routine_resolution_error(
450            kind,
451            "42883",
452            name,
453            argument_types,
454            "does not exist",
455        ));
456    }
457
458    if !rank_function_matches(&mut candidates, argument_types) || candidates.len() != 1 {
459        return Err(static_routine_resolution_error(
460            kind,
461            "42725",
462            name,
463            argument_types,
464            "is not unique",
465        ));
466    }
467    let matched = candidates
468        .pop()
469        .ok_or_else(|| SQLError::Internal("resolved routine candidate disappeared".into()))?;
470    ensure_routine_kind(
471        name,
472        argument_names,
473        argument_types,
474        kind,
475        &matched.function.def,
476    )?;
477    check_selected_default_types(catalog, kind, name, &matched)?;
478    Ok(matched)
479}
480
481pub(super) fn retain_earliest_effective_signatures(candidates: &mut Vec<StaticFunctionMatch>) {
482    let mut visible = Vec::<(Vec<String>, String)>::new();
483    candidates.retain(|candidate| {
484        let schema = RelationIdentity::parse_reference(&candidate.function.def.name)
485            .ok()
486            .and_then(|(schema, _)| schema)
487            .unwrap_or_default();
488        if let Some((_, first_schema)) = visible
489            .iter()
490            .find(|(signature, _)| signature == &candidate.argument_types)
491        {
492            return first_schema == &schema;
493        }
494        visible.push((candidate.argument_types.clone(), schema));
495        true
496    });
497}
498
499fn static_routine_match(
500    catalog: &RoutineTypeSnapshot,
501    function: Arc<SQLUserFunction>,
502    argument_names: &[Option<String>],
503    argument_types: &[Option<ColumnType>],
504    explicit_variadic: bool,
505    kind: RoutineCallKind,
506) -> Result<Option<StaticFunctionMatch>, RoutineSignatureMatchError> {
507    production::match_ordinary(
508        catalog,
509        function,
510        RoutineCallDescriptor {
511            argument_names,
512            argument_types,
513            explicit_variadic,
514        },
515        kind,
516    )
517}
518
519pub(crate) fn static_signature_error(
520    _kind: RoutineCallKind,
521    _name: &str,
522    error: RoutineSignatureMatchError,
523) -> SQLError {
524    production::diagnostics::signature(&error, &uqa_core::memory::ProductionControl::uncontrolled())
525        .expect("ordinary signature diagnostic")
526}
527
528fn ensure_routine_kind(
529    name: &str,
530    argument_names: &[Option<String>],
531    argument_types: &[Option<ColumnType>],
532    expected: RoutineCallKind,
533    definition: &CreateFunction,
534) -> Result<(), SQLError> {
535    production::diagnostics::kind(
536        name,
537        RoutineCallDescriptor {
538            argument_names,
539            argument_types,
540            explicit_variadic: false,
541        },
542        expected,
543        definition,
544        &uqa_core::memory::ProductionControl::uncontrolled(),
545    )
546}
547
548fn static_bound_routine_error(kind: RoutineCallKind, binding: &FunctionBinding) -> SQLError {
549    production::diagnostics::bound(
550        kind,
551        binding,
552        &uqa_core::memory::ProductionControl::uncontrolled(),
553    )
554    .expect("ordinary bound routine diagnostic")
555}
556
557fn static_routine_resolution_error(
558    kind: RoutineCallKind,
559    sqlstate: &str,
560    name: &str,
561    argument_types: &[Option<ColumnType>],
562    suffix: &str,
563) -> SQLError {
564    production::diagnostics::resolution(
565        kind,
566        sqlstate,
567        name,
568        RoutineCallDescriptor {
569            argument_names: &[],
570            argument_types,
571            explicit_variadic: false,
572        },
573        suffix,
574        &uqa_core::memory::ProductionControl::uncontrolled(),
575    )
576    .expect("ordinary routine resolution diagnostic")
577}
578
579/// Defaults do not exclude or rank an overload. Their polymorphic consistency is
580/// checked only after the ordinary supplied-argument rules choose one candidate.
581pub(super) fn check_selected_default_types(
582    catalog: &dyn RoutineTypeCatalog,
583    _kind: RoutineCallKind,
584    _name: &str,
585    matched: &StaticFunctionMatch,
586) -> Result<(), SQLError> {
587    if let Some(error) = &matched.default_error {
588        return Err(default_type_error(catalog, error)?);
589    }
590    // An actual anyarray supplies no element identity. Its sole-input exception
591    // permits an anyarray result, but cannot specialize an anyelement result.
592    if matched
593        .invocation
594        .parameter_types
595        .iter()
596        .any(|ty| ty == "anyarray")
597        && matched.invocation.return_type.as_deref().is_some_and(|ty| {
598            matches!(
599                canonical_routine_type_name(ty).as_str(),
600                "anyelement" | "anynonarray" | "anyenum"
601            )
602        })
603    {
604        return Err(default_type_error(
605            catalog,
606            &RoutineSignatureMatchError::IndeterminateArrayElement,
607        )?);
608    }
609    Ok(())
610}
611
612fn default_type_error(
613    catalog: &dyn RoutineTypeCatalog,
614    error: &RoutineSignatureMatchError,
615) -> Result<SQLError, SQLError> {
616    production::diagnostics::default_type(
617        catalog,
618        error,
619        &uqa_core::memory::ProductionControl::uncontrolled(),
620    )
621}