Skip to content

Apache DataFusion SQL Query Engine

Refactor Expr::TryCast to use a struct (#4642)

ygf114ec559d1db46
diff --git a/datafusion/core/src/physical_optimizer/pruning.rs b/datafusion/core/src/physical_optimizer/pruning.rs
index df616574ec..2645b15ee0 100644
--- a/datafusion/core/src/physical_optimizer/pruning.rs
+++ b/datafusion/core/src/physical_optimizer/pruning.rs
@@ -46,7 +46,7 @@ use arrow::{
record_batch::RecordBatch,
};
use datafusion_common::{downcast_value, ScalarValue};
-use datafusion_expr::expr::{BinaryExpr, Cast};
+use datafusion_expr::expr::{BinaryExpr, Cast, TryCast};
use datafusion_expr::expr_rewriter::{ExprRewritable, ExprRewriter};
use datafusion_expr::{binary_expr, cast, try_cast, ExprSchemable};
use datafusion_physical_expr::create_physical_expr;
@@ -551,7 +551,7 @@ fn rewrite_expr_to_prunable(
Ok((cast(left, data_type.clone()), op, right))
}
// `try_cast(col) op lit()`
- Expr::TryCast { expr, data_type } => {
+ Expr::TryCast(TryCast { expr, data_type }) => {
let from_type = expr.get_type(&schema)?;
verify_support_type_for_prune(&from_type, data_type)?;
let (left, op, right) =
diff --git a/datafusion/core/src/physical_plan/planner.rs b/datafusion/core/src/physical_plan/planner.rs
index 52113dbfe0..d0d74c54f1 100644
--- a/datafusion/core/src/physical_plan/planner.rs
+++ b/datafusion/core/src/physical_plan/planner.rs
@@ -63,7 +63,7 @@ use arrow::datatypes::{Schema, SchemaRef};
use async_trait::async_trait;
use datafusion_common::{DFSchema, ScalarValue};
use datafusion_expr::expr::{
- Between, BinaryExpr, Cast, GetIndexedField, GroupingSet, Like,
+ Between, BinaryExpr, Cast, GetIndexedField, GroupingSet, Like, TryCast,
};
use datafusion_expr::expr_rewriter::unnormalize_cols;
use datafusion_expr::utils::expand_wildcard;
@@ -135,7 +135,7 @@ fn create_physical_name(e: &Expr, is_first_expr: bool) -> Result<String> {
// CAST does not change the expression name
create_physical_name(expr, false)
}
- Expr::TryCast { expr, .. } => {
+ Expr::TryCast(TryCast { expr, .. }) => {
// CAST does not change the expression name
create_physical_name(expr, false)
}
diff --git a/datafusion/expr/src/expr.rs b/datafusion/expr/src/expr.rs
index c37a99fa32..168e2f37d5 100644
--- a/datafusion/expr/src/expr.rs
+++ b/datafusion/expr/src/expr.rs
@@ -148,12 +148,7 @@ pub enum Expr {
Cast(Cast),
/// 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,
- },
+ TryCast(TryCast),
/// A sort expression, that can be used to sort values.
Sort {
/// The expression to sort on
@@ -446,6 +441,22 @@ impl Cast {
}
}
+/// TryCast Expression
+#[derive(Clone, PartialEq, Eq, Hash)]
+pub struct TryCast {
+ /// The expression being cast
+ pub expr: Box<Expr>,
+ /// The `DataType` the expression will yield
+ pub data_type: DataType,
+}
+
+impl TryCast {
+ /// Create a new TryCast expression
+ pub fn new(expr: Box<Expr>, data_type: DataType) -> Self {
+ Self { expr, data_type }
+ }
+}
+
/// Grouping sets
/// See https://www.postgresql.org/docs/current/queries-table-expressions.html#QUERIES-GROUPING-SETS
/// for Postgres definition.
@@ -790,7 +801,7 @@ impl fmt::Debug for Expr {
Expr::Cast(Cast { expr, data_type }) => {
write!(f, "CAST({:?} AS {:?})", expr, data_type)
}
- Expr::TryCast { expr, data_type } => {
+ Expr::TryCast(TryCast { expr, data_type }) => {
write!(f, "TRY_CAST({:?} AS {:?})", expr, data_type)
}
Expr::Not(expr) => write!(f, "NOT {:?}", expr),
@@ -1142,7 +1153,7 @@ fn create_name(e: &Expr) -> Result<String> {
// CAST does not change the expression name
create_name(expr)
}
- Expr::TryCast { expr, .. } => {
+ Expr::TryCast(TryCast { expr, .. }) => {
// CAST does not change the expression name
create_name(expr)
}
diff --git a/datafusion/expr/src/expr_fn.rs b/datafusion/expr/src/expr_fn.rs
index 4ecc94f74c..d305013f1a 100644
--- a/datafusion/expr/src/expr_fn.rs
+++ b/datafusion/expr/src/expr_fn.rs
@@ -17,7 +17,7 @@
//! Functions for creating logical expressions
-use crate::expr::{BinaryExpr, Cast, GroupingSet};
+use crate::expr::{BinaryExpr, Cast, GroupingSet, TryCast};
use crate::{
aggregate_function, built_in_function, conditional_expressions::CaseBuilder,
logical_plan::Subquery, AccumulatorFunctionImplementation, AggregateUDF,
@@ -270,10 +270,7 @@ pub fn cast(expr: Expr, data_type: DataType) -> Expr {
/// Create a try cast expression
pub fn try_cast(expr: Expr, data_type: DataType) -> Expr {
- Expr::TryCast {
- expr: Box::new(expr),
- data_type,
- }
+ Expr::TryCast(TryCast::new(Box::new(expr), data_type))
}
/// Create is null expression
diff --git a/datafusion/expr/src/expr_rewriter.rs b/datafusion/expr/src/expr_rewriter.rs
index b107d59176..09432155d1 100644
--- a/datafusion/expr/src/expr_rewriter.rs
+++ b/datafusion/expr/src/expr_rewriter.rs
@@ -17,7 +17,9 @@
//! Expression rewriter
-use crate::expr::{Between, BinaryExpr, Case, Cast, GetIndexedField, GroupingSet, Like};
+use crate::expr::{
+ Between, BinaryExpr, Case, Cast, GetIndexedField, GroupingSet, Like, TryCast,
+};
use crate::logical_plan::{Aggregate, Projection};
use crate::utils::{from_plan, grouping_set_to_exprlist};
use crate::{Expr, ExprSchemable, LogicalPlan};
@@ -206,10 +208,9 @@ impl ExprRewritable for Expr {
Expr::Cast(Cast { expr, data_type }) => {
Expr::Cast(Cast::new(rewrite_boxed(expr, rewriter)?, data_type))
}
- Expr::TryCast { expr, data_type } => Expr::TryCast {
- expr: rewrite_boxed(expr, rewriter)?,
- data_type,
- },
+ Expr::TryCast(TryCast { expr, data_type }) => {
+ Expr::TryCast(TryCast::new(rewrite_boxed(expr, rewriter)?, data_type))
+ }
Expr::Sort {
expr,
asc,
diff --git a/datafusion/expr/src/expr_schema.rs b/datafusion/expr/src/expr_schema.rs
index ae516001bc..4696e881c7 100644
--- a/datafusion/expr/src/expr_schema.rs
+++ b/datafusion/expr/src/expr_schema.rs
@@ -16,7 +16,7 @@
// under the License.
use super::{Between, Expr, Like};
-use crate::expr::{BinaryExpr, Cast, GetIndexedField};
+use crate::expr::{BinaryExpr, Cast, GetIndexedField, TryCast};
use crate::field_util::get_indexed_field;
use crate::type_coercion::binary::binary_operator_data_type;
use crate::{aggregate_function, function, window_function};
@@ -61,9 +61,8 @@ impl ExprSchemable for Expr {
Expr::ScalarVariable(ty, _) => Ok(ty.clone()),
Expr::Literal(l) => Ok(l.get_datatype()),
Expr::Case(case) => case.when_then_expr[0].1.get_type(schema),
- Expr::Cast(Cast { data_type, .. }) | Expr::TryCast { data_type, .. } => {
- Ok(data_type.clone())
- }
+ Expr::Cast(Cast { data_type, .. })
+ | Expr::TryCast(TryCast { data_type, .. }) => Ok(data_type.clone()),
Expr::ScalarUDF { fun, args } => {
let data_types = args
.iter()
diff --git a/datafusion/expr/src/expr_visitor.rs b/datafusion/expr/src/expr_visitor.rs
index b5c6c68025..a38f29ed6b 100644
--- a/datafusion/expr/src/expr_visitor.rs
+++ b/datafusion/expr/src/expr_visitor.rs
@@ -19,7 +19,7 @@
use crate::expr::Cast;
use crate::{
- expr::{BinaryExpr, GroupingSet},
+ expr::{BinaryExpr, GroupingSet, TryCast},
Between, Expr, GetIndexedField, Like,
};
use datafusion_common::Result;
@@ -110,7 +110,7 @@ impl ExprVisitable for Expr {
| Expr::IsNull(expr)
| Expr::Negative(expr)
| Expr::Cast(Cast { expr, .. })
- | Expr::TryCast { expr, .. }
+ | Expr::TryCast(TryCast { expr, .. })
| Expr::Sort { expr, .. }
| Expr::InSubquery { expr, .. } => expr.accept(visitor),
Expr::GetIndexedField(GetIndexedField { expr, .. }) => expr.accept(visitor),
diff --git a/datafusion/expr/src/lib.rs b/datafusion/expr/src/lib.rs
index eb943cf3ea..0ba332d141 100644
--- a/datafusion/expr/src/lib.rs
+++ b/datafusion/expr/src/lib.rs
@@ -57,7 +57,7 @@ pub use aggregate_function::AggregateFunction;
pub use built_in_function::BuiltinScalarFunction;
pub use columnar_value::ColumnarValue;
pub use expr::{
- Between, BinaryExpr, Case, Cast, Expr, GetIndexedField, GroupingSet, Like,
+ Between, BinaryExpr, Case, Cast, Expr, GetIndexedField, GroupingSet, Like, TryCast,
};
pub use expr_fn::*;
pub use expr_schema::ExprSchemable;
diff --git a/datafusion/expr/src/logical_plan/builder.rs b/datafusion/expr/src/logical_plan/builder.rs
index 1c3b813f70..0b69d01571 100644
--- a/datafusion/expr/src/logical_plan/builder.rs
+++ b/datafusion/expr/src/logical_plan/builder.rs
@@ -1016,15 +1016,7 @@ pub fn wrap_projection_for_join_if_necessary(
//
// then a and cast(a as int) will use the same field name - `a` in projection schema.
// https://github.com/apache/arrow-datafusion/issues/4478
- if matches!(key, Expr::Cast(_))
- || matches!(
- key,
- Expr::TryCast {
- expr: _,
- data_type: _
- }
- )
- {
+ if matches!(key, Expr::Cast(_)) || matches!(key, Expr::TryCast(_)) {
let alias = format!("{:?}", key);
key.clone().alias(alias)
} else {
diff --git a/datafusion/expr/src/utils.rs b/datafusion/expr/src/utils.rs
index e920915c08..491693d936 100644
--- a/datafusion/expr/src/utils.rs
+++ b/datafusion/expr/src/utils.rs
@@ -25,7 +25,9 @@ use crate::logical_plan::{
Limit, Partitioning, Prepare, Projection, Repartition, Sort, Subquery, SubqueryAlias,
Union, Values, Window,
};
-use crate::{Cast, Expr, ExprSchemable, LogicalPlan, LogicalPlanBuilder, TableScan};
+use crate::{
+ Cast, Expr, ExprSchemable, LogicalPlan, LogicalPlanBuilder, TableScan, TryCast,
+};
use arrow::datatypes::{DataType, TimeUnit};
use datafusion_common::{
Column, DFField, DFSchema, DFSchemaRef, DataFusionError, Result, ScalarValue,
@@ -694,10 +696,10 @@ pub fn columnize_expr(e: Expr, input_schema: &DFSchema) -> Expr {
expr: Box::new(columnize_expr(*expr, input_schema)),
data_type,
}),
- Expr::TryCast { expr, data_type } => Expr::TryCast {
- expr: Box::new(columnize_expr(*expr, input_schema)),
+ Expr::TryCast(TryCast { expr, data_type }) => Expr::TryCast(TryCast::new(
+ Box::new(columnize_expr(*expr, input_schema)),
data_type,
- },
+ )),
Expr::ScalarSubquery(_) => e.clone(),
_ => match e.display_name() {
Ok(name) => match input_schema.field_with_unqualified_name(&name) {
diff --git a/datafusion/optimizer/src/eliminate_outer_join.rs b/datafusion/optimizer/src/eliminate_outer_join.rs
index a78d61dace..ffe270cdbf 100644
--- a/datafusion/optimizer/src/eliminate_outer_join.rs
+++ b/datafusion/optimizer/src/eliminate_outer_join.rs
@@ -19,13 +19,12 @@
use crate::{utils, OptimizerConfig, OptimizerRule};
use datafusion_common::{Column, DFSchema, Result};
use datafusion_expr::{
- expr::BinaryExpr,
logical_plan::{Join, JoinType, LogicalPlan},
utils::from_plan,
};
use datafusion_expr::{Expr, Operator};
-use datafusion_expr::expr::Cast;
+use datafusion_expr::expr::{BinaryExpr, Cast, TryCast};
use std::sync::Arc;
#[derive(Default)]
@@ -294,7 +293,7 @@ fn extract_non_nullable_columns(
)
}
Expr::Cast(Cast { expr, data_type: _ })
- | Expr::TryCast { expr, data_type: _ } => extract_non_nullable_columns(
+ | Expr::TryCast(TryCast { expr, data_type: _ }) => extract_non_nullable_columns(
expr,
non_nullable_cols,
left_schema,
diff --git a/datafusion/optimizer/src/unwrap_cast_in_comparison.rs b/datafusion/optimizer/src/unwrap_cast_in_comparison.rs
index 5d02d085d1..0d6a1265cd 100644
--- a/datafusion/optimizer/src/unwrap_cast_in_comparison.rs
+++ b/datafusion/optimizer/src/unwrap_cast_in_comparison.rs
@@ -24,7 +24,7 @@ use arrow::datatypes::{
DataType, TimeUnit, MAX_DECIMAL_FOR_EACH_PRECISION, MIN_DECIMAL_FOR_EACH_PRECISION,
};
use datafusion_common::{DFSchema, DFSchemaRef, DataFusionError, Result, ScalarValue};
-use datafusion_expr::expr::{BinaryExpr, Cast};
+use datafusion_expr::expr::{BinaryExpr, Cast, TryCast};
use datafusion_expr::expr_rewriter::{ExprRewriter, RewriteRecursion};
use datafusion_expr::utils::from_plan;
use datafusion_expr::{
@@ -152,7 +152,8 @@ impl ExprRewriter for UnwrapCastExprRewriter {
match (&left, &right) {
(
Expr::Literal(left_lit_value),
- Expr::TryCast { expr, .. } | Expr::Cast(Cast { expr, .. }),
+ Expr::TryCast(TryCast { expr, .. })
+ | Expr::Cast(Cast { expr, .. }),
) => {
// if the left_lit_value can be casted to the type of expr
// we need to unwrap the cast for cast/try_cast expr, and add cast to the literal
@@ -169,7 +170,8 @@ impl ExprRewriter for UnwrapCastExprRewriter {
}
}
(
- Expr::TryCast { expr, .. } | Expr::Cast(Cast { expr, .. }),
+ Expr::TryCast(TryCast { expr, .. })
+ | Expr::Cast(Cast { expr, .. }),
Expr::Literal(right_lit_value),
) => {
// if the right_lit_value can be casted to the type of expr
@@ -202,10 +204,10 @@ impl ExprRewriter for UnwrapCastExprRewriter {
negated,
} => {
if let Some(
- Expr::TryCast {
+ Expr::TryCast(TryCast {
expr: internal_left_expr,
..
- }
+ })
| Expr::Cast(Cast {
expr: internal_left_expr,
..
diff --git a/datafusion/physical-expr/src/planner.rs b/datafusion/physical-expr/src/planner.rs
index 4442b52a26..d5e2c05e7e 100644
--- a/datafusion/physical-expr/src/planner.rs
+++ b/datafusion/physical-expr/src/planner.rs
@@ -29,7 +29,7 @@ use arrow::datatypes::{DataType, Schema};
use datafusion_common::{DFSchema, DataFusionError, Result, ScalarValue};
use datafusion_expr::expr::Cast;
use datafusion_expr::{
- binary_expr, Between, BinaryExpr, Expr, GetIndexedField, Like, Operator,
+ binary_expr, Between, BinaryExpr, Expr, GetIndexedField, Like, Operator, TryCast,
};
use std::sync::Arc;
@@ -303,7 +303,7 @@ pub fn create_physical_expr(
input_schema,
data_type.clone(),
),
- Expr::TryCast { expr, data_type } => expressions::try_cast(
+ Expr::TryCast(TryCast { expr, data_type }) => expressions::try_cast(
create_physical_expr(expr, input_dfschema, input_schema, execution_props)?,
input_schema,
data_type.clone(),
diff --git a/datafusion/proto/src/from_proto.rs b/datafusion/proto/src/from_proto.rs
index 106519ce23..ebe1870d33 100644
--- a/datafusion/proto/src/from_proto.rs
+++ b/datafusion/proto/src/from_proto.rs
@@ -32,7 +32,7 @@ use datafusion_common::{
Column, DFField, DFSchema, DFSchemaRef, DataFusionError, OwnedTableReference,
ScalarValue,
};
-use datafusion_expr::expr::{BinaryExpr, Cast};
+use datafusion_expr::expr::{BinaryExpr, Cast, TryCast};
use datafusion_expr::{
abs, acos, array, ascii, asin, atan, atan2, bit_length, btrim, ceil,
character_length, chr, coalesce, concat_expr, concat_ws_expr, cos, date_bin,
@@ -954,7 +954,7 @@ pub fn parse_expr(
ExprType::TryCast(cast) => {
let expr = Box::new(parse_required_expr(&cast.expr, registry, "expr")?);
let data_type = cast.arrow_type.as_ref().required("arrow_type")?;
- Ok(Expr::TryCast { expr, data_type })
+ Ok(Expr::TryCast(TryCast::new(expr, data_type)))
}
ExprType::Sort(sort) => Ok(Expr::Sort {
expr: Box::new(parse_required_expr(&sort.expr, registry, "expr")?),
diff --git a/datafusion/sql/src/planner.rs b/datafusion/sql/src/planner.rs
index 6cf279eda4..13a4fb0a70 100644
--- a/datafusion/sql/src/planner.rs
+++ b/datafusion/sql/src/planner.rs
@@ -42,7 +42,9 @@ use datafusion_common::{
field_not_found, Column, DFSchema, DFSchemaRef, DataFusionError, Result, ScalarValue,
};
use datafusion_common::{OwnedTableReference, TableReference};
-use datafusion_expr::expr::{Between, BinaryExpr, Case, Cast, GroupingSet, Like};
+use datafusion_expr::expr::{
+ Between, BinaryExpr, Case, Cast, GroupingSet, Like, TryCast,
+};
use datafusion_expr::expr_rewriter::normalize_col;
use datafusion_expr::expr_rewriter::normalize_col_with_schemas;
use datafusion_expr::logical_plan::builder::{
@@ -2060,10 +2062,10 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {
SQLExpr::TryCast {
expr,
data_type,
- } => Ok(Expr::TryCast {
- expr: Box::new(self.sql_expr_to_logical_expr(*expr, schema, planner_context)?),
- data_type: self.convert_data_type(&data_type)?,
- }),
+ } => Ok(Expr::TryCast(TryCast::new(
+ Box::new(self.sql_expr_to_logical_expr(*expr, schema, planner_context)?),
+ self.convert_data_type(&data_type)?,
+ ))),
SQLExpr::TypedString {
data_type,
diff --git a/datafusion/sql/src/utils.rs b/datafusion/sql/src/utils.rs
index f9624b4009..1e712597d5 100644
--- a/datafusion/sql/src/utils.rs
+++ b/datafusion/sql/src/utils.rs
@@ -26,7 +26,7 @@ use datafusion_expr::expr::{
Between, BinaryExpr, Case, GetIndexedField, GroupingSet, Like,
};
use datafusion_expr::utils::{expr_as_column_expr, find_column_exprs};
-use datafusion_expr::{Expr, LogicalPlan};
+use datafusion_expr::{Expr, LogicalPlan, TryCast};
use std::collections::HashMap;
/// Make a best-effort attempt at resolving all columns in the expression tree
@@ -345,13 +345,13 @@ where
Box::new(clone_with_replacement(expr, replacement_fn)?),
data_type.clone(),
))),
- Expr::TryCast {
+ Expr::TryCast(TryCast {
expr: nested_expr,
data_type,
- } => Ok(Expr::TryCast {
- expr: Box::new(clone_with_replacement(nested_expr, replacement_fn)?),
- data_type: data_type.clone(),
- }),
+ }) => Ok(Expr::TryCast(TryCast::new(
+ Box::new(clone_with_replacement(nested_expr, replacement_fn)?),
+ data_type.clone(),
+ ))),
Expr::Sort {
expr: nested_expr,
asc,