You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@calcite.apache.org by jh...@apache.org on 2023/06/10 20:36:45 UTC

[calcite] 01/02: [CALCITE-5707] Add ARRAY_CONTAINS function (enabled in Spark library)

This is an automated email from the ASF dual-hosted git repository.

jhyde pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/calcite.git

commit 3dfefd1a95b831cc57434264f224e789bba35df9
Author: yongen.ly <yo...@alibaba-inc.com>
AuthorDate: Wed May 17 15:45:04 2023 +0800

    [CALCITE-5707] Add ARRAY_CONTAINS function (enabled in Spark library)
    
    Flink has a similar function, but has slightly different
    behavior from Spark.
      array_contains(array[1, null], cast(null as integer))
    returns TRUE in Flink, UNKNOWN in Spark. This change
    implements the Spark behavior.
    
    Replace SqlFunctions.arrayContains with List.contains (Julian Hyde).
    
    Tweak Util.distinctList, and add note that SqlFunctions.distinct could
    use a similar algorithm (Julian Hyde).
    
    Close apache/calcite#3207
---
 .../calcite/adapter/enumerable/RexImpTable.java    |  2 +
 .../org/apache/calcite/runtime/SqlFunctions.java   |  5 +-
 .../main/java/org/apache/calcite/sql/SqlKind.java  |  3 +
 .../calcite/sql/fun/SqlLibraryOperators.java       |  9 ++-
 .../sql/type/ArrayElementOperandTypeChecker.java   | 75 ++++++++++++++++++++++
 .../org/apache/calcite/sql/type/OperandTypes.java  |  3 +
 .../org/apache/calcite/sql/type/ReturnTypes.java   |  8 +++
 .../apache/calcite/sql/type/SqlTypeTransforms.java | 15 +++++
 .../org/apache/calcite/util/BuiltInMethod.java     |  1 +
 .../main/java/org/apache/calcite/util/Util.java    | 16 +++--
 .../java/org/apache/calcite/util/UtilTest.java     |  7 ++
 site/_docs/reference.md                            |  1 +
 .../org/apache/calcite/test/SqlOperatorTest.java   | 32 +++++++++
 13 files changed, 169 insertions(+), 8 deletions(-)

diff --git a/core/src/main/java/org/apache/calcite/adapter/enumerable/RexImpTable.java b/core/src/main/java/org/apache/calcite/adapter/enumerable/RexImpTable.java
index f55ed21542..8f4272f15c 100644
--- a/core/src/main/java/org/apache/calcite/adapter/enumerable/RexImpTable.java
+++ b/core/src/main/java/org/apache/calcite/adapter/enumerable/RexImpTable.java
@@ -121,6 +121,7 @@ import static org.apache.calcite.sql.fun.SqlLibraryOperators.ARRAY_AGG;
 import static org.apache.calcite.sql.fun.SqlLibraryOperators.ARRAY_COMPACT;
 import static org.apache.calcite.sql.fun.SqlLibraryOperators.ARRAY_CONCAT;
 import static org.apache.calcite.sql.fun.SqlLibraryOperators.ARRAY_CONCAT_AGG;
+import static org.apache.calcite.sql.fun.SqlLibraryOperators.ARRAY_CONTAINS;
 import static org.apache.calcite.sql.fun.SqlLibraryOperators.ARRAY_DISTINCT;
 import static org.apache.calcite.sql.fun.SqlLibraryOperators.ARRAY_EXCEPT;
 import static org.apache.calcite.sql.fun.SqlLibraryOperators.ARRAY_INTERSECT;
@@ -694,6 +695,7 @@ public class RexImpTable {
       defineMethod(STRUCT_ACCESS, BuiltInMethod.STRUCT_ACCESS.method, NullPolicy.ANY);
       defineMethod(MEMBER_OF, BuiltInMethod.MEMBER_OF.method, NullPolicy.NONE);
       defineMethod(ARRAY_COMPACT, BuiltInMethod.ARRAY_COMPACT.method, NullPolicy.STRICT);
+      defineMethod(ARRAY_CONTAINS, BuiltInMethod.LIST_CONTAINS.method, NullPolicy.ANY);
       defineMethod(ARRAY_DISTINCT, BuiltInMethod.ARRAY_DISTINCT.method, NullPolicy.STRICT);
       defineMethod(ARRAY_EXCEPT, BuiltInMethod.ARRAY_EXCEPT.method, NullPolicy.ANY);
       defineMethod(ARRAY_INTERSECT, BuiltInMethod.ARRAY_INTERSECT.method, NullPolicy.ANY);
diff --git a/core/src/main/java/org/apache/calcite/runtime/SqlFunctions.java b/core/src/main/java/org/apache/calcite/runtime/SqlFunctions.java
index e1835b49d0..3155cbe35b 100644
--- a/core/src/main/java/org/apache/calcite/runtime/SqlFunctions.java
+++ b/core/src/main/java/org/apache/calcite/runtime/SqlFunctions.java
@@ -3880,7 +3880,10 @@ public class SqlFunctions {
     return result;
   }
 
-  /** Support the ARRAY_DISTINCT function. */
+  /** Support the ARRAY_DISTINCT function.
+   *
+   * <p>Note: If the list does not contain null,
+   * {@link Util#distinctList(List)} is probably faster. */
   public static List distinct(List list) {
     Set result = new LinkedHashSet<>(list);
     return new ArrayList<>(result);
diff --git a/core/src/main/java/org/apache/calcite/sql/SqlKind.java b/core/src/main/java/org/apache/calcite/sql/SqlKind.java
index a53936c201..4861005730 100644
--- a/core/src/main/java/org/apache/calcite/sql/SqlKind.java
+++ b/core/src/main/java/org/apache/calcite/sql/SqlKind.java
@@ -683,6 +683,9 @@ public enum SqlKind {
   /** {@code ARRAY_CONCAT} function (BigQuery semantics). */
   ARRAY_CONCAT,
 
+  /** {@code ARRAY_CONTAINS} function (Spark semantics). */
+  ARRAY_CONTAINS,
+
   /** {@code ARRAY_DISTINCT} function (Spark semantics). */
   ARRAY_DISTINCT,
 
diff --git a/core/src/main/java/org/apache/calcite/sql/fun/SqlLibraryOperators.java b/core/src/main/java/org/apache/calcite/sql/fun/SqlLibraryOperators.java
index e5ea8aa67e..a8ef9312b9 100644
--- a/core/src/main/java/org/apache/calcite/sql/fun/SqlLibraryOperators.java
+++ b/core/src/main/java/org/apache/calcite/sql/fun/SqlLibraryOperators.java
@@ -886,7 +886,14 @@ public abstract class SqlLibraryOperators {
           ReturnTypes.LEAST_RESTRICTIVE,
           OperandTypes.AT_LEAST_ONE_SAME_VARIADIC);
 
-  /** The "ARRAY_DISTINCT(array)" function (Spark). */
+  /** The "ARRAY_CONTAINS(array, element)" function. */
+  @LibraryOperator(libraries = {SPARK})
+  public static final SqlFunction ARRAY_CONTAINS =
+      SqlBasicFunction.create(SqlKind.ARRAY_CONTAINS,
+          ReturnTypes.BOOLEAN_NULLABLE,
+          OperandTypes.ARRAY_ELEMENT);
+
+  /** The "ARRAY_DISTINCT(array)" function. */
   @LibraryOperator(libraries = {SPARK})
   public static final SqlFunction ARRAY_DISTINCT =
       SqlBasicFunction.create(SqlKind.ARRAY_DISTINCT,
diff --git a/core/src/main/java/org/apache/calcite/sql/type/ArrayElementOperandTypeChecker.java b/core/src/main/java/org/apache/calcite/sql/type/ArrayElementOperandTypeChecker.java
new file mode 100644
index 0000000000..8291b1681d
--- /dev/null
+++ b/core/src/main/java/org/apache/calcite/sql/type/ArrayElementOperandTypeChecker.java
@@ -0,0 +1,75 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to you under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.calcite.sql.type;
+
+import org.apache.calcite.rel.type.RelDataType;
+import org.apache.calcite.sql.SqlCallBinding;
+import org.apache.calcite.sql.SqlNode;
+import org.apache.calcite.sql.SqlOperandCountRange;
+import org.apache.calcite.sql.SqlOperator;
+
+import com.google.common.collect.ImmutableList;
+
+import static org.apache.calcite.sql.type.NonNullableAccessors.getComponentTypeOrThrow;
+import static org.apache.calcite.util.Static.RESOURCE;
+
+/**
+ * Parameter type-checking strategy where types must be Array and Array element type.
+ */
+public class ArrayElementOperandTypeChecker implements SqlOperandTypeChecker {
+  //~ Methods ----------------------------------------------------------------
+
+  @Override public boolean checkOperandTypes(
+      SqlCallBinding callBinding,
+      boolean throwOnFailure) {
+    final SqlNode op0 = callBinding.operand(0);
+    if (!OperandTypes.ARRAY.checkSingleOperandType(
+        callBinding,
+        op0,
+        0,
+        throwOnFailure)) {
+      return false;
+    }
+
+    RelDataType arrayComponentType =
+        getComponentTypeOrThrow(SqlTypeUtil.deriveType(callBinding, op0));
+    final SqlNode op1 = callBinding.operand(1);
+    RelDataType aryType1 = SqlTypeUtil.deriveType(callBinding, op1);
+
+    RelDataType biggest =
+        callBinding.getTypeFactory().leastRestrictive(
+            ImmutableList.of(arrayComponentType, aryType1));
+    if (biggest == null) {
+      if (throwOnFailure) {
+        throw callBinding.newError(
+            RESOURCE.typeNotComparable(
+                arrayComponentType.toString(), aryType1.toString()));
+      }
+
+      return false;
+    }
+    return true;
+  }
+
+  @Override public SqlOperandCountRange getOperandCountRange() {
+    return SqlOperandCountRanges.of(2);
+  }
+
+  @Override public String getAllowedSignatures(SqlOperator op, String opName) {
+    return "<ARRAY> " + opName + " <ARRAY>";
+  }
+}
diff --git a/core/src/main/java/org/apache/calcite/sql/type/OperandTypes.java b/core/src/main/java/org/apache/calcite/sql/type/OperandTypes.java
index cd01b9882b..c663ea1024 100644
--- a/core/src/main/java/org/apache/calcite/sql/type/OperandTypes.java
+++ b/core/src/main/java/org/apache/calcite/sql/type/OperandTypes.java
@@ -487,6 +487,9 @@ public abstract class OperandTypes {
   public static final SqlSingleOperandTypeChecker MAP =
       family(SqlTypeFamily.MAP);
 
+  public static final SqlOperandTypeChecker ARRAY_ELEMENT =
+      new ArrayElementOperandTypeChecker();
+
   /**
    * Operand type-checking strategy where type must be a literal or NULL.
    */
diff --git a/core/src/main/java/org/apache/calcite/sql/type/ReturnTypes.java b/core/src/main/java/org/apache/calcite/sql/type/ReturnTypes.java
index f0fcbc3ed8..e34cc32dd3 100644
--- a/core/src/main/java/org/apache/calcite/sql/type/ReturnTypes.java
+++ b/core/src/main/java/org/apache/calcite/sql/type/ReturnTypes.java
@@ -246,6 +246,7 @@ public abstract class ReturnTypes {
    */
   public static final SqlReturnTypeInference BOOLEAN =
       explicit(SqlTypeName.BOOLEAN);
+
   /**
    * Type-inference strategy whereby the result type of a call is Boolean,
    * with nulls allowed if any of the operands allow nulls.
@@ -253,6 +254,13 @@ public abstract class ReturnTypes {
   public static final SqlReturnTypeInference BOOLEAN_NULLABLE =
       BOOLEAN.andThen(SqlTypeTransforms.TO_NULLABLE);
 
+  /**
+   * Type-inference strategy whereby the result type of a call is Boolean,
+   * with nulls allowed if the type of the operand #0 (0-based) is nullable.
+   */
+  public static final SqlReturnTypeInference BOOLEAN_NULLABLE_IF_ARG0_NULLABLE =
+      BOOLEAN.andThen(SqlTypeTransforms.ARG0_NULLABLE);
+
   /**
    * Type-inference strategy with similar effect to {@link #BOOLEAN_NULLABLE},
    * which is more efficient, but can only be used if all arguments are
diff --git a/core/src/main/java/org/apache/calcite/sql/type/SqlTypeTransforms.java b/core/src/main/java/org/apache/calcite/sql/type/SqlTypeTransforms.java
index f4602cfe81..97562713c9 100644
--- a/core/src/main/java/org/apache/calcite/sql/type/SqlTypeTransforms.java
+++ b/core/src/main/java/org/apache/calcite/sql/type/SqlTypeTransforms.java
@@ -96,6 +96,21 @@ public abstract class SqlTypeTransforms {
         return typeToTransform;
       };
 
+  /**
+   * Parameter type-inference transform strategy where a derived type is
+   * transformed into the same type, but nullable if and only if the type
+   * of a call's operand #0 (0-based) is nullable.
+   */
+  public static final SqlTypeTransform ARG0_NULLABLE =
+      (opBinding, typeToTransform) -> {
+        RelDataType arg0 = opBinding.getOperandType(0);
+        if (arg0.isNullable()) {
+          return opBinding.getTypeFactory()
+              .createTypeWithNullability(typeToTransform, true);
+        }
+        return typeToTransform;
+      };
+
   /**
    * Type-inference strategy whereby the result type of a call is VARYING the
    * type given. The length returned is the same as length of the first
diff --git a/core/src/main/java/org/apache/calcite/util/BuiltInMethod.java b/core/src/main/java/org/apache/calcite/util/BuiltInMethod.java
index f9e7102def..1810c03c4d 100644
--- a/core/src/main/java/org/apache/calcite/util/BuiltInMethod.java
+++ b/core/src/main/java/org/apache/calcite/util/BuiltInMethod.java
@@ -321,6 +321,7 @@ public enum BuiltInMethod {
   COLLECTION_ADD(Collection.class, "add", Object.class),
   COLLECTION_ADDALL(Collection.class, "addAll", Collection.class),
   COLLECTION_RETAIN_ALL(Collection.class, "retainAll", Collection.class),
+  LIST_CONTAINS(List.class, "contains", Object.class),
   LIST_GET(List.class, "get", int.class),
   ITERATOR_HAS_NEXT(Iterator.class, "hasNext"),
   ITERATOR_NEXT(Iterator.class, "next"),
diff --git a/core/src/main/java/org/apache/calcite/util/Util.java b/core/src/main/java/org/apache/calcite/util/Util.java
index 4134e903cb..66dae20104 100644
--- a/core/src/main/java/org/apache/calcite/util/Util.java
+++ b/core/src/main/java/org/apache/calcite/util/Util.java
@@ -2229,12 +2229,16 @@ public class Util {
    * <p>If the list is already unique it is returned unchanged. */
   public static <E> List<E> distinctList(List<E> list) {
     // If the list is small, check for duplicates using pairwise comparison.
-    if (list.size() < QUICK_DISTINCT && isDistinct(list)) {
-      return list;
-    }
-    // Lists that have all the same element are common. Avoiding creating a set.
-    if (allSameElement(list)) {
-      return ImmutableList.of(list.get(0));
+    if (list.size() < QUICK_DISTINCT) {
+      if (isDistinct(list)) {
+        return list;
+      }
+    } else {
+      // Lists that have all the same element are common. Avoiding creating a
+      // set.
+      if (allSameElement(list)) {
+        return ImmutableList.of(list.get(0));
+      }
     }
     return ImmutableList.copyOf(new LinkedHashSet<>(list));
   }
diff --git a/core/src/test/java/org/apache/calcite/util/UtilTest.java b/core/src/test/java/org/apache/calcite/util/UtilTest.java
index 865341c40f..a08cf1a8e8 100644
--- a/core/src/test/java/org/apache/calcite/util/UtilTest.java
+++ b/core/src/test/java/org/apache/calcite/util/UtilTest.java
@@ -1864,6 +1864,13 @@ class UtilTest {
     assertThat(Util.distinctList(cbcaC), is(Arrays.asList("c", "b", "a")));
     final List<String> a2 = ImmutableList.of("a", "a");
     assertThat(Util.distinctList(a2), is(a));
+    // Short list that is not distinct
+    final List<String> aab = ImmutableList.of("a", "a", "b");
+    final List<String> ab = Arrays.asList("a", "b");
+    assertThat(Util.distinctList(aab), is(ab));
+    // Short list that is not distinct and has later duplicate element
+    final List<String> aaba = ImmutableList.of("a", "a", "b", "a");
+    assertThat(Util.distinctList(aaba), is(ab));
     final List<String> a1m = Collections.nCopies(1_000_000, "a");
     assertThat(Util.distinctList(a1m), is(a));
   }
diff --git a/site/_docs/reference.md b/site/_docs/reference.md
index 62c04898a2..08091dcfa6 100644
--- a/site/_docs/reference.md
+++ b/site/_docs/reference.md
@@ -2654,6 +2654,7 @@ BigQuery's type system uses confusingly different names for types and functions:
 | s | ARRAY(expr [, expr ]*)                         | Construct an array in Apache Spark
 | s | ARRAY_COMPACT(array)                           | Removes null values from the *array*
 | b | ARRAY_CONCAT(array [, array ]*)                | Concatenates one or more arrays. If any input argument is `NULL` the function returns `NULL`
+| s | ARRAY_CONTAINS(array, element)                 | Returns true if the *array* contains the *element*
 | s | ARRAY_DISTINCT(array)                          | Removes duplicate values from the *array* that keeps ordering of elements
 | s | ARRAY_EXCEPT(array1, array2)                   | Returns an array of the elements in *array1* but not in *array2*, without duplicates
 | s | ARRAY_INTERSECT(array1, array2)                | Returns an array of the elements in the intersection of *array1* and *array2*, without duplicates
diff --git a/testkit/src/main/java/org/apache/calcite/test/SqlOperatorTest.java b/testkit/src/main/java/org/apache/calcite/test/SqlOperatorTest.java
index 1ed0e4782b..271648c8bf 100644
--- a/testkit/src/main/java/org/apache/calcite/test/SqlOperatorTest.java
+++ b/testkit/src/main/java/org/apache/calcite/test/SqlOperatorTest.java
@@ -5364,6 +5364,38 @@ public class SqlOperatorTest {
     f.checkNull("array_concat(cast(null as integer array), array[1])");
   }
 
+  /** Tests {@code ARRAY_CONTAINS} function from Spark. */
+  @Test void testArrayContainsFunc() {
+    final SqlOperatorFixture f0 = fixture();
+    f0.setFor(SqlLibraryOperators.ARRAY_CONTAINS);
+    f0.checkFails("^array_contains(array[1, 2], 1)^",
+        "No match found for function signature "
+            + "ARRAY_CONTAINS\\(<INTEGER ARRAY>, <NUMERIC>\\)", false);
+
+    final SqlOperatorFixture f = f0.withLibrary(SqlLibrary.SPARK);
+    f.checkScalar("array_contains(array[1, 2], 1)", true,
+        "BOOLEAN NOT NULL");
+    f.checkScalar("array_contains(array[1], 1)", true,
+        "BOOLEAN NOT NULL");
+    f.checkScalar("array_contains(array(), 1)", false,
+        "BOOLEAN NOT NULL");
+    f.checkScalar("array_contains(array[array[1, 2], array[3, 4]], array[1, 2])", true,
+        "BOOLEAN NOT NULL");
+    f.checkScalar("array_contains(array[map[1, 'a'], map[2, 'b']], map[1, 'a'])", true,
+        "BOOLEAN NOT NULL");
+    f.checkNull("array_contains(cast(null as integer array), 1)");
+    f.checkType("array_contains(cast(null as integer array), 1)", "BOOLEAN");
+    // Flink and Spark differ on the following. The expression
+    //   array_contains(array[1, null], cast(null as integer))
+    // returns TRUE in Flink, and returns UNKNOWN in Spark. The current
+    // function has Spark behavior, but if we supported a Flink function
+    // library (i.e. "fun=flink") we could add a function with Flink behavior.
+    f.checkNull("array_contains(array[1, null], cast(null as integer))");
+    f.checkType("array_contains(array[1, null], cast(null as integer))", "BOOLEAN");
+    f.checkFails("^array_contains(array[1, 2], true)^",
+        "INTEGER is not comparable to BOOLEAN", false);
+  }
+
   /** Tests {@code ARRAY_DISTINCT} function from Spark. */
   @Test void testArrayDistinctFunc() {
     final SqlOperatorFixture f0 = fixture();