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


##########
core/src/main/java/org/apache/calcite/rex/RexSimplify.java:
##########
@@ -500,17 +501,66 @@ 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) {
+        ArrayList<RexNode> rexNodes = new ArrayList<>(e.operands);
+        rexNodes.set(1, rexBuilder.makeLiteral(simplifyLikeString(likeStr, 
"\\", "%")));
+        e = (RexCall) rexBuilder.makeCall(e.getParserPosition(), 
e.getOperator(), rexNodes);
+      }
+      if (e.operands.size() == 3 && e.operands.get(2) instanceof RexLiteral) {
+        final RexLiteral escapeLiteral = (RexLiteral) e.operands.get(2);
+        String escape = requireNonNull(escapeLiteral.getValueAs(String.class));
+        ArrayList<RexNode> rexNodes = new ArrayList<>(e.operands);
+        rexNodes.set(1, rexBuilder.makeLiteral(simplifyLikeString(likeStr, 
escape, "%")));
+        e = (RexCall) rexBuilder.makeCall(e.getParserPosition(), 
e.getOperator(), rexNodes);
+      }
     }
     return simplifyGenericNode(e);
   }
 
+  /**
+   * Simplifies like string with escape.
+   * A like '%%#%%A%%' escape '#' should simplify to A like '%#%%A%' escape 
'#'.
+   */
+  private String simplifyLikeString(String content, String escape, String 
wildcard) {
+    ArrayList<String> result = new ArrayList<>();

Review Comment:
   I had change to StringBuilder to append char which seems more suitable.



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