asolimando commented on code in PR #4460:
URL: https://github.com/apache/calcite/pull/4460#discussion_r2311826564


##########
core/src/main/java/org/apache/calcite/rex/RexSimplify.java:
##########
@@ -500,17 +501,67 @@ private RexNode simplifyDivide(RexCall e) {
   private RexNode simplifyLike(RexCall e, RexUnknownAs unknownAs) {
     if (e.operands.get(1) instanceof RexLiteral) {
       final RexLiteral literal = (RexLiteral) e.operands.get(1);
-      if ("%".equals(literal.getValueAs(String.class))) {
-        // "x LIKE '%'" simplifies to "x = x"
+      String likeStr = requireNonNull(literal.getValueAs(String.class));
+      Pattern pattern = Pattern.compile("%+");
+      String value = pattern.matcher(likeStr).replaceAll("%");
+      if ("%".equals(value)) {
+        // "x LIKE '%'" or "x LIKE '%...'" simplifies to "x = x"
         final RexNode x = e.operands.get(0);
         return simplify(
             rexBuilder.makeCall(
                 e.getParserPosition(), SqlStdOperatorTable.EQUALS, x, x), 
unknownAs);
       }
+      // simplify "x LIKE '%%\%%a%%%'" to "x LIKE '%\%%a%'", default escape is 
'\'
+      if (e.operands.size() == 2) {
+        e = (RexCall) rexBuilder
+            .makeCall(e.getParserPosition(), e.getOperator(), 
e.operands.get(0),
+                rexBuilder.makeLiteral(simplifyLikeString(likeStr, '\\', 
'%')));
+      }
+      if (e.operands.size() == 3 && e.operands.get(2) instanceof RexLiteral) {
+        final RexLiteral escapeLiteral = (RexLiteral) e.operands.get(2);
+        Character escape = 
requireNonNull(escapeLiteral.getValueAs(Character.class));
+        e = (RexCall) rexBuilder
+            .makeCall(e.getParserPosition(), e.getOperator(), 
e.operands.get(0),
+                rexBuilder.makeLiteral(simplifyLikeString(likeStr, escape, 
'%')),
+                escapeLiteral);
+      }
     }
     return simplifyGenericNode(e);
   }
 
+  /**
+   * Simplifies like string with escape.
+   * A like '%%#%%A%%' escape '#' should simplify to A like '%#%%A%' escape 
'#'.
+   */
+  private String simplifyLikeString(String content, char escape, char 
wildcard) {

Review Comment:
   Agreed, but please make sure to file a ticket with the details and examples 
Mihai provided before merging, so we make sure that the effort and insight from 
the reviewer isn't lost (PR comments aren't really looked at after merging).



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to