Skip to content

Commit 5a03823

Browse files
adriangbfindepi
authored andcommitted
Simplify EXPR LIKE 'constant' to expr = 'constant'
1 parent 96a6cd2 commit 5a03823

File tree

2 files changed

+27
-2
lines changed

2 files changed

+27
-2
lines changed

datafusion/optimizer/src/simplify_expressions/expr_simplifier.rs

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1514,6 +1514,19 @@ impl<'a, S: SimplifyInfo> TreeNodeRewriter for Simplifier<'a, S> {
15141514
..like
15151515
}))
15161516
}
1517+
Some(pattern_str)
1518+
if like.escape_char.is_none()
1519+
&& !pattern_str.contains(['%', '_'].as_ref()) =>
1520+
{
1521+
// If the pattern does not contain any wildcards, we can simplify the like expression to an equality expression
1522+
// TODO: handle escape characters
1523+
Transformed::yes(Expr::BinaryExpr(BinaryExpr {
1524+
left: like.expr.clone(),
1525+
op: if like.negated { NotEq } else { Eq },
1526+
right: like.pattern.clone(),
1527+
}))
1528+
}
1529+
15171530
Some(_pattern_str) => Transformed::no(Expr::Like(like)),
15181531
}
15191532
}
@@ -3791,6 +3804,16 @@ mod tests {
37913804

37923805
let expr = not_ilike(null, lit("a%"));
37933806
assert_eq!(simplify(expr), lit_bool_null());
3807+
3808+
// expr [NOT] [I]LIKE with pattern without wildcards
3809+
let expr = like(col("c1"), lit("a"));
3810+
assert_eq!(simplify(expr), col("c1").eq(lit("a")));
3811+
let expr = not_like(col("c1"), lit("a"));
3812+
assert_eq!(simplify(expr), col("c1").not_eq(lit("a")));
3813+
let expr = like(col("c1"), lit("a_"));
3814+
assert_eq!(simplify(expr), col("c1").like(lit("a_")));
3815+
let expr = not_like(col("c1"), lit("a_"));
3816+
assert_eq!(simplify(expr), col("c1").not_like(lit("a_")));
37943817
}
37953818

37963819
#[test]
@@ -4166,6 +4189,7 @@ mod tests {
41664189
Ok(DataType::Int16)
41674190
}
41684191
}
4192+
41694193
#[test]
41704194
fn test_optimize_volatile_conditions() {
41714195
let fun = Arc::new(ScalarUDF::new_from_impl(VolatileUdf::new()));

datafusion/sqllogictest/test_files/string/string_view.slt

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -396,8 +396,9 @@ EXPLAIN SELECT
396396
FROM test;
397397
----
398398
logical_plan
399-
01)Projection: test.column1_utf8view LIKE Utf8View("foo") AS like, test.column1_utf8view ILIKE Utf8View("foo") AS ilike
400-
02)--TableScan: test projection=[column1_utf8view]
399+
01)Projection: __common_expr_1 AS like, __common_expr_1 AS ilike
400+
02)--Projection: test.column1_utf8view = Utf8View("foo") AS __common_expr_1
401+
03)----TableScan: test projection=[column1_utf8view]
401402

402403

403404
query TT

0 commit comments

Comments
 (0)