Skip to content

Commit 18e4bf0

Browse files
committed
enhance: simplify x=x (apache#15387)
- if x is not nullable, x=x -> true - else, x=x -> x is NOT NULL
1 parent 1a39175 commit 18e4bf0

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

datafusion/optimizer/src/simplify_expressions/expr_simplifier.rs

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -760,6 +760,17 @@ impl<S: SimplifyInfo> TreeNodeRewriter for Simplifier<'_, S> {
760760
None => lit_bool_null(),
761761
})
762762
}
763+
// A = A --> A IS NOT NULL
764+
// A = A --> true (if A not nullable)
765+
Expr::BinaryExpr(BinaryExpr {
766+
left,
767+
op: Eq,
768+
right,
769+
}) if left == right => Transformed::yes(match !info.nullable(&right)? {
770+
true => lit(true),
771+
false => Expr::IsNotNull(left),
772+
}),
773+
763774
// Rules for NotEq
764775
//
765776

@@ -2152,6 +2163,17 @@ mod tests {
21522163
}
21532164
}
21542165

2166+
#[test]
2167+
fn test_simplify_eq_not_self() {
2168+
let expr_a = col("c2").eq(col("c2"));
2169+
let expr_b = col("c2_non_null").eq(col("c2_non_null"));
2170+
let expected_a = col("c2").is_not_null();
2171+
let expected_b = lit(true);
2172+
2173+
assert_eq!(simplify(expr_a), expected_a);
2174+
assert_eq!(simplify(expr_b), expected_b);
2175+
}
2176+
21552177
#[test]
21562178
fn test_simplify_or_true() {
21572179
let expr_a = col("c2").or(lit(true));

datafusion/sqllogictest/test_files/simplify_expr.slt

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,5 +63,16 @@ query T
6363
select b from t where b !~ '.*'
6464
----
6565

66+
query TT
67+
explain select * from t where a = a;
68+
----
69+
logical_plan
70+
01)Filter: t.a IS NOT NULL
71+
02)--TableScan: t projection=[a, b]
72+
physical_plan
73+
01)CoalesceBatchesExec: target_batch_size=8192
74+
02)--FilterExec: a@0 IS NOT NULL
75+
03)----DataSourceExec: partitions=1, partition_sizes=[1]
76+
6677
statement ok
6778
drop table t;

0 commit comments

Comments
 (0)