1use serde::{Deserialize, Serialize};
8
9use super::{EnumFunctionOperation, RangeSubtype};
10
11#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
12pub struct FunctionBinding {
13 #[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 #[serde(default, skip_serializing_if = "Option::is_none")]
22 pub dispatch: Option<FunctionDispatch>,
23 #[serde(default, skip_serializing_if = "Option::is_none")]
25 pub invocation: Option<Box<RoutineInvocationBinding>>,
26 #[serde(default, skip_serializing_if = "Option::is_none")]
28 pub composite_field: Option<Box<CompositeFieldBinding>>,
29 #[serde(default, skip_serializing_if = "Option::is_none")]
31 pub resolution_error: Option<Box<FunctionResolutionError>>,
32 #[serde(default, skip_serializing_if = "Option::is_none")]
34 pub input_collation: Option<crate::catalog::collations::CollationSelection>,
35}
36
37#[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 #[serde(default, skip_serializing_if = "Option::is_none")]
45 pub collation_oid: Option<u32>,
46 pub dropped: bool,
47 #[serde(default, skip_serializing_if = "Option::is_none")]
49 pub changed_type: Option<super::ColumnType>,
50}
51
52#[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#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
82pub enum FunctionDispatch {
83 NumericOperator(NumericOperator),
84 Pattern {
86 operator: super::PatternOperator,
87 oid: Option<std::num::NonZeroU32>,
88 },
89 PatternEscape {
91 similar: bool,
92 },
93 BooleanTest(BooleanTest),
95 Collate {
97 oid: Option<u32>,
98 },
99 CollationFor {
101 collation_oid: u32,
102 noncollatable_type_oid: Option<u32>,
103 },
104 TypeOf {
106 type_oid: u32,
107 },
108 NamedArgument,
109 VariadicArgument,
110 ArraySubscripts,
111 ArraySlices,
112 ArraySlicesWithBounds(super::ArraySliceBounds),
114 Subscript,
115 Slice,
116 FieldSelect,
118 AnyOperator,
119 AllOperator,
120 IsDistinct,
121 DistinctNot,
123 RowDistinct,
125 ValueIsDistinct,
127 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 RegexSubstring,
143 SimilarSubstring,
145 ArraySortJson,
146 Concat {
148 oid: Option<u32>,
149 },
150 ArrayConcat,
152 ArrayAppend,
153 ArrayPrepend,
154 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 Enum {
170 operation: EnumFunctionOperation,
171 type_oid: u32,
172 },
173 MergeAction,
175}
176
177#[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 #[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#[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 ContainsElement,
245 ElementContainedBy,
247 Adjacent,
248}
249
250impl FunctionDispatch {
251 #[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 #[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 #[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 #[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#[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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
483pub struct RoutineInvocationBinding {
484 pub argument_positions: Vec<usize>,
486 pub argument_targets: Vec<String>,
488 #[serde(default, skip_serializing_if = "Vec::is_empty")]
490 pub argument_sources: Vec<Option<String>>,
491 pub parameter_types: Vec<String>,
493 pub return_type: Option<String>,
495 pub variadic_mode: RoutineVariadicMode,
497}
498
499#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
501pub enum RoutineVariadicMode {
502 #[default]
504 None,
505 Expanded {
507 parameter_index: usize,
509 },
510 Explicit {
512 parameter_index: usize,
514 },
515}
516
517impl FunctionBinding {
518 #[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 #[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 #[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 #[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 #[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 #[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 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 #[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 #[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 #[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;