You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@flink.apache.org by GitBox <gi...@apache.org> on 2021/01/06 11:53:58 UTC

[GitHub] [flink] dawidwys commented on a change in pull request #14378: [FLINK-20522][table] Make implementing a built-in function straightforward

dawidwys commented on a change in pull request #14378:
URL: https://github.com/apache/flink/pull/14378#discussion_r552530118



##########
File path: flink-table/flink-table-common/src/main/java/org/apache/flink/table/functions/SpecializedFunction.java
##########
@@ -0,0 +1,73 @@
+/*
+ * 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;
+
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.configuration.ReadableConfig;
+import org.apache.flink.table.api.TableException;
+import org.apache.flink.table.catalog.DataTypeFactory;
+import org.apache.flink.table.types.inference.CallContext;
+
+/**
+ * A {@link FunctionDefinition} that can provide a runtime implementation (i.e. the function's body)
+ * that is specialized for the given call and session.
+ *
+ * <p>The planner tries to defer the specialization until shortly before code generation, where the
+ * information given by a {@link FunctionDefinition} is not enough anymore and a subclass of
+ * {@link UserDefinedFunction} is required for runtime.
+ *
+ * <p>This interface is useful when the runtime code should know about information that is only available
+ * after planning (e.g. local session time zone or precision/scale of decimal return type).
+ *
+ * <p>A {@link UserDefinedFunction} that is registered in the API is implicitly specialized but can
+ * also implement this interface to reconfigure itself before runtime.
+ */
+@PublicEvolving
+public interface SpecializedFunction extends FunctionDefinition {
+
+	/**
+	 * Provides a runtime implementation that is specialized for the given call and session.
+	 *
+	 * <p>The method must return an instance of {@link UserDefinedFunction} or throw a {@link TableException}
+	 * if the given call is not supported. The returned instance must have the same {@link FunctionDefinition}
+	 * semantics but can have a different {@link #getTypeInference(DataTypeFactory)} implementation.

Review comment:
       I am wondering if we should be more elaborate here and add a more prominent warning.
   
   Can the type inference change arbitrarily? I think it is quite easy to abuse it, e.g. :
   ```
   	/**
   	 * A specialized "compile time" function for returning the argument's data type.
   	 */
   	public static class NumberScalarFunction extends ScalarFunction implements SpecializedFunction {
   
   		private final boolean doubleNumber;
   
   		public NumberScalarFunction() {
   			this.doubleNumber = false;
   		}
   
   		public NumberScalarFunction(boolean doubleNumber) {
   			this.doubleNumber = doubleNumber;
   		}
   
   		@SuppressWarnings("unused")
   		public Object eval(@DataTypeHint(inputGroup = InputGroup.ANY) Object unused) {
   			if (doubleNumber) {
   				return 0D;
   			} else {
   				return 0;
   			}
   		}
   
   		@Override
   		public TypeInference getTypeInference(DataTypeFactory typeFactory) {
   			return TypeInference.newBuilder()
   				.inputTypeStrategy(InputTypeStrategies.WILDCARD)
   				.outputTypeStrategy(doubleNumber ? TypeStrategies.explicit(DataTypes.DOUBLE()) : TypeStrategies.explicit(DataTypes.INT()))
   				.build();
   		}
   
   		@Override
   		public NumberScalarFunction specialize(SpecializedContext context) {
   			if (context.getCallContext().isArgumentLiteral(0) && context
   				.getCallContext()
   				.getArgumentValue(0, Boolean.class)
   				.get()) { // this could be based e.g. on the input type
   				return new NumberScalarFunction(true);
   			} else {
   				return new NumberScalarFunction(false);
   			}
   		}
   	}
   
   	public static class DoubleScalarFunction extends ScalarFunction {
   
   		public String eval(double unused) {
   			return Double.toString(unused);
   		}
   
   		public int eval(int number) {
   			return number;
   		}
   
   		@Override
   		public TypeInference getTypeInference(DataTypeFactory typeFactory) {
   			Map<InputTypeStrategy, TypeStrategy> map = new HashMap<>();
   			map.put(
   				InputTypeStrategies.sequence(InputTypeStrategies.logical(LogicalTypeRoot.DOUBLE)),
   				TypeStrategies.explicit(DataTypes.DOUBLE())
   			);
   			map.put(
   				InputTypeStrategies.sequence(InputTypeStrategies.logical(LogicalTypeRoot.INTEGER)),
   				TypeStrategies.explicit(DataTypes.INT())
   			);
   			return TypeInference.newBuilder()
   				.inputTypeStrategy(InputTypeStrategies.sequence(InputTypeStrategies.or(
   					InputTypeStrategies.logical(LogicalTypeRoot.DOUBLE),
   					InputTypeStrategies.logical(LogicalTypeRoot.INTEGER)
   				)))
   				.outputTypeStrategy(
   					TypeStrategies.mapping(
   						map
   					)
   				)
   				.build();
   		}
   	}
   
   And then: 
   
   		tEnv().createTemporarySystemFunction("Innner", NumberScalarFunction.class);
   		tEnv().createTemporarySystemFunction("Outerr", DoubleScalarFunction.class);
   
   		final TableResult result = tEnv()
   			.executeSql(
   				"SELECT "
   					+ " Outerr(Innner(s)) "
   					+ "FROM SourceTable");
   ```
   
   The end result type will be `INT` though some invokations of the inner function might produce double type.
   
   Correct me if I am wrong but the specialized function should have a `TypeInference` that is a specialized version of the original one.
   
   In short I just thought it would be better to make it very clear this is a rather low level and very powerful kind of function that requires a lot of thought.

##########
File path: flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/functions/aggregate/BuiltInAggregateFunction.java
##########
@@ -0,0 +1,120 @@
+/*
+ * 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.aggregate;
+
+import org.apache.flink.annotation.Internal;
+import org.apache.flink.table.catalog.DataTypeFactory;
+import org.apache.flink.table.functions.AggregateFunction;
+import org.apache.flink.table.functions.BuiltInFunctionDefinition;
+import org.apache.flink.table.functions.FunctionRequirement;
+import org.apache.flink.table.functions.SpecializedFunction.SpecializedContext;
+import org.apache.flink.table.types.DataType;
+import org.apache.flink.table.types.inference.CallContext;
+import org.apache.flink.table.types.inference.TypeInference;
+import org.apache.flink.table.types.inference.TypeStrategies;
+import org.apache.flink.table.types.utils.DataTypeUtils;
+import org.apache.flink.util.Preconditions;
+
+import javax.annotation.Nullable;
+
+import java.util.List;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+/**
+ * Base class for runtime implementation represented as {@link AggregateFunction} that is constructed
+ * from {@link BuiltInFunctionDefinition#specialize(SpecializedContext)}.
+ *
+ * <p>Subclasses must offer a constructor that takes {@link SpecializedContext} if they are constructed
+ * from a {@link BuiltInFunctionDefinition}. Otherwise the {@link #BuiltInAggregateFunction()} constructor
+ * might be more appropriate.
+ *
+ * <p>By default, all built-in functions work on internal data structures. However, this can be
+ * changed by overriding {@link #getArgumentDataTypes()}, {@link #getAccumulatorDataType()}, and
+ * {@link #getOutputDataType()}. Or by overriding {@link #getTypeInference(DataTypeFactory)} directly.
+ *
+ * <p>Since the accumulator type is runtime specific, it must be declared explicitly; otherwise it is
+ * derived from the output type.
+ */
+@Internal
+public abstract class BuiltInAggregateFunction<T, ACC> extends AggregateFunction<T, ACC> {
+
+	// can be null if a Calcite function definition is the origin
+	private transient @Nullable BuiltInFunctionDefinition definition;
+
+	private transient List<DataType> argumentDataTypes;
+
+	private transient DataType outputDataType;
+
+	public BuiltInAggregateFunction(BuiltInFunctionDefinition definition, SpecializedContext context) {
+		this.definition = definition;
+		final CallContext callContext = context.getCallContext();
+		argumentDataTypes = callContext.getArgumentDataTypes().stream()
+			.map(DataTypeUtils::toInternalDataType)
+			.collect(Collectors.toList());
+		outputDataType = callContext.getOutputDataType()
+			.map(DataTypeUtils::toInternalDataType)
+			.orElseThrow(IllegalStateException::new);
+	}
+
+	public BuiltInAggregateFunction() {

Review comment:
       Can it be `protected` then?




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org