Skip to content

Apache DataFusion SQL Query Engine

ARROW-10236: [Rust] Add can_cast_types to arrow cast kernel, use in DataFusion

alamb4e9d45ff58b9
diff --git a/rust/datafusion/src/logical_plan/mod.rs b/rust/datafusion/src/logical_plan/mod.rs
index b8d0cc7fb8..6df92fe190 100644
--- a/rust/datafusion/src/logical_plan/mod.rs
+++ b/rust/datafusion/src/logical_plan/mod.rs
@@ -25,7 +25,10 @@ use fmt::Debug;
use std::{any::Any, collections::HashMap, collections::HashSet, fmt, sync::Arc};
use aggregates::{AccumulatorFunctionImplementation, StateTypeFunction};
-use arrow::datatypes::{DataType, Field, Schema, SchemaRef};
+use arrow::{
+ compute::can_cast_types,
+ datatypes::{DataType, Field, Schema, SchemaRef},
+};
use crate::datasource::parquet::ParquetTable;
use crate::datasource::TableProvider;
@@ -37,8 +40,7 @@ use crate::{
};
use crate::{
physical_plan::{
- aggregates, expressions::binary_operator_data_type, functions,
- type_coercion::can_coerce_from, udf::ScalarUDF,
+ aggregates, expressions::binary_operator_data_type, functions, udf::ScalarUDF,
},
sql::parser::FileType,
};
@@ -333,12 +335,13 @@ impl Expr {
///
/// # Errors
///
- /// This function errors when it is impossible to cast the expression to the target [arrow::datatypes::DataType].
+ /// This function errors when it is impossible to cast the
+ /// expression to the target [arrow::datatypes::DataType].
pub fn cast_to(&self, cast_to_type: &DataType, schema: &Schema) -> Result<Expr> {
let this_type = self.get_type(schema)?;
if this_type == *cast_to_type {
Ok(self.clone())
- } else if can_coerce_from(cast_to_type, &this_type) {
+ } else if can_cast_types(&this_type, cast_to_type) {
Ok(Expr::Cast {
expr: Box::new(self.clone()),
data_type: cast_to_type.clone(),
diff --git a/rust/datafusion/src/physical_plan/expressions.rs b/rust/datafusion/src/physical_plan/expressions.rs
index 1f5dafdc19..084f8186c5 100644
--- a/rust/datafusion/src/physical_plan/expressions.rs
+++ b/rust/datafusion/src/physical_plan/expressions.rs
@@ -49,6 +49,7 @@ use arrow::{
},
datatypes::Field,
};
+use compute::can_cast_types;
/// returns the name of the state
pub fn format_state_name(name: &str, state_name: &str) -> String {
@@ -1525,7 +1526,10 @@ impl PhysicalExpr for CastExpr {
}
}
-/// Returns a cast operation, if casting needed.
+/// Returns a physical cast operation that casts `expr` to `cast_type`
+/// if casting is needed.
+///
+/// Note that such casts may lose type information
pub fn cast(
expr: Arc<dyn PhysicalExpr>,
input_schema: &Schema,
@@ -1533,19 +1537,12 @@ pub fn cast(
) -> Result<Arc<dyn PhysicalExpr>> {
let expr_type = expr.data_type(input_schema)?;
if expr_type == cast_type {
- return Ok(expr.clone());
- }
- if is_numeric(&expr_type) && (is_numeric(&cast_type) || cast_type == DataType::Utf8) {
- Ok(Arc::new(CastExpr { expr, cast_type }))
- } else if expr_type == DataType::Binary && cast_type == DataType::Utf8 {
- Ok(Arc::new(CastExpr { expr, cast_type }))
- } else if is_numeric(&expr_type)
- && cast_type == DataType::Timestamp(TimeUnit::Nanosecond, None)
- {
+ Ok(expr.clone())
+ } else if can_cast_types(&expr_type, &cast_type) {
Ok(Arc::new(CastExpr { expr, cast_type }))
} else {
Err(ExecutionError::General(format!(
- "Invalid CAST from {:?} to {:?}",
+ "Unsupported CAST from {:?} to {:?}",
expr_type, cast_type
)))
}
@@ -1985,9 +1982,10 @@ mod tests {
#[test]
fn invalid_cast() -> Result<()> {
- let schema = Schema::new(vec![Field::new("a", DataType::Utf8, false)]);
- let result = cast(col("a"), &schema, DataType::Int32);
- result.expect_err("Invalid CAST from Utf8 to Int32");
+ // Ensure a useful error happens at plan time if invalid casts are used
+ let schema = Schema::new(vec![Field::new("a", DataType::Int32, false)]);
+ let result = cast(col("a"), &schema, DataType::LargeBinary);
+ result.expect_err("expected Invalid CAST");
Ok(())
}