uqa-sql 0.4.0

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
//
// Unified Query Algebra
//
// Copyright (c) 2023-2026 Cognica, Inc.
//

use serde::{Deserialize, Serialize};

use super::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>>,
    /// 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<FunctionResolutionError>,
}

/// 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 {
        let (sqlstate, message) = match self {
            Self::UndefinedFunction { signature } => (
                "42883".to_string(),
                format!("function {signature} does not exist"),
            ),
            Self::Operator(error) => (error.sqlstate.clone(), error.message.clone()),
        };
        crate::SQLError::Routine { sqlstate, message }
    }
}

/// 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),
    NamedArgument,
    VariadicArgument,
    ArraySubscripts,
    ArraySlices,
    Subscript,
    Slice,
    AnyOperator,
    AllOperator,
    IsDistinct,
    BetweenSymmetric,
    ToBinInt4,
    ToBinInt8,
    ToHexInt4,
    ToHexInt8,
    ToOctInt4,
    ToOctInt8,
    RandomInt4Range,
    RandomInt8Range,
    RandomNumericRange,
    ArraySortJson,
    JsonExtract {
        as_text: bool,
        path: bool,
    },
    Range {
        operation: RangeFunctionOperation,
        subtype: RangeSubtype,
        multirange: bool,
    },
}

/// 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,
    Adjacent,
}

impl FunctionDispatch {
    /// 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::NumericOperator(operator) => operator.symbol(),
            Self::NamedArgument => "named argument",
            Self::VariadicArgument => "VARIADIC argument",
            Self::ArraySubscripts | Self::Subscript => "subscript",
            Self::ArraySlices | Self::Slice => "slice",
            Self::AnyOperator => "ANY operator",
            Self::AllOperator => "ALL operator",
            Self::IsDistinct => "IS DISTINCT FROM",
            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::ArraySortJson => "pg_catalog.array_sort",
            Self::JsonExtract { as_text: false, .. } => "JSON extraction operator",
            Self::JsonExtract { as_text: true, .. } => "JSON text extraction operator",
            Self::Range { operation, .. } => operation.label(),
        }
    }

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

    /// Decode the compiler-private function spellings written into durable expressions by releases through 0.1.6. 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 {
            "__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,
}

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 => "@",
        }
    }

    #[must_use]
    pub const fn arity(self) -> usize {
        match self {
            Self::Modulo | Self::Power => 2,
            Self::Plus | Self::SquareRoot | Self::CubeRoot | Self::Absolute => 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::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 {
    /// 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,
            resolution_error: 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,
                resolution_error: 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,
            resolution_error: Some(FunctionResolutionError::UndefinedFunction {
                signature: signature.into(),
            }),
        }
    }

    /// Upgrade one function node deserialized from the catalog format written by releases through 0.1.6. Bound user routines are deliberately 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
    }

    /// 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;