twalthr commented on code in PR #29967:
URL: https://github.com/apache/flink/pull/29967#discussion_r4663733814
##########
flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/internal/TableImpl.java:
##########
@@ -962,6 +962,11 @@ public Table fromChangelog(final Expression... arguments) {
BuiltInFunctionDefinitions.FROM_CHANGELOG.getName(),
(Object[]) arguments);
}
+ @Override
+ public Table deduplicate(final Expression... arguments) {
Review Comment:
Is this correct, I thought we require a partitioning?
##########
docs/content.zh/docs/sql/reference/queries/deduplication.md:
##########
@@ -69,4 +69,143 @@ FROM (
WHERE row_num = 1
```
+## DEDUPLICATE
+
+{{< label Streaming >}}
+
+The `DEDUPLICATE` process table function (PTF) keeps the first or the last row
per key of an append-only table, as long as the state of the key is retained.
Rows are ordered by arrival or by `sequence_by` columns.
+
+### Syntax
+
+```sql
+SELECT * FROM DEDUPLICATE(
+ input => TABLE source_table PARTITION BY key_col[, ...],
+ [keep => 'first' | 'last',]
+ [sequence_by => DESCRIPTOR(col[, ...]),]
+ [state_ttl => INTERVAL '1' HOUR,]
+ [reset_ttl_on_duplicate => true | false,]
Review Comment:
Didn't we say we remove `reset_ttl_on_duplicate`? The FLIP discussion
settled without it, just the open points section of the FLIP was not updated.
##########
docs/content.zh/docs/sql/reference/queries/deduplication.md:
##########
@@ -69,4 +69,143 @@ FROM (
WHERE row_num = 1
```
+## DEDUPLICATE
+
+{{< label Streaming >}}
+
+The `DEDUPLICATE` process table function (PTF) keeps the first or the last row
per key of an append-only table, as long as the state of the key is retained.
Rows are ordered by arrival or by `sequence_by` columns.
+
+### Syntax
+
+```sql
+SELECT * FROM DEDUPLICATE(
+ input => TABLE source_table PARTITION BY key_col[, ...],
+ [keep => 'first' | 'last',]
+ [sequence_by => DESCRIPTOR(col[, ...]),]
+ [state_ttl => INTERVAL '1' HOUR,]
+ [reset_ttl_on_duplicate => true | false,]
+ [uid => 'my-id']
+)
+```
+
+### Parameters
+
+| Parameter | Required | Description |
+|:----------|:---------|:------------|
+| `input` | Yes | The append-only input table. `PARTITION BY` is required and
its columns are the key of the output.|
+| `keep` | No | `'first'` (default) keeps the earliest arrival or the smallest
`sequence_by` value, `'last'` keeps the latest arrival or the greatest. Must be
a literal. Arrival order is not deterministic across reruns, use `sequence_by`
for a repeatable result. |
+| `sequence_by` | No | One or more columns that order the records of a key
instead of their arrival. The first column decides, later columns break ties,
and `NULL` orders below every other value. On a tie, the later arrival wins for
`'last'` and the earlier one for `'first'`. Columns must be numeric, string,
binary, boolean or date-time, and not part of `PARTITION BY`. |
Review Comment:
ascending or descending order?
##########
flink-table/flink-table-common/src/main/java/org/apache/flink/table/types/inference/strategies/DeduplicateTypeStrategy.java:
##########
@@ -0,0 +1,151 @@
+/*
+ * 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.flink.table.types.inference.strategies;
+
+import org.apache.flink.annotation.Internal;
+import org.apache.flink.table.api.DataTypes;
+import org.apache.flink.table.api.ValidationException;
+import org.apache.flink.table.connector.ChangelogMode;
+import org.apache.flink.table.functions.ChangelogFunction.ChangelogContext;
+import org.apache.flink.table.functions.ChangelogModeStrategy;
+import org.apache.flink.table.functions.TableSemantics;
+import org.apache.flink.table.types.DataType;
+import org.apache.flink.table.types.inference.CallContext;
+import org.apache.flink.table.types.inference.InputTypeStrategy;
+import org.apache.flink.table.types.inference.TypeStrategy;
+import
org.apache.flink.table.types.inference.strategies.DeduplicateTypeStrategyUtils.Keep;
+import org.apache.flink.types.RowKind;
+
+import java.util.Arrays;
+import java.util.List;
+import java.util.Optional;
+import java.util.stream.Collectors;
+
+/**
+ * Type strategies for the {@code DEDUPLICATE} process table function.
+ *
+ * <p>The output is updating and keyed by the PARTITION BY columns: the
PARTITION BY columns
+ * followed by the remaining input columns, without time attributes.
+ */
+@Internal
+public final class DeduplicateTypeStrategy {
+
+ public static final int ARG_INPUT = 0;
+ public static final int ARG_KEEP = 1;
+ public static final int ARG_SEQUENCE_BY = 2;
+ public static final int ARG_STATE_TTL = 3;
+ public static final int ARG_RESET_TTL_ON_DUPLICATE = 4;
+ private static final String NAME = "DEDUPLICATE";
+
+ public static final InputTypeStrategy INPUT_TYPE_STRATEGY =
+ new ValidationOnlyInputTypeStrategy() {
+ @Override
+ public Optional<List<DataType>> inferInputTypes(
+ final CallContext callContext, final boolean
throwOnFailure) {
+ final Optional<String> error = validate(callContext);
+ if (error.isPresent()) {
+ return callContext.fail(throwOnFailure, "%s",
error.get());
+ }
+ return Optional.of(callContext.getArgumentDataTypes());
+ }
+ };
+
+ public static final TypeStrategy OUTPUT_TYPE_STRATEGY =
+ callContext ->
+ Optional.of(
+ DataTypes.ROW(
+
DeduplicateTypeStrategyUtils.outputFields(
+
tableSemantics(callContext)))
+ .notNull());
+
+ public static final ChangelogModeStrategy CHANGELOG_MODE_STRATEGY =
+ DeduplicateTypeStrategy::inferChangelogMode;
+
+ /** Returns the {@code keep} argument, or {@link Keep#FIRST} when it is
omitted. */
+ public static Keep keep(final CallContext callContext) {
+ return DeduplicateTypeStrategyUtils.keep(callContext, ARG_KEEP);
+ }
+
+ /**
+ * Returns the positions of the {@code sequence_by} columns, in the listed
order, within the
+ * output row without the PARTITION BY columns.
+ */
+ public static int[] sequenceByOutputIndices(final CallContext callContext)
{
+ return DeduplicateTypeStrategyUtils.sequenceByOutputIndices(
+ callContext, tableSemantics(callContext), ARG_SEQUENCE_BY);
+ }
+
+ private static Optional<String> validate(final CallContext callContext) {
+ final TableSemantics tableSemantics = tableSemantics(callContext);
+ return validateNoOrderBy(tableSemantics)
+ .or(
+ () ->
+
DeduplicateTypeStrategyUtils.validatePartitionByNoTimeAttribute(
+ tableSemantics, NAME))
+ .or(() ->
DeduplicateTypeStrategyUtils.validateKeep(callContext, ARG_KEEP, NAME))
+ .or(
+ () ->
+
DeduplicateTypeStrategyUtils.validateSequenceBy(
+ callContext, tableSemantics,
ARG_SEQUENCE_BY, NAME))
+ .or(() ->
DeduplicateTypeStrategyUtils.validateStateTtl(callContext, ARG_STATE_TTL))
+ .or(
+ () ->
+
DeduplicateTypeStrategyUtils.validateResetTtlOnDuplicate(
+ callContext,
ARG_RESET_TTL_ON_DUPLICATE));
+ }
+
+ private static Optional<String> validateNoOrderBy(final TableSemantics
tableSemantics) {
Review Comment:
We can adjust the framework for avoiding this.
##########
flink-table/flink-table-common/src/main/java/org/apache/flink/table/functions/BuiltInFunctionDefinitions.java:
##########
@@ -939,6 +940,30 @@ ANY, and(logical(LogicalTypeRoot.BOOLEAN), LITERAL)
"org.apache.flink.table.runtime.functions.ptf.FromChangelogFunction")
.build();
+ public static final BuiltInFunctionDefinition DEDUPLICATE =
+ BuiltInFunctionDefinition.newBuilder()
Review Comment:
Of topic but important and now is a good time to start with it:
The BuiltInFunctionDefinition class grows further and further. We should
move the definition and everything related to it to a dedicated class:
`org.apache.flink.table.functions.definitions.DeduplicateDefinition`
This class can contain:
```
public static final BuiltInFunctionDefinition INSTANCE = ...;
input strategy, the output strategy, etc.
```
##########
flink-table/flink-table-common/src/main/java/org/apache/flink/table/types/inference/strategies/DeduplicateTypeStrategyUtils.java:
##########
@@ -0,0 +1,250 @@
+/*
+ * 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.flink.table.types.inference.strategies;
+
+import org.apache.flink.annotation.Internal;
+import org.apache.flink.table.api.DataTypes.Field;
+import org.apache.flink.table.functions.TableSemantics;
+import org.apache.flink.table.types.DataType;
+import org.apache.flink.table.types.inference.CallContext;
+import org.apache.flink.table.types.logical.LogicalType;
+import org.apache.flink.table.types.logical.LogicalTypeFamily;
+import org.apache.flink.table.types.logical.LogicalTypeRoot;
+import org.apache.flink.table.types.logical.utils.LogicalTypeChecks;
+import org.apache.flink.table.types.logical.utils.LogicalTypeUtils;
+import org.apache.flink.table.types.utils.DataTypeUtils;
+import org.apache.flink.types.ColumnList;
+import org.apache.flink.util.TimeUtils;
+
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Optional;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+/** Argument validation and output type helpers shared by the deduplication
PTFs. */
+@Internal
+public final class DeduplicateTypeStrategyUtils {
+
+ /** Which record of a key is kept. */
+ @Internal
+ public enum Keep {
+ FIRST("first"),
+ LAST("last");
+
+ private final String value;
+
+ Keep(final String value) {
+ this.value = value;
+ }
+
+ /** Returns the mode for an argument value, or empty if the value
names no mode. */
+ public static Optional<Keep> fromValue(final String value) {
+ return Arrays.stream(values()).filter(keep ->
keep.value.equals(value)).findFirst();
+ }
+ }
+
+ /** Returns the {@code keep} argument, or {@link Keep#FIRST} when it is
omitted. */
+ public static Keep keep(final CallContext callContext, final int argPos) {
+ return callContext
+ .getArgumentValue(argPos, String.class)
+ .map(
+ value ->
+ Keep.fromValue(value)
+ .orElseThrow(
+ () ->
+ new
IllegalStateException(
+ "Validated
keep argument expected.")))
+ .orElse(Keep.FIRST);
+ }
+
+ /**
+ * Returns the positions of the {@code sequence_by} columns, in the listed
order, within the
+ * output row without the PARTITION BY columns.
+ */
+ public static int[] sequenceByOutputIndices(
+ final CallContext callContext, final TableSemantics
tableSemantics, final int argPos) {
+ final List<String> fieldNames =
DataType.getFieldNames(tableSemantics.dataType());
+ final List<Integer> outputIndices =
+
Arrays.stream(ChangelogTypeStrategyUtils.computeOutputIndices(tableSemantics))
+ .boxed()
+ .collect(Collectors.toList());
+ return sequenceBy(callContext, argPos).stream()
+ .mapToInt(column ->
outputIndices.indexOf(fieldNames.indexOf(column)))
+ .toArray();
+ }
+
+ /** Returns the input columns without time attributes. */
+ public static List<Field> inputFields(final TableSemantics tableSemantics)
{
+ final DataType inputType = tableSemantics.dataType();
Review Comment:
Kind of a bug in the framework. It should have removed the time attributes
for you.
##########
flink-table/flink-table-common/src/main/java/org/apache/flink/table/types/inference/strategies/DeduplicateTypeStrategyUtils.java:
##########
@@ -0,0 +1,250 @@
+/*
+ * 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.flink.table.types.inference.strategies;
+
+import org.apache.flink.annotation.Internal;
+import org.apache.flink.table.api.DataTypes.Field;
+import org.apache.flink.table.functions.TableSemantics;
+import org.apache.flink.table.types.DataType;
+import org.apache.flink.table.types.inference.CallContext;
+import org.apache.flink.table.types.logical.LogicalType;
+import org.apache.flink.table.types.logical.LogicalTypeFamily;
+import org.apache.flink.table.types.logical.LogicalTypeRoot;
+import org.apache.flink.table.types.logical.utils.LogicalTypeChecks;
+import org.apache.flink.table.types.logical.utils.LogicalTypeUtils;
+import org.apache.flink.table.types.utils.DataTypeUtils;
+import org.apache.flink.types.ColumnList;
+import org.apache.flink.util.TimeUtils;
+
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Optional;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+/** Argument validation and output type helpers shared by the deduplication
PTFs. */
+@Internal
+public final class DeduplicateTypeStrategyUtils {
+
+ /** Which record of a key is kept. */
+ @Internal
+ public enum Keep {
+ FIRST("first"),
+ LAST("last");
+
+ private final String value;
+
+ Keep(final String value) {
+ this.value = value;
+ }
+
+ /** Returns the mode for an argument value, or empty if the value
names no mode. */
+ public static Optional<Keep> fromValue(final String value) {
+ return Arrays.stream(values()).filter(keep ->
keep.value.equals(value)).findFirst();
+ }
+ }
+
+ /** Returns the {@code keep} argument, or {@link Keep#FIRST} when it is
omitted. */
+ public static Keep keep(final CallContext callContext, final int argPos) {
+ return callContext
+ .getArgumentValue(argPos, String.class)
+ .map(
+ value ->
+ Keep.fromValue(value)
+ .orElseThrow(
+ () ->
+ new
IllegalStateException(
+ "Validated
keep argument expected.")))
+ .orElse(Keep.FIRST);
+ }
+
+ /**
+ * Returns the positions of the {@code sequence_by} columns, in the listed
order, within the
+ * output row without the PARTITION BY columns.
+ */
+ public static int[] sequenceByOutputIndices(
+ final CallContext callContext, final TableSemantics
tableSemantics, final int argPos) {
+ final List<String> fieldNames =
DataType.getFieldNames(tableSemantics.dataType());
+ final List<Integer> outputIndices =
+
Arrays.stream(ChangelogTypeStrategyUtils.computeOutputIndices(tableSemantics))
+ .boxed()
+ .collect(Collectors.toList());
+ return sequenceBy(callContext, argPos).stream()
+ .mapToInt(column ->
outputIndices.indexOf(fieldNames.indexOf(column)))
+ .toArray();
+ }
+
+ /** Returns the input columns without time attributes. */
+ public static List<Field> inputFields(final TableSemantics tableSemantics)
{
+ final DataType inputType = tableSemantics.dataType();
+ return DataType.getFields(
+ DataTypeUtils.replaceLogicalType(
+ inputType,
+
LogicalTypeUtils.removeTimeAttributes(inputType.getLogicalType())));
+ }
+
+ /** Returns the output columns after the PARTITION BY columns, without
time attributes. */
+ public static List<Field> outputFields(final TableSemantics
tableSemantics) {
+ final List<Field> inputFields = inputFields(tableSemantics);
+ return
Arrays.stream(ChangelogTypeStrategyUtils.computeOutputIndices(tableSemantics))
+ .mapToObj(inputFields::get)
+ .collect(Collectors.toList());
+ }
+
+ public static Optional<String> validatePartitionByNoTimeAttribute(
+ final TableSemantics tableSemantics, final String functionName) {
+ final List<Field> fields =
DataType.getFields(tableSemantics.dataType());
+ return Arrays.stream(tableSemantics.partitionByColumns())
+ .mapToObj(fields::get)
+ .filter(
+ field ->
+ LogicalTypeChecks.isTimeAttribute(
+ field.getDataType().getLogicalType()))
+ .findFirst()
+ .map(
+ field ->
+ String.format(
+ "%s does not support a time attribute
as a "
+ + "PARTITION BY column, but
'%s' is one. Use "
+ + "CAST(%s AS %s) in a
subquery first.",
+ functionName,
+ field.getName(),
+ field.getName(),
+
DataTypeUtils.removeTimeAttribute(field.getDataType())
+ .getLogicalType()
+ .asSummaryString()));
+ }
+
+ public static Optional<String> validateKeep(
+ final CallContext callContext, final int argPos, final String
functionName) {
+ if (callContext.isArgumentNull(argPos)) {
+ return Optional.empty();
+ }
+ final String received;
+ if (!callContext.isArgumentLiteral(argPos)) {
+ received = "a non-literal expression";
+ } else {
+ final String value = callContext.getArgumentValue(argPos,
String.class).orElse(null);
+ if (value == null || Keep.fromValue(value).isPresent()) {
+ return Optional.empty();
+ }
+ received = String.format("keep => '%s'", value);
+ }
+ return Optional.of(
+ String.format(
+ "%s requires keep => 'first' or keep => 'last', but
received %s.",
+ functionName, received));
+ }
+
+ public static Optional<String> validateSequenceBy(
+ final CallContext callContext,
+ final TableSemantics tableSemantics,
+ final int argPos,
+ final String functionName) {
+ final List<String> fieldNames =
DataType.getFieldNames(tableSemantics.dataType());
+ final List<DataType> fieldTypes =
DataType.getFieldDataTypes(tableSemantics.dataType());
+ final Set<String> seen = new HashSet<>();
+ for (final String column : sequenceBy(callContext, argPos)) {
+ final int index = fieldNames.indexOf(column);
+ if (index == -1) {
+ return Optional.of(
+ String.format(
+ "The sequence_by column '%s' does not exist in
the input of "
+ + "%s. Available columns are: %s.",
+ column, functionName, String.join(", ",
fieldNames)));
+ }
+ if (!seen.add(column)) {
+ return Optional.of(
+ String.format(
+ "The sequence_by column '%s' is listed more
than once. List each "
+ + "ordering column once.",
+ column));
+ }
+ if (Arrays.stream(tableSemantics.partitionByColumns()).anyMatch(c
-> c == index)) {
+ return Optional.of(
+ String.format(
+ "The sequence_by column '%s' is a PARTITION BY
column, which has "
+ + "the same value for every record of
a key. Use a "
+ + "non-PARTITION BY column.",
+ column));
+ }
+ final LogicalType type = fieldTypes.get(index).getLogicalType();
+ if (!isOrderable(type)) {
+ return Optional.of(
+ String.format(
+ "The sequence_by column '%s' has type '%s',
which cannot order "
+ + "records. Use a numeric, string,
boolean, or date-time "
+ + "column.",
+ column, type.asSummaryString()));
+ }
+ }
+ return Optional.empty();
+ }
+
+ public static Optional<String> validateStateTtl(
Review Comment:
Add a CallContextUtils that can be reused for ttl extraction.
##########
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/functions/ptf/DeduplicateUtils.java:
##########
@@ -0,0 +1,146 @@
+/*
+ * 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.flink.table.runtime.functions.ptf;
+
+import org.apache.flink.annotation.Internal;
+import org.apache.flink.table.api.DataTypes;
+import org.apache.flink.table.data.RowData;
+import org.apache.flink.table.functions.FunctionContext;
+import
org.apache.flink.table.functions.SpecializedFunction.ExpressionEvaluator;
+import org.apache.flink.table.functions.SpecializedFunction.SpecializedContext;
+import org.apache.flink.table.functions.TableSemantics;
+import org.apache.flink.table.types.DataType;
+import
org.apache.flink.table.types.inference.strategies.DeduplicateTypeStrategyUtils.Keep;
+import org.apache.flink.util.FlinkRuntimeException;
+
+import javax.annotation.Nullable;
+
+import java.io.Serializable;
+import java.lang.invoke.MethodHandle;
+
+import static org.apache.flink.table.api.Expressions.$;
+import static org.apache.flink.table.api.Expressions.ifThenElse;
+import static
org.apache.flink.table.types.inference.strategies.DeduplicateTypeStrategy.ARG_INPUT;
+
+/** Record ordering of the built-in deduplication PTFs. */
+@Internal
+public final class DeduplicateUtils {
+
+ public static TableSemantics tableSemantics(final SpecializedContext
context) {
+ return context.getCallContext()
+ .getTableSemantics(ARG_INPUT)
+ .orElseThrow(() -> new IllegalStateException("Table argument
expected."));
+ }
+
+ /**
+ * Returns whether a new record replaces the current one, given the order
of the new record
+ * relative to the current one: with {@code last} the later arrival wins
on a tie, with {@code
+ * first} only a strictly smaller record replaces.
+ */
+ public static boolean replaces(final Keep keep, final int order) {
+ return keep == Keep.LAST ? order >= 0 : order < 0;
+ }
+
+ /**
+ * Compares two records by their {@code sequence_by} values in ascending
order. The first column
+ * decides, later ones break ties, and NULL orders below every other value.
+ */
+ @Internal
+ public static final class SequenceComparator implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ private final int[] indices;
+
+ private final DataType[] types;
+
+ private final ExpressionEvaluator[] evaluators;
+
+ private transient MethodHandle[] compareHandles;
+
+ private transient RowData.FieldGetter[] getters;
+
+ /** Creates a comparator of the columns at {@code indices}, which have
the given types. */
+ public SequenceComparator(
+ final SpecializedContext context, final int[] indices, final
DataType[] types) {
+ this.indices = indices;
+ this.types = types;
+ this.evaluators = new ExpressionEvaluator[types.length];
+ for (int i = 0; i < types.length; i++) {
+ final DataType type = types[i].notNull().toInternal();
+ evaluators[i] =
+ context.createEvaluator(
Review Comment:
This definitely works but since we want optimal performance I wonder whether
using `ComparatorCodeGenerator` is an option? The `ExpressionEvaluator` is very
generic and adds overhead for MethodHandle invocation.
##########
flink-table/flink-table-common/src/main/java/org/apache/flink/table/types/inference/strategies/DeduplicateTypeStrategyUtils.java:
##########
@@ -0,0 +1,250 @@
+/*
+ * 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.flink.table.types.inference.strategies;
+
+import org.apache.flink.annotation.Internal;
+import org.apache.flink.table.api.DataTypes.Field;
+import org.apache.flink.table.functions.TableSemantics;
+import org.apache.flink.table.types.DataType;
+import org.apache.flink.table.types.inference.CallContext;
+import org.apache.flink.table.types.logical.LogicalType;
+import org.apache.flink.table.types.logical.LogicalTypeFamily;
+import org.apache.flink.table.types.logical.LogicalTypeRoot;
+import org.apache.flink.table.types.logical.utils.LogicalTypeChecks;
+import org.apache.flink.table.types.logical.utils.LogicalTypeUtils;
+import org.apache.flink.table.types.utils.DataTypeUtils;
+import org.apache.flink.types.ColumnList;
+import org.apache.flink.util.TimeUtils;
+
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Optional;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+/** Argument validation and output type helpers shared by the deduplication
PTFs. */
+@Internal
+public final class DeduplicateTypeStrategyUtils {
+
+ /** Which record of a key is kept. */
+ @Internal
+ public enum Keep {
+ FIRST("first"),
+ LAST("last");
+
+ private final String value;
+
+ Keep(final String value) {
+ this.value = value;
+ }
+
+ /** Returns the mode for an argument value, or empty if the value
names no mode. */
+ public static Optional<Keep> fromValue(final String value) {
+ return Arrays.stream(values()).filter(keep ->
keep.value.equals(value)).findFirst();
+ }
+ }
+
+ /** Returns the {@code keep} argument, or {@link Keep#FIRST} when it is
omitted. */
+ public static Keep keep(final CallContext callContext, final int argPos) {
+ return callContext
+ .getArgumentValue(argPos, String.class)
+ .map(
+ value ->
+ Keep.fromValue(value)
+ .orElseThrow(
+ () ->
+ new
IllegalStateException(
+ "Validated
keep argument expected.")))
+ .orElse(Keep.FIRST);
+ }
+
+ /**
+ * Returns the positions of the {@code sequence_by} columns, in the listed
order, within the
+ * output row without the PARTITION BY columns.
+ */
+ public static int[] sequenceByOutputIndices(
+ final CallContext callContext, final TableSemantics
tableSemantics, final int argPos) {
+ final List<String> fieldNames =
DataType.getFieldNames(tableSemantics.dataType());
+ final List<Integer> outputIndices =
+
Arrays.stream(ChangelogTypeStrategyUtils.computeOutputIndices(tableSemantics))
+ .boxed()
+ .collect(Collectors.toList());
+ return sequenceBy(callContext, argPos).stream()
+ .mapToInt(column ->
outputIndices.indexOf(fieldNames.indexOf(column)))
+ .toArray();
+ }
+
+ /** Returns the input columns without time attributes. */
+ public static List<Field> inputFields(final TableSemantics tableSemantics)
{
+ final DataType inputType = tableSemantics.dataType();
+ return DataType.getFields(
+ DataTypeUtils.replaceLogicalType(
+ inputType,
+
LogicalTypeUtils.removeTimeAttributes(inputType.getLogicalType())));
+ }
+
+ /** Returns the output columns after the PARTITION BY columns, without
time attributes. */
+ public static List<Field> outputFields(final TableSemantics
tableSemantics) {
+ final List<Field> inputFields = inputFields(tableSemantics);
+ return
Arrays.stream(ChangelogTypeStrategyUtils.computeOutputIndices(tableSemantics))
+ .mapToObj(inputFields::get)
+ .collect(Collectors.toList());
+ }
+
+ public static Optional<String> validatePartitionByNoTimeAttribute(
+ final TableSemantics tableSemantics, final String functionName) {
+ final List<Field> fields =
DataType.getFields(tableSemantics.dataType());
+ return Arrays.stream(tableSemantics.partitionByColumns())
+ .mapToObj(fields::get)
+ .filter(
+ field ->
+ LogicalTypeChecks.isTimeAttribute(
+ field.getDataType().getLogicalType()))
+ .findFirst()
+ .map(
+ field ->
+ String.format(
+ "%s does not support a time attribute
as a "
+ + "PARTITION BY column, but
'%s' is one. Use "
+ + "CAST(%s AS %s) in a
subquery first.",
+ functionName,
+ field.getName(),
+ field.getName(),
+
DataTypeUtils.removeTimeAttribute(field.getDataType())
+ .getLogicalType()
+ .asSummaryString()));
+ }
+
+ public static Optional<String> validateKeep(
+ final CallContext callContext, final int argPos, final String
functionName) {
+ if (callContext.isArgumentNull(argPos)) {
+ return Optional.empty();
+ }
+ final String received;
+ if (!callContext.isArgumentLiteral(argPos)) {
+ received = "a non-literal expression";
+ } else {
+ final String value = callContext.getArgumentValue(argPos,
String.class).orElse(null);
Review Comment:
Add a CallContextUtils that helps you extract the enum from args. Many
functions will need this.
##########
flink-table/flink-table-common/src/main/java/org/apache/flink/table/functions/BuiltInFunctionDefinitions.java:
##########
@@ -939,6 +940,30 @@ ANY, and(logical(LogicalTypeRoot.BOOLEAN), LITERAL)
"org.apache.flink.table.runtime.functions.ptf.FromChangelogFunction")
.build();
+ public static final BuiltInFunctionDefinition DEDUPLICATE =
+ BuiltInFunctionDefinition.newBuilder()
Review Comment:
Also `DeduplicateTypeStrategyUtils` can end up there. So there is one large
class containing everything one needs to understand.
##########
flink-table/flink-table-common/src/main/java/org/apache/flink/table/types/inference/strategies/DeduplicateTypeStrategy.java:
##########
@@ -0,0 +1,151 @@
+/*
+ * 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.flink.table.types.inference.strategies;
+
+import org.apache.flink.annotation.Internal;
+import org.apache.flink.table.api.DataTypes;
+import org.apache.flink.table.api.ValidationException;
+import org.apache.flink.table.connector.ChangelogMode;
+import org.apache.flink.table.functions.ChangelogFunction.ChangelogContext;
+import org.apache.flink.table.functions.ChangelogModeStrategy;
+import org.apache.flink.table.functions.TableSemantics;
+import org.apache.flink.table.types.DataType;
+import org.apache.flink.table.types.inference.CallContext;
+import org.apache.flink.table.types.inference.InputTypeStrategy;
+import org.apache.flink.table.types.inference.TypeStrategy;
+import
org.apache.flink.table.types.inference.strategies.DeduplicateTypeStrategyUtils.Keep;
+import org.apache.flink.types.RowKind;
+
+import java.util.Arrays;
+import java.util.List;
+import java.util.Optional;
+import java.util.stream.Collectors;
+
+/**
+ * Type strategies for the {@code DEDUPLICATE} process table function.
+ *
+ * <p>The output is updating and keyed by the PARTITION BY columns: the
PARTITION BY columns
+ * followed by the remaining input columns, without time attributes.
+ */
+@Internal
+public final class DeduplicateTypeStrategy {
+
+ public static final int ARG_INPUT = 0;
+ public static final int ARG_KEEP = 1;
+ public static final int ARG_SEQUENCE_BY = 2;
+ public static final int ARG_STATE_TTL = 3;
+ public static final int ARG_RESET_TTL_ON_DUPLICATE = 4;
+ private static final String NAME = "DEDUPLICATE";
+
+ public static final InputTypeStrategy INPUT_TYPE_STRATEGY =
+ new ValidationOnlyInputTypeStrategy() {
+ @Override
+ public Optional<List<DataType>> inferInputTypes(
+ final CallContext callContext, final boolean
throwOnFailure) {
+ final Optional<String> error = validate(callContext);
+ if (error.isPresent()) {
+ return callContext.fail(throwOnFailure, "%s",
error.get());
+ }
+ return Optional.of(callContext.getArgumentDataTypes());
+ }
+ };
+
+ public static final TypeStrategy OUTPUT_TYPE_STRATEGY =
+ callContext ->
+ Optional.of(
+ DataTypes.ROW(
+
DeduplicateTypeStrategyUtils.outputFields(
+
tableSemantics(callContext)))
+ .notNull());
+
+ public static final ChangelogModeStrategy CHANGELOG_MODE_STRATEGY =
+ DeduplicateTypeStrategy::inferChangelogMode;
+
+ /** Returns the {@code keep} argument, or {@link Keep#FIRST} when it is
omitted. */
+ public static Keep keep(final CallContext callContext) {
+ return DeduplicateTypeStrategyUtils.keep(callContext, ARG_KEEP);
+ }
+
+ /**
+ * Returns the positions of the {@code sequence_by} columns, in the listed
order, within the
+ * output row without the PARTITION BY columns.
+ */
+ public static int[] sequenceByOutputIndices(final CallContext callContext)
{
+ return DeduplicateTypeStrategyUtils.sequenceByOutputIndices(
+ callContext, tableSemantics(callContext), ARG_SEQUENCE_BY);
+ }
+
+ private static Optional<String> validate(final CallContext callContext) {
+ final TableSemantics tableSemantics = tableSemantics(callContext);
+ return validateNoOrderBy(tableSemantics)
+ .or(
+ () ->
+
DeduplicateTypeStrategyUtils.validatePartitionByNoTimeAttribute(
+ tableSemantics, NAME))
+ .or(() ->
DeduplicateTypeStrategyUtils.validateKeep(callContext, ARG_KEEP, NAME))
+ .or(
+ () ->
+
DeduplicateTypeStrategyUtils.validateSequenceBy(
+ callContext, tableSemantics,
ARG_SEQUENCE_BY, NAME))
+ .or(() ->
DeduplicateTypeStrategyUtils.validateStateTtl(callContext, ARG_STATE_TTL))
+ .or(
+ () ->
+
DeduplicateTypeStrategyUtils.validateResetTtlOnDuplicate(
+ callContext,
ARG_RESET_TTL_ON_DUPLICATE));
+ }
+
+ private static Optional<String> validateNoOrderBy(final TableSemantics
tableSemantics) {
+ if (tableSemantics.orderByColumns().length == 0) {
+ return Optional.empty();
+ }
+ final List<String> fieldNames =
DataType.getFieldNames(tableSemantics.dataType());
+ final String columns =
+ Arrays.stream(tableSemantics.orderByColumns())
+ .mapToObj(fieldNames::get)
+ .collect(Collectors.joining(", "));
+ return Optional.of(
+ String.format(
+ "DEDUPLICATE does not support ORDER BY, but received
ORDER BY %s. "
+ + "Use sequence_by => DESCRIPTOR(%s) instead.",
+ columns, columns));
+ }
+
+ private static ChangelogMode inferChangelogMode(final ChangelogContext
changelogContext) {
+ final ChangelogMode requiredMode =
changelogContext.getRequiredChangelogMode();
+ final ChangelogMode.Builder builder =
+ ChangelogMode.newBuilder()
+ .addContainedKind(RowKind.INSERT)
+ .addContainedKind(RowKind.UPDATE_AFTER);
+ if (requiredMode != null &&
requiredMode.contains(RowKind.UPDATE_BEFORE)) {
+ builder.addContainedKind(RowKind.UPDATE_BEFORE);
+ }
+ return builder.build();
+ }
+
+ private static TableSemantics tableSemantics(final CallContext
callContext) {
Review Comment:
alternatively to a CallContextUtils that all functions can share.
##########
flink-table/flink-table-common/src/main/java/org/apache/flink/table/types/inference/strategies/DeduplicateTypeStrategy.java:
##########
@@ -0,0 +1,151 @@
+/*
+ * 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.flink.table.types.inference.strategies;
+
+import org.apache.flink.annotation.Internal;
+import org.apache.flink.table.api.DataTypes;
+import org.apache.flink.table.api.ValidationException;
+import org.apache.flink.table.connector.ChangelogMode;
+import org.apache.flink.table.functions.ChangelogFunction.ChangelogContext;
+import org.apache.flink.table.functions.ChangelogModeStrategy;
+import org.apache.flink.table.functions.TableSemantics;
+import org.apache.flink.table.types.DataType;
+import org.apache.flink.table.types.inference.CallContext;
+import org.apache.flink.table.types.inference.InputTypeStrategy;
+import org.apache.flink.table.types.inference.TypeStrategy;
+import
org.apache.flink.table.types.inference.strategies.DeduplicateTypeStrategyUtils.Keep;
+import org.apache.flink.types.RowKind;
+
+import java.util.Arrays;
+import java.util.List;
+import java.util.Optional;
+import java.util.stream.Collectors;
+
+/**
+ * Type strategies for the {@code DEDUPLICATE} process table function.
+ *
+ * <p>The output is updating and keyed by the PARTITION BY columns: the
PARTITION BY columns
+ * followed by the remaining input columns, without time attributes.
+ */
+@Internal
+public final class DeduplicateTypeStrategy {
+
+ public static final int ARG_INPUT = 0;
+ public static final int ARG_KEEP = 1;
+ public static final int ARG_SEQUENCE_BY = 2;
+ public static final int ARG_STATE_TTL = 3;
+ public static final int ARG_RESET_TTL_ON_DUPLICATE = 4;
+ private static final String NAME = "DEDUPLICATE";
+
+ public static final InputTypeStrategy INPUT_TYPE_STRATEGY =
+ new ValidationOnlyInputTypeStrategy() {
+ @Override
+ public Optional<List<DataType>> inferInputTypes(
+ final CallContext callContext, final boolean
throwOnFailure) {
+ final Optional<String> error = validate(callContext);
+ if (error.isPresent()) {
+ return callContext.fail(throwOnFailure, "%s",
error.get());
+ }
+ return Optional.of(callContext.getArgumentDataTypes());
+ }
+ };
+
+ public static final TypeStrategy OUTPUT_TYPE_STRATEGY =
+ callContext ->
+ Optional.of(
+ DataTypes.ROW(
+
DeduplicateTypeStrategyUtils.outputFields(
+
tableSemantics(callContext)))
+ .notNull());
+
+ public static final ChangelogModeStrategy CHANGELOG_MODE_STRATEGY =
+ DeduplicateTypeStrategy::inferChangelogMode;
+
+ /** Returns the {@code keep} argument, or {@link Keep#FIRST} when it is
omitted. */
+ public static Keep keep(final CallContext callContext) {
+ return DeduplicateTypeStrategyUtils.keep(callContext, ARG_KEEP);
+ }
+
+ /**
+ * Returns the positions of the {@code sequence_by} columns, in the listed
order, within the
+ * output row without the PARTITION BY columns.
+ */
+ public static int[] sequenceByOutputIndices(final CallContext callContext)
{
+ return DeduplicateTypeStrategyUtils.sequenceByOutputIndices(
+ callContext, tableSemantics(callContext), ARG_SEQUENCE_BY);
+ }
+
+ private static Optional<String> validate(final CallContext callContext) {
+ final TableSemantics tableSemantics = tableSemantics(callContext);
+ return validateNoOrderBy(tableSemantics)
+ .or(
+ () ->
+
DeduplicateTypeStrategyUtils.validatePartitionByNoTimeAttribute(
+ tableSemantics, NAME))
+ .or(() ->
DeduplicateTypeStrategyUtils.validateKeep(callContext, ARG_KEEP, NAME))
+ .or(
+ () ->
+
DeduplicateTypeStrategyUtils.validateSequenceBy(
+ callContext, tableSemantics,
ARG_SEQUENCE_BY, NAME))
+ .or(() ->
DeduplicateTypeStrategyUtils.validateStateTtl(callContext, ARG_STATE_TTL))
+ .or(
+ () ->
+
DeduplicateTypeStrategyUtils.validateResetTtlOnDuplicate(
+ callContext,
ARG_RESET_TTL_ON_DUPLICATE));
+ }
+
+ private static Optional<String> validateNoOrderBy(final TableSemantics
tableSemantics) {
+ if (tableSemantics.orderByColumns().length == 0) {
+ return Optional.empty();
+ }
+ final List<String> fieldNames =
DataType.getFieldNames(tableSemantics.dataType());
+ final String columns =
+ Arrays.stream(tableSemantics.orderByColumns())
+ .mapToObj(fieldNames::get)
+ .collect(Collectors.joining(", "));
+ return Optional.of(
+ String.format(
+ "DEDUPLICATE does not support ORDER BY, but received
ORDER BY %s. "
+ + "Use sequence_by => DESCRIPTOR(%s) instead.",
+ columns, columns));
+ }
+
+ private static ChangelogMode inferChangelogMode(final ChangelogContext
changelogContext) {
+ final ChangelogMode requiredMode =
changelogContext.getRequiredChangelogMode();
+ final ChangelogMode.Builder builder =
+ ChangelogMode.newBuilder()
+ .addContainedKind(RowKind.INSERT)
+ .addContainedKind(RowKind.UPDATE_AFTER);
+ if (requiredMode != null &&
requiredMode.contains(RowKind.UPDATE_BEFORE)) {
+ builder.addContainedKind(RowKind.UPDATE_BEFORE);
+ }
+ return builder.build();
+ }
+
+ private static TableSemantics tableSemantics(final CallContext
callContext) {
Review Comment:
Let's move this into a default `CallContext.getTableSemanticOrThrow`.
--
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]