Apache DataFusion SQL Query Engine
ARROW-7364: [Rust][DataFusion] Add cast options to cast kernel and TRY_CAST to DataFusion
Mike Seddon8f1f836d9f53
diff --git a/rust/datafusion/Cargo.toml b/rust/datafusion/Cargo.tomlindex f78550e77c..fd1c1b2959 100644--- a/rust/datafusion/Cargo.toml+++ b/rust/datafusion/Cargo.toml@@ -52,7 +52,7 @@ ahash = "0.7"hashbrown = "0.11"arrow = { path = "../arrow", version = "4.0.0-SNAPSHOT", features = ["prettyprint"] }parquet = { path = "../parquet", version = "4.0.0-SNAPSHOT", features = ["arrow"] }-sqlparser = "0.8.0"+sqlparser = "0.9.0"clap = "2.33"rustyline = {version = "7.0", optional = true}paste = "^1.0"diff --git a/rust/datafusion/README.md b/rust/datafusion/README.mdindex e847f0bce3..d0bb7d3889 100644--- a/rust/datafusion/README.md+++ b/rust/datafusion/README.md@@ -160,6 +160,8 @@ DataFusion also includes a simple command-line interactive SQL utility. See the- [x] Limit- [x] Aggregate- [x] Common math functions+- [x] cast+- [x] try_cast- Postgres compatible String functions- [x] ascii- [x] bit_lengthdiff --git a/rust/datafusion/src/logical_plan/expr.rs b/rust/datafusion/src/logical_plan/expr.rsindex 991b16058b..fa9b9e0a24 100644--- a/rust/datafusion/src/logical_plan/expr.rs+++ b/rust/datafusion/src/logical_plan/expr.rs@@ -142,13 +142,22 @@ pub enum Expr {/// Optional "else" expressionelse_expr: Option<Box<Expr>>,},- /// Casts the expression to a given type. This expression is guaranteed to have a fixed type.+ /// Casts the expression to a given type and will return a runtime error if the expression cannot be cast.+ /// This expression is guaranteed to have a fixed type.Cast {/// The expression being castexpr: Box<Expr>,/// The `DataType` the expression will yielddata_type: DataType,},+ /// Casts the expression to a given type and will return a null value if the expression cannot be cast.+ /// This expression is guaranteed to have a fixed type.+ TryCast {+ /// The expression being cast+ expr: Box<Expr>,+ /// The `DataType` the expression will yield+ data_type: DataType,+ },/// A sort expression, that can be used to sort values.Sort {/// The expression to sort on@@ -220,6 +229,7 @@ impl Expr {Expr::Literal(l) => Ok(l.get_datatype()),Expr::Case { when_then_expr, .. } => when_then_expr[0].1.get_type(schema),Expr::Cast { data_type, .. } => Ok(data_type.clone()),+ Expr::TryCast { data_type, .. } => Ok(data_type.clone()),Expr::ScalarUDF { fun, args } => {let data_types = args.iter()@@ -303,6 +313,7 @@ impl Expr {}}Expr::Cast { expr, .. } => expr.nullable(input_schema),+ Expr::TryCast { .. } => Ok(true),Expr::ScalarFunction { .. } => Ok(true),Expr::ScalarUDF { .. } => Ok(true),Expr::AggregateFunction { .. } => Ok(true),@@ -552,6 +563,7 @@ impl Expr {}}Expr::Cast { expr, .. } => expr.accept(visitor),+ Expr::TryCast { expr, .. } => expr.accept(visitor),Expr::Sort { expr, .. } => expr.accept(visitor),Expr::ScalarFunction { args, .. } => args.iter()@@ -671,6 +683,10 @@ impl Expr {expr: rewrite_boxed(expr, rewriter)?,data_type,},+ Expr::TryCast { expr, data_type } => Expr::TryCast {+ expr: rewrite_boxed(expr, rewriter)?,+ data_type,+ },Expr::Sort {expr,asc,@@ -1197,6 +1213,9 @@ impl fmt::Debug for Expr {Expr::Cast { expr, data_type } => {write!(f, "CAST({:?} AS {:?})", expr, data_type)}+ Expr::TryCast { expr, data_type } => {+ write!(f, "TRY_CAST({:?} AS {:?})", expr, data_type)+ }Expr::Not(expr) => write!(f, "NOT {:?}", expr),Expr::Negative(expr) => write!(f, "(- {:?})", expr),Expr::IsNull(expr) => write!(f, "{:?} IS NULL", expr),@@ -1315,6 +1334,10 @@ fn create_name(e: &Expr, input_schema: &DFSchema) -> Result<String> {let expr = create_name(expr, input_schema)?;Ok(format!("CAST({} AS {:?})", expr, data_type))}+ Expr::TryCast { expr, data_type } => {+ let expr = create_name(expr, input_schema)?;+ Ok(format!("TRY_CAST({} AS {:?})", expr, data_type))+ }Expr::Not(expr) => {let expr = create_name(expr, input_schema)?;Ok(format!("NOT {}", expr))diff --git a/rust/datafusion/src/optimizer/utils.rs b/rust/datafusion/src/optimizer/utils.rsindex da21c58fee..fe1d023819 100644--- a/rust/datafusion/src/optimizer/utils.rs+++ b/rust/datafusion/src/optimizer/utils.rs@@ -73,6 +73,7 @@ impl ExpressionVisitor for ColumnNameVisitor<'_> {Expr::Between { .. } => {}Expr::Case { .. } => {}Expr::Cast { .. } => {}+ Expr::TryCast { .. } => {}Expr::Sort { .. } => {}Expr::ScalarFunction { .. } => {}Expr::ScalarUDF { .. } => {}@@ -261,6 +262,7 @@ pub fn expr_sub_expressions(expr: &Expr) -> Result<Vec<Expr>> {Ok(expr_list)}Expr::Cast { expr, .. } => Ok(vec![expr.as_ref().to_owned()]),+ Expr::TryCast { expr, .. } => Ok(vec![expr.as_ref().to_owned()]),Expr::Column(_) => Ok(vec![]),Expr::Alias(expr, ..) => Ok(vec![expr.as_ref().to_owned()]),Expr::Literal(_) => Ok(vec![]),@@ -357,6 +359,10 @@ pub fn rewrite_expression(expr: &Expr, expressions: &[Expr]) -> Result<Expr> {expr: Box::new(expressions[0].clone()),data_type: data_type.clone(),}),+ Expr::TryCast { data_type, .. } => Ok(Expr::TryCast {+ expr: Box::new(expressions[0].clone()),+ data_type: data_type.clone(),+ }),Expr::Alias(_, alias) => {Ok(Expr::Alias(Box::new(expressions[0].clone()), alias.clone()))}diff --git a/rust/datafusion/src/physical_plan/expressions/binary.rs b/rust/datafusion/src/physical_plan/expressions/binary.rsindex 362ef9cc6d..5c2d9ce02f 100644--- a/rust/datafusion/src/physical_plan/expressions/binary.rs+++ b/rust/datafusion/src/physical_plan/expressions/binary.rs@@ -39,7 +39,7 @@ use arrow::record_batch::RecordBatch;use crate::error::{DataFusionError, Result};use crate::logical_plan::Operator;-use crate::physical_plan::expressions::cast;+use crate::physical_plan::expressions::try_cast;use crate::physical_plan::{ColumnarValue, PhysicalExpr};use crate::scalar::ScalarValue;@@ -547,8 +547,8 @@ fn binary_cast(let cast_type = common_binary_type(lhs_type, op, rhs_type)?;Ok((- cast(lhs, input_schema, cast_type.clone())?,- cast(rhs, input_schema, cast_type)?,+ try_cast(lhs, input_schema, cast_type.clone())?,+ try_cast(rhs, input_schema, cast_type)?,))}diff --git a/rust/datafusion/src/physical_plan/expressions/cast.rs b/rust/datafusion/src/physical_plan/expressions/cast.rsindex bcf54dc14b..ba395f54d9 100644--- a/rust/datafusion/src/physical_plan/expressions/cast.rs+++ b/rust/datafusion/src/physical_plan/expressions/cast.rs@@ -25,23 +25,37 @@ use crate::physical_plan::PhysicalExpr;use crate::scalar::ScalarValue;use arrow::compute;use arrow::compute::kernels;+use arrow::compute::CastOptions;use arrow::datatypes::{DataType, Schema};use arrow::record_batch::RecordBatch;use compute::can_cast_types;-/// CAST expression casts an expression to a specific data type+/// provide Datafusion default cast options+pub const DEFAULT_DATAFUSION_CAST_OPTIONS: CastOptions = CastOptions { safe: false };++/// CAST expression casts an expression to a specific data type and returns a runtime error on invalid cast#[derive(Debug)]pub struct CastExpr {/// The expression to castexpr: Arc<dyn PhysicalExpr>,/// The data type to cast tocast_type: DataType,+ /// Cast options+ cast_options: CastOptions,}impl CastExpr {/// Create a new CastExpr- pub fn new(expr: Arc<dyn PhysicalExpr>, cast_type: DataType) -> Self {- Self { expr, cast_type }+ pub fn new(+ expr: Arc<dyn PhysicalExpr>,+ cast_type: DataType,+ cast_options: CastOptions,+ ) -> Self {+ Self {+ expr,+ cast_type,+ cast_options,+ }}/// The expression to cast@@ -78,13 +92,20 @@ impl PhysicalExpr for CastExpr {fn evaluate(&self, batch: &RecordBatch) -> Result<ColumnarValue> {let value = self.expr.evaluate(batch)?;match value {- ColumnarValue::Array(array) => Ok(ColumnarValue::Array(kernels::cast::cast(- &array,- &self.cast_type,- )?)),+ ColumnarValue::Array(array) => {+ Ok(ColumnarValue::Array(kernels::cast::cast_with_options(+ &array,+ &self.cast_type,+ &self.cast_options,+ )?))+ }ColumnarValue::Scalar(scalar) => {let scalar_array = scalar.to_array();- let cast_array = kernels::cast::cast(&scalar_array, &self.cast_type)?;+ let cast_array = kernels::cast::cast_with_options(+ &scalar_array,+ &self.cast_type,+ &self.cast_options,+ )?;let cast_scalar = ScalarValue::try_from_array(&cast_array, 0)?;Ok(ColumnarValue::Scalar(cast_scalar))}@@ -96,16 +117,17 @@ impl PhysicalExpr for CastExpr {/// `cast_type`, if any casting is needed.////// Note that such casts may lose type information-pub fn cast(+pub fn cast_with_options(expr: Arc<dyn PhysicalExpr>,input_schema: &Schema,cast_type: DataType,+ cast_options: CastOptions,) -> Result<Arc<dyn PhysicalExpr>> {let expr_type = expr.data_type(input_schema)?;if expr_type == cast_type {Ok(expr.clone())} else if can_cast_types(&expr_type, &cast_type) {- Ok(Arc::new(CastExpr::new(expr, cast_type)))+ Ok(Arc::new(CastExpr::new(expr, cast_type, cast_options)))} else {Err(DataFusionError::Internal(format!("Unsupported CAST from {:?} to {:?}",@@ -114,6 +136,23 @@ pub fn cast(}}+/// Return a PhysicalExpression representing `expr` casted to+/// `cast_type`, if any casting is needed.+///+/// Note that such casts may lose type information+pub fn cast(+ expr: Arc<dyn PhysicalExpr>,+ input_schema: &Schema,+ cast_type: DataType,+) -> Result<Arc<dyn PhysicalExpr>> {+ cast_with_options(+ expr,+ input_schema,+ cast_type,+ DEFAULT_DATAFUSION_CAST_OPTIONS,+ )+}+#[cfg(test)]mod tests {use super::*;@@ -121,7 +160,7 @@ mod tests {use crate::physical_plan::expressions::col;use arrow::array::{StringArray, Time64NanosecondArray};use arrow::{- array::{Int32Array, Int64Array, TimestampNanosecondArray, UInt32Array},+ array::{Array, Int32Array, Int64Array, TimestampNanosecondArray, UInt32Array},datatypes::*,};@@ -132,14 +171,14 @@ mod tests {// 4. verify that the resulting expression is of type B// 5. verify that the resulting values are downcastable and correctmacro_rules! generic_test_cast {- ($A_ARRAY:ident, $A_TYPE:expr, $A_VEC:expr, $TYPEARRAY:ident, $TYPE:expr, $VEC:expr) => {{+ ($A_ARRAY:ident, $A_TYPE:expr, $A_VEC:expr, $TYPEARRAY:ident, $TYPE:expr, $VEC:expr, $CAST_OPTIONS:expr) => {{let schema = Schema::new(vec![Field::new("a", $A_TYPE, false)]);let a = $A_ARRAY::from($A_VEC);let batch =RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(a)])?;// verify that we can construct the expression- let expression = cast(col("a"), &schema, $TYPE)?;+ let expression = cast_with_options(col("a"), &schema, $TYPE, $CAST_OPTIONS)?;// verify that its display is correctassert_eq!(format!("CAST(a AS {:?})", $TYPE), format!("{}", expression));@@ -164,7 +203,10 @@ mod tests {// verify that the result itself is correctfor (i, x) in $VEC.iter().enumerate() {- assert_eq!(result.value(i), *x);+ match x {+ Some(x) => assert_eq!(result.value(i), *x),+ None => assert!(!result.is_valid(i)),+ }}}};}@@ -177,7 +219,14 @@ mod tests {vec![1, 2, 3, 4, 5],UInt32Array,DataType::UInt32,- vec![1_u32, 2_u32, 3_u32, 4_u32, 5_u32]+ vec![+ Some(1_u32),+ Some(2_u32),+ Some(3_u32),+ Some(4_u32),+ Some(5_u32)+ ],+ DEFAULT_DATAFUSION_CAST_OPTIONS);Ok(())}@@ -190,17 +239,19 @@ mod tests {vec![1, 2, 3, 4, 5],StringArray,DataType::Utf8,- vec!["1", "2", "3", "4", "5"]+ vec![Some("1"), Some("2"), Some("3"), Some("4"), Some("5")],+ DEFAULT_DATAFUSION_CAST_OPTIONS);Ok(())}+#[allow(clippy::redundant_clone)]#[test]fn test_cast_i64_t64() -> Result<()> {let original = vec![1, 2, 3, 4, 5];- let expected: Vec<i64> = original+ let expected: Vec<Option<i64>> = original.iter()- .map(|i| Time64NanosecondArray::from(vec![*i]).value(0))+ .map(|i| Some(Time64NanosecondArray::from(vec![*i]).value(0))).collect();generic_test_cast!(Int64Array,@@ -208,7 +259,8 @@ mod tests {original.clone(),TimestampNanosecondArray,DataType::Timestamp(TimeUnit::Nanosecond, None),- expected+ expected,+ DEFAULT_DATAFUSION_CAST_OPTIONS);Ok(())}@@ -217,7 +269,33 @@ mod tests {fn invalid_cast() {// Ensure a useful error happens at plan time if invalid casts are usedlet schema = Schema::new(vec![Field::new("a", DataType::Int32, false)]);+let result = cast(col("a"), &schema, DataType::LargeBinary);result.expect_err("expected Invalid CAST");}++ #[test]+ fn invalid_cast_with_options_error() -> Result<()> {+ // Ensure a useful error happens at plan time if invalid casts are used+ let schema = Schema::new(vec![Field::new("a", DataType::Utf8, false)]);+ let a = StringArray::from(vec!["9.1"]);+ let batch = RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(a)])?;+ let expression = cast_with_options(+ col("a"),+ &schema,+ DataType::Int32,+ DEFAULT_DATAFUSION_CAST_OPTIONS,+ )?;+ let result = expression.evaluate(&batch);++ match result {+ Ok(_) => panic!("expected error"),+ Err(e) => {+ assert!(e.to_string().contains(+ "Cast error: Cannot cast string '9.1' to value of arrow::datatypes::types::Int32Type type"+ ))+ }+ }+ Ok(())+ }}diff --git a/rust/datafusion/src/physical_plan/expressions/mod.rs b/rust/datafusion/src/physical_plan/expressions/mod.rsindex fe5fea1e2e..6e25220595 100644--- a/rust/datafusion/src/physical_plan/expressions/mod.rs+++ b/rust/datafusion/src/physical_plan/expressions/mod.rs@@ -42,11 +42,12 @@ mod negative;mod not;mod nullif;mod sum;+mod try_cast;pub use average::{avg_return_type, Avg, AvgAccumulator};pub use binary::{binary, binary_operator_data_type, BinaryExpr};pub use case::{case, CaseExpr};-pub use cast::{cast, CastExpr};+pub use cast::{cast, cast_with_options, CastExpr};pub use column::{col, Column};pub use count::Count;pub use in_list::{in_list, InListExpr};@@ -58,6 +59,7 @@ pub use negative::{negative, NegativeExpr};pub use not::{not, NotExpr};pub use nullif::{nullif_func, SUPPORTED_NULLIF_TYPES};pub use sum::{sum_return_type, Sum};+pub use try_cast::{try_cast, TryCastExpr};/// returns the name of the statepub fn format_state_name(name: &str, state_name: &str) -> String {format!("{}[{}]", name, state_name)diff --git a/rust/datafusion/src/physical_plan/expressions/try_cast.rs b/rust/datafusion/src/physical_plan/expressions/try_cast.rsnew file mode 100644index 0000000000..5e402fdea2--- /dev/null+++ b/rust/datafusion/src/physical_plan/expressions/try_cast.rs@@ -0,0 +1,247 @@+// Licensed to the Apache Software Foundation (ASF) under one+// or more contributor license agreements. See the NOTICE file+// distributed with this work for additional information+// regarding copyright ownership. The ASF licenses this file+// to you under the Apache License, Version 2.0 (the+// "License"); you may not use this file except in compliance+// with the License. You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing,+// software distributed under the License is distributed on an+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+// KIND, either express or implied. See the License for the+// specific language governing permissions and limitations+// under the License.++use std::any::Any;+use std::fmt;+use std::sync::Arc;++use super::ColumnarValue;+use crate::error::{DataFusionError, Result};+use crate::physical_plan::PhysicalExpr;+use crate::scalar::ScalarValue;+use arrow::compute;+use arrow::compute::kernels;+use arrow::datatypes::{DataType, Schema};+use arrow::record_batch::RecordBatch;+use compute::can_cast_types;++/// TRY_CAST expression casts an expression to a specific data type and retuns NULL on invalid cast+#[derive(Debug)]+pub struct TryCastExpr {+ /// The expression to cast+ expr: Arc<dyn PhysicalExpr>,+ /// The data type to cast to+ cast_type: DataType,+}++impl TryCastExpr {+ /// Create a new CastExpr+ pub fn new(expr: Arc<dyn PhysicalExpr>, cast_type: DataType) -> Self {+ Self { expr, cast_type }+ }++ /// The expression to cast+ pub fn expr(&self) -> &Arc<dyn PhysicalExpr> {+ &self.expr+ }++ /// The data type to cast to+ pub fn cast_type(&self) -> &DataType {+ &self.cast_type+ }+}++impl fmt::Display for TryCastExpr {+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {+ write!(f, "CAST({} AS {:?})", self.expr, self.cast_type)+ }+}++impl PhysicalExpr for TryCastExpr {+ /// Return a reference to Any that can be used for downcasting+ fn as_any(&self) -> &dyn Any {+ self+ }++ fn data_type(&self, _input_schema: &Schema) -> Result<DataType> {+ Ok(self.cast_type.clone())+ }++ fn nullable(&self, _input_schema: &Schema) -> Result<bool> {+ Ok(true)+ }++ fn evaluate(&self, batch: &RecordBatch) -> Result<ColumnarValue> {+ let value = self.expr.evaluate(batch)?;+ match value {+ ColumnarValue::Array(array) => Ok(ColumnarValue::Array(kernels::cast::cast(+ &array,+ &self.cast_type,+ )?)),+ ColumnarValue::Scalar(scalar) => {+ let scalar_array = scalar.to_array();+ let cast_array = kernels::cast::cast(&scalar_array, &self.cast_type)?;+ let cast_scalar = ScalarValue::try_from_array(&cast_array, 0)?;+ Ok(ColumnarValue::Scalar(cast_scalar))+ }+ }+ }+}++/// Return a PhysicalExpression representing `expr` casted to+/// `cast_type`, if any casting is needed.+///+/// Note that such casts may lose type information+pub fn try_cast(+ expr: Arc<dyn PhysicalExpr>,+ input_schema: &Schema,+ cast_type: DataType,+) -> Result<Arc<dyn PhysicalExpr>> {+ let expr_type = expr.data_type(input_schema)?;+ if expr_type == cast_type {+ Ok(expr.clone())+ } else if can_cast_types(&expr_type, &cast_type) {+ Ok(Arc::new(TryCastExpr::new(expr, cast_type)))+ } else {+ Err(DataFusionError::Internal(format!(+ "Unsupported CAST from {:?} to {:?}",+ expr_type, cast_type+ )))+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::error::Result;+ use crate::physical_plan::expressions::col;+ use arrow::array::{StringArray, Time64NanosecondArray};+ use arrow::{+ array::{Array, Int32Array, Int64Array, TimestampNanosecondArray, UInt32Array},+ datatypes::*,+ };++ // runs an end-to-end test of physical type cast+ // 1. construct a record batch with a column "a" of type A+ // 2. construct a physical expression of CAST(a AS B)+ // 3. evaluate the expression+ // 4. verify that the resulting expression is of type B+ // 5. verify that the resulting values are downcastable and correct+ macro_rules! generic_test_cast {+ ($A_ARRAY:ident, $A_TYPE:expr, $A_VEC:expr, $TYPEARRAY:ident, $TYPE:expr, $VEC:expr) => {{+ let schema = Schema::new(vec![Field::new("a", $A_TYPE, false)]);+ let a = $A_ARRAY::from($A_VEC);+ let batch =+ RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(a)])?;++ // verify that we can construct the expression+ let expression = try_cast(col("a"), &schema, $TYPE)?;++ // verify that its display is correct+ assert_eq!(format!("CAST(a AS {:?})", $TYPE), format!("{}", expression));++ // verify that the expression's type is correct+ assert_eq!(expression.data_type(&schema)?, $TYPE);++ // compute+ let result = expression.evaluate(&batch)?.into_array(batch.num_rows());++ // verify that the array's data_type is correct+ assert_eq!(*result.data_type(), $TYPE);++ // verify that the len is correct+ assert_eq!(result.len(), $A_VEC.len());++ // verify that the data itself is downcastable+ let result = result+ .as_any()+ .downcast_ref::<$TYPEARRAY>()+ .expect("failed to downcast");++ // verify that the result itself is correct+ for (i, x) in $VEC.iter().enumerate() {+ match x {+ Some(x) => assert_eq!(result.value(i), *x),+ None => assert!(!result.is_valid(i)),+ }+ }+ }};+ }++ #[test]+ fn test_cast_i32_u32() -> Result<()> {+ generic_test_cast!(+ Int32Array,+ DataType::Int32,+ vec![1, 2, 3, 4, 5],+ UInt32Array,+ DataType::UInt32,+ vec![+ Some(1_u32),+ Some(2_u32),+ Some(3_u32),+ Some(4_u32),+ Some(5_u32)+ ]+ );+ Ok(())+ }++ #[test]+ fn test_cast_i32_utf8() -> Result<()> {+ generic_test_cast!(+ Int32Array,+ DataType::Int32,+ vec![1, 2, 3, 4, 5],+ StringArray,+ DataType::Utf8,+ vec![Some("1"), Some("2"), Some("3"), Some("4"), Some("5")]+ );+ Ok(())+ }++ #[test]+ fn test_try_cast_utf8_i32() -> Result<()> {+ generic_test_cast!(+ StringArray,+ DataType::Utf8,+ vec!["a", "2", "3", "b", "5"],+ Int32Array,+ DataType::Int32,+ vec![None, Some(2), Some(3), None, Some(5)]+ );+ Ok(())+ }++ #[allow(clippy::redundant_clone)]+ #[test]+ fn test_cast_i64_t64() -> Result<()> {+ let original = vec![1, 2, 3, 4, 5];+ let expected: Vec<Option<i64>> = original+ .iter()+ .map(|i| Some(Time64NanosecondArray::from(vec![*i]).value(0)))+ .collect();+ generic_test_cast!(+ Int64Array,+ DataType::Int64,+ original.clone(),+ TimestampNanosecondArray,+ DataType::Timestamp(TimeUnit::Nanosecond, None),+ expected+ );+ Ok(())+ }++ #[test]+ fn invalid_cast() {+ // 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 = try_cast(col("a"), &schema, DataType::LargeBinary);+ result.expect_err("expected Invalid CAST");+ }+}diff --git a/rust/datafusion/src/physical_plan/planner.rs b/rust/datafusion/src/physical_plan/planner.rsindex dd4184c5e1..a24ef2942e 100644--- a/rust/datafusion/src/physical_plan/planner.rs+++ b/rust/datafusion/src/physical_plan/planner.rs@@ -547,6 +547,11 @@ impl DefaultPhysicalPlanner {input_schema,data_type.clone(),),+ Expr::TryCast { expr, data_type } => expressions::try_cast(+ self.create_physical_expr(expr, input_schema, ctx_state)?,+ input_schema,+ data_type.clone(),+ ),Expr::Not(expr) => expressions::not(self.create_physical_expr(expr, input_schema, ctx_state)?,input_schema,@@ -799,7 +804,8 @@ mod tests {let plan = plan(&logical_plan)?;// verify that the plan correctly casts u8 to i64- let expected = "BinaryExpr { left: Column { name: \"c7\" }, op: Lt, right: CastExpr { expr: Literal { value: UInt8(5) }, cast_type: Int64 } }";+ // the cast here is implicit so has CastOptions with safe=true+ let expected = "BinaryExpr { left: Column { name: \"c7\" }, op: Lt, right: TryCastExpr { expr: Literal { value: UInt8(5) }, cast_type: Int64 } }";assert!(format!("{:?}", plan).contains(expected));Ok(())@@ -833,7 +839,8 @@ mod tests {let plan = plan(&logical_plan)?;// c12 is f64, c7 is u8 -> cast c7 to f64- let expected = "predicate: BinaryExpr { left: CastExpr { expr: Column { name: \"c7\" }, cast_type: Float64 }, op: Lt, right: Column { name: \"c12\" } }";+ // the cast here is implicit so has CastOptions with safe=true+ let expected = "predicate: BinaryExpr { left: TryCastExpr { expr: Column { name: \"c7\" }, cast_type: Float64 }, op: Lt, right: Column { name: \"c12\" } }";assert!(format!("{:?}", plan).contains(expected));Ok(())}@@ -958,7 +965,8 @@ mod tests {.build()?;let execution_plan = plan(&logical_plan)?;// verify that the plan correctly adds cast from Int64(1) to Utf8- let expected = "InListExpr { expr: Column { name: \"c1\" }, list: [Literal { value: Utf8(\"a\") }, CastExpr { expr: Literal { value: Int64(1) }, cast_type: Utf8 }], negated: false }";+ let expected = "InListExpr { expr: Column { name: \"c1\" }, list: [Literal { value: Utf8(\"a\") }, CastExpr { expr: Literal { value: Int64(1) }, cast_type: Utf8, cast_options: CastOptions { safe: false } }], negated: false }";+ println!("{:?}", execution_plan);assert!(format!("{:?}", execution_plan).contains(expected));// expression: "a in (true, 'a')"diff --git a/rust/datafusion/src/physical_plan/type_coercion.rs b/rust/datafusion/src/physical_plan/type_coercion.rsindex ae920cb870..24b51ba606 100644--- a/rust/datafusion/src/physical_plan/type_coercion.rs+++ b/rust/datafusion/src/physical_plan/type_coercion.rs@@ -35,7 +35,7 @@ use arrow::datatypes::{DataType, Schema, TimeUnit};use super::{functions::Signature, PhysicalExpr};use crate::error::{DataFusionError, Result};-use crate::physical_plan::expressions::cast;+use crate::physical_plan::expressions::try_cast;/// Returns `expressions` coerced to types compatible with/// `signature`, if possible.@@ -56,7 +56,7 @@ pub fn coerce(expressions.iter().enumerate()- .map(|(i, expr)| cast(expr.clone(), &schema, new_types[i].clone()))+ .map(|(i, expr)| try_cast(expr.clone(), &schema, new_types[i].clone())).collect::<Result<Vec<_>>>()}@@ -260,7 +260,7 @@ mod tests {let expressions = |t: Vec<DataType>, schema| -> Result<Vec<_>> {t.iter().enumerate()- .map(|(i, t)| cast(col(&format!("c{}", i)), &schema, t.clone()))+ .map(|(i, t)| try_cast(col(&format!("c{}", i)), &schema, t.clone())).collect::<Result<Vec<_>>>()};diff --git a/rust/datafusion/src/sql/planner.rs b/rust/datafusion/src/sql/planner.rsindex 9c8a800af1..f3ea7c9e34 100644--- a/rust/datafusion/src/sql/planner.rs+++ b/rust/datafusion/src/sql/planner.rs@@ -926,6 +926,14 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {data_type: convert_data_type(data_type)?,}),+ SQLExpr::TryCast {+ ref expr,+ ref data_type,+ } => Ok(Expr::TryCast {+ expr: Box::new(self.sql_expr_to_logical_expr(&expr)?),+ data_type: convert_data_type(data_type)?,+ }),+SQLExpr::TypedString {ref data_type,ref value,diff --git a/rust/datafusion/src/sql/utils.rs b/rust/datafusion/src/sql/utils.rsindex ffcb772cd0..f41643d2ab 100644--- a/rust/datafusion/src/sql/utils.rs+++ b/rust/datafusion/src/sql/utils.rs@@ -319,6 +319,13 @@ whereexpr: Box::new(clone_with_replacement(&**nested_expr, replacement_fn)?),data_type: data_type.clone(),}),+ Expr::TryCast {+ expr: nested_expr,+ data_type,+ } => Ok(Expr::TryCast {+ expr: Box::new(clone_with_replacement(&**nested_expr, replacement_fn)?),+ data_type: data_type.clone(),+ }),Expr::Sort {expr: nested_expr,asc,@@ -328,7 +335,6 @@ whereasc: *asc,nulls_first: *nulls_first,}),-Expr::Column(_) | Expr::Literal(_) | Expr::ScalarVariable(_) => {Ok(expr.clone())}diff --git a/rust/datafusion/tests/sql.rs b/rust/datafusion/tests/sql.rsindex 5f3bc30b2c..e92bf5593f 100644--- a/rust/datafusion/tests/sql.rs+++ b/rust/datafusion/tests/sql.rs@@ -32,7 +32,7 @@ use arrow::{};use datafusion::execution::context::ExecutionContext;-use datafusion::logical_plan::{LogicalPlan, ToDFSchema};+use datafusion::logical_plan::LogicalPlan;use datafusion::prelude::create_udf;use datafusion::{datasource::{csv::CsvReadOptions, MemTable},@@ -1530,16 +1530,11 @@ async fn execute(ctx: &mut ExecutionContext, sql: &str) -> Vec<Vec<String>> {let msg = format!("Creating physical plan for '{}': {:?}", sql, plan);let plan = ctx.create_physical_plan(&plan).expect(&msg);- let physical_schema = plan.schema();let msg = format!("Executing physical plan for '{}': {:?}", sql, plan);let results = collect(plan).await.expect(&msg);assert_eq!(logical_schema.as_ref(), optimized_logical_schema.as_ref());- assert_eq!(- logical_schema.as_ref(),- &physical_schema.to_dfschema().unwrap()- );result_vec(&results)}@@ -2583,7 +2578,7 @@ async fn in_list_array() -> Result<()> {,c1 IN ('x', 'y') AS utf8_in_false,c1 NOT IN ('x', 'y') AS utf8_not_in_true,c1 NOT IN ('a', 'c') AS utf8_not_in_false- ,CAST(CAST(c1 AS int) AS varchar) IN ('a', 'c') AS utf8_in_null+ ,NULL IN ('a', 'c') AS utf8_in_nullFROM aggregate_test_100 WHERE c12 < 0.05";let actual = execute(&mut ctx, sql).await;let expected = vec![@@ -2662,3 +2657,35 @@ async fn invalid_qualified_table_references() -> Result<()> {}Ok(())}++#[tokio::test]+async fn test_cast_expressions() -> Result<()> {+ test_expression!("CAST('0' AS INT)", "0");+ test_expression!("CAST(NULL AS INT)", "NULL");+ test_expression!("TRY_CAST('0' AS INT)", "0");+ test_expression!("TRY_CAST('x' AS INT)", "NULL");+ Ok(())+}++#[tokio::test]+async fn test_cast_expressions_error() -> Result<()> {+ // sin(utf8) should error+ let mut ctx = create_ctx()?;+ register_aggregate_csv(&mut ctx)?;+ let sql = "SELECT CAST(c1 AS INT) FROM aggregate_test_100";+ let plan = ctx.create_logical_plan(&sql).unwrap();+ let plan = ctx.optimize(&plan).unwrap();+ let plan = ctx.create_physical_plan(&plan).unwrap();+ let result = collect(plan).await;++ match result {+ Ok(_) => panic!("expected error"),+ Err(e) => {+ assert!(e.to_string().contains(+ "Cast error: Cannot cast string 'c' to value of arrow::datatypes::types::Int32Type type"+ ))+ }+ }++ Ok(())+}