-
Notifications
You must be signed in to change notification settings - Fork 123
Support the CARDINALITY() SQL function #4074
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
33 changes: 33 additions & 0 deletions
33
docs/sphinx/source/reference/Functions/scalar_functions/cardinality.rst
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,33 @@ | ||
| =========== | ||
| CARDINALITY | ||
| =========== | ||
|
|
||
| The CARDINALITY function returns the cardinality of an array. | ||
|
|
||
| Syntax | ||
| ====== | ||
|
|
||
| .. code-block:: sql | ||
|
|
||
| CARDINALITY( <expr> ) | ||
|
|
||
| Parameters | ||
| ========== | ||
|
|
||
| ``expr`` | ||
| An array expression. | ||
|
|
||
| Returns | ||
| ======= | ||
|
|
||
| Given an array value, returns a value of type INTEGER representing the number of elements in the array, or 0 if it is | ||
| empty. If the argument is NULL, the result is the NULL value. | ||
|
|
||
| Example | ||
| ======= | ||
|
|
||
| .. code-block:: sql | ||
|
|
||
| CREATE TABLE t1 (id INTEGER, arr INTEGER ARRAY); | ||
| INSERT INTO t1 VALUES (1, [1, 2]); | ||
| SELECT CARDINALITY(arr) FROM t1; -- yields 2 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
180 changes: 180 additions & 0 deletions
180
.../main/java/com/apple/foundationdb/record/query/plan/cascades/values/CardinalityValue.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,180 @@ | ||
| /* | ||
| * CardinalityValue.java | ||
| * | ||
| * This source file is part of the FoundationDB open source project | ||
| * | ||
| * Copyright 2023-2030 Apple Inc. and the FoundationDB project authors | ||
| * | ||
| * Licensed 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 com.apple.foundationdb.record.query.plan.cascades.values; | ||
|
|
||
| import com.apple.foundationdb.annotation.API; | ||
| import com.apple.foundationdb.annotation.SpotBugsSuppressWarnings; | ||
| import com.apple.foundationdb.record.EvaluationContext; | ||
| import com.apple.foundationdb.record.FunctionNames; | ||
| import com.apple.foundationdb.record.ObjectPlanHash; | ||
| import com.apple.foundationdb.record.PlanDeserializer; | ||
| import com.apple.foundationdb.record.PlanHashable; | ||
| import com.apple.foundationdb.record.PlanSerializationContext; | ||
| import com.apple.foundationdb.record.planprotos.PCardinalityValue; | ||
| import com.apple.foundationdb.record.planprotos.PValue; | ||
| import com.apple.foundationdb.record.provider.foundationdb.FDBRecordStoreBase; | ||
| import com.apple.foundationdb.record.query.plan.cascades.AliasMap; | ||
| import com.apple.foundationdb.record.query.plan.cascades.BuiltInFunction; | ||
| import com.apple.foundationdb.record.query.plan.cascades.SemanticException; | ||
| import com.apple.foundationdb.record.query.plan.cascades.typing.Type; | ||
| import com.apple.foundationdb.record.query.plan.cascades.typing.Typed; | ||
| import com.apple.foundationdb.record.query.plan.explain.ExplainTokens; | ||
| import com.apple.foundationdb.record.query.plan.explain.ExplainTokensWithPrecedence; | ||
| import com.google.auto.service.AutoService; | ||
| import com.google.common.base.Verify; | ||
| import com.google.common.collect.ImmutableList; | ||
| import com.google.protobuf.Message; | ||
|
|
||
| import javax.annotation.Nonnull; | ||
| import javax.annotation.Nullable; | ||
| import java.util.List; | ||
| import java.util.Objects; | ||
| import java.util.function.Supplier; | ||
|
|
||
| /** | ||
| * A value representing the {@code CARDINALITY()} function. | ||
| */ | ||
| @API(API.Status.EXPERIMENTAL) | ||
| public class CardinalityValue extends AbstractValue { | ||
| private static final ObjectPlanHash BASE_HASH = new ObjectPlanHash("Cardinality-Value"); | ||
|
|
||
| @Nonnull | ||
| private final Value childValue; | ||
|
|
||
| public CardinalityValue(@Nonnull final Value childValue) { | ||
| SemanticException.check(childValue.getResultType().isArray(), SemanticException.ErrorCode.INCOMPATIBLE_TYPE, "The argument of CARDINALITY() must be an array expression."); | ||
|
|
||
| this.childValue = childValue; | ||
| } | ||
|
|
||
| @Nonnull | ||
| @Override | ||
| public List<? extends Value> computeChildren() { | ||
| return List.of(childValue); | ||
| } | ||
|
|
||
| @Nonnull | ||
| @Override | ||
| public Value withChildren(final Iterable<? extends Value> newChildren) { | ||
| final var newChildrenList = ImmutableList.copyOf(newChildren); | ||
| Verify.verify(newChildrenList.size() == 1); | ||
| return new CardinalityValue(newChildrenList.get(0)); | ||
| } | ||
|
|
||
| @Nonnull | ||
| @Override | ||
| public Type getResultType() { | ||
| // Array indexes and sizes are 32-bit integers. | ||
| return Type.primitiveType(Type.TypeCode.INT); | ||
| } | ||
|
|
||
| @Override | ||
| public <M extends Message> Object eval(@Nullable final FDBRecordStoreBase<M> store, @Nonnull final EvaluationContext context) { | ||
| final Object childResult = childValue.eval(store, context); | ||
| if (childResult == null) { | ||
| return null; | ||
| } | ||
| return ((List<?>)childResult).size(); | ||
| } | ||
|
|
||
| @Override | ||
| public int hashCodeWithoutChildren() { | ||
| return PlanHashable.objectsPlanHash(PlanHashable.CURRENT_FOR_CONTINUATION, BASE_HASH); | ||
| } | ||
|
|
||
| @Override | ||
| public int planHash(@Nonnull final PlanHashMode mode) { | ||
| return PlanHashable.objectsPlanHash(mode, BASE_HASH, childValue); | ||
| } | ||
|
|
||
| @Nonnull | ||
| @Override | ||
| public ExplainTokensWithPrecedence explain(@Nonnull final Iterable<Supplier<ExplainTokensWithPrecedence>> explainSuppliers) { | ||
| return ExplainTokensWithPrecedence.of(new ExplainTokens().addFunctionCall(FunctionNames.CARDINALITY, | ||
| Value.explainFunctionArguments(explainSuppliers))); | ||
| } | ||
|
|
||
| @Override | ||
| public int hashCode() { | ||
| return semanticHashCode(); | ||
| } | ||
|
|
||
| @SuppressWarnings("EqualsWhichDoesntCheckParameterClass") | ||
| @SpotBugsSuppressWarnings("EQ_UNUSUAL") | ||
| @Override | ||
| public boolean equals(final Object other) { | ||
| return semanticEquals(other, AliasMap.emptyMap()); | ||
| } | ||
|
|
||
| @Nonnull | ||
| @Override | ||
| public PCardinalityValue toProto(@Nonnull final PlanSerializationContext serializationContext) { | ||
| return PCardinalityValue.newBuilder() | ||
| .setChildValue(childValue.toValueProto(serializationContext)) | ||
| .build(); | ||
| } | ||
|
|
||
| @Nonnull | ||
| @Override | ||
| public PValue toValueProto(@Nonnull PlanSerializationContext serializationContext) { | ||
| return PValue.newBuilder().setCardinalityValue(toProto(serializationContext)).build(); | ||
| } | ||
|
|
||
| @Nonnull | ||
| public static CardinalityValue fromProto(@Nonnull final PlanSerializationContext serializationContext, @Nonnull final PCardinalityValue cardinalityValueProto) { | ||
| return new CardinalityValue(Value.fromValueProto(serializationContext, Objects.requireNonNull(cardinalityValueProto.getChildValue()))); | ||
| } | ||
|
|
||
| /** | ||
| * The {@code CARDINALITY()} function. | ||
| */ | ||
| @AutoService(BuiltInFunction.class) | ||
| public static class CardinalityFn extends BuiltInFunction<Value> { | ||
| public CardinalityFn() { | ||
| super(FunctionNames.CARDINALITY, | ||
| List.of(Type.any()), (builtInFunction, arguments) -> encapsulateInternal(arguments)); | ||
| } | ||
|
|
||
| private static Value encapsulateInternal(@Nonnull final List<? extends Typed> arguments) { | ||
| Verify.verify(arguments.size() == 1); | ||
| return new CardinalityValue((Value)arguments.get(0)); | ||
|
RobertBrunel marked this conversation as resolved.
|
||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Deserializer. | ||
| */ | ||
| @AutoService(PlanDeserializer.class) | ||
| public static class Deserializer implements PlanDeserializer<PCardinalityValue, CardinalityValue> { | ||
| @Nonnull | ||
| @Override | ||
| public Class<PCardinalityValue> getProtoMessageClass() { | ||
| return PCardinalityValue.class; | ||
| } | ||
|
|
||
| @Nonnull | ||
| @Override | ||
| public CardinalityValue fromProto(@Nonnull final PlanSerializationContext serializationContext, | ||
| @Nonnull final PCardinalityValue cardinalityValueProto) { | ||
| return CardinalityValue.fromProto(serializationContext, cardinalityValueProto); | ||
| } | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
63 changes: 63 additions & 0 deletions
63
...t/java/com/apple/foundationdb/record/query/plan/cascades/values/CardinalityValueTest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,63 @@ | ||
| /* | ||
| * CardinalityValueTest.java | ||
| * | ||
| * This source file is part of the FoundationDB open source project | ||
| * | ||
| * Copyright 2023-2030 Apple Inc. and the FoundationDB project authors | ||
| * | ||
| * Licensed 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 com.apple.foundationdb.record.query.plan.cascades.values; | ||
|
|
||
| import com.apple.foundationdb.record.query.plan.cascades.typing.Type; | ||
| import org.junit.jupiter.api.Assertions; | ||
| import org.junit.jupiter.api.Test; | ||
|
|
||
| import java.util.List; | ||
|
|
||
| class CardinalityValueTest { | ||
|
|
||
| private static final Type.Array INT_ARRAY_TYPE = new Type.Array(Type.primitiveType(Type.TypeCode.INT)); | ||
| private static final Type.Array STRING_ARRAY_TYPE = new Type.Array(Type.primitiveType(Type.TypeCode.STRING)); | ||
|
|
||
| private static final LiteralValue<List<Integer>> INT_ARRAY_1 = | ||
| new LiteralValue<>(INT_ARRAY_TYPE, List.of(1, 2, 3)); | ||
| private static final LiteralValue<List<Integer>> INT_ARRAY_2 = | ||
| new LiteralValue<>(INT_ARRAY_TYPE, List.of(4, 5)); | ||
| private static final LiteralValue<List<String>> STRING_ARRAY = | ||
| new LiteralValue<>(STRING_ARRAY_TYPE, List.of("a", "b")); | ||
|
|
||
| @Test | ||
| void testEqualsAndHashCode() { | ||
| final var c1 = new CardinalityValue(INT_ARRAY_1); | ||
| final var c2 = new CardinalityValue(INT_ARRAY_1); | ||
| final var cDifferentChild = new CardinalityValue(INT_ARRAY_2); | ||
| final var cDifferentElementType = new CardinalityValue(STRING_ARRAY); | ||
|
|
||
| // Reflexive | ||
| Assertions.assertEquals(c1, c1); | ||
|
|
||
| // Two instances with the same child are equal and have the same hash code | ||
| Assertions.assertEquals(c1, c2); | ||
| Assertions.assertEquals(c1.hashCode(), c2.hashCode()); | ||
|
|
||
| // Instances with different children are not equal | ||
| Assertions.assertNotEquals(cDifferentChild, c1); | ||
| Assertions.assertNotEquals(cDifferentElementType, c1); | ||
|
|
||
| // Not equal to null or an unrelated type | ||
| Assertions.assertNotEquals(null, c1); | ||
| Assertions.assertNotEquals("not a Value", c1); | ||
| } | ||
|
RobertBrunel marked this conversation as resolved.
|
||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
27 changes: 27 additions & 0 deletions
27
yaml-tests/src/test/resources/arrays_cardinality.metrics.binpb
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
23 changes: 23 additions & 0 deletions
23
yaml-tests/src/test/resources/arrays_cardinality.metrics.yaml
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,23 @@ | ||
| arrays-cardinality-tests: | ||
| - query: EXPLAIN SELECT CARDINALITY("int_arr") FROM "tab1_nn" | ||
| ref: arrays_cardinality.yamsql:57 | ||
| explain: SCAN([IS tab1_nn]) | MAP (cardinality(_.int_arr) AS _0) | ||
| task_count: 146 | ||
| task_total_time_ms: 71 | ||
| transform_count: 40 | ||
| transform_time_ms: 55 | ||
| transform_yield_count: 13 | ||
| insert_time_ms: 2 | ||
| insert_new_count: 12 | ||
| insert_reused_count: 2 | ||
| - query: EXPLAIN SELECT CARDINALITY("int_arr") FROM "tab1" | ||
| ref: arrays_cardinality.yamsql:61 | ||
| explain: SCAN([IS tab1]) | MAP (cardinality(_.int_arr) AS _0) | ||
| task_count: 146 | ||
| task_total_time_ms: 9 | ||
| transform_count: 40 | ||
| transform_time_ms: 4 | ||
| transform_yield_count: 13 | ||
| insert_time_ms: 0 | ||
| insert_new_count: 12 | ||
| insert_reused_count: 2 |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.