Skip to content

Commit

Permalink
Simplify EXPR LIKE 'constant' to expr = 'constant'
Browse files Browse the repository at this point in the history
  • Loading branch information
adriangb authored and findepi committed Nov 7, 2024
1 parent dad2d89 commit e05417a
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 2 deletions.
24 changes: 24 additions & 0 deletions datafusion/optimizer/src/simplify_expressions/expr_simplifier.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1514,6 +1514,19 @@ impl<'a, S: SimplifyInfo> TreeNodeRewriter for Simplifier<'a, S> {
..like
}))
}
Some(pattern_str)
if like.escape_char.is_none()
&& !pattern_str.contains(['%', '_'].as_ref()) =>
{
// If the pattern does not contain any wildcards, we can simplify the like expression to an equality expression
// TODO: handle escape characters
Transformed::yes(Expr::BinaryExpr(BinaryExpr {
left: like.expr.clone(),
op: if like.negated { NotEq } else { Eq },
right: like.pattern.clone(),
}))
}

Some(_pattern_str) => Transformed::no(Expr::Like(like)),
}
}
Expand Down Expand Up @@ -3791,6 +3804,16 @@ mod tests {

let expr = not_ilike(null, lit("a%"));
assert_eq!(simplify(expr), lit_bool_null());

// expr [NOT] [I]LIKE with pattern without wildcards
let expr = like(col("c1"), lit("a"));
assert_eq!(simplify(expr), col("c1").eq(lit("a")));
let expr = not_like(col("c1"), lit("a"));
assert_eq!(simplify(expr), col("c1").not_eq(lit("a")));
let expr = like(col("c1"), lit("a_"));
assert_eq!(simplify(expr), col("c1").like(lit("a_")));
let expr = not_like(col("c1"), lit("a_"));
assert_eq!(simplify(expr), col("c1").not_like(lit("a_")));
}

#[test]
Expand Down Expand Up @@ -4166,6 +4189,7 @@ mod tests {
Ok(DataType::Int16)
}
}

#[test]
fn test_optimize_volatile_conditions() {
let fun = Arc::new(ScalarUDF::new_from_impl(VolatileUdf::new()));
Expand Down
5 changes: 3 additions & 2 deletions datafusion/sqllogictest/test_files/string/string_view.slt
Original file line number Diff line number Diff line change
Expand Up @@ -396,8 +396,9 @@ EXPLAIN SELECT
FROM test;
----
logical_plan
01)Projection: test.column1_utf8view LIKE Utf8View("foo") AS like, test.column1_utf8view ILIKE Utf8View("foo") AS ilike
02)--TableScan: test projection=[column1_utf8view]
01)Projection: __common_expr_1 AS like, __common_expr_1 AS ilike
02)--Projection: test.column1_utf8view = Utf8View("foo") AS __common_expr_1
03)----TableScan: test projection=[column1_utf8view]


query TT
Expand Down

0 comments on commit e05417a

Please sign in to comment.