1use std::collections::HashMap;
19use std::fmt;
20use std::hash::Hash;
21use std::sync::Arc;
22
23use crate::physical_expr::PhysicalExpr;
24
25use arrow::compute::{CastOptions, can_cast_types};
26use arrow::datatypes::{DataType, DataType::*, Field, FieldRef, Schema};
27use arrow::record_batch::RecordBatch;
28use arrow_schema::extension::{EXTENSION_TYPE_METADATA_KEY, EXTENSION_TYPE_NAME_KEY};
29use datafusion_common::datatype::DataTypeExt;
30use datafusion_common::format::DEFAULT_FORMAT_OPTIONS;
31use datafusion_common::nested_struct::{
32 requires_nested_struct_cast, validate_data_type_compatibility,
33};
34use datafusion_common::{Result, not_impl_err};
35use datafusion_expr_common::columnar_value::ColumnarValue;
36use datafusion_expr_common::interval_arithmetic::Interval;
37use datafusion_expr_common::sort_properties::ExprProperties;
38
39const DEFAULT_CAST_OPTIONS: CastOptions<'static> = CastOptions {
40 safe: false,
41 format_options: DEFAULT_FORMAT_OPTIONS,
42};
43
44const DEFAULT_SAFE_CAST_OPTIONS: CastOptions<'static> = CastOptions {
45 safe: true,
46 format_options: DEFAULT_FORMAT_OPTIONS,
47};
48
49fn can_cast_named_struct_types(source: &DataType, target: &DataType) -> bool {
56 validate_data_type_compatibility("", source, target).is_ok()
57}
58
59#[derive(Debug, Clone, Eq)]
61pub struct CastExpr {
62 pub expr: Arc<dyn PhysicalExpr>,
64 target_field: FieldRef,
72 explicit_target: bool,
76 cast_options: CastOptions<'static>,
78}
79
80impl PartialEq for CastExpr {
82 fn eq(&self, other: &Self) -> bool {
83 self.expr.eq(&other.expr)
86 && self.cast_type().eq(other.cast_type())
87 && self.target_metadata().eq(&other.target_metadata())
88 && self.target_nullable().eq(&other.target_nullable())
89 && self.cast_options.eq(&other.cast_options)
90 }
91}
92
93impl Hash for CastExpr {
94 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
95 self.expr.hash(state);
96 self.cast_type().hash(state);
97 if let Some(metadata) = self.target_metadata() {
99 let mut entries: Vec<_> = metadata.iter().collect();
100 entries.sort_by_key(|(k, _)| *k);
101 for (k, v) in entries {
102 k.hash(state);
103 v.hash(state);
104 }
105 }
106 self.target_nullable().hash(state);
107 self.cast_options.hash(state);
108 }
109}
110
111impl CastExpr {
112 pub fn new(
122 expr: Arc<dyn PhysicalExpr>,
123 cast_type: DataType,
124 cast_options: Option<CastOptions<'static>>,
125 ) -> Self {
126 Self {
127 expr,
128 target_field: cast_type.into_nullable_field_ref(),
129 explicit_target: false,
130 cast_options: cast_options.unwrap_or(DEFAULT_CAST_OPTIONS),
131 }
132 }
133
134 pub fn new_with_target_field(
148 expr: Arc<dyn PhysicalExpr>,
149 target_field: FieldRef,
150 cast_options: Option<CastOptions<'static>>,
151 ) -> Self {
152 Self {
153 expr,
154 target_field,
155 explicit_target: true,
156 cast_options: cast_options.unwrap_or(DEFAULT_CAST_OPTIONS),
157 }
158 }
159
160 pub fn expr(&self) -> &Arc<dyn PhysicalExpr> {
162 &self.expr
163 }
164
165 pub fn cast_type(&self) -> &DataType {
167 self.target_field.data_type()
168 }
169
170 pub fn target_metadata(&self) -> Option<&HashMap<String, String>> {
172 self.explicit_target.then(|| self.target_field.metadata())
173 }
174
175 pub fn target_nullable(&self) -> Option<bool> {
177 self.explicit_target
178 .then(|| self.target_field.is_nullable())
179 }
180
181 pub fn target_field(&self) -> &FieldRef {
195 &self.target_field
196 }
197
198 pub fn cast_options(&self) -> &CastOptions<'static> {
200 &self.cast_options
201 }
202
203 pub fn has_explicit_metadata(&self) -> bool {
205 self.explicit_target
206 }
207
208 pub fn has_explicit_nullability(&self) -> bool {
210 self.explicit_target
211 }
212
213 fn resolved_target_field(&self, input_schema: &Schema) -> Result<FieldRef> {
214 let source_result = self.expr.return_field(input_schema);
218
219 if self.explicit_target {
220 let name = source_result
222 .as_ref()
223 .map(|f| f.name().to_string())
224 .unwrap_or_default();
225 return Ok(Arc::new(
226 Field::new(
227 name,
228 self.cast_type().clone(),
229 self.target_field.is_nullable(),
230 )
231 .with_metadata(self.target_field.metadata().clone()),
232 ));
233 }
234
235 source_result.map(|source_field| {
238 let mut metadata = source_field.metadata().clone();
239 metadata.remove(EXTENSION_TYPE_NAME_KEY);
240 metadata.remove(EXTENSION_TYPE_METADATA_KEY);
241
242 Arc::new(
243 source_field
244 .as_ref()
245 .clone()
246 .with_data_type(self.cast_type().clone())
247 .with_metadata(metadata),
248 )
249 })
250 }
251
252 pub fn check_bigger_cast(cast_type: &DataType, src: &DataType) -> bool {
255 if cast_type.eq(src) {
256 return true;
257 }
258 matches!(
259 (src, cast_type),
260 (Int8, Int16 | Int32 | Int64)
261 | (Int16, Int32 | Int64)
262 | (Int32, Int64)
263 | (UInt8, UInt16 | UInt32 | UInt64)
264 | (UInt16, UInt32 | UInt64)
265 | (UInt32, UInt64)
266 | (Int8 | Int16 | UInt8 | UInt16, Float32)
267 | (Int8 | Int16 | Int32 | UInt8 | UInt16 | UInt32, Float64)
268 | (Utf8, LargeUtf8)
269 )
270 }
271
272 pub fn is_bigger_cast(&self, src: &DataType) -> bool {
274 Self::check_bigger_cast(self.cast_type(), src)
275 }
276}
277
278pub(crate) fn is_order_preserving_cast_family(
279 source_type: &DataType,
280 target_type: &DataType,
281) -> bool {
282 (source_type.is_numeric() || *source_type == Boolean) && target_type.is_numeric()
283 || source_type.is_temporal() && target_type.is_temporal()
284 || source_type.eq(target_type)
285}
286
287pub(crate) fn cast_expr_properties(
288 child: &ExprProperties,
289 target_type: &DataType,
290) -> Result<ExprProperties> {
291 let unbounded = Interval::make_unbounded(target_type)?;
292 let source_type = child.range.data_type();
293 let bigger_cast = CastExpr::check_bigger_cast(target_type, &source_type);
297 if is_order_preserving_cast_family(&source_type, target_type) || bigger_cast {
298 Ok(child
299 .clone()
300 .with_range(unbounded)
301 .with_strictly_order_preserving(
302 child.strictly_order_preserving && bigger_cast,
303 ))
304 } else {
305 Ok(ExprProperties::new_unknown().with_range(unbounded))
306 }
307}
308
309impl fmt::Display for CastExpr {
310 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
311 write!(f, "CAST({} AS {})", self.expr, self.cast_type())
312 }
313}
314
315impl PhysicalExpr for CastExpr {
316 fn data_type(&self, _input_schema: &Schema) -> Result<DataType> {
317 Ok(self.cast_type().clone())
318 }
319
320 fn nullable(&self, input_schema: &Schema) -> Result<bool> {
321 let child_nullable = self.expr.nullable(input_schema)?;
327 let target_nullable = self.resolved_target_field(input_schema)?.is_nullable();
328 Ok(child_nullable || target_nullable)
329 }
330
331 fn evaluate(&self, batch: &RecordBatch) -> Result<ColumnarValue> {
332 let value = self.expr.evaluate(batch)?;
333 value.cast_to(self.cast_type(), Some(&self.cast_options))
334 }
335
336 fn return_field(&self, input_schema: &Schema) -> Result<FieldRef> {
337 self.resolved_target_field(input_schema)
338 }
339
340 fn children(&self) -> Vec<&Arc<dyn PhysicalExpr>> {
341 vec![&self.expr]
342 }
343
344 fn with_new_children(
345 self: Arc<Self>,
346 children: Vec<Arc<dyn PhysicalExpr>>,
347 ) -> Result<Arc<dyn PhysicalExpr>> {
348 Ok(Arc::new(CastExpr {
349 expr: Arc::clone(&children[0]),
350 target_field: Arc::clone(&self.target_field),
351 explicit_target: self.explicit_target,
352 cast_options: self.cast_options.clone(),
353 }))
354 }
355
356 fn evaluate_bounds(&self, children: &[&Interval]) -> Result<Interval> {
357 children[0].cast_to(self.cast_type(), &self.cast_options)
359 }
360
361 fn propagate_constraints(
362 &self,
363 interval: &Interval,
364 children: &[&Interval],
365 ) -> Result<Option<Vec<Interval>>> {
366 let source_type = children[0].data_type();
367 let target_type = self.cast_type();
368 if !can_propagate_cast_constraints(&source_type, target_type) {
369 return Ok(Some(vec![]));
370 }
371 Ok(Some(vec![
372 interval.cast_to(&source_type, &DEFAULT_SAFE_CAST_OPTIONS)?,
373 ]))
374 }
375
376 fn get_properties(&self, children: &[ExprProperties]) -> Result<ExprProperties> {
379 cast_expr_properties(&children[0], self.cast_type())
380 }
381
382 fn fmt_sql(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
383 write!(f, "CAST(")?;
384 self.expr.fmt_sql(f)?;
385 write!(f, " AS {:?}", self.cast_type())?;
386
387 write!(f, ")")
388 }
389
390 #[cfg(feature = "proto")]
391 fn try_to_proto(
392 &self,
393 ctx: &datafusion_physical_expr_common::physical_expr::proto_encode::PhysicalExprEncodeCtx<'_>,
394 ) -> Result<Option<datafusion_proto_models::protobuf::PhysicalExprNode>> {
395 use datafusion_proto_models::protobuf;
396
397 Ok(Some(protobuf::PhysicalExprNode {
398 expr_id: None,
399 expr_type: Some(protobuf::physical_expr_node::ExprType::Cast(Box::new(
400 protobuf::PhysicalCastNode {
401 expr: Some(Box::new(ctx.encode_child(self.expr())?)),
402 arrow_type: Some(self.cast_type().try_into()?),
403 },
404 ))),
405 }))
406 }
407}
408
409fn can_propagate_cast_constraints(source: &DataType, target: &DataType) -> bool {
416 CastExpr::check_bigger_cast(target, source)
417 || (source.is_integer() && target.is_integer())
418 || (*source == Float32 && *target == Float64)
420}
421
422#[cfg(feature = "proto")]
423impl CastExpr {
424 pub fn try_from_proto(
432 node: &datafusion_proto_models::protobuf::PhysicalExprNode,
433 ctx: &datafusion_physical_expr_common::physical_expr::proto_decode::PhysicalExprDecodeCtx<'_>,
434 ) -> Result<Arc<dyn PhysicalExpr>> {
435 use datafusion_common::internal_datafusion_err;
436 use datafusion_common::internal_err;
437 use datafusion_proto_models::protobuf;
438
439 let cast_expr = match &node.expr_type {
440 Some(protobuf::physical_expr_node::ExprType::Cast(cast_expr)) => {
441 cast_expr.as_ref()
442 }
443 _ => return internal_err!("PhysicalExprNode is not a CastExpr"),
444 };
445
446 let expr = ctx.decode_required_expression(
447 cast_expr.expr.as_deref(),
448 "CastExpr",
449 "expr",
450 )?;
451 let arrow_type = cast_expr.arrow_type.as_ref().ok_or_else(|| {
452 internal_datafusion_err!("CastExpr is missing required field 'arrow_type'")
453 })?;
454
455 Ok(Arc::new(CastExpr::new(expr, arrow_type.try_into()?, None)))
456 }
457}
458
459pub fn cast_with_options(
464 expr: Arc<dyn PhysicalExpr>,
465 input_schema: &Schema,
466 cast_type: DataType,
467 cast_options: Option<CastOptions<'static>>,
468) -> Result<Arc<dyn PhysicalExpr>> {
469 let expr_type = expr.data_type(input_schema)?;
470
471 if expr_type == cast_type {
473 return Ok(Arc::clone(&expr));
474 }
475
476 let can_build_cast = if requires_nested_struct_cast(&expr_type, &cast_type) {
477 can_cast_named_struct_types(&expr_type, &cast_type)
478 } else {
479 can_cast_types(&expr_type, &cast_type)
480 };
481
482 if !can_build_cast {
483 return not_impl_err!("Unsupported CAST from {expr_type} to {cast_type}");
484 }
485
486 Ok(Arc::new(CastExpr::new(expr, cast_type, cast_options)))
487}
488
489pub fn cast_with_target_field(
497 expr: Arc<dyn PhysicalExpr>,
498 input_schema: &Schema,
499 target_field: &FieldRef,
500 cast_options: Option<CastOptions<'static>>,
501) -> Result<Arc<dyn PhysicalExpr>> {
502 let expr_type = expr.data_type(input_schema)?;
503 let cast_type = target_field.data_type();
504
505 let is_type_only = target_field.name().is_empty()
509 && target_field.is_nullable()
510 && target_field.metadata().is_empty();
511
512 if expr_type == *cast_type && is_type_only {
517 let source_field = expr.return_field(input_schema)?;
518 let has_extension_metadata = source_field
519 .metadata()
520 .contains_key(EXTENSION_TYPE_NAME_KEY);
521 if !has_extension_metadata {
522 return Ok(Arc::clone(&expr));
523 }
524 }
525
526 let can_build_cast = if requires_nested_struct_cast(&expr_type, cast_type) {
527 can_cast_named_struct_types(&expr_type, cast_type)
533 } else {
534 can_cast_types(&expr_type, cast_type)
535 };
536
537 if !can_build_cast {
538 return not_impl_err!("Unsupported CAST from {expr_type} to {cast_type}");
539 }
540
541 if is_type_only {
545 Ok(Arc::new(CastExpr::new(
546 expr,
547 cast_type.clone(),
548 cast_options,
549 )))
550 } else {
551 Ok(Arc::new(CastExpr::new_with_target_field(
552 expr,
553 Arc::clone(target_field),
554 cast_options,
555 )))
556 }
557}
558
559pub fn cast(
564 expr: Arc<dyn PhysicalExpr>,
565 input_schema: &Schema,
566 cast_type: DataType,
567) -> Result<Arc<dyn PhysicalExpr>> {
568 cast_with_options(expr, input_schema, cast_type, None)
569}
570
571#[cfg(test)]
572mod tests {
573 use super::*;
574
575 use crate::expressions::column::col;
576
577 use arrow::{
578 array::{
579 Array, ArrayRef, Decimal128Array, Float32Array, Float64Array, Int8Array,
580 Int16Array, Int32Array, Int64Array, StringArray, StructArray,
581 Time64NanosecondArray, TimestampNanosecondArray, UInt32Array,
582 },
583 datatypes::*,
584 };
585 use datafusion_common::ScalarValue;
586 use datafusion_common::cast::{
587 as_boolean_array, as_int64_array, as_string_array, as_struct_array,
588 as_uint8_array,
589 };
590 use datafusion_common::rounding::{next_down, next_up};
591 use datafusion_physical_expr_common::physical_expr::fmt_sql;
592 use insta::assert_snapshot;
593 use std::collections::HashMap;
594
595 #[test]
596 fn test_cast_constraint_propagation() -> Result<()> {
597 for (source, target, propagates) in [
598 (Utf8, Int32, false),
599 (Utf8View, Int32, false),
600 (Timestamp(TimeUnit::Nanosecond, None), Date32, false),
601 (Int32, Date32, false),
603 (Date32, Int32, false),
604 (Utf8, LargeUtf8, true),
605 (Utf8, Utf8, true),
606 (Float64, Int32, false),
607 (Int64, Float32, false),
608 (Float64, Float32, false),
609 (Decimal128(4, 1), Decimal128(4, 0), false),
610 (Decimal128(4, 1), Int32, false),
611 (Float64, Decimal128(4, 1), false),
612 (Int8, Int64, true),
613 (Int64, Int8, true),
614 (Int32, UInt32, true),
615 (UInt32, Int32, true),
616 (Int32, Float64, true),
617 (Float32, Float64, true),
618 (Decimal128(4, 1), Decimal128(4, 1), true),
619 ] {
620 let schema = Schema::new(vec![Field::new("x", source.clone(), true)]);
621 let expr = CastExpr::new(col("x", &schema)?, target.clone(), None);
622 let input = Interval::make_unbounded(&source)?;
623 let value = ScalarValue::Int32(Some(0)).cast_to(&target)?;
624 let output = Interval::from(&value);
625 let expected = if propagates {
626 vec![Interval::from(&value.cast_to(&source)?)]
627 } else {
628 vec![]
629 };
630 assert_eq!(
631 expr.propagate_constraints(&output, &[&input])?,
632 Some(expected),
633 "{source} -> {target}"
634 );
635 }
636 Ok(())
637 }
638
639 #[test]
640 fn test_float_widening_constraint_boundaries() -> Result<()> {
641 let mut values = vec![
642 f32::NEG_INFINITY,
643 -f32::MAX,
644 -1.0,
645 -f32::MIN_POSITIVE,
646 -f32::from_bits(1),
647 -0.0,
648 0.0,
649 f32::from_bits(1),
650 f32::MIN_POSITIVE,
651 1.0,
652 f32::MAX,
653 f32::INFINITY,
654 ];
655 values.extend(
657 [0x7f800001, 0x7f800002, 0x7fc00001, 0xff800001, 0xffc00001]
658 .map(f32::from_bits),
659 );
660 values.extend([next_down(1.0f32), next_up(1.0f32)]);
661 let schema = Arc::new(Schema::new(vec![Field::new("x", Float32, false)]));
662 let batch = RecordBatch::try_new(
663 Arc::clone(&schema),
664 vec![Arc::new(Float32Array::from(values.clone()))],
665 )?;
666 let expr = CastExpr::new(col("x", &schema)?, Float64, None);
667 let array = expr.evaluate(&batch)?.into_array(values.len())?;
668 let widened = array.as_any().downcast_ref::<Float64Array>().unwrap();
669 let mut bounds = vec![-f64::MAX, f64::MAX];
670 for value in widened.values() {
671 bounds.extend([next_down(*value), *value, next_up(*value)]);
672 }
673 bounds.extend([
675 f64::from(f32::from_bits(1)) / 2.0,
676 -f64::from(f32::from_bits(1)) / 2.0,
677 f64::midpoint(1.0, f64::from(next_up(1.0f32))),
678 ]);
679 bounds.sort_by(f64::total_cmp);
680 bounds.dedup_by(|a, b| a.to_bits() == b.to_bits());
681 let input = Interval::make_unbounded(&Float32)?;
682 for (i, lower) in bounds.iter().enumerate() {
683 for upper in &bounds[i..] {
684 let output = Interval::make(Some(*lower), Some(*upper))?;
685 let propagated = expr.propagate_constraints(&output, &[&input])?.unwrap();
686 assert_eq!(propagated.len(), 1);
687 for (index, value) in values.iter().enumerate() {
688 if output.contains_value(ScalarValue::Float64(Some(
689 widened.value(index),
690 )))? {
691 assert!(
692 propagated[0]
693 .contains_value(ScalarValue::Float32(Some(*value)))?,
694 "input bits={:08x}, output={output}, propagated={:?}",
695 value.to_bits(),
696 propagated[0]
697 );
698 }
699 }
700 }
701 }
702 Ok(())
703 }
704
705 fn make_struct_array(fields: Fields, arrays: Vec<ArrayRef>) -> StructArray {
706 StructArray::new(fields, arrays, None)
707 }
708
709 fn cast_struct_array(
710 column: &str,
711 input_field: Field,
712 target_field: Field,
713 input_array: StructArray,
714 ) -> Result<StructArray> {
715 let schema = Arc::new(Schema::new(vec![input_field]));
716 let batch = RecordBatch::try_new(
717 Arc::clone(&schema),
718 vec![Arc::new(input_array) as ArrayRef],
719 )?;
720 let expr = CastExpr::new_with_target_field(
721 col(column, schema.as_ref())?,
722 Arc::new(target_field),
723 None,
724 );
725
726 let result = expr.evaluate(&batch)?.into_array(batch.num_rows())?;
727 Ok(as_struct_array(result.as_ref())?.clone())
728 }
729
730 macro_rules! generic_decimal_to_other_test_cast {
737 ($DECIMAL_ARRAY:ident, $A_TYPE:expr, $TYPEARRAY:ident, $TYPE:expr, $VEC:expr,$CAST_OPTIONS:expr) => {{
738 let schema = Schema::new(vec![Field::new("a", $A_TYPE, true)]);
739 let batch = RecordBatch::try_new(
740 Arc::new(schema.clone()),
741 vec![Arc::new($DECIMAL_ARRAY)],
742 )?;
743 let expression =
745 cast_with_options(col("a", &schema)?, &schema, $TYPE, $CAST_OPTIONS)?;
746
747 assert_eq!(format!("CAST(a@0 AS {})", $TYPE), format!("{}", expression));
749
750 assert_eq!(expression.data_type(&schema)?, $TYPE);
752
753 let result = expression
755 .evaluate(&batch)?
756 .into_array(batch.num_rows())
757 .expect("Failed to convert to array");
758
759 assert_eq!(*result.data_type(), $TYPE);
761
762 let result = result
764 .as_any()
765 .downcast_ref::<$TYPEARRAY>()
766 .expect("failed to downcast");
767
768 for (i, x) in $VEC.iter().enumerate() {
770 match x {
771 Some(x) => assert_eq!(result.value(i), *x),
772 None => assert!(result.is_null(i)),
773 }
774 }
775 }};
776 }
777
778 macro_rules! generic_test_cast {
785 ($A_ARRAY:ident, $A_TYPE:expr, $A_VEC:expr, $TYPEARRAY:ident, $TYPE:expr, $VEC:expr, $CAST_OPTIONS:expr) => {{
786 let schema = Schema::new(vec![Field::new("a", $A_TYPE, true)]);
787 let a_vec_len = $A_VEC.len();
788 let a = $A_ARRAY::from($A_VEC);
789 let batch =
790 RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(a)])?;
791
792 let expression =
794 cast_with_options(col("a", &schema)?, &schema, $TYPE, $CAST_OPTIONS)?;
795
796 assert_eq!(format!("CAST(a@0 AS {})", $TYPE), format!("{}", expression));
798
799 assert_eq!(expression.data_type(&schema)?, $TYPE);
801
802 let result = expression
804 .evaluate(&batch)?
805 .into_array(batch.num_rows())
806 .expect("Failed to convert to array");
807
808 assert_eq!(*result.data_type(), $TYPE);
810
811 assert_eq!(result.len(), a_vec_len);
813
814 let result = result
816 .as_any()
817 .downcast_ref::<$TYPEARRAY>()
818 .expect("failed to downcast");
819
820 for (i, x) in $VEC.iter().enumerate() {
822 match x {
823 Some(x) => assert_eq!(result.value(i), *x),
824 None => assert!(result.is_null(i)),
825 }
826 }
827 }};
828 }
829
830 #[test]
831 fn test_cast_decimal_to_decimal() -> Result<()> {
832 let array = vec![
833 Some(1234),
834 Some(2222),
835 Some(3),
836 Some(4000),
837 Some(5000),
838 None,
839 ];
840
841 let decimal_array = array
842 .clone()
843 .into_iter()
844 .collect::<Decimal128Array>()
845 .with_precision_and_scale(10, 3)?;
846
847 generic_decimal_to_other_test_cast!(
848 decimal_array,
849 Decimal128(10, 3),
850 Decimal128Array,
851 Decimal128(20, 6),
852 [
853 Some(1_234_000),
854 Some(2_222_000),
855 Some(3_000),
856 Some(4_000_000),
857 Some(5_000_000),
858 None
859 ],
860 None
861 );
862
863 let decimal_array = array
864 .into_iter()
865 .collect::<Decimal128Array>()
866 .with_precision_and_scale(10, 3)?;
867
868 generic_decimal_to_other_test_cast!(
869 decimal_array,
870 Decimal128(10, 3),
871 Decimal128Array,
872 Decimal128(10, 2),
873 [Some(123), Some(222), Some(0), Some(400), Some(500), None],
874 None
875 );
876
877 Ok(())
878 }
879
880 #[test]
881 fn test_cast_decimal_to_decimal_overflow() -> Result<()> {
882 let array = vec![Some(123456789)];
883
884 let decimal_array = array
885 .clone()
886 .into_iter()
887 .collect::<Decimal128Array>()
888 .with_precision_and_scale(10, 3)?;
889
890 let schema = Schema::new(vec![Field::new("a", Decimal128(10, 3), false)]);
891 let batch = RecordBatch::try_new(
892 Arc::new(schema.clone()),
893 vec![Arc::new(decimal_array)],
894 )?;
895 let expression =
896 cast_with_options(col("a", &schema)?, &schema, Decimal128(6, 2), None)?;
897 let e = expression.evaluate(&batch).unwrap_err().strip_backtrace(); assert_snapshot!(e, @"Arrow error: Invalid argument error: 123456.79 is too large to store in a Decimal128 of precision 6. Max is 9999.99");
899 let expression_safe = cast_with_options(
901 col("a", &schema)?,
902 &schema,
903 Decimal128(6, 2),
904 Some(DEFAULT_SAFE_CAST_OPTIONS),
905 )?;
906 let result_safe = expression_safe
907 .evaluate(&batch)?
908 .into_array(batch.num_rows())
909 .expect("failed to convert to array");
910
911 assert!(result_safe.is_null(0));
912
913 Ok(())
914 }
915
916 #[test]
917 fn test_cast_decimal_to_numeric() -> Result<()> {
918 let array = vec![Some(1), Some(2), Some(3), Some(4), Some(5), None];
919 let decimal_array = array
921 .clone()
922 .into_iter()
923 .collect::<Decimal128Array>()
924 .with_precision_and_scale(10, 0)?;
925 generic_decimal_to_other_test_cast!(
926 decimal_array,
927 Decimal128(10, 0),
928 Int8Array,
929 Int8,
930 [
931 Some(1_i8),
932 Some(2_i8),
933 Some(3_i8),
934 Some(4_i8),
935 Some(5_i8),
936 None
937 ],
938 None
939 );
940
941 let decimal_array = array
943 .clone()
944 .into_iter()
945 .collect::<Decimal128Array>()
946 .with_precision_and_scale(10, 0)?;
947 generic_decimal_to_other_test_cast!(
948 decimal_array,
949 Decimal128(10, 0),
950 Int16Array,
951 Int16,
952 [
953 Some(1_i16),
954 Some(2_i16),
955 Some(3_i16),
956 Some(4_i16),
957 Some(5_i16),
958 None
959 ],
960 None
961 );
962
963 let decimal_array = array
965 .clone()
966 .into_iter()
967 .collect::<Decimal128Array>()
968 .with_precision_and_scale(10, 0)?;
969 generic_decimal_to_other_test_cast!(
970 decimal_array,
971 Decimal128(10, 0),
972 Int32Array,
973 Int32,
974 [
975 Some(1_i32),
976 Some(2_i32),
977 Some(3_i32),
978 Some(4_i32),
979 Some(5_i32),
980 None
981 ],
982 None
983 );
984
985 let decimal_array = array
987 .into_iter()
988 .collect::<Decimal128Array>()
989 .with_precision_and_scale(10, 0)?;
990 generic_decimal_to_other_test_cast!(
991 decimal_array,
992 Decimal128(10, 0),
993 Int64Array,
994 Int64,
995 [
996 Some(1_i64),
997 Some(2_i64),
998 Some(3_i64),
999 Some(4_i64),
1000 Some(5_i64),
1001 None
1002 ],
1003 None
1004 );
1005
1006 let array = vec![
1008 Some(1234),
1009 Some(2222),
1010 Some(3),
1011 Some(4000),
1012 Some(5000),
1013 None,
1014 ];
1015 let decimal_array = array
1016 .clone()
1017 .into_iter()
1018 .collect::<Decimal128Array>()
1019 .with_precision_and_scale(10, 3)?;
1020 generic_decimal_to_other_test_cast!(
1021 decimal_array,
1022 Decimal128(10, 3),
1023 Float32Array,
1024 Float32,
1025 [
1026 Some(1.234_f32),
1027 Some(2.222_f32),
1028 Some(0.003_f32),
1029 Some(4.0_f32),
1030 Some(5.0_f32),
1031 None
1032 ],
1033 None
1034 );
1035
1036 let decimal_array = array
1038 .into_iter()
1039 .collect::<Decimal128Array>()
1040 .with_precision_and_scale(20, 6)?;
1041 generic_decimal_to_other_test_cast!(
1042 decimal_array,
1043 Decimal128(20, 6),
1044 Float64Array,
1045 Float64,
1046 [
1047 Some(0.001234_f64),
1048 Some(0.002222_f64),
1049 Some(0.000003_f64),
1050 Some(0.004_f64),
1051 Some(0.005_f64),
1052 None
1053 ],
1054 None
1055 );
1056 Ok(())
1057 }
1058
1059 #[test]
1060 fn test_cast_numeric_to_decimal() -> Result<()> {
1061 generic_test_cast!(
1063 Int8Array,
1064 Int8,
1065 vec![1, 2, 3, 4, 5],
1066 Decimal128Array,
1067 Decimal128(3, 0),
1068 [Some(1), Some(2), Some(3), Some(4), Some(5)],
1069 None
1070 );
1071
1072 generic_test_cast!(
1074 Int16Array,
1075 Int16,
1076 vec![1, 2, 3, 4, 5],
1077 Decimal128Array,
1078 Decimal128(5, 0),
1079 [Some(1), Some(2), Some(3), Some(4), Some(5)],
1080 None
1081 );
1082
1083 generic_test_cast!(
1085 Int32Array,
1086 Int32,
1087 vec![1, 2, 3, 4, 5],
1088 Decimal128Array,
1089 Decimal128(10, 0),
1090 [Some(1), Some(2), Some(3), Some(4), Some(5)],
1091 None
1092 );
1093
1094 generic_test_cast!(
1096 Int64Array,
1097 Int64,
1098 vec![1, 2, 3, 4, 5],
1099 Decimal128Array,
1100 Decimal128(20, 0),
1101 [Some(1), Some(2), Some(3), Some(4), Some(5)],
1102 None
1103 );
1104
1105 generic_test_cast!(
1107 Int64Array,
1108 Int64,
1109 vec![1, 2, 3, 4, 5],
1110 Decimal128Array,
1111 Decimal128(20, 2),
1112 [Some(100), Some(200), Some(300), Some(400), Some(500)],
1113 None
1114 );
1115
1116 generic_test_cast!(
1118 Float32Array,
1119 Float32,
1120 vec![1.5, 2.5, 3.0, 1.123_456_8, 5.50],
1121 Decimal128Array,
1122 Decimal128(10, 2),
1123 [Some(150), Some(250), Some(300), Some(112), Some(550)],
1124 None
1125 );
1126
1127 generic_test_cast!(
1129 Float64Array,
1130 Float64,
1131 vec![1.5, 2.5, 3.0, 1.123_456_8, 5.50],
1132 Decimal128Array,
1133 Decimal128(20, 4),
1134 [
1135 Some(15000),
1136 Some(25000),
1137 Some(30000),
1138 Some(11235),
1139 Some(55000)
1140 ],
1141 None
1142 );
1143 Ok(())
1144 }
1145
1146 #[test]
1147 fn test_cast_i32_u32() -> Result<()> {
1148 generic_test_cast!(
1149 Int32Array,
1150 Int32,
1151 vec![1, 2, 3, 4, 5],
1152 UInt32Array,
1153 UInt32,
1154 [
1155 Some(1_u32),
1156 Some(2_u32),
1157 Some(3_u32),
1158 Some(4_u32),
1159 Some(5_u32)
1160 ],
1161 None
1162 );
1163 Ok(())
1164 }
1165
1166 #[test]
1167 fn test_cast_i32_utf8() -> Result<()> {
1168 generic_test_cast!(
1169 Int32Array,
1170 Int32,
1171 vec![1, 2, 3, 4, 5],
1172 StringArray,
1173 Utf8,
1174 [Some("1"), Some("2"), Some("3"), Some("4"), Some("5")],
1175 None
1176 );
1177 Ok(())
1178 }
1179
1180 #[test]
1181 fn test_cast_i64_t64() -> Result<()> {
1182 let original = vec![1, 2, 3, 4, 5];
1183 let expected: Vec<Option<i64>> = original
1184 .iter()
1185 .map(|i| Some(Time64NanosecondArray::from(vec![*i]).value(0)))
1186 .collect();
1187 generic_test_cast!(
1188 Int64Array,
1189 Int64,
1190 original,
1191 TimestampNanosecondArray,
1192 Timestamp(TimeUnit::Nanosecond, None),
1193 expected,
1194 None
1195 );
1196 Ok(())
1197 }
1198
1199 #[test]
1203 fn invalid_cast() {
1204 let schema = Schema::new(vec![Field::new("a", Int32, false)]);
1206
1207 let result = cast(
1208 col("a", &schema).unwrap(),
1209 &schema,
1210 Interval(IntervalUnit::MonthDayNano),
1211 );
1212 result.expect_err("expected Invalid CAST");
1213 }
1214
1215 #[test]
1216 fn invalid_cast_with_options_error() -> Result<()> {
1217 let schema = Schema::new(vec![Field::new("a", Utf8, false)]);
1219 let a = StringArray::from(vec!["9.1"]);
1220 let batch = RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(a)])?;
1221 let expression = cast_with_options(col("a", &schema)?, &schema, Int32, None)?;
1222 let result = expression.evaluate(&batch);
1223
1224 match result {
1225 Ok(_) => panic!("expected error"),
1226 Err(e) => {
1227 assert!(
1228 e.to_string()
1229 .contains("Cannot cast string '9.1' to value of Int32 type")
1230 )
1231 }
1232 }
1233 Ok(())
1234 }
1235
1236 #[test]
1237 fn field_aware_cast_preserves_target_field_semantics() -> Result<()> {
1238 let metadata = HashMap::from([("target_meta".to_string(), "1".to_string())]);
1240
1241 for (child_nullable, target_nullable) in [(true, false), (false, true)] {
1242 let schema = Schema::new(vec![Field::new("a", Int32, child_nullable)]);
1243 let target_field = Arc::new(
1244 Field::new("cast_target", Int64, target_nullable)
1245 .with_metadata(metadata.clone()),
1246 );
1247 let expr = CastExpr::new_with_target_field(
1248 col("a", &schema)?,
1249 Arc::clone(&target_field),
1250 None,
1251 );
1252
1253 let field = expr.return_field(&schema)?;
1254 assert_eq!(field.name(), "a");
1256 assert_eq!(field.data_type(), &Int64);
1257 assert_eq!(field.is_nullable(), target_nullable);
1259 assert_eq!(
1261 field.metadata().get("target_meta"),
1262 Some(&"1".to_string()),
1263 "Target metadata should be preserved exactly"
1264 );
1265 assert_eq!(expr.nullable(&schema)?, child_nullable || target_nullable);
1266 }
1267
1268 Ok(())
1269 }
1270
1271 #[test]
1272 fn target_field_accessor_returns_the_constructed_field() -> Result<()> {
1273 let schema = Schema::new(vec![Field::new("a", Int32, true)]);
1274 let metadata = HashMap::from([("target_meta".to_string(), "1".to_string())]);
1275 let target_field =
1276 Arc::new(Field::new("cast_target", Int64, false).with_metadata(metadata));
1277
1278 let expr = CastExpr::new_with_target_field(
1279 col("a", &schema)?,
1280 Arc::clone(&target_field),
1281 None,
1282 );
1283
1284 assert_eq!(expr.target_field(), &target_field);
1286 assert_eq!(expr.cast_type(), &Int64);
1287 assert_eq!(expr.target_metadata(), Some(target_field.metadata()));
1288 assert_eq!(expr.target_nullable(), Some(false));
1289 assert!(expr.has_explicit_metadata());
1290 assert!(expr.has_explicit_nullability());
1291
1292 let type_only = CastExpr::new(col("a", &schema)?, Int64, None);
1294 assert_eq!(type_only.cast_type(), &Int64);
1295 assert_eq!(type_only.target_metadata(), None);
1296 assert_eq!(type_only.target_nullable(), None);
1297 assert!(!type_only.has_explicit_metadata());
1298 assert!(!type_only.has_explicit_nullability());
1299
1300 Ok(())
1301 }
1302
1303 #[test]
1304 fn type_only_cast_preserves_legacy_field_name_and_nullability() -> Result<()> {
1305 let schema = Schema::new(vec![Field::new("a", Int32, false)]);
1306 let expr = CastExpr::new(col("a", &schema)?, Int64, None);
1307
1308 let field = expr.return_field(&schema)?;
1309
1310 assert_eq!(field.name(), "a");
1311 assert_eq!(field.data_type(), &Int64);
1312 assert!(!field.is_nullable());
1313 assert!(!expr.nullable(&schema)?);
1314
1315 Ok(())
1316 }
1317
1318 #[test]
1319 fn struct_cast_validation_uses_nested_target_fields() -> Result<()> {
1320 let source_type = Struct(Fields::from(vec![
1321 Arc::new(Field::new("x", Int32, true)),
1322 Arc::new(Field::new("y", Utf8, true)),
1323 ]));
1324 let schema = Schema::new(vec![Field::new("a", source_type.clone(), true)]);
1325
1326 let valid_target = Struct(Fields::from(vec![
1327 Arc::new(Field::new("y", Utf8, true)),
1328 Arc::new(Field::new("x", Int64, true)),
1329 ]));
1330 cast_with_options(col("a", &schema)?, &schema, valid_target, None)?;
1331
1332 let invalid_target = Struct(Fields::from(vec![
1333 Arc::new(Field::new("y", Utf8, true)),
1334 Arc::new(Field::new("missing", Int64, false)),
1335 ]));
1336 let err = cast_with_options(col("a", &schema)?, &schema, invalid_target, None)
1337 .expect_err("missing required struct field should fail");
1338
1339 assert!(err.to_string().contains("Unsupported CAST"));
1340
1341 Ok(())
1342 }
1343
1344 #[test]
1345 fn field_aware_cast_struct_array_missing_child() -> Result<()> {
1346 let source_a = Field::new("a", Int32, true);
1347 let source_b = Field::new("b", Utf8, true);
1348 let target_field = Field::new(
1349 "s",
1350 Struct(
1351 vec![
1352 Arc::new(Field::new("a", Int64, true)),
1353 Arc::new(Field::new("c", Utf8, true)),
1354 ]
1355 .into(),
1356 ),
1357 true,
1358 );
1359
1360 let struct_array = cast_struct_array(
1361 "s",
1362 Field::new(
1363 "s",
1364 Struct(
1365 vec![Arc::new(source_a.clone()), Arc::new(source_b.clone())].into(),
1366 ),
1367 true,
1368 ),
1369 target_field,
1370 make_struct_array(
1371 vec![Arc::new(source_a), Arc::new(source_b)].into(),
1372 vec![
1373 Arc::new(Int32Array::from(vec![Some(1), None])) as ArrayRef,
1374 Arc::new(StringArray::from(vec![Some("alpha"), Some("beta")]))
1375 as ArrayRef,
1376 ],
1377 ),
1378 )?;
1379 let cast_a = as_int64_array(struct_array.column_by_name("a").unwrap().as_ref())?;
1380 assert_eq!(cast_a.value(0), 1);
1381 assert!(cast_a.is_null(1));
1382
1383 let cast_c = as_string_array(struct_array.column_by_name("c").unwrap().as_ref())?;
1384 assert!(cast_c.is_null(0));
1385 assert!(cast_c.is_null(1));
1386 Ok(())
1387 }
1388
1389 #[test]
1390 fn field_aware_cast_nested_struct_array() -> Result<()> {
1391 let inner_source = Field::new(
1392 "inner",
1393 Struct(vec![Arc::new(Field::new("x", Int32, true))].into()),
1394 true,
1395 );
1396 let inner_target = Field::new(
1397 "inner",
1398 Struct(
1399 vec![
1400 Arc::new(Field::new("x", Int64, true)),
1401 Arc::new(Field::new("y", Boolean, true)),
1402 ]
1403 .into(),
1404 ),
1405 true,
1406 );
1407 let target_field =
1408 Field::new("root", Struct(vec![Arc::new(inner_target)].into()), true);
1409
1410 let inner_struct = make_struct_array(
1411 vec![Arc::new(Field::new("x", Int32, true))].into(),
1412 vec![Arc::new(Int32Array::from(vec![Some(7), None])) as ArrayRef],
1413 );
1414 let outer_struct = make_struct_array(
1415 vec![Arc::new(inner_source.clone())].into(),
1416 vec![Arc::new(inner_struct) as ArrayRef],
1417 );
1418 let struct_array = cast_struct_array(
1419 "root",
1420 Field::new("root", Struct(vec![Arc::new(inner_source)].into()), true),
1421 target_field,
1422 outer_struct,
1423 )?;
1424 let inner =
1425 as_struct_array(struct_array.column_by_name("inner").unwrap().as_ref())?;
1426 let x = as_int64_array(inner.column_by_name("x").unwrap().as_ref())?;
1427 assert_eq!(x.value(0), 7);
1428 assert!(x.is_null(1));
1429 let y = as_boolean_array(inner.column_by_name("y").unwrap().as_ref())?;
1430 assert!(y.is_null(0));
1431 assert!(y.is_null(1));
1432 Ok(())
1433 }
1434
1435 #[test]
1436 fn field_aware_cast_struct_scalar() -> Result<()> {
1437 let source_field = Field::new("a", Int32, true);
1438 let target_field = Field::new(
1439 "s",
1440 Struct(vec![Arc::new(Field::new("a", UInt8, true))].into()),
1441 true,
1442 );
1443
1444 let schema = Arc::new(Schema::new(vec![Field::new(
1445 "s",
1446 Struct(vec![Arc::new(source_field.clone())].into()),
1447 true,
1448 )]));
1449 let scalar_struct = make_struct_array(
1450 vec![Arc::new(source_field)].into(),
1451 vec![Arc::new(Int32Array::from(vec![Some(9)])) as ArrayRef],
1452 );
1453 let literal = Arc::new(crate::expressions::Literal::new(ScalarValue::Struct(
1454 Arc::new(scalar_struct),
1455 )));
1456 let target_field = Arc::new(target_field);
1457 let expr = CastExpr::new_with_target_field(literal, target_field, None);
1458
1459 let batch = RecordBatch::new_empty(schema);
1460 let result = expr.evaluate(&batch)?;
1461 let ColumnarValue::Scalar(ScalarValue::Struct(array)) = result else {
1462 panic!("expected struct scalar");
1463 };
1464 let casted = as_uint8_array(array.column_by_name("a").unwrap().as_ref())?;
1465 assert_eq!(casted.value(0), 9);
1466 Ok(())
1467 }
1468
1469 #[test]
1470 #[ignore] fn test_cast_decimal() -> Result<()> {
1472 let schema = Schema::new(vec![Field::new("a", Int64, false)]);
1473 let a = Int64Array::from(vec![100]);
1474 let batch = RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(a)])?;
1475 let expression =
1476 cast_with_options(col("a", &schema)?, &schema, Decimal128(38, 38), None)?;
1477 expression.evaluate(&batch)?;
1478 Ok(())
1479 }
1480
1481 #[test]
1482 fn test_fmt_sql() -> Result<()> {
1483 let schema = Schema::new(vec![Field::new("a", Int32, true)]);
1484
1485 let expr = cast(col("a", &schema)?, &schema, Int64)?;
1487 let display_string = expr.to_string();
1488 assert_eq!(display_string, "CAST(a@0 AS Int64)");
1489 let sql_string = fmt_sql(expr.as_ref()).to_string();
1490 assert_eq!(sql_string, "CAST(a AS Int64)");
1491
1492 let schema = Schema::new(vec![Field::new("b", Utf8, true)]);
1494 let expr = cast(col("b", &schema)?, &schema, Int32)?;
1495 let display_string = expr.to_string();
1496 assert_eq!(display_string, "CAST(b@0 AS Int32)");
1497 let sql_string = fmt_sql(expr.as_ref()).to_string();
1498 assert_eq!(sql_string, "CAST(b AS Int32)");
1499
1500 Ok(())
1501 }
1502
1503 #[test]
1504 fn type_only_cast_strips_extension_metadata() -> Result<()> {
1505 let source_meta = HashMap::from([
1507 (
1508 EXTENSION_TYPE_NAME_KEY.to_string(),
1509 "arrow.uuid".to_string(),
1510 ),
1511 ("custom_key".to_string(), "custom_value".to_string()),
1512 ]);
1513 let schema = Schema::new(vec![
1514 Field::new("a", FixedSizeBinary(16), false).with_metadata(source_meta),
1515 ]);
1516
1517 let expr = CastExpr::new(col("a", &schema)?, Utf8, None);
1518
1519 let field = expr.return_field(&schema)?;
1520 assert!(
1521 field.metadata().get(EXTENSION_TYPE_NAME_KEY).is_none(),
1522 "Type-only cast should strip extension type name from source"
1523 );
1524 assert_eq!(
1525 field.metadata().get("custom_key"),
1526 Some(&"custom_value".to_string()),
1527 "Type-only cast should preserve non-extension metadata"
1528 );
1529
1530 Ok(())
1531 }
1532
1533 #[test]
1534 fn field_aware_cast_uses_exact_target_metadata() -> Result<()> {
1535 let source_meta = HashMap::from([
1537 (
1538 EXTENSION_TYPE_NAME_KEY.to_string(),
1539 "source.type".to_string(),
1540 ),
1541 ("source_key".to_string(), "source_value".to_string()),
1542 ]);
1543 let target_meta = HashMap::from([
1544 (
1545 EXTENSION_TYPE_NAME_KEY.to_string(),
1546 "target.type".to_string(),
1547 ),
1548 (
1549 EXTENSION_TYPE_METADATA_KEY.to_string(),
1550 "target_ext_meta".to_string(),
1551 ),
1552 ("target_key".to_string(), "target_value".to_string()),
1553 ]);
1554 let schema = Schema::new(vec![
1555 Field::new("a", FixedSizeBinary(16), false).with_metadata(source_meta),
1556 ]);
1557
1558 let target_field =
1559 Arc::new(Field::new("b", Utf8, true).with_metadata(target_meta));
1560 let expr = CastExpr::new_with_target_field(
1561 col("a", &schema)?,
1562 Arc::clone(&target_field),
1563 None,
1564 );
1565
1566 let field = expr.return_field(&schema)?;
1567 assert_eq!(
1568 field.metadata().get(EXTENSION_TYPE_NAME_KEY),
1569 Some(&"target.type".to_string()),
1570 "Field-aware cast should use target's extension type name"
1571 );
1572 assert_eq!(
1573 field.metadata().get(EXTENSION_TYPE_METADATA_KEY),
1574 Some(&"target_ext_meta".to_string()),
1575 "Field-aware cast should use target's extension type metadata"
1576 );
1577 assert!(
1578 field.metadata().get("source_key").is_none(),
1579 "Field-aware cast should NOT preserve source metadata"
1580 );
1581 assert_eq!(
1582 field.metadata().get("target_key"),
1583 Some(&"target_value".to_string()),
1584 "Field-aware cast should preserve target's non-extension metadata"
1585 );
1586
1587 Ok(())
1588 }
1589
1590 #[test]
1591 fn test_check_bigger_cast_precision_loss() {
1592 use DataType::*;
1593
1594 assert!(CastExpr::check_bigger_cast(&Int16, &Int8));
1596 assert!(CastExpr::check_bigger_cast(&Int64, &Int32));
1597 assert!(CastExpr::check_bigger_cast(&Float32, &Int16));
1598 assert!(CastExpr::check_bigger_cast(&Float32, &UInt16));
1599 assert!(CastExpr::check_bigger_cast(&Float64, &Int32));
1600 assert!(CastExpr::check_bigger_cast(&Float64, &UInt32));
1601 assert!(CastExpr::check_bigger_cast(&LargeUtf8, &Utf8));
1602
1603 assert!(!CastExpr::check_bigger_cast(&Float32, &Int32));
1605 assert!(!CastExpr::check_bigger_cast(&Float32, &UInt32));
1606 assert!(!CastExpr::check_bigger_cast(&Float64, &Int64));
1607 assert!(!CastExpr::check_bigger_cast(&Float64, &UInt64));
1608
1609 assert!(!CastExpr::check_bigger_cast(&UInt16, &Int8));
1611 assert!(!CastExpr::check_bigger_cast(&UInt32, &Int16));
1612 assert!(!CastExpr::check_bigger_cast(&Int16, &UInt8));
1613 }
1614}
1615
1616#[cfg(all(test, feature = "proto"))]
1618mod proto_tests {
1619 use super::*;
1620 use crate::expressions::{Column, col};
1621 use crate::proto_test_util::{
1622 StubDecoder, StubEncoder, UnreachableDecoder, column_node,
1623 };
1624 use arrow::datatypes::Field;
1625 use datafusion_common::DataFusionError;
1626 use datafusion_physical_expr_common::physical_expr::proto_decode::PhysicalExprDecodeCtx;
1627 use datafusion_physical_expr_common::physical_expr::proto_encode::PhysicalExprEncodeCtx;
1628 use datafusion_proto_models::datafusion_common::ArrowType;
1629 use datafusion_proto_models::protobuf::{
1630 PhysicalCastNode, PhysicalExprNode, physical_expr_node,
1631 };
1632
1633 fn proto_cast_fixture() -> CastExpr {
1635 let schema = Schema::new(vec![Field::new("a", Int32, false)]);
1636 CastExpr::new(col("a", &schema).unwrap(), Int64, None)
1637 }
1638
1639 fn proto_int64_arrow_type() -> ArrowType {
1640 (&Int64).try_into().unwrap()
1641 }
1642
1643 fn proto_cast_node(
1645 expr: Option<Box<PhysicalExprNode>>,
1646 arrow_type: Option<ArrowType>,
1647 ) -> PhysicalExprNode {
1648 PhysicalExprNode {
1649 expr_id: None,
1650 expr_type: Some(physical_expr_node::ExprType::Cast(Box::new(
1651 PhysicalCastNode { expr, arrow_type },
1652 ))),
1653 }
1654 }
1655
1656 #[test]
1657 fn try_to_proto_encodes_cast_expr() {
1658 let cast = proto_cast_fixture();
1659 let encoder = StubEncoder::ok();
1660 let ctx = PhysicalExprEncodeCtx::new(&encoder);
1661
1662 let node = cast
1663 .try_to_proto(&ctx)
1664 .unwrap()
1665 .expect("CastExpr should encode to Some(node)");
1666
1667 assert!(node.expr_id.is_none());
1668 let cast_node = match node.expr_type {
1669 Some(physical_expr_node::ExprType::Cast(cast_node)) => *cast_node,
1670 other => panic!("expected a Cast node, got {other:?}"),
1671 };
1672 assert!(cast_node.expr.is_some());
1673
1674 let arrow_type = cast_node
1675 .arrow_type
1676 .as_ref()
1677 .expect("cast type should be encoded");
1678 let data_type: DataType = arrow_type.try_into().unwrap();
1679 assert_eq!(data_type, Int64);
1680 }
1681
1682 #[test]
1683 fn try_to_proto_propagates_child_encode_error() {
1684 let cast = proto_cast_fixture();
1685 let encoder = StubEncoder::failing_on(1);
1686 let ctx = PhysicalExprEncodeCtx::new(&encoder);
1687
1688 let err = cast.try_to_proto(&ctx).unwrap_err();
1689 assert!(matches!(
1690 err,
1691 DataFusionError::Internal(msg) if msg.contains("call 1")
1692 ));
1693 }
1694
1695 #[test]
1696 fn try_from_proto_decodes_cast_expr() {
1697 let node = proto_cast_node(
1698 Some(Box::new(column_node("a"))),
1699 Some(proto_int64_arrow_type()),
1700 );
1701 let schema = Schema::empty();
1702 let decoder = StubDecoder::ok();
1703 let ctx = PhysicalExprDecodeCtx::new(&schema, &decoder);
1704
1705 let decoded = CastExpr::try_from_proto(&node, &ctx).unwrap();
1706 let cast = decoded
1707 .downcast_ref::<CastExpr>()
1708 .expect("decoded expr should be a CastExpr");
1709
1710 assert_eq!(cast.cast_type(), &Int64);
1711 assert!(cast.expr().downcast_ref::<Column>().is_some());
1712 }
1713
1714 #[test]
1715 fn try_from_proto_rejects_non_cast_node() {
1716 let node = column_node("a");
1717 let schema = Schema::empty();
1718 let decoder = UnreachableDecoder;
1719 let ctx = PhysicalExprDecodeCtx::new(&schema, &decoder);
1720
1721 let err = CastExpr::try_from_proto(&node, &ctx).unwrap_err();
1722 assert!(matches!(
1723 err,
1724 DataFusionError::Internal(msg)
1725 if msg.contains("PhysicalExprNode is not a CastExpr")
1726 ));
1727 }
1728
1729 #[test]
1730 fn try_from_proto_rejects_missing_expr() {
1731 let node = proto_cast_node(None, Some(proto_int64_arrow_type()));
1732 let schema = Schema::empty();
1733 let decoder = UnreachableDecoder;
1734 let ctx = PhysicalExprDecodeCtx::new(&schema, &decoder);
1735
1736 let err = CastExpr::try_from_proto(&node, &ctx).unwrap_err();
1737 assert!(matches!(
1738 err,
1739 DataFusionError::Internal(msg)
1740 if msg.contains("CastExpr is missing required field 'expr'")
1741 ));
1742 }
1743
1744 #[test]
1745 fn try_from_proto_rejects_missing_arrow_type() {
1746 let node = proto_cast_node(Some(Box::new(column_node("a"))), None);
1747 let schema = Schema::empty();
1748 let decoder = StubDecoder::ok();
1749 let ctx = PhysicalExprDecodeCtx::new(&schema, &decoder);
1750
1751 let err = CastExpr::try_from_proto(&node, &ctx).unwrap_err();
1752 assert!(matches!(
1753 err,
1754 DataFusionError::Internal(msg)
1755 if msg.contains("CastExpr is missing required field 'arrow_type'")
1756 ));
1757 }
1758
1759 #[test]
1760 fn try_from_proto_propagates_child_decode_error() {
1761 let node = proto_cast_node(
1762 Some(Box::new(column_node("a"))),
1763 Some(proto_int64_arrow_type()),
1764 );
1765 let schema = Schema::empty();
1766 let decoder = StubDecoder::failing_on(1);
1767 let ctx = PhysicalExprDecodeCtx::new(&schema, &decoder);
1768
1769 let err = CastExpr::try_from_proto(&node, &ctx).unwrap_err();
1770 assert!(matches!(
1771 err,
1772 DataFusionError::Internal(msg) if msg.contains("call 1")
1773 ));
1774 }
1775}