1use std::fmt::Display;
8use std::hash::Hash;
9use std::sync::Arc;
10
11use arrow::datatypes::{
12 DECIMAL32_MAX_PRECISION, DECIMAL64_MAX_PRECISION, DECIMAL128_MAX_PRECISION, DataType,
13 Decimal128Type, DecimalType, Field, IntervalUnit, TimeUnit,
14};
15use datafusion_common::types::{LogicalType, LogicalTypeRef, NativeType};
16use datafusion_common::utils::ListCoercion;
17use datafusion_common::{Result, internal_err, plan_err};
18use indexmap::IndexSet;
19use itertools::Itertools;
20
21pub const TIMEZONE_WILDCARD: &str = "+TZ";
30
31pub const FIXED_SIZE_LIST_WILDCARD: i32 = i32::MIN;
35
36#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Hash)]
43pub enum Volatility {
44 Immutable,
52 Stable,
64 Volatile,
75}
76
77#[derive(Debug, Clone, Copy, PartialEq, Eq)]
79pub enum Arity {
80 Fixed(usize),
82 Variable,
84}
85
86#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Hash)]
144pub enum TypeSignature {
145 Variadic(Vec<DataType>),
154 UserDefined,
162 VariadicAny,
164 Uniform(usize, Vec<DataType>),
171 Exact(Vec<DataType>),
175 Coercible(Vec<Coercion>),
183 Comparable(usize),
203 Any(usize),
207 OneOf(Vec<TypeSignature>),
217 ArraySignature(ArrayFunctionSignature),
219 Numeric(usize),
227 String(usize),
238 Nullary,
240}
241
242impl TypeSignature {
243 #[inline]
244 pub fn is_one_of(&self) -> bool {
245 matches!(self, TypeSignature::OneOf(_))
246 }
247
248 pub fn arity(&self) -> Arity {
267 match self {
268 TypeSignature::Exact(types) => Arity::Fixed(types.len()),
269 TypeSignature::Uniform(count, _) => Arity::Fixed(*count),
270 TypeSignature::Numeric(count) => Arity::Fixed(*count),
271 TypeSignature::String(count) => Arity::Fixed(*count),
272 TypeSignature::Comparable(count) => Arity::Fixed(*count),
273 TypeSignature::Any(count) => Arity::Fixed(*count),
274 TypeSignature::Coercible(types) => Arity::Fixed(types.len()),
275 TypeSignature::Nullary => Arity::Fixed(0),
276 TypeSignature::ArraySignature(ArrayFunctionSignature::Array {
277 arguments,
278 ..
279 }) => Arity::Fixed(arguments.len()),
280 TypeSignature::ArraySignature(ArrayFunctionSignature::RecursiveArray) => {
281 Arity::Fixed(1)
282 }
283 TypeSignature::ArraySignature(ArrayFunctionSignature::MapArray) => {
284 Arity::Fixed(1)
285 }
286 TypeSignature::OneOf(variants) => {
287 let has_variable = variants.iter().any(|v| v.arity() == Arity::Variable);
289 if has_variable {
290 return Arity::Variable;
291 }
292 let max_arity = variants
294 .iter()
295 .filter_map(|v| match v.arity() {
296 Arity::Fixed(n) => Some(n),
297 Arity::Variable => None,
298 })
299 .max();
300 match max_arity {
301 Some(n) => Arity::Fixed(n),
302 None => Arity::Variable,
303 }
304 }
305 TypeSignature::Variadic(_)
306 | TypeSignature::VariadicAny
307 | TypeSignature::UserDefined => Arity::Variable,
308 }
309 }
310}
311
312impl Display for TypeSignature {
313 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
314 match self {
315 TypeSignature::Variadic(types) => {
316 write!(f, "Variadic({})", types.iter().join(", "))
317 }
318 TypeSignature::UserDefined => write!(f, "UserDefined"),
319 TypeSignature::VariadicAny => write!(f, "VariadicAny"),
320 TypeSignature::Uniform(count, types) => {
321 write!(f, "Uniform({count}, [{}])", types.iter().join(", "))
322 }
323 TypeSignature::Exact(types) => {
324 write!(f, "Exact({})", types.iter().join(", "))
325 }
326 TypeSignature::Coercible(coercions) => {
327 write!(f, "Coercible({})", coercions.iter().join(", "))
328 }
329 TypeSignature::Comparable(count) => write!(f, "Comparable({count})"),
330 TypeSignature::Any(count) => write!(f, "Any({count})"),
331 TypeSignature::OneOf(sigs) => {
332 write!(f, "OneOf(")?;
333 for (i, sig) in sigs.iter().enumerate() {
334 if i > 0 {
335 write!(f, ", ")?;
336 }
337 write!(f, "{sig}")?;
338 }
339 write!(f, ")")
340 }
341 TypeSignature::ArraySignature(sig) => write!(f, "ArraySignature({sig})"),
342 TypeSignature::Numeric(count) => write!(f, "Numeric({count})"),
343 TypeSignature::String(count) => write!(f, "String({count})"),
344 TypeSignature::Nullary => write!(f, "Nullary"),
345 }
346 }
347}
348
349#[derive(Debug, Clone, Eq, PartialEq, PartialOrd, Hash)]
358pub enum TypeSignatureClass {
359 Any,
361 Timestamp,
363 Time,
365 Interval,
367 Duration,
369 Native(LogicalTypeRef),
371 Integer,
373 Float,
375 Decimal,
377 Numeric,
379 Binary,
381}
382
383impl Display for TypeSignatureClass {
384 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
385 match self {
386 Self::Any => write!(f, "Any"),
387 Self::Timestamp => write!(f, "Timestamp"),
388 Self::Time => write!(f, "Time"),
389 Self::Interval => write!(f, "Interval"),
390 Self::Duration => write!(f, "Duration"),
391 Self::Native(logical_type) => write!(f, "{logical_type}"),
392 Self::Integer => write!(f, "Integer"),
393 Self::Float => write!(f, "Float"),
394 Self::Decimal => write!(f, "Decimal"),
395 Self::Numeric => write!(f, "Numeric"),
396 Self::Binary => write!(f, "Binary"),
397 }
398 }
399}
400
401impl TypeSignatureClass {
402 fn get_example_types(&self) -> Vec<DataType> {
408 match self {
409 TypeSignatureClass::Any => vec![],
410 TypeSignatureClass::Native(l) => get_data_types(l.native()),
411 TypeSignatureClass::Timestamp => {
412 vec![
413 DataType::Timestamp(TimeUnit::Nanosecond, None),
414 DataType::Timestamp(
415 TimeUnit::Nanosecond,
416 Some(TIMEZONE_WILDCARD.into()),
417 ),
418 ]
419 }
420 TypeSignatureClass::Time => {
421 vec![DataType::Time64(TimeUnit::Nanosecond)]
422 }
423 TypeSignatureClass::Interval => {
424 vec![DataType::Interval(IntervalUnit::DayTime)]
425 }
426 TypeSignatureClass::Duration => {
427 vec![DataType::Duration(TimeUnit::Nanosecond)]
428 }
429 TypeSignatureClass::Integer => {
430 vec![DataType::Int64]
431 }
432 TypeSignatureClass::Binary => {
433 vec![DataType::Binary]
434 }
435 TypeSignatureClass::Decimal => vec![Decimal128Type::DEFAULT_TYPE],
436 TypeSignatureClass::Float => vec![DataType::Float64],
437 TypeSignatureClass::Numeric => vec![
438 DataType::Float64,
439 DataType::Int64,
440 Decimal128Type::DEFAULT_TYPE,
441 ],
442 }
443 }
444
445 fn get_representative_types(&self) -> Vec<NativeType> {
450 match self {
451 TypeSignatureClass::Any => vec![],
452 TypeSignatureClass::Native(l) => vec![l.native().clone()],
453 TypeSignatureClass::Timestamp => {
454 vec![
455 NativeType::Timestamp(TimeUnit::Nanosecond, None),
456 NativeType::Timestamp(
457 TimeUnit::Nanosecond,
458 Some(TIMEZONE_WILDCARD.into()),
459 ),
460 ]
461 }
462 TypeSignatureClass::Time => {
463 vec![NativeType::Time(TimeUnit::Nanosecond)]
464 }
465 TypeSignatureClass::Interval => {
466 vec![NativeType::Interval(IntervalUnit::DayTime)]
467 }
468 TypeSignatureClass::Duration => {
469 vec![NativeType::Duration(TimeUnit::Nanosecond)]
470 }
471 TypeSignatureClass::Integer => {
472 vec![NativeType::Int64]
473 }
474 TypeSignatureClass::Binary => {
475 vec![NativeType::Binary]
476 }
477 TypeSignatureClass::Decimal => vec![Decimal128Type::DEFAULT_TYPE.into()],
478 TypeSignatureClass::Float => vec![NativeType::Float64],
479 TypeSignatureClass::Numeric => {
480 vec![
481 NativeType::Float64,
482 NativeType::Int64,
483 Decimal128Type::DEFAULT_TYPE.into(),
484 ]
485 }
486 }
487 }
488
489 pub fn matches_native_type(&self, logical_type: &NativeType) -> bool {
491 if logical_type == &NativeType::Null {
492 return true;
493 }
494
495 match self {
496 TypeSignatureClass::Any => true,
497 TypeSignatureClass::Native(t) if t.native() == logical_type => true,
498 TypeSignatureClass::Timestamp if logical_type.is_timestamp() => true,
499 TypeSignatureClass::Time if logical_type.is_time() => true,
500 TypeSignatureClass::Interval if logical_type.is_interval() => true,
501 TypeSignatureClass::Duration if logical_type.is_duration() => true,
502 TypeSignatureClass::Integer if logical_type.is_integer() => true,
503 TypeSignatureClass::Binary if logical_type.is_binary() => true,
504 TypeSignatureClass::Decimal if logical_type.is_decimal() => true,
505 TypeSignatureClass::Float if logical_type.is_float() => true,
506 TypeSignatureClass::Numeric if logical_type.is_numeric() => true,
507 _ => false,
508 }
509 }
510
511 pub fn default_casted_type(
513 &self,
514 native_type: &NativeType,
515 origin_type: &DataType,
516 ) -> Result<DataType> {
517 match self {
518 TypeSignatureClass::Any => Ok(origin_type.to_owned()),
519 TypeSignatureClass::Native(logical_type) => {
520 logical_type.native().default_cast_for(origin_type)
521 }
522 TypeSignatureClass::Timestamp if native_type.is_timestamp() => {
524 Ok(origin_type.to_owned())
525 }
526 TypeSignatureClass::Time if native_type.is_time() => {
527 Ok(origin_type.to_owned())
528 }
529 TypeSignatureClass::Interval if native_type.is_interval() => {
530 Ok(origin_type.to_owned())
531 }
532 TypeSignatureClass::Duration if native_type.is_duration() => {
533 Ok(origin_type.to_owned())
534 }
535 TypeSignatureClass::Integer if native_type.is_integer() => {
536 Ok(origin_type.to_owned())
537 }
538 TypeSignatureClass::Binary if native_type.is_binary() => {
539 Ok(origin_type.to_owned())
540 }
541 TypeSignatureClass::Binary if native_type.is_null() => Ok(DataType::Binary),
544 TypeSignatureClass::Decimal if native_type.is_decimal() => {
545 Ok(origin_type.to_owned())
546 }
547 TypeSignatureClass::Float if native_type.is_float() => {
548 Ok(origin_type.to_owned())
549 }
550 TypeSignatureClass::Numeric if native_type.is_numeric() => {
551 Ok(origin_type.to_owned())
552 }
553 _ if native_type.is_null() => Ok(origin_type.to_owned()),
554 _ => internal_err!("May miss the matching logic in `matches_native_type`"),
555 }
556 }
557}
558
559#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Hash)]
560pub enum ArrayFunctionSignature {
561 Array {
563 arguments: Vec<ArrayFunctionArgument>,
565 array_coercion: Option<ListCoercion>,
567 },
568 RecursiveArray,
571 MapArray,
574}
575
576impl Display for ArrayFunctionSignature {
577 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
578 match self {
579 ArrayFunctionSignature::Array { arguments, .. } => {
580 for (idx, argument) in arguments.iter().enumerate() {
581 write!(f, "{argument}")?;
582 if idx != arguments.len() - 1 {
583 write!(f, ", ")?;
584 }
585 }
586 Ok(())
587 }
588 ArrayFunctionSignature::RecursiveArray => {
589 write!(f, "recursive_array")
590 }
591 ArrayFunctionSignature::MapArray => {
592 write!(f, "map_array")
593 }
594 }
595 }
596}
597
598#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Hash)]
599pub enum ArrayFunctionArgument {
600 Element,
603 Index,
605 Array,
608 String,
610}
611
612impl Display for ArrayFunctionArgument {
613 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
614 match self {
615 ArrayFunctionArgument::Element => {
616 write!(f, "element")
617 }
618 ArrayFunctionArgument::Index => {
619 write!(f, "index")
620 }
621 ArrayFunctionArgument::Array => {
622 write!(f, "array")
623 }
624 ArrayFunctionArgument::String => {
625 write!(f, "string")
626 }
627 }
628 }
629}
630
631static NUMERICS: &[DataType] = &[
633 DataType::Int8,
634 DataType::Int16,
635 DataType::Int32,
636 DataType::Int64,
637 DataType::UInt8,
638 DataType::UInt16,
639 DataType::UInt32,
640 DataType::UInt64,
641 DataType::Float16,
642 DataType::Float32,
643 DataType::Float64,
644];
645
646impl TypeSignature {
647 pub fn to_string_repr(&self) -> Vec<String> {
648 match self {
649 TypeSignature::Nullary => {
650 vec!["NullAry()".to_string()]
651 }
652 TypeSignature::Variadic(types) => {
653 vec![format!("{}, ..", Self::join_types(types, "/"))]
654 }
655 TypeSignature::Uniform(arg_count, valid_types) => {
656 vec![
657 std::iter::repeat_n(Self::join_types(valid_types, "/"), *arg_count)
658 .collect::<Vec<String>>()
659 .join(", "),
660 ]
661 }
662 TypeSignature::String(num) => {
663 vec![format!("String({num})")]
664 }
665 TypeSignature::Numeric(num) => {
666 vec![format!("Numeric({num})")]
667 }
668 TypeSignature::Comparable(num) => {
669 vec![format!("Comparable({num})")]
670 }
671 TypeSignature::Coercible(coercions) => {
672 vec![Self::join_types(coercions, ", ")]
673 }
674 TypeSignature::Exact(types) => {
675 vec![Self::join_types(types, ", ")]
676 }
677 TypeSignature::Any(arg_count) => {
678 vec![
679 std::iter::repeat_n("Any", *arg_count)
680 .collect::<Vec<&str>>()
681 .join(", "),
682 ]
683 }
684 TypeSignature::UserDefined => {
685 vec!["UserDefined".to_string()]
686 }
687 TypeSignature::VariadicAny => vec!["Any, .., Any".to_string()],
688 TypeSignature::OneOf(sigs) => {
689 sigs.iter().flat_map(|s| s.to_string_repr()).collect()
690 }
691 TypeSignature::ArraySignature(array_signature) => {
692 vec![array_signature.to_string()]
693 }
694 }
695 }
696
697 pub fn to_string_repr_with_names(
723 &self,
724 parameter_names: Option<&[String]>,
725 ) -> Vec<String> {
726 match self {
727 TypeSignature::Exact(types) => {
728 if let Some(names) = parameter_names {
729 vec![
730 names
731 .iter()
732 .zip(types.iter())
733 .map(|(name, typ)| format!("{name}: {typ}"))
734 .collect::<Vec<_>>()
735 .join(", "),
736 ]
737 } else {
738 vec![Self::join_types(types, ", ")]
739 }
740 }
741 TypeSignature::Any(count) => {
742 if let Some(names) = parameter_names {
743 vec![
744 names
745 .iter()
746 .take(*count)
747 .map(|name| format!("{name}: Any"))
748 .collect::<Vec<_>>()
749 .join(", "),
750 ]
751 } else {
752 vec![
753 std::iter::repeat_n("Any", *count)
754 .collect::<Vec<&str>>()
755 .join(", "),
756 ]
757 }
758 }
759 TypeSignature::Uniform(count, types) => {
760 if let Some(names) = parameter_names {
761 let type_str = Self::join_types(types, "/");
762 vec![
763 names
764 .iter()
765 .take(*count)
766 .map(|name| format!("{name}: {type_str}"))
767 .collect::<Vec<_>>()
768 .join(", "),
769 ]
770 } else {
771 self.to_string_repr()
772 }
773 }
774 TypeSignature::Coercible(coercions) => {
775 if let Some(names) = parameter_names {
776 vec![
777 names
778 .iter()
779 .zip(coercions.iter())
780 .map(|(name, coercion)| format!("{name}: {coercion}"))
781 .collect::<Vec<_>>()
782 .join(", "),
783 ]
784 } else {
785 vec![Self::join_types(coercions, ", ")]
786 }
787 }
788 TypeSignature::Comparable(count) => {
789 if let Some(names) = parameter_names {
790 vec![
791 names
792 .iter()
793 .take(*count)
794 .map(|name| format!("{name}: Comparable"))
795 .collect::<Vec<_>>()
796 .join(", "),
797 ]
798 } else {
799 self.to_string_repr()
800 }
801 }
802 TypeSignature::Numeric(count) => {
803 if let Some(names) = parameter_names {
804 vec![
805 names
806 .iter()
807 .take(*count)
808 .map(|name| format!("{name}: Numeric"))
809 .collect::<Vec<_>>()
810 .join(", "),
811 ]
812 } else {
813 self.to_string_repr()
814 }
815 }
816 TypeSignature::String(count) => {
817 if let Some(names) = parameter_names {
818 vec![
819 names
820 .iter()
821 .take(*count)
822 .map(|name| format!("{name}: String"))
823 .collect::<Vec<_>>()
824 .join(", "),
825 ]
826 } else {
827 self.to_string_repr()
828 }
829 }
830 TypeSignature::Nullary => self.to_string_repr(),
831 TypeSignature::ArraySignature(array_sig) => {
832 if let Some(names) = parameter_names {
833 match array_sig {
834 ArrayFunctionSignature::Array { arguments, .. } => {
835 vec![
836 names
837 .iter()
838 .zip(arguments.iter())
839 .map(|(name, arg_type)| format!("{name}: {arg_type}"))
840 .collect::<Vec<_>>()
841 .join(", "),
842 ]
843 }
844 ArrayFunctionSignature::RecursiveArray => {
845 vec![
846 names
847 .iter()
848 .take(1)
849 .map(|name| format!("{name}: recursive_array"))
850 .collect::<Vec<_>>()
851 .join(", "),
852 ]
853 }
854 ArrayFunctionSignature::MapArray => {
855 vec![
856 names
857 .iter()
858 .take(1)
859 .map(|name| format!("{name}: map_array"))
860 .collect::<Vec<_>>()
861 .join(", "),
862 ]
863 }
864 }
865 } else {
866 self.to_string_repr()
867 }
868 }
869 TypeSignature::OneOf(sigs) => sigs
870 .iter()
871 .flat_map(|s| s.to_string_repr_with_names(parameter_names))
872 .collect(),
873 TypeSignature::UserDefined => {
874 if let Some(names) = parameter_names {
875 vec![names.join(", ")]
876 } else {
877 self.to_string_repr()
878 }
879 }
880 TypeSignature::Variadic(_) | TypeSignature::VariadicAny => {
882 self.to_string_repr()
883 }
884 }
885 }
886
887 pub fn join_types<T: Display>(types: &[T], delimiter: &str) -> String {
889 types
890 .iter()
891 .map(|t| t.to_string())
892 .collect::<Vec<String>>()
893 .join(delimiter)
894 }
895
896 pub fn supports_zero_argument(&self) -> bool {
898 match &self {
899 TypeSignature::Exact(vec) => vec.is_empty(),
900 TypeSignature::Nullary => true,
901 TypeSignature::OneOf(types) => types
902 .iter()
903 .any(|type_sig| type_sig.supports_zero_argument()),
904 _ => false,
905 }
906 }
907
908 pub fn used_to_support_zero_arguments(&self) -> bool {
911 match &self {
912 TypeSignature::Any(num) => *num == 0,
913 _ => self.supports_zero_argument(),
914 }
915 }
916
917 #[deprecated(since = "55.0.0", note = "See get_representative_types instead")]
924 pub fn get_example_types(&self) -> Vec<Vec<DataType>> {
925 match self {
926 TypeSignature::Exact(types) => vec![types.clone()],
927 TypeSignature::OneOf(types) => types
928 .iter()
929 .flat_map(|type_sig| type_sig.get_example_types())
930 .collect(),
931 TypeSignature::Uniform(arg_count, types) => types
932 .iter()
933 .cloned()
934 .map(|data_type| vec![data_type; *arg_count])
935 .collect(),
936 TypeSignature::Coercible(coercions) => coercions
937 .iter()
938 .map(|c| {
939 let mut all_types: IndexSet<DataType> =
940 c.desired_type().get_example_types().into_iter().collect();
941
942 if let Some(implicit_coercion) = c.implicit_coercion() {
943 let allowed_casts: Vec<DataType> = implicit_coercion
944 .allowed_source_types
945 .iter()
946 .flat_map(|t| t.get_example_types())
947 .collect();
948 all_types.extend(allowed_casts);
949 }
950
951 all_types.into_iter().collect::<Vec<_>>()
952 })
953 .multi_cartesian_product()
954 .collect(),
955 TypeSignature::Variadic(types) => types
956 .iter()
957 .cloned()
958 .map(|data_type| vec![data_type])
959 .collect(),
960 TypeSignature::Numeric(arg_count) => NUMERICS
961 .iter()
962 .cloned()
963 .map(|numeric_type| vec![numeric_type; *arg_count])
964 .collect(),
965 TypeSignature::String(arg_count) => get_data_types(&NativeType::String)
966 .into_iter()
967 .map(|dt| vec![dt; *arg_count])
968 .collect::<Vec<_>>(),
969 TypeSignature::Any(_)
971 | TypeSignature::Comparable(_)
972 | TypeSignature::Nullary
973 | TypeSignature::VariadicAny
974 | TypeSignature::ArraySignature(_)
975 | TypeSignature::UserDefined => vec![],
976 }
977 }
978
979 pub fn get_representative_types(&self) -> Vec<Vec<NativeType>> {
987 match self {
988 TypeSignature::Exact(types) => vec![
989 types
990 .iter()
991 .map(|data_type| NativeType::from(data_type.clone()))
992 .collect(),
993 ],
994 TypeSignature::OneOf(types) => types
995 .iter()
996 .flat_map(|type_sig| type_sig.get_representative_types())
997 .collect(),
998 TypeSignature::Uniform(arg_count, types) => types
999 .iter()
1000 .cloned()
1001 .map(|data_type| vec![data_type.into(); *arg_count])
1002 .collect(),
1003 TypeSignature::Coercible(coercions) => coercions
1004 .iter()
1005 .map(|c| {
1006 let mut all_types: IndexSet<NativeType> = c
1007 .desired_type()
1008 .get_representative_types()
1009 .into_iter()
1010 .collect();
1011
1012 if let Some(implicit_coercion) = c.implicit_coercion() {
1013 let allowed_casts: Vec<NativeType> = implicit_coercion
1014 .allowed_source_types
1015 .iter()
1016 .flat_map(|t| t.get_representative_types())
1017 .collect();
1018 all_types.extend(allowed_casts);
1019 }
1020
1021 all_types.into_iter().collect::<Vec<_>>()
1022 })
1023 .multi_cartesian_product()
1024 .collect(),
1025 TypeSignature::Variadic(types) => types
1026 .iter()
1027 .cloned()
1028 .map(|data_type| vec![data_type.into()])
1029 .collect(),
1030 TypeSignature::Numeric(arg_count) => TypeSignatureClass::Numeric
1031 .get_representative_types()
1032 .into_iter()
1033 .map(|t| vec![t; *arg_count])
1034 .collect(),
1035 TypeSignature::String(arg_count) => {
1036 vec![vec![NativeType::String; *arg_count]]
1037 }
1038 TypeSignature::Any(_)
1040 | TypeSignature::Comparable(_)
1041 | TypeSignature::Nullary
1042 | TypeSignature::VariadicAny
1043 | TypeSignature::ArraySignature(_)
1044 | TypeSignature::UserDefined => vec![],
1045 }
1046 }
1047}
1048
1049fn get_data_types(native_type: &NativeType) -> Vec<DataType> {
1051 match native_type {
1052 NativeType::Null => vec![DataType::Null],
1053 NativeType::Boolean => vec![DataType::Boolean],
1054 NativeType::Int8 => vec![DataType::Int8],
1055 NativeType::Int16 => vec![DataType::Int16],
1056 NativeType::Int32 => vec![DataType::Int32],
1057 NativeType::Int64 => vec![DataType::Int64],
1058 NativeType::UInt8 => vec![DataType::UInt8],
1059 NativeType::UInt16 => vec![DataType::UInt16],
1060 NativeType::UInt32 => vec![DataType::UInt32],
1061 NativeType::UInt64 => vec![DataType::UInt64],
1062 NativeType::Float16 => vec![DataType::Float16],
1063 NativeType::Float32 => vec![DataType::Float32],
1064 NativeType::Float64 => vec![DataType::Float64],
1065 NativeType::Date => vec![DataType::Date32, DataType::Date64],
1066 NativeType::Binary => vec![
1067 DataType::Binary,
1068 DataType::LargeBinary,
1069 DataType::BinaryView,
1070 ],
1071 NativeType::String => {
1072 vec![DataType::Utf8, DataType::LargeUtf8, DataType::Utf8View]
1073 }
1074 NativeType::Decimal(precision, scale) => {
1075 let mut types = vec![DataType::Decimal256(*precision, *scale)];
1077 if *precision <= DECIMAL32_MAX_PRECISION {
1078 types.push(DataType::Decimal32(*precision, *scale));
1079 }
1080 if *precision <= DECIMAL64_MAX_PRECISION {
1081 types.push(DataType::Decimal64(*precision, *scale));
1082 }
1083 if *precision <= DECIMAL128_MAX_PRECISION {
1084 types.push(DataType::Decimal128(*precision, *scale));
1085 }
1086 types
1087 }
1088 NativeType::Timestamp(time_unit, timezone) => {
1089 vec![DataType::Timestamp(*time_unit, timezone.to_owned())]
1090 }
1091 NativeType::Time(TimeUnit::Second) => vec![DataType::Time32(TimeUnit::Second)],
1092 NativeType::Time(TimeUnit::Millisecond) => {
1093 vec![DataType::Time32(TimeUnit::Millisecond)]
1094 }
1095 NativeType::Time(TimeUnit::Microsecond) => {
1096 vec![DataType::Time64(TimeUnit::Microsecond)]
1097 }
1098 NativeType::Time(TimeUnit::Nanosecond) => {
1099 vec![DataType::Time64(TimeUnit::Nanosecond)]
1100 }
1101 NativeType::Duration(time_unit) => vec![DataType::Duration(*time_unit)],
1102 NativeType::Interval(interval_unit) => vec![DataType::Interval(*interval_unit)],
1103 NativeType::FixedSizeBinary(size) => vec![DataType::FixedSizeBinary(*size)],
1104 NativeType::FixedSizeList(logical_field, size) => {
1105 get_data_types(logical_field.logical_type.native())
1106 .iter()
1107 .map(|child_dt| {
1108 let field = Field::new(
1109 logical_field.name.clone(),
1110 child_dt.clone(),
1111 logical_field.nullable,
1112 );
1113 DataType::FixedSizeList(Arc::new(field), *size)
1114 })
1115 .collect()
1116 }
1117 NativeType::List(_)
1119 | NativeType::Struct(_)
1120 | NativeType::Union(_)
1121 | NativeType::Map(_) => {
1122 vec![]
1123 }
1124 }
1125}
1126
1127#[derive(Debug, Clone, Eq, PartialOrd)]
1151pub enum Coercion {
1152 Exact {
1154 desired_type: TypeSignatureClass,
1156 encoding_preservation: EncodingPreservation,
1158 },
1159
1160 Implicit {
1162 desired_type: TypeSignatureClass,
1164 implicit_coercion: ImplicitCoercion,
1166 encoding_preservation: EncodingPreservation,
1168 },
1169}
1170
1171#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Hash)]
1174pub struct EncodingPreservation {
1175 preserve_dictionary: bool,
1176}
1177
1178impl EncodingPreservation {
1179 pub const fn dictionary() -> Self {
1181 Self {
1182 preserve_dictionary: true,
1183 }
1184 }
1185
1186 pub const fn with_dictionary(mut self) -> Self {
1188 self.preserve_dictionary = true;
1189 self
1190 }
1191
1192 pub const fn preserve_dictionary(self) -> bool {
1194 self.preserve_dictionary
1195 }
1196}
1197
1198impl Coercion {
1199 pub fn new_exact(desired_type: TypeSignatureClass) -> Self {
1200 Self::Exact {
1201 desired_type,
1202 encoding_preservation: EncodingPreservation::default(),
1203 }
1204 }
1205
1206 pub fn new_implicit(
1211 desired_type: TypeSignatureClass,
1212 allowed_source_types: Vec<TypeSignatureClass>,
1213 default_casted_type: NativeType,
1214 ) -> Self {
1215 Self::Implicit {
1216 desired_type,
1217 implicit_coercion: ImplicitCoercion {
1218 allowed_source_types,
1219 default_casted_type,
1220 },
1221 encoding_preservation: EncodingPreservation::default(),
1222 }
1223 }
1224
1225 pub fn new_implicit_native(
1233 desired_type: LogicalTypeRef,
1234 allowed_source_types: Vec<TypeSignatureClass>,
1235 ) -> Self {
1236 let default_casted_type = desired_type.native().clone();
1237 Self::new_implicit(
1238 TypeSignatureClass::Native(desired_type),
1239 allowed_source_types,
1240 default_casted_type,
1241 )
1242 }
1243
1244 pub fn with_encoding_preservation(
1245 mut self,
1246 encoding_preservation: EncodingPreservation,
1247 ) -> Self {
1248 match &mut self {
1249 Coercion::Exact {
1250 encoding_preservation: current,
1251 ..
1252 }
1253 | Coercion::Implicit {
1254 encoding_preservation: current,
1255 ..
1256 } => *current = encoding_preservation,
1257 }
1258 self
1259 }
1260
1261 pub fn encoding_preservation(&self) -> EncodingPreservation {
1262 match self {
1263 Coercion::Exact {
1264 encoding_preservation,
1265 ..
1266 }
1267 | Coercion::Implicit {
1268 encoding_preservation,
1269 ..
1270 } => *encoding_preservation,
1271 }
1272 }
1273
1274 pub fn allowed_source_types(&self) -> &[TypeSignatureClass] {
1275 match self {
1276 Coercion::Exact { .. } => &[],
1277 Coercion::Implicit {
1278 implicit_coercion, ..
1279 } => implicit_coercion.allowed_source_types.as_slice(),
1280 }
1281 }
1282
1283 pub fn default_casted_type(&self) -> Option<&NativeType> {
1284 match self {
1285 Coercion::Exact { .. } => None,
1286 Coercion::Implicit {
1287 implicit_coercion, ..
1288 } => Some(&implicit_coercion.default_casted_type),
1289 }
1290 }
1291
1292 pub fn desired_type(&self) -> &TypeSignatureClass {
1293 match self {
1294 Coercion::Exact { desired_type, .. } => desired_type,
1295 Coercion::Implicit { desired_type, .. } => desired_type,
1296 }
1297 }
1298
1299 pub fn implicit_coercion(&self) -> Option<&ImplicitCoercion> {
1300 match self {
1301 Coercion::Exact { .. } => None,
1302 Coercion::Implicit {
1303 implicit_coercion, ..
1304 } => Some(implicit_coercion),
1305 }
1306 }
1307}
1308
1309impl Display for Coercion {
1310 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1311 write!(f, "{}", self.desired_type())
1312 }
1313}
1314
1315impl PartialEq for Coercion {
1316 fn eq(&self, other: &Self) -> bool {
1317 self.desired_type() == other.desired_type()
1318 && self.implicit_coercion() == other.implicit_coercion()
1319 && self.encoding_preservation() == other.encoding_preservation()
1320 }
1321}
1322
1323impl Hash for Coercion {
1324 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
1325 self.desired_type().hash(state);
1326 self.implicit_coercion().hash(state);
1327 self.encoding_preservation().hash(state);
1328 }
1329}
1330
1331#[derive(Debug, Clone, Eq, PartialOrd)]
1353pub struct ImplicitCoercion {
1354 allowed_source_types: Vec<TypeSignatureClass>,
1356
1357 default_casted_type: NativeType,
1361}
1362
1363impl Display for ImplicitCoercion {
1364 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1365 write!(f, "ImplicitCoercion(")?;
1366 for (i, source_type) in self.allowed_source_types.iter().enumerate() {
1367 if i > 0 {
1368 write!(f, ", ")?;
1369 }
1370 write!(f, "{source_type}")?;
1371 }
1372 write!(f, "; default={}", self.default_casted_type)
1373 }
1374}
1375
1376impl PartialEq for ImplicitCoercion {
1377 fn eq(&self, other: &Self) -> bool {
1378 self.allowed_source_types == other.allowed_source_types
1379 && self.default_casted_type == other.default_casted_type
1380 }
1381}
1382
1383impl Hash for ImplicitCoercion {
1384 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
1385 self.allowed_source_types.hash(state);
1386 self.default_casted_type.hash(state);
1387 }
1388}
1389
1390#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Hash)]
1397pub struct Signature {
1398 pub type_signature: TypeSignature,
1400 pub volatility: Volatility,
1402 pub parameter_names: Option<Vec<String>>,
1409}
1410
1411impl Signature {
1412 pub fn new(type_signature: TypeSignature, volatility: Volatility) -> Self {
1414 Signature {
1415 type_signature,
1416 volatility,
1417 parameter_names: None,
1418 }
1419 }
1420 pub fn variadic(common_types: Vec<DataType>, volatility: Volatility) -> Self {
1422 Self {
1423 type_signature: TypeSignature::Variadic(common_types),
1424 volatility,
1425 parameter_names: None,
1426 }
1427 }
1428 pub fn user_defined(volatility: Volatility) -> Self {
1430 Self {
1431 type_signature: TypeSignature::UserDefined,
1432 volatility,
1433 parameter_names: None,
1434 }
1435 }
1436
1437 pub fn numeric(arg_count: usize, volatility: Volatility) -> Self {
1439 Self {
1440 type_signature: TypeSignature::Numeric(arg_count),
1441 volatility,
1442 parameter_names: None,
1443 }
1444 }
1445
1446 pub fn string(arg_count: usize, volatility: Volatility) -> Self {
1448 Self {
1449 type_signature: TypeSignature::String(arg_count),
1450 volatility,
1451 parameter_names: None,
1452 }
1453 }
1454
1455 pub fn variadic_any(volatility: Volatility) -> Self {
1457 Self {
1458 type_signature: TypeSignature::VariadicAny,
1459 volatility,
1460 parameter_names: None,
1461 }
1462 }
1463 pub fn uniform(
1465 arg_count: usize,
1466 valid_types: Vec<DataType>,
1467 volatility: Volatility,
1468 ) -> Self {
1469 Self {
1470 type_signature: TypeSignature::Uniform(arg_count, valid_types),
1471 volatility,
1472 parameter_names: None,
1473 }
1474 }
1475 pub fn exact(exact_types: Vec<DataType>, volatility: Volatility) -> Self {
1477 Signature {
1478 type_signature: TypeSignature::Exact(exact_types),
1479 volatility,
1480 parameter_names: None,
1481 }
1482 }
1483
1484 pub fn coercible(target_types: Vec<Coercion>, volatility: Volatility) -> Self {
1486 Self {
1487 type_signature: TypeSignature::Coercible(target_types),
1488 volatility,
1489 parameter_names: None,
1490 }
1491 }
1492
1493 pub fn comparable(arg_count: usize, volatility: Volatility) -> Self {
1495 Self {
1496 type_signature: TypeSignature::Comparable(arg_count),
1497 volatility,
1498 parameter_names: None,
1499 }
1500 }
1501
1502 pub fn nullary(volatility: Volatility) -> Self {
1503 Signature {
1504 type_signature: TypeSignature::Nullary,
1505 volatility,
1506 parameter_names: None,
1507 }
1508 }
1509
1510 pub fn any(arg_count: usize, volatility: Volatility) -> Self {
1512 Signature {
1513 type_signature: TypeSignature::Any(arg_count),
1514 volatility,
1515 parameter_names: None,
1516 }
1517 }
1518
1519 pub fn one_of(type_signatures: Vec<TypeSignature>, volatility: Volatility) -> Self {
1521 Signature {
1522 type_signature: TypeSignature::OneOf(type_signatures),
1523 volatility,
1524 parameter_names: None,
1525 }
1526 }
1527
1528 pub fn array_and_element(volatility: Volatility) -> Self {
1530 Signature {
1531 type_signature: TypeSignature::ArraySignature(
1532 ArrayFunctionSignature::Array {
1533 arguments: vec![
1534 ArrayFunctionArgument::Array,
1535 ArrayFunctionArgument::Element,
1536 ],
1537 array_coercion: Some(ListCoercion::FixedSizedListToList),
1538 },
1539 ),
1540 volatility,
1541 parameter_names: None,
1542 }
1543 }
1544
1545 pub fn element_and_array(volatility: Volatility) -> Self {
1547 Signature {
1548 type_signature: TypeSignature::ArraySignature(
1549 ArrayFunctionSignature::Array {
1550 arguments: vec![
1551 ArrayFunctionArgument::Element,
1552 ArrayFunctionArgument::Array,
1553 ],
1554 array_coercion: Some(ListCoercion::FixedSizedListToList),
1555 },
1556 ),
1557 volatility,
1558 parameter_names: None,
1559 }
1560 }
1561
1562 pub fn arrays(
1564 n: usize,
1565 coercion: Option<ListCoercion>,
1566 volatility: Volatility,
1567 ) -> Self {
1568 Signature {
1569 type_signature: TypeSignature::ArraySignature(
1570 ArrayFunctionSignature::Array {
1571 arguments: vec![ArrayFunctionArgument::Array; n],
1572 array_coercion: coercion,
1573 },
1574 ),
1575 volatility,
1576 parameter_names: None,
1577 }
1578 }
1579
1580 pub fn array_and_element_and_optional_index(volatility: Volatility) -> Self {
1582 Signature {
1583 type_signature: TypeSignature::OneOf(vec![
1584 TypeSignature::ArraySignature(ArrayFunctionSignature::Array {
1585 arguments: vec![
1586 ArrayFunctionArgument::Array,
1587 ArrayFunctionArgument::Element,
1588 ],
1589 array_coercion: Some(ListCoercion::FixedSizedListToList),
1590 }),
1591 TypeSignature::ArraySignature(ArrayFunctionSignature::Array {
1592 arguments: vec![
1593 ArrayFunctionArgument::Array,
1594 ArrayFunctionArgument::Element,
1595 ArrayFunctionArgument::Index,
1596 ],
1597 array_coercion: Some(ListCoercion::FixedSizedListToList),
1598 }),
1599 ]),
1600 volatility,
1601 parameter_names: None,
1602 }
1603 }
1604
1605 pub fn array_and_index(volatility: Volatility) -> Self {
1607 Signature {
1608 type_signature: TypeSignature::ArraySignature(
1609 ArrayFunctionSignature::Array {
1610 arguments: vec![
1611 ArrayFunctionArgument::Array,
1612 ArrayFunctionArgument::Index,
1613 ],
1614 array_coercion: Some(ListCoercion::FixedSizedListToList),
1615 },
1616 ),
1617 volatility,
1618 parameter_names: None,
1619 }
1620 }
1621
1622 pub fn array(volatility: Volatility) -> Self {
1624 Signature::arrays(1, Some(ListCoercion::FixedSizedListToList), volatility)
1625 }
1626
1627 pub fn with_parameter_names(mut self, names: Vec<impl Into<String>>) -> Result<Self> {
1643 let names = names.into_iter().map(Into::into).collect::<Vec<String>>();
1644 self.validate_parameter_names(&names)?;
1646 self.parameter_names = Some(names);
1647 Ok(self)
1648 }
1649
1650 fn validate_parameter_names(&self, names: &[String]) -> Result<()> {
1652 match self.type_signature.arity() {
1653 Arity::Fixed(expected) => {
1654 if names.len() != expected {
1655 return plan_err!(
1656 "Parameter names count ({}) does not match signature arity ({})",
1657 names.len(),
1658 expected
1659 );
1660 }
1661 }
1662 Arity::Variable => {
1663 if self.type_signature != TypeSignature::UserDefined {
1666 return plan_err!(
1667 "Cannot specify parameter names for variable arity signature: {:?}",
1668 self.type_signature
1669 );
1670 }
1671 }
1672 }
1673
1674 let mut seen = std::collections::HashSet::with_capacity(names.len());
1675 for name in names {
1676 if !seen.insert(name) {
1677 return plan_err!("Duplicate parameter name: '{}'", name);
1678 }
1679 }
1680
1681 Ok(())
1682 }
1683}
1684
1685#[cfg(test)]
1686mod tests {
1687 use datafusion_common::types::{
1688 NativeType, logical_float64, logical_int32, logical_int64, logical_string,
1689 };
1690
1691 use super::*;
1692 use crate::signature::{
1693 ArrayFunctionArgument, ArrayFunctionSignature, Coercion, TypeSignatureClass,
1694 };
1695
1696 #[test]
1697 fn supports_zero_argument_tests() {
1698 let positive_cases = vec![
1700 TypeSignature::Exact(vec![]),
1701 TypeSignature::OneOf(vec![
1702 TypeSignature::Exact(vec![DataType::Int8]),
1703 TypeSignature::Nullary,
1704 TypeSignature::Uniform(1, vec![DataType::Int8]),
1705 ]),
1706 TypeSignature::Nullary,
1707 ];
1708
1709 for case in positive_cases {
1710 assert!(
1711 case.supports_zero_argument(),
1712 "Expected {case:?} to support zero arguments"
1713 );
1714 }
1715
1716 let negative_cases = vec![
1718 TypeSignature::Exact(vec![DataType::Utf8]),
1719 TypeSignature::Uniform(1, vec![DataType::Float64]),
1720 TypeSignature::Any(1),
1721 TypeSignature::VariadicAny,
1722 TypeSignature::OneOf(vec![
1723 TypeSignature::Exact(vec![DataType::Int8]),
1724 TypeSignature::Uniform(1, vec![DataType::Int8]),
1725 ]),
1726 ];
1727
1728 for case in negative_cases {
1729 assert!(
1730 !case.supports_zero_argument(),
1731 "Expected {case:?} not to support zero arguments"
1732 );
1733 }
1734 }
1735
1736 #[test]
1737 fn type_signature_partial_ord() {
1738 assert!(TypeSignature::UserDefined < TypeSignature::VariadicAny);
1740 assert!(TypeSignature::UserDefined < TypeSignature::Any(1));
1741
1742 assert!(
1743 TypeSignature::Uniform(1, vec![DataType::Null])
1744 < TypeSignature::Uniform(1, vec![DataType::Boolean])
1745 );
1746 assert!(
1747 TypeSignature::Uniform(1, vec![DataType::Null])
1748 < TypeSignature::Uniform(2, vec![DataType::Null])
1749 );
1750 assert!(
1751 TypeSignature::Uniform(usize::MAX, vec![DataType::Null])
1752 < TypeSignature::Exact(vec![DataType::Null])
1753 );
1754 }
1755
1756 #[test]
1758 #[expect(deprecated)]
1759 fn test_get_example_types() {
1760 let type_signature = TypeSignature::Exact(vec![DataType::Int32, DataType::Int64]);
1761 let possible_types = type_signature.get_example_types();
1762 assert_eq!(possible_types, vec![vec![DataType::Int32, DataType::Int64]]);
1763
1764 let type_signature = TypeSignature::OneOf(vec![
1765 TypeSignature::Exact(vec![DataType::Int32, DataType::Int64]),
1766 TypeSignature::Exact(vec![DataType::Float32, DataType::Float64]),
1767 ]);
1768 let possible_types = type_signature.get_example_types();
1769 assert_eq!(
1770 possible_types,
1771 vec![
1772 vec![DataType::Int32, DataType::Int64],
1773 vec![DataType::Float32, DataType::Float64]
1774 ]
1775 );
1776
1777 let type_signature = TypeSignature::OneOf(vec![
1778 TypeSignature::Exact(vec![DataType::Int32, DataType::Int64]),
1779 TypeSignature::Exact(vec![DataType::Float32, DataType::Float64]),
1780 TypeSignature::Exact(vec![DataType::Utf8]),
1781 ]);
1782 let possible_types = type_signature.get_example_types();
1783 assert_eq!(
1784 possible_types,
1785 vec![
1786 vec![DataType::Int32, DataType::Int64],
1787 vec![DataType::Float32, DataType::Float64],
1788 vec![DataType::Utf8]
1789 ]
1790 );
1791
1792 let type_signature =
1793 TypeSignature::Uniform(2, vec![DataType::Float32, DataType::Int64]);
1794 let possible_types = type_signature.get_example_types();
1795 assert_eq!(
1796 possible_types,
1797 vec![
1798 vec![DataType::Float32, DataType::Float32],
1799 vec![DataType::Int64, DataType::Int64]
1800 ]
1801 );
1802
1803 let type_signature = TypeSignature::Coercible(vec![
1804 Coercion::new_exact(TypeSignatureClass::Native(logical_string())),
1805 Coercion::new_exact(TypeSignatureClass::Native(logical_int64())),
1806 ]);
1807 let possible_types = type_signature.get_example_types();
1808 assert_eq!(
1809 possible_types,
1810 vec![
1811 vec![DataType::Utf8, DataType::Int64],
1812 vec![DataType::LargeUtf8, DataType::Int64],
1813 vec![DataType::Utf8View, DataType::Int64]
1814 ]
1815 );
1816
1817 let type_signature =
1818 TypeSignature::Variadic(vec![DataType::Int32, DataType::Int64]);
1819 let possible_types = type_signature.get_example_types();
1820 assert_eq!(
1821 possible_types,
1822 vec![vec![DataType::Int32], vec![DataType::Int64]]
1823 );
1824
1825 let type_signature = TypeSignature::Numeric(2);
1826 let possible_types = type_signature.get_example_types();
1827 assert_eq!(
1828 possible_types,
1829 vec![
1830 vec![DataType::Int8, DataType::Int8],
1831 vec![DataType::Int16, DataType::Int16],
1832 vec![DataType::Int32, DataType::Int32],
1833 vec![DataType::Int64, DataType::Int64],
1834 vec![DataType::UInt8, DataType::UInt8],
1835 vec![DataType::UInt16, DataType::UInt16],
1836 vec![DataType::UInt32, DataType::UInt32],
1837 vec![DataType::UInt64, DataType::UInt64],
1838 vec![DataType::Float16, DataType::Float16],
1839 vec![DataType::Float32, DataType::Float32],
1840 vec![DataType::Float64, DataType::Float64]
1841 ]
1842 );
1843
1844 let type_signature = TypeSignature::String(2);
1845 let possible_types = type_signature.get_example_types();
1846 assert_eq!(
1847 possible_types,
1848 vec![
1849 vec![DataType::Utf8, DataType::Utf8],
1850 vec![DataType::LargeUtf8, DataType::LargeUtf8],
1851 vec![DataType::Utf8View, DataType::Utf8View]
1852 ]
1853 );
1854 }
1855
1856 #[test]
1857 fn test_get_representative_types() {
1858 let type_signature = TypeSignature::Exact(vec![DataType::Int32, DataType::Int64]);
1859 let types = type_signature.get_representative_types();
1860 assert_eq!(types, vec![vec![NativeType::Int32, NativeType::Int64]]);
1861
1862 let type_signature = TypeSignature::OneOf(vec![
1863 TypeSignature::Exact(vec![DataType::Int32, DataType::Int64]),
1864 TypeSignature::Exact(vec![DataType::Float32, DataType::Float64]),
1865 ]);
1866 let types = type_signature.get_representative_types();
1867 assert_eq!(
1868 types,
1869 vec![
1870 vec![NativeType::Int32, NativeType::Int64],
1871 vec![NativeType::Float32, NativeType::Float64]
1872 ]
1873 );
1874
1875 let type_signature = TypeSignature::OneOf(vec![
1876 TypeSignature::Exact(vec![DataType::Int32, DataType::Int64]),
1877 TypeSignature::Exact(vec![DataType::Float32, DataType::Float64]),
1878 TypeSignature::Exact(vec![DataType::Utf8]),
1879 ]);
1880 let types = type_signature.get_representative_types();
1881 assert_eq!(
1882 types,
1883 vec![
1884 vec![NativeType::Int32, NativeType::Int64],
1885 vec![NativeType::Float32, NativeType::Float64],
1886 vec![NativeType::String]
1887 ]
1888 );
1889
1890 let type_signature =
1891 TypeSignature::Uniform(2, vec![DataType::Float32, DataType::Int64]);
1892 let types = type_signature.get_representative_types();
1893 assert_eq!(
1894 types,
1895 vec![
1896 vec![NativeType::Float32, NativeType::Float32],
1897 vec![NativeType::Int64, NativeType::Int64]
1898 ]
1899 );
1900
1901 let type_signature = TypeSignature::Coercible(vec![
1902 Coercion::new_exact(TypeSignatureClass::Native(logical_string())),
1903 Coercion::new_exact(TypeSignatureClass::Native(logical_int64())),
1904 ]);
1905 let types = type_signature.get_representative_types();
1906 assert_eq!(types, vec![vec![NativeType::String, NativeType::Int64]]);
1907
1908 let type_signature =
1909 TypeSignature::Variadic(vec![DataType::Int32, DataType::Int64]);
1910 let types = type_signature.get_representative_types();
1911 assert_eq!(
1912 types,
1913 vec![vec![NativeType::Int32], vec![NativeType::Int64]]
1914 );
1915
1916 let type_signature = TypeSignature::Numeric(2);
1917 let types = type_signature.get_representative_types();
1918 assert_eq!(
1919 types,
1920 vec![
1921 vec![NativeType::Float64, NativeType::Float64],
1922 vec![NativeType::Int64, NativeType::Int64],
1923 vec![
1924 Decimal128Type::DEFAULT_TYPE.into(),
1925 Decimal128Type::DEFAULT_TYPE.into()
1926 ],
1927 ]
1928 );
1929
1930 let type_signature = TypeSignature::String(2);
1931 let possible_types = type_signature.get_representative_types();
1932 assert_eq!(
1933 possible_types,
1934 vec![vec![NativeType::String, NativeType::String],]
1935 );
1936 }
1937
1938 #[test]
1939 fn test_signature_with_parameter_names() {
1940 let sig = Signature::exact(
1941 vec![DataType::Int32, DataType::Utf8],
1942 Volatility::Immutable,
1943 )
1944 .with_parameter_names(vec!["count".to_string(), "name".to_string()])
1945 .unwrap();
1946
1947 assert_eq!(
1948 sig.parameter_names,
1949 Some(vec!["count".to_string(), "name".to_string()])
1950 );
1951 assert_eq!(
1952 sig.type_signature,
1953 TypeSignature::Exact(vec![DataType::Int32, DataType::Utf8])
1954 );
1955 }
1956
1957 #[test]
1958 fn test_signature_parameter_names_wrong_count() {
1959 let result = Signature::exact(
1960 vec![DataType::Int32, DataType::Utf8],
1961 Volatility::Immutable,
1962 )
1963 .with_parameter_names(vec!["count".to_string()]); assert!(result.is_err());
1966 assert!(
1967 result
1968 .unwrap_err()
1969 .to_string()
1970 .contains("does not match signature arity")
1971 );
1972 }
1973
1974 #[test]
1975 fn test_signature_parameter_names_duplicate() {
1976 let result = Signature::exact(
1977 vec![DataType::Int32, DataType::Int32],
1978 Volatility::Immutable,
1979 )
1980 .with_parameter_names(vec!["count".to_string(), "count".to_string()]);
1981
1982 assert!(result.is_err());
1983 assert!(
1984 result
1985 .unwrap_err()
1986 .to_string()
1987 .contains("Duplicate parameter name")
1988 );
1989 }
1990
1991 #[test]
1992 fn test_signature_parameter_names_variadic() {
1993 let result = Signature::variadic(vec![DataType::Int32], Volatility::Immutable)
1994 .with_parameter_names(vec!["arg".to_string()]);
1995
1996 assert!(result.is_err());
1997 assert!(
1998 result
1999 .unwrap_err()
2000 .to_string()
2001 .contains("variable arity signature")
2002 );
2003 }
2004
2005 #[test]
2006 fn test_signature_without_parameter_names() {
2007 let sig = Signature::exact(
2008 vec![DataType::Int32, DataType::Utf8],
2009 Volatility::Immutable,
2010 );
2011
2012 assert_eq!(sig.parameter_names, None);
2013 }
2014
2015 #[test]
2016 fn test_signature_uniform_with_parameter_names() {
2017 let sig = Signature::uniform(3, vec![DataType::Float64], Volatility::Immutable)
2018 .with_parameter_names(vec!["x".to_string(), "y".to_string(), "z".to_string()])
2019 .unwrap();
2020
2021 assert_eq!(
2022 sig.parameter_names,
2023 Some(vec!["x".to_string(), "y".to_string(), "z".to_string()])
2024 );
2025 }
2026
2027 #[test]
2028 fn test_signature_numeric_with_parameter_names() {
2029 let sig = Signature::numeric(2, Volatility::Immutable)
2030 .with_parameter_names(vec!["a".to_string(), "b".to_string()])
2031 .unwrap();
2032
2033 assert_eq!(
2034 sig.parameter_names,
2035 Some(vec!["a".to_string(), "b".to_string()])
2036 );
2037 }
2038
2039 #[test]
2040 fn test_signature_nullary_with_empty_names() {
2041 let sig = Signature::nullary(Volatility::Immutable)
2042 .with_parameter_names(Vec::<String>::new())
2043 .unwrap();
2044
2045 assert_eq!(sig.parameter_names, Some(vec![]));
2046 }
2047
2048 #[test]
2049 fn test_to_string_repr_with_names_exact() {
2050 let sig = TypeSignature::Exact(vec![DataType::Int32, DataType::Utf8]);
2051
2052 assert_eq!(sig.to_string_repr_with_names(None), vec!["Int32, Utf8"]);
2053
2054 let names = vec!["id".to_string(), "name".to_string()];
2055 assert_eq!(
2056 sig.to_string_repr_with_names(Some(&names)),
2057 vec!["id: Int32, name: Utf8"]
2058 );
2059 }
2060
2061 #[test]
2062 fn test_to_string_repr_with_names_any() {
2063 let sig = TypeSignature::Any(3);
2064
2065 assert_eq!(sig.to_string_repr_with_names(None), vec!["Any, Any, Any"]);
2066
2067 let names = vec!["x".to_string(), "y".to_string(), "z".to_string()];
2068 assert_eq!(
2069 sig.to_string_repr_with_names(Some(&names)),
2070 vec!["x: Any, y: Any, z: Any"]
2071 );
2072 }
2073
2074 #[test]
2075 fn test_to_string_repr_with_names_one_of() {
2076 let sig =
2077 TypeSignature::OneOf(vec![TypeSignature::Any(2), TypeSignature::Any(3)]);
2078
2079 assert_eq!(
2080 sig.to_string_repr_with_names(None),
2081 vec!["Any, Any", "Any, Any, Any"]
2082 );
2083
2084 let names = vec![
2085 "str".to_string(),
2086 "start_pos".to_string(),
2087 "length".to_string(),
2088 ];
2089 assert_eq!(
2090 sig.to_string_repr_with_names(Some(&names)),
2091 vec![
2092 "str: Any, start_pos: Any",
2093 "str: Any, start_pos: Any, length: Any"
2094 ]
2095 );
2096 }
2097
2098 #[test]
2099 fn test_to_string_repr_with_names_partial() {
2100 let sig = TypeSignature::Exact(vec![DataType::Int32, DataType::Utf8]);
2102
2103 let names = vec!["a".to_string(), "b".to_string(), "c".to_string()];
2105 assert_eq!(
2106 sig.to_string_repr_with_names(Some(&names)),
2107 vec!["a: Int32, b: Utf8"]
2108 );
2109 }
2110
2111 #[test]
2112 fn test_to_string_repr_with_names_uniform() {
2113 let sig = TypeSignature::Uniform(2, vec![DataType::Float64]);
2114
2115 assert_eq!(
2116 sig.to_string_repr_with_names(None),
2117 vec!["Float64, Float64"]
2118 );
2119
2120 let names = vec!["x".to_string(), "y".to_string()];
2121 assert_eq!(
2122 sig.to_string_repr_with_names(Some(&names)),
2123 vec!["x: Float64, y: Float64"]
2124 );
2125 }
2126
2127 #[test]
2128 fn test_to_string_repr_with_names_coercible() {
2129 let sig = TypeSignature::Coercible(vec![
2130 Coercion::new_exact(TypeSignatureClass::Native(logical_int32())),
2131 Coercion::new_exact(TypeSignatureClass::Native(logical_int32())),
2132 ]);
2133
2134 let names = vec!["a".to_string(), "b".to_string()];
2135 let result = sig.to_string_repr_with_names(Some(&names));
2136 assert_eq!(result.len(), 1);
2138 assert!(result[0].starts_with("a: "));
2139 assert!(result[0].contains(", b: "));
2140 }
2141
2142 #[test]
2143 fn test_to_string_repr_with_names_comparable_numeric_string() {
2144 let comparable = TypeSignature::Comparable(3);
2145 let numeric = TypeSignature::Numeric(2);
2146 let string_sig = TypeSignature::String(2);
2147
2148 let names = vec!["a".to_string(), "b".to_string(), "c".to_string()];
2149
2150 assert_eq!(
2152 comparable.to_string_repr_with_names(Some(&names)),
2153 vec!["a: Comparable, b: Comparable, c: Comparable"]
2154 );
2155 assert_eq!(
2156 numeric.to_string_repr_with_names(Some(&names)),
2157 vec!["a: Numeric, b: Numeric"]
2158 );
2159 assert_eq!(
2160 string_sig.to_string_repr_with_names(Some(&names)),
2161 vec!["a: String, b: String"]
2162 );
2163 }
2164
2165 #[test]
2166 fn test_to_string_repr_with_names_variadic_fallback() {
2167 let variadic = TypeSignature::Variadic(vec![DataType::Utf8, DataType::LargeUtf8]);
2168 let names = vec!["x".to_string()];
2169 assert_eq!(
2170 variadic.to_string_repr_with_names(Some(&names)),
2171 variadic.to_string_repr()
2172 );
2173
2174 let variadic_any = TypeSignature::VariadicAny;
2175 assert_eq!(
2176 variadic_any.to_string_repr_with_names(Some(&names)),
2177 variadic_any.to_string_repr()
2178 );
2179
2180 let user_defined = TypeSignature::UserDefined;
2182 assert_eq!(
2183 user_defined.to_string_repr_with_names(Some(&names)),
2184 vec!["x"]
2185 );
2186 assert_eq!(
2187 user_defined.to_string_repr_with_names(None),
2188 user_defined.to_string_repr()
2189 );
2190 }
2191
2192 #[test]
2193 fn test_to_string_repr_with_names_nullary() {
2194 let sig = TypeSignature::Nullary;
2195 let names = vec!["x".to_string()];
2196
2197 assert_eq!(
2199 sig.to_string_repr_with_names(Some(&names)),
2200 vec!["NullAry()"]
2201 );
2202 assert_eq!(sig.to_string_repr_with_names(None), vec!["NullAry()"]);
2203 }
2204
2205 #[test]
2206 fn test_to_string_repr_with_names_array_signature() {
2207 let sig = TypeSignature::ArraySignature(ArrayFunctionSignature::Array {
2208 arguments: vec![
2209 ArrayFunctionArgument::Array,
2210 ArrayFunctionArgument::Index,
2211 ArrayFunctionArgument::Element,
2212 ],
2213 array_coercion: None,
2214 });
2215
2216 assert_eq!(
2217 sig.to_string_repr_with_names(None),
2218 vec!["array, index, element"]
2219 );
2220
2221 let names = vec!["arr".to_string(), "idx".to_string(), "val".to_string()];
2222 assert_eq!(
2223 sig.to_string_repr_with_names(Some(&names)),
2224 vec!["arr: array, idx: index, val: element"]
2225 );
2226
2227 let recursive =
2228 TypeSignature::ArraySignature(ArrayFunctionSignature::RecursiveArray);
2229 let names = vec!["array".to_string()];
2230 assert_eq!(
2231 recursive.to_string_repr_with_names(Some(&names)),
2232 vec!["array: recursive_array"]
2233 );
2234
2235 let map_array = TypeSignature::ArraySignature(ArrayFunctionSignature::MapArray);
2237 let names = vec!["map".to_string()];
2238 assert_eq!(
2239 map_array.to_string_repr_with_names(Some(&names)),
2240 vec!["map: map_array"]
2241 );
2242 }
2243
2244 #[test]
2245 fn test_type_signature_arity_exact() {
2246 let sig = TypeSignature::Exact(vec![DataType::Int32, DataType::Utf8]);
2247 assert_eq!(sig.arity(), Arity::Fixed(2));
2248
2249 let sig = TypeSignature::Exact(vec![]);
2250 assert_eq!(sig.arity(), Arity::Fixed(0));
2251 }
2252
2253 #[test]
2254 fn test_type_signature_arity_uniform() {
2255 let sig = TypeSignature::Uniform(3, vec![DataType::Float64]);
2256 assert_eq!(sig.arity(), Arity::Fixed(3));
2257
2258 let sig = TypeSignature::Uniform(1, vec![DataType::Int32]);
2259 assert_eq!(sig.arity(), Arity::Fixed(1));
2260 }
2261
2262 #[test]
2263 fn test_type_signature_arity_numeric() {
2264 let sig = TypeSignature::Numeric(2);
2265 assert_eq!(sig.arity(), Arity::Fixed(2));
2266 }
2267
2268 #[test]
2269 fn test_type_signature_arity_string() {
2270 let sig = TypeSignature::String(3);
2271 assert_eq!(sig.arity(), Arity::Fixed(3));
2272 }
2273
2274 #[test]
2275 fn test_type_signature_arity_comparable() {
2276 let sig = TypeSignature::Comparable(2);
2277 assert_eq!(sig.arity(), Arity::Fixed(2));
2278 }
2279
2280 #[test]
2281 fn test_type_signature_arity_any() {
2282 let sig = TypeSignature::Any(4);
2283 assert_eq!(sig.arity(), Arity::Fixed(4));
2284 }
2285
2286 #[test]
2287 fn test_type_signature_arity_coercible() {
2288 let sig = TypeSignature::Coercible(vec![
2289 Coercion::new_exact(TypeSignatureClass::Native(logical_int32())),
2290 Coercion::new_exact(TypeSignatureClass::Native(logical_string())),
2291 ]);
2292 assert_eq!(sig.arity(), Arity::Fixed(2));
2293 }
2294
2295 #[test]
2296 fn test_type_signature_arity_nullary() {
2297 let sig = TypeSignature::Nullary;
2298 assert_eq!(sig.arity(), Arity::Fixed(0));
2299 }
2300
2301 #[test]
2302 fn test_type_signature_arity_array_signature() {
2303 let sig = TypeSignature::ArraySignature(ArrayFunctionSignature::Array {
2305 arguments: vec![ArrayFunctionArgument::Array, ArrayFunctionArgument::Index],
2306 array_coercion: None,
2307 });
2308 assert_eq!(sig.arity(), Arity::Fixed(2));
2309
2310 let sig = TypeSignature::ArraySignature(ArrayFunctionSignature::Array {
2312 arguments: vec![
2313 ArrayFunctionArgument::Array,
2314 ArrayFunctionArgument::Element,
2315 ArrayFunctionArgument::Index,
2316 ],
2317 array_coercion: None,
2318 });
2319 assert_eq!(sig.arity(), Arity::Fixed(3));
2320
2321 let sig = TypeSignature::ArraySignature(ArrayFunctionSignature::RecursiveArray);
2323 assert_eq!(sig.arity(), Arity::Fixed(1));
2324
2325 let sig = TypeSignature::ArraySignature(ArrayFunctionSignature::MapArray);
2327 assert_eq!(sig.arity(), Arity::Fixed(1));
2328 }
2329
2330 #[test]
2331 fn test_type_signature_arity_one_of_fixed() {
2332 let sig = TypeSignature::OneOf(vec![
2334 TypeSignature::Exact(vec![DataType::Int32]),
2335 TypeSignature::Exact(vec![DataType::Int32, DataType::Utf8]),
2336 TypeSignature::Exact(vec![
2337 DataType::Int32,
2338 DataType::Utf8,
2339 DataType::Float64,
2340 ]),
2341 ]);
2342 assert_eq!(sig.arity(), Arity::Fixed(3));
2343 }
2344
2345 #[test]
2346 fn test_type_signature_arity_one_of_variable() {
2347 let sig = TypeSignature::OneOf(vec![
2349 TypeSignature::Exact(vec![DataType::Int32]),
2350 TypeSignature::VariadicAny,
2351 ]);
2352 assert_eq!(sig.arity(), Arity::Variable);
2353 }
2354
2355 #[test]
2356 fn test_type_signature_arity_variadic() {
2357 let sig = TypeSignature::Variadic(vec![DataType::Int32]);
2358 assert_eq!(sig.arity(), Arity::Variable);
2359
2360 let sig = TypeSignature::VariadicAny;
2361 assert_eq!(sig.arity(), Arity::Variable);
2362 }
2363
2364 #[test]
2365 fn test_type_signature_arity_user_defined() {
2366 let sig = TypeSignature::UserDefined;
2367 assert_eq!(sig.arity(), Arity::Variable);
2368 }
2369
2370 #[test]
2371 fn test_type_signature_display() {
2372 use insta::assert_snapshot;
2373
2374 assert_snapshot!(TypeSignature::Nullary, @"Nullary");
2375 assert_snapshot!(TypeSignature::Any(2), @"Any(2)");
2376 assert_snapshot!(TypeSignature::Numeric(3), @"Numeric(3)");
2377 assert_snapshot!(TypeSignature::String(1), @"String(1)");
2378 assert_snapshot!(TypeSignature::Comparable(2), @"Comparable(2)");
2379 assert_snapshot!(TypeSignature::VariadicAny, @"VariadicAny");
2380 assert_snapshot!(TypeSignature::UserDefined, @"UserDefined");
2381
2382 assert_snapshot!(
2383 TypeSignature::Exact(vec![DataType::Int32, DataType::Utf8]),
2384 @"Exact(Int32, Utf8)"
2385 );
2386 assert_snapshot!(
2387 TypeSignature::Variadic(vec![DataType::Utf8, DataType::LargeUtf8]),
2388 @"Variadic(Utf8, LargeUtf8)"
2389 );
2390 assert_snapshot!(
2391 TypeSignature::Uniform(2, vec![DataType::Float32, DataType::Float64]),
2392 @"Uniform(2, [Float32, Float64])"
2393 );
2394
2395 assert_snapshot!(
2396 TypeSignature::Coercible(vec![
2397 Coercion::new_exact(TypeSignatureClass::Native(logical_float64())),
2398 Coercion::new_exact(TypeSignatureClass::Native(logical_int32())),
2399 ]),
2400 @"Coercible(Float64, Int32)"
2401 );
2402
2403 assert_snapshot!(
2404 TypeSignature::OneOf(vec![
2405 TypeSignature::Nullary,
2406 TypeSignature::VariadicAny,
2407 ]),
2408 @"OneOf(Nullary, VariadicAny)"
2409 );
2410 }
2411
2412 #[test]
2413 fn test_type_signature_class_display() {
2414 use insta::assert_snapshot;
2415
2416 assert_snapshot!(TypeSignatureClass::Any, @"Any");
2417 assert_snapshot!(TypeSignatureClass::Numeric, @"Numeric");
2418 assert_snapshot!(TypeSignatureClass::Integer, @"Integer");
2419 assert_snapshot!(TypeSignatureClass::Float, @"Float");
2420 assert_snapshot!(TypeSignatureClass::Decimal, @"Decimal");
2421 assert_snapshot!(TypeSignatureClass::Timestamp, @"Timestamp");
2422 assert_snapshot!(TypeSignatureClass::Time, @"Time");
2423 assert_snapshot!(TypeSignatureClass::Interval, @"Interval");
2424 assert_snapshot!(TypeSignatureClass::Duration, @"Duration");
2425 assert_snapshot!(TypeSignatureClass::Binary, @"Binary");
2426 assert_snapshot!(TypeSignatureClass::Native(logical_int32()), @"Int32");
2427 assert_snapshot!(TypeSignatureClass::Native(logical_string()), @"String");
2428 }
2429
2430 #[test]
2431 fn test_coercion_display() {
2432 use insta::assert_snapshot;
2433
2434 let exact_int = Coercion::new_exact(TypeSignatureClass::Native(logical_int32()));
2435 assert_snapshot!(exact_int, @"Int32");
2436
2437 let exact_numeric = Coercion::new_exact(TypeSignatureClass::Numeric);
2438 assert_snapshot!(exact_numeric, @"Numeric");
2439
2440 let implicit = Coercion::new_implicit(
2441 TypeSignatureClass::Native(logical_float64()),
2442 vec![TypeSignatureClass::Numeric],
2443 NativeType::Float64,
2444 );
2445 assert_snapshot!(implicit, @"Float64");
2446
2447 let implicit_with_multiple_sources = Coercion::new_implicit(
2448 TypeSignatureClass::Native(logical_int64()),
2449 vec![TypeSignatureClass::Integer, TypeSignatureClass::Numeric],
2450 NativeType::Int64,
2451 );
2452 assert_snapshot!(implicit_with_multiple_sources, @"Int64");
2453 }
2454
2455 #[test]
2456 fn test_new_implicit_native() {
2457 let allowed_source_types = vec![TypeSignatureClass::Numeric];
2458
2459 assert_eq!(
2460 Coercion::new_implicit_native(
2461 logical_float64(),
2462 allowed_source_types.clone(),
2463 ),
2464 Coercion::new_implicit(
2465 TypeSignatureClass::Native(logical_float64()),
2466 allowed_source_types,
2467 NativeType::Float64,
2468 )
2469 );
2470 }
2471
2472 #[test]
2473 fn test_coercion_encoding_preservation_affects_equality() {
2474 assert!(!EncodingPreservation::default().preserve_dictionary());
2475 let preserve_dictionary = EncodingPreservation::dictionary();
2476 assert!(preserve_dictionary.preserve_dictionary());
2477
2478 let default = Coercion::new_exact(TypeSignatureClass::Native(logical_string()));
2479 let preserving = default
2480 .clone()
2481 .with_encoding_preservation(preserve_dictionary);
2482
2483 assert_ne!(default, preserving);
2484 }
2485
2486 #[test]
2487 fn test_to_string_repr_coercible() {
2488 use insta::assert_snapshot;
2489
2490 let sig = TypeSignature::Coercible(vec![
2492 Coercion::new_implicit(
2493 TypeSignatureClass::Native(logical_float64()),
2494 vec![TypeSignatureClass::Numeric],
2495 NativeType::Float64,
2496 ),
2497 Coercion::new_implicit(
2498 TypeSignatureClass::Native(logical_int64()),
2499 vec![TypeSignatureClass::Integer],
2500 NativeType::Int64,
2501 ),
2502 ]);
2503 let repr = sig.to_string_repr();
2504 assert_eq!(repr.len(), 1);
2505 assert_snapshot!(repr[0], @"Float64, Int64");
2506 }
2507
2508 #[test]
2509 fn test_to_string_repr_coercible_exact() {
2510 use insta::assert_snapshot;
2511
2512 let sig = TypeSignature::Coercible(vec![
2513 Coercion::new_exact(TypeSignatureClass::Native(logical_string())),
2514 Coercion::new_exact(TypeSignatureClass::Native(logical_int64())),
2515 ]);
2516 let repr = sig.to_string_repr();
2517 assert_eq!(repr.len(), 1);
2518 assert_snapshot!(repr[0], @"String, Int64");
2519 }
2520}