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 NamedArgument,
105 VariadicArgument,
106 ArraySubscripts,
107 ArraySlices,
108 ArraySlicesWithBounds(super::ArraySliceBounds),
110 Subscript,
111 Slice,
112 FieldSelect,
114 AnyOperator,
115 AllOperator,
116 IsDistinct,
117 DistinctNot,
119 RowDistinct,
121 ValueIsDistinct,
123 ValueNullTest {
125 negated: bool,
126 },
127 BetweenSymmetric,
128 ToBinInt4,
129 ToBinInt8,
130 ToHexInt4,
131 ToHexInt8,
132 ToOctInt4,
133 ToOctInt8,
134 RandomInt4Range,
135 RandomInt8Range,
136 RandomNumericRange,
137 RegexSubstring,
139 SimilarSubstring,
141 ArraySortJson,
142 Concat {
144 oid: Option<u32>,
145 },
146 ArrayConcat,
148 ArrayAppend,
149 ArrayPrepend,
150 JsonPath {
152 as_text: bool,
153 jsonb: bool,
154 },
155 JsonExtract {
156 as_text: bool,
157 path: bool,
158 },
159 Range {
160 operation: RangeFunctionOperation,
161 subtype: RangeSubtype,
162 multirange: bool,
163 },
164 Enum {
166 operation: EnumFunctionOperation,
167 type_oid: u32,
168 },
169 MergeAction,
171}
172
173#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
175pub enum BooleanTest {
176 IsTrue,
177 IsNotTrue,
178 IsFalse,
179 IsNotFalse,
180 IsUnknown,
181 IsNotUnknown,
182}
183
184impl BooleanTest {
185 #[must_use]
186 pub const fn label(self) -> &'static str {
187 match self {
188 Self::IsTrue => "IS TRUE",
189 Self::IsNotTrue => "IS NOT TRUE",
190 Self::IsFalse => "IS FALSE",
191 Self::IsNotFalse => "IS NOT FALSE",
192 Self::IsUnknown => "IS UNKNOWN",
193 Self::IsNotUnknown => "IS NOT UNKNOWN",
194 }
195 }
196
197 #[must_use]
199 pub const fn catalog_code(self) -> i64 {
200 match self {
201 Self::IsTrue => 0,
202 Self::IsNotTrue => 1,
203 Self::IsFalse => 2,
204 Self::IsNotFalse => 3,
205 Self::IsUnknown => 4,
206 Self::IsNotUnknown => 5,
207 }
208 }
209
210 #[must_use]
211 pub const fn from_catalog_code(code: i64) -> Option<Self> {
212 match code {
213 0 => Some(Self::IsTrue),
214 1 => Some(Self::IsNotTrue),
215 2 => Some(Self::IsFalse),
216 3 => Some(Self::IsNotFalse),
217 4 => Some(Self::IsUnknown),
218 5 => Some(Self::IsNotUnknown),
219 _ => None,
220 }
221 }
222}
223
224#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
226pub enum RangeFunctionOperation {
227 Lower,
228 Upper,
229 IsEmpty,
230 LowerInclusive,
231 UpperInclusive,
232 LowerInfinite,
233 UpperInfinite,
234 Merge,
235 Multirange,
236 Overlap,
237 Contains,
238 ContainedBy,
239 ContainsElement,
241 ElementContainedBy,
243 Adjacent,
244}
245
246impl FunctionDispatch {
247 #[must_use]
249 pub const fn is_concatenation(self) -> bool {
250 matches!(
251 self,
252 Self::Concat { .. } | Self::ArrayConcat | Self::ArrayAppend | Self::ArrayPrepend
253 )
254 }
255
256 #[must_use]
258 pub const fn label(self) -> &'static str {
259 match self {
260 Self::MergeAction => "merge_action",
261 Self::NumericOperator(operator) => operator.symbol(),
262 Self::Pattern { operator, .. } => operator.syntax(),
263 Self::PatternEscape { similar: false } => "pg_catalog.like_escape",
264 Self::PatternEscape { similar: true } => "pg_catalog.similar_to_escape",
265 Self::BooleanTest(test) => test.label(),
266 Self::Collate { .. } => "COLLATE",
267 Self::CollationFor { .. } => "pg_catalog.pg_collation_for",
268 Self::NamedArgument => "named argument",
269 Self::VariadicArgument => "VARIADIC argument",
270 Self::ArraySubscripts | Self::Subscript => "subscript",
271 Self::ArraySlices | Self::ArraySlicesWithBounds(_) | Self::Slice => "slice",
272 Self::FieldSelect => "field selection",
273 Self::AnyOperator => "ANY operator",
274 Self::AllOperator => "ALL operator",
275 Self::IsDistinct | Self::ValueIsDistinct | Self::RowDistinct => "IS DISTINCT FROM",
276 Self::DistinctNot => "IS NOT DISTINCT FROM",
277 Self::ValueNullTest { negated: false } => "IS NULL",
278 Self::ValueNullTest { negated: true } => "IS NOT NULL",
279 Self::BetweenSymmetric => "BETWEEN SYMMETRIC",
280 Self::ToBinInt4 | Self::ToBinInt8 => "pg_catalog.to_bin",
281 Self::ToHexInt4 | Self::ToHexInt8 => "pg_catalog.to_hex",
282 Self::ToOctInt4 | Self::ToOctInt8 => "pg_catalog.to_oct",
283 Self::RandomInt4Range | Self::RandomInt8Range | Self::RandomNumericRange => {
284 "pg_catalog.random"
285 }
286 Self::RegexSubstring | Self::SimilarSubstring => "pg_catalog.substring",
287 Self::ArraySortJson => "pg_catalog.array_sort",
288 Self::Concat { .. } => "||",
289 Self::ArrayConcat => "pg_catalog.array_cat",
290 Self::ArrayAppend => "pg_catalog.array_append",
291 Self::ArrayPrepend => "pg_catalog.array_prepend",
292 Self::JsonPath {
293 as_text: false,
294 jsonb: false,
295 } => "pg_catalog.json_extract_path",
296 Self::JsonPath {
297 as_text: true,
298 jsonb: false,
299 } => "pg_catalog.json_extract_path_text",
300 Self::JsonPath {
301 as_text: false,
302 jsonb: true,
303 } => "pg_catalog.jsonb_extract_path",
304 Self::JsonPath {
305 as_text: true,
306 jsonb: true,
307 } => "pg_catalog.jsonb_extract_path_text",
308 Self::JsonExtract { as_text: false, .. } => "JSON extraction operator",
309 Self::JsonExtract { as_text: true, .. } => "JSON text extraction operator",
310 Self::Range { operation, .. } => operation.label(),
311 Self::Enum { operation, .. } => operation.label(),
312 }
313 }
314
315 #[must_use]
316 pub const fn is_call_argument_marker(self) -> bool {
317 matches!(self, Self::NamedArgument | Self::VariadicArgument)
318 }
319
320 #[must_use]
322 pub const fn json_extraction_symbol(self) -> Option<&'static str> {
323 match self {
324 Self::JsonExtract {
325 as_text: false,
326 path: false,
327 } => Some("->"),
328 Self::JsonExtract {
329 as_text: true,
330 path: false,
331 } => Some("->>"),
332 Self::JsonExtract {
333 as_text: false,
334 path: true,
335 } => Some("#>"),
336 Self::JsonExtract {
337 as_text: true,
338 path: true,
339 } => Some("#>>"),
340 _ => None,
341 }
342 }
343
344 #[doc(hidden)]
346 #[must_use]
347 pub fn from_legacy_serialized_name(name: &str) -> Option<Self> {
348 let fixed = match name {
349 "merge_action" => Self::MergeAction,
350 "__named_arg" => Self::NamedArgument,
351 "__variadic_arg" => Self::VariadicArgument,
352 "__array_subscripts" => Self::ArraySubscripts,
353 "__array_slices" => Self::ArraySlices,
354 "__subscript" => Self::Subscript,
355 "__slice" => Self::Slice,
356 "__any_op" => Self::AnyOperator,
357 "__all_op" => Self::AllOperator,
358 "__is_distinct" => Self::IsDistinct,
359 "__between_symmetric" => Self::BetweenSymmetric,
360 "__to_bin_int4" => Self::ToBinInt4,
361 "__to_bin_int8" => Self::ToBinInt8,
362 "__to_hex_int4" => Self::ToHexInt4,
363 "__to_hex_int8" => Self::ToHexInt8,
364 "__to_oct_int4" => Self::ToOctInt4,
365 "__to_oct_int8" => Self::ToOctInt8,
366 "__random_int4_range" => Self::RandomInt4Range,
367 "__random_int8_range" => Self::RandomInt8Range,
368 "__random_numeric_range" => Self::RandomNumericRange,
369 "__array_sort_json" => Self::ArraySortJson,
370 _ => return Self::legacy_range_dispatch(name),
371 };
372 Some(fixed)
373 }
374
375 fn legacy_range_dispatch(name: &str) -> Option<Self> {
376 let encoded = name.strip_prefix("__range_")?;
377 let subtypes = [
378 RangeSubtype::Integer,
379 RangeSubtype::BigInteger,
380 RangeSubtype::Numeric,
381 RangeSubtype::Date,
382 RangeSubtype::Timestamp,
383 RangeSubtype::TimestampTz,
384 ];
385 for subtype in subtypes {
386 for (type_name, multirange) in [
387 (subtype.multirange_name(), true),
388 (subtype.range_name(), false),
389 ] {
390 let Some(operation) = encoded.strip_suffix(type_name) else {
391 continue;
392 };
393 let operation = match operation.trim_end_matches('_') {
394 "lower" => RangeFunctionOperation::Lower,
395 "upper" => RangeFunctionOperation::Upper,
396 "isempty" => RangeFunctionOperation::IsEmpty,
397 "lower_inc" => RangeFunctionOperation::LowerInclusive,
398 "upper_inc" => RangeFunctionOperation::UpperInclusive,
399 "lower_inf" => RangeFunctionOperation::LowerInfinite,
400 "upper_inf" => RangeFunctionOperation::UpperInfinite,
401 "merge" => RangeFunctionOperation::Merge,
402 "multirange" => RangeFunctionOperation::Multirange,
403 "overlap" => RangeFunctionOperation::Overlap,
404 "contains" => RangeFunctionOperation::Contains,
405 "contained_by" => RangeFunctionOperation::ContainedBy,
406 "adjacent" => RangeFunctionOperation::Adjacent,
407 _ => continue,
408 };
409 return Some(Self::Range {
410 operation,
411 subtype,
412 multirange,
413 });
414 }
415 }
416 None
417 }
418}
419
420#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
422pub enum NumericOperator {
423 Modulo,
424 Power,
425 Plus,
426 SquareRoot,
427 CubeRoot,
428 Absolute,
429}
430
431impl NumericOperator {
432 #[must_use]
433 pub const fn symbol(self) -> &'static str {
434 match self {
435 Self::Modulo => "%",
436 Self::Power => "^",
437 Self::Plus => "+",
438 Self::SquareRoot => "|/",
439 Self::CubeRoot => "||/",
440 Self::Absolute => "@",
441 }
442 }
443
444 #[must_use]
445 pub const fn arity(self) -> usize {
446 match self {
447 Self::Modulo | Self::Power => 2,
448 Self::Plus | Self::SquareRoot | Self::CubeRoot | Self::Absolute => 1,
449 }
450 }
451}
452
453impl RangeFunctionOperation {
454 #[must_use]
455 pub const fn label(self) -> &'static str {
456 match self {
457 Self::Lower => "pg_catalog.lower",
458 Self::Upper => "pg_catalog.upper",
459 Self::IsEmpty => "pg_catalog.isempty",
460 Self::LowerInclusive => "pg_catalog.lower_inc",
461 Self::UpperInclusive => "pg_catalog.upper_inc",
462 Self::LowerInfinite => "pg_catalog.lower_inf",
463 Self::UpperInfinite => "pg_catalog.upper_inf",
464 Self::Merge => "pg_catalog.range_merge",
465 Self::Multirange => "pg_catalog.multirange",
466 Self::Overlap => "range overlap operator",
467 Self::Contains => "range contains operator",
468 Self::ContainedBy => "range contained-by operator",
469 Self::ContainsElement => "range contains element operator",
470 Self::ElementContainedBy => "element contained-by range operator",
471 Self::Adjacent => "range adjacent operator",
472 }
473 }
474}
475
476#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
478pub struct RoutineInvocationBinding {
479 pub argument_positions: Vec<usize>,
481 pub argument_targets: Vec<String>,
483 #[serde(default, skip_serializing_if = "Vec::is_empty")]
485 pub argument_sources: Vec<Option<String>>,
486 pub parameter_types: Vec<String>,
488 pub return_type: Option<String>,
490 pub variadic_mode: RoutineVariadicMode,
492}
493
494#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
496pub enum RoutineVariadicMode {
497 #[default]
499 None,
500 Expanded {
502 parameter_index: usize,
504 },
505 Explicit {
507 parameter_index: usize,
509 },
510}
511
512impl FunctionBinding {
513 #[doc(hidden)]
515 pub fn upgrade_legacy_array_slices(
516 binding: &mut Option<Self>,
517 arguments: usize,
518 is_bare_null: impl Fn(usize) -> bool,
519 ) -> bool {
520 let Some(binding) = binding
521 .as_mut()
522 .filter(|binding| binding.dispatch == Some(FunctionDispatch::ArraySlices))
523 else {
524 return false;
525 };
526 let Some(Ok(access)) = super::ArrayAccess::from_dispatch(
527 FunctionDispatch::ArraySlices,
528 arguments,
529 is_bare_null,
530 ) else {
531 return false;
532 };
533 binding.dispatch = Some(FunctionDispatch::ArraySlicesWithBounds(
534 access.slice_bounds().expect("slice bounds"),
535 ));
536 true
537 }
538
539 #[must_use]
541 pub fn polymorphic_builtin_syntax(name: &str) -> Self {
542 assert!(Self::is_polymorphic_builtin_syntax_name(name));
543 Self {
544 object_id: None,
545 name: name.into(),
546 argument_types: Vec::new(),
547 builtin: true,
548 dispatch: None,
549 invocation: None,
550 composite_field: None,
551 resolution_error: None,
552 input_collation: None,
553 }
554 }
555
556 #[must_use]
558 pub fn dispatched(dispatch: FunctionDispatch) -> Self {
559 Self::dispatched_with_control(
560 dispatch,
561 &uqa_core::memory::ProductionControl::uncontrolled(),
562 )
563 .expect("ordinary dispatch constructor cannot be cancelled or limited")
564 .into_uncontrolled()
565 .expect("ordinary dispatch owner")
566 }
567
568 pub fn dispatched_with_control(
569 dispatch: FunctionDispatch,
570 control: &uqa_core::memory::ProductionControl<'_>,
571 ) -> Result<uqa_core::memory::Produced<Self>, uqa_core::ValueRetentionError> {
572 let (name, memory) = control.copy_text(dispatch.label())?.into_parts();
573 control.finish(
574 Self {
575 object_id: None,
576 name,
577 argument_types: Vec::new(),
578 builtin: true,
579 dispatch: Some(dispatch),
580 invocation: None,
581 composite_field: None,
582 resolution_error: None,
583 input_collation: None,
584 },
585 memory,
586 )
587 }
588
589 #[must_use]
591 pub fn undefined_function(name: impl Into<String>, signature: impl Into<String>) -> Self {
592 Self {
593 object_id: None,
594 name: name.into(),
595 argument_types: Vec::new(),
596 builtin: false,
597 dispatch: None,
598 invocation: None,
599 composite_field: None,
600 resolution_error: Some(Box::new(FunctionResolutionError::UndefinedFunction {
601 signature: signature.into(),
602 })),
603 input_collation: None,
604 }
605 }
606
607 #[doc(hidden)]
609 pub fn upgrade_legacy_serialized_dispatch(
610 display_name: &mut String,
611 binding: &mut Option<Self>,
612 ) -> bool {
613 if binding
614 .as_ref()
615 .is_some_and(|binding| binding.dispatch.is_some() || !binding.builtin)
616 {
617 return false;
618 }
619 let Some(dispatch) = FunctionDispatch::from_legacy_serialized_name(display_name) else {
620 return false;
621 };
622 if let Some(binding) = binding {
623 binding.dispatch = Some(dispatch);
624 display_name.clone_from(&binding.name);
625 } else {
626 let upgraded = Self::dispatched(dispatch);
627 display_name.clone_from(&upgraded.name);
628 *binding = Some(upgraded);
629 }
630 true
631 }
632
633 #[must_use]
635 pub fn selected_input_collation(binding: Option<&Self>) -> u32 {
636 binding.and_then(|binding| binding.input_collation).map_or(
637 crate::catalog::collations::DEFAULT_COLLATION_OID as u32,
638 |selected| selected.oid(),
639 )
640 }
641
642 pub fn rebind(binding: &mut Option<Self>, mut selected: Self) {
644 if selected.input_collation.is_none() {
645 selected.input_collation = binding.as_ref().and_then(|binding| binding.input_collation);
646 }
647 *binding = Some(selected);
648 }
649
650 #[must_use]
652 pub fn builtin_by_name(
653 name: &str,
654 input_collation: Option<crate::catalog::collations::CollationSelection>,
655 ) -> Self {
656 Self {
657 object_id: None,
658 name: name.into(),
659 argument_types: Vec::new(),
660 builtin: true,
661 dispatch: None,
662 invocation: None,
663 composite_field: None,
664 resolution_error: None,
665 input_collation,
666 }
667 }
668
669 #[must_use]
671 pub fn is_polymorphic_builtin_syntax(&self) -> bool {
672 self.builtin
673 && self.argument_types.is_empty()
674 && Self::is_polymorphic_builtin_syntax_name(&self.name)
675 }
676
677 #[must_use]
679 pub fn is_polymorphic_builtin_syntax_name(name: &str) -> bool {
680 matches!(name, "coalesce" | "greatest" | "least" | "nullif")
681 }
682}
683
684pub type GeneratedFunctionDependency = FunctionBinding;