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