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(flatten)]
28 pub value_binding: Option<Box<FunctionValueBinding>>,
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)]
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#[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 #[serde(default, skip_serializing_if = "Option::is_none")]
80 pub collation_oid: Option<u32>,
81 pub dropped: bool,
82 #[serde(default, skip_serializing_if = "Option::is_none")]
84 pub changed_type: Option<super::ColumnType>,
85}
86
87#[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#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
117pub enum FunctionDispatch {
118 NumericOperator(NumericOperator),
119 Pattern {
121 operator: super::PatternOperator,
122 oid: Option<std::num::NonZeroU32>,
123 },
124 PatternEscape {
126 similar: bool,
127 },
128 BooleanTest(BooleanTest),
130 Collate {
132 oid: Option<u32>,
133 },
134 CollationFor {
136 collation_oid: u32,
137 noncollatable_type_oid: Option<u32>,
138 },
139 TypeOf {
141 type_oid: u32,
142 },
143 NamedArgument,
144 VariadicArgument,
145 ArraySubscripts,
146 ArraySlices,
147 ArraySlicesWithBounds(super::ArraySliceBounds),
149 Subscript,
150 Slice,
151 FieldSelect,
153 AssignmentStore,
155 AnyOperator,
156 AllOperator,
157 IsDistinct,
158 DistinctNot,
160 RowDistinct,
162 ValueIsDistinct,
164 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 RegexSubstring,
180 SimilarSubstring,
182 ArraySortJson,
183 Concat {
185 oid: Option<u32>,
186 },
187 ArrayConcat,
189 ArrayAppend,
190 ArrayPrepend,
191 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 Enum {
207 operation: EnumFunctionOperation,
208 type_oid: u32,
209 },
210 MergeAction,
212}
213
214#[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 #[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#[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 ContainsElement,
282 ElementContainedBy,
284 Adjacent,
285}
286
287impl FunctionDispatch {
288 #[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 #[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 #[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 #[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#[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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
539pub struct RoutineInvocationBinding {
540 pub argument_positions: Vec<usize>,
542 pub argument_targets: Vec<String>,
544 #[serde(default, skip_serializing_if = "Vec::is_empty")]
546 pub argument_sources: Vec<Option<String>>,
547 pub parameter_types: Vec<String>,
549 pub return_type: Option<String>,
551 pub variadic_mode: RoutineVariadicMode,
553}
554
555#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
557pub enum RoutineVariadicMode {
558 #[default]
560 None,
561 Expanded {
563 parameter_index: usize,
565 },
566 Explicit {
568 parameter_index: usize,
570 },
571}
572
573impl FunctionBinding {
574 #[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 #[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 #[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 #[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 #[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 #[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 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 #[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 #[must_use]
732 pub fn is_polymorphic_builtin_syntax(&self) -> bool {
733 self.builtin
734 && self.argument_types.is_empty()
735 && Self::is_polymorphic_builtin_syntax_name(&self.name)
736 }
737
738 #[must_use]
740 pub fn is_polymorphic_builtin_syntax_name(name: &str) -> bool {
741 matches!(name, "coalesce" | "greatest" | "least" | "nullif")
742 }
743}
744
745pub type GeneratedFunctionDependency = FunctionBinding;