From 6274092992b1f5fe8d5949fcc6e58d0cb0a3b79e Mon Sep 17 00:00:00 2001 From: TJ Banghart Date: Fri, 22 Nov 2024 13:50:40 -0800 Subject: [PATCH] [CALCITE-6688] Allow basic symmetric operators to be reversed. --- .../java/org/apache/calcite/sql/SqlBasicFunction.java | 4 ++++ .../java/org/apache/calcite/rex/RexNormalizeTest.java | 8 ++++++++ .../org/apache/calcite/rex/RexProgramBuilderBase.java | 8 ++++++++ 3 files changed, 20 insertions(+) diff --git a/core/src/main/java/org/apache/calcite/sql/SqlBasicFunction.java b/core/src/main/java/org/apache/calcite/sql/SqlBasicFunction.java index 980df24d4e8..4885175f593 100644 --- a/core/src/main/java/org/apache/calcite/sql/SqlBasicFunction.java +++ b/core/src/main/java/org/apache/calcite/sql/SqlBasicFunction.java @@ -158,6 +158,10 @@ public static SqlBasicFunction create(String name, @Override public boolean isDeterministic() { return deterministic; } + + @Override public @Nullable SqlOperator reverse() { + return isSymmetrical() ? this : null; + } @Override public SqlMonotonicity getMonotonicity(SqlOperatorBinding call) { return monotonicityInference.apply(call); diff --git a/core/src/test/java/org/apache/calcite/rex/RexNormalizeTest.java b/core/src/test/java/org/apache/calcite/rex/RexNormalizeTest.java index 0939dd16de7..c1827638d63 100644 --- a/core/src/test/java/org/apache/calcite/rex/RexNormalizeTest.java +++ b/core/src/test/java/org/apache/calcite/rex/RexNormalizeTest.java @@ -91,6 +91,14 @@ class RexNormalizeTest extends RexProgramTestBase { assertNodeEquals( ne(vBool(0), vBool(1)), ne(vBool(1), vBool(0))); + + assertNodeEquals( + greatest(vInt(0), vInt(1)), + greatest(vInt(1), vInt(0))); + + assertNodeEquals( + least(vInt(0), vInt(1)), + least(vInt(1), vInt(0))); } @Test void reversibleDifferentArgOps() { diff --git a/core/src/test/java/org/apache/calcite/rex/RexProgramBuilderBase.java b/core/src/test/java/org/apache/calcite/rex/RexProgramBuilderBase.java index f8f98fdfa03..6051e758016 100644 --- a/core/src/test/java/org/apache/calcite/rex/RexProgramBuilderBase.java +++ b/core/src/test/java/org/apache/calcite/rex/RexProgramBuilderBase.java @@ -25,6 +25,7 @@ import org.apache.calcite.rel.type.RelDataTypeFactory; import org.apache.calcite.rel.type.RelDataTypeSystem; import org.apache.calcite.sql.fun.SqlInternalOperators; +import org.apache.calcite.sql.fun.SqlLibraryOperators; import org.apache.calcite.sql.fun.SqlStdOperatorTable; import org.apache.calcite.sql.type.SqlTypeName; @@ -326,6 +327,13 @@ protected RexNode sub(RexNode n1, RexNode n2) { protected RexNode add(RexNode n1, RexNode n2) { return rexBuilder.makeCall(SqlStdOperatorTable.PLUS, n1, n2); } + protected RexNode greatest(RexNode... nodes) { + return rexBuilder.makeCall(SqlLibraryOperators.GREATEST, nodes); + } + + protected RexNode least(RexNode... nodes) { + return rexBuilder.makeCall(SqlLibraryOperators.LEAST, nodes); + } protected RexNode m2v(RexNode n) { return rexBuilder.makeCall(SqlInternalOperators.M2V, n);