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