chunweilei commented on a change in pull request #1854: [CALCITE-3852] 
RexSimplify doesn't simplify NOT EQUAL predicates
URL: https://github.com/apache/calcite/pull/1854#discussion_r393508461
 
 

 ##########
 File path: core/src/main/java/org/apache/calcite/rex/RexSimplify.java
 ##########
 @@ -1560,18 +1560,62 @@ RexNode simplifyAnd2ForUnknownAsFalse(List<RexNode> 
terms,
     return RexUtil.composeConjunction(rexBuilder, terms);
   }
 
+  private RexNode simplifyNotEqual(RexNode e) {
+    final Comparison comparison = Comparison.of(e);
+    // Check for comparison with null values
+    if (comparison == null
+        || comparison.literal.getValue() == null) {
+      return e;
+    }
+
+    for (RexNode node: predicates.pulledUpPredicates) {
+      final Comparison predicate = Comparison.of(node);
+      if (predicate == null
+          || predicate.kind != SqlKind.EQUALS
+          || predicate.literal.getValue() == null
+          || !predicate.ref.equals(comparison.ref)) {
+        continue;
+      }
+
+      // Given x=5 and x is not nullable, x!=5 can be simplified to false and 
x!=3 can be
+      // simplified to true.
+      // Given x=5 and x is nullable, x!=5 can be simplified to 'null and x is 
null' and x!=3 can
+      // be simplified to 'null or x is not null'.
+      final RelDataType type = comparison.ref.getType();
+      final boolean nullable = type.isNullable();
+      if (predicate.literal.equals(comparison.literal)) {
+        return nullable ? rexBuilder.makeCall(SqlStdOperatorTable.AND,
+            rexBuilder.makeNullLiteral(type),
+            rexBuilder.makeCall(SqlStdOperatorTable.IS_NULL, comparison.ref))
+            : rexBuilder.makeLiteral(false);
+      } else {
+        return nullable ? rexBuilder.makeCall(SqlStdOperatorTable.OR,
+            rexBuilder.makeNullLiteral(type),
+            rexBuilder.makeCall(SqlStdOperatorTable.IS_NOT_NULL, 
comparison.ref))
+            : rexBuilder.makeLiteral(true);
+      }
+    }
+    return e;
+  }
+
   private <C extends Comparable<C>> RexNode simplifyUsingPredicates(RexNode e,
       Class<C> clazz) {
     if (predicates.pulledUpPredicates.isEmpty()) {
       return e;
     }
+
+    if (e.getKind() == SqlKind.NOT_EQUALS) {
+      return simplifyNotEqual(e);
+    }
+
     final Comparison comparison = Comparison.of(e);
     // Check for comparison with null values
     if (comparison == null
-        || comparison.kind == SqlKind.NOT_EQUALS
         || comparison.literal.getValue() == null) {
       return e;
     }
+
+
 
 Review comment:
   Ok.

----------------------------------------------------------------
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.
 
For queries about this service, please contact Infrastructure at:
[email protected]


With regards,
Apache Git Services

Reply via email to