twalthr commented on code in PR #29967:
URL: https://github.com/apache/flink/pull/29967#discussion_r4681532311
##########
flink-table/flink-table-common/src/main/java/org/apache/flink/table/functions/SpecializedFunction.java:
##########
@@ -113,6 +114,52 @@ ExpressionEvaluator createEvaluator(
*/
ExpressionEvaluator createEvaluator(
BuiltInFunctionDefinition function, DataType outputDataType,
DataType... args);
+
+ /**
+ * Creates a serializable comparator for values of the given data
type, which orders them
+ * ascending with NULL before every other value.
Review Comment:
according to Claude:
```
In Flink SQL, NULLs sort first in ascending order and last in descending
order by default.
```
ideally, we add an additional enum as a parameter to this method to give a
choice:
```
public enum ComparatorOrder {
ASC_NULLS_FIRST,
ASC_NULLS_LAST,
DESC_NULLS_FIRST,
DESC_NULLS_LAST;
}
```
##########
flink-table/flink-table-common/src/main/java/org/apache/flink/table/functions/SpecializedFunction.java:
##########
@@ -113,6 +114,52 @@ ExpressionEvaluator createEvaluator(
*/
ExpressionEvaluator createEvaluator(
BuiltInFunctionDefinition function, DataType outputDataType,
DataType... args);
+
+ /**
+ * Creates a serializable comparator for values of the given data
type, which orders them
+ * ascending with NULL before every other value.
+ *
+ * <p>The comparator uses the same ordering as {@code ORDER BY}. A
{@code ROW} type is
+ * compared field by field, and the compared values are {@link
RowData}. Any other type is
+ * compared as a single value. Types that cannot be ordered are
rejected during planning.
+ *
+ * <p>Initialize the comparator in {@link
UserDefinedFunction#open(FunctionContext)} by
+ * calling {@link GeneratedComparator#open(FunctionContext)}.
+ *
+ * @param dataType type of the compared values, which are expected in
the internal data
+ * structure of the type, see {@link DataType#toInternal()}
+ */
+ GeneratedComparator createComparator(DataType dataType);
+ }
+
+ /**
+ * Serializable comparator that can be passed into a {@link
UserDefinedFunction}. An instance is
+ * not thread-safe and must be opened before values are compared.
+ *
+ * @see ExpressionEvaluatorFactory#createComparator(DataType)
+ */
+ @PublicEvolving
+ interface GeneratedComparator extends Serializable {
Review Comment:
Move the interface one level up. So out of ExpressionEvaluatorFactory and
under SpecializedFunction.
##########
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/functions/DefaultGeneratedComparator.java:
##########
@@ -0,0 +1,70 @@
+/*
+ * 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;
+
+import org.apache.flink.annotation.Internal;
+import org.apache.flink.table.data.GenericRowData;
+import org.apache.flink.table.data.RowData;
+import org.apache.flink.table.functions.FunctionContext;
+import
org.apache.flink.table.functions.SpecializedFunction.GeneratedComparator;
+import org.apache.flink.table.runtime.generated.GeneratedRecordComparator;
+import org.apache.flink.table.runtime.generated.RecordComparator;
+
+/**
+ * Default runtime implementation for {@link GeneratedComparator}, backed by a
generated {@link
+ * RecordComparator}. A value that is not a row is compared as a row of one
field.
+ */
+@Internal
+public final class DefaultGeneratedComparator implements GeneratedComparator {
+
+ private static final long serialVersionUID = 1L;
+
+ private final GeneratedRecordComparator generated;
+
+ private final boolean isRow;
+
+ private transient RecordComparator comparator;
+
+ private transient GenericRowData leftRow;
+
+ private transient GenericRowData rightRow;
+
+ public DefaultGeneratedComparator(
+ final GeneratedRecordComparator generated, final boolean isRow) {
+ this.generated = generated;
+ this.isRow = isRow;
+ }
+
+ @Override
+ public void open(final FunctionContext context) {
+ comparator = generated.newInstance(context.getUserCodeClassLoader());
+ leftRow = new GenericRowData(1);
+ rightRow = new GenericRowData(1);
+ }
+
+ @Override
+ public int compare(final Object left, final Object right) {
+ if (isRow) {
+ return comparator.compare((RowData) left, (RowData) right);
+ }
+ leftRow.setField(0, left);
+ rightRow.setField(0, right);
+ return comparator.compare(leftRow, rightRow);
+ }
Review Comment:
if you think that close() is not needed, we can remove it from the interface
for now
##########
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/functions/ptf/DeduplicateUtils.java:
##########
@@ -0,0 +1,105 @@
+/*
+ * 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.data.utils.ProjectedRowData;
+import org.apache.flink.table.functions.FunctionContext;
+import
org.apache.flink.table.functions.SpecializedFunction.GeneratedComparator;
+import org.apache.flink.table.functions.SpecializedFunction.SpecializedContext;
+import org.apache.flink.table.functions.TableSemantics;
+import org.apache.flink.table.functions.definitions.DeduplicateDefinition.Keep;
+import org.apache.flink.table.types.DataType;
+import org.apache.flink.table.types.inference.utils.CallContextUtils;
+
+import java.io.Serializable;
+import java.util.stream.IntStream;
+
+import static
org.apache.flink.table.functions.definitions.DeduplicateDefinition.ARG_INPUT;
+
+/** Record ordering of the built-in deduplication PTFs. */
+@Internal
+public final class DeduplicateUtils {
+
+ public static TableSemantics tableSemantics(final SpecializedContext
context) {
+ return
CallContextUtils.getTableSemanticsOrThrow(context.getCallContext(), ARG_INPUT);
+ }
+
+ /**
+ * 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 GeneratedComparator comparator;
+
+ private transient ProjectedRowData projectedLeft;
+
+ private transient ProjectedRowData projectedRight;
+
+ /** 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;
+ final DataTypes.Field[] fields =
+ IntStream.range(0, types.length)
+ .mapToObj(i -> DataTypes.FIELD("f" + i, types[i]))
Review Comment:
use `ROW(DataType)`
##########
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/functions/ptf/Deduplicate.java:
##########
@@ -0,0 +1,63 @@
+/*
+ * 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.functions.BuiltInFunctionDefinitions;
+import org.apache.flink.table.functions.UserDefinedFunction;
+import org.apache.flink.table.functions.definitions.DeduplicateDefinition;
+import org.apache.flink.table.functions.definitions.DeduplicateDefinition.Keep;
+import org.apache.flink.table.runtime.functions.BuiltInSpecializedFunction;
+import org.apache.flink.table.types.inference.CallContext;
+
+/**
+ * Runtime implementation of {@link BuiltInFunctionDefinitions#DEDUPLICATE}.
+ *
+ * <pre>
+ * keep sequence_by implementation
Review Comment:
very helpful
##########
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/codegen/sort/GeneratedComparatorUtils.java:
##########
@@ -0,0 +1,52 @@
+/*
+ * 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.planner.codegen.sort;
+
+import org.apache.flink.annotation.Internal;
+import org.apache.flink.configuration.ReadableConfig;
+import
org.apache.flink.table.functions.SpecializedFunction.GeneratedComparator;
+import org.apache.flink.table.planner.plan.nodes.exec.spec.SortSpec;
+import org.apache.flink.table.runtime.functions.DefaultGeneratedComparator;
+import org.apache.flink.table.types.DataType;
+import org.apache.flink.table.types.logical.LogicalType;
+import org.apache.flink.table.types.logical.LogicalTypeRoot;
+import org.apache.flink.table.types.logical.RowType;
+
+/** Generates {@link GeneratedComparator}s with the ordering of {@code ORDER
BY}. */
+@Internal
+public final class GeneratedComparatorUtils {
Review Comment:
drop this class and add this method to `ComparatorCodeGenerator`, keep all
comparator logic in one place
##########
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/codegen/sort/GeneratedComparatorUtils.java:
##########
@@ -0,0 +1,52 @@
+/*
+ * 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.planner.codegen.sort;
+
+import org.apache.flink.annotation.Internal;
+import org.apache.flink.configuration.ReadableConfig;
+import
org.apache.flink.table.functions.SpecializedFunction.GeneratedComparator;
+import org.apache.flink.table.planner.plan.nodes.exec.spec.SortSpec;
+import org.apache.flink.table.runtime.functions.DefaultGeneratedComparator;
+import org.apache.flink.table.types.DataType;
+import org.apache.flink.table.types.logical.LogicalType;
+import org.apache.flink.table.types.logical.LogicalTypeRoot;
+import org.apache.flink.table.types.logical.RowType;
+
+/** Generates {@link GeneratedComparator}s with the ordering of {@code ORDER
BY}. */
+@Internal
+public final class GeneratedComparatorUtils {
+
+ /** Generates a comparator that orders all fields ascending with NULL
first. */
+ public static GeneratedComparator create(
+ final ReadableConfig config, final ClassLoader classLoader, final
DataType dataType) {
+ final LogicalType type = dataType.getLogicalType();
+ final boolean isRow = type.is(LogicalTypeRoot.ROW);
Review Comment:
we can also support structured types here. Just replace this check with
`org.apache.flink.table.types.logical.utils.LogicalTypeChecks#isCompositeType`
and
`org.apache.flink.table.types.logical.utils.LogicalTypeChecks#getFieldTypes`
for a generic implementation
##########
flink-table/flink-table-common/src/main/java/org/apache/flink/table/functions/definitions/DeduplicateDefinition.java:
##########
@@ -0,0 +1,262 @@
+/*
+ * 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.functions.definitions;
+
+import org.apache.flink.annotation.Internal;
+import org.apache.flink.table.api.DataTypes;
+import org.apache.flink.table.api.DataTypes.Field;
+import org.apache.flink.table.connector.ChangelogMode;
+import org.apache.flink.table.functions.BuiltInFunctionDefinition;
+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.StaticArgument;
+import org.apache.flink.table.types.inference.StaticArgumentTrait;
+import org.apache.flink.table.types.inference.TypeStrategy;
+import
org.apache.flink.table.types.inference.strategies.ChangelogTypeStrategyUtils;
+import
org.apache.flink.table.types.inference.strategies.ValidationOnlyInputTypeStrategy;
+import org.apache.flink.table.types.inference.utils.CallContextUtils;
+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.utils.DataTypeUtils;
+import org.apache.flink.types.ColumnList;
+import org.apache.flink.types.Row;
+import org.apache.flink.types.RowKind;
+
+import java.util.Arrays;
+import java.util.EnumSet;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Optional;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+import static org.apache.flink.table.functions.FunctionKind.PROCESS_TABLE;
+
+/**
+ * Definition of the {@code DEDUPLICATE} built-in 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.
+ */
+@Internal
+public final class DeduplicateDefinition {
+
+ 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;
+
+ private static final String NAME = "DEDUPLICATE";
+
+ /** Which record of a key is kept. */
+ @Internal
+ public enum Keep {
+ FIRST,
+ LAST
+ }
+
+ 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());
+ }
+ };
+
+ static final TypeStrategy OUTPUT_TYPE_STRATEGY =
+ callContext ->
+
Optional.of(DataTypes.ROW(outputFields(tableSemantics(callContext))).notNull());
+
+ static final ChangelogModeStrategy CHANGELOG_MODE_STRATEGY =
+ DeduplicateDefinition::inferChangelogMode;
+
+ public static final BuiltInFunctionDefinition INSTANCE =
+ BuiltInFunctionDefinition.newBuilder()
+ .name(NAME)
+ .kind(PROCESS_TABLE)
+ .staticArguments(
+ StaticArgument.table(
+ "input",
+ Row.class,
+ false,
+ EnumSet.of(
+ StaticArgumentTrait.TABLE,
+
StaticArgumentTrait.SET_SEMANTIC_TABLE,
+ StaticArgumentTrait.NO_ORDER_BY)),
+ StaticArgument.scalar("keep", DataTypes.STRING(),
true),
+ StaticArgument.scalar("sequence_by",
DataTypes.DESCRIPTOR(), true),
+ StaticArgument.scalar(
+ "state_ttl",
DataTypes.INTERVAL(DataTypes.SECOND()), true))
+ .changelogModeStrategy(CHANGELOG_MODE_STRATEGY)
+ .inputTypeStrategy(INPUT_TYPE_STRATEGY)
+ .outputTypeStrategy(OUTPUT_TYPE_STRATEGY)
+
.runtimeClass("org.apache.flink.table.runtime.functions.ptf.Deduplicate")
+ .build();
+
+ /** Returns the {@code keep} argument, or {@link Keep#FIRST} when it is
omitted. */
+ public static Keep keep(final CallContext callContext) {
+ return CallContextUtils.getEnumArgument(callContext, ARG_KEEP,
Keep.class)
+ .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 = tableSemantics(callContext);
+ final List<String> fieldNames =
DataType.getFieldNames(tableSemantics.dataType());
+ final List<Integer> outputIndices =
+
Arrays.stream(ChangelogTypeStrategyUtils.computeOutputIndices(tableSemantics))
+ .boxed()
+ .collect(Collectors.toList());
+ return sequenceBy(callContext).stream()
+ .mapToInt(column ->
outputIndices.indexOf(fieldNames.indexOf(column)))
+ .toArray();
+ }
+
+ private static Optional<String> validate(final CallContext callContext) {
+ final TableSemantics tableSemantics = tableSemantics(callContext);
+ return validatePartitionByNoTimeAttribute(tableSemantics)
+ .or(
+ () ->
+ CallContextUtils.validateEnumArgument(
+ callContext, ARG_KEEP, "keep", NAME,
Keep.class))
+ .or(() -> validateSequenceBy(callContext, tableSemantics))
+ .or(() -> CallContextUtils.validateStateTtl(callContext,
ARG_STATE_TTL));
Review Comment:
reads nicely
##########
flink-table/flink-table-common/src/main/java/org/apache/flink/table/functions/definitions/DeduplicateDefinition.java:
##########
@@ -0,0 +1,262 @@
+/*
+ * 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.functions.definitions;
+
+import org.apache.flink.annotation.Internal;
+import org.apache.flink.table.api.DataTypes;
+import org.apache.flink.table.api.DataTypes.Field;
+import org.apache.flink.table.connector.ChangelogMode;
+import org.apache.flink.table.functions.BuiltInFunctionDefinition;
+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.StaticArgument;
+import org.apache.flink.table.types.inference.StaticArgumentTrait;
+import org.apache.flink.table.types.inference.TypeStrategy;
+import
org.apache.flink.table.types.inference.strategies.ChangelogTypeStrategyUtils;
+import
org.apache.flink.table.types.inference.strategies.ValidationOnlyInputTypeStrategy;
+import org.apache.flink.table.types.inference.utils.CallContextUtils;
+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.utils.DataTypeUtils;
+import org.apache.flink.types.ColumnList;
+import org.apache.flink.types.Row;
+import org.apache.flink.types.RowKind;
+
+import java.util.Arrays;
+import java.util.EnumSet;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Optional;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+import static org.apache.flink.table.functions.FunctionKind.PROCESS_TABLE;
+
+/**
+ * Definition of the {@code DEDUPLICATE} built-in 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.
+ */
+@Internal
+public final class DeduplicateDefinition {
+
+ 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;
+
+ private static final String NAME = "DEDUPLICATE";
+
+ /** Which record of a key is kept. */
+ @Internal
+ public enum Keep {
+ FIRST,
+ LAST
+ }
+
+ 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());
+ }
+ };
+
+ static final TypeStrategy OUTPUT_TYPE_STRATEGY =
+ callContext ->
+
Optional.of(DataTypes.ROW(outputFields(tableSemantics(callContext))).notNull());
+
+ static final ChangelogModeStrategy CHANGELOG_MODE_STRATEGY =
+ DeduplicateDefinition::inferChangelogMode;
+
+ public static final BuiltInFunctionDefinition INSTANCE =
+ BuiltInFunctionDefinition.newBuilder()
+ .name(NAME)
+ .kind(PROCESS_TABLE)
+ .staticArguments(
+ StaticArgument.table(
+ "input",
+ Row.class,
+ false,
+ EnumSet.of(
+ StaticArgumentTrait.TABLE,
+
StaticArgumentTrait.SET_SEMANTIC_TABLE,
+ StaticArgumentTrait.NO_ORDER_BY)),
+ StaticArgument.scalar("keep", DataTypes.STRING(),
true),
+ StaticArgument.scalar("sequence_by",
DataTypes.DESCRIPTOR(), true),
+ StaticArgument.scalar(
+ "state_ttl",
DataTypes.INTERVAL(DataTypes.SECOND()), true))
+ .changelogModeStrategy(CHANGELOG_MODE_STRATEGY)
+ .inputTypeStrategy(INPUT_TYPE_STRATEGY)
+ .outputTypeStrategy(OUTPUT_TYPE_STRATEGY)
+
.runtimeClass("org.apache.flink.table.runtime.functions.ptf.Deduplicate")
+ .build();
+
+ /** Returns the {@code keep} argument, or {@link Keep#FIRST} when it is
omitted. */
+ public static Keep keep(final CallContext callContext) {
+ return CallContextUtils.getEnumArgument(callContext, ARG_KEEP,
Keep.class)
+ .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 = tableSemantics(callContext);
+ final List<String> fieldNames =
DataType.getFieldNames(tableSemantics.dataType());
+ final List<Integer> outputIndices =
+
Arrays.stream(ChangelogTypeStrategyUtils.computeOutputIndices(tableSemantics))
+ .boxed()
+ .collect(Collectors.toList());
+ return sequenceBy(callContext).stream()
+ .mapToInt(column ->
outputIndices.indexOf(fieldNames.indexOf(column)))
+ .toArray();
+ }
+
+ private static Optional<String> validate(final CallContext callContext) {
+ final TableSemantics tableSemantics = tableSemantics(callContext);
+ return validatePartitionByNoTimeAttribute(tableSemantics)
+ .or(
+ () ->
+ CallContextUtils.validateEnumArgument(
+ callContext, ARG_KEEP, "keep", NAME,
Keep.class))
+ .or(() -> validateSequenceBy(callContext, tableSemantics))
+ .or(() -> CallContextUtils.validateStateTtl(callContext,
ARG_STATE_TTL));
+ }
+
+ 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) {
+ return CallContextUtils.getTableSemanticsOrThrow(callContext,
ARG_INPUT);
+ }
+
+ /** Returns the output columns after the PARTITION BY columns. */
+ private static List<Field> outputFields(final TableSemantics
tableSemantics) {
+ final List<Field> inputFields =
DataType.getFields(tableSemantics.dataType());
+ return
Arrays.stream(ChangelogTypeStrategyUtils.computeOutputIndices(tableSemantics))
+ .mapToObj(inputFields::get)
+ .collect(Collectors.toList());
+ }
+
+ private static Optional<String> validatePartitionByNoTimeAttribute(
+ final TableSemantics tableSemantics) {
+ final List<Field> fields =
DataType.getFields(tableSemantics.dataType());
+ return Arrays.stream(tableSemantics.partitionByColumns())
+ .mapToObj(fields::get)
+ .filter(
+ field ->
+ LogicalTypeChecks.isTimeAttribute(
Review Comment:
The time attribute logic still feels misplaced here. The framework should
fully handle this for the function.
--
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]