1use super::binary::binary_numeric_coercion;
6use crate::{
7 AggregateUDF, HigherOrderTypeSignature, HigherOrderUDF, ScalarUDF, Signature,
8 TypeSignature, ValueOrLambda, WindowUDF,
9};
10use arrow::datatypes::{Field, FieldRef};
11use arrow::{
12 compute::can_cast_types,
13 datatypes::{DataType, TimeUnit},
14};
15use datafusion_common::internal_datafusion_err;
16use datafusion_common::types::LogicalType;
17use datafusion_common::utils::{
18 ListCoercion, base_type, coerced_fixed_size_list_to_list,
19};
20use datafusion_common::{
21 Result, exec_err, internal_err, plan_err, types::NativeType, utils::list_ndims,
22};
23use datafusion_expr_common::signature::{
24 ArrayFunctionArgument, EncodingPreservation, TypeSignatureClass,
25};
26use datafusion_expr_common::type_coercion::binary::type_union_resolution;
27use datafusion_expr_common::{
28 signature::{ArrayFunctionSignature, FIXED_SIZE_LIST_WILDCARD, TIMEZONE_WILDCARD},
29 type_coercion::binary::comparison_coercion,
30 type_coercion::binary::string_coercion,
31};
32use itertools::Itertools as _;
33use std::sync::Arc;
34
35pub trait UDFCoercionExt {
38 fn name(&self) -> &str;
40 fn signature(&self) -> &Signature;
43 fn coerce_types(&self, arg_types: &[DataType]) -> Result<Vec<DataType>>;
46}
47
48impl UDFCoercionExt for ScalarUDF {
49 fn name(&self) -> &str {
50 self.name()
51 }
52
53 fn signature(&self) -> &Signature {
54 self.signature()
55 }
56
57 fn coerce_types(&self, arg_types: &[DataType]) -> Result<Vec<DataType>> {
58 self.coerce_types(arg_types)
59 }
60}
61
62impl UDFCoercionExt for AggregateUDF {
63 fn name(&self) -> &str {
64 self.name()
65 }
66
67 fn signature(&self) -> &Signature {
68 self.signature()
69 }
70
71 fn coerce_types(&self, arg_types: &[DataType]) -> Result<Vec<DataType>> {
72 self.coerce_types(arg_types)
73 }
74}
75
76impl UDFCoercionExt for WindowUDF {
77 fn name(&self) -> &str {
78 self.name()
79 }
80
81 fn signature(&self) -> &Signature {
82 self.signature()
83 }
84
85 fn coerce_types(&self, arg_types: &[DataType]) -> Result<Vec<DataType>> {
86 self.coerce_types(arg_types)
87 }
88}
89
90pub fn fields_with_udf<F: UDFCoercionExt>(
98 current_fields: &[FieldRef],
99 func: &F,
100) -> Result<Vec<FieldRef>> {
101 let signature = func.signature();
102 let type_signature = &signature.type_signature;
103
104 if current_fields.is_empty() && type_signature != &TypeSignature::UserDefined {
105 if type_signature.supports_zero_argument() {
106 return Ok(vec![]);
107 } else if type_signature.used_to_support_zero_arguments() {
108 return plan_err!(
110 "'{}' does not support zero arguments. Use TypeSignature::Nullary for zero arguments",
111 func.name()
112 );
113 } else {
114 return plan_err!("'{}' does not support zero arguments", func.name());
115 }
116 }
117 let current_types = current_fields
118 .iter()
119 .map(|f| f.data_type())
120 .cloned()
121 .collect::<Vec<_>>();
122
123 let valid_types = get_valid_types_with_udf(type_signature, ¤t_types, func)?;
124 if valid_types
125 .iter()
126 .any(|data_type| data_type == ¤t_types)
127 {
128 return Ok(current_fields.to_vec());
129 }
130
131 let updated_types =
132 try_coerce_types(func.name(), valid_types, ¤t_types, type_signature)?;
133
134 Ok(current_fields
135 .iter()
136 .zip(updated_types)
137 .map(|(current_field, new_type)| {
138 current_field.as_ref().clone().with_data_type(new_type)
139 })
140 .map(Arc::new)
141 .collect())
142}
143
144pub fn value_fields_with_higher_order_udf<L: Clone>(
157 current_fields: &[ValueOrLambda<FieldRef, L>],
158 func: &HigherOrderUDF,
159) -> Result<Vec<ValueOrLambda<FieldRef, L>>> {
160 match func.signature().type_signature {
161 HigherOrderTypeSignature::UserDefined => {
162 let arg_types = current_fields
163 .iter()
164 .filter_map(|p| match p {
165 ValueOrLambda::Value(field) => Some(field.data_type().clone()),
166 ValueOrLambda::Lambda(_) => None,
167 })
168 .collect::<Vec<_>>();
169
170 let coerced_types = func.coerce_value_types(&arg_types)?;
171
172 if coerced_types.len() != arg_types.len() {
173 return plan_err!(
174 "{} coerce_value_types should have returned {} items but returned {}",
175 func.name(),
176 arg_types.len(),
177 coerced_types.len()
178 );
179 }
180
181 let mut coerced_types = coerced_types.into_iter();
189
190 current_fields
191 .iter()
192 .map(|current_field| match current_field {
193 ValueOrLambda::Value(field) => {
194 let data_type = coerced_types.next().ok_or_else(|| {
195 internal_datafusion_err!(
196 "coerced_types len should have been checked above"
197 )
198 })?;
199
200 Ok(ValueOrLambda::Value(Arc::new(
201 field.as_ref().clone().with_data_type(data_type),
202 )))
203 }
204 ValueOrLambda::Lambda(lambda) => {
205 Ok(ValueOrLambda::Lambda(lambda.clone()))
206 }
207 })
208 .collect()
209 }
210 HigherOrderTypeSignature::VariadicAny => Ok(current_fields.to_vec()),
211 HigherOrderTypeSignature::Any(number) => {
212 if current_fields.len() != number {
213 return plan_err!(
214 "The function '{}' expected {number} arguments but received {}",
215 func.name(),
216 current_fields.len()
217 );
218 }
219
220 Ok(current_fields.to_vec())
221 }
222 HigherOrderTypeSignature::Exact(ref expected) => {
223 if current_fields.len() != expected.len() {
224 let name = func.name();
225 let expected_len = expected.len();
226 let actual_len = current_fields.len();
227 return plan_err!(
228 "The function '{name}' expected {expected_len} argument(s) but received {actual_len}"
229 );
230 }
231
232 for (i, (actual, expected)) in
233 current_fields.iter().zip(expected.iter()).enumerate()
234 {
235 match (actual, expected) {
236 (ValueOrLambda::Value(_), ValueOrLambda::Value(_)) => {}
237 (ValueOrLambda::Lambda(_), ValueOrLambda::Lambda(_)) => {}
238 (ValueOrLambda::Value(_), ValueOrLambda::Lambda(_)) => {
239 let name = func.name();
240 return plan_err!(
241 "The function '{name}' expected a lambda at position {i} but received a value"
242 );
243 }
244 (ValueOrLambda::Lambda(_), ValueOrLambda::Value(_)) => {
245 let name = func.name();
246 return plan_err!(
247 "The function '{name}' expected a value at position {i} but received a lambda"
248 );
249 }
250 }
251 }
252
253 let arg_types = current_fields
254 .iter()
255 .filter_map(|p| match p {
256 ValueOrLambda::Value(field) => Some(field.data_type().clone()),
257 ValueOrLambda::Lambda(_) => None,
258 })
259 .collect::<Vec<_>>();
260
261 let coerced_types = func.coerce_value_types(&arg_types)?;
262
263 if coerced_types.len() != arg_types.len() {
264 return plan_err!(
265 "{} coerce_value_types should have returned {} items but returned {}",
266 func.name(),
267 arg_types.len(),
268 coerced_types.len()
269 );
270 }
271
272 let mut coerced_types = coerced_types.into_iter();
273
274 current_fields
275 .iter()
276 .map(|current_field| match current_field {
277 ValueOrLambda::Value(field) => {
278 let data_type = coerced_types.next().ok_or_else(|| {
279 internal_datafusion_err!(
280 "coerced_types len should have been checked above"
281 )
282 })?;
283
284 Ok(ValueOrLambda::Value(Arc::new(
285 field.as_ref().clone().with_data_type(data_type),
286 )))
287 }
288 ValueOrLambda::Lambda(lambda) => {
289 Ok(ValueOrLambda::Lambda(lambda.clone()))
290 }
291 })
292 .collect()
293 }
294 }
295}
296
297pub fn value_fields_with_higher_order_udf_and_lambdas(
310 current_fields: &[ValueOrLambda<FieldRef, FieldRef>],
311 func: &HigherOrderUDF,
312) -> Result<Vec<ValueOrLambda<FieldRef, FieldRef>>> {
313 let mut new_fields = value_fields_with_higher_order_udf(current_fields, func)?;
314
315 let new_types = new_fields
316 .iter()
317 .map(|f| match f {
318 ValueOrLambda::Value(f) => ValueOrLambda::Value(f.data_type().clone()),
319 ValueOrLambda::Lambda(f) => ValueOrLambda::Lambda(f.data_type().clone()),
320 })
321 .collect::<Vec<_>>();
322
323 if let Some(new_value_types) = func.coerce_values_for_lambdas(&new_types)? {
324 let mut new_value_types = new_value_types.into_iter();
325
326 let value_types_count = new_types
327 .iter()
328 .filter(|e| matches!(e, ValueOrLambda::Value(_)))
329 .count();
330
331 if new_value_types.len() != value_types_count {
332 return plan_err!(
333 "{} coerce_values_for_lambdas returned {} values but {value_types_count} expected",
334 func.name(),
335 new_value_types.len()
336 );
337 }
338
339 for new_field in &mut new_fields {
340 match new_field {
341 ValueOrLambda::Value(value) => {
342 let coerce_to = new_value_types.next().ok_or_else(|| {
343 internal_datafusion_err!(
344 "new_value_types len should have been checked above"
345 )
346 })?;
347
348 if value.data_type() != &coerce_to {
349 Arc::make_mut(value).set_data_type(coerce_to);
350 }
351 }
352 ValueOrLambda::Lambda(_) => {}
353 }
354 }
355 }
356
357 Ok(new_fields)
358}
359
360#[deprecated(since = "52.0.0", note = "use fields_with_udf")]
368pub fn data_types_with_scalar_udf(
369 current_types: &[DataType],
370 func: &ScalarUDF,
371) -> Result<Vec<DataType>> {
372 let current_fields = current_types
373 .iter()
374 .map(|dt| Arc::new(Field::new("f", dt.clone(), true)))
375 .collect::<Vec<_>>();
376 Ok(fields_with_udf(¤t_fields, func)?
377 .iter()
378 .map(|f| f.data_type().clone())
379 .collect())
380}
381
382#[deprecated(since = "52.0.0", note = "use fields_with_udf")]
390pub fn fields_with_aggregate_udf(
391 current_fields: &[FieldRef],
392 func: &AggregateUDF,
393) -> Result<Vec<FieldRef>> {
394 fields_with_udf(current_fields, func)
395}
396
397#[deprecated(since = "52.0.0", note = "use fields_with_udf")]
405pub fn fields_with_window_udf(
406 current_fields: &[FieldRef],
407 func: &WindowUDF,
408) -> Result<Vec<FieldRef>> {
409 fields_with_udf(current_fields, func)
410}
411
412#[deprecated(since = "52.0.0", note = "use fields_with_udf")]
420pub fn data_types(
421 function_name: impl AsRef<str>,
422 current_types: &[DataType],
423 signature: &Signature,
424) -> Result<Vec<DataType>> {
425 let type_signature = &signature.type_signature;
426
427 if current_types.is_empty() && type_signature != &TypeSignature::UserDefined {
428 if type_signature.supports_zero_argument() {
429 return Ok(vec![]);
430 } else if type_signature.used_to_support_zero_arguments() {
431 return plan_err!(
433 "function '{}' has signature {type_signature} which does not support zero arguments. Use TypeSignature::Nullary for zero arguments",
434 function_name.as_ref()
435 );
436 } else {
437 return plan_err!(
438 "Function '{}' has signature {type_signature} which does not support zero arguments",
439 function_name.as_ref()
440 );
441 }
442 }
443
444 let valid_types =
445 get_valid_types(function_name.as_ref(), type_signature, current_types)?;
446 if valid_types
447 .iter()
448 .any(|data_type| data_type == current_types)
449 {
450 return Ok(current_types.to_vec());
451 }
452
453 try_coerce_types(
454 function_name.as_ref(),
455 valid_types,
456 current_types,
457 type_signature,
458 )
459}
460
461fn is_well_supported_signature(type_signature: &TypeSignature) -> bool {
462 match type_signature {
463 TypeSignature::OneOf(type_signatures) => {
464 type_signatures.iter().all(is_well_supported_signature)
465 }
466 TypeSignature::UserDefined
467 | TypeSignature::Numeric(_)
468 | TypeSignature::String(_)
469 | TypeSignature::Coercible(_)
470 | TypeSignature::Any(_)
471 | TypeSignature::Nullary
472 | TypeSignature::Comparable(_) => true,
473 TypeSignature::Variadic(_)
474 | TypeSignature::VariadicAny
475 | TypeSignature::Uniform(_, _)
476 | TypeSignature::Exact(_)
477 | TypeSignature::ArraySignature(_) => false,
478 }
479}
480
481fn try_coerce_types(
482 function_name: &str,
483 valid_types: Vec<Vec<DataType>>,
484 current_types: &[DataType],
485 type_signature: &TypeSignature,
486) -> Result<Vec<DataType>> {
487 let mut valid_types = valid_types;
488
489 if !valid_types.is_empty() && is_well_supported_signature(type_signature) {
491 if !type_signature.is_one_of() {
494 assert_eq!(valid_types.len(), 1);
495 }
496
497 let valid_types = valid_types.swap_remove(0);
498 if let Some(t) = maybe_data_types_without_coercion(&valid_types, current_types) {
499 return Ok(t);
500 }
501 } else {
502 for valid_types in valid_types {
506 if let Some(types) = maybe_data_types(&valid_types, current_types) {
507 return Ok(types);
508 }
509 }
510 }
511
512 plan_err!(
514 "Failed to coerce arguments to satisfy a call to '{function_name}' function: coercion from {} to the signature {type_signature} failed",
515 current_types.iter().join(", ")
516 )
517}
518
519fn get_valid_types_with_udf<F: UDFCoercionExt>(
520 signature: &TypeSignature,
521 current_types: &[DataType],
522 func: &F,
523) -> Result<Vec<Vec<DataType>>> {
524 let valid_types = match signature {
525 TypeSignature::UserDefined => match func.coerce_types(current_types) {
526 Ok(coerced_types) => vec![coerced_types],
527 Err(e) => {
528 return exec_err!(
529 "Function '{}' user-defined coercion failed with: {}",
530 func.name(),
531 e.strip_backtrace()
532 );
533 }
534 },
535 TypeSignature::OneOf(signatures) => {
536 let mut res = vec![];
537 let mut errors = vec![];
538 for sig in signatures {
539 match get_valid_types_with_udf(sig, current_types, func) {
540 Ok(valid_types) => {
541 res.extend(valid_types);
542 }
543 Err(e) => {
544 errors.push(e.to_string());
545 }
546 }
547 }
548
549 if res.is_empty() {
555 return plan_err!(
556 "Function '{}' failed to match any signature, errors: {}",
557 func.name(),
558 errors.join(",")
559 );
560 } else {
561 res
562 }
563 }
564 _ => get_valid_types(func.name(), signature, current_types)?,
565 };
566
567 Ok(valid_types)
568}
569
570fn get_valid_types(
572 function_name: &str,
573 signature: &TypeSignature,
574 current_types: &[DataType],
575) -> Result<Vec<Vec<DataType>>> {
576 fn array_valid_types(
577 function_name: &str,
578 current_types: &[DataType],
579 arguments: &[ArrayFunctionArgument],
580 array_coercion: Option<&ListCoercion>,
581 ) -> Result<Vec<Vec<DataType>>> {
582 fn rebuild_array_type(
583 current_type: &DataType,
584 element_type: &DataType,
585 nullable: bool,
586 large_list: bool,
587 fixed_size: Option<i32>,
588 ) -> DataType {
589 let field = match current_type {
592 DataType::List(field)
593 | DataType::LargeList(field)
594 | DataType::FixedSizeList(field, _) => Some(Arc::new(
595 field
596 .as_ref()
597 .clone()
598 .with_data_type(element_type.clone())
599 .with_nullable(nullable),
600 )),
601 _ => None,
602 };
603
604 if large_list {
605 field.map_or_else(
606 || DataType::new_large_list(element_type.clone(), nullable),
607 DataType::LargeList,
608 )
609 } else if let Some(size) = fixed_size {
610 field.map_or_else(
611 || {
612 DataType::new_fixed_size_list(
613 element_type.clone(),
614 size,
615 nullable,
616 )
617 },
618 |field| DataType::FixedSizeList(field, size),
619 )
620 } else {
621 field.map_or_else(
622 || DataType::new_list(element_type.clone(), nullable),
623 DataType::List,
624 )
625 }
626 }
627
628 if current_types.len() != arguments.len() {
629 return Ok(vec![vec![]]);
630 }
631
632 let mut large_list = false;
633 let mut fixed_size = array_coercion != Some(&ListCoercion::FixedSizedListToList);
634 let mut list_sizes = Vec::with_capacity(arguments.len());
635 let mut element_types = Vec::with_capacity(arguments.len());
636 let mut nested_item_nullability = Vec::with_capacity(arguments.len());
637 for (argument, current_type) in arguments.iter().zip(current_types.iter()) {
638 match argument {
639 ArrayFunctionArgument::Index | ArrayFunctionArgument::String => {
640 nested_item_nullability.push(None);
641 }
642 ArrayFunctionArgument::Element => {
643 element_types.push(current_type.clone());
644 nested_item_nullability.push(None);
645 }
646 ArrayFunctionArgument::Array => match current_type {
647 DataType::Null => {
648 element_types.push(DataType::Null);
649 nested_item_nullability.push(None);
650 }
651 DataType::List(field) | DataType::ListView(field) => {
652 element_types.push(field.data_type().clone());
653 nested_item_nullability.push(Some(field.is_nullable()));
654 fixed_size = false;
655 }
656 DataType::LargeList(field) | DataType::LargeListView(field) => {
657 element_types.push(field.data_type().clone());
658 nested_item_nullability.push(Some(field.is_nullable()));
659 large_list = true;
660 fixed_size = false;
661 }
662 DataType::FixedSizeList(field, size) => {
663 element_types.push(field.data_type().clone());
664 nested_item_nullability.push(Some(field.is_nullable()));
665 list_sizes.push(*size)
666 }
667 arg_type => {
668 plan_err!("{function_name} does not support type {arg_type}")?
669 }
670 },
671 }
672 }
673
674 debug_assert_eq!(nested_item_nullability.len(), arguments.len());
675
676 let Some(element_type) = type_union_resolution(&element_types) else {
677 return Ok(vec![vec![]]);
678 };
679
680 if !fixed_size {
681 list_sizes.clear()
682 }
683
684 let mut list_sizes = list_sizes.into_iter();
685 let valid_types = arguments
686 .iter()
687 .zip(current_types.iter())
688 .zip(nested_item_nullability)
689 .map(|((argument_type, current_type), is_nested_item_nullable)| {
690 match argument_type {
691 ArrayFunctionArgument::Index => DataType::Int64,
692 ArrayFunctionArgument::String => DataType::Utf8,
693 ArrayFunctionArgument::Element => element_type.clone(),
694 ArrayFunctionArgument::Array => {
697 if current_type.is_null() {
698 DataType::Null
699 } else {
700 rebuild_array_type(
701 current_type,
702 &element_type,
703 is_nested_item_nullable.unwrap_or(true),
704 large_list,
705 list_sizes.next(),
706 )
707 }
708 }
709 }
710 });
711
712 Ok(vec![valid_types.collect()])
713 }
714
715 fn recursive_array(array_type: &DataType) -> Option<DataType> {
716 match array_type {
717 DataType::List(_)
718 | DataType::LargeList(_)
719 | DataType::ListView(_)
720 | DataType::LargeListView(_)
721 | DataType::FixedSizeList(_, _) => {
722 let array_type = coerced_fixed_size_list_to_list(array_type);
723 Some(array_type)
724 }
725 _ => None,
726 }
727 }
728
729 fn function_length_check(
730 function_name: &str,
731 length: usize,
732 expected_length: usize,
733 ) -> Result<()> {
734 if length != expected_length {
735 return plan_err!(
736 "Function '{function_name}' expects {expected_length} arguments but received {length}"
737 );
738 }
739 Ok(())
740 }
741
742 let valid_types = match signature {
743 TypeSignature::Variadic(valid_types) => valid_types
744 .iter()
745 .map(|valid_type| vec![valid_type.clone(); current_types.len()])
746 .collect(),
747 TypeSignature::String(number) => {
748 function_length_check(function_name, current_types.len(), *number)?;
749
750 let mut new_types = Vec::with_capacity(current_types.len());
751 for data_type in current_types.iter() {
752 let logical_data_type: NativeType = data_type.into();
753 if logical_data_type == NativeType::String {
754 new_types.push(data_type.to_owned());
755 } else if logical_data_type == NativeType::Null {
756 new_types.push(DataType::Utf8);
758 } else {
759 return plan_err!(
760 "Function '{function_name}' expects String but received {logical_data_type}"
761 );
762 }
763 }
764
765 fn find_common_type(
767 function_name: &str,
768 lhs_type: &DataType,
769 rhs_type: &DataType,
770 ) -> Result<DataType> {
771 match (lhs_type, rhs_type) {
772 (DataType::Dictionary(_, lhs), DataType::Dictionary(_, rhs)) => {
773 find_common_type(function_name, lhs, rhs)
774 }
775 (DataType::Dictionary(_, v), other)
776 | (other, DataType::Dictionary(_, v)) => {
777 find_common_type(function_name, v, other)
778 }
779 _ => {
780 if let Some(coerced_type) = string_coercion(lhs_type, rhs_type) {
781 Ok(coerced_type)
782 } else {
783 plan_err!(
784 "Function '{function_name}' could not coerce {lhs_type} and {rhs_type} to a common string type"
785 )
786 }
787 }
788 }
789 }
790
791 let mut coerced_type = new_types.first().unwrap().to_owned();
793 for t in new_types.iter().skip(1) {
794 coerced_type = find_common_type(function_name, &coerced_type, t)?;
795 }
796
797 fn base_type_or_default_type(data_type: &DataType) -> DataType {
798 if let DataType::Dictionary(_, v) = data_type {
799 base_type_or_default_type(v)
800 } else {
801 data_type.to_owned()
802 }
803 }
804
805 vec![vec![base_type_or_default_type(&coerced_type); *number]]
806 }
807 TypeSignature::Numeric(number) => {
808 function_length_check(function_name, current_types.len(), *number)?;
809
810 let non_nulls = current_types
811 .iter()
812 .filter(|&t| NativeType::from(t) != NativeType::Null)
813 .collect::<Vec<_>>();
814 let mut valid_type = non_nulls
815 .first()
816 .copied()
817 .cloned()
818 .unwrap_or(DataType::Float64);
822 for &t in non_nulls.iter().skip(1) {
824 let logical_data_type: NativeType = t.into();
825
826 if !logical_data_type.is_numeric() {
827 return plan_err!(
828 "Function '{function_name}' expects Numeric but received {logical_data_type}"
829 );
830 }
831
832 if let Some(coerced_type) = binary_numeric_coercion(&valid_type, t) {
833 valid_type = coerced_type;
834 } else {
835 return plan_err!(
836 "For function '{function_name}' {valid_type} and {t} are not coercible to a common numeric type"
837 );
838 }
839 }
840
841 let logical_data_type: NativeType = valid_type.clone().into();
842 if !logical_data_type.is_numeric() {
843 return plan_err!(
844 "Function '{function_name}' expects Numeric but received {logical_data_type}"
845 );
846 }
847
848 vec![vec![valid_type; *number]]
849 }
850 TypeSignature::Comparable(num) => {
851 function_length_check(function_name, current_types.len(), *num)?;
852 let mut target_type = current_types[0].to_owned();
853 for data_type in current_types.iter().skip(1) {
854 if let Some(dt) = comparison_coercion(&target_type, data_type) {
855 target_type = dt;
856 } else {
857 return plan_err!(
858 "For function '{function_name}' {target_type} and {data_type} is not comparable"
859 );
860 }
861 }
862 if target_type.is_null() {
864 vec![vec![DataType::Utf8View; *num]]
865 } else {
866 vec![vec![target_type; *num]]
867 }
868 }
869 TypeSignature::Coercible(param_types) => {
870 function_length_check(function_name, current_types.len(), param_types.len())?;
871
872 fn coercion_value_type<'a>(
873 current_type: &'a DataType,
874 desired_type: &TypeSignatureClass,
875 ) -> &'a DataType {
876 if matches!(desired_type, TypeSignatureClass::Any) {
877 return current_type;
878 }
879
880 match current_type {
881 DataType::Dictionary(_, value_type) => {
882 coercion_value_type(value_type, desired_type)
883 }
884 _ => current_type,
885 }
886 }
887
888 fn preserve_encoding(
889 current_type: &DataType,
890 casted_type: DataType,
891 desired_type: &TypeSignatureClass,
892 encoding_preservation: EncodingPreservation,
893 ) -> DataType {
894 if matches!(desired_type, TypeSignatureClass::Any) {
895 return casted_type;
896 }
897
898 match current_type {
899 DataType::Dictionary(key_type, value_type) => {
900 let casted_type = preserve_encoding(
901 value_type,
902 casted_type,
903 desired_type,
904 encoding_preservation,
905 );
906 if encoding_preservation.preserve_dictionary() {
907 DataType::Dictionary(key_type.clone(), Box::new(casted_type))
908 } else {
909 casted_type
910 }
911 }
912 _ => casted_type,
913 }
914 }
915
916 let mut new_types = Vec::with_capacity(current_types.len());
917 for (current_type, param) in current_types.iter().zip(param_types.iter()) {
918 let current_native_type: NativeType = current_type.into();
919 let encoding_preservation = param.encoding_preservation();
920 let coercion_value_type =
921 coercion_value_type(current_type, param.desired_type());
922
923 if param
924 .desired_type()
925 .matches_native_type(¤t_native_type)
926 {
927 let casted_type = param
928 .desired_type()
929 .default_casted_type(¤t_native_type, coercion_value_type)?;
930
931 new_types.push(preserve_encoding(
932 current_type,
933 casted_type,
934 param.desired_type(),
935 encoding_preservation,
936 ));
937 } else if param
938 .allowed_source_types()
939 .iter()
940 .any(|t| t.matches_native_type(¤t_native_type))
941 {
942 let default_casted_type = param.default_casted_type().unwrap();
944 let casted_type =
945 default_casted_type.default_cast_for(coercion_value_type)?;
946 new_types.push(preserve_encoding(
947 current_type,
948 casted_type,
949 param.desired_type(),
950 encoding_preservation,
951 ));
952 } else {
953 let hint = if matches!(current_native_type, NativeType::Binary) {
954 "\n\nHint: Binary types are not automatically coerced to String. Use CAST(column AS VARCHAR) to convert Binary data to String."
955 } else {
956 ""
957 };
958 return plan_err!(
959 "Function '{function_name}' requires {}, but received {} (DataType: {}).{hint}",
960 param.desired_type(),
961 current_native_type,
962 current_type
963 );
964 }
965 }
966
967 vec![new_types]
968 }
969 TypeSignature::Uniform(number, valid_types) => {
970 if *number == 0 {
971 return plan_err!(
972 "The function '{function_name}' expected at least one argument"
973 );
974 }
975
976 valid_types
977 .iter()
978 .map(|valid_type| vec![valid_type.clone(); *number])
979 .collect()
980 }
981 TypeSignature::UserDefined => {
982 return internal_err!(
983 "Function '{function_name}' user-defined signature should be handled by function-specific coerce_types"
984 );
985 }
986 TypeSignature::VariadicAny => {
987 if current_types.is_empty() {
988 return plan_err!(
989 "Function '{function_name}' expected at least one argument but received 0"
990 );
991 }
992 vec![current_types.to_vec()]
993 }
994 TypeSignature::Exact(valid_types) => vec![valid_types.clone()],
995 TypeSignature::ArraySignature(function_signature) => match function_signature {
996 ArrayFunctionSignature::Array {
997 arguments,
998 array_coercion,
999 } => array_valid_types(
1000 function_name,
1001 current_types,
1002 arguments,
1003 array_coercion.as_ref(),
1004 )?,
1005 ArrayFunctionSignature::RecursiveArray => {
1006 if current_types.len() != 1 {
1007 return Ok(vec![vec![]]);
1008 }
1009 recursive_array(¤t_types[0])
1010 .map_or_else(|| vec![vec![]], |array_type| vec![vec![array_type]])
1011 }
1012 ArrayFunctionSignature::MapArray => {
1013 if current_types.len() != 1 {
1014 return Ok(vec![vec![]]);
1015 }
1016
1017 match ¤t_types[0] {
1018 DataType::Map(_, _) => vec![vec![current_types[0].clone()]],
1019 _ => vec![vec![]],
1020 }
1021 }
1022 },
1023 TypeSignature::Nullary => {
1024 if !current_types.is_empty() {
1025 return plan_err!(
1026 "The function '{function_name}' expected zero argument but received {}",
1027 current_types.len()
1028 );
1029 }
1030 vec![vec![]]
1031 }
1032 TypeSignature::Any(number) => {
1033 if current_types.is_empty() {
1034 return plan_err!(
1035 "The function '{function_name}' expected at least one argument but received 0"
1036 );
1037 }
1038
1039 if current_types.len() != *number {
1040 return plan_err!(
1041 "The function '{function_name}' expected {number} arguments but received {}",
1042 current_types.len()
1043 );
1044 }
1045 vec![current_types.to_vec()]
1046 }
1047 TypeSignature::OneOf(types) => types
1048 .iter()
1049 .filter_map(|t| get_valid_types(function_name, t, current_types).ok())
1050 .flatten()
1051 .collect::<Vec<_>>(),
1052 };
1053
1054 Ok(valid_types)
1055}
1056
1057fn maybe_data_types(
1064 valid_types: &[DataType],
1065 current_types: &[DataType],
1066) -> Option<Vec<DataType>> {
1067 if valid_types.len() != current_types.len() {
1068 return None;
1069 }
1070
1071 let mut new_type = Vec::with_capacity(valid_types.len());
1072 for (i, valid_type) in valid_types.iter().enumerate() {
1073 let current_type = ¤t_types[i];
1074
1075 if current_type == valid_type {
1076 new_type.push(current_type.clone())
1077 } else {
1078 let coerced_type = coerced_from(valid_type, current_type)?;
1082 new_type.push(coerced_type)
1083 }
1084 }
1085 Some(new_type)
1086}
1087
1088fn maybe_data_types_without_coercion(
1092 valid_types: &[DataType],
1093 current_types: &[DataType],
1094) -> Option<Vec<DataType>> {
1095 if valid_types.len() != current_types.len() {
1096 return None;
1097 }
1098
1099 let mut new_type = Vec::with_capacity(valid_types.len());
1100 for (i, valid_type) in valid_types.iter().enumerate() {
1101 let current_type = ¤t_types[i];
1102
1103 if current_type == valid_type {
1104 new_type.push(current_type.clone())
1105 } else if can_cast_types(current_type, valid_type) {
1106 new_type.push(valid_type.clone())
1108 } else {
1109 return None;
1110 }
1111 }
1112 Some(new_type)
1113}
1114
1115#[deprecated(since = "53.0.0", note = "Unused internal function")]
1120pub fn can_coerce_from(type_into: &DataType, type_from: &DataType) -> bool {
1121 if type_into == type_from {
1122 return true;
1123 }
1124 if let Some(coerced) = coerced_from(type_into, type_from) {
1125 return coerced == *type_into;
1126 }
1127 false
1128}
1129
1130fn coerced_from<'a>(
1137 type_into: &'a DataType,
1138 type_from: &'a DataType,
1139) -> Option<DataType> {
1140 use self::DataType::*;
1141
1142 match (type_into, type_from) {
1144 (_, Dictionary(_, value_type))
1146 if coerced_from(type_into, value_type).is_some() =>
1147 {
1148 Some(type_into.clone())
1149 }
1150 (Dictionary(_, value_type), _)
1151 if coerced_from(value_type, type_from).is_some() =>
1152 {
1153 Some(type_into.clone())
1154 }
1155 (_, RunEndEncoded(_, value_type))
1156 if coerced_from(type_into, value_type.data_type()).is_some() =>
1157 {
1158 Some(type_into.clone())
1159 }
1160 (RunEndEncoded(_, value_type), _)
1161 if coerced_from(value_type.data_type(), type_from).is_some() =>
1162 {
1163 Some(type_into.clone())
1164 }
1165 (Int8, Null | Int8) => Some(type_into.clone()),
1167 (Int16, Null | Int8 | Int16 | UInt8) => Some(type_into.clone()),
1168 (Int32, Null | Int8 | Int16 | Int32 | UInt8 | UInt16) => Some(type_into.clone()),
1169 (Int64, Null | Int8 | Int16 | Int32 | Int64 | UInt8 | UInt16 | UInt32) => {
1170 Some(type_into.clone())
1171 }
1172 (UInt8, Null | UInt8) => Some(type_into.clone()),
1173 (UInt16, Null | UInt8 | UInt16) => Some(type_into.clone()),
1174 (UInt32, Null | UInt8 | UInt16 | UInt32) => Some(type_into.clone()),
1175 (UInt64, Null | UInt8 | UInt16 | UInt32 | UInt64) => Some(type_into.clone()),
1176 (Float16, Null | Int8 | Int16 | UInt8 | UInt16 | Float16) => {
1177 Some(type_into.clone())
1178 }
1179 (
1180 Float32,
1181 Null | Int8 | Int16 | Int32 | Int64 | UInt8 | UInt16 | UInt32 | UInt64
1182 | Float16 | Float32,
1183 ) => Some(type_into.clone()),
1184 (
1185 Float64,
1186 Null
1187 | Int8
1188 | Int16
1189 | Int32
1190 | Int64
1191 | UInt8
1192 | UInt16
1193 | UInt32
1194 | UInt64
1195 | Float16
1196 | Float32
1197 | Float64
1198 | Decimal32(_, _)
1199 | Decimal64(_, _)
1200 | Decimal128(_, _)
1201 | Decimal256(_, _),
1202 ) => Some(type_into.clone()),
1203 (
1204 Timestamp(TimeUnit::Nanosecond, None),
1205 Null | Timestamp(_, None) | Date32 | Date64 | Utf8 | LargeUtf8 | Utf8View,
1206 ) => Some(type_into.clone()),
1207 (Interval(_), Null | Utf8 | LargeUtf8 | Utf8View) => Some(type_into.clone()),
1208 (Utf8 | LargeUtf8 | Utf8View, _) => Some(type_into.clone()),
1210 (BinaryView, Binary | LargeBinary | Null) => Some(type_into.clone()),
1212 (Null, _) if can_cast_types(type_from, type_into) => Some(type_into.clone()),
1213
1214 (List(_), FixedSizeList(_, _)) => Some(type_into.clone()),
1215
1216 (List(_) | LargeList(_) | ListView(_) | LargeListView(_), _)
1219 if base_type(type_from).is_null()
1220 || list_ndims(type_from) == list_ndims(type_into) =>
1221 {
1222 Some(type_into.clone())
1223 }
1224 (
1226 FixedSizeList(f_into, FIXED_SIZE_LIST_WILDCARD),
1227 FixedSizeList(f_from, size_from),
1228 ) => match coerced_from(f_into.data_type(), f_from.data_type()) {
1229 Some(data_type) if &data_type != f_into.data_type() => {
1230 let new_field =
1231 Arc::new(f_into.as_ref().clone().with_data_type(data_type));
1232 Some(FixedSizeList(new_field, *size_from))
1233 }
1234 Some(_) => Some(FixedSizeList(Arc::clone(f_into), *size_from)),
1235 _ => None,
1236 },
1237 (Timestamp(unit, Some(tz)), _) if tz.as_ref() == TIMEZONE_WILDCARD => {
1238 match type_from {
1239 Timestamp(_, Some(from_tz)) => {
1240 Some(Timestamp(*unit, Some(Arc::clone(from_tz))))
1241 }
1242 Null | Date32 | Utf8 | LargeUtf8 | Timestamp(_, None) => {
1243 Some(Timestamp(*unit, Some("+00".into())))
1245 }
1246 _ => None,
1247 }
1248 }
1249 (Timestamp(_, Some(_)), Null | Timestamp(_, _) | Date32 | Utf8 | LargeUtf8) => {
1250 Some(type_into.clone())
1251 }
1252 (_, Null) if can_cast_types(type_from, type_into) => Some(type_into.clone()),
1259 _ => None,
1260 }
1261}
1262
1263#[cfg(test)]
1264mod tests {
1265 use crate::{
1266 HigherOrderFunctionArgs, HigherOrderReturnFieldArgs, HigherOrderSignature,
1267 HigherOrderUDFImpl, Volatility,
1268 };
1269
1270 use super::*;
1271 use arrow::datatypes::IntervalUnit;
1272 use datafusion_common::{
1273 assert_contains,
1274 types::{logical_binary, logical_int64, logical_string},
1275 };
1276 use datafusion_expr_common::{
1277 columnar_value::ColumnarValue,
1278 signature::{Coercion, EncodingPreservation, TypeSignatureClass},
1279 };
1280
1281 #[test]
1282 fn test_string_conversion() {
1283 let cases = vec![
1284 (DataType::Utf8View, DataType::Utf8),
1285 (DataType::Utf8View, DataType::LargeUtf8),
1286 (DataType::Utf8View, DataType::Null),
1287 ];
1288
1289 for case in cases {
1290 assert_eq!(coerced_from(&case.0, &case.1), Some(case.0));
1291 }
1292 }
1293
1294 #[test]
1295 fn test_binary_conversion() {
1296 let cases = vec![
1297 (DataType::BinaryView, DataType::Binary),
1298 (DataType::BinaryView, DataType::LargeBinary),
1299 (DataType::BinaryView, DataType::Null),
1300 ];
1301
1302 for case in cases {
1303 assert_eq!(coerced_from(&case.0, &case.1), Some(case.0));
1304 }
1305 }
1306
1307 #[test]
1308 fn test_coerced_from_null() {
1309 assert_eq!(
1311 coerced_from(
1312 &DataType::Interval(IntervalUnit::MonthDayNano),
1313 &DataType::Null
1314 ),
1315 Some(DataType::Interval(IntervalUnit::MonthDayNano))
1316 );
1317
1318 assert_eq!(
1320 coerced_from(&DataType::Date32, &DataType::Null),
1321 Some(DataType::Date32)
1322 );
1323
1324 assert_eq!(
1326 coerced_from(
1327 &DataType::Timestamp(TimeUnit::Microsecond, Some("+00".into())),
1328 &DataType::Null
1329 ),
1330 Some(DataType::Timestamp(
1331 TimeUnit::Microsecond,
1332 Some("+00".into())
1333 ))
1334 );
1335 }
1336
1337 #[test]
1338 fn test_maybe_data_types() {
1339 let cases = vec![
1341 (
1343 vec![DataType::UInt8, DataType::UInt16],
1344 vec![DataType::UInt8, DataType::UInt16],
1345 Some(vec![DataType::UInt8, DataType::UInt16]),
1346 ),
1347 (
1349 vec![DataType::UInt16, DataType::UInt16],
1350 vec![DataType::UInt8, DataType::UInt16],
1351 Some(vec![DataType::UInt16, DataType::UInt16]),
1352 ),
1353 (vec![], vec![], Some(vec![])),
1355 (
1357 vec![DataType::Boolean, DataType::UInt16],
1358 vec![DataType::UInt8, DataType::UInt16],
1359 None,
1360 ),
1361 (
1363 vec![DataType::Boolean, DataType::UInt32],
1364 vec![DataType::Boolean, DataType::UInt16],
1365 Some(vec![DataType::Boolean, DataType::UInt32]),
1366 ),
1367 (
1369 vec![
1370 DataType::Timestamp(TimeUnit::Nanosecond, None),
1371 DataType::Timestamp(TimeUnit::Nanosecond, Some("+TZ".into())),
1372 DataType::Timestamp(TimeUnit::Nanosecond, Some("+01".into())),
1373 ],
1374 vec![DataType::Utf8, DataType::Utf8, DataType::Utf8],
1375 Some(vec![
1376 DataType::Timestamp(TimeUnit::Nanosecond, None),
1377 DataType::Timestamp(TimeUnit::Nanosecond, Some("+00".into())),
1378 DataType::Timestamp(TimeUnit::Nanosecond, Some("+01".into())),
1379 ]),
1380 ),
1381 ];
1382
1383 for case in cases {
1384 assert_eq!(maybe_data_types(&case.0, &case.1), case.2)
1385 }
1386 }
1387
1388 #[test]
1389 fn test_get_valid_types_numeric() -> Result<()> {
1390 let get_valid_types_flatten =
1391 |function_name: &str,
1392 signature: &TypeSignature,
1393 current_types: &[DataType]| {
1394 get_valid_types(function_name, signature, current_types)
1395 .unwrap()
1396 .into_iter()
1397 .flatten()
1398 .collect::<Vec<_>>()
1399 };
1400
1401 let got = get_valid_types_flatten(
1403 "test",
1404 &TypeSignature::Numeric(1),
1405 &[DataType::Int32],
1406 );
1407 assert_eq!(got, [DataType::Int32]);
1408
1409 let got = get_valid_types_flatten(
1411 "test",
1412 &TypeSignature::Numeric(2),
1413 &[DataType::Int32, DataType::Int64],
1414 );
1415 assert_eq!(got, [DataType::Int64, DataType::Int64]);
1416
1417 let got = get_valid_types_flatten(
1419 "test",
1420 &TypeSignature::Numeric(3),
1421 &[DataType::Int32, DataType::Int64, DataType::Float64],
1422 );
1423 assert_eq!(
1424 got,
1425 [DataType::Float64, DataType::Float64, DataType::Float64]
1426 );
1427
1428 let got = get_valid_types(
1430 "test",
1431 &TypeSignature::Numeric(2),
1432 &[DataType::Int32, DataType::Utf8],
1433 )
1434 .unwrap_err();
1435 assert_contains!(
1436 got.to_string(),
1437 "Function 'test' expects Numeric but received String"
1438 );
1439
1440 let got = get_valid_types_flatten(
1442 "test",
1443 &TypeSignature::Numeric(1),
1444 &[DataType::Null],
1445 );
1446 assert_eq!(got, [DataType::Float64]);
1447
1448 let got = get_valid_types_flatten(
1449 "test",
1450 &TypeSignature::Numeric(2),
1451 &[DataType::Null, DataType::Null],
1452 );
1453 assert_eq!(got, [DataType::Float64, DataType::Float64]);
1454
1455 let got = get_valid_types(
1457 "test",
1458 &TypeSignature::Numeric(1),
1459 &[DataType::Timestamp(TimeUnit::Second, None)],
1460 )
1461 .unwrap_err();
1462 assert_contains!(
1463 got.to_string(),
1464 "Function 'test' expects Numeric but received Timestamp(s)"
1465 );
1466
1467 let got = get_valid_types_flatten(
1469 "test",
1470 &TypeSignature::Numeric(2),
1471 &[DataType::Null, DataType::Int32],
1472 );
1473 assert_eq!(got, [DataType::Int32, DataType::Int32]);
1474
1475 let got = get_valid_types_flatten(
1476 "test",
1477 &TypeSignature::Numeric(2),
1478 &[DataType::Int32, DataType::Null],
1479 );
1480 assert_eq!(got, [DataType::Int32, DataType::Int32]);
1481
1482 Ok(())
1483 }
1484
1485 #[test]
1486 fn test_get_valid_types_one_of() -> Result<()> {
1487 let signature =
1488 TypeSignature::OneOf(vec![TypeSignature::Any(1), TypeSignature::Any(2)]);
1489
1490 let invalid_types = get_valid_types(
1491 "test",
1492 &signature,
1493 &[DataType::Int32, DataType::Int32, DataType::Int32],
1494 )?;
1495 assert_eq!(invalid_types.len(), 0);
1496
1497 let args = vec![DataType::Int32, DataType::Int32];
1498 let valid_types = get_valid_types("test", &signature, &args)?;
1499 assert_eq!(valid_types.len(), 1);
1500 assert_eq!(valid_types[0], args);
1501
1502 let args = vec![DataType::Int32];
1503 let valid_types = get_valid_types("test", &signature, &args)?;
1504 assert_eq!(valid_types.len(), 1);
1505 assert_eq!(valid_types[0], args);
1506
1507 Ok(())
1508 }
1509
1510 #[test]
1511 fn test_get_valid_types_length_check() -> Result<()> {
1512 let signature = TypeSignature::Numeric(1);
1513
1514 let err = get_valid_types("test", &signature, &[]).unwrap_err();
1515 assert_contains!(
1516 err.to_string(),
1517 "Function 'test' expects 1 arguments but received 0"
1518 );
1519
1520 let err = get_valid_types(
1521 "test",
1522 &signature,
1523 &[DataType::Int32, DataType::Int32, DataType::Int32],
1524 )
1525 .unwrap_err();
1526 assert_contains!(
1527 err.to_string(),
1528 "Function 'test' expects 1 arguments but received 3"
1529 );
1530
1531 Ok(())
1532 }
1533
1534 struct MockUdf(Signature);
1535
1536 impl UDFCoercionExt for MockUdf {
1537 fn name(&self) -> &str {
1538 "test"
1539 }
1540 fn signature(&self) -> &Signature {
1541 &self.0
1542 }
1543 fn coerce_types(&self, _arg_types: &[DataType]) -> Result<Vec<DataType>> {
1544 unimplemented!()
1545 }
1546 }
1547
1548 #[test]
1549 fn test_fixed_list_wildcard_coerce() -> Result<()> {
1550 let inner = Arc::new(Field::new_list_field(DataType::Int32, false));
1551 let current_fields = vec![Arc::new(Field::new(
1553 "t",
1554 DataType::FixedSizeList(Arc::clone(&inner), 2),
1555 true,
1556 ))];
1557
1558 let signature = Signature::exact(
1559 vec![DataType::FixedSizeList(
1560 Arc::clone(&inner),
1561 FIXED_SIZE_LIST_WILDCARD,
1562 )],
1563 Volatility::Stable,
1564 );
1565
1566 let coerced_fields = fields_with_udf(¤t_fields, &MockUdf(signature))?;
1567 assert_eq!(coerced_fields, current_fields);
1568
1569 let signature = Signature::exact(
1571 vec![DataType::FixedSizeList(Arc::clone(&inner), 3)],
1572 Volatility::Stable,
1573 );
1574 let coerced_fields = fields_with_udf(¤t_fields, &MockUdf(signature));
1575 assert!(coerced_fields.is_err());
1576
1577 let signature = Signature::exact(
1579 vec![DataType::FixedSizeList(Arc::clone(&inner), 2)],
1580 Volatility::Stable,
1581 );
1582 let coerced_fields =
1583 fields_with_udf(¤t_fields, &MockUdf(signature)).unwrap();
1584 assert_eq!(coerced_fields, current_fields);
1585
1586 Ok(())
1587 }
1588
1589 #[test]
1590 fn test_nested_wildcard_fixed_size_lists() -> Result<()> {
1591 let type_into = DataType::FixedSizeList(
1592 Arc::new(Field::new_list_field(
1593 DataType::FixedSizeList(
1594 Arc::new(Field::new_list_field(DataType::Int32, false)),
1595 FIXED_SIZE_LIST_WILDCARD,
1596 ),
1597 false,
1598 )),
1599 FIXED_SIZE_LIST_WILDCARD,
1600 );
1601
1602 let type_from = DataType::FixedSizeList(
1603 Arc::new(Field::new_list_field(
1604 DataType::FixedSizeList(
1605 Arc::new(Field::new_list_field(DataType::Int8, false)),
1606 4,
1607 ),
1608 false,
1609 )),
1610 3,
1611 );
1612
1613 assert_eq!(
1614 coerced_from(&type_into, &type_from),
1615 Some(DataType::FixedSizeList(
1616 Arc::new(Field::new_list_field(
1617 DataType::FixedSizeList(
1618 Arc::new(Field::new_list_field(DataType::Int32, false)),
1619 4,
1620 ),
1621 false,
1622 )),
1623 3,
1624 ))
1625 );
1626
1627 Ok(())
1628 }
1629
1630 #[test]
1631 fn test_coerced_from_dictionary() {
1632 let type_into =
1633 DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::UInt32));
1634 let type_from = DataType::Int64;
1635 assert_eq!(coerced_from(&type_into, &type_from), None);
1636
1637 let type_from =
1638 DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::UInt32));
1639 let type_into = DataType::Int64;
1640 assert_eq!(
1641 coerced_from(&type_into, &type_from),
1642 Some(type_into.clone())
1643 );
1644 }
1645
1646 #[test]
1647 fn test_coerced_from_run_end_encoded() {
1648 let run_end_encoded_of = |value_type: DataType| {
1649 DataType::RunEndEncoded(
1650 Field::new("run_ends", DataType::Int32, false).into(),
1651 Field::new("values", value_type, true).into(),
1652 )
1653 };
1654
1655 let type_into = run_end_encoded_of(DataType::UInt32);
1656 let type_from = DataType::Int64;
1657 assert_eq!(coerced_from(&type_into, &type_from), None);
1658
1659 let type_from = run_end_encoded_of(DataType::UInt32);
1660 let type_into = DataType::Int64;
1661 assert_eq!(
1662 coerced_from(&type_into, &type_from),
1663 Some(type_into.clone())
1664 );
1665
1666 let type_from =
1671 run_end_encoded_of(DataType::Timestamp(TimeUnit::Nanosecond, None));
1672 let type_into = DataType::Timestamp(TimeUnit::Nanosecond, None);
1673 assert_eq!(
1674 coerced_from(&type_into, &type_from),
1675 Some(type_into.clone())
1676 );
1677
1678 let type_into = run_end_encoded_of(DataType::Int64);
1683 let type_from = DataType::Int32;
1684 assert_eq!(
1685 coerced_from(&type_into, &type_from),
1686 Some(type_into.clone())
1687 );
1688 }
1689
1690 #[test]
1691 fn test_get_valid_types_array_and_array() -> Result<()> {
1692 let function = "array_and_array";
1693 let signature = Signature::arrays(
1694 2,
1695 Some(ListCoercion::FixedSizedListToList),
1696 Volatility::Immutable,
1697 );
1698
1699 let data_types = vec![
1700 DataType::new_list(DataType::Int32, true),
1701 DataType::new_large_list(DataType::Float64, true),
1702 ];
1703 assert_eq!(
1704 get_valid_types(function, &signature.type_signature, &data_types)?,
1705 vec![vec![
1706 DataType::new_large_list(DataType::Float64, true),
1707 DataType::new_large_list(DataType::Float64, true),
1708 ]]
1709 );
1710
1711 let data_types = vec![
1712 DataType::new_fixed_size_list(DataType::Int64, 3, true),
1713 DataType::new_fixed_size_list(DataType::Int32, 5, true),
1714 ];
1715 assert_eq!(
1716 get_valid_types(function, &signature.type_signature, &data_types)?,
1717 vec![vec![
1718 DataType::new_list(DataType::Int64, true),
1719 DataType::new_list(DataType::Int64, true),
1720 ]]
1721 );
1722
1723 let data_types = vec![
1724 DataType::new_fixed_size_list(DataType::Null, 3, true),
1725 DataType::new_large_list(DataType::Utf8, true),
1726 ];
1727 assert_eq!(
1728 get_valid_types(function, &signature.type_signature, &data_types)?,
1729 vec![vec![
1730 DataType::new_large_list(DataType::Utf8, true),
1731 DataType::new_large_list(DataType::Utf8, true),
1732 ]]
1733 );
1734
1735 let data_types = vec![
1736 DataType::ListView(Field::new_list_field(DataType::Int32, true).into()),
1737 DataType::new_list(DataType::Int32, true),
1738 ];
1739 assert_eq!(
1740 get_valid_types(function, &signature.type_signature, &data_types)?,
1741 vec![vec![
1742 DataType::new_list(DataType::Int32, true),
1743 DataType::new_list(DataType::Int32, true),
1744 ]]
1745 );
1746
1747 let data_types = vec![
1748 DataType::LargeListView(Field::new_list_field(DataType::Int32, true).into()),
1749 DataType::new_list(DataType::Int32, true),
1750 ];
1751 assert_eq!(
1752 get_valid_types(function, &signature.type_signature, &data_types)?,
1753 vec![vec![
1754 DataType::new_large_list(DataType::Int32, true),
1755 DataType::new_large_list(DataType::Int32, true),
1756 ]]
1757 );
1758
1759 let data_types = vec![
1760 DataType::ListView(Field::new_list_field(DataType::Int32, true).into()),
1761 DataType::ListView(Field::new_list_field(DataType::Int32, true).into()),
1762 ];
1763 assert_eq!(
1764 get_valid_types(function, &signature.type_signature, &data_types)?,
1765 vec![vec![
1766 DataType::new_list(DataType::Int32, true),
1767 DataType::new_list(DataType::Int32, true),
1768 ]]
1769 );
1770
1771 let data_types = vec![
1772 DataType::LargeListView(Field::new_list_field(DataType::Int32, true).into()),
1773 DataType::LargeListView(Field::new_list_field(DataType::Int32, true).into()),
1774 ];
1775 assert_eq!(
1776 get_valid_types(function, &signature.type_signature, &data_types)?,
1777 vec![vec![
1778 DataType::new_large_list(DataType::Int32, true),
1779 DataType::new_large_list(DataType::Int32, true),
1780 ]]
1781 );
1782
1783 Ok(())
1784 }
1785
1786 #[test]
1787 fn test_get_valid_types_array_and_element() -> Result<()> {
1788 let function = "array_and_element";
1789 let signature = Signature::array_and_element(Volatility::Immutable);
1790
1791 let data_types =
1792 vec![DataType::new_list(DataType::Int32, true), DataType::Float64];
1793 assert_eq!(
1794 get_valid_types(function, &signature.type_signature, &data_types)?,
1795 vec![vec![
1796 DataType::new_list(DataType::Float64, true),
1797 DataType::Float64,
1798 ]]
1799 );
1800
1801 let data_types = vec![
1802 DataType::new_large_list(DataType::Int32, true),
1803 DataType::Null,
1804 ];
1805 assert_eq!(
1806 get_valid_types(function, &signature.type_signature, &data_types)?,
1807 vec![vec![
1808 DataType::new_large_list(DataType::Int32, true),
1809 DataType::Int32,
1810 ]]
1811 );
1812
1813 let data_types = vec![
1814 DataType::new_fixed_size_list(DataType::Null, 3, true),
1815 DataType::Utf8,
1816 ];
1817 assert_eq!(
1818 get_valid_types(function, &signature.type_signature, &data_types)?,
1819 vec![vec![
1820 DataType::new_list(DataType::Utf8, true),
1821 DataType::Utf8,
1822 ]]
1823 );
1824
1825 Ok(())
1826 }
1827
1828 #[test]
1829 fn test_get_valid_types_array_and_index_preserves_list_field_name() -> Result<()> {
1830 let struct_fields = vec![
1831 Field::new("id", DataType::Utf8, true),
1832 Field::new("prim", DataType::Boolean, true),
1833 ];
1834 let current_type = DataType::List(Arc::new(Field::new(
1835 "element",
1836 DataType::Struct(struct_fields.into()),
1837 true,
1838 )));
1839 let signature = Signature::array_and_index(Volatility::Immutable);
1840
1841 assert_eq!(
1842 get_valid_types(
1843 "array_element",
1844 &signature.type_signature,
1845 &[current_type.clone(), DataType::Int64],
1846 )?,
1847 vec![vec![current_type, DataType::Int64]]
1848 );
1849
1850 Ok(())
1851 }
1852
1853 #[test]
1854 fn test_get_valid_types_element_and_array() -> Result<()> {
1855 let function = "element_and_array";
1856 let signature = Signature::element_and_array(Volatility::Immutable);
1857
1858 let data_types = vec![
1859 DataType::new_large_list(DataType::Null, false),
1860 DataType::new_list(DataType::new_list(DataType::Int64, true), true),
1861 ];
1862 assert_eq!(
1863 get_valid_types(function, &signature.type_signature, &data_types)?,
1864 vec![vec![
1865 DataType::new_large_list(DataType::Int64, true),
1866 DataType::new_list(DataType::new_large_list(DataType::Int64, true), true),
1867 ]]
1868 );
1869
1870 Ok(())
1871 }
1872
1873 #[test]
1874 fn test_coercible_nulls() -> Result<()> {
1875 fn null_input(coercion: Coercion) -> Result<Vec<DataType>> {
1876 fields_with_udf(
1877 &[Field::new("field", DataType::Null, true).into()],
1878 &MockUdf(Signature::coercible(vec![coercion], Volatility::Immutable)),
1879 )
1880 .map(|v| v.into_iter().map(|f| f.data_type().clone()).collect())
1881 }
1882
1883 let output = null_input(Coercion::new_exact(TypeSignatureClass::Native(
1885 logical_int64(),
1886 )))?;
1887 assert_eq!(vec![DataType::Int64], output);
1888
1889 let output = null_input(Coercion::new_implicit(
1890 TypeSignatureClass::Native(logical_int64()),
1891 vec![],
1892 NativeType::Int64,
1893 ))?;
1894 assert_eq!(vec![DataType::Int64], output);
1895
1896 let output = null_input(Coercion::new_exact(TypeSignatureClass::Integer))?;
1898 assert_eq!(vec![DataType::Null], output);
1899
1900 let output = null_input(Coercion::new_implicit(
1901 TypeSignatureClass::Integer,
1902 vec![],
1903 NativeType::Int64,
1904 ))?;
1905 assert_eq!(vec![DataType::Null], output);
1906
1907 Ok(())
1908 }
1909
1910 #[test]
1911 fn test_coercible_dictionary() -> Result<()> {
1912 let dictionary =
1913 DataType::Dictionary(Box::new(DataType::Int8), Box::new(DataType::Int64));
1914 fn dictionary_input(coercion: Coercion) -> Result<Vec<DataType>> {
1915 fields_with_udf(
1916 &[Field::new(
1917 "field",
1918 DataType::Dictionary(
1919 Box::new(DataType::Int8),
1920 Box::new(DataType::Int64),
1921 ),
1922 true,
1923 )
1924 .into()],
1925 &MockUdf(Signature::coercible(vec![coercion], Volatility::Immutable)),
1926 )
1927 .map(|v| v.into_iter().map(|f| f.data_type().clone()).collect())
1928 }
1929
1930 let output = dictionary_input(Coercion::new_exact(TypeSignatureClass::Native(
1932 logical_int64(),
1933 )))?;
1934 assert_eq!(vec![DataType::Int64], output);
1935
1936 let output = dictionary_input(Coercion::new_implicit(
1937 TypeSignatureClass::Native(logical_int64()),
1938 vec![],
1939 NativeType::Int64,
1940 ))?;
1941 assert_eq!(vec![DataType::Int64], output);
1942
1943 let output = dictionary_input(Coercion::new_exact(TypeSignatureClass::Any))?;
1945 assert_eq!(vec![dictionary.clone()], output);
1946
1947 let output = dictionary_input(
1948 Coercion::new_exact(TypeSignatureClass::Any)
1949 .with_encoding_preservation(EncodingPreservation::dictionary()),
1950 )?;
1951 assert_eq!(vec![dictionary.clone()], output);
1952
1953 let output = dictionary_input(Coercion::new_exact(TypeSignatureClass::Integer))?;
1955 assert_eq!(vec![DataType::Int64], output);
1956
1957 let output = dictionary_input(Coercion::new_implicit(
1958 TypeSignatureClass::Integer,
1959 vec![],
1960 NativeType::Int64,
1961 ))?;
1962 assert_eq!(vec![DataType::Int64], output);
1963
1964 let output = dictionary_input(
1966 Coercion::new_exact(TypeSignatureClass::Integer)
1967 .with_encoding_preservation(EncodingPreservation::dictionary()),
1968 )?;
1969 assert_eq!(vec![dictionary], output);
1970
1971 Ok(())
1972 }
1973
1974 #[test]
1975 fn test_coercible_dictionary_preserves_encoding() -> Result<()> {
1976 fn dictionary_input(
1977 value_type: DataType,
1978 coercion: Coercion,
1979 ) -> Result<Vec<DataType>> {
1980 fields_with_udf(
1981 &[Field::new(
1982 "field",
1983 DataType::Dictionary(Box::new(DataType::Int8), Box::new(value_type)),
1984 true,
1985 )
1986 .into()],
1987 &MockUdf(Signature::coercible(vec![coercion], Volatility::Immutable)),
1988 )
1989 .map(|v| v.into_iter().map(|f| f.data_type().clone()).collect())
1990 }
1991
1992 let coercion = Coercion::new_exact(TypeSignatureClass::Native(logical_string()))
1993 .with_encoding_preservation(EncodingPreservation::dictionary());
1994
1995 assert_eq!(
1996 dictionary_input(DataType::LargeUtf8, coercion.clone())?,
1997 vec![DataType::Dictionary(
1998 Box::new(DataType::Int8),
1999 Box::new(DataType::LargeUtf8),
2000 )]
2001 );
2002 assert_eq!(
2003 dictionary_input(
2004 DataType::BinaryView,
2005 Coercion::new_implicit(
2006 TypeSignatureClass::Native(logical_string()),
2007 vec![TypeSignatureClass::Native(logical_binary())],
2008 NativeType::String,
2009 )
2010 .with_encoding_preservation(EncodingPreservation::dictionary()),
2011 )?,
2012 vec![DataType::Dictionary(
2013 Box::new(DataType::Int8),
2014 Box::new(DataType::Utf8View),
2015 )]
2016 );
2017 assert_eq!(
2019 dictionary_input(
2020 DataType::Int32,
2021 Coercion::new_implicit(
2022 TypeSignatureClass::Native(logical_int64()),
2023 vec![TypeSignatureClass::Integer],
2024 NativeType::Int64,
2025 ),
2026 )?,
2027 vec![DataType::Int64]
2028 );
2029 assert_eq!(
2031 dictionary_input(
2032 DataType::Int32,
2033 Coercion::new_implicit(
2034 TypeSignatureClass::Native(logical_int64()),
2035 vec![TypeSignatureClass::Integer],
2036 NativeType::Int64,
2037 )
2038 .with_encoding_preservation(EncodingPreservation::dictionary()),
2039 )?,
2040 vec![DataType::Dictionary(
2041 Box::new(DataType::Int8),
2042 Box::new(DataType::Int64),
2043 )]
2044 );
2045 assert_eq!(
2047 dictionary_input(
2048 DataType::Int32,
2049 Coercion::new_implicit(
2050 TypeSignatureClass::Integer,
2051 vec![],
2052 NativeType::Int64,
2053 ),
2054 )?,
2055 vec![DataType::Int32]
2056 );
2057 assert_eq!(
2059 dictionary_input(
2060 DataType::Int32,
2061 Coercion::new_implicit(
2062 TypeSignatureClass::Integer,
2063 vec![],
2064 NativeType::Int64,
2065 )
2066 .with_encoding_preservation(EncodingPreservation::dictionary()),
2067 )?,
2068 vec![DataType::Dictionary(
2069 Box::new(DataType::Int8),
2070 Box::new(DataType::Int32),
2071 )]
2072 );
2073
2074 Ok(())
2075 }
2076
2077 #[test]
2078 fn test_coercible_nested_dictionary() -> Result<()> {
2079 let nested_dictionary = DataType::Dictionary(
2080 Box::new(DataType::Int8),
2081 Box::new(DataType::Dictionary(
2082 Box::new(DataType::Int16),
2083 Box::new(DataType::Int32),
2084 )),
2085 );
2086 let nested_dictionary_input = |coercion| -> Result<Vec<DataType>> {
2087 fields_with_udf(
2088 &[Field::new("field", nested_dictionary.clone(), true).into()],
2089 &MockUdf(Signature::coercible(vec![coercion], Volatility::Immutable)),
2090 )
2091 .map(|v| v.into_iter().map(|f| f.data_type().clone()).collect())
2092 };
2093
2094 let output =
2096 nested_dictionary_input(Coercion::new_exact(TypeSignatureClass::Integer))?;
2097 assert_eq!(vec![DataType::Int32], output);
2098
2099 let output = nested_dictionary_input(
2101 Coercion::new_exact(TypeSignatureClass::Integer)
2102 .with_encoding_preservation(EncodingPreservation::dictionary()),
2103 )?;
2104 assert_eq!(vec![nested_dictionary.clone()], output);
2105
2106 let int64_coercion = || {
2107 Coercion::new_implicit(
2108 TypeSignatureClass::Native(logical_int64()),
2109 vec![TypeSignatureClass::Integer],
2110 NativeType::Int64,
2111 )
2112 };
2113
2114 let output = nested_dictionary_input(int64_coercion())?;
2116 assert_eq!(vec![DataType::Int64], output);
2117
2118 let output = nested_dictionary_input(
2120 int64_coercion()
2121 .with_encoding_preservation(EncodingPreservation::dictionary()),
2122 )?;
2123 assert_eq!(
2124 vec![DataType::Dictionary(
2125 Box::new(DataType::Int8),
2126 Box::new(DataType::Dictionary(
2127 Box::new(DataType::Int16),
2128 Box::new(DataType::Int64),
2129 )),
2130 )],
2131 output
2132 );
2133
2134 Ok(())
2135 }
2136
2137 #[test]
2138 fn test_coercible_run_end_encoded() -> Result<()> {
2139 let run_end_encoded = DataType::RunEndEncoded(
2140 Field::new("run_ends", DataType::Int16, false).into(),
2141 Field::new("values", DataType::Int64, true).into(),
2142 );
2143 fn run_end_encoded_input(coercion: Coercion) -> Result<Vec<DataType>> {
2144 fields_with_udf(
2145 &[Field::new(
2146 "field",
2147 DataType::RunEndEncoded(
2148 Field::new("run_ends", DataType::Int16, false).into(),
2149 Field::new("values", DataType::Int64, true).into(),
2150 ),
2151 true,
2152 )
2153 .into()],
2154 &MockUdf(Signature::coercible(vec![coercion], Volatility::Immutable)),
2155 )
2156 .map(|v| v.into_iter().map(|f| f.data_type().clone()).collect())
2157 }
2158
2159 let output = run_end_encoded_input(Coercion::new_exact(
2161 TypeSignatureClass::Native(logical_int64()),
2162 ))?;
2163 assert_eq!(vec![DataType::Int64], output);
2164
2165 let output = run_end_encoded_input(Coercion::new_implicit(
2166 TypeSignatureClass::Native(logical_int64()),
2167 vec![],
2168 NativeType::Int64,
2169 ))?;
2170 assert_eq!(vec![DataType::Int64], output);
2171
2172 let output =
2174 run_end_encoded_input(Coercion::new_exact(TypeSignatureClass::Integer))?;
2175 assert_eq!(vec![run_end_encoded.clone()], output);
2176
2177 let output = run_end_encoded_input(Coercion::new_implicit(
2178 TypeSignatureClass::Integer,
2179 vec![],
2180 NativeType::Int64,
2181 ))?;
2182 assert_eq!(vec![run_end_encoded.clone()], output);
2183
2184 Ok(())
2185 }
2186
2187 #[test]
2188 fn test_get_valid_types_coercible_binary() -> Result<()> {
2189 let signature = Signature::coercible(
2190 vec![Coercion::new_exact(TypeSignatureClass::Native(
2191 logical_binary(),
2192 ))],
2193 Volatility::Immutable,
2194 );
2195
2196 for t in [
2198 DataType::Binary,
2199 DataType::BinaryView,
2200 DataType::LargeBinary,
2201 ] {
2202 assert_eq!(
2203 get_valid_types("", &signature.type_signature, std::slice::from_ref(&t))?,
2204 vec![vec![t]]
2205 );
2206 }
2207
2208 Ok(())
2209 }
2210
2211 #[test]
2212 fn test_get_valid_types_fixed_size_arrays() -> Result<()> {
2213 let function = "fixed_size_arrays";
2214 let signature = Signature::arrays(2, None, Volatility::Immutable);
2215
2216 let data_types = vec![
2217 DataType::new_fixed_size_list(DataType::Int64, 3, true),
2218 DataType::new_fixed_size_list(DataType::Int32, 5, true),
2219 ];
2220 assert_eq!(
2221 get_valid_types(function, &signature.type_signature, &data_types)?,
2222 vec![vec![
2223 DataType::new_fixed_size_list(DataType::Int64, 3, true),
2224 DataType::new_fixed_size_list(DataType::Int64, 5, true),
2225 ]]
2226 );
2227
2228 let data_types = vec![
2229 DataType::new_fixed_size_list(DataType::Int64, 3, true),
2230 DataType::new_list(DataType::Int32, true),
2231 ];
2232 assert_eq!(
2233 get_valid_types(function, &signature.type_signature, &data_types)?,
2234 vec![vec![
2235 DataType::new_list(DataType::Int64, true),
2236 DataType::new_list(DataType::Int64, true),
2237 ]]
2238 );
2239
2240 let data_types = vec![
2241 DataType::new_fixed_size_list(DataType::Utf8, 3, true),
2242 DataType::new_list(DataType::new_list(DataType::Int32, true), true),
2243 ];
2244 assert_eq!(
2245 get_valid_types(function, &signature.type_signature, &data_types)?,
2246 vec![vec![]]
2247 );
2248
2249 let data_types = vec![
2250 DataType::new_fixed_size_list(DataType::Int64, 3, false),
2251 DataType::new_list(DataType::Int32, false),
2252 ];
2253 assert_eq!(
2254 get_valid_types(function, &signature.type_signature, &data_types)?,
2255 vec![vec![
2256 DataType::new_list(DataType::Int64, false),
2257 DataType::new_list(DataType::Int64, false),
2258 ]]
2259 );
2260
2261 Ok(())
2262 }
2263
2264 #[derive(Debug, PartialEq, Eq, Hash)]
2265 struct MockHigherOrderUDF {
2266 signature: HigherOrderSignature,
2267 coerced_value_types: Vec<DataType>,
2268 }
2269
2270 impl HigherOrderUDFImpl for MockHigherOrderUDF {
2271 fn name(&self) -> &str {
2272 "mock_higher_order_function"
2273 }
2274
2275 fn signature(&self) -> &HigherOrderSignature {
2276 &self.signature
2277 }
2278
2279 fn coerce_value_types(&self, arg_types: &[DataType]) -> Result<Vec<DataType>> {
2280 if arg_types.len() != 1 {
2281 return plan_err!(
2282 "mock_higher_order_function expects 1 value arguments, got {}",
2283 arg_types.len()
2284 );
2285 }
2286 Ok(self.coerced_value_types.clone())
2287 }
2288
2289 fn coerce_values_for_lambdas(
2290 &self,
2291 fields: &[ValueOrLambda<DataType, DataType>],
2292 ) -> Result<Option<Vec<DataType>>> {
2293 let [
2295 ValueOrLambda::Value(list),
2296 ValueOrLambda::Value(_initial),
2297 ValueOrLambda::Lambda(merge),
2298 ] = fields
2299 else {
2300 unreachable!()
2301 };
2302
2303 Ok(Some(vec![list.clone(), merge.clone()]))
2304 }
2305
2306 fn lambda_parameters(
2307 &self,
2308 _step: usize,
2309 _fields: &[ValueOrLambda<FieldRef, Option<FieldRef>>],
2310 ) -> Result<crate::LambdaParametersProgress> {
2311 unimplemented!("mock_higher_order_function")
2312 }
2313
2314 fn return_field_from_args(
2315 &self,
2316 _args: HigherOrderReturnFieldArgs,
2317 ) -> Result<FieldRef> {
2318 unimplemented!("mock_higher_order_function")
2319 }
2320
2321 fn invoke_with_args(
2322 &self,
2323 _args: HigherOrderFunctionArgs,
2324 ) -> Result<ColumnarValue> {
2325 unimplemented!("mock_higher_order_function")
2326 }
2327 }
2328
2329 #[test]
2330 fn test_higher_order_function_user_defined_type_coercion() {
2331 let fun = HigherOrderUDF::new_from_impl(MockHigherOrderUDF {
2332 signature: HigherOrderSignature::user_defined(Volatility::Immutable),
2333 coerced_value_types: vec![DataType::new_large_list(DataType::Int32, false)],
2334 });
2335
2336 let new_fields = value_fields_with_higher_order_udf(
2337 &[
2338 ValueOrLambda::Value(Arc::new(Field::new_list(
2339 "",
2340 Field::new_list_field(DataType::Int32, false),
2341 false,
2342 ))),
2343 ValueOrLambda::Lambda(()),
2344 ],
2345 &fun,
2346 )
2347 .unwrap();
2348
2349 assert_eq!(
2351 new_fields,
2352 vec![
2353 ValueOrLambda::Value(Arc::new(Field::new_large_list(
2354 "",
2355 Field::new_list_field(DataType::Int32, false),
2356 false
2357 ))),
2358 ValueOrLambda::Lambda(()),
2359 ]
2360 )
2361 }
2362
2363 #[test]
2364 fn test_higher_order_function_coerce_values_for_lambdas() {
2365 let fun = HigherOrderUDF::new_from_impl(MockHigherOrderUDF {
2366 signature: HigherOrderSignature::variadic_any(Volatility::Immutable),
2367 coerced_value_types: vec![],
2368 });
2369
2370 let new_fields = value_fields_with_higher_order_udf_and_lambdas(
2371 &[
2372 ValueOrLambda::Value(Arc::new(Field::new_list(
2373 "",
2374 Field::new_list_field(DataType::Float32, true),
2375 true,
2376 ))),
2377 ValueOrLambda::Value(Arc::new(Field::new("", DataType::Int32, true))),
2378 ValueOrLambda::Lambda(Arc::new(Field::new("", DataType::Float32, true))),
2379 ],
2380 &fun,
2381 )
2382 .unwrap();
2383
2384 assert_eq!(
2386 new_fields,
2387 vec![
2388 ValueOrLambda::Value(Arc::new(Field::new_list(
2389 "",
2390 Field::new_list_field(DataType::Float32, true),
2391 true,
2392 ))),
2393 ValueOrLambda::Value(Arc::new(Field::new("", DataType::Float32, true))),
2394 ValueOrLambda::Lambda(Arc::new(Field::new("", DataType::Float32, true))),
2395 ]
2396 )
2397 }
2398
2399 #[test]
2400 fn test_higher_order_function_user_defined_type_coercion_bad_args() {
2401 let fun = HigherOrderUDF::new_from_impl(MockHigherOrderUDF {
2402 signature: HigherOrderSignature::user_defined(Volatility::Immutable),
2403 coerced_value_types: vec![DataType::Int32],
2404 });
2405
2406 let err = value_fields_with_higher_order_udf::<()>(&[], &fun).unwrap_err();
2407
2408 assert_contains!(
2409 err.to_string(),
2410 "mock_higher_order_function expects 1 value arguments, got 0"
2411 );
2412 }
2413
2414 #[test]
2415 fn test_higher_order_function_faulty_user_defined_type_coercion() {
2416 let fun = HigherOrderUDF::new_from_impl(MockHigherOrderUDF {
2417 signature: HigherOrderSignature::user_defined(Volatility::Immutable),
2418 coerced_value_types: vec![DataType::Int32, DataType::Int32],
2419 });
2420
2421 let err = value_fields_with_higher_order_udf::<()>(
2422 &[ValueOrLambda::Value(Arc::new(Field::new(
2423 "",
2424 DataType::Int32,
2425 false,
2426 )))],
2427 &fun,
2428 )
2429 .unwrap_err();
2430
2431 assert_contains!(
2432 err.to_string(),
2433 "mock_higher_order_function coerce_value_types should have returned 1 items but returned 2"
2434 );
2435 }
2436
2437 #[test]
2438 fn test_higher_order_function_any_signature() {
2439 let fun = HigherOrderUDF::new_from_impl(MockHigherOrderUDF {
2440 signature: HigherOrderSignature::any(1, Volatility::Immutable),
2441 coerced_value_types: vec![],
2442 });
2443
2444 let new_fields =
2445 value_fields_with_higher_order_udf(&[ValueOrLambda::Lambda(())], &fun)
2446 .unwrap();
2447
2448 assert_eq!(new_fields, vec![ValueOrLambda::Lambda(())])
2450 }
2451
2452 #[test]
2453 fn test_higher_order_function_any_signature_bad_args() {
2454 let fun = HigherOrderUDF::new_from_impl(MockHigherOrderUDF {
2455 signature: HigherOrderSignature::any(1, Volatility::Immutable),
2456 coerced_value_types: vec![],
2457 });
2458
2459 let err = value_fields_with_higher_order_udf::<()>(&[], &fun).unwrap_err();
2460
2461 assert_contains!(
2462 err.to_string(),
2463 "The function 'mock_higher_order_function' expected 1 arguments but received 0"
2464 );
2465 }
2466
2467 #[test]
2468 fn test_higher_order_function_exact_signature() {
2469 let fun = HigherOrderUDF::new_from_impl(MockHigherOrderUDF {
2470 signature: HigherOrderSignature::exact(
2471 vec![ValueOrLambda::Value(()), ValueOrLambda::Lambda(())],
2472 Volatility::Immutable,
2473 ),
2474 coerced_value_types: vec![DataType::new_large_list(DataType::Int32, false)],
2475 });
2476
2477 let new_fields = value_fields_with_higher_order_udf(
2478 &[
2479 ValueOrLambda::Value(Arc::new(Field::new_list(
2480 "",
2481 Field::new_list_field(DataType::Int32, false),
2482 false,
2483 ))),
2484 ValueOrLambda::Lambda(()),
2485 ],
2486 &fun,
2487 )
2488 .unwrap();
2489
2490 assert_eq!(
2492 new_fields,
2493 vec![
2494 ValueOrLambda::Value(Arc::new(Field::new_large_list(
2495 "",
2496 Field::new_list_field(DataType::Int32, false),
2497 false
2498 ))),
2499 ValueOrLambda::Lambda(()),
2500 ]
2501 )
2502 }
2503
2504 #[test]
2505 fn test_higher_order_function_exact_signature_wrong_value_count() {
2506 let fun = HigherOrderUDF::new_from_impl(MockHigherOrderUDF {
2507 signature: HigherOrderSignature::exact(
2508 vec![ValueOrLambda::Value(()), ValueOrLambda::Lambda(())],
2509 Volatility::Immutable,
2510 ),
2511 coerced_value_types: vec![],
2512 });
2513
2514 let err = value_fields_with_higher_order_udf::<()>(
2515 &[ValueOrLambda::Lambda(()), ValueOrLambda::Lambda(())],
2516 &fun,
2517 )
2518 .unwrap_err();
2519
2520 assert_contains!(
2521 err.to_string(),
2522 "expected a value at position 0 but received a lambda"
2523 );
2524 }
2525
2526 #[test]
2527 fn test_higher_order_function_exact_signature_wrong_lambda_count() {
2528 let fun = HigherOrderUDF::new_from_impl(MockHigherOrderUDF {
2529 signature: HigherOrderSignature::exact(
2530 vec![ValueOrLambda::Value(()), ValueOrLambda::Lambda(())],
2531 Volatility::Immutable,
2532 ),
2533 coerced_value_types: vec![],
2534 });
2535
2536 let err = value_fields_with_higher_order_udf::<()>(
2537 &[
2538 ValueOrLambda::Value(Arc::new(Field::new("", DataType::Int32, false))),
2539 ValueOrLambda::Value(Arc::new(Field::new("", DataType::Int32, false))),
2540 ],
2541 &fun,
2542 )
2543 .unwrap_err();
2544
2545 assert_contains!(
2546 err.to_string(),
2547 "expected a lambda at position 1 but received a value"
2548 );
2549 }
2550}