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


##########
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:
   Yes, there may be more optimization points here, and I will gradually 
improve them in future. Based on this issue, which is mainly to compress 
redundant ```'%'``` characters, I feel that this PR can solve this problem 
separately, so I squashed all the commits first.



-- 
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