You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@flink.apache.org by go...@apache.org on 2021/01/19 14:19:51 UTC
[flink] 03/05: [FLINK-20949][table-planner-blink] Introduce
StreamPhysicalLegacySink,
and make StreamExecLegacySink only extended from ExecNode
This is an automated email from the ASF dual-hosted git repository.
godfrey pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/flink.git
commit e99b6e1e692200655c64a15978581e89565a50f8
Author: godfreyhe <go...@163.com>
AuthorDate: Thu Jan 14 10:19:34 2021 +0800
[FLINK-20949][table-planner-blink] Introduce StreamPhysicalLegacySink, and make StreamExecLegacySink only extended from ExecNode
This closes #14637
---
.../nodes/exec/common/CommonExecLegacySink.java | 196 ++++++++++++++++++++
.../nodes/exec/stream/StreamExecLegacySink.java | 85 +++++++++
.../plan/nodes/exec/utils/ExecNodePlanDumper.java | 2 +
.../table/planner/codegen/SinkCodeGenerator.scala | 37 ++--
.../nodes/physical/batch/BatchExecLegacySink.scala | 19 +-
.../physical/stream/StreamExecLegacySink.scala | 199 ---------------------
.../physical/stream/StreamPhysicalLegacySink.scala | 70 ++++++++
.../FlinkChangelogModeInferenceProgram.scala | 4 +-
.../planner/plan/rules/FlinkStreamRuleSets.scala | 2 +-
...le.scala => StreamPhysicalLegacySinkRule.scala} | 14 +-
.../planner/plan/utils/UpdatingPlanChecker.scala | 5 +-
11 files changed, 395 insertions(+), 238 deletions(-)
diff --git a/flink-table/flink-table-planner-blink/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/common/CommonExecLegacySink.java b/flink-table/flink-table-planner-blink/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/common/CommonExecLegacySink.java
new file mode 100644
index 0000000..1d95a1a
--- /dev/null
+++ b/flink-table/flink-table-planner-blink/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/common/CommonExecLegacySink.java
@@ -0,0 +1,196 @@
+/*
+ * 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.plan.nodes.exec.common;
+
+import org.apache.flink.api.common.typeinfo.TypeInformation;
+import org.apache.flink.api.dag.Transformation;
+import org.apache.flink.streaming.api.datastream.DataStream;
+import org.apache.flink.streaming.api.datastream.DataStreamSink;
+import org.apache.flink.streaming.api.transformations.OneInputTransformation;
+import org.apache.flink.table.api.TableException;
+import org.apache.flink.table.data.RowData;
+import org.apache.flink.table.planner.codegen.CodeGenUtils;
+import org.apache.flink.table.planner.codegen.CodeGeneratorContext;
+import org.apache.flink.table.planner.codegen.SinkCodeGenerator;
+import org.apache.flink.table.planner.delegation.PlannerBase;
+import org.apache.flink.table.planner.plan.nodes.exec.ExecEdge;
+import org.apache.flink.table.planner.plan.nodes.exec.ExecNode;
+import org.apache.flink.table.planner.plan.nodes.exec.ExecNodeBase;
+import org.apache.flink.table.planner.sinks.DataStreamTableSink;
+import org.apache.flink.table.planner.sinks.TableSinkUtils;
+import org.apache.flink.table.runtime.operators.CodeGenOperatorFactory;
+import org.apache.flink.table.sinks.AppendStreamTableSink;
+import org.apache.flink.table.sinks.RetractStreamTableSink;
+import org.apache.flink.table.sinks.StreamTableSink;
+import org.apache.flink.table.sinks.TableSink;
+import org.apache.flink.table.sinks.UpsertStreamTableSink;
+import org.apache.flink.table.types.DataType;
+import org.apache.flink.table.types.logical.LogicalType;
+import org.apache.flink.table.types.logical.RowType;
+
+import javax.annotation.Nullable;
+
+import java.util.Collections;
+
+/**
+ * Base {@link ExecNode} to to write data into an external sink defined by a {@link TableSink}.
+ *
+ * @param <T> The return type of the {@link TableSink}.
+ */
+public abstract class CommonExecLegacySink<T> extends ExecNodeBase<Object> {
+ protected final TableSink<T> tableSink;
+ protected final @Nullable String[] upsertKeys;
+ protected final boolean needRetraction;
+ protected final boolean isStreaming;
+
+ public CommonExecLegacySink(
+ TableSink<T> tableSink,
+ @Nullable String[] upsertKeys,
+ boolean needRetraction,
+ boolean isStreaming,
+ ExecEdge inputEdge,
+ LogicalType outputType,
+ String description) {
+ super(Collections.singletonList(inputEdge), outputType, description);
+ this.tableSink = tableSink;
+ this.upsertKeys = upsertKeys;
+ this.needRetraction = needRetraction;
+ this.isStreaming = isStreaming;
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ protected Transformation<Object> translateToPlanInternal(PlannerBase planner) {
+ if (tableSink instanceof StreamTableSink) {
+ final Transformation<T> transform;
+ if (tableSink instanceof RetractStreamTableSink) {
+ transform = translateToTransformation(planner, true);
+ } else if (tableSink instanceof UpsertStreamTableSink) {
+ UpsertStreamTableSink<T> upsertSink = (UpsertStreamTableSink<T>) tableSink;
+ final boolean isAppendOnlyTable = !needRetraction;
+ upsertSink.setIsAppendOnly(isAppendOnlyTable);
+ if (upsertKeys != null) {
+ upsertSink.setKeyFields(upsertKeys);
+ } else {
+ if (isAppendOnlyTable) {
+ upsertSink.setKeyFields(null);
+ } else {
+ throw new TableException(
+ "UpsertStreamTableSink requires that Table has a full primary keys if it is updated.");
+ }
+ }
+
+ transform = translateToTransformation(planner, true);
+ } else if (tableSink instanceof AppendStreamTableSink) {
+ // verify table is an insert-only (append-only) table
+ if (needRetraction) {
+ throw new TableException(
+ "AppendStreamTableSink requires that Table has only insert changes.");
+ }
+ transform = translateToTransformation(planner, false);
+ } else {
+ if (isStreaming) {
+ throw new TableException(
+ "Stream Tables can only be emitted by AppendStreamTableSink, "
+ + "RetractStreamTableSink, or UpsertStreamTableSink.");
+ } else {
+ transform = translateToTransformation(planner, false);
+ }
+ }
+
+ final DataStream<T> dataStream = new DataStream<T>(planner.getExecEnv(), transform);
+ final DataStreamSink<?> dsSink =
+ ((StreamTableSink<T>) tableSink).consumeDataStream(dataStream);
+ if (dsSink == null) {
+ throw new TableException(
+ String.format(
+ "The StreamTableSink#consumeDataStream(DataStream) must be implemented "
+ + "and return the sink transformation DataStreamSink. "
+ + "However, %s doesn't implement this method.",
+ tableSink.getClass().getCanonicalName()));
+ }
+ return dsSink.getTransformation();
+ } else if (tableSink instanceof DataStreamTableSink) {
+ // In case of table to DataStream through
+ // StreamTableEnvironment#toAppendStream/toRetractStream,
+ // we insert a DataStreamTableSink that wraps the given DataStream as a LogicalSink. It
+ // is no real table sink, so we just need translate its input to Transformation.
+ return (Transformation<Object>)
+ translateToTransformation(
+ planner, ((DataStreamTableSink<T>) tableSink).withChangeFlag());
+ } else {
+ throw new TableException(
+ String.format(
+ "Only Support StreamTableSink! However %s is not a StreamTableSink.",
+ tableSink.getClass().getCanonicalName()));
+ }
+ }
+
+ /** Check whether the given row type is legal and do some conversion if needed. */
+ protected abstract RowType checkAndConvertInputTypeIfNeeded(RowType inputRowType);
+
+ /**
+ * Translates {@link TableSink} into a {@link Transformation}.
+ *
+ * @param withChangeFlag Set to true to emit records with change flags.
+ * @return The {@link Transformation} that corresponds to the translated {@link TableSink}.
+ */
+ @SuppressWarnings("unchecked")
+ private Transformation<T> translateToTransformation(
+ PlannerBase planner, boolean withChangeFlag) {
+ // if no change flags are requested, verify table is an insert-only (append-only) table.
+ if (!withChangeFlag && needRetraction) {
+ throw new TableException(
+ "Table is not an append-only table. "
+ + "Use the toRetractStream() in order to handle add and retract messages.");
+ }
+
+ final ExecNode<RowData> inputNode = (ExecNode<RowData>) getInputNodes().get(0);
+ final Transformation<RowData> inputTransform = inputNode.translateToPlan(planner);
+ final RowType inputRowType = (RowType) inputNode.getOutputType();
+ final RowType convertedInputRowType = checkAndConvertInputTypeIfNeeded(inputRowType);
+ final DataType resultDataType = tableSink.getConsumedDataType();
+ if (CodeGenUtils.isInternalClass(resultDataType)) {
+ return (Transformation<T>) inputTransform;
+ } else {
+ final DataType physicalOutputType =
+ TableSinkUtils.inferSinkPhysicalDataType(
+ resultDataType, convertedInputRowType, withChangeFlag);
+
+ final TypeInformation<T> outputTypeInfo =
+ SinkCodeGenerator.deriveSinkOutputTypeInfo(
+ tableSink, physicalOutputType, withChangeFlag);
+
+ final CodeGenOperatorFactory<T> converterOperator =
+ SinkCodeGenerator.generateRowConverterOperator(
+ new CodeGeneratorContext(planner.getTableConfig()),
+ convertedInputRowType,
+ tableSink,
+ physicalOutputType,
+ withChangeFlag,
+ "SinkConversion");
+ return new OneInputTransformation<>(
+ inputTransform,
+ "SinkConversionTo" + resultDataType.getConversionClass().getSimpleName(),
+ converterOperator,
+ outputTypeInfo,
+ inputTransform.getParallelism());
+ }
+ }
+}
diff --git a/flink-table/flink-table-planner-blink/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/stream/StreamExecLegacySink.java b/flink-table/flink-table-planner-blink/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/stream/StreamExecLegacySink.java
new file mode 100644
index 0000000..e8e63b7
--- /dev/null
+++ b/flink-table/flink-table-planner-blink/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/stream/StreamExecLegacySink.java
@@ -0,0 +1,85 @@
+/*
+ * 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.plan.nodes.exec.stream;
+
+import org.apache.flink.table.api.TableException;
+import org.apache.flink.table.planner.plan.nodes.exec.ExecEdge;
+import org.apache.flink.table.planner.plan.nodes.exec.ExecNode;
+import org.apache.flink.table.planner.plan.nodes.exec.common.CommonExecLegacySink;
+import org.apache.flink.table.runtime.typeutils.TypeCheckUtils;
+import org.apache.flink.table.sinks.TableSink;
+import org.apache.flink.table.types.logical.LogicalType;
+import org.apache.flink.table.types.logical.RowType;
+import org.apache.flink.table.types.logical.TimestampType;
+
+import javax.annotation.Nullable;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.stream.Collectors;
+
+/**
+ * Stream {@link ExecNode} to to write data into an external sink defined by a {@link TableSink}.
+ *
+ * @param <T> The return type of the {@link TableSink}.
+ */
+public class StreamExecLegacySink<T> extends CommonExecLegacySink<T>
+ implements StreamExecNode<Object> {
+
+ public StreamExecLegacySink(
+ TableSink<T> tableSink,
+ @Nullable String[] upsertKeys,
+ boolean needRetraction,
+ ExecEdge inputEdge,
+ LogicalType outputType,
+ String description) {
+ super(tableSink, upsertKeys, needRetraction, true, inputEdge, outputType, description);
+ }
+
+ protected RowType checkAndConvertInputTypeIfNeeded(RowType inputRowType) {
+ final List<Integer> rowtimeFieldIndices = new ArrayList<>();
+ for (int i = 0; i < inputRowType.getFieldCount(); ++i) {
+ if (TypeCheckUtils.isRowTime(inputRowType.getTypeAt(i))) {
+ rowtimeFieldIndices.add(i);
+ }
+ }
+
+ if (rowtimeFieldIndices.size() > 1) {
+ throw new TableException(
+ String.format(
+ "Found more than one rowtime field: [%s] in "
+ + "the table that should be converted to a DataStream.\n"
+ + "Please select the rowtime field that should be used as event-time timestamp for the "
+ + "DataStream by casting all other fields to TIMESTAMP.",
+ rowtimeFieldIndices.stream()
+ .map(i -> inputRowType.getFieldNames().get(i))
+ .collect(Collectors.joining(", "))));
+ } else if (rowtimeFieldIndices.size() == 1) {
+ LogicalType[] convertedFieldTypes =
+ inputRowType.getChildren().stream()
+ .map(t -> TypeCheckUtils.isRowTime(t) ? new TimestampType(3) : t)
+ .toArray(LogicalType[]::new);
+
+ return RowType.of(
+ convertedFieldTypes, inputRowType.getFieldNames().toArray(new String[0]));
+ } else {
+ return inputRowType;
+ }
+ }
+}
diff --git a/flink-table/flink-table-planner-blink/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/utils/ExecNodePlanDumper.java b/flink-table/flink-table-planner-blink/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/utils/ExecNodePlanDumper.java
index 1eadbc9..2e2c79b 100644
--- a/flink-table/flink-table-planner-blink/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/utils/ExecNodePlanDumper.java
+++ b/flink-table/flink-table-planner-blink/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/utils/ExecNodePlanDumper.java
@@ -20,6 +20,7 @@ package org.apache.flink.table.planner.plan.nodes.exec.utils;
import org.apache.flink.table.planner.plan.nodes.calcite.LegacySink;
import org.apache.flink.table.planner.plan.nodes.exec.ExecNode;
+import org.apache.flink.table.planner.plan.nodes.exec.common.CommonExecLegacySink;
import org.apache.flink.table.planner.plan.nodes.exec.common.CommonExecSink;
import org.apache.flink.table.planner.plan.nodes.exec.visitor.ExecNodeVisitor;
import org.apache.flink.table.planner.plan.nodes.exec.visitor.ExecNodeVisitorImpl;
@@ -159,6 +160,7 @@ public class ExecNodePlanDumper {
int reuseId = reuseInfo.getReuseId(node);
boolean isReuseNode = reuseId >= 0;
if (node instanceof LegacySink
+ || node instanceof CommonExecLegacySink
|| node instanceof CommonExecSink
|| (isReuseNode && isFirstVisit)) {
if (isReuseNode) {
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/planner/codegen/SinkCodeGenerator.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/planner/codegen/SinkCodeGenerator.scala
index e5e4edd..2d135da 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/planner/codegen/SinkCodeGenerator.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/planner/codegen/SinkCodeGenerator.scala
@@ -24,49 +24,52 @@ import org.apache.flink.api.java.tuple.{Tuple2 => JTuple2}
import org.apache.flink.api.java.typeutils.runtime.TupleSerializerBase
import org.apache.flink.api.java.typeutils.{PojoTypeInfo, TupleTypeInfo}
import org.apache.flink.api.scala.createTuple2TypeInformation
-import org.apache.flink.table.api.{TableConfig, TableException}
+import org.apache.flink.table.api.TableException
import org.apache.flink.table.data.util.RowDataUtil
import org.apache.flink.table.data.{GenericRowData, RowData}
-import org.apache.flink.table.planner.codegen.CodeGenUtils.{genToExternalConverter, genToExternalConverterWithLegacy}
+import org.apache.flink.table.planner.codegen.CodeGenUtils.genToExternalConverterWithLegacy
import org.apache.flink.table.planner.codegen.GeneratedExpression.NO_CODE
import org.apache.flink.table.planner.codegen.OperatorCodeGenerator.generateCollect
-import org.apache.flink.table.planner.sinks.TableSinkUtils
import org.apache.flink.table.runtime.operators.CodeGenOperatorFactory
import org.apache.flink.table.runtime.types.TypeInfoDataTypeConverter.fromDataTypeToTypeInfo
import org.apache.flink.table.runtime.types.TypeInfoLogicalTypeConverter.fromTypeInfoToLogicalType
import org.apache.flink.table.sinks.TableSink
+import org.apache.flink.table.types.DataType
import org.apache.flink.table.types.logical.RowType
import scala.collection.JavaConverters._
object SinkCodeGenerator {
- /** Code gen a operator to convert internal type rows to external type. **/
- def generateRowConverterOperator[OUT](
- ctx: CodeGeneratorContext,
- config: TableConfig,
- inputRowType: RowType,
+ def deriveSinkOutputTypeInfo[OUT](
sink: TableSink[_],
- withChangeFlag: Boolean,
- operatorName: String): (CodeGenOperatorFactory[OUT], TypeInformation[OUT]) = {
-
- val physicalOutputType = TableSinkUtils.inferSinkPhysicalDataType(
- sink.getConsumedDataType,
- inputRowType,
- withChangeFlag)
+ physicalOutputType: DataType,
+ withChangeFlag: Boolean): TypeInformation[OUT] = {
val physicalTypeInfo = fromDataTypeToTypeInfo(physicalOutputType)
-
val outputTypeInfo = if (withChangeFlag) {
val consumedClass = sink.getConsumedDataType.getConversionClass
if (consumedClass == classOf[(_, _)]) {
createTuple2TypeInformation(Types.BOOLEAN, physicalTypeInfo)
} else if (consumedClass == classOf[JTuple2[_, _]]) {
new TupleTypeInfo(Types.BOOLEAN, physicalTypeInfo)
+ } else {
+ throw new TableException("This should not happen.")
}
} else {
physicalTypeInfo
}
+ outputTypeInfo.asInstanceOf[TypeInformation[OUT]]
+ }
+ /** Code gen a operator to convert internal type rows to external type. **/
+ def generateRowConverterOperator[OUT](
+ ctx: CodeGeneratorContext,
+ inputRowType: RowType,
+ sink: TableSink[_],
+ physicalOutputType: DataType,
+ withChangeFlag: Boolean,
+ operatorName: String): CodeGenOperatorFactory[OUT] = {
+ val physicalTypeInfo = fromDataTypeToTypeInfo(physicalOutputType)
val inputTerm = CodeGenUtils.DEFAULT_INPUT1_TERM
var afterIndexModify = inputTerm
val fieldIndexProcessCode = physicalTypeInfo match {
@@ -149,6 +152,6 @@ object SinkCodeGenerator {
|$retractProcessCode
|""".stripMargin,
inputRowType)
- (new CodeGenOperatorFactory[OUT](generated), outputTypeInfo.asInstanceOf[TypeInformation[OUT]])
+ new CodeGenOperatorFactory[OUT](generated)
}
}
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/planner/plan/nodes/physical/batch/BatchExecLegacySink.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/planner/plan/nodes/physical/batch/BatchExecLegacySink.scala
index e3edf0e..a90d9c3 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/planner/plan/nodes/physical/batch/BatchExecLegacySink.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/planner/plan/nodes/physical/batch/BatchExecLegacySink.scala
@@ -30,7 +30,7 @@ import org.apache.flink.table.planner.plan.nodes.exec.batch.BatchExecNode
import org.apache.flink.table.planner.plan.nodes.exec.utils.ExecNodeUtil
import org.apache.flink.table.planner.plan.nodes.exec.{ExecEdge, LegacyBatchExecNode}
import org.apache.flink.table.planner.plan.utils.UpdatingPlanChecker
-import org.apache.flink.table.planner.sinks.DataStreamTableSink
+import org.apache.flink.table.planner.sinks.{DataStreamTableSink, TableSinkUtils}
import org.apache.flink.table.runtime.types.ClassLogicalTypeConverter
import org.apache.flink.table.runtime.typeutils.InternalTypeInfo
import org.apache.flink.table.sinks.{RetractStreamTableSink, StreamTableSink, TableSink, UpsertStreamTableSink}
@@ -81,7 +81,7 @@ class BatchExecLegacySink[T](
case upsertSink: UpsertStreamTableSink[T] =>
upsertSink.setIsAppendOnly(true)
upsertSink.setKeyFields(
- UpdatingPlanChecker.getUniqueKeyForUpsertSink(this, planner, upsertSink).orNull)
+ UpdatingPlanChecker.getUniqueKeyForUpsertSink(this, upsertSink).orNull)
translateToTransformation(withChangeFlag = true, planner)
case _ =>
@@ -123,14 +123,19 @@ class BatchExecLegacySink[T](
if (CodeGenUtils.isInternalClass(resultDataType)) {
plan
} else {
- val (converterOperator, outputTypeInfo) = generateRowConverterOperator[T](
+ val inputRowType = plan.getOutputType.asInstanceOf[InternalTypeInfo[RowData]].toRowType
+ val physicalOutputType = TableSinkUtils.inferSinkPhysicalDataType(
+ sink.getConsumedDataType,
+ inputRowType,
+ withChangeFlag)
+ val outputTypeInfo = deriveSinkOutputTypeInfo[T](sink, physicalOutputType, withChangeFlag)
+ val converterOperator = generateRowConverterOperator[T](
CodeGeneratorContext(config),
- config,
- plan.getOutputType.asInstanceOf[InternalTypeInfo[RowData]].toRowType,
+ inputRowType,
sink,
+ physicalOutputType,
withChangeFlag,
- "SinkConversion"
- )
+ "SinkConversion")
ExecNodeUtil.createOneInputTransformation(
plan,
s"SinkConversionTo${resultDataType.getConversionClass.getSimpleName}",
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/planner/plan/nodes/physical/stream/StreamExecLegacySink.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/planner/plan/nodes/physical/stream/StreamExecLegacySink.scala
deleted file mode 100644
index 15034dd..0000000
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/planner/plan/nodes/physical/stream/StreamExecLegacySink.scala
+++ /dev/null
@@ -1,199 +0,0 @@
-/*
- * 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.plan.nodes.physical.stream
-
-import org.apache.flink.api.dag.Transformation
-import org.apache.flink.streaming.api.datastream.DataStream
-import org.apache.flink.streaming.api.transformations.OneInputTransformation
-import org.apache.flink.table.api.{Table, TableException}
-import org.apache.flink.table.data.RowData
-import org.apache.flink.table.planner.calcite.FlinkTypeFactory
-import org.apache.flink.table.planner.codegen.SinkCodeGenerator.generateRowConverterOperator
-import org.apache.flink.table.planner.codegen.{CodeGenUtils, CodeGeneratorContext}
-import org.apache.flink.table.planner.delegation.StreamPlanner
-import org.apache.flink.table.planner.plan.nodes.calcite.LegacySink
-import org.apache.flink.table.planner.plan.nodes.exec.LegacyStreamExecNode
-import org.apache.flink.table.planner.plan.nodes.exec.stream.StreamExecNode
-import org.apache.flink.table.planner.plan.utils.{ChangelogPlanUtils, UpdatingPlanChecker}
-import org.apache.flink.table.planner.sinks.DataStreamTableSink
-import org.apache.flink.table.runtime.typeutils.{InternalTypeInfo, TypeCheckUtils}
-import org.apache.flink.table.sinks._
-import org.apache.flink.table.types.logical.TimestampType
-
-import org.apache.calcite.plan.{RelOptCluster, RelTraitSet}
-import org.apache.calcite.rel.RelNode
-
-import java.util
-
-import scala.collection.JavaConversions._
-
-/**
- * Stream physical RelNode to to write data into an external sink defined by a [[TableSink]].
- */
-class StreamExecLegacySink[T](
- cluster: RelOptCluster,
- traitSet: RelTraitSet,
- inputRel: RelNode,
- sink: TableSink[T],
- sinkName: String)
- extends LegacySink(cluster, traitSet, inputRel, sink, sinkName)
- with StreamPhysicalRel
- with LegacyStreamExecNode[Any] {
-
- override def requireWatermark: Boolean = false
-
- override def copy(traitSet: RelTraitSet, inputs: util.List[RelNode]): RelNode = {
- new StreamExecLegacySink(cluster, traitSet, inputs.get(0), sink, sinkName)
- }
-
- //~ ExecNode methods -----------------------------------------------------------
-
- override protected def translateToPlanInternal(
- planner: StreamPlanner): Transformation[Any] = {
- val resultTransformation = sink match {
- case streamTableSink: StreamTableSink[T] =>
- val transformation = streamTableSink match {
- case _: RetractStreamTableSink[T] =>
- translateToTransformation(withChangeFlag = true, planner)
-
- case upsertSink: UpsertStreamTableSink[T] =>
- // check for append only table
- val isAppendOnlyTable = ChangelogPlanUtils.inputInsertOnly(this)
- upsertSink.setIsAppendOnly(isAppendOnlyTable)
-
- // check that we have keys if the table has changes (is not append-only)
- UpdatingPlanChecker.getUniqueKeyForUpsertSink(this, planner, upsertSink) match {
- case Some(keys) => upsertSink.setKeyFields(keys)
- case None if isAppendOnlyTable => upsertSink.setKeyFields(null)
- case None if !isAppendOnlyTable => throw new TableException(
- "UpsertStreamTableSink requires that Table has" +
- " a full primary keys if it is updated.")
- }
-
- translateToTransformation(withChangeFlag = true, planner)
-
- case _: AppendStreamTableSink[T] =>
- // verify table is an insert-only (append-only) table
- if (!ChangelogPlanUtils.inputInsertOnly(this)) {
- throw new TableException(
- "AppendStreamTableSink requires that Table has only insert changes.")
- }
- translateToTransformation(withChangeFlag = false, planner)
-
- case _ =>
- throw new TableException(
- "Stream Tables can only be emitted by AppendStreamTableSink, " +
- "RetractStreamTableSink, or UpsertStreamTableSink.")
- }
- val dataStream = new DataStream(planner.getExecEnv, transformation)
- val dsSink = streamTableSink.consumeDataStream(dataStream)
- if (dsSink == null) {
- throw new TableException("The StreamTableSink#consumeDataStream(DataStream) must be " +
- "implemented and return the sink transformation DataStreamSink. " +
- s"However, ${sink.getClass.getCanonicalName} doesn't implement this method.")
- }
- dsSink.getTransformation
-
- case dsTableSink: DataStreamTableSink[_] =>
- // In case of table to stream through BatchTableEnvironment#translateToDataStream,
- // we insert a DataStreamTableSink then wrap it as a LogicalSink, there is no real batch
- // table sink, so we do not need to invoke TableSink#emitBoundedStream and set resource,
- // just a translation to Transformation is ok.
- translateToTransformation(dsTableSink.withChangeFlag, planner)
-
- case _ =>
- throw new TableException(s"Only Support StreamTableSink! " +
- s"However ${sink.getClass.getCanonicalName} is not a StreamTableSink.")
- }
- resultTransformation.asInstanceOf[Transformation[Any]]
- }
-
- /**
- * Translates a logical [[RelNode]] into a [[Transformation]].
- *
- * @param withChangeFlag Set to true to emit records with change flags.
- * @return The [[Transformation]] that corresponds to the translated [[Table]].
- */
- private def translateToTransformation(
- withChangeFlag: Boolean,
- planner: StreamPlanner): Transformation[T] = {
- val config = planner.getTableConfig
- // if no change flags are requested, verify table is an insert-only (append-only) table.
- if (!withChangeFlag && !ChangelogPlanUtils.inputInsertOnly(this)) {
- throw new TableException(
- "Table is not an append-only table. " +
- "Use the toRetractStream() in order to handle add and retract messages.")
- }
-
- // get RowData plan
- val parTransformation = getInputNodes.get(0) match {
- // Sink's input must be LegacyStreamExecNode[RowData] or StreamExecNode[RowData] now.
- case legacyNode: LegacyStreamExecNode[RowData] => legacyNode.translateToPlan(planner)
- case node: StreamExecNode[RowData] => node.translateToPlan(planner)
- case _ =>
- throw new TableException("Cannot generate DataStream due to an invalid logical plan. " +
- "This is a bug and should not happen. Please file an issue.")
- }
- val logicalType = getInput.getRowType
- val rowtimeFields = logicalType.getFieldList
- .filter(f => FlinkTypeFactory.isRowtimeIndicatorType(f.getType))
-
- val convType = if (rowtimeFields.size > 1) {
- throw new TableException(
- s"Found more than one rowtime field: [${rowtimeFields.map(_.getName).mkString(", ")}] in " +
- s"the table that should be converted to a DataStream.\n" +
- s"Please select the rowtime field that should be used as event-time timestamp for the " +
- s"DataStream by casting all other fields to TIMESTAMP.")
- } else if (rowtimeFields.size == 1) {
- val origRowType = parTransformation.getOutputType.asInstanceOf[InternalTypeInfo[RowData]]
- val convFieldTypes = origRowType.toRowFieldTypes.map { t =>
- if (TypeCheckUtils.isRowTime(t)) {
- new TimestampType(3)
- } else {
- t
- }
- }
- InternalTypeInfo.ofFields(convFieldTypes, origRowType.toRowFieldNames)
- } else {
- parTransformation.getOutputType
- }
-
- val resultDataType = sink.getConsumedDataType
- if (CodeGenUtils.isInternalClass(resultDataType)) {
- parTransformation.asInstanceOf[Transformation[T]]
- } else {
- val (converterOperator, outputTypeInfo) = generateRowConverterOperator[T](
- CodeGeneratorContext(config),
- config,
- convType.asInstanceOf[InternalTypeInfo[RowData]].toRowType,
- sink,
- withChangeFlag,
- "SinkConversion"
- )
- new OneInputTransformation(
- parTransformation,
- s"SinkConversionTo${resultDataType.getConversionClass.getSimpleName}",
- converterOperator,
- outputTypeInfo,
- parTransformation.getParallelism)
- }
-
- }
-
-}
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/planner/plan/nodes/physical/stream/StreamPhysicalLegacySink.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/planner/plan/nodes/physical/stream/StreamPhysicalLegacySink.scala
new file mode 100644
index 0000000..ab1a248
--- /dev/null
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/planner/plan/nodes/physical/stream/StreamPhysicalLegacySink.scala
@@ -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.planner.plan.nodes.physical.stream
+
+import org.apache.flink.table.planner.plan.nodes.calcite.LegacySink
+import org.apache.flink.table.planner.plan.nodes.exec.stream.StreamExecLegacySink
+import org.apache.flink.table.planner.plan.nodes.exec.{ExecEdge, ExecNode}
+import org.apache.flink.table.planner.plan.utils.{ChangelogPlanUtils, UpdatingPlanChecker}
+import org.apache.flink.table.runtime.types.LogicalTypeDataTypeConverter.fromDataTypeToLogicalType
+import org.apache.flink.table.sinks._
+
+import org.apache.calcite.plan.{RelOptCluster, RelTraitSet}
+import org.apache.calcite.rel.RelNode
+
+import java.util
+
+/**
+ * Stream physical RelNode to to write data into an external sink defined by a [[TableSink]].
+ *
+ * @tparam T The return type of the [[TableSink]].
+ */
+class StreamPhysicalLegacySink[T](
+ cluster: RelOptCluster,
+ traitSet: RelTraitSet,
+ inputRel: RelNode,
+ sink: TableSink[T],
+ sinkName: String)
+ extends LegacySink(cluster, traitSet, inputRel, sink, sinkName)
+ with StreamPhysicalRel {
+
+ override def requireWatermark: Boolean = false
+
+ override def copy(traitSet: RelTraitSet, inputs: util.List[RelNode]): RelNode = {
+ new StreamPhysicalLegacySink(cluster, traitSet, inputs.get(0), sink, sinkName)
+ }
+
+ override def translateToExecNode(): ExecNode[_] = {
+ val upsertKeys = sink match {
+ case upsertSink: UpsertStreamTableSink[T] =>
+ UpdatingPlanChecker.getUniqueKeyForUpsertSink(this, upsertSink)
+ case _ => Option.empty[Array[String]]
+ }
+ val needRetraction = !ChangelogPlanUtils.inputInsertOnly(this)
+
+ new StreamExecLegacySink(
+ sink,
+ upsertKeys.orNull,
+ needRetraction,
+ ExecEdge.DEFAULT,
+ fromDataTypeToLogicalType(sink.getConsumedDataType),
+ getRelDetailedDescription
+ )
+ }
+}
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/planner/plan/optimize/program/FlinkChangelogModeInferenceProgram.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/planner/plan/optimize/program/FlinkChangelogModeInferenceProgram.scala
index 1112649..245971d 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/planner/plan/optimize/program/FlinkChangelogModeInferenceProgram.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/planner/plan/optimize/program/FlinkChangelogModeInferenceProgram.scala
@@ -127,7 +127,7 @@ class FlinkChangelogModeInferenceProgram extends FlinkOptimizeProgram[StreamOpti
// ignore required trait from context, because sink is the true root
sink.copy(sinkTrait, children).asInstanceOf[StreamPhysicalRel]
- case sink: StreamExecLegacySink[_] =>
+ case sink: StreamPhysicalLegacySink[_] =>
val (sinkRequiredTrait, name) = sink.sink match {
case _: UpsertStreamTableSink[_] =>
(ModifyKindSetTrait.ALL_CHANGES, "UpsertStreamTableSink")
@@ -429,7 +429,7 @@ class FlinkChangelogModeInferenceProgram extends FlinkOptimizeProgram[StreamOpti
}
visitSink(sink, sinkRequiredTraits)
- case sink: StreamExecLegacySink[_] =>
+ case sink: StreamPhysicalLegacySink[_] =>
val childModifyKindSet = getModifyKindSet(sink.getInput)
val onlyAfter = onlyAfterOrNone(childModifyKindSet)
val beforeAndAfter = beforeAfterOrNone(childModifyKindSet)
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/planner/plan/rules/FlinkStreamRuleSets.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/planner/plan/rules/FlinkStreamRuleSets.scala
index fe7cb9b..a78f647 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/planner/plan/rules/FlinkStreamRuleSets.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/planner/plan/rules/FlinkStreamRuleSets.scala
@@ -445,7 +445,7 @@ object FlinkStreamRuleSets {
StreamPhysicalPythonCorrelateRule.INSTANCE,
// sink
StreamPhysicalSinkRule.INSTANCE,
- StreamExecLegacySinkRule.INSTANCE
+ StreamPhysicalLegacySinkRule.INSTANCE
)
/**
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/planner/plan/rules/physical/stream/StreamExecLegacySinkRule.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/planner/plan/rules/physical/stream/StreamPhysicalLegacySinkRule.scala
similarity index 93%
rename from flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/planner/plan/rules/physical/stream/StreamExecLegacySinkRule.scala
rename to flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/planner/plan/rules/physical/stream/StreamPhysicalLegacySinkRule.scala
index d47a905..33a7f2c 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/planner/plan/rules/physical/stream/StreamExecLegacySinkRule.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/planner/plan/rules/physical/stream/StreamPhysicalLegacySinkRule.scala
@@ -23,7 +23,7 @@ import org.apache.flink.table.filesystem.FileSystemOptions
import org.apache.flink.table.planner.plan.`trait`.FlinkRelDistribution
import org.apache.flink.table.planner.plan.nodes.FlinkConventions
import org.apache.flink.table.planner.plan.nodes.logical.FlinkLogicalLegacySink
-import org.apache.flink.table.planner.plan.nodes.physical.stream.StreamExecLegacySink
+import org.apache.flink.table.planner.plan.nodes.physical.stream.StreamPhysicalLegacySink
import org.apache.flink.table.sinks.PartitionableTableSink
import org.apache.calcite.plan.RelOptRule
@@ -32,11 +32,11 @@ import org.apache.calcite.rel.convert.ConverterRule
import scala.collection.JavaConversions._
-class StreamExecLegacySinkRule extends ConverterRule(
+class StreamPhysicalLegacySinkRule extends ConverterRule(
classOf[FlinkLogicalLegacySink],
FlinkConventions.LOGICAL,
FlinkConventions.STREAM_PHYSICAL,
- "StreamExecLegacySinkRule") {
+ "StreamPhysicalLegacySinkRule") {
def convert(rel: RelNode): RelNode = {
val sinkNode = rel.asInstanceOf[FlinkLogicalLegacySink]
@@ -75,7 +75,7 @@ class StreamExecLegacySinkRule extends ConverterRule(
val newInput = RelOptRule.convert(sinkNode.getInput, requiredTraitSet)
- new StreamExecLegacySink(
+ new StreamPhysicalLegacySink(
rel.getCluster,
newTrait,
newInput,
@@ -84,8 +84,6 @@ class StreamExecLegacySinkRule extends ConverterRule(
}
}
-object StreamExecLegacySinkRule {
-
- val INSTANCE: RelOptRule = new StreamExecLegacySinkRule
-
+object StreamPhysicalLegacySinkRule {
+ val INSTANCE: RelOptRule = new StreamPhysicalLegacySinkRule
}
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/planner/plan/utils/UpdatingPlanChecker.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/planner/plan/utils/UpdatingPlanChecker.scala
index da0144e..fba986e 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/planner/plan/utils/UpdatingPlanChecker.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/planner/plan/utils/UpdatingPlanChecker.scala
@@ -17,7 +17,6 @@
*/
package org.apache.flink.table.planner.plan.utils
-import org.apache.flink.table.planner.delegation.PlannerBase
import org.apache.flink.table.planner.plan.metadata.FlinkRelMetadataQuery
import org.apache.flink.table.planner.plan.nodes.calcite.LegacySink
import org.apache.flink.table.sinks.UpsertStreamTableSink
@@ -28,15 +27,13 @@ object UpdatingPlanChecker {
def getUniqueKeyForUpsertSink(
sinkNode: LegacySink,
- planner: PlannerBase,
sink: UpsertStreamTableSink[_]): Option[Array[String]] = {
// extract unique key fields
// Now we pick shortest one to sink
// TODO UpsertStreamTableSink setKeyFields interface should be Array[Array[String]]
val sinkFieldNames = sink.getTableSchema.getFieldNames
/** Extracts the unique keys of the table produced by the plan. */
- val fmq = FlinkRelMetadataQuery.reuseOrCreate(
- planner.getRelBuilder.getCluster.getMetadataQuery)
+ val fmq = FlinkRelMetadataQuery.reuseOrCreate(sinkNode.getCluster.getMetadataQuery)
val uniqueKeys = fmq.getUniqueKeys(sinkNode.getInput)
if (uniqueKeys != null && uniqueKeys.size() > 0) {
uniqueKeys