Apache DataFusion SQL Query Engine
Simplify comparisons and binary operations involving NULL (#17088)
Piotr Findeisen876b504cb077
diff --git a/datafusion/expr-common/src/operator.rs b/datafusion/expr-common/src/operator.rsindex bfc5ee9a36..33512b0c35 100644--- a/datafusion/expr-common/src/operator.rs+++ b/datafusion/expr-common/src/operator.rs@@ -328,6 +328,60 @@ impl Operator {Operator::Multiply | Operator::Divide | Operator::Modulo => 45,}}++ /// Returns true if the `Expr::BinaryOperator` with this operator+ /// is guaranteed to return null if either side is null.+ pub fn returns_null_on_null(&self) -> bool {+ match self {+ Operator::Eq+ | Operator::NotEq+ | Operator::Lt+ | Operator::LtEq+ | Operator::Gt+ | Operator::GtEq+ | Operator::Plus+ | Operator::Minus+ | Operator::Multiply+ | Operator::Divide+ | Operator::Modulo+ | Operator::RegexMatch+ | Operator::RegexIMatch+ | Operator::RegexNotMatch+ | Operator::RegexNotIMatch+ | Operator::LikeMatch+ | Operator::ILikeMatch+ | Operator::NotLikeMatch+ | Operator::NotILikeMatch+ | Operator::BitwiseAnd+ | Operator::BitwiseOr+ | Operator::BitwiseXor+ | Operator::BitwiseShiftRight+ | Operator::BitwiseShiftLeft+ | Operator::AtArrow+ | Operator::ArrowAt+ | Operator::Arrow+ | Operator::LongArrow+ | Operator::HashArrow+ | Operator::HashLongArrow+ | Operator::AtAt+ | Operator::IntegerDivide+ | Operator::HashMinus+ | Operator::AtQuestion+ | Operator::Question+ | Operator::QuestionAnd+ | Operator::QuestionPipe => true,++ // E.g. `TRUE OR NULL` is `TRUE`+ Operator::Or+ // E.g. `FALSE AND NULL` is `FALSE`+ | Operator::And+ // IS DISTINCT FROM and IS NOT DISTINCT FROM always return a TRUE/FALSE value, never NULL+ | Operator::IsDistinctFrom+ | Operator::IsNotDistinctFrom+ // DataFusion string concatenation operator treats NULL as an empty string+ | Operator::StringConcat => false,+ }+ }}impl fmt::Display for Operator {diff --git a/datafusion/optimizer/src/simplify_expressions/expr_simplifier.rs b/datafusion/optimizer/src/simplify_expressions/expr_simplifier.rsindex 0a68734d32..128e84018c 100644--- a/datafusion/optimizer/src/simplify_expressions/expr_simplifier.rs+++ b/datafusion/optimizer/src/simplify_expressions/expr_simplifier.rs@@ -772,6 +772,29 @@ impl<S: SimplifyInfo> TreeNodeRewriter for Simplifier<'_, S> {let info = self.info;Ok(match expr {+ // `value op NULL` -> `NULL`+ // `NULL op value` -> `NULL`+ // except for few operators that can return non-null value even when one of the operands is NULL+ ref expr @ Expr::BinaryExpr(BinaryExpr {+ ref left,+ ref op,+ ref right,+ }) if op.returns_null_on_null()+ && (is_null(left.as_ref()) || is_null(right.as_ref())) =>+ {+ Transformed::yes(Expr::Literal(+ ScalarValue::try_new_null(&info.get_data_type(expr)?)?,+ None,+ ))+ }++ // `NULL {AND, OR} NULL` -> `NULL`+ Expr::BinaryExpr(BinaryExpr {+ left,+ op: And | Or,+ right,+ }) if is_null(&left) && is_null(&right) => Transformed::yes(lit_bool_null()),+//// Rules for Eq//@@ -1047,14 +1070,6 @@ impl<S: SimplifyInfo> TreeNodeRewriter for Simplifier<'_, S> {}) if is_one(&right) => {simplify_right_is_one_case(info, left, &Multiply, &right)?}- // A * null --> null- Expr::BinaryExpr(BinaryExpr {- left,- op: Multiply,- right,- }) if is_null(&right) => {- simplify_right_is_null_case(info, &left, &Multiply, right)?- }// 1 * A --> AExpr::BinaryExpr(BinaryExpr {left,@@ -1064,14 +1079,6 @@ impl<S: SimplifyInfo> TreeNodeRewriter for Simplifier<'_, S> {// 1 * A is equivalent to A * 1simplify_right_is_one_case(info, right, &Multiply, &left)?}- // null * A --> null- Expr::BinaryExpr(BinaryExpr {- left,- op: Multiply,- right,- }) if is_null(&left) => {- simplify_right_is_null_case(info, &right, &Multiply, left)?- }// A * 0 --> 0 (if A is not null and not floating, since NAN * 0 -> NAN)Expr::BinaryExpr(BinaryExpr {@@ -1108,37 +1115,11 @@ impl<S: SimplifyInfo> TreeNodeRewriter for Simplifier<'_, S> {}) if is_one(&right) => {simplify_right_is_one_case(info, left, &Divide, &right)?}- // A / null --> null- Expr::BinaryExpr(BinaryExpr {- left,- op: Divide,- right,- }) if is_null(&right) => {- simplify_right_is_null_case(info, &left, &Divide, right)?- }- // null / A --> null- Expr::BinaryExpr(BinaryExpr {- left,- op: Divide,- right,- }) if is_null(&left) => simplify_null_div_other_case(info, left, &right)?,//// Rules for Modulo//- // A % null --> null- Expr::BinaryExpr(BinaryExpr {- left: _,- op: Modulo,- right,- }) if is_null(&right) => Transformed::yes(*right),- // null % A --> null- Expr::BinaryExpr(BinaryExpr {- left,- op: Modulo,- right: _,- }) if is_null(&left) => Transformed::yes(*left),// A % 1 --> 0 (if A is not nullable and not floating, since NAN % 1 --> NAN)Expr::BinaryExpr(BinaryExpr {left,@@ -1158,20 +1139,6 @@ impl<S: SimplifyInfo> TreeNodeRewriter for Simplifier<'_, S> {// Rules for BitwiseAnd//- // A & null -> null- Expr::BinaryExpr(BinaryExpr {- left: _,- op: BitwiseAnd,- right,- }) if is_null(&right) => Transformed::yes(*right),-- // null & A -> null- Expr::BinaryExpr(BinaryExpr {- left,- op: BitwiseAnd,- right: _,- }) if is_null(&left) => Transformed::yes(*left),-// A & 0 -> 0 (if A not nullable)Expr::BinaryExpr(BinaryExpr {left,@@ -1246,20 +1213,6 @@ impl<S: SimplifyInfo> TreeNodeRewriter for Simplifier<'_, S> {// Rules for BitwiseOr//- // A | null -> null- Expr::BinaryExpr(BinaryExpr {- left: _,- op: BitwiseOr,- right,- }) if is_null(&right) => Transformed::yes(*right),-- // null | A -> null- Expr::BinaryExpr(BinaryExpr {- left,- op: BitwiseOr,- right: _,- }) if is_null(&left) => Transformed::yes(*left),-// A | 0 -> A (even if A is null)Expr::BinaryExpr(BinaryExpr {left,@@ -1334,20 +1287,6 @@ impl<S: SimplifyInfo> TreeNodeRewriter for Simplifier<'_, S> {// Rules for BitwiseXor//- // A ^ null -> null- Expr::BinaryExpr(BinaryExpr {- left: _,- op: BitwiseXor,- right,- }) if is_null(&right) => Transformed::yes(*right),-- // null ^ A -> null- Expr::BinaryExpr(BinaryExpr {- left,- op: BitwiseXor,- right: _,- }) if is_null(&left) => Transformed::yes(*left),-// A ^ 0 -> A (if A not nullable)Expr::BinaryExpr(BinaryExpr {left,@@ -1424,20 +1363,6 @@ impl<S: SimplifyInfo> TreeNodeRewriter for Simplifier<'_, S> {// Rules for BitwiseShiftRight//- // A >> null -> null- Expr::BinaryExpr(BinaryExpr {- left: _,- op: BitwiseShiftRight,- right,- }) if is_null(&right) => Transformed::yes(*right),-- // null >> A -> null- Expr::BinaryExpr(BinaryExpr {- left,- op: BitwiseShiftRight,- right: _,- }) if is_null(&left) => Transformed::yes(*left),-// A >> 0 -> A (even if A is null)Expr::BinaryExpr(BinaryExpr {left,@@ -1449,20 +1374,6 @@ impl<S: SimplifyInfo> TreeNodeRewriter for Simplifier<'_, S> {// Rules for BitwiseShiftRight//- // A << null -> null- Expr::BinaryExpr(BinaryExpr {- left: _,- op: BitwiseShiftLeft,- right,- }) if is_null(&right) => Transformed::yes(*right),-- // null << A -> null- Expr::BinaryExpr(BinaryExpr {- left,- op: BitwiseShiftLeft,- right: _,- }) if is_null(&left) => Transformed::yes(*left),-// A << 0 -> A (even if A is null)Expr::BinaryExpr(BinaryExpr {left,@@ -2110,58 +2021,6 @@ fn simplify_right_is_one_case<S: SimplifyInfo>(}}-// A * null -> null-// A / null -> null-//-// Move this function body out of the large match branch avoid stack overflow-fn simplify_right_is_null_case<S: SimplifyInfo>(- info: &S,- left: &Expr,- op: &Operator,- right: Box<Expr>,-) -> Result<Transformed<Expr>> {- // Check if resulting type would be different due to coercion- let left_type = info.get_data_type(left)?;- let right_type = info.get_data_type(&right)?;- match BinaryTypeCoercer::new(&left_type, op, &right_type).get_result_type() {- Ok(result_type) => {- // Only cast if the types differ- if right_type != result_type {- Ok(Transformed::yes(Expr::Cast(Cast::new(right, result_type))))- } else {- Ok(Transformed::yes(*right))- }- }- Err(_) => Ok(Transformed::yes(*right)),- }-}--// null / A --> null-//-// Move this function body out of the large match branch avoid stack overflow-fn simplify_null_div_other_case<S: SimplifyInfo>(- info: &S,- left: Box<Expr>,- right: &Expr,-) -> Result<Transformed<Expr>> {- // Check if resulting type would be different due to coercion- let left_type = info.get_data_type(&left)?;- let right_type = info.get_data_type(right)?;- match BinaryTypeCoercer::new(&left_type, &Operator::Divide, &right_type)- .get_result_type()- {- Ok(result_type) => {- // Only cast if the types differ- if left_type != result_type {- Ok(Transformed::yes(Expr::Cast(Cast::new(left, result_type))))- } else {- Ok(Transformed::yes(*left))- }- }- Err(_) => Ok(Transformed::yes(*left)),- }-}-#[cfg(test)]mod tests {use super::*;@@ -2432,15 +2291,15 @@ mod tests {#[test]fn test_simplify_multiply_by_null() {- let null = lit(ScalarValue::Null);+ let null = lit(ScalarValue::Int64(None));// A * null --> null{- let expr = col("c2") * null.clone();+ let expr = col("c3") * null.clone();assert_eq!(simplify(expr), null);}// null * A --> null{- let expr = null.clone() * col("c2");+ let expr = null.clone() * col("c3");assert_eq!(simplify(expr), null);}}@@ -2496,14 +2355,14 @@ mod tests {#[test]fn test_simplify_divide_null() {// A / null --> null- let null = lit(ScalarValue::Null);+ let null = lit(ScalarValue::Int64(None));{- let expr = col("c1") / null.clone();+ let expr = col("c3") / null.clone();assert_eq!(simplify(expr), null);}// null / A --> null{- let expr = null.clone() / col("c1");+ let expr = null.clone() / col("c3");assert_eq!(simplify(expr), null);}}@@ -2519,15 +2378,15 @@ mod tests {#[test]fn test_simplify_modulo_by_null() {- let null = lit(ScalarValue::Null);+ let null = lit(ScalarValue::Int64(None));// A % null --> null{- let expr = col("c2") % null.clone();+ let expr = col("c3") % null.clone();assert_eq!(simplify(expr), null);}// null % A --> null{- let expr = null.clone() % col("c2");+ let expr = null.clone() % col("c3");assert_eq!(simplify(expr), null);}}@@ -2573,45 +2432,45 @@ mod tests {#[test]fn test_simplify_bitwise_xor_by_null() {- let null = lit(ScalarValue::Null);+ let null = lit(ScalarValue::Int64(None));// A ^ null --> null{- let expr = col("c2") ^ null.clone();+ let expr = col("c3") ^ null.clone();assert_eq!(simplify(expr), null);}// null ^ A --> null{- let expr = null.clone() ^ col("c2");+ let expr = null.clone() ^ col("c3");assert_eq!(simplify(expr), null);}}#[test]fn test_simplify_bitwise_shift_right_by_null() {- let null = lit(ScalarValue::Null);+ let null = lit(ScalarValue::Int64(None));// A >> null --> null{- let expr = col("c2") >> null.clone();+ let expr = col("c3") >> null.clone();assert_eq!(simplify(expr), null);}// null >> A --> null{- let expr = null.clone() >> col("c2");+ let expr = null.clone() >> col("c3");assert_eq!(simplify(expr), null);}}#[test]fn test_simplify_bitwise_shift_left_by_null() {- let null = lit(ScalarValue::Null);+ let null = lit(ScalarValue::Int64(None));// A << null --> null{- let expr = col("c2") << null.clone();+ let expr = col("c3") << null.clone();assert_eq!(simplify(expr), null);}// null << A --> null{- let expr = null.clone() << col("c2");+ let expr = null.clone() << col("c3");assert_eq!(simplify(expr), null);}}@@ -2678,15 +2537,15 @@ mod tests {#[test]fn test_simplify_bitwise_and_by_null() {- let null = lit(ScalarValue::Null);+ let null = Expr::Literal(ScalarValue::Int64(None), None);// A & null --> null{- let expr = col("c2") & null.clone();+ let expr = col("c3") & null.clone();assert_eq!(simplify(expr), null);}// null & A --> null{- let expr = null.clone() & col("c2");+ let expr = null.clone() & col("c3");assert_eq!(simplify(expr), null);}}diff --git a/datafusion/optimizer/src/simplify_expressions/unwrap_cast.rs b/datafusion/optimizer/src/simplify_expressions/unwrap_cast.rsindex 6e66e467a8..eef45b4c18 100644--- a/datafusion/optimizer/src/simplify_expressions/unwrap_cast.rs+++ b/datafusion/optimizer/src/simplify_expressions/unwrap_cast.rs@@ -297,9 +297,9 @@ mod tests {let expected = col("c2").eq(lit(16i64));assert_eq!(optimize_test(c2_eq_lit, &schema), expected);- // cast(c1, INT64) < INT64(NULL) => INT32(c1) < INT32(NULL)+ // cast(c1, INT64) < INT64(NULL) => NULLlet c1_lt_lit_null = cast(col("c1"), DataType::Int64).lt(null_i64());- let expected = col("c1").lt(null_i32());+ let expected = null_bool();assert_eq!(optimize_test(c1_lt_lit_null, &schema), expected);// cast(INT8(NULL), INT32) < INT32(12) => INT8(NULL) < INT8(12) => BOOL(NULL)@@ -317,9 +317,9 @@ mod tests {let expected = col("c1").not_eq(lit(123i32));assert_eq!(optimize_test(expr_input, &schema), expected);- // cast(c1, UTF8) = NULL => c1 = NULL+ // cast(c1, UTF8) = NULL => NULLlet expr_input = cast(col("c1"), DataType::Utf8).eq(lit(ScalarValue::Utf8(None)));- let expected = col("c1").eq(lit(ScalarValue::Int32(None)));+ let expected = null_bool();assert_eq!(optimize_test(expr_input, &schema), expected);}@@ -422,7 +422,7 @@ mod tests {// c3 < INT64(NULL)let c1_lt_lit_null = cast(col("c3"), DataType::Int64).lt(null_i64());- let expected = col("c3").lt(null_decimal(18, 2));+ let expected = null_bool();assert_eq!(optimize_test(c1_lt_lit_null, &schema), expected);// decimal to decimal@@ -653,10 +653,6 @@ mod tests {lit(ScalarValue::TimestampNanosecond(Some(ts), utc))}- fn null_decimal(precision: u8, scale: i8) -> Expr {- lit(ScalarValue::Decimal128(None, precision, scale))- }-fn timestamp_nano_none_type() -> DataType {DataType::Timestamp(TimeUnit::Nanosecond, None)}diff --git a/datafusion/sqllogictest/test_files/errors.slt b/datafusion/sqllogictest/test_files/errors.sltindex dc7a53adf8..1b4700c9bf 100644--- a/datafusion/sqllogictest/test_files/errors.slt+++ b/datafusion/sqllogictest/test_files/errors.slt@@ -168,8 +168,9 @@ CREATE TABLE tab0(col0 INTEGER, col1 INTEGER, col2 INTEGER);statement okINSERT INTO tab0 VALUES(83,0,38);-query error DataFusion error: Arrow error: Divide by zero error+query ISELECT DISTINCT - 84 FROM tab0 AS cor0 WHERE NOT + 96 / + col1 <= NULL GROUP BY col1, col0;+----statement okcreate table a(timestamp int, birthday int, ts int, tokens int, amp int, staamp int);diff --git a/datafusion/sqllogictest/test_files/parquet.slt b/datafusion/sqllogictest/test_files/parquet.sltindex ef99423c27..e722005bf0 100644--- a/datafusion/sqllogictest/test_files/parquet.slt+++ b/datafusion/sqllogictest/test_files/parquet.slt@@ -785,7 +785,7 @@ select v, k from t where (v between 1 and 2) or (v between 9999 and 10000) order9999 k-999910000 k-10000-# Updating the file should invalidate the cache. Otherwise, the following queries would fail+# Updating the file should invalidate the cache. Otherwise, the following queries would fail# (e.g., with "Arrow: Parquet argument error: External: incomplete frame").query ICOPY (@@ -862,4 +862,3 @@ select part, k, v from t order by kstatement okDROP TABLE t;-diff --git a/datafusion/sqllogictest/test_files/predicates.slt b/datafusion/sqllogictest/test_files/predicates.sltindex f4bf75c83c..f141a66fb5 100644--- a/datafusion/sqllogictest/test_files/predicates.slt+++ b/datafusion/sqllogictest/test_files/predicates.slt@@ -777,6 +777,52 @@ physical_plan16)--------------------RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=117)----------------------DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/core/tests/tpch-csv/part.csv]]}, projection=[p_partkey, p_brand], file_type=csv, has_header=true+# Simplification of a binary operator with a NULL value++statement ok+create table t(x int) as values (1), (2), (3);++query TT+EXPLAIN FORMAT INDENT SELECT x > NULL FROM t;+----+logical_plan+01)Projection: Boolean(NULL) AS t.x > NULL+02)--TableScan: t projection=[]+physical_plan+01)ProjectionExec: expr=[NULL as t.x > NULL]+02)--DataSourceExec: partitions=1, partition_sizes=[1]++query TT+EXPLAIN FORMAT INDENT SELECT * FROM t WHERE x > NULL;+----+logical_plan EmptyRelation+physical_plan EmptyExec++query TT+EXPLAIN FORMAT INDENT SELECT * FROM t WHERE x < 5 AND (10 * NULL < x);+----+logical_plan+01)Filter: t.x < Int32(5) AND Boolean(NULL)+02)--TableScan: t projection=[x]+physical_plan+01)CoalesceBatchesExec: target_batch_size=8192+02)--FilterExec: x@0 < 5 AND NULL+03)----DataSourceExec: partitions=1, partition_sizes=[1]++query TT+EXPLAIN FORMAT INDENT SELECT * FROM t WHERE x < 5 OR (10 * NULL < x);+----+logical_plan+01)Filter: t.x < Int32(5) OR Boolean(NULL)+02)--TableScan: t projection=[x]+physical_plan+01)CoalesceBatchesExec: target_batch_size=8192+02)--FilterExec: x@0 < 5 OR NULL+03)----DataSourceExec: partitions=1, partition_sizes=[1]++statement ok+drop table t;+# Inlist simplificationstatement okdiff --git a/datafusion/sqllogictest/test_files/spark/predicate/ilike.slt b/datafusion/sqllogictest/test_files/spark/predicate/ilike.sltindex 8a3170c158..68e8b1c59a 100644--- a/datafusion/sqllogictest/test_files/spark/predicate/ilike.slt+++ b/datafusion/sqllogictest/test_files/spark/predicate/ilike.slt@@ -38,7 +38,7 @@ SELECT ilike(arrow_cast('Spark', 'Utf8View'), arrow_cast('_Park', 'LargeUtf8'))----true-query B+query BSELECT ilike('Spark'::string, '_park'::string);----truediff --git a/datafusion/substrait/tests/cases/roundtrip_logical_plan.rs b/datafusion/substrait/tests/cases/roundtrip_logical_plan.rsindex bc7b2a07fe..5ec6663347 100644--- a/datafusion/substrait/tests/cases/roundtrip_logical_plan.rs+++ b/datafusion/substrait/tests/cases/roundtrip_logical_plan.rs@@ -348,7 +348,7 @@ async fn decimal_literal() -> Result<()> {#[tokio::test]async fn null_decimal_literal() -> Result<()> {- roundtrip("SELECT * FROM data WHERE b = NULL").await+ roundtrip("SELECT *, CAST(NULL AS decimal(10, 2)) FROM data").await}#[tokio::test]