Skip to main content

uqa_sql/routines/resolution/
production.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Selected routine metadata borrows immutable declarations and admits its independent output.
8
9use super::{RoutineCallKind, RoutineOverloadContext};
10use crate::{
11    ast::{
12        ColumnType, CreateFunction, FunctionBinding, FunctionReturns, RoutineInvocationBinding,
13        RoutineVariadicMode,
14    },
15    type_resolution::{
16        canonical_routine_type_name_with_control, FunctionBindingParts, ResolvedFunctionOverload,
17        RoutineSignatureMatchError,
18    },
19    SQLError,
20};
21use uqa_core::{
22    memory::{Produced, ProductionControl},
23    RelationIdentity, RelationName,
24};
25
26pub(super) mod combined;
27pub(super) mod diagnostics;
28mod invocation;
29mod matching;
30mod parameters;
31mod routine;
32pub(super) mod selection;
33mod table;
34pub use routine::OwnedStaticFunctionMatch;
35
36#[cfg(test)]
37mod tests;
38
39/// Observe the original first-occurrence search-path order, including duplicate entries.
40pub fn search_path_precedes_pg_catalog<'a>(
41    path: impl IntoIterator<Item = &'a str>,
42    schema: RelationName<'_>,
43    control: &ProductionControl<'_>,
44) -> Result<bool, SQLError> {
45    let mut user_position = None;
46    let mut catalog_position = None;
47    for (position, entry) in path.into_iter().enumerate() {
48        control.check()?;
49        if user_position.is_none() && RelationName::decoded(entry) == schema {
50            user_position = Some(position);
51        }
52        if catalog_position.is_none() && entry == "pg_catalog" {
53            catalog_position = Some(position);
54        }
55        if let (Some(user), Some(catalog)) = (user_position, catalog_position) {
56            return Ok(user < catalog);
57        }
58    }
59    Ok(false)
60}
61
62impl RoutineOverloadContext<'_> {
63    pub(super) fn user_function_precedes_pg_catalog_with_control(
64        &self,
65        name: &str,
66        control: &ProductionControl<'_>,
67    ) -> Result<bool, SQLError> {
68        control.check()?;
69        let Some(schema) = RelationIdentity::borrowed_reference(name).and_then(|name| name.schema)
70        else {
71            return Ok(false);
72        };
73        self.catalog
74            .routine_schema_precedes_pg_catalog(schema, control)
75    }
76
77    /// Revalidate the selected identity and invocation, then construct exactly the binding and result type the caller retains.
78    pub fn resolve_bound_function_overload_with_control(
79        &self,
80        name: &str,
81        binding: &FunctionBinding,
82        argument_names: &[Option<String>],
83        argument_types: &[Option<ColumnType>],
84        explicit_variadic: bool,
85        control: &ProductionControl<'_>,
86    ) -> Result<Produced<ResolvedFunctionOverload>, SQLError> {
87        control.check()?;
88        let kind = RoutineCallKind::Function;
89        let function = self
90            .catalog
91            .select_bound_routine_with_control(binding, kind, control)?
92            .ok_or_else(|| {
93                diagnostics::bound(kind, binding, control).unwrap_or_else(std::convert::identity)
94            })?;
95        let invocation = binding.invocation.as_deref().ok_or_else(|| {
96            diagnostics::bound(kind, binding, control).unwrap_or_else(std::convert::identity)
97        })?;
98        let invocation_is_explicit = matches!(
99            invocation.variadic_mode,
100            RoutineVariadicMode::Explicit { .. }
101        );
102        if invocation.argument_positions.len() != argument_types.len()
103            || invocation_is_explicit != explicit_variadic
104        {
105            return Err(
106                diagnostics::bound(kind, binding, control).unwrap_or_else(std::convert::identity)
107            );
108        }
109        diagnostics::kind(
110            name,
111            crate::type_resolution::RoutineCallDescriptor {
112                argument_names,
113                argument_types,
114                explicit_variadic,
115            },
116            kind,
117            &function.def,
118            control,
119        )?;
120        check_invocation_result(self, invocation, control)?;
121        let selected = FunctionBindingParts {
122            object_id: function.def.object_id,
123            name: control.copy_text(&function.def.name)?,
124            argument_types: crate::plan::copy::copy_syntax_with_control(
125                &binding.argument_types,
126                control,
127            )?,
128            builtin: false,
129            dispatch: None,
130            invocation: Some(crate::plan::copy::copy_syntax_with_control(
131                invocation, control,
132            )?),
133            value_binding: None,
134            resolution_error: None,
135            input_collation: None,
136        }
137        .finish(control)?;
138        let result = static_function_return_type_with_control(
139            self,
140            name,
141            &function.def,
142            Some(invocation),
143            control,
144        )?;
145        let precedes_pg_catalog =
146            self.user_function_precedes_pg_catalog_with_control(&function.def.name, control)?;
147        let (binding, binding_memory) = selected.into_parts();
148        let (return_type, return_memory) = result.into_parts();
149        Ok(control.finish(
150            ResolvedFunctionOverload {
151                binding,
152                return_type,
153                exact_matches: 0,
154                known_arguments: argument_types.iter().flatten().count(),
155                preferred_matches: 0,
156                precedes_pg_catalog,
157            },
158            control.combine(binding_memory, return_memory),
159        )?)
160    }
161}
162
163fn check_invocation_result(
164    resolver: &RoutineOverloadContext<'_>,
165    invocation: &RoutineInvocationBinding,
166    control: &ProductionControl<'_>,
167) -> Result<(), SQLError> {
168    for ty in &invocation.parameter_types {
169        control.check()?;
170        if ty != "anyarray" {
171            continue;
172        }
173        if let Some(result) = &invocation.return_type {
174            let canonical = canonical_routine_type_name_with_control(result, control)?;
175            if matches!(canonical.as_str(), "anyelement" | "anynonarray" | "anyenum") {
176                return Err(diagnostics::default_type(
177                    resolver.catalog,
178                    &RoutineSignatureMatchError::IndeterminateArrayElement,
179                    control,
180                )?);
181            }
182        }
183        break;
184    }
185    Ok(())
186}
187
188pub(super) fn static_function_return_type_with_control(
189    resolver: &RoutineOverloadContext<'_>,
190    name: &str,
191    definition: &CreateFunction,
192    invocation: Option<&RoutineInvocationBinding>,
193    control: &ProductionControl<'_>,
194) -> Result<Produced<ColumnType>, SQLError> {
195    control.check()?;
196    let invocation_return = invocation.and_then(|invocation| invocation.return_type.as_deref());
197    let declared_return = match &definition.returns {
198        FunctionReturns::Scalar { type_name } | FunctionReturns::SetOf { type_name } => {
199            Some(type_name.as_str())
200        }
201        FunctionReturns::Table | FunctionReturns::None => None,
202    };
203    if let Some(type_name) = invocation_return.or(declared_return) {
204        if canonical_routine_type_name_with_control(type_name, control)?.as_str() == "trigger" {
205            return Err(SQLError::Routine {
206                sqlstate: "0A000".into(),
207                message: "trigger functions can only be called as triggers".into(),
208            });
209        }
210    }
211    if matches!(definition.returns, FunctionReturns::Table)
212        || definition.output_params().nth(1).is_some()
213    {
214        return Ok(control.finish(ColumnType::Record, control.empty_reservation())?);
215    }
216    if let Some(type_name) = invocation_return {
217        return resolve_return_type(resolver, type_name, control)?.ok_or_else(|| {
218            return_type_error(
219                format_args!("function `{name}` has unresolved return type `{type_name}`"),
220                control,
221            )
222        });
223    }
224    let type_name = match &definition.returns {
225        FunctionReturns::Scalar { type_name } | FunctionReturns::SetOf { type_name } => type_name,
226        FunctionReturns::None => {
227            &definition
228                .output_params()
229                .next()
230                .ok_or_else(|| {
231                    return_type_error(
232                        format_args!("function `{name}` does not return a value"),
233                        control,
234                    )
235                })?
236                .type_name
237        }
238        FunctionReturns::Table => unreachable!("table result handled above"),
239    };
240    resolve_return_type(resolver, type_name, control)?
241        .ok_or_else(|| return_type_error(format_args!("unknown type `{type_name}`"), control))
242}
243
244fn return_type_error(
245    message: std::fmt::Arguments<'_>,
246    control: &ProductionControl<'_>,
247) -> SQLError {
248    match control.format(message) {
249        Ok(message) => {
250            let (message, _memory) = message.into_parts();
251            SQLError::TypeMismatch(message)
252        }
253        Err(error) => error.into(),
254    }
255}
256
257fn resolve_return_type(
258    resolver: &RoutineOverloadContext<'_>,
259    name: &str,
260    control: &ProductionControl<'_>,
261) -> Result<Option<Produced<ColumnType>>, SQLError> {
262    if let Some(ty) = resolver
263        .catalog
264        .resolve_catalog_column_type_with_control(name, control)?
265    {
266        return Ok(Some(ty));
267    }
268    match ColumnType::from_sql_name_with_control(name, control) {
269        Ok(ty) => Ok(Some(ty)),
270        Err(error)
271            if matches!(error.primary(), SQLError::Cancelled(_))
272                || error.sqlstate() == Some("53200") =>
273        {
274            Err(error)
275        }
276        Err(_) => Ok(None),
277    }
278}
279
280pub(super) fn match_ordinary(
281    catalog: &super::RoutineTypeSnapshot,
282    function: std::sync::Arc<crate::routines::SQLUserFunction>,
283    call: crate::type_resolution::RoutineCallDescriptor<'_>,
284    kind: RoutineCallKind,
285) -> Result<Option<crate::routines::StaticFunctionMatch>, RoutineSignatureMatchError> {
286    let control = ProductionControl::uncontrolled();
287    match matching::match_candidate(catalog, function, call, kind, &control) {
288        Ok(matched) => Ok(matched.map(|matched| {
289            let signature = matched
290                .signature
291                .into_uncontrolled()
292                .expect("ordinary matched routine");
293            let invocation = matched
294                .invocation
295                .into_uncontrolled()
296                .expect("ordinary invocation metadata");
297            crate::routines::StaticFunctionMatch {
298                function: matched.function,
299                invocation: Box::new(invocation),
300                argument_types: signature.argument_signature,
301                raw_exact_matches: signature.raw_exact_matches,
302                exact_matches: signature.exact_matches,
303                preferred_matches: signature.preferred_matches,
304                variadic_expansion: signature.variadic_mode
305                    == crate::type_resolution::RoutineVariadicMode::Pack,
306                default_error: signature.default_error,
307            }
308        })),
309        Err(crate::type_resolution::RoutineSignatureProductionError::Signature(error)) => {
310            Err(error
311                .into_uncontrolled()
312                .expect("ordinary signature diagnostic"))
313        }
314        Err(crate::type_resolution::RoutineSignatureProductionError::Production(error)) => {
315            panic!("ordinary routine matching cannot fail production: {error}")
316        }
317    }
318}
319
320pub(crate) fn selected_binding(
321    function: &crate::routines::SQLUserFunction,
322    invocation: Produced<RoutineInvocationBinding>,
323    control: &ProductionControl<'_>,
324) -> Result<Produced<FunctionBinding>, SQLError> {
325    let mut arguments = uqa_core::memory::ProductionVec::new(*control);
326    for parameter in function.def.identity_params() {
327        control.check()?;
328        arguments.push_produced(canonical_routine_type_name_with_control(
329            &parameter.type_name,
330            control,
331        )?)?;
332    }
333    FunctionBindingParts {
334        object_id: function.def.object_id,
335        name: control.copy_text(&function.def.name)?,
336        argument_types: arguments.finish()?,
337        builtin: false,
338        dispatch: None,
339        invocation: Some(invocation),
340        value_binding: None,
341        resolution_error: None,
342        input_collation: None,
343    }
344    .finish(control)
345}