uqa-sql 0.6.3

PostgreSQL-compatible SQL compiler built on libpg_query
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
//
// Unified Query Algebra
//
// Copyright (c) 2023-2026 Cognica, Inc.
//

use serde::{Deserialize, Serialize};

use super::{EnumFunctionOperation, RangeSubtype};

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct FunctionBinding {
    /// Stable identity of a bound user routine. Built-ins and unbound calls leave this unset.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub object_id: Option<[u8; 16]>,
    pub name: String,
    pub argument_types: Vec<String>,
    #[serde(default)]
    pub builtin: bool,
    /// Executor operation selected structurally during parsing or overload binding. SQL-visible routine lookup never consults display-name conventions for these operations.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub dispatch: Option<FunctionDispatch>,
    /// Concrete invocation contract selected during routine overload resolution.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub invocation: Option<Box<RoutineInvocationBinding>>,
    /// Field selection and assignment carry mutually exclusive typed value metadata outside ordinary expression storage.
    #[serde(flatten)]
    pub value_binding: Option<Box<FunctionValueBinding>>,
    /// 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.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub resolution_error: Option<Box<FunctionResolutionError>>,
    /// 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.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub input_collation: Option<crate::catalog::collations::CollationSelection>,
}

/// Typed native value operations share one optional allocation. The external keys preserve stored field-selection bindings.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum FunctionValueBinding {
    CompositeField(CompositeFieldBinding),
    Assignment(super::AssignmentBinding),
}

impl FunctionBinding {
    pub fn composite_field(&self) -> Option<&CompositeFieldBinding> {
        match self.value_binding.as_deref() {
            Some(FunctionValueBinding::CompositeField(field)) => Some(field),
            _ => None,
        }
    }
    pub fn composite_field_mut(&mut self) -> Option<&mut CompositeFieldBinding> {
        match self.value_binding.as_deref_mut() {
            Some(FunctionValueBinding::CompositeField(field)) => Some(field),
            _ => None,
        }
    }
    pub fn set_composite_field(&mut self, field: CompositeFieldBinding) {
        self.value_binding = Some(Box::new(FunctionValueBinding::CompositeField(field)));
    }
    pub fn assignment(&self) -> Option<&super::AssignmentBinding> {
        match self.value_binding.as_deref() {
            Some(FunctionValueBinding::Assignment(assignment)) => Some(assignment),
            _ => None,
        }
    }
    pub fn set_assignment(&mut self, assignment: super::AssignmentBinding) {
        self.value_binding = Some(Box::new(FunctionValueBinding::Assignment(assignment)));
    }
}

/// A field selected during preparation. Attribute numbers are never reused, even when a later attribute has the same name.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CompositeFieldBinding {
    pub type_oid: u32,
    pub number: i16,
    pub result_type: super::ColumnType,
    /// The field's declaration at preparation, independently of the argument's collation.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub collation_oid: Option<u32>,
    pub dropped: bool,
    /// 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.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub changed_type: Option<super::ColumnType>,
}

/// Static function-call failure discovered while binding declared argument types.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum FunctionResolutionError {
    UndefinedFunction { signature: String },
    Operator(Box<OperatorResolutionError>),
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct OperatorResolutionError {
    pub sqlstate: String,
    pub message: String,
}

impl FunctionResolutionError {
    #[must_use]
    pub fn sql_error(&self) -> crate::SQLError {
        match self {
            Self::UndefinedFunction { signature } => {
                crate::SQLError::undefined_function_call(signature)
            }
            Self::Operator(error) => crate::SQLError::Routine {
                sqlstate: error.sqlstate.clone(),
                message: error.message.clone(),
            },
        }
    }
}

/// Structural identity for parser-owned expressions and overload-specific built-in implementations. These variants occupy no SQL function-name namespace.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum FunctionDispatch {
    NumericOperator(NumericOperator),
    /// SQL pattern syntax, retaining its selected binary operator after escape processing.
    Pattern {
        operator: super::PatternOperator,
        oid: Option<std::num::NonZeroU32>,
    },
    /// A parser-owned escape helper, evaluated and folded independently of the strict match operator.
    PatternEscape {
        similar: bool,
    },
    /// A non-strict SQL Boolean test, distinct from routine lookup and equality.
    BooleanTest(BooleanTest),
    /// A collation clause, retaining its selected identity independently of its written name.
    Collate {
        oid: Option<u32>,
    },
    /// The selected argument metadata of `pg_collation_for`; the argument still executes before the observation.
    CollationFor {
        collation_oid: u32,
        noncollatable_type_oid: Option<u32>,
    },
    /// The analyzed argument type of `pg_typeof`; ordinary argument evaluation still precedes the observation.
    TypeOf {
        type_oid: u32,
    },
    NamedArgument,
    VariadicArgument,
    ArraySubscripts,
    ArraySlices,
    /// Slice syntax with independently retained omitted endpoints.
    ArraySlicesWithBounds(super::ArraySliceBounds),
    Subscript,
    Slice,
    /// `(expression).field`: the field of a composite value, or the key of a document map.
    FieldSelect,
    /// Rebuild a typed assignment path using the binding's operand positions.
    AssignmentStore,
    AnyOperator,
    AllOperator,
    IsDistinct,
    /// Negation synthesized by IS NOT DISTINCT FROM, whose operand is not a written Boolean context.
    DistinctNot,
    /// Disjunction of selected ROW DISTINCT field comparisons, with ordered short-circuit evaluation.
    RowDistinct,
    /// One selected DISTINCT comparison of complete field values; nested ROW constructors remain one record-valued operand.
    ValueIsDistinct,
    /// The outer NULL test selected by DISTINCT against a bare NULL, without testing individual record fields or requiring equality.
    ValueNullTest {
        negated: bool,
    },
    BetweenSymmetric,
    ToBinInt4,
    ToBinInt8,
    ToHexInt4,
    ToHexInt8,
    ToOctInt4,
    ToOctInt8,
    RandomInt4Range,
    RandomInt8Range,
    RandomNumericRange,
    /// `substring(text, text)`: the POSIX regular-expression extraction selected by overload resolution, never inferred from argument values.
    RegexSubstring,
    /// `substring(text, text, text)`: SQL regular-expression extraction, which applies `similar_to_escape` before the POSIX extraction.
    SimilarSubstring,
    ArraySortJson,
    /// SQL concatenation syntax, with its selected catalog overload after operand analysis.
    Concat {
        oid: Option<u32>,
    },
    /// The selected array `||` overload, retained even when its arguments evaluate to NULL.
    ArrayConcat,
    ArrayAppend,
    ArrayPrepend,
    /// A resolved JSON path function whose final argument is the declared text array.
    JsonPath {
        as_text: bool,
        jsonb: bool,
    },
    JsonExtract {
        as_text: bool,
        path: bool,
    },
    Range {
        operation: RangeFunctionOperation,
        subtype: RangeSubtype,
        multirange: bool,
    },
    /// An `anyenum` support function bound to one concrete enum type.
    Enum {
        operation: EnumFunctionOperation,
        type_oid: u32,
    },
    /// The current MERGE action, read from the executor-owned row attribute.
    MergeAction,
}

/// The six predicates over SQL's true, false and NULL Boolean inputs.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum BooleanTest {
    IsTrue,
    IsNotTrue,
    IsFalse,
    IsNotFalse,
    IsUnknown,
    IsNotUnknown,
}

impl BooleanTest {
    #[must_use]
    pub const fn label(self) -> &'static str {
        match self {
            Self::IsTrue => "IS TRUE",
            Self::IsNotTrue => "IS NOT TRUE",
            Self::IsFalse => "IS FALSE",
            Self::IsNotFalse => "IS NOT FALSE",
            Self::IsUnknown => "IS UNKNOWN",
            Self::IsNotUnknown => "IS NOT UNKNOWN",
        }
    }

    /// Stable `PostgreSQL` catalog node identity, independent of parser protobuf tags.
    #[must_use]
    pub const fn catalog_code(self) -> i64 {
        match self {
            Self::IsTrue => 0,
            Self::IsNotTrue => 1,
            Self::IsFalse => 2,
            Self::IsNotFalse => 3,
            Self::IsUnknown => 4,
            Self::IsNotUnknown => 5,
        }
    }

    #[must_use]
    pub const fn from_catalog_code(code: i64) -> Option<Self> {
        match code {
            0 => Some(Self::IsTrue),
            1 => Some(Self::IsNotTrue),
            2 => Some(Self::IsFalse),
            3 => Some(Self::IsNotFalse),
            4 => Some(Self::IsUnknown),
            5 => Some(Self::IsNotUnknown),
            _ => None,
        }
    }
}

/// Operation selected for one typed range or multirange call.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum RangeFunctionOperation {
    Lower,
    Upper,
    IsEmpty,
    LowerInclusive,
    UpperInclusive,
    LowerInfinite,
    UpperInfinite,
    Merge,
    Multirange,
    Overlap,
    Contains,
    ContainedBy,
    /// The range operand is first; the second operand has its declared subtype.
    ContainsElement,
    /// The range operand is second; the first operand has its declared subtype.
    ElementContainedBy,
    Adjacent,
}

impl FunctionDispatch {
    /// Whether this expression retains SQL concatenation syntax and operand roles.
    #[must_use]
    pub const fn is_concatenation(self) -> bool {
        matches!(
            self,
            Self::Concat { .. } | Self::ArrayConcat | Self::ArrayAppend | Self::ArrayPrepend
        )
    }

    /// Human-readable expression label used only in diagnostics and serialized plans; dispatch is always selected by the enum variant.
    #[must_use]
    pub const fn label(self) -> &'static str {
        match self {
            Self::MergeAction => "merge_action",
            Self::NumericOperator(operator) => operator.symbol(),
            Self::Pattern { operator, .. } => operator.syntax(),
            Self::PatternEscape { similar: false } => "pg_catalog.like_escape",
            Self::PatternEscape { similar: true } => "pg_catalog.similar_to_escape",
            Self::BooleanTest(test) => test.label(),
            Self::Collate { .. } => "COLLATE",
            Self::CollationFor { .. } => "pg_catalog.pg_collation_for",
            Self::TypeOf { .. } => "pg_catalog.pg_typeof",
            Self::NamedArgument => "named argument",
            Self::VariadicArgument => "VARIADIC argument",
            Self::ArraySubscripts | Self::Subscript => "subscript",
            Self::ArraySlices | Self::ArraySlicesWithBounds(_) | Self::Slice => "slice",
            Self::FieldSelect => "field selection",
            Self::AssignmentStore => "assignment",
            Self::AnyOperator => "ANY operator",
            Self::AllOperator => "ALL operator",
            Self::IsDistinct | Self::ValueIsDistinct | Self::RowDistinct => "IS DISTINCT FROM",
            Self::DistinctNot => "IS NOT DISTINCT FROM",
            Self::ValueNullTest { negated: false } => "IS NULL",
            Self::ValueNullTest { negated: true } => "IS NOT NULL",
            Self::BetweenSymmetric => "BETWEEN SYMMETRIC",
            Self::ToBinInt4 | Self::ToBinInt8 => "pg_catalog.to_bin",
            Self::ToHexInt4 | Self::ToHexInt8 => "pg_catalog.to_hex",
            Self::ToOctInt4 | Self::ToOctInt8 => "pg_catalog.to_oct",
            Self::RandomInt4Range | Self::RandomInt8Range | Self::RandomNumericRange => {
                "pg_catalog.random"
            }
            Self::RegexSubstring | Self::SimilarSubstring => "pg_catalog.substring",
            Self::ArraySortJson => "pg_catalog.array_sort",
            Self::Concat { .. } => "||",
            Self::ArrayConcat => "pg_catalog.array_cat",
            Self::ArrayAppend => "pg_catalog.array_append",
            Self::ArrayPrepend => "pg_catalog.array_prepend",
            Self::JsonPath {
                as_text: false,
                jsonb: false,
            } => "pg_catalog.json_extract_path",
            Self::JsonPath {
                as_text: true,
                jsonb: false,
            } => "pg_catalog.json_extract_path_text",
            Self::JsonPath {
                as_text: false,
                jsonb: true,
            } => "pg_catalog.jsonb_extract_path",
            Self::JsonPath {
                as_text: true,
                jsonb: true,
            } => "pg_catalog.jsonb_extract_path_text",
            Self::JsonExtract { as_text: false, .. } => "JSON extraction operator",
            Self::JsonExtract { as_text: true, .. } => "JSON text extraction operator",
            Self::Range { operation, .. } => operation.label(),
            Self::Enum { operation, .. } => operation.label(),
        }
    }

    #[must_use]
    pub const fn is_call_argument_marker(self) -> bool {
        matches!(self, Self::NamedArgument | Self::VariadicArgument)
    }

    /// The SQL spelling of a retained JSON extraction operator, independent of its diagnostic label.
    #[must_use]
    pub const fn json_extraction_symbol(self) -> Option<&'static str> {
        match self {
            Self::JsonExtract {
                as_text: false,
                path: false,
            } => Some("->"),
            Self::JsonExtract {
                as_text: true,
                path: false,
            } => Some("->>"),
            Self::JsonExtract {
                as_text: false,
                path: true,
            } => Some("#>"),
            Self::JsonExtract {
                as_text: true,
                path: true,
            } => Some("#>>"),
            _ => None,
        }
    }

    /// Decode function spellings in older durable expressions. This is a catalog migration primitive, never a SQL routine lookup path.
    #[doc(hidden)]
    #[must_use]
    pub fn from_legacy_serialized_name(name: &str) -> Option<Self> {
        let fixed = match name {
            "merge_action" => Self::MergeAction,
            "__named_arg" => Self::NamedArgument,
            "__variadic_arg" => Self::VariadicArgument,
            "__array_subscripts" => Self::ArraySubscripts,
            "__array_slices" => Self::ArraySlices,
            "__subscript" => Self::Subscript,
            "__slice" => Self::Slice,
            "__any_op" => Self::AnyOperator,
            "__all_op" => Self::AllOperator,
            "__is_distinct" => Self::IsDistinct,
            "__between_symmetric" => Self::BetweenSymmetric,
            "__to_bin_int4" => Self::ToBinInt4,
            "__to_bin_int8" => Self::ToBinInt8,
            "__to_hex_int4" => Self::ToHexInt4,
            "__to_hex_int8" => Self::ToHexInt8,
            "__to_oct_int4" => Self::ToOctInt4,
            "__to_oct_int8" => Self::ToOctInt8,
            "__random_int4_range" => Self::RandomInt4Range,
            "__random_int8_range" => Self::RandomInt8Range,
            "__random_numeric_range" => Self::RandomNumericRange,
            "__array_sort_json" => Self::ArraySortJson,
            _ => return Self::legacy_range_dispatch(name),
        };
        Some(fixed)
    }

    fn legacy_range_dispatch(name: &str) -> Option<Self> {
        let encoded = name.strip_prefix("__range_")?;
        let subtypes = [
            RangeSubtype::Integer,
            RangeSubtype::BigInteger,
            RangeSubtype::Numeric,
            RangeSubtype::Date,
            RangeSubtype::Timestamp,
            RangeSubtype::TimestampTz,
        ];
        for subtype in subtypes {
            for (type_name, multirange) in [
                (subtype.multirange_name(), true),
                (subtype.range_name(), false),
            ] {
                let Some(operation) = encoded.strip_suffix(type_name) else {
                    continue;
                };
                let operation = match operation.trim_end_matches('_') {
                    "lower" => RangeFunctionOperation::Lower,
                    "upper" => RangeFunctionOperation::Upper,
                    "isempty" => RangeFunctionOperation::IsEmpty,
                    "lower_inc" => RangeFunctionOperation::LowerInclusive,
                    "upper_inc" => RangeFunctionOperation::UpperInclusive,
                    "lower_inf" => RangeFunctionOperation::LowerInfinite,
                    "upper_inf" => RangeFunctionOperation::UpperInfinite,
                    "merge" => RangeFunctionOperation::Merge,
                    "multirange" => RangeFunctionOperation::Multirange,
                    "overlap" => RangeFunctionOperation::Overlap,
                    "contains" => RangeFunctionOperation::Contains,
                    "contained_by" => RangeFunctionOperation::ContainedBy,
                    "adjacent" => RangeFunctionOperation::Adjacent,
                    _ => continue,
                };
                return Some(Self::Range {
                    operation,
                    subtype,
                    multirange,
                });
            }
        }
        None
    }
}

/// Numeric operator syntax, kept separate from ordinary calls such as `mod` or `abs`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum NumericOperator {
    Modulo,
    Power,
    Plus,
    SquareRoot,
    CubeRoot,
    Absolute,
    BitAnd,
    BitOr,
    BitXor,
    BitNot,
    ShiftLeft,
    ShiftRight,
}

impl NumericOperator {
    #[must_use]
    pub const fn symbol(self) -> &'static str {
        match self {
            Self::Modulo => "%",
            Self::Power => "^",
            Self::Plus => "+",
            Self::SquareRoot => "|/",
            Self::CubeRoot => "||/",
            Self::Absolute => "@",
            Self::BitAnd => "&",
            Self::BitOr => "|",
            Self::BitXor => "#",
            Self::BitNot => "~",
            Self::ShiftLeft => "<<",
            Self::ShiftRight => ">>",
        }
    }

    #[must_use]
    pub const fn arity(self) -> usize {
        match self {
            Self::Modulo
            | Self::Power
            | Self::BitAnd
            | Self::BitOr
            | Self::BitXor
            | Self::ShiftLeft
            | Self::ShiftRight => 2,
            Self::Plus | Self::SquareRoot | Self::CubeRoot | Self::Absolute | Self::BitNot => 1,
        }
    }
}

impl RangeFunctionOperation {
    #[must_use]
    pub const fn label(self) -> &'static str {
        match self {
            Self::Lower => "pg_catalog.lower",
            Self::Upper => "pg_catalog.upper",
            Self::IsEmpty => "pg_catalog.isempty",
            Self::LowerInclusive => "pg_catalog.lower_inc",
            Self::UpperInclusive => "pg_catalog.upper_inc",
            Self::LowerInfinite => "pg_catalog.lower_inf",
            Self::UpperInfinite => "pg_catalog.upper_inf",
            Self::Merge => "pg_catalog.range_merge",
            Self::Multirange => "pg_catalog.multirange",
            Self::Overlap => "range overlap operator",
            Self::Contains => "range contains operator",
            Self::ContainedBy => "range contained-by operator",
            Self::ContainsElement => "range contains element operator",
            Self::ElementContainedBy => "element contained-by range operator",
            Self::Adjacent => "range adjacent operator",
        }
    }
}

/// Concrete parameter and result types selected for one routine invocation.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RoutineInvocationBinding {
    /// Zero-based declared parameter index for each call argument, aligned with the call argument list.
    pub argument_positions: Vec<usize>,
    /// Concrete coercion target for each call argument, aligned with the call argument list.
    pub argument_targets: Vec<String>,
    /// Declared source types before argument coercion; absent only in legacy bindings.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub argument_sources: Vec<Option<String>>,
    /// Concrete type for each declared parameter, aligned with [`crate::ast::CreateFunction::params`].
    pub parameter_types: Vec<String>,
    /// Concrete invocation result type after polymorphic substitution.
    pub return_type: Option<String>,
    /// Whether and where the declared variadic parameter participates in this invocation.
    pub variadic_mode: RoutineVariadicMode,
}

/// Call syntax selected for a routine's variadic parameter.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum RoutineVariadicMode {
    /// The invocation does not use a variadic parameter.
    #[default]
    None,
    /// Trailing call arguments are expanded into the declared variadic array parameter.
    Expanded {
        /// Zero-based index in [`crate::ast::CreateFunction::params`].
        parameter_index: usize,
    },
    /// An explicit `VARIADIC` array argument supplies the declared variadic parameter.
    Explicit {
        /// Zero-based index in [`crate::ast::CreateFunction::params`].
        parameter_index: usize,
    },
}

impl FunctionBinding {
    /// Preserve the predecessor format's encoded omission before an optimizer can fold supplied expressions to NULL.
    #[doc(hidden)]
    pub fn upgrade_legacy_array_slices(
        binding: &mut Option<Self>,
        arguments: usize,
        is_bare_null: impl Fn(usize) -> bool,
    ) -> bool {
        let Some(binding) = binding
            .as_mut()
            .filter(|binding| binding.dispatch == Some(FunctionDispatch::ArraySlices))
        else {
            return false;
        };
        let Some(Ok(access)) = super::ArrayAccess::from_dispatch(
            FunctionDispatch::ArraySlices,
            arguments,
            is_bare_null,
        ) else {
            return false;
        };
        binding.dispatch = Some(FunctionDispatch::ArraySlicesWithBounds(
            access.slice_bounds().expect("slice bounds"),
        ));
        true
    }

    /// Construct the identity marker used when `PostgreSQL` parses a polymorphic syntax expression instead of an ordinary function call.
    #[must_use]
    pub fn polymorphic_builtin_syntax(name: &str) -> Self {
        assert!(Self::is_polymorphic_builtin_syntax_name(name));
        Self {
            object_id: None,
            name: name.into(),
            argument_types: Vec::new(),
            builtin: true,
            dispatch: None,
            invocation: None,
            value_binding: None,
            resolution_error: None,
            input_collation: None,
        }
    }

    /// Construct a parser- or binder-owned expression with an identity that cannot collide with a SQL routine name.
    #[must_use]
    pub fn dispatched(dispatch: FunctionDispatch) -> Self {
        Self::dispatched_with_control(
            dispatch,
            &uqa_core::memory::ProductionControl::uncontrolled(),
        )
        .expect("ordinary dispatch constructor cannot be cancelled or limited")
        .into_uncontrolled()
        .expect("ordinary dispatch owner")
    }

    pub fn dispatched_with_control(
        dispatch: FunctionDispatch,
        control: &uqa_core::memory::ProductionControl<'_>,
    ) -> Result<uqa_core::memory::Produced<Self>, uqa_core::ValueRetentionError> {
        let (name, memory) = control.copy_text(dispatch.label())?.into_parts();
        control.finish(
            Self {
                object_id: None,
                name,
                argument_types: Vec::new(),
                builtin: true,
                dispatch: Some(dispatch),
                invocation: None,
                value_binding: None,
                resolution_error: None,
                input_collation: None,
            },
            memory,
        )
    }

    /// Preserve an undefined-overload error structurally without fabricating a dispatch name.
    #[must_use]
    pub fn undefined_function(name: impl Into<String>, signature: impl Into<String>) -> Self {
        Self {
            object_id: None,
            name: name.into(),
            argument_types: Vec::new(),
            builtin: false,
            dispatch: None,
            invocation: None,
            value_binding: None,
            resolution_error: Some(Box::new(FunctionResolutionError::UndefinedFunction {
                signature: signature.into(),
            })),
            input_collation: None,
        }
    }

    /// 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.
    #[doc(hidden)]
    pub fn upgrade_legacy_serialized_dispatch(
        display_name: &mut String,
        binding: &mut Option<Self>,
    ) -> bool {
        if binding
            .as_ref()
            .is_some_and(|binding| binding.dispatch.is_some() || !binding.builtin)
        {
            return false;
        }
        let Some(dispatch) = FunctionDispatch::from_legacy_serialized_name(display_name) else {
            return false;
        };
        if let Some(binding) = binding {
            binding.dispatch = Some(dispatch);
            display_name.clone_from(&binding.name);
        } else {
            let upgraded = Self::dispatched(dispatch);
            display_name.clone_from(&upgraded.name);
            *binding = Some(upgraded);
        }
        true
    }

    /// The input collation a collation-dependent built-in runs with: the retained selection, or the database default collation when none was recorded.
    #[must_use]
    pub fn selected_input_collation(binding: Option<&Self>) -> u32 {
        binding.and_then(|binding| binding.input_collation).map_or(
            crate::catalog::collations::DEFAULT_COLLATION_OID as u32,
            |selected| selected.oid(),
        )
    }

    /// 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.
    pub fn rebind(binding: &mut Option<Self>, mut selected: Self) {
        if selected.input_collation.is_none() {
            selected.input_collation = binding.as_ref().and_then(|binding| binding.input_collation);
        }
        *binding = Some(selected);
    }

    /// A built-in call that analysis selected by name, without a registered catalog signature, retained so its input collation reaches execution.
    #[must_use]
    pub fn builtin_by_name(
        name: &str,
        input_collation: Option<crate::catalog::collations::CollationSelection>,
    ) -> Self {
        Self {
            object_id: None,
            name: name.into(),
            argument_types: Vec::new(),
            builtin: true,
            dispatch: None,
            invocation: None,
            value_binding: None,
            resolution_error: None,
            input_collation,
        }
    }

    /// Admit a dynamically selected built-in name before constructing its retained binding.
    pub(crate) fn builtin_by_name_with_control(
        name: &str,
        input_collation: Option<crate::catalog::collations::CollationSelection>,
        control: &uqa_core::memory::ProductionControl<'_>,
    ) -> Result<uqa_core::memory::Produced<Self>, crate::SQLError> {
        let (name, memory) = control.copy_text(name)?.into_parts();
        Ok(control.finish(
            Self {
                object_id: None,
                name,
                argument_types: Vec::new(),
                builtin: true,
                dispatch: None,
                invocation: None,
                value_binding: None,
                resolution_error: None,
                input_collation,
            },
            memory,
        )?)
    }

    /// Return whether this binding marks a polymorphic syntax expression whose argument types must be inferred from its operands.
    #[must_use]
    pub fn is_polymorphic_builtin_syntax(&self) -> bool {
        self.builtin
            && self.argument_types.is_empty()
            && Self::is_polymorphic_builtin_syntax_name(&self.name)
    }

    /// Return whether an unqualified local name belongs to `PostgreSQL`'s polymorphic function-like syntax expressions.
    #[must_use]
    pub fn is_polymorphic_builtin_syntax_name(name: &str) -> bool {
        matches!(name, "coalesce" | "greatest" | "least" | "nullif")
    }
}

pub type GeneratedFunctionDependency = FunctionBinding;