Skip to content

Commit 7d9bb37

Browse files
authored
Improve error message for unsupported cast between struct and other types (#6919)
1 parent 1d2696d commit 7d9bb37

File tree

1 file changed

+32
-6
lines changed

1 file changed

+32
-6
lines changed

arrow-cast/src/cast/mod.rs

Lines changed: 32 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1189,12 +1189,12 @@ pub fn cast_with_options(
11891189
let array = StructArray::try_new(to_fields.clone(), fields, array.nulls().cloned())?;
11901190
Ok(Arc::new(array) as ArrayRef)
11911191
}
1192-
(Struct(_), _) => Err(ArrowError::CastError(
1193-
"Cannot cast from struct to other types except struct".to_string(),
1194-
)),
1195-
(_, Struct(_)) => Err(ArrowError::CastError(
1196-
"Cannot cast to struct from other types except struct".to_string(),
1197-
)),
1192+
(Struct(_), _) => Err(ArrowError::CastError(format!(
1193+
"Casting from {from_type:?} to {to_type:?} not supported"
1194+
))),
1195+
(_, Struct(_)) => Err(ArrowError::CastError(format!(
1196+
"Casting from {from_type:?} to {to_type:?} not supported"
1197+
))),
11981198
(_, Boolean) => match from_type {
11991199
UInt8 => cast_numeric_to_bool::<UInt8Type>(array),
12001200
UInt16 => cast_numeric_to_bool::<UInt16Type>(array),
@@ -9941,6 +9941,32 @@ mod tests {
99419941
);
99429942
}
99439943

9944+
#[test]
9945+
fn test_cast_struct_to_non_struct() {
9946+
let boolean = Arc::new(BooleanArray::from(vec![true, false]));
9947+
let struct_array = StructArray::from(vec![(
9948+
Arc::new(Field::new("a", DataType::Boolean, false)),
9949+
boolean.clone() as ArrayRef,
9950+
)]);
9951+
let to_type = DataType::Utf8;
9952+
let result = cast(&struct_array, &to_type);
9953+
assert_eq!(
9954+
r#"Cast error: Casting from Struct([Field { name: "a", data_type: Boolean, nullable: false, dict_id: 0, dict_is_ordered: false, metadata: {} }]) to Utf8 not supported"#,
9955+
result.unwrap_err().to_string()
9956+
);
9957+
}
9958+
9959+
#[test]
9960+
fn test_cast_non_struct_to_struct() {
9961+
let array = StringArray::from(vec!["a", "b"]);
9962+
let to_type = DataType::Struct(vec![Field::new("a", DataType::Boolean, false)].into());
9963+
let result = cast(&array, &to_type);
9964+
assert_eq!(
9965+
r#"Cast error: Casting from Utf8 to Struct([Field { name: "a", data_type: Boolean, nullable: false, dict_id: 0, dict_is_ordered: false, metadata: {} }]) not supported"#,
9966+
result.unwrap_err().to_string()
9967+
);
9968+
}
9969+
99449970
#[test]
99459971
fn test_decimal_to_decimal_throw_error_on_precision_overflow_same_scale() {
99469972
let array = vec![Some(123456789)];

0 commit comments

Comments
 (0)