diff --git a/arrow-cast/src/cast.rs b/arrow-cast/src/cast.rs index 1f5359bae1f9..aa40ad425a5e 100644 --- a/arrow-cast/src/cast.rs +++ b/arrow-cast/src/cast.rs @@ -2128,8 +2128,8 @@ fn cast_decimal_to_decimal( if input_scale > output_scale { // For example, input_scale is 4 and output_scale is 3; // Original value is 11234_i128, and will be cast to 1123_i128. - let array = array.as_any().downcast_ref::().unwrap(); if BYTE_WIDTH1 == 16 { + let array = array.as_any().downcast_ref::().unwrap(); if BYTE_WIDTH2 == 16 { let div = 10_i128 .pow_checked((input_scale - output_scale) as u32) @@ -3816,6 +3816,34 @@ mod tests { ); } + #[test] + fn test_cast_decimal256_to_decimal128_overflow() { + let input_type = DataType::Decimal256(76, 5); + let output_type = DataType::Decimal128(38, 7); + assert!(can_cast_types(&input_type, &output_type)); + let array = vec![Some(i256::from_i128(i128::MAX))]; + let input_decimal_array = create_decimal256_array(array, 76, 5).unwrap(); + let array = Arc::new(input_decimal_array) as ArrayRef; + let result = + cast_with_options(&array, &output_type, &CastOptions { safe: false }); + assert_eq!("Invalid argument error: 17014118346046923173168730371588410572700 cannot be casted to 128-bit integer for Decimal128", + result.unwrap_err().to_string()); + } + + #[test] + fn test_cast_decimal256_to_decimal256_overflow() { + let input_type = DataType::Decimal256(76, 5); + let output_type = DataType::Decimal256(76, 55); + assert!(can_cast_types(&input_type, &output_type)); + let array = vec![Some(i256::from_i128(i128::MAX))]; + let input_decimal_array = create_decimal256_array(array, 76, 5).unwrap(); + let array = Arc::new(input_decimal_array) as ArrayRef; + let result = + cast_with_options(&array, &output_type, &CastOptions { safe: false }); + assert_eq!("Cast error: Cannot cast to \"Decimal256\"(76, 55). Overflowing on 170141183460469231731687303715884105727", + result.unwrap_err().to_string()); + } + #[test] fn test_cast_decimal256_to_decimal128() { let input_type = DataType::Decimal256(20, 3);