Skip to main content

uqa_sql/ast/
function_binding.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7use serde::{Deserialize, Serialize};
8
9use super::{EnumFunctionOperation, RangeSubtype};
10
11#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
12pub struct FunctionBinding {
13    /// Stable identity of a bound user routine. Built-ins and unbound calls leave this unset.
14    #[serde(default, skip_serializing_if = "Option::is_none")]
15    pub object_id: Option<[u8; 16]>,
16    pub name: String,
17    pub argument_types: Vec<String>,
18    #[serde(default)]
19    pub builtin: bool,
20    /// Executor operation selected structurally during parsing or overload binding. SQL-visible routine lookup never consults display-name conventions for these operations.
21    #[serde(default, skip_serializing_if = "Option::is_none")]
22    pub dispatch: Option<FunctionDispatch>,
23    /// Concrete invocation contract selected during routine overload resolution.
24    #[serde(default, skip_serializing_if = "Option::is_none")]
25    pub invocation: Option<Box<RoutineInvocationBinding>>,
26    /// Prepared field identity and its original result type; executable copies refresh its live descriptor without changing the result contract.
27    #[serde(default, skip_serializing_if = "Option::is_none")]
28    pub composite_field: Option<Box<CompositeFieldBinding>>,
29    /// A typed overload-resolution failure retained until the expression reaches a fallible planning or execution boundary. This never reuses the SQL function-name namespace as an error channel.
30    #[serde(default, skip_serializing_if = "Option::is_none")]
31    pub resolution_error: Option<Box<FunctionResolutionError>>,
32    /// The collation analysis selected for the call's collatable inputs, `PostgreSQL`'s `inputcollid`: the merged collation of its arguments, where an explicit `COLLATE` wins and conflicting implicit collations leave zero, an indeterminate selection that a collation-dependent function reports when it runs. A call without collatable inputs records nothing. Definitions stored before this selection was retained also record nothing; [`Self::selected_input_collation`] then supplies the database default collation, which is what `PostgreSQL` records when every collatable input carries the default collation, and recreating such a definition records its actual selection.
33    #[serde(default, skip_serializing_if = "Option::is_none")]
34    pub input_collation: Option<crate::catalog::collations::CollationSelection>,
35}
36
37/// A field selected during preparation. Attribute numbers are never reused, even when a later attribute has the same name.
38#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
39pub struct CompositeFieldBinding {
40    pub type_oid: u32,
41    pub number: i16,
42    pub result_type: super::ColumnType,
43    /// The field's declaration at preparation, independently of the argument's collation.
44    #[serde(default, skip_serializing_if = "Option::is_none")]
45    pub collation_oid: Option<u32>,
46    pub dropped: bool,
47    /// The live attribute type in an executable copy, when it differs from the original type OID. Type modifiers do not change `FieldSelect`'s result contract.
48    #[serde(default, skip_serializing_if = "Option::is_none")]
49    pub changed_type: Option<super::ColumnType>,
50}
51
52/// Static function-call failure discovered while binding declared argument types.
53#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
54pub enum FunctionResolutionError {
55    UndefinedFunction { signature: String },
56    Operator(Box<OperatorResolutionError>),
57}
58
59#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
60pub struct OperatorResolutionError {
61    pub sqlstate: String,
62    pub message: String,
63}
64
65impl FunctionResolutionError {
66    #[must_use]
67    pub fn sql_error(&self) -> crate::SQLError {
68        match self {
69            Self::UndefinedFunction { signature } => {
70                crate::SQLError::undefined_function_call(signature)
71            }
72            Self::Operator(error) => crate::SQLError::Routine {
73                sqlstate: error.sqlstate.clone(),
74                message: error.message.clone(),
75            },
76        }
77    }
78}
79
80/// Structural identity for parser-owned expressions and overload-specific built-in implementations. These variants occupy no SQL function-name namespace.
81#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
82pub enum FunctionDispatch {
83    NumericOperator(NumericOperator),
84    /// SQL pattern syntax, retaining its selected binary operator after escape processing.
85    Pattern {
86        operator: super::PatternOperator,
87        oid: Option<std::num::NonZeroU32>,
88    },
89    /// A parser-owned escape helper, evaluated and folded independently of the strict match operator.
90    PatternEscape {
91        similar: bool,
92    },
93    /// A non-strict SQL Boolean test, distinct from routine lookup and equality.
94    BooleanTest(BooleanTest),
95    /// A collation clause, retaining its selected identity independently of its written name.
96    Collate {
97        oid: Option<u32>,
98    },
99    /// The selected argument metadata of `pg_collation_for`; the argument still executes before the observation.
100    CollationFor {
101        collation_oid: u32,
102        noncollatable_type_oid: Option<u32>,
103    },
104    NamedArgument,
105    VariadicArgument,
106    ArraySubscripts,
107    ArraySlices,
108    /// Slice syntax with independently retained omitted endpoints.
109    ArraySlicesWithBounds(super::ArraySliceBounds),
110    Subscript,
111    Slice,
112    /// `(expression).field`: the field of a composite value, or the key of a document map.
113    FieldSelect,
114    AnyOperator,
115    AllOperator,
116    IsDistinct,
117    /// Negation synthesized by IS NOT DISTINCT FROM, whose operand is not a written Boolean context.
118    DistinctNot,
119    /// Disjunction of selected ROW DISTINCT field comparisons, with ordered short-circuit evaluation.
120    RowDistinct,
121    /// One selected DISTINCT comparison of complete field values; nested ROW constructors remain one record-valued operand.
122    ValueIsDistinct,
123    /// The outer NULL test selected by DISTINCT against a bare NULL, without testing individual record fields or requiring equality.
124    ValueNullTest {
125        negated: bool,
126    },
127    BetweenSymmetric,
128    ToBinInt4,
129    ToBinInt8,
130    ToHexInt4,
131    ToHexInt8,
132    ToOctInt4,
133    ToOctInt8,
134    RandomInt4Range,
135    RandomInt8Range,
136    RandomNumericRange,
137    /// `substring(text, text)`: the POSIX regular-expression extraction selected by overload resolution, never inferred from argument values.
138    RegexSubstring,
139    /// `substring(text, text, text)`: SQL regular-expression extraction, which applies `similar_to_escape` before the POSIX extraction.
140    SimilarSubstring,
141    ArraySortJson,
142    /// SQL concatenation syntax, with its selected catalog overload after operand analysis.
143    Concat {
144        oid: Option<u32>,
145    },
146    /// The selected array `||` overload, retained even when its arguments evaluate to NULL.
147    ArrayConcat,
148    ArrayAppend,
149    ArrayPrepend,
150    /// A resolved JSON path function whose final argument is the declared text array.
151    JsonPath {
152        as_text: bool,
153        jsonb: bool,
154    },
155    JsonExtract {
156        as_text: bool,
157        path: bool,
158    },
159    Range {
160        operation: RangeFunctionOperation,
161        subtype: RangeSubtype,
162        multirange: bool,
163    },
164    /// An `anyenum` support function bound to one concrete enum type.
165    Enum {
166        operation: EnumFunctionOperation,
167        type_oid: u32,
168    },
169    /// The current MERGE action, read from the executor-owned row attribute.
170    MergeAction,
171}
172
173/// The six predicates over SQL's true, false and NULL Boolean inputs.
174#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
175pub enum BooleanTest {
176    IsTrue,
177    IsNotTrue,
178    IsFalse,
179    IsNotFalse,
180    IsUnknown,
181    IsNotUnknown,
182}
183
184impl BooleanTest {
185    #[must_use]
186    pub const fn label(self) -> &'static str {
187        match self {
188            Self::IsTrue => "IS TRUE",
189            Self::IsNotTrue => "IS NOT TRUE",
190            Self::IsFalse => "IS FALSE",
191            Self::IsNotFalse => "IS NOT FALSE",
192            Self::IsUnknown => "IS UNKNOWN",
193            Self::IsNotUnknown => "IS NOT UNKNOWN",
194        }
195    }
196
197    /// Stable `PostgreSQL` catalog node identity, independent of parser protobuf tags.
198    #[must_use]
199    pub const fn catalog_code(self) -> i64 {
200        match self {
201            Self::IsTrue => 0,
202            Self::IsNotTrue => 1,
203            Self::IsFalse => 2,
204            Self::IsNotFalse => 3,
205            Self::IsUnknown => 4,
206            Self::IsNotUnknown => 5,
207        }
208    }
209
210    #[must_use]
211    pub const fn from_catalog_code(code: i64) -> Option<Self> {
212        match code {
213            0 => Some(Self::IsTrue),
214            1 => Some(Self::IsNotTrue),
215            2 => Some(Self::IsFalse),
216            3 => Some(Self::IsNotFalse),
217            4 => Some(Self::IsUnknown),
218            5 => Some(Self::IsNotUnknown),
219            _ => None,
220        }
221    }
222}
223
224/// Operation selected for one typed range or multirange call.
225#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
226pub enum RangeFunctionOperation {
227    Lower,
228    Upper,
229    IsEmpty,
230    LowerInclusive,
231    UpperInclusive,
232    LowerInfinite,
233    UpperInfinite,
234    Merge,
235    Multirange,
236    Overlap,
237    Contains,
238    ContainedBy,
239    /// The range operand is first; the second operand has its declared subtype.
240    ContainsElement,
241    /// The range operand is second; the first operand has its declared subtype.
242    ElementContainedBy,
243    Adjacent,
244}
245
246impl FunctionDispatch {
247    /// Whether this expression retains SQL concatenation syntax and operand roles.
248    #[must_use]
249    pub const fn is_concatenation(self) -> bool {
250        matches!(
251            self,
252            Self::Concat { .. } | Self::ArrayConcat | Self::ArrayAppend | Self::ArrayPrepend
253        )
254    }
255
256    /// Human-readable expression label used only in diagnostics and serialized plans; dispatch is always selected by the enum variant.
257    #[must_use]
258    pub const fn label(self) -> &'static str {
259        match self {
260            Self::MergeAction => "merge_action",
261            Self::NumericOperator(operator) => operator.symbol(),
262            Self::Pattern { operator, .. } => operator.syntax(),
263            Self::PatternEscape { similar: false } => "pg_catalog.like_escape",
264            Self::PatternEscape { similar: true } => "pg_catalog.similar_to_escape",
265            Self::BooleanTest(test) => test.label(),
266            Self::Collate { .. } => "COLLATE",
267            Self::CollationFor { .. } => "pg_catalog.pg_collation_for",
268            Self::NamedArgument => "named argument",
269            Self::VariadicArgument => "VARIADIC argument",
270            Self::ArraySubscripts | Self::Subscript => "subscript",
271            Self::ArraySlices | Self::ArraySlicesWithBounds(_) | Self::Slice => "slice",
272            Self::FieldSelect => "field selection",
273            Self::AnyOperator => "ANY operator",
274            Self::AllOperator => "ALL operator",
275            Self::IsDistinct | Self::ValueIsDistinct | Self::RowDistinct => "IS DISTINCT FROM",
276            Self::DistinctNot => "IS NOT DISTINCT FROM",
277            Self::ValueNullTest { negated: false } => "IS NULL",
278            Self::ValueNullTest { negated: true } => "IS NOT NULL",
279            Self::BetweenSymmetric => "BETWEEN SYMMETRIC",
280            Self::ToBinInt4 | Self::ToBinInt8 => "pg_catalog.to_bin",
281            Self::ToHexInt4 | Self::ToHexInt8 => "pg_catalog.to_hex",
282            Self::ToOctInt4 | Self::ToOctInt8 => "pg_catalog.to_oct",
283            Self::RandomInt4Range | Self::RandomInt8Range | Self::RandomNumericRange => {
284                "pg_catalog.random"
285            }
286            Self::RegexSubstring | Self::SimilarSubstring => "pg_catalog.substring",
287            Self::ArraySortJson => "pg_catalog.array_sort",
288            Self::Concat { .. } => "||",
289            Self::ArrayConcat => "pg_catalog.array_cat",
290            Self::ArrayAppend => "pg_catalog.array_append",
291            Self::ArrayPrepend => "pg_catalog.array_prepend",
292            Self::JsonPath {
293                as_text: false,
294                jsonb: false,
295            } => "pg_catalog.json_extract_path",
296            Self::JsonPath {
297                as_text: true,
298                jsonb: false,
299            } => "pg_catalog.json_extract_path_text",
300            Self::JsonPath {
301                as_text: false,
302                jsonb: true,
303            } => "pg_catalog.jsonb_extract_path",
304            Self::JsonPath {
305                as_text: true,
306                jsonb: true,
307            } => "pg_catalog.jsonb_extract_path_text",
308            Self::JsonExtract { as_text: false, .. } => "JSON extraction operator",
309            Self::JsonExtract { as_text: true, .. } => "JSON text extraction operator",
310            Self::Range { operation, .. } => operation.label(),
311            Self::Enum { operation, .. } => operation.label(),
312        }
313    }
314
315    #[must_use]
316    pub const fn is_call_argument_marker(self) -> bool {
317        matches!(self, Self::NamedArgument | Self::VariadicArgument)
318    }
319
320    /// The SQL spelling of a retained JSON extraction operator, independent of its diagnostic label.
321    #[must_use]
322    pub const fn json_extraction_symbol(self) -> Option<&'static str> {
323        match self {
324            Self::JsonExtract {
325                as_text: false,
326                path: false,
327            } => Some("->"),
328            Self::JsonExtract {
329                as_text: true,
330                path: false,
331            } => Some("->>"),
332            Self::JsonExtract {
333                as_text: false,
334                path: true,
335            } => Some("#>"),
336            Self::JsonExtract {
337                as_text: true,
338                path: true,
339            } => Some("#>>"),
340            _ => None,
341        }
342    }
343
344    /// Decode function spellings in older durable expressions. This is a catalog migration primitive, never a SQL routine lookup path.
345    #[doc(hidden)]
346    #[must_use]
347    pub fn from_legacy_serialized_name(name: &str) -> Option<Self> {
348        let fixed = match name {
349            "merge_action" => Self::MergeAction,
350            "__named_arg" => Self::NamedArgument,
351            "__variadic_arg" => Self::VariadicArgument,
352            "__array_subscripts" => Self::ArraySubscripts,
353            "__array_slices" => Self::ArraySlices,
354            "__subscript" => Self::Subscript,
355            "__slice" => Self::Slice,
356            "__any_op" => Self::AnyOperator,
357            "__all_op" => Self::AllOperator,
358            "__is_distinct" => Self::IsDistinct,
359            "__between_symmetric" => Self::BetweenSymmetric,
360            "__to_bin_int4" => Self::ToBinInt4,
361            "__to_bin_int8" => Self::ToBinInt8,
362            "__to_hex_int4" => Self::ToHexInt4,
363            "__to_hex_int8" => Self::ToHexInt8,
364            "__to_oct_int4" => Self::ToOctInt4,
365            "__to_oct_int8" => Self::ToOctInt8,
366            "__random_int4_range" => Self::RandomInt4Range,
367            "__random_int8_range" => Self::RandomInt8Range,
368            "__random_numeric_range" => Self::RandomNumericRange,
369            "__array_sort_json" => Self::ArraySortJson,
370            _ => return Self::legacy_range_dispatch(name),
371        };
372        Some(fixed)
373    }
374
375    fn legacy_range_dispatch(name: &str) -> Option<Self> {
376        let encoded = name.strip_prefix("__range_")?;
377        let subtypes = [
378            RangeSubtype::Integer,
379            RangeSubtype::BigInteger,
380            RangeSubtype::Numeric,
381            RangeSubtype::Date,
382            RangeSubtype::Timestamp,
383            RangeSubtype::TimestampTz,
384        ];
385        for subtype in subtypes {
386            for (type_name, multirange) in [
387                (subtype.multirange_name(), true),
388                (subtype.range_name(), false),
389            ] {
390                let Some(operation) = encoded.strip_suffix(type_name) else {
391                    continue;
392                };
393                let operation = match operation.trim_end_matches('_') {
394                    "lower" => RangeFunctionOperation::Lower,
395                    "upper" => RangeFunctionOperation::Upper,
396                    "isempty" => RangeFunctionOperation::IsEmpty,
397                    "lower_inc" => RangeFunctionOperation::LowerInclusive,
398                    "upper_inc" => RangeFunctionOperation::UpperInclusive,
399                    "lower_inf" => RangeFunctionOperation::LowerInfinite,
400                    "upper_inf" => RangeFunctionOperation::UpperInfinite,
401                    "merge" => RangeFunctionOperation::Merge,
402                    "multirange" => RangeFunctionOperation::Multirange,
403                    "overlap" => RangeFunctionOperation::Overlap,
404                    "contains" => RangeFunctionOperation::Contains,
405                    "contained_by" => RangeFunctionOperation::ContainedBy,
406                    "adjacent" => RangeFunctionOperation::Adjacent,
407                    _ => continue,
408                };
409                return Some(Self::Range {
410                    operation,
411                    subtype,
412                    multirange,
413                });
414            }
415        }
416        None
417    }
418}
419
420/// Numeric operator syntax, kept separate from ordinary calls such as `mod` or `abs`.
421#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
422pub enum NumericOperator {
423    Modulo,
424    Power,
425    Plus,
426    SquareRoot,
427    CubeRoot,
428    Absolute,
429}
430
431impl NumericOperator {
432    #[must_use]
433    pub const fn symbol(self) -> &'static str {
434        match self {
435            Self::Modulo => "%",
436            Self::Power => "^",
437            Self::Plus => "+",
438            Self::SquareRoot => "|/",
439            Self::CubeRoot => "||/",
440            Self::Absolute => "@",
441        }
442    }
443
444    #[must_use]
445    pub const fn arity(self) -> usize {
446        match self {
447            Self::Modulo | Self::Power => 2,
448            Self::Plus | Self::SquareRoot | Self::CubeRoot | Self::Absolute => 1,
449        }
450    }
451}
452
453impl RangeFunctionOperation {
454    #[must_use]
455    pub const fn label(self) -> &'static str {
456        match self {
457            Self::Lower => "pg_catalog.lower",
458            Self::Upper => "pg_catalog.upper",
459            Self::IsEmpty => "pg_catalog.isempty",
460            Self::LowerInclusive => "pg_catalog.lower_inc",
461            Self::UpperInclusive => "pg_catalog.upper_inc",
462            Self::LowerInfinite => "pg_catalog.lower_inf",
463            Self::UpperInfinite => "pg_catalog.upper_inf",
464            Self::Merge => "pg_catalog.range_merge",
465            Self::Multirange => "pg_catalog.multirange",
466            Self::Overlap => "range overlap operator",
467            Self::Contains => "range contains operator",
468            Self::ContainedBy => "range contained-by operator",
469            Self::ContainsElement => "range contains element operator",
470            Self::ElementContainedBy => "element contained-by range operator",
471            Self::Adjacent => "range adjacent operator",
472        }
473    }
474}
475
476/// Concrete parameter and result types selected for one routine invocation.
477#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
478pub struct RoutineInvocationBinding {
479    /// Zero-based declared parameter index for each call argument, aligned with the call argument list.
480    pub argument_positions: Vec<usize>,
481    /// Concrete coercion target for each call argument, aligned with the call argument list.
482    pub argument_targets: Vec<String>,
483    /// Declared source types before argument coercion; absent only in legacy bindings.
484    #[serde(default, skip_serializing_if = "Vec::is_empty")]
485    pub argument_sources: Vec<Option<String>>,
486    /// Concrete type for each declared parameter, aligned with [`crate::ast::CreateFunction::params`].
487    pub parameter_types: Vec<String>,
488    /// Concrete invocation result type after polymorphic substitution.
489    pub return_type: Option<String>,
490    /// Whether and where the declared variadic parameter participates in this invocation.
491    pub variadic_mode: RoutineVariadicMode,
492}
493
494/// Call syntax selected for a routine's variadic parameter.
495#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
496pub enum RoutineVariadicMode {
497    /// The invocation does not use a variadic parameter.
498    #[default]
499    None,
500    /// Trailing call arguments are expanded into the declared variadic array parameter.
501    Expanded {
502        /// Zero-based index in [`crate::ast::CreateFunction::params`].
503        parameter_index: usize,
504    },
505    /// An explicit `VARIADIC` array argument supplies the declared variadic parameter.
506    Explicit {
507        /// Zero-based index in [`crate::ast::CreateFunction::params`].
508        parameter_index: usize,
509    },
510}
511
512impl FunctionBinding {
513    /// Preserve the predecessor format's encoded omission before an optimizer can fold supplied expressions to NULL.
514    #[doc(hidden)]
515    pub fn upgrade_legacy_array_slices(
516        binding: &mut Option<Self>,
517        arguments: usize,
518        is_bare_null: impl Fn(usize) -> bool,
519    ) -> bool {
520        let Some(binding) = binding
521            .as_mut()
522            .filter(|binding| binding.dispatch == Some(FunctionDispatch::ArraySlices))
523        else {
524            return false;
525        };
526        let Some(Ok(access)) = super::ArrayAccess::from_dispatch(
527            FunctionDispatch::ArraySlices,
528            arguments,
529            is_bare_null,
530        ) else {
531            return false;
532        };
533        binding.dispatch = Some(FunctionDispatch::ArraySlicesWithBounds(
534            access.slice_bounds().expect("slice bounds"),
535        ));
536        true
537    }
538
539    /// Construct the identity marker used when `PostgreSQL` parses a polymorphic syntax expression instead of an ordinary function call.
540    #[must_use]
541    pub fn polymorphic_builtin_syntax(name: &str) -> Self {
542        assert!(Self::is_polymorphic_builtin_syntax_name(name));
543        Self {
544            object_id: None,
545            name: name.into(),
546            argument_types: Vec::new(),
547            builtin: true,
548            dispatch: None,
549            invocation: None,
550            composite_field: None,
551            resolution_error: None,
552            input_collation: None,
553        }
554    }
555
556    /// Construct a parser- or binder-owned expression with an identity that cannot collide with a SQL routine name.
557    #[must_use]
558    pub fn dispatched(dispatch: FunctionDispatch) -> Self {
559        Self::dispatched_with_control(
560            dispatch,
561            &uqa_core::memory::ProductionControl::uncontrolled(),
562        )
563        .expect("ordinary dispatch constructor cannot be cancelled or limited")
564        .into_uncontrolled()
565        .expect("ordinary dispatch owner")
566    }
567
568    pub fn dispatched_with_control(
569        dispatch: FunctionDispatch,
570        control: &uqa_core::memory::ProductionControl<'_>,
571    ) -> Result<uqa_core::memory::Produced<Self>, uqa_core::ValueRetentionError> {
572        let (name, memory) = control.copy_text(dispatch.label())?.into_parts();
573        control.finish(
574            Self {
575                object_id: None,
576                name,
577                argument_types: Vec::new(),
578                builtin: true,
579                dispatch: Some(dispatch),
580                invocation: None,
581                composite_field: None,
582                resolution_error: None,
583                input_collation: None,
584            },
585            memory,
586        )
587    }
588
589    /// Preserve an undefined-overload error structurally without fabricating a dispatch name.
590    #[must_use]
591    pub fn undefined_function(name: impl Into<String>, signature: impl Into<String>) -> Self {
592        Self {
593            object_id: None,
594            name: name.into(),
595            argument_types: Vec::new(),
596            builtin: false,
597            dispatch: None,
598            invocation: None,
599            composite_field: None,
600            resolution_error: Some(Box::new(FunctionResolutionError::UndefinedFunction {
601                signature: signature.into(),
602            })),
603            input_collation: None,
604        }
605    }
606
607    /// Upgrade one function node from older serialized catalog syntax. Bound user routines are left untouched even when their SQL names resemble an old compiler marker.
608    #[doc(hidden)]
609    pub fn upgrade_legacy_serialized_dispatch(
610        display_name: &mut String,
611        binding: &mut Option<Self>,
612    ) -> bool {
613        if binding
614            .as_ref()
615            .is_some_and(|binding| binding.dispatch.is_some() || !binding.builtin)
616        {
617            return false;
618        }
619        let Some(dispatch) = FunctionDispatch::from_legacy_serialized_name(display_name) else {
620            return false;
621        };
622        if let Some(binding) = binding {
623            binding.dispatch = Some(dispatch);
624            display_name.clone_from(&binding.name);
625        } else {
626            let upgraded = Self::dispatched(dispatch);
627            display_name.clone_from(&upgraded.name);
628            *binding = Some(upgraded);
629        }
630        true
631    }
632
633    /// The input collation a collation-dependent built-in runs with: the retained selection, or the database default collation when none was recorded.
634    #[must_use]
635    pub fn selected_input_collation(binding: Option<&Self>) -> u32 {
636        binding.and_then(|binding| binding.input_collation).map_or(
637            crate::catalog::collations::DEFAULT_COLLATION_OID as u32,
638            |selected| selected.oid(),
639        )
640    }
641
642    /// Replace the binding of an analyzed call with a later structural or overload selection. Later binding passes do not observe argument collations, so the selection keeps the input collation analysis retained.
643    pub fn rebind(binding: &mut Option<Self>, mut selected: Self) {
644        if selected.input_collation.is_none() {
645            selected.input_collation = binding.as_ref().and_then(|binding| binding.input_collation);
646        }
647        *binding = Some(selected);
648    }
649
650    /// A built-in call that analysis selected by name, without a registered catalog signature, retained so its input collation reaches execution.
651    #[must_use]
652    pub fn builtin_by_name(
653        name: &str,
654        input_collation: Option<crate::catalog::collations::CollationSelection>,
655    ) -> Self {
656        Self {
657            object_id: None,
658            name: name.into(),
659            argument_types: Vec::new(),
660            builtin: true,
661            dispatch: None,
662            invocation: None,
663            composite_field: None,
664            resolution_error: None,
665            input_collation,
666        }
667    }
668
669    /// Return whether this binding marks a polymorphic syntax expression whose argument types must be inferred from its operands.
670    #[must_use]
671    pub fn is_polymorphic_builtin_syntax(&self) -> bool {
672        self.builtin
673            && self.argument_types.is_empty()
674            && Self::is_polymorphic_builtin_syntax_name(&self.name)
675    }
676
677    /// Return whether an unqualified local name belongs to `PostgreSQL`'s polymorphic function-like syntax expressions.
678    #[must_use]
679    pub fn is_polymorphic_builtin_syntax_name(name: &str) -> bool {
680        matches!(name, "coalesce" | "greatest" | "least" | "nullif")
681    }
682}
683
684pub type GeneratedFunctionDependency = FunctionBinding;