You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@flink.apache.org by ku...@apache.org on 2019/04/26 08:25:49 UTC
[flink] branch master updated: [FLINK-12321][table-planner-blink]
Supports sub-plan reuse in blink planner
This is an automated email from the ASF dual-hosted git repository.
kurt pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/flink.git
The following commit(s) were added to refs/heads/master by this push:
new 34f392d [FLINK-12321][table-planner-blink] Supports sub-plan reuse in blink planner
34f392d is described below
commit 34f392d2218406cfec9b74fb0efddbcaa3764f89
Author: godfrey he <go...@163.com>
AuthorDate: Fri Apr 26 16:25:37 2019 +0800
[FLINK-12321][table-planner-blink] Supports sub-plan reuse in blink planner
This closes #8253
---
.../flink/table/api/PlannerConfigOptions.java | 13 +
.../table/plan/nodes/exec/ExecNodeVisitorImpl.java | 33 +
.../flink/table/api/BatchTableEnvironment.scala | 9 +-
.../apache/flink/table/api/TableEnvironment.scala | 11 +-
.../plan/nodes/common/CommonPhysicalExchange.scala | 1 +
.../plan/nodes/common/CommonPhysicalJoin.scala | 1 +
.../flink/table/plan/nodes/exec/ExecNode.scala | 9 +
.../plan/nodes/logical/FlinkLogicalCalc.scala | 12 +-
.../logical/FlinkLogicalDataStreamTableScan.scala | 1 +
.../plan/nodes/logical/FlinkLogicalJoin.scala | 1 +
.../logical/FlinkLogicalTableSourceScan.scala | 19 +-
.../logical/FlinkLogicalWindowAggregate.scala | 4 +-
.../batch/BatchExecBoundedStreamScan.scala | 11 +-
.../plan/nodes/physical/batch/BatchExecCalc.scala | 8 +
.../nodes/physical/batch/BatchExecCorrelate.scala | 6 +
.../nodes/physical/batch/BatchExecExchange.scala | 40 +-
.../nodes/physical/batch/BatchExecExpand.scala | 8 +
.../physical/batch/BatchExecHashAggregate.scala | 2 +
.../batch/BatchExecHashAggregateBase.scala | 8 +
.../nodes/physical/batch/BatchExecHashJoin.scala | 31 +
.../batch/BatchExecHashWindowAggregate.scala | 2 +
.../batch/BatchExecHashWindowAggregateBase.scala | 8 +
.../nodes/physical/batch/BatchExecJoinBase.scala | 7 +-
.../plan/nodes/physical/batch/BatchExecLimit.scala | 8 +
.../batch/BatchExecLocalHashAggregate.scala | 2 +
.../batch/BatchExecLocalHashWindowAggregate.scala | 2 +
.../batch/BatchExecLocalSortAggregate.scala | 2 +
.../batch/BatchExecLocalSortWindowAggregate.scala | 2 +
.../physical/batch/BatchExecNestedLoopJoin.scala | 26 +
.../physical/batch/BatchExecOverAggregate.scala | 13 +-
.../plan/nodes/physical/batch/BatchExecRank.scala | 8 +
.../plan/nodes/physical/batch/BatchExecSink.scala | 6 +
.../plan/nodes/physical/batch/BatchExecSort.scala | 8 +
.../physical/batch/BatchExecSortAggregate.scala | 2 +
.../batch/BatchExecSortAggregateBase.scala | 8 +
.../nodes/physical/batch/BatchExecSortLimit.scala | 8 +
.../physical/batch/BatchExecSortMergeJoin.scala | 12 +-
.../batch/BatchExecSortWindowAggregate.scala | 2 +
.../batch/BatchExecSortWindowAggregateBase.scala | 8 +
.../physical/batch/BatchExecTableSourceScan.scala | 27 +-
.../plan/nodes/physical/batch/BatchExecUnion.scala | 8 +
.../nodes/physical/batch/BatchExecValues.scala | 12 +-
.../batch/BatchExecWindowAggregateBase.scala | 1 +
.../nodes/physical/stream/StreamExecCalc.scala | 8 +
.../physical/stream/StreamExecCorrelate.scala | 8 +-
.../physical/stream/StreamExecDataStreamScan.scala | 8 +
.../physical/stream/StreamExecDeduplicate.scala | 14 +-
.../nodes/physical/stream/StreamExecExchange.scala | 6 +
.../nodes/physical/stream/StreamExecExpand.scala | 10 +-
.../stream/StreamExecGlobalGroupAggregate.scala | 8 +
.../physical/stream/StreamExecGroupAggregate.scala | 8 +
.../StreamExecIncrementalGroupAggregate.scala | 7 +
.../nodes/physical/stream/StreamExecJoinBase.scala | 28 +-
.../nodes/physical/stream/StreamExecLimit.scala | 6 +
.../stream/StreamExecLocalGroupAggregate.scala | 8 +
.../physical/stream/StreamExecOverAggregate.scala | 27 +-
.../nodes/physical/stream/StreamExecRank.scala | 6 +
.../nodes/physical/stream/StreamExecSink.scala | 6 +
.../nodes/physical/stream/StreamExecSort.scala | 12 +-
.../physical/stream/StreamExecSortLimit.scala | 6 +
.../stream/StreamExecTableSourceScan.scala | 27 +-
.../physical/stream/StreamExecTemporalSort.scala | 6 +
.../nodes/physical/stream/StreamExecUnion.scala | 19 +-
.../nodes/physical/stream/StreamExecValues.scala | 14 +-
.../stream/StreamExecWatermarkAssigner.scala | 27 +-
.../physical/stream/StreamExecWindowJoin.scala | 26 +-
.../plan/reuse/DeadlockBreakupProcessor.scala | 343 +++++++
.../flink/table/plan/reuse/SubplanReuser.scala | 240 +++++
.../physical/batch/BatchExecAggRuleBase.scala | 4 +-
.../rules/physical/batch/BatchExecRankRule.scala | 6 +-
.../batch/BatchExecSortMergeJoinRule.scala | 4 +-
.../table/plan/trait/FlinkRelDistribution.scala | 4 +-
.../flink/table/plan/util/CorrelateUtil.scala | 2 +-
.../flink/table/plan/util/ExecNodePlanDumper.scala | 399 ++++++++
.../flink/table/plan/util/FlinkRelOptUtil.scala | 58 +-
.../flink/table/plan/util/OverAggregateUtil.scala | 2 +-
.../flink/table/plan/util/RelDigestUtil.scala | 120 +++
.../table/plan/util/RelFieldCollationUtil.scala | 83 --
.../apache/flink/table/plan/util/RelShuttles.scala | 148 +++
.../utils/JavaUserDefinedScalarFunctions.java | 21 +
.../utils/JavaUserDefinedTableFunctions.java | 72 ++
.../digest/testGetDigestWithDynamicFunction.out | 31 +
.../testGetDigestWithDynamicFunctionView.out | 34 +
.../table/plan/batch/sql/DeadlockBreakupTest.xml | 317 ++++++
.../table/plan/batch/sql/SubplanReuseTest.xml | 1041 ++++++++++++++++++++
.../flink/table/plan/batch/sql/ValuesTest.xml | 10 +-
.../table/plan/batch/sql/agg/GroupingSetsTest.xml | 31 +-
.../plan/batch/sql/join/SingleRowJoinTest.xml | 21 +-
.../table/plan/stream/sql/SubplanReuseTest.xml | 646 ++++++++++++
.../flink/table/plan/stream/sql/ValuesTest.xml | 10 +-
.../table/plan/batch/sql/DeadlockBreakupTest.scala | 188 ++++
.../table/plan/batch/sql/SubplanReuseTest.scala | 445 +++++++++
.../table/plan/stream/sql/SubplanReuseTest.scala | 301 ++++++
.../flink/table/plan/util/RelDigestUtilTest.scala | 108 ++
.../table/runtime/batch/sql/CorrelateITCase2.scala | 44 +-
.../flink/table/runtime/batch/sql/MiscITCase.scala | 2 +-
.../runtime/batch/sql/agg/GroupingSetsITCase.scala | 4 +-
.../table/runtime/stream/sql/CorrelateITCase.scala | 2 +-
.../apache/flink/table/util/TableTestBase.scala | 57 +-
99 files changed, 5266 insertions(+), 237 deletions(-)
diff --git a/flink-table/flink-table-planner-blink/src/main/java/org/apache/flink/table/api/PlannerConfigOptions.java b/flink-table/flink-table-planner-blink/src/main/java/org/apache/flink/table/api/PlannerConfigOptions.java
index e20256c..48b87c8 100644
--- a/flink-table/flink-table-planner-blink/src/main/java/org/apache/flink/table/api/PlannerConfigOptions.java
+++ b/flink-table/flink-table-planner-blink/src/main/java/org/apache/flink/table/api/PlannerConfigOptions.java
@@ -89,4 +89,17 @@ public class PlannerConfigOptions {
.defaultValue(true)
.withDescription("Whether to enable incremental aggregate.");
+
+ public static final ConfigOption<Boolean> SQL_OPTIMIZER_REUSE_SUB_PLAN_ENABLED =
+ key("sql.optimizer.reuse.sub-plan.enabled")
+ .defaultValue(true)
+ .withDescription("When true, the optimizer will try to find out duplicated " +
+ "sub-plan and reuse them.");
+
+ public static final ConfigOption<Boolean> SQL_OPTIMIZER_REUSE_TABLE_SOURCE_ENABLED =
+ key("sql.optimizer.reuse.table-source.enabled")
+ .defaultValue(true)
+ .withDescription("When true, the optimizer will try to find out duplicated table-source and " +
+ "reuse them. This works only when " + SQL_OPTIMIZER_REUSE_SUB_PLAN_ENABLED + " is true.");
+
}
diff --git a/flink-table/flink-table-planner-blink/src/main/java/org/apache/flink/table/plan/nodes/exec/ExecNodeVisitorImpl.java b/flink-table/flink-table-planner-blink/src/main/java/org/apache/flink/table/plan/nodes/exec/ExecNodeVisitorImpl.java
new file mode 100644
index 0000000..f93f45a
--- /dev/null
+++ b/flink-table/flink-table-planner-blink/src/main/java/org/apache/flink/table/plan/nodes/exec/ExecNodeVisitorImpl.java
@@ -0,0 +1,33 @@
+/*
+ * 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.plan.nodes.exec;
+
+/**
+ * Implement of {@link ExecNodeVisitor}.
+ */
+public class ExecNodeVisitorImpl implements ExecNodeVisitor {
+
+ public void visit(ExecNode<?, ?> node) {
+ visitInputs(node);
+ }
+
+ protected void visitInputs(ExecNode<?, ?> node) {
+ node.getInputNodes().forEach(n -> n.accept(this));
+ }
+}
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/api/BatchTableEnvironment.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/api/BatchTableEnvironment.scala
index 4d30195..2b38b31 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/api/BatchTableEnvironment.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/api/BatchTableEnvironment.scala
@@ -25,6 +25,7 @@ import org.apache.flink.table.plan.`trait`.FlinkRelDistributionTraitDef
import org.apache.flink.table.plan.nodes.calcite.LogicalSink
import org.apache.flink.table.plan.nodes.exec.{BatchExecNode, ExecNode}
import org.apache.flink.table.plan.optimize.{BatchOptimizer, Optimizer}
+import org.apache.flink.table.plan.reuse.DeadlockBreakupProcessor
import org.apache.flink.table.plan.schema.{BatchTableSourceTable, TableSourceSinkTable, TableSourceTable}
import org.apache.flink.table.plan.stats.FlinkStatistic
import org.apache.flink.table.plan.util.FlinkRelOptUtil
@@ -32,7 +33,7 @@ import org.apache.flink.table.sinks._
import org.apache.flink.table.sources._
import org.apache.calcite.plan.{ConventionTraitDef, RelTrait, RelTraitDef}
-import org.apache.calcite.rel.RelCollationTraitDef
+import org.apache.calcite.rel.{RelCollationTraitDef, RelNode}
import org.apache.calcite.sql.SqlExplainLevel
import _root_.scala.collection.JavaConversions._
@@ -82,6 +83,12 @@ class BatchTableEnvironment(
}
}
+ override private[flink] def translateNodeDag(rels: Seq[RelNode]): Seq[ExecNode[_, _]] = {
+ val nodeDag = super.translateNodeDag(rels)
+ // breakup deadlock
+ new DeadlockBreakupProcessor().process(nodeDag)
+ }
+
/**
* Merge global job parameters and table config parameters,
* and set the merged result to GlobalJobParameters
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/api/TableEnvironment.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/api/TableEnvironment.scala
index 68f1323..317ea06 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/api/TableEnvironment.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/api/TableEnvironment.scala
@@ -38,10 +38,11 @@ import org.apache.flink.table.plan.cost.FlinkCostFactory
import org.apache.flink.table.plan.nodes.exec.ExecNode
import org.apache.flink.table.plan.nodes.physical.FlinkPhysicalRel
import org.apache.flink.table.plan.optimize.Optimizer
+import org.apache.flink.table.plan.reuse.SubplanReuser
import org.apache.flink.table.plan.schema.RelTable
import org.apache.flink.table.plan.stats.FlinkStatistic
+import org.apache.flink.table.plan.util.SameRelObjectShuttle
import org.apache.flink.table.sinks.TableSink
-import org.apache.flink.table.sinks.CollectTableSink
import org.apache.flink.table.sources.TableSource
import org.apache.flink.table.typeutils.BaseRowTypeInfo
import org.apache.flink.table.validate.FunctionCatalog
@@ -211,8 +212,14 @@ abstract class TableEnvironment(val config: TableConfig) {
@VisibleForTesting
private[flink] def translateNodeDag(rels: Seq[RelNode]): Seq[ExecNode[_, _]] = {
require(rels.nonEmpty && rels.forall(_.isInstanceOf[FlinkPhysicalRel]))
+ // Rewrite same rel object to different rel objects
+ // in order to get the correct dag (dag reuse is based on object not digest)
+ val shuttle = new SameRelObjectShuttle()
+ val relsWithoutSameObj = rels.map(_.accept(shuttle))
+ // reuse subplan
+ val reusedPlan = SubplanReuser.reuseDuplicatedSubplan(relsWithoutSameObj, config)
// convert FlinkPhysicalRel DAG to ExecNode DAG
- rels.map(_.asInstanceOf[ExecNode[_, _]])
+ reusedPlan.map(_.asInstanceOf[ExecNode[_, _]])
}
/**
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/common/CommonPhysicalExchange.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/common/CommonPhysicalExchange.scala
index 3625676..e0fba03 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/common/CommonPhysicalExchange.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/common/CommonPhysicalExchange.scala
@@ -105,4 +105,5 @@ abstract class CommonPhysicalExchange(
}
if (fieldNames.isEmpty) exchangeName else exchangeName + fieldNames
}
+
}
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/common/CommonPhysicalJoin.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/common/CommonPhysicalJoin.scala
index 7ed38a8..fd41e79 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/common/CommonPhysicalJoin.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/common/CommonPhysicalJoin.scala
@@ -75,4 +75,5 @@ trait CommonPhysicalJoin extends Join with FlinkPhysicalRel {
RelExplainUtil.expressionToString(getCondition, inputRowType, getExpressionString))
.item("select", getRowType.getFieldNames.mkString(", "))
}
+
}
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/exec/ExecNode.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/exec/ExecNode.scala
index 869db32..d86ecd5 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/exec/ExecNode.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/exec/ExecNode.scala
@@ -67,6 +67,15 @@ trait ExecNode[E <: TableEnvironment, T] {
def getInputNodes: util.List[ExecNode[E, _]]
/**
+ * Replaces the <code>ordinalInParent</code><sup>th</sup> input.
+ * You must override this method if you override [[getInputNodes]].
+ *
+ * @param ordinalInParent Position of the child input, 0 is the first
+ * @param newInputNode New node that should be put at position ordinalInParent
+ */
+ def replaceInputNode(ordinalInParent: Int, newInputNode: ExecNode[E, _]): Unit
+
+ /**
* Accepts a visit from a [[ExecNodeVisitor]].
*
* @param visitor ExecNodeVisitor
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/logical/FlinkLogicalCalc.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/logical/FlinkLogicalCalc.scala
index 1086ec3..92e8a6b 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/logical/FlinkLogicalCalc.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/logical/FlinkLogicalCalc.scala
@@ -22,12 +22,16 @@ import org.apache.flink.table.plan.nodes.FlinkConventions
import org.apache.flink.table.plan.nodes.common.CommonCalc
import org.apache.calcite.plan._
-import org.apache.calcite.rel.RelNode
+import org.apache.calcite.rel.{RelCollation, RelCollationTraitDef, RelNode}
import org.apache.calcite.rel.convert.ConverterRule
import org.apache.calcite.rel.core.Calc
import org.apache.calcite.rel.logical.LogicalCalc
+import org.apache.calcite.rel.metadata.RelMdCollation
import org.apache.calcite.rex.RexProgram
+import java.util
+import java.util.function.Supplier
+
/**
* Sub-class of [[Calc]] that is a relational expression which computes project expressions
* and also filters in Flink.
@@ -67,7 +71,11 @@ object FlinkLogicalCalc {
input: RelNode,
calcProgram: RexProgram): FlinkLogicalCalc = {
val cluster = input.getCluster
- val traitSet = cluster.traitSet.replace(FlinkConventions.LOGICAL).simplify()
+ val mq = cluster.getMetadataQuery
+ val traitSet = cluster.traitSet.replace(FlinkConventions.LOGICAL).replaceIfs(
+ RelCollationTraitDef.INSTANCE, new Supplier[util.List[RelCollation]]() {
+ def get: util.List[RelCollation] = RelMdCollation.calc(mq, input, calcProgram)
+ })
new FlinkLogicalCalc(cluster, traitSet, input, calcProgram)
}
}
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/logical/FlinkLogicalDataStreamTableScan.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/logical/FlinkLogicalDataStreamTableScan.scala
index d94772d..634011e 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/logical/FlinkLogicalDataStreamTableScan.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/logical/FlinkLogicalDataStreamTableScan.scala
@@ -53,6 +53,7 @@ class FlinkLogicalDataStreamTableScan(
val rowSize = mq.getAverageRowSize(this)
planner.getCostFactory.makeCost(rowCnt, rowCnt, rowCnt * rowSize)
}
+
}
class FlinkLogicalDataStreamTableScanConverter
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/logical/FlinkLogicalJoin.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/logical/FlinkLogicalJoin.scala
index d33630b..5b03586 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/logical/FlinkLogicalJoin.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/logical/FlinkLogicalJoin.scala
@@ -67,6 +67,7 @@ class FlinkLogicalJoin(
planner.getCostFactory.makeCost(rowCnt, cpuCost, ioCost)
}
+
}
/**
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/logical/FlinkLogicalTableSourceScan.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/logical/FlinkLogicalTableSourceScan.scala
index 6b6cd03..b630b91 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/logical/FlinkLogicalTableSourceScan.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/logical/FlinkLogicalTableSourceScan.scala
@@ -25,13 +25,18 @@ import org.apache.flink.table.plan.nodes.logical.FlinkLogicalTableSourceScan.isT
import org.apache.flink.table.plan.schema.{FlinkRelOptTable, TableSourceTable}
import org.apache.flink.table.sources._
+import com.google.common.collect.ImmutableList
import org.apache.calcite.plan._
import org.apache.calcite.rel.`type`.RelDataType
import org.apache.calcite.rel.convert.ConverterRule
import org.apache.calcite.rel.core.TableScan
import org.apache.calcite.rel.logical.LogicalTableScan
import org.apache.calcite.rel.metadata.RelMetadataQuery
-import org.apache.calcite.rel.{RelNode, RelWriter}
+import org.apache.calcite.rel.{RelCollation, RelCollationTraitDef, RelNode, RelWriter}
+import org.apache.calcite.schema.Table
+
+import java.util
+import java.util.function.Supplier
/**
* Sub-class of [[TableScan]] that is a relational operator
@@ -110,7 +115,17 @@ object FlinkLogicalTableSourceScan {
}
def create(cluster: RelOptCluster, relOptTable: FlinkRelOptTable): FlinkLogicalTableSourceScan = {
- val traitSet = cluster.traitSet().replace(FlinkConventions.LOGICAL).simplify()
+ val table = relOptTable.unwrap(classOf[Table])
+ val traitSet = cluster.traitSetOf(FlinkConventions.LOGICAL).replaceIfs(
+ RelCollationTraitDef.INSTANCE, new Supplier[util.List[RelCollation]]() {
+ def get: util.List[RelCollation] = {
+ if (table != null) {
+ table.getStatistic.getCollations
+ } else {
+ ImmutableList.of[RelCollation]
+ }
+ }
+ })
new FlinkLogicalTableSourceScan(cluster, traitSet, relOptTable)
}
}
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/logical/FlinkLogicalWindowAggregate.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/logical/FlinkLogicalWindowAggregate.scala
index 9b6990d..1b91102 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/logical/FlinkLogicalWindowAggregate.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/logical/FlinkLogicalWindowAggregate.scala
@@ -60,8 +60,7 @@ class FlinkLogicalWindowAggregate(
indicator: Boolean,
groupSet: ImmutableBitSet,
groupSets: util.List[ImmutableBitSet],
- aggCalls: util.List[AggregateCall])
- : Aggregate = {
+ aggCalls: util.List[AggregateCall]): Aggregate = {
new FlinkLogicalWindowAggregate(
window,
namedProperties,
@@ -112,6 +111,7 @@ class FlinkLogicalWindowAggregate(
.item("window", window)
.item("properties", namedProperties.map(_.name).mkString(", "))
}
+
}
class FlinkLogicalWindowAggregateConverter
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecBoundedStreamScan.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecBoundedStreamScan.scala
index 93505c4..4d88e4d 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecBoundedStreamScan.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecBoundedStreamScan.scala
@@ -71,8 +71,18 @@ class BatchExecBoundedStreamScan(
.item("fields", getRowType.getFieldNames.asScala.mkString(", "))
}
+ //~ ExecNode methods -----------------------------------------------------------
+
override def getDamBehavior = DamBehavior.PIPELINED
+ override def getInputNodes: util.List[ExecNode[BatchTableEnvironment, _]] = List()
+
+ override def replaceInputNode(
+ ordinalInParent: Int,
+ newInputNode: ExecNode[BatchTableEnvironment, _]): Unit = {
+ replaceInput(ordinalInParent, newInputNode.asInstanceOf[RelNode])
+ }
+
override def translateToPlanInternal(
tableEnv: BatchTableEnvironment): StreamTransformation[BaseRow] = {
val config = tableEnv.getConfig
@@ -99,5 +109,4 @@ class BatchExecBoundedStreamScan(
boundedStreamTable.dataStream.getType.getTypeClass)
}
- override def getInputNodes: util.List[ExecNode[BatchTableEnvironment, _]] = List()
}
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecCalc.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecCalc.scala
index a178c75..ace866d 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecCalc.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecCalc.scala
@@ -57,11 +57,19 @@ class BatchExecCalc(
new BatchExecCalc(cluster, traitSet, child, program, outputRowType)
}
+ //~ ExecNode methods -----------------------------------------------------------
+
override def getDamBehavior = DamBehavior.PIPELINED
override def getInputNodes: util.List[ExecNode[BatchTableEnvironment, _]] =
List(getInput.asInstanceOf[ExecNode[BatchTableEnvironment, _]])
+ override def replaceInputNode(
+ ordinalInParent: Int,
+ newInputNode: ExecNode[BatchTableEnvironment, _]): Unit = {
+ replaceInput(ordinalInParent, newInputNode.asInstanceOf[RelNode])
+ }
+
override def translateToPlanInternal(
tableEnv: BatchTableEnvironment): StreamTransformation[BaseRow] = {
val config = tableEnv.getConfig
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecCorrelate.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecCorrelate.scala
index a8b4b87..7097e82 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecCorrelate.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecCorrelate.scala
@@ -101,6 +101,12 @@ class BatchExecCorrelate(
override def getInputNodes: util.List[ExecNode[BatchTableEnvironment, _]] =
getInputs.map(_.asInstanceOf[ExecNode[BatchTableEnvironment, _]])
+ override def replaceInputNode(
+ ordinalInParent: Int,
+ newInputNode: ExecNode[BatchTableEnvironment, _]): Unit = {
+ replaceInput(ordinalInParent, newInputNode.asInstanceOf[RelNode])
+ }
+
/**
* Internal method, translates the [[org.apache.flink.table.plan.nodes.exec.BatchExecNode]]
* into a Batch operator.
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecExchange.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecExchange.scala
index 7a3610a..da2de93 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecExchange.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecExchange.scala
@@ -18,11 +18,13 @@
package org.apache.flink.table.plan.nodes.physical.batch
+import org.apache.flink.configuration.Configuration
+import org.apache.flink.runtime.io.network.DataExchangeMode
import org.apache.flink.runtime.operators.DamBehavior
import org.apache.flink.streaming.api.transformations.{PartitionTransformation, StreamTransformation}
import org.apache.flink.streaming.runtime.partitioner.{BroadcastPartitioner, GlobalPartitioner, RebalancePartitioner}
import org.apache.flink.table.`type`.RowType
-import org.apache.flink.table.api.BatchTableEnvironment
+import org.apache.flink.table.api.{BatchTableEnvironment, TableException}
import org.apache.flink.table.calcite.FlinkTypeFactory
import org.apache.flink.table.codegen.{CodeGeneratorContext, HashCodeGenerator}
import org.apache.flink.table.dataformat.BaseRow
@@ -32,7 +34,7 @@ import org.apache.flink.table.runtime.BinaryHashPartitioner
import org.apache.flink.table.typeutils.BaseRowTypeInfo
import org.apache.calcite.plan.{RelOptCluster, RelTraitSet}
-import org.apache.calcite.rel.{RelDistribution, RelNode}
+import org.apache.calcite.rel.{RelDistribution, RelNode, RelWriter}
import java.util
@@ -100,6 +102,9 @@ class BatchExecExchange(
// and different PartitionTransformation objects will be created which have same input.
// cache input transformation to reuse
private var reusedInput: Option[StreamTransformation[BaseRow]] = None
+ // the required exchange mode for reusable ExchangeBatchExec
+ // if it's None, use value from getDataExchangeMode
+ private var requiredExchangeMode: Option[DataExchangeMode] = None
override def copy(
traitSet: RelTraitSet,
@@ -108,6 +113,26 @@ class BatchExecExchange(
new BatchExecExchange(cluster, traitSet, newInput, relDistribution)
}
+ override def explainTerms(pw: RelWriter): RelWriter = {
+ super.explainTerms(pw)
+ .itemIf("exchange_mode", requiredExchangeMode.orNull,
+ requiredExchangeMode.contains(DataExchangeMode.BATCH))
+ }
+
+ //~ ExecNode methods -----------------------------------------------------------
+
+ def setRequiredDataExchangeMode(exchangeMode: DataExchangeMode): Unit = {
+ require(exchangeMode != null)
+ requiredExchangeMode = Some(exchangeMode)
+ }
+
+ private[flink] def getDataExchangeMode(tableConf: Configuration): DataExchangeMode = {
+ requiredExchangeMode match {
+ case Some(mode) if mode eq DataExchangeMode.BATCH => mode
+ case _ => DataExchangeMode.PIPELINED
+ }
+ }
+
override def getDamBehavior: DamBehavior = {
distribution.getType match {
case RelDistribution.Type.RANGE_DISTRIBUTED => DamBehavior.FULL_DAM
@@ -118,6 +143,12 @@ class BatchExecExchange(
override def getInputNodes: util.List[ExecNode[BatchTableEnvironment, _]] =
getInputs.map(_.asInstanceOf[ExecNode[BatchTableEnvironment, _]])
+ override def replaceInputNode(
+ ordinalInParent: Int,
+ newInputNode: ExecNode[BatchTableEnvironment, _]): Unit = {
+ replaceInput(ordinalInParent, newInputNode.asInstanceOf[RelNode])
+ }
+
override def translateToPlanInternal(
tableEnv: BatchTableEnvironment): StreamTransformation[BaseRow] = {
val input = reusedInput match {
@@ -132,6 +163,11 @@ class BatchExecExchange(
val inputType = input.getOutputType.asInstanceOf[BaseRowTypeInfo]
val outputRowType = FlinkTypeFactory.toInternalRowType(getRowType).toTypeInfo
+ // TODO supports DataExchangeMode.BATCH in runtime
+ if (requiredExchangeMode.contains(DataExchangeMode.BATCH)) {
+ throw new TableException("DataExchangeMode.BATCH is not supported now")
+ }
+
relDistribution.getType match {
case RelDistribution.Type.ANY =>
val transformation = new PartitionTransformation(
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecExpand.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecExpand.scala
index 38acfaf..8c1ac50 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecExpand.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecExpand.scala
@@ -67,12 +67,20 @@ class BatchExecExpand(
.item("projects", RelExplainUtil.projectsToString(projects, input.getRowType, getRowType))
}
+ //~ ExecNode methods -----------------------------------------------------------
+
override def getDamBehavior: DamBehavior = DamBehavior.PIPELINED
override def getInputNodes: util.List[ExecNode[BatchTableEnvironment, _]] = {
getInputs.map(_.asInstanceOf[ExecNode[BatchTableEnvironment, _]])
}
+ override def replaceInputNode(
+ ordinalInParent: Int,
+ newInputNode: ExecNode[BatchTableEnvironment, _]): Unit = {
+ replaceInput(ordinalInParent, newInputNode.asInstanceOf[RelNode])
+ }
+
override protected def translateToPlanInternal(
tableEnv: BatchTableEnvironment): StreamTransformation[BaseRow] = {
val config = tableEnv.getConfig
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecHashAggregate.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecHashAggregate.scala
index 52a314f..a3e3bc9 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecHashAggregate.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecHashAggregate.scala
@@ -94,6 +94,8 @@ class BatchExecHashAggregate(
isGlobal = true))
}
+ //~ ExecNode methods -----------------------------------------------------------
+
override def getDamBehavior = DamBehavior.FULL_DAM
override def getOperatorName: String = {
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecHashAggregateBase.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecHashAggregateBase.scala
index f9f22d2..1502299 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecHashAggregateBase.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecHashAggregateBase.scala
@@ -102,9 +102,17 @@ abstract class BatchExecHashAggregateBase(
costFactory.makeCost(rowCount, cpuCost, 0, 0, memCost)
}
+ //~ ExecNode methods -----------------------------------------------------------
+
override def getInputNodes: util.List[ExecNode[BatchTableEnvironment, _]] =
List(getInput.asInstanceOf[ExecNode[BatchTableEnvironment, _]])
+ override def replaceInputNode(
+ ordinalInParent: Int,
+ newInputNode: ExecNode[BatchTableEnvironment, _]): Unit = {
+ replaceInput(ordinalInParent, newInputNode.asInstanceOf[RelNode])
+ }
+
def getOperatorName: String
def getParallelism(input: StreamTransformation[BaseRow], conf: TableConfig): Int
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecHashJoin.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecHashJoin.scala
index e50c913..8c74c09 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecHashJoin.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecHashJoin.scala
@@ -17,8 +17,14 @@
*/
package org.apache.flink.table.plan.nodes.physical.batch
+import org.apache.flink.runtime.operators.DamBehavior
+import org.apache.flink.streaming.api.transformations.StreamTransformation
+import org.apache.flink.table.api.{BatchTableEnvironment, TableException}
+import org.apache.flink.table.dataformat.BaseRow
import org.apache.flink.table.plan.cost.{FlinkCost, FlinkCostFactory}
+import org.apache.flink.table.plan.nodes.exec.ExecNode
import org.apache.flink.table.plan.util.{FlinkRelMdUtil, JoinUtil}
+import org.apache.flink.table.runtime.join.HashJoinType
import org.apache.flink.table.typeutils.BinaryRowSerializer
import org.apache.calcite.plan._
@@ -28,6 +34,8 @@ import org.apache.calcite.rel.{RelNode, RelWriter}
import org.apache.calcite.rex.RexNode
import org.apache.calcite.util.Util
+import java.util
+
import scala.collection.JavaConversions._
/**
@@ -50,6 +58,9 @@ trait BatchExecHashJoinBase extends BatchExecJoinBase {
def buildRel: RelNode = if (leftIsBuild) getLeft else getRight
def probeRel: RelNode = if (leftIsBuild) getRight else getLeft
+ val hashJoinType: HashJoinType = HashJoinType.of(leftIsBuild, getJoinType.generatesNullsOnRight(),
+ getJoinType.generatesNullsOnLeft())
+
override def explainTerms(pw: RelWriter): RelWriter = {
super.explainTerms(pw)
.itemIf("isBroadcast", "true", isBroadcast)
@@ -91,6 +102,26 @@ trait BatchExecHashJoinBase extends BatchExecJoinBase {
1
}
}
+
+ //~ ExecNode methods -----------------------------------------------------------
+
+ override def getDamBehavior: DamBehavior = {
+ if (hashJoinType.buildLeftSemiOrAnti()) DamBehavior.FULL_DAM else DamBehavior.MATERIALIZING
+ }
+
+ override def getInputNodes: util.List[ExecNode[BatchTableEnvironment, _]] =
+ getInputs.map(_.asInstanceOf[ExecNode[BatchTableEnvironment, _]])
+
+ override def replaceInputNode(
+ ordinalInParent: Int,
+ newInputNode: ExecNode[BatchTableEnvironment, _]): Unit = {
+ replaceInput(ordinalInParent, newInputNode.asInstanceOf[RelNode])
+ }
+
+ override def translateToPlanInternal(
+ tableEnv: BatchTableEnvironment): StreamTransformation[BaseRow] = {
+ throw new TableException("Implements this")
+ }
}
class BatchExecHashJoin(
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecHashWindowAggregate.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecHashWindowAggregate.scala
index f5b43da..cf20c6f 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecHashWindowAggregate.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecHashWindowAggregate.scala
@@ -87,6 +87,8 @@ class BatchExecHashWindowAggregate(
isMerge)
}
+ //~ ExecNode methods -----------------------------------------------------------
+
override def getDamBehavior: DamBehavior = DamBehavior.FULL_DAM
override def getOperatorName: String = {
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecHashWindowAggregateBase.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecHashWindowAggregateBase.scala
index 56ad79f..72cca4f 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecHashWindowAggregateBase.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecHashWindowAggregateBase.scala
@@ -101,9 +101,17 @@ abstract class BatchExecHashWindowAggregateBase(
costFactory.makeCost(rowCnt, hashCpuCost + aggFunctionCpuCost, 0, 0, memCost)
}
+ //~ ExecNode methods -----------------------------------------------------------
+
override def getInputNodes: util.List[ExecNode[BatchTableEnvironment, _]] =
List(getInput.asInstanceOf[ExecNode[BatchTableEnvironment, _]])
+ override def replaceInputNode(
+ ordinalInParent: Int,
+ newInputNode: ExecNode[BatchTableEnvironment, _]): Unit = {
+ replaceInput(ordinalInParent, newInputNode.asInstanceOf[RelNode])
+ }
+
def getOperatorName: String
override def translateToPlanInternal(
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecJoinBase.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecJoinBase.scala
index eec1008..5f1d1e7 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecJoinBase.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecJoinBase.scala
@@ -20,15 +20,20 @@ package org.apache.flink.table.plan.nodes.physical.batch
import org.apache.flink.table.`type`.RowType
import org.apache.flink.table.api.TableConfig
import org.apache.flink.table.codegen.{CodeGeneratorContext, ExprCodeGenerator, FunctionCodeGenerator}
+import org.apache.flink.table.dataformat.BaseRow
import org.apache.flink.table.generated.GeneratedJoinCondition
import org.apache.flink.table.plan.nodes.common.CommonPhysicalJoin
+import org.apache.flink.table.plan.nodes.exec.BatchExecNode
import org.apache.calcite.rel.core.Join
/**
* Batch physical RelNode for [[Join]]
*/
-trait BatchExecJoinBase extends CommonPhysicalJoin with BatchPhysicalRel {
+trait BatchExecJoinBase
+ extends CommonPhysicalJoin
+ with BatchPhysicalRel
+ with BatchExecNode[BaseRow] {
private[flink] def generateCondition(
config: TableConfig,
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecLimit.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecLimit.scala
index a6109e4..3944461 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecLimit.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecLimit.scala
@@ -86,11 +86,19 @@ class BatchExecLimit(
costFactory.makeCost(rowCount, cpuCost, 0, 0, 0)
}
+ //~ ExecNode methods -----------------------------------------------------------
+
override def getDamBehavior: DamBehavior = DamBehavior.PIPELINED
override def getInputNodes: util.List[ExecNode[BatchTableEnvironment, _]] =
List(getInput.asInstanceOf[ExecNode[BatchTableEnvironment, _]])
+ override def replaceInputNode(
+ ordinalInParent: Int,
+ newInputNode: ExecNode[BatchTableEnvironment, _]): Unit = {
+ replaceInput(ordinalInParent, newInputNode.asInstanceOf[RelNode])
+ }
+
override def translateToPlanInternal(
tableEnv: BatchTableEnvironment): StreamTransformation[BaseRow] = {
val input = getInputNodes.get(0).translateToPlan(tableEnv)
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecLocalHashAggregate.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecLocalHashAggregate.scala
index a4e09f7..9bf440c 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecLocalHashAggregate.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecLocalHashAggregate.scala
@@ -92,6 +92,8 @@ class BatchExecLocalHashAggregate(
isGlobal = false))
}
+ //~ ExecNode methods -----------------------------------------------------------
+
override def getDamBehavior: DamBehavior = {
if (grouping.length == 0) DamBehavior.FULL_DAM else DamBehavior.MATERIALIZING
}
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecLocalHashWindowAggregate.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecLocalHashWindowAggregate.scala
index 65011e9..cc1eec8 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecLocalHashWindowAggregate.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecLocalHashWindowAggregate.scala
@@ -83,6 +83,8 @@ class BatchExecLocalHashWindowAggregate(
enableAssignPane)
}
+ //~ ExecNode methods -----------------------------------------------------------
+
override def getDamBehavior: DamBehavior = DamBehavior.MATERIALIZING
override def getOperatorName: String = {
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecLocalSortAggregate.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecLocalSortAggregate.scala
index ded9c5a..bac96fd 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecLocalSortAggregate.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecLocalSortAggregate.scala
@@ -90,6 +90,8 @@ class BatchExecLocalSortAggregate(
isGlobal = false))
}
+ //~ ExecNode methods -----------------------------------------------------------
+
override def getDamBehavior: DamBehavior = {
if (grouping.length == 0) DamBehavior.FULL_DAM else DamBehavior.MATERIALIZING
}
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecLocalSortWindowAggregate.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecLocalSortWindowAggregate.scala
index 1706592..a11101c 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecLocalSortWindowAggregate.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecLocalSortWindowAggregate.scala
@@ -86,6 +86,8 @@ class BatchExecLocalSortWindowAggregate(
enableAssignPane)
}
+ //~ ExecNode methods -----------------------------------------------------------
+
override def getDamBehavior: DamBehavior = DamBehavior.MATERIALIZING
override def getOperatorName: String = "LocalSortWindowAggregateBatchExec"
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecNestedLoopJoin.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecNestedLoopJoin.scala
index 78991cd..a1888dd 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecNestedLoopJoin.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecNestedLoopJoin.scala
@@ -18,7 +18,12 @@
package org.apache.flink.table.plan.nodes.physical.batch
+import org.apache.flink.runtime.operators.DamBehavior
+import org.apache.flink.streaming.api.transformations.StreamTransformation
+import org.apache.flink.table.api.{BatchTableEnvironment, TableException}
+import org.apache.flink.table.dataformat.BaseRow
import org.apache.flink.table.plan.cost.{FlinkCost, FlinkCostFactory}
+import org.apache.flink.table.plan.nodes.exec.ExecNode
import org.apache.flink.table.typeutils.BinaryRowSerializer
import org.apache.calcite.plan._
@@ -27,6 +32,8 @@ import org.apache.calcite.rel.metadata.RelMetadataQuery
import org.apache.calcite.rel.{RelNode, RelWriter}
import org.apache.calcite.rex.RexNode
+import java.util
+
import scala.collection.JavaConversions._
/**
@@ -72,6 +79,25 @@ trait BatchExecNestedLoopJoinBase extends BatchExecJoinBase {
(rowCount * probeRowSize / FlinkCost.SQL_DEFAULT_PARALLELISM_WORKER_PROCESS_SIZE).toInt)
}
}
+
+ //~ ExecNode methods -----------------------------------------------------------
+
+ override def getDamBehavior: DamBehavior = DamBehavior.PIPELINED
+
+ override def getInputNodes: util.List[ExecNode[BatchTableEnvironment, _]] =
+ getInputs.map(_.asInstanceOf[ExecNode[BatchTableEnvironment, _]])
+
+ override def replaceInputNode(
+ ordinalInParent: Int,
+ newInputNode: ExecNode[BatchTableEnvironment, _]): Unit = {
+ replaceInput(ordinalInParent, newInputNode.asInstanceOf[RelNode])
+ }
+
+ override def translateToPlanInternal(
+ tableEnv: BatchTableEnvironment): StreamTransformation[BaseRow] = {
+ throw new TableException("Implements this")
+ }
+
}
class BatchExecNestedLoopJoin(
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecOverAggregate.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecOverAggregate.scala
index 799a1bb..83397ee 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecOverAggregate.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecOverAggregate.scala
@@ -24,10 +24,10 @@ import org.apache.flink.table.CalcitePair
import org.apache.flink.table.`type`.InternalTypes
import org.apache.flink.table.api.{BatchTableEnvironment, TableConfig, TableConfigOptions}
import org.apache.flink.table.calcite.FlinkTypeFactory
-import org.apache.flink.table.codegen.agg.AggsHandlerCodeGenerator
-import org.apache.flink.table.codegen.sort.ComparatorCodeGenerator
import org.apache.flink.table.codegen.CodeGeneratorContext
+import org.apache.flink.table.codegen.agg.AggsHandlerCodeGenerator
import org.apache.flink.table.codegen.over.{MultiFieldRangeBoundComparatorCodeGenerator, RangeBoundComparatorCodeGenerator}
+import org.apache.flink.table.codegen.sort.ComparatorCodeGenerator
import org.apache.flink.table.dataformat.{BaseRow, BinaryRow}
import org.apache.flink.table.functions.UserDefinedFunction
import org.apache.flink.table.generated.GeneratedRecordComparator
@@ -53,7 +53,6 @@ import org.apache.calcite.sql.fun.SqlLeadLagAggFunction
import org.apache.calcite.tools.RelBuilder
import java.util
-import java.util.function.Function
import scala.collection.JavaConversions._
import scala.collection.mutable.ArrayBuffer
@@ -243,11 +242,19 @@ class BatchExecOverAggregate(
windowGroupInfo
}
+ //~ ExecNode methods -----------------------------------------------------------
+
override def getDamBehavior = DamBehavior.PIPELINED
override def getInputNodes: util.List[ExecNode[BatchTableEnvironment, _]] =
List(getInput.asInstanceOf[ExecNode[BatchTableEnvironment, _]])
+ override def replaceInputNode(
+ ordinalInParent: Int,
+ newInputNode: ExecNode[BatchTableEnvironment, _]): Unit = {
+ replaceInput(ordinalInParent, newInputNode.asInstanceOf[RelNode])
+ }
+
override def translateToPlanInternal(
tableEnv: BatchTableEnvironment): StreamTransformation[BaseRow] = {
val input = getInputNodes.get(0).translateToPlan(tableEnv)
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecRank.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecRank.scala
index 05cd325..1363a47 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecRank.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecRank.scala
@@ -112,11 +112,19 @@ class BatchExecRank(
costFactory.makeCost(rowCount, cpuCost, 0, 0, memCost)
}
+ //~ ExecNode methods -----------------------------------------------------------
+
override def getDamBehavior: DamBehavior = DamBehavior.PIPELINED
override def getInputNodes: util.List[ExecNode[BatchTableEnvironment, _]] =
List(getInput.asInstanceOf[ExecNode[BatchTableEnvironment, _]])
+ override def replaceInputNode(
+ ordinalInParent: Int,
+ newInputNode: ExecNode[BatchTableEnvironment, _]): Unit = {
+ replaceInput(ordinalInParent, newInputNode.asInstanceOf[RelNode])
+ }
+
override def translateToPlanInternal(
tableEnv: BatchTableEnvironment): StreamTransformation[BaseRow] = {
val input = getInputNodes.get(0).translateToPlan(tableEnv)
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecSink.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecSink.scala
index 97b2d9e..90e9a6e 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecSink.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecSink.scala
@@ -67,6 +67,12 @@ class BatchExecSink[T](
List(getInput.asInstanceOf[ExecNode[BatchTableEnvironment, _]])
}
+ override def replaceInputNode(
+ ordinalInParent: Int,
+ newInputNode: ExecNode[BatchTableEnvironment, _]): Unit = {
+ replaceInput(ordinalInParent, newInputNode.asInstanceOf[RelNode])
+ }
+
override protected def translateToPlanInternal(
tableEnv: BatchTableEnvironment): StreamTransformation[Any] = {
val resultTransformation = sink match {
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecSort.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecSort.scala
index a533532..3bca41d 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecSort.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecSort.scala
@@ -86,11 +86,19 @@ class BatchExecSort(
costFactory.makeCost(rowCount, cpuCost, 0, 0, memCost)
}
+ //~ ExecNode methods -----------------------------------------------------------
+
override def getDamBehavior = DamBehavior.FULL_DAM
override def getInputNodes: util.List[ExecNode[BatchTableEnvironment, _]] =
List(getInput.asInstanceOf[ExecNode[BatchTableEnvironment, _]])
+ override def replaceInputNode(
+ ordinalInParent: Int,
+ newInputNode: ExecNode[BatchTableEnvironment, _]): Unit = {
+ replaceInput(ordinalInParent, newInputNode.asInstanceOf[RelNode])
+ }
+
override def translateToPlanInternal(
tableEnv: BatchTableEnvironment): StreamTransformation[BaseRow] = {
val input = getInputNodes.get(0).translateToPlan(tableEnv)
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecSortAggregate.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecSortAggregate.scala
index d960e3f..63b0758 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecSortAggregate.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecSortAggregate.scala
@@ -95,6 +95,8 @@ class BatchExecSortAggregate(
isGlobal = true))
}
+ //~ ExecNode methods -----------------------------------------------------------
+
override def getDamBehavior: DamBehavior = {
if (grouping.length == 0) DamBehavior.FULL_DAM else DamBehavior.PIPELINED
}
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecSortAggregateBase.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecSortAggregateBase.scala
index 938b011..679ea11 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecSortAggregateBase.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecSortAggregateBase.scala
@@ -86,9 +86,17 @@ abstract class BatchExecSortAggregateBase(
costFactory.makeCost(rowCount, cpuCost, 0, 0, memCost)
}
+ //~ ExecNode methods -----------------------------------------------------------
+
override def getInputNodes: util.List[ExecNode[BatchTableEnvironment, _]] =
List(getInput.asInstanceOf[ExecNode[BatchTableEnvironment, _]])
+ override def replaceInputNode(
+ ordinalInParent: Int,
+ newInputNode: ExecNode[BatchTableEnvironment, _]): Unit = {
+ replaceInput(ordinalInParent, newInputNode.asInstanceOf[RelNode])
+ }
+
def getOperatorName: String
def getParallelism(input: StreamTransformation[BaseRow], conf: TableConfig): Int
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecSortLimit.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecSortLimit.scala
index d24985c..33043c1 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecSortLimit.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecSortLimit.scala
@@ -109,11 +109,19 @@ class BatchExecSortLimit(
costFactory.makeCost(rowCount, cpuCost, 0, 0, memCost)
}
+ //~ ExecNode methods -----------------------------------------------------------
+
override def getDamBehavior: DamBehavior = DamBehavior.FULL_DAM
override def getInputNodes: util.List[ExecNode[BatchTableEnvironment, _]] =
List(getInput.asInstanceOf[ExecNode[BatchTableEnvironment, _]])
+ override def replaceInputNode(
+ ordinalInParent: Int,
+ newInputNode: ExecNode[BatchTableEnvironment, _]): Unit = {
+ replaceInput(ordinalInParent, newInputNode.asInstanceOf[RelNode])
+ }
+
override def translateToPlanInternal(
tableEnv: BatchTableEnvironment): StreamTransformation[BaseRow] = {
if (limitEnd == Long.MaxValue) {
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecSortMergeJoin.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecSortMergeJoin.scala
index 5f02fb4..4db56da 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecSortMergeJoin.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecSortMergeJoin.scala
@@ -119,17 +119,23 @@ trait BatchExecSortMergeJoinBase extends BatchExecJoinBase with BatchExecNode[Ba
costFactory.makeCost(rowCount, cpuCost, 0, 0, sortMemCost)
}
+ //~ ExecNode methods -----------------------------------------------------------
+
/**
* Now must be full dam without two input operator chain.
* TODO two input operator chain will return different value.
*/
- override def getDamBehavior: DamBehavior = {
- DamBehavior.FULL_DAM
- }
+ override def getDamBehavior: DamBehavior = DamBehavior.FULL_DAM
override def getInputNodes: util.List[ExecNode[BatchTableEnvironment, _]] =
getInputs.map(_.asInstanceOf[ExecNode[BatchTableEnvironment, _]])
+ override def replaceInputNode(
+ ordinalInParent: Int,
+ newInputNode: ExecNode[BatchTableEnvironment, _]): Unit = {
+ replaceInput(ordinalInParent, newInputNode.asInstanceOf[RelNode])
+ }
+
override def translateToPlanInternal(
tableEnv: BatchTableEnvironment): StreamTransformation[BaseRow] = {
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecSortWindowAggregate.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecSortWindowAggregate.scala
index 9f76290..0b5adae 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecSortWindowAggregate.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecSortWindowAggregate.scala
@@ -88,6 +88,8 @@ class BatchExecSortWindowAggregate(
isMerge)
}
+ //~ ExecNode methods -----------------------------------------------------------
+
override def getDamBehavior: DamBehavior = DamBehavior.PIPELINED
override def getOperatorName: String = {
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecSortWindowAggregateBase.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecSortWindowAggregateBase.scala
index 6192bda..6a431a5 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecSortWindowAggregateBase.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecSortWindowAggregateBase.scala
@@ -91,9 +91,17 @@ abstract class BatchExecSortWindowAggregateBase(
costFactory.makeCost(mq.getRowCount(this), cpu, 0, 0, memCost)
}
+ //~ ExecNode methods -----------------------------------------------------------
+
override def getInputNodes: util.List[ExecNode[BatchTableEnvironment, _]] =
List(getInput.asInstanceOf[ExecNode[BatchTableEnvironment, _]])
+ override def replaceInputNode(
+ ordinalInParent: Int,
+ newInputNode: ExecNode[BatchTableEnvironment, _]): Unit = {
+ replaceInput(ordinalInParent, newInputNode.asInstanceOf[RelNode])
+ }
+
def getOperatorName: String
def getParallelism(input: StreamTransformation[BaseRow], conf: TableConfig): Int
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecTableSourceScan.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecTableSourceScan.scala
index 432d31a..93acefa 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecTableSourceScan.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecTableSourceScan.scala
@@ -18,6 +18,11 @@
package org.apache.flink.table.plan.nodes.physical.batch
+import org.apache.flink.runtime.operators.DamBehavior
+import org.apache.flink.streaming.api.transformations.StreamTransformation
+import org.apache.flink.table.api.{BatchTableEnvironment, TableException}
+import org.apache.flink.table.dataformat.BaseRow
+import org.apache.flink.table.plan.nodes.exec.{BatchExecNode, ExecNode}
import org.apache.flink.table.plan.nodes.physical.PhysicalTableSourceScan
import org.apache.flink.table.plan.schema.FlinkRelOptTable
import org.apache.flink.table.sources.BatchTableSource
@@ -28,6 +33,8 @@ import org.apache.calcite.rel.metadata.RelMetadataQuery
import java.util
+import scala.collection.JavaConversions._
+
/**
* Batch physical RelNode to read data from an external source defined by a [[BatchTableSource]].
*/
@@ -36,7 +43,8 @@ class BatchExecTableSourceScan(
traitSet: RelTraitSet,
relOptTable: FlinkRelOptTable)
extends PhysicalTableSourceScan(cluster, traitSet, relOptTable)
- with BatchPhysicalRel {
+ with BatchPhysicalRel
+ with BatchExecNode[BaseRow]{
override def copy(traitSet: RelTraitSet, inputs: util.List[RelNode]): RelNode = {
new BatchExecTableSourceScan(cluster, traitSet, relOptTable)
@@ -53,4 +61,21 @@ class BatchExecTableSourceScan(
planner.getCostFactory.makeCost(rowCnt, cpu, size)
}
+ //~ ExecNode methods -----------------------------------------------------------
+
+ override def getDamBehavior: DamBehavior = DamBehavior.PIPELINED
+
+ override def getInputNodes: util.List[ExecNode[BatchTableEnvironment, _]] = List()
+
+ override def replaceInputNode(
+ ordinalInParent: Int,
+ newInputNode: ExecNode[BatchTableEnvironment, _]): Unit = {
+ replaceInput(ordinalInParent, newInputNode.asInstanceOf[RelNode])
+ }
+
+ override def translateToPlanInternal(
+ tableEnv: BatchTableEnvironment): StreamTransformation[BaseRow] = {
+ throw new TableException("Implements this")
+ }
+
}
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecUnion.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecUnion.scala
index 6800462..9919d0b 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecUnion.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecUnion.scala
@@ -58,11 +58,19 @@ class BatchExecUnion(
.item("union", getRowType.getFieldNames.mkString(", "))
}
+ //~ ExecNode methods -----------------------------------------------------------
+
override def getDamBehavior: DamBehavior = DamBehavior.PIPELINED
override def getInputNodes: util.List[ExecNode[BatchTableEnvironment, _]] =
getInputs.map(_.asInstanceOf[ExecNode[BatchTableEnvironment, _]])
+ override def replaceInputNode(
+ ordinalInParent: Int,
+ newInputNode: ExecNode[BatchTableEnvironment, _]): Unit = {
+ replaceInput(ordinalInParent, newInputNode.asInstanceOf[RelNode])
+ }
+
override def translateToPlanInternal(
tableEnv: BatchTableEnvironment): StreamTransformation[BaseRow] = {
val transformations = getInputNodes.map {
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecValues.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecValues.scala
index ad312f2..d6f0dca 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecValues.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecValues.scala
@@ -64,6 +64,14 @@ class BatchExecValues(
override def getDamBehavior: DamBehavior = DamBehavior.PIPELINED
+ override def getInputNodes: util.List[ExecNode[BatchTableEnvironment, _]] = List()
+
+ override def replaceInputNode(
+ ordinalInParent: Int,
+ newInputNode: ExecNode[BatchTableEnvironment, _]): Unit = {
+ replaceInput(ordinalInParent, newInputNode.asInstanceOf[RelNode])
+ }
+
override protected def translateToPlanInternal(
tableEnv: BatchTableEnvironment): StreamTransformation[BaseRow] = {
val inputFormat = ValuesCodeGenerator.generatorInputFormat(
@@ -74,9 +82,5 @@ class BatchExecValues(
tableEnv.streamEnv.createInput(inputFormat, inputFormat.getProducedType).getTransformation
}
- override def getInputNodes: util.List[ExecNode[BatchTableEnvironment, _]] = {
- new util.ArrayList[ExecNode[BatchTableEnvironment, _]]()
- }
-
}
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecWindowAggregateBase.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecWindowAggregateBase.scala
index bdd1d8d..811e032 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecWindowAggregateBase.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecWindowAggregateBase.scala
@@ -71,4 +71,5 @@ abstract class BatchExecWindowAggregateBase(
isMerge = isMerge,
isGlobal = isFinal))
}
+
}
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecCalc.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecCalc.scala
index 4886e05..a8a286d 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecCalc.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecCalc.scala
@@ -67,9 +67,17 @@ class StreamExecCalc(
new StreamExecCalc(cluster, traitSet, child, program, outputRowType)
}
+ //~ ExecNode methods -----------------------------------------------------------
+
override def getInputNodes: util.List[ExecNode[StreamTableEnvironment, _]] =
List(getInput.asInstanceOf[ExecNode[StreamTableEnvironment, _]])
+ override def replaceInputNode(
+ ordinalInParent: Int,
+ newInputNode: ExecNode[StreamTableEnvironment, _]): Unit = {
+ replaceInput(ordinalInParent, newInputNode.asInstanceOf[RelNode])
+ }
+
override def translateToPlanInternal(
tableEnv: StreamTableEnvironment): StreamTransformation[BaseRow] = {
val config = tableEnv.getConfig
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecCorrelate.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecCorrelate.scala
index 9649c18..30e5f6e 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecCorrelate.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecCorrelate.scala
@@ -24,7 +24,7 @@ import org.apache.flink.table.dataformat.BaseRow
import org.apache.flink.table.functions.utils.TableSqlFunction
import org.apache.flink.table.plan.nodes.exec.{ExecNode, StreamExecNode}
import org.apache.flink.table.plan.nodes.logical.FlinkLogicalTableFunctionScan
-import org.apache.flink.table.plan.util.RelExplainUtil
+import org.apache.flink.table.plan.util.{CorrelateUtil, RelExplainUtil}
import org.apache.flink.table.runtime.AbstractProcessStreamOperator
import org.apache.calcite.plan.{RelOptCluster, RelTraitSet}
@@ -108,6 +108,12 @@ class StreamExecCorrelate(
override def getInputNodes: util.List[ExecNode[StreamTableEnvironment, _]] =
getInputs.map(_.asInstanceOf[ExecNode[StreamTableEnvironment, _]])
+ override def replaceInputNode(
+ ordinalInParent: Int,
+ newInputNode: ExecNode[StreamTableEnvironment, _]): Unit = {
+ replaceInput(ordinalInParent, newInputNode.asInstanceOf[RelNode])
+ }
+
override def translateToPlanInternal(
tableEnv: StreamTableEnvironment): StreamTransformation[BaseRow] = {
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecDataStreamScan.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecDataStreamScan.scala
index a8a42b1..8165bd1 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecDataStreamScan.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecDataStreamScan.scala
@@ -91,8 +91,16 @@ class StreamExecDataStreamScan(
.item("fields", getRowType.getFieldNames.asScala.mkString(", "))
}
+ //~ ExecNode methods -----------------------------------------------------------
+
override def getInputNodes: util.List[ExecNode[StreamTableEnvironment, _]] = List()
+ override def replaceInputNode(
+ ordinalInParent: Int,
+ newInputNode: ExecNode[StreamTableEnvironment, _]): Unit = {
+ replaceInput(ordinalInParent, newInputNode.asInstanceOf[RelNode])
+ }
+
override protected def translateToPlanInternal(
tableEnv: StreamTableEnvironment): StreamTransformation[BaseRow] = {
val config = tableEnv.getConfig
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecDeduplicate.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecDeduplicate.scala
index a286b07..3a59b70 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecDeduplicate.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecDeduplicate.scala
@@ -88,6 +88,16 @@ class StreamExecDeduplicate(
//~ ExecNode methods -----------------------------------------------------------
+ override def getInputNodes: util.List[ExecNode[StreamTableEnvironment, _]] = {
+ List(getInput.asInstanceOf[ExecNode[StreamTableEnvironment, _]])
+ }
+
+ override def replaceInputNode(
+ ordinalInParent: Int,
+ newInputNode: ExecNode[StreamTableEnvironment, _]): Unit = {
+ replaceInput(ordinalInParent, newInputNode.asInstanceOf[RelNode])
+ }
+
override protected def translateToPlanInternal(
tableEnv: StreamTableEnvironment): StreamTransformation[BaseRow] = {
@@ -146,10 +156,6 @@ class StreamExecDeduplicate(
ret
}
- override def getInputNodes: util.List[ExecNode[StreamTableEnvironment, _]] = {
- List(getInput.asInstanceOf[ExecNode[StreamTableEnvironment, _]])
- }
-
private def getOperatorName: String = {
val fieldNames = getRowType.getFieldNames
val keyNames = uniqueKeys.map(fieldNames.get).mkString(", ")
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecExchange.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecExchange.scala
index a9efa6b..f5723bc 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecExchange.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecExchange.scala
@@ -71,6 +71,12 @@ class StreamExecExchange(
List(getInput.asInstanceOf[ExecNode[StreamTableEnvironment, _]])
}
+ override def replaceInputNode(
+ ordinalInParent: Int,
+ newInputNode: ExecNode[StreamTableEnvironment, _]): Unit = {
+ replaceInput(ordinalInParent, newInputNode.asInstanceOf[RelNode])
+ }
+
override protected def translateToPlanInternal(
tableEnv: StreamTableEnvironment): StreamTransformation[BaseRow] = {
val inputTransform = getInputNodes.get(0).translateToPlan(tableEnv)
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecExpand.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecExpand.scala
index a90306e..2bf7766 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecExpand.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecExpand.scala
@@ -19,7 +19,7 @@ package org.apache.flink.table.plan.nodes.physical.stream
import org.apache.flink.streaming.api.transformations.{OneInputTransformation, StreamTransformation}
import org.apache.flink.table.`type`.{RowType, TypeConverters}
-import org.apache.flink.table.api.{StreamTableEnvironment, TableConfigOptions}
+import org.apache.flink.table.api.StreamTableEnvironment
import org.apache.flink.table.calcite.FlinkTypeFactory
import org.apache.flink.table.codegen.{CodeGeneratorContext, ExpandCodeGenerator}
import org.apache.flink.table.dataformat.BaseRow
@@ -63,10 +63,18 @@ class StreamExecExpand(
new StreamExecExpand(cluster, traitSet, inputs.get(0), outputRowType, projects, expandIdIndex)
}
+ //~ ExecNode methods -----------------------------------------------------------
+
override def getInputNodes: util.List[ExecNode[StreamTableEnvironment, _]] = {
getInputs.map(_.asInstanceOf[ExecNode[StreamTableEnvironment, _]])
}
+ override def replaceInputNode(
+ ordinalInParent: Int,
+ newInputNode: ExecNode[StreamTableEnvironment, _]): Unit = {
+ replaceInput(ordinalInParent, newInputNode.asInstanceOf[RelNode])
+ }
+
override protected def translateToPlanInternal(
tableEnv: StreamTableEnvironment): StreamTransformation[BaseRow] = {
val config = tableEnv.getConfig
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecGlobalGroupAggregate.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecGlobalGroupAggregate.scala
index 41ad409..e7f879d 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecGlobalGroupAggregate.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecGlobalGroupAggregate.scala
@@ -98,10 +98,18 @@ class StreamExecGlobalGroupAggregate(
isGlobal = true))
}
+ //~ ExecNode methods -----------------------------------------------------------
+
override def getInputNodes: util.List[ExecNode[StreamTableEnvironment, _]] = {
getInputs.map(_.asInstanceOf[ExecNode[StreamTableEnvironment, _]])
}
+ override def replaceInputNode(
+ ordinalInParent: Int,
+ newInputNode: ExecNode[StreamTableEnvironment, _]): Unit = {
+ replaceInput(ordinalInParent, newInputNode.asInstanceOf[RelNode])
+ }
+
override protected def translateToPlanInternal(
tableEnv: StreamTableEnvironment): StreamTransformation[BaseRow] = {
val tableConfig = tableEnv.getConfig
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecGroupAggregate.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecGroupAggregate.scala
index 2dcf908..a9ef5ce 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecGroupAggregate.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecGroupAggregate.scala
@@ -107,10 +107,18 @@ class StreamExecGroupAggregate(
grouping))
}
+ //~ ExecNode methods -----------------------------------------------------------
+
override def getInputNodes: util.List[ExecNode[StreamTableEnvironment, _]] = {
getInputs.map(_.asInstanceOf[ExecNode[StreamTableEnvironment, _]])
}
+ override def replaceInputNode(
+ ordinalInParent: Int,
+ newInputNode: ExecNode[StreamTableEnvironment, _]): Unit = {
+ replaceInput(ordinalInParent, newInputNode.asInstanceOf[RelNode])
+ }
+
override protected def translateToPlanInternal(
tableEnv: StreamTableEnvironment): StreamTransformation[BaseRow] = {
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecIncrementalGroupAggregate.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecIncrementalGroupAggregate.scala
index f30655d..868be32 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecIncrementalGroupAggregate.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecIncrementalGroupAggregate.scala
@@ -120,11 +120,18 @@ class StreamExecIncrementalGroupAggregate(
shuffleKey = Some(partialAggGrouping)))
}
+ //~ ExecNode methods -----------------------------------------------------------
override def getInputNodes: util.List[ExecNode[StreamTableEnvironment, _]] = {
getInputs.map(_.asInstanceOf[ExecNode[StreamTableEnvironment, _]])
}
+ override def replaceInputNode(
+ ordinalInParent: Int,
+ newInputNode: ExecNode[StreamTableEnvironment, _]): Unit = {
+ replaceInput(ordinalInParent, newInputNode.asInstanceOf[RelNode])
+ }
+
override protected def translateToPlanInternal(
tableEnv: StreamTableEnvironment): StreamTransformation[BaseRow] = {
val inputTransformation = getInputNodes.get(0).translateToPlan(tableEnv)
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecJoinBase.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecJoinBase.scala
index a927f44..164f141 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecJoinBase.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecJoinBase.scala
@@ -18,8 +18,12 @@
package org.apache.flink.table.plan.nodes.physical.stream
+import org.apache.flink.streaming.api.transformations.StreamTransformation
+import org.apache.flink.table.api.{StreamTableEnvironment, TableException}
+import org.apache.flink.table.dataformat.BaseRow
import org.apache.flink.table.plan.FlinkJoinRelType
import org.apache.flink.table.plan.nodes.common.CommonPhysicalJoin
+import org.apache.flink.table.plan.nodes.exec.{ExecNode, StreamExecNode}
import org.apache.calcite.plan._
import org.apache.calcite.plan.hep.HepRelVertex
@@ -28,6 +32,8 @@ import org.apache.calcite.rel.core.{CorrelationId, Join, JoinRelType}
import org.apache.calcite.rel.metadata.RelMetadataQuery
import org.apache.calcite.rex.RexNode
+import java.util
+
import scala.collection.JavaConversions._
/**
@@ -36,7 +42,10 @@ import scala.collection.JavaConversions._
* Regular joins are the most generic type of join in which any new records or changes to
* either side of the join input are visible and are affecting the whole join result.
*/
-trait StreamExecJoinBase extends CommonPhysicalJoin with StreamPhysicalRel {
+trait StreamExecJoinBase
+ extends CommonPhysicalJoin
+ with StreamPhysicalRel
+ with StreamExecNode[BaseRow] {
override def producesUpdates: Boolean = {
flinkJoinType != FlinkJoinRelType.INNER && flinkJoinType != FlinkJoinRelType.SEMI
@@ -84,6 +93,23 @@ trait StreamExecJoinBase extends CommonPhysicalJoin with StreamPhysicalRel {
planner.getCostFactory.makeCost(elementRate, elementRate, 0)
}
+ //~ ExecNode methods -----------------------------------------------------------
+
+ override def getInputNodes: util.List[ExecNode[StreamTableEnvironment, _]] = {
+ getInputs.map(_.asInstanceOf[ExecNode[StreamTableEnvironment, _]])
+ }
+
+ override def replaceInputNode(
+ ordinalInParent: Int,
+ newInputNode: ExecNode[StreamTableEnvironment, _]): Unit = {
+ replaceInput(ordinalInParent, newInputNode.asInstanceOf[RelNode])
+ }
+
+ override protected def translateToPlanInternal(
+ tableEnv: StreamTableEnvironment): StreamTransformation[BaseRow] = {
+ throw new TableException("Implements this")
+ }
+
}
class StreamExecJoin(
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecLimit.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecLimit.scala
index c44175b..8db06d8 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecLimit.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecLimit.scala
@@ -96,6 +96,12 @@ class StreamExecLimit(
List(getInput.asInstanceOf[ExecNode[StreamTableEnvironment, _]])
}
+ override def replaceInputNode(
+ ordinalInParent: Int,
+ newInputNode: ExecNode[StreamTableEnvironment, _]): Unit = {
+ replaceInput(ordinalInParent, newInputNode.asInstanceOf[RelNode])
+ }
+
override protected def translateToPlanInternal(
tableEnv: StreamTableEnvironment): StreamTransformation[BaseRow] = {
if (fetch == null) {
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecLocalGroupAggregate.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecLocalGroupAggregate.scala
index ed6dab4..97d0288 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecLocalGroupAggregate.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecLocalGroupAggregate.scala
@@ -95,10 +95,18 @@ class StreamExecLocalGroupAggregate(
isLocal = true))
}
+ //~ ExecNode methods -----------------------------------------------------------
+
override def getInputNodes: util.List[ExecNode[StreamTableEnvironment, _]] = {
getInputs.map(_.asInstanceOf[ExecNode[StreamTableEnvironment, _]])
}
+ override def replaceInputNode(
+ ordinalInParent: Int,
+ newInputNode: ExecNode[StreamTableEnvironment, _]): Unit = {
+ replaceInput(ordinalInParent, newInputNode.asInstanceOf[RelNode])
+ }
+
override protected def translateToPlanInternal(
tableEnv: StreamTableEnvironment): StreamTransformation[BaseRow] = {
val inputTransformation = getInputNodes.get(0).translateToPlan(tableEnv)
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecOverAggregate.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecOverAggregate.scala
index 3a085aa..93e6831 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecOverAggregate.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecOverAggregate.scala
@@ -17,8 +17,12 @@
*/
package org.apache.flink.table.plan.nodes.physical.stream
+import org.apache.flink.streaming.api.transformations.StreamTransformation
import org.apache.flink.table.CalcitePair
+import org.apache.flink.table.api.{StreamTableEnvironment, TableException}
import org.apache.flink.table.calcite.FlinkTypeFactory
+import org.apache.flink.table.dataformat.BaseRow
+import org.apache.flink.table.plan.nodes.exec.{ExecNode, StreamExecNode}
import org.apache.flink.table.plan.util.RelExplainUtil
import org.apache.calcite.plan.{RelOptCluster, RelOptCost, RelOptPlanner, RelTraitSet}
@@ -31,7 +35,7 @@ import org.apache.calcite.rex.RexLiteral
import java.util
-import scala.collection.JavaConverters._
+import scala.collection.JavaConversions._
/**
* Stream physical RelNode for time-based over [[Window]].
@@ -44,7 +48,8 @@ class StreamExecOverAggregate(
inputRowType: RelDataType,
logicWindow: Window)
extends SingleRel(cluster, traitSet, inputRel)
- with StreamPhysicalRel {
+ with StreamPhysicalRel
+ with StreamExecNode[BaseRow] {
override def producesUpdates: Boolean = false
@@ -91,7 +96,7 @@ class StreamExecOverAggregate(
override def explainTerms(pw: RelWriter): RelWriter = {
val overWindow: Group = logicWindow.groups.get(0)
- val constants: Seq[RexLiteral] = logicWindow.constants.asScala
+ val constants: Seq[RexLiteral] = logicWindow.constants
val partitionKeys: Array[Int] = overWindow.keys.toArray
val namedAggregates: Seq[CalcitePair[AggregateCall, String]] = generateNamedAggregates
@@ -115,4 +120,20 @@ class StreamExecOverAggregate(
yield new CalcitePair[AggregateCall, String](aggregateCalls.get(i), "w0$o" + i)
}
+ //~ ExecNode methods -----------------------------------------------------------
+
+ override def getInputNodes: util.List[ExecNode[StreamTableEnvironment, _]] = {
+ getInputs.map(_.asInstanceOf[ExecNode[StreamTableEnvironment, _]])
+ }
+
+ override def replaceInputNode(
+ ordinalInParent: Int,
+ newInputNode: ExecNode[StreamTableEnvironment, _]): Unit = {
+ replaceInput(ordinalInParent, newInputNode.asInstanceOf[RelNode])
+ }
+
+ override protected def translateToPlanInternal(
+ tableEnv: StreamTableEnvironment): StreamTransformation[BaseRow] = {
+ throw new TableException("Implements this")
+ }
}
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecRank.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecRank.scala
index 5d3db0d..11aad71 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecRank.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecRank.scala
@@ -117,6 +117,12 @@ class StreamExecRank(
List(getInput.asInstanceOf[ExecNode[StreamTableEnvironment, _]])
}
+ override def replaceInputNode(
+ ordinalInParent: Int,
+ newInputNode: ExecNode[StreamTableEnvironment, _]): Unit = {
+ replaceInput(ordinalInParent, newInputNode.asInstanceOf[RelNode])
+ }
+
override protected def translateToPlanInternal(
tableEnv: StreamTableEnvironment): StreamTransformation[BaseRow] = {
val tableConfig = tableEnv.getConfig
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecSink.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecSink.scala
index e7a472d..efe754f 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecSink.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecSink.scala
@@ -73,6 +73,12 @@ class StreamExecSink[T](
List(getInput.asInstanceOf[ExecNode[StreamTableEnvironment, _]])
}
+ override def replaceInputNode(
+ ordinalInParent: Int,
+ newInputNode: ExecNode[StreamTableEnvironment, _]): Unit = {
+ replaceInput(ordinalInParent, newInputNode.asInstanceOf[RelNode])
+ }
+
override protected def translateToPlanInternal(
tableEnv: StreamTableEnvironment): StreamTransformation[Any] = {
val resultTransformation = sink match {
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecSort.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecSort.scala
index 0c61064..1750621 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecSort.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecSort.scala
@@ -45,9 +45,9 @@ import scala.collection.JavaConversions._
*
* @see [[StreamExecTemporalSort]] which must be time-ascending-order sort without `limit`.
*
- * e.g.
- * ''SELECT * FROM TABLE ORDER BY ROWTIME, a'' will be converted to [[StreamExecTemporalSort]]
- * ''SELECT * FROM TABLE ORDER BY a, ROWTIME'' will be converted to [[StreamExecSort]]
+ * e.g.
+ * ''SELECT * FROM TABLE ORDER BY ROWTIME, a'' will be converted to [[StreamExecTemporalSort]]
+ * ''SELECT * FROM TABLE ORDER BY a, ROWTIME'' will be converted to [[StreamExecSort]]
*/
@Experimental
class StreamExecSort(
@@ -99,6 +99,12 @@ class StreamExecSort(
List(getInput.asInstanceOf[ExecNode[StreamTableEnvironment, _]])
}
+ override def replaceInputNode(
+ ordinalInParent: Int,
+ newInputNode: ExecNode[StreamTableEnvironment, _]): Unit = {
+ replaceInput(ordinalInParent, newInputNode.asInstanceOf[RelNode])
+ }
+
/**
* Internal method, translates this node into a Flink operator.
*
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecSortLimit.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecSortLimit.scala
index 94fc2ea..d536a27 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecSortLimit.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecSortLimit.scala
@@ -120,6 +120,12 @@ class StreamExecSortLimit(
List(getInput.asInstanceOf[ExecNode[StreamTableEnvironment, _]])
}
+ override def replaceInputNode(
+ ordinalInParent: Int,
+ newInputNode: ExecNode[StreamTableEnvironment, _]): Unit = {
+ replaceInput(ordinalInParent, newInputNode.asInstanceOf[RelNode])
+ }
+
override protected def translateToPlanInternal(
tableEnv: StreamTableEnvironment): StreamTransformation[BaseRow] = {
if (fetch == null) {
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecTableSourceScan.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecTableSourceScan.scala
index 03081f6..4b2a8aa 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecTableSourceScan.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecTableSourceScan.scala
@@ -18,6 +18,10 @@
package org.apache.flink.table.plan.nodes.physical.stream
+import org.apache.flink.streaming.api.transformations.StreamTransformation
+import org.apache.flink.table.api.{StreamTableEnvironment, TableException}
+import org.apache.flink.table.dataformat.BaseRow
+import org.apache.flink.table.plan.nodes.exec.{ExecNode, StreamExecNode}
import org.apache.flink.table.plan.nodes.physical.PhysicalTableSourceScan
import org.apache.flink.table.plan.schema.FlinkRelOptTable
import org.apache.flink.table.sources.StreamTableSource
@@ -26,6 +30,10 @@ import org.apache.calcite.plan._
import org.apache.calcite.rel.RelNode
import org.apache.calcite.rel.metadata.RelMetadataQuery
+import java.util
+
+import scala.collection.JavaConversions._
+
/**
* Stream physical RelNode to read data from an external source defined by a [[StreamTableSource]].
*/
@@ -34,7 +42,8 @@ class StreamExecTableSourceScan(
traitSet: RelTraitSet,
relOptTable: FlinkRelOptTable)
extends PhysicalTableSourceScan(cluster, traitSet, relOptTable)
- with StreamPhysicalRel {
+ with StreamPhysicalRel
+ with StreamExecNode[BaseRow] {
override def producesUpdates: Boolean = false
@@ -56,4 +65,20 @@ class StreamExecTableSourceScan(
planner.getCostFactory.makeCost(rowCnt, rowCnt, rowCnt * rowSize)
}
+ //~ ExecNode methods -----------------------------------------------------------
+
+ override def getInputNodes: util.List[ExecNode[StreamTableEnvironment, _]] = {
+ getInputs.map(_.asInstanceOf[ExecNode[StreamTableEnvironment, _]])
+ }
+
+ override def replaceInputNode(
+ ordinalInParent: Int,
+ newInputNode: ExecNode[StreamTableEnvironment, _]): Unit = {
+ replaceInput(ordinalInParent, newInputNode.asInstanceOf[RelNode])
+ }
+
+ override protected def translateToPlanInternal(
+ tableEnv: StreamTableEnvironment): StreamTransformation[BaseRow] = {
+ throw new TableException("Implements this")
+ }
}
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecTemporalSort.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecTemporalSort.scala
index 2892ab2..60e1484 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecTemporalSort.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecTemporalSort.scala
@@ -89,6 +89,12 @@ class StreamExecTemporalSort(
List(getInput.asInstanceOf[ExecNode[StreamTableEnvironment, _]])
}
+ override def replaceInputNode(
+ ordinalInParent: Int,
+ newInputNode: ExecNode[StreamTableEnvironment, _]): Unit = {
+ replaceInput(ordinalInParent, newInputNode.asInstanceOf[RelNode])
+ }
+
/**
* Internal method, translates this node into a Flink operator.
*
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecUnion.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecUnion.scala
index 4cf5fd6..c9356fb 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecUnion.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecUnion.scala
@@ -18,16 +18,15 @@
package org.apache.flink.table.plan.nodes.physical.stream
-import org.apache.calcite.plan.{RelOptCluster, RelTraitSet}
-import org.apache.calcite.rel.`type`.RelDataType
-import org.apache.calcite.rel.core.{SetOp, Union}
-import org.apache.calcite.rel.{RelNode, RelWriter}
import org.apache.flink.streaming.api.transformations.{StreamTransformation, UnionTransformation}
import org.apache.flink.table.api.StreamTableEnvironment
-import org.apache.flink.table.calcite.FlinkTypeFactory
import org.apache.flink.table.dataformat.BaseRow
import org.apache.flink.table.plan.nodes.exec.{ExecNode, StreamExecNode}
-import org.apache.flink.table.typeutils.BaseRowTypeInfo
+
+import org.apache.calcite.plan.{RelOptCluster, RelTraitSet}
+import org.apache.calcite.rel.`type`.RelDataType
+import org.apache.calcite.rel.core.{SetOp, Union}
+import org.apache.calcite.rel.{RelNode, RelWriter}
import java.util
@@ -68,10 +67,18 @@ class StreamExecUnion(
super.explainTerms(pw).item("union", outputRowType.getFieldNames.mkString(", "))
}
+ //~ ExecNode methods -----------------------------------------------------------
+
override def getInputNodes: util.List[ExecNode[StreamTableEnvironment, _]] = {
getInputs.map(_.asInstanceOf[ExecNode[StreamTableEnvironment, _]])
}
+ override def replaceInputNode(
+ ordinalInParent: Int,
+ newInputNode: ExecNode[StreamTableEnvironment, _]): Unit = {
+ replaceInput(ordinalInParent, newInputNode.asInstanceOf[RelNode])
+ }
+
override protected def translateToPlanInternal(
tableEnv: StreamTableEnvironment): StreamTransformation[BaseRow] = {
val transformations = getInputNodes.map {
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecValues.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecValues.scala
index 4b63f18..4546919 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecValues.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecValues.scala
@@ -64,6 +64,16 @@ class StreamExecValues(
//~ ExecNode methods -----------------------------------------------------------
+ override def getInputNodes: util.List[ExecNode[StreamTableEnvironment, _]] = {
+ new util.ArrayList[ExecNode[StreamTableEnvironment, _]]()
+ }
+
+ override def replaceInputNode(
+ ordinalInParent: Int,
+ newInputNode: ExecNode[StreamTableEnvironment, _]): Unit = {
+ replaceInput(ordinalInParent, newInputNode.asInstanceOf[RelNode])
+ }
+
override protected def translateToPlanInternal(
tableEnv: StreamTableEnvironment): StreamTransformation[BaseRow] = {
if (tableEnv.getConfig.getConf.getBoolean(
@@ -81,8 +91,4 @@ class StreamExecValues(
}
}
- override def getInputNodes: util.List[ExecNode[StreamTableEnvironment, _]] = {
- new util.ArrayList[ExecNode[StreamTableEnvironment, _]]()
- }
-
}
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecWatermarkAssigner.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecWatermarkAssigner.scala
index facd712..f0dbe67 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecWatermarkAssigner.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecWatermarkAssigner.scala
@@ -18,9 +18,12 @@
package org.apache.flink.table.plan.nodes.physical.stream
-import org.apache.flink.table.api.{TableConfigOptions, TableException}
+import org.apache.flink.streaming.api.transformations.StreamTransformation
+import org.apache.flink.table.api.{StreamTableEnvironment, TableConfigOptions, TableException}
+import org.apache.flink.table.dataformat.BaseRow
import org.apache.flink.table.plan.`trait`.{MiniBatchIntervalTraitDef, MiniBatchMode}
import org.apache.flink.table.plan.nodes.calcite.WatermarkAssigner
+import org.apache.flink.table.plan.nodes.exec.{ExecNode, StreamExecNode}
import org.apache.flink.table.plan.optimize.program.FlinkOptimizeContext
import org.apache.flink.util.Preconditions
@@ -29,6 +32,8 @@ import org.apache.calcite.rel.{RelNode, RelWriter}
import java.util
+import scala.collection.JavaConversions._
+
/**
* Stream physical RelNode for [[WatermarkAssigner]].
*/
@@ -39,7 +44,8 @@ class StreamExecWatermarkAssigner(
rowtimeFieldIndex: Option[Int],
watermarkDelay: Option[Long])
extends WatermarkAssigner(cluster, traits, inputRel, rowtimeFieldIndex, watermarkDelay)
- with StreamPhysicalRel {
+ with StreamPhysicalRel
+ with StreamExecNode[BaseRow] {
override def producesUpdates: Boolean = false
@@ -83,6 +89,23 @@ class StreamExecWatermarkAssigner(
super.explainTerms(pw).item("miniBatchInterval", value)
}
+ //~ ExecNode methods -----------------------------------------------------------
+
+ override def getInputNodes: util.List[ExecNode[StreamTableEnvironment, _]] = {
+ getInputs.map(_.asInstanceOf[ExecNode[StreamTableEnvironment, _]])
+ }
+
+ override def replaceInputNode(
+ ordinalInParent: Int,
+ newInputNode: ExecNode[StreamTableEnvironment, _]): Unit = {
+ replaceInput(ordinalInParent, newInputNode.asInstanceOf[RelNode])
+ }
+
+ override protected def translateToPlanInternal(
+ tableEnv: StreamTableEnvironment): StreamTransformation[BaseRow] = {
+ throw new TableException("Implements this")
+ }
+
}
object StreamExecWatermarkAssigner {
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecWindowJoin.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecWindowJoin.scala
index 0b1f904..2138c2f 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecWindowJoin.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecWindowJoin.scala
@@ -18,7 +18,11 @@
package org.apache.flink.table.plan.nodes.physical.stream
+import org.apache.flink.streaming.api.transformations.StreamTransformation
+import org.apache.flink.table.api.{StreamTableEnvironment, TableException}
+import org.apache.flink.table.dataformat.BaseRow
import org.apache.flink.table.plan.FlinkJoinRelType
+import org.apache.flink.table.plan.nodes.exec.{ExecNode, StreamExecNode}
import org.apache.flink.table.plan.util.RelExplainUtil
import org.apache.calcite.plan._
@@ -27,6 +31,8 @@ import org.apache.calcite.rel.core.JoinRelType
import org.apache.calcite.rel.{BiRel, RelNode, RelWriter}
import org.apache.calcite.rex.RexNode
+import java.util
+
import scala.collection.JavaConversions._
/**
@@ -47,7 +53,8 @@ class StreamExecWindowJoin(
rightTimeIndex: Int,
remainCondition: Option[RexNode])
extends BiRel(cluster, traitSet, leftRel, rightRel)
- with StreamPhysicalRel {
+ with StreamPhysicalRel
+ with StreamExecNode[BaseRow] {
override def producesUpdates: Boolean = false
@@ -91,4 +98,21 @@ class StreamExecWindowJoin(
.item("select", getRowType.getFieldNames.mkString(", "))
}
+ //~ ExecNode methods -----------------------------------------------------------
+
+ override def getInputNodes: util.List[ExecNode[StreamTableEnvironment, _]] = {
+ getInputs.map(_.asInstanceOf[ExecNode[StreamTableEnvironment, _]])
+ }
+
+ override def replaceInputNode(
+ ordinalInParent: Int,
+ newInputNode: ExecNode[StreamTableEnvironment, _]): Unit = {
+ replaceInput(ordinalInParent, newInputNode.asInstanceOf[RelNode])
+ }
+
+ override protected def translateToPlanInternal(
+ tableEnv: StreamTableEnvironment): StreamTransformation[BaseRow] = {
+ throw new TableException("Implements this")
+ }
+
}
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/reuse/DeadlockBreakupProcessor.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/reuse/DeadlockBreakupProcessor.scala
new file mode 100644
index 0000000..7dbbad5
--- /dev/null
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/reuse/DeadlockBreakupProcessor.scala
@@ -0,0 +1,343 @@
+/*
+ * 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.plan.reuse
+
+import org.apache.flink.runtime.io.network.DataExchangeMode
+import org.apache.flink.runtime.operators.DamBehavior
+import org.apache.flink.streaming.api.datastream.DataStream
+import org.apache.flink.table.api.TableException
+import org.apache.flink.table.plan.`trait`.FlinkRelDistribution
+import org.apache.flink.table.plan.nodes.exec.{BatchExecNode, ExecNode, ExecNodeVisitorImpl}
+import org.apache.flink.table.plan.nodes.physical.batch._
+
+import com.google.common.collect.{Maps, Sets}
+import org.apache.calcite.rel.RelNode
+
+import java.util
+
+import scala.collection.JavaConversions._
+import scala.collection.mutable
+
+/**
+ * A DeadlockBreakupProcessor that finds out all deadlocks in the DAG, and resolves them.
+ *
+ * NOTES: This processor can be only applied on [[BatchExecNode]] DAG.
+ *
+ * Reused node (may be a [[BatchExecNode]] which has more than one outputs or
+ * a [[BatchExecBoundedStreamScan]] which transformation is used for different scan)
+ * might lead to a deadlock when a HashJoin or NestedLoopJoin have same reused inputs.
+ * Sets Exchange node(if it does not exist, add new one) as BATCH mode to break up the deadlock.
+ *
+ * e.g. SQL: WITH r AS (SELECT a, b FROM x limit 10)
+ * SELECT r1.a FROM r r1, r r2 WHERE r1.a = r2.a AND r1.b > 10 AND r2.b < 20
+ * the physical plan is: (sub-plan reused is enabled)
+ * {{{
+ * Calc(select=[a, b, b0])
+ * +- HashJoin(where=[=(a, a0)], join=[a, b, a0, b0], joinType=[InnerJoin], isBroadcast=[true],
+ * build=[left])
+ * :- Calc(select=[a, b], where=[>(b, 10)])
+ * : +- Limit(offset=[0], limit=[10], global=[true], reuse_id=[1])
+ * : +- Exchange(distribution=[single])
+ * : +- Limit(offset=[0], limit=[10], global=[false])
+ * : +- ScanTableSource(table=[[builtin, default, x,
+ * source: [selectedFields=[a, b]]]], fields=[a, b])
+ * +- Exchange(distribution=[broadcast])
+ * +- Calc(select=[a, b], where=[<(b, 20)])
+ * +- Reused(reference_id=[1])
+ * }}}
+ * the HashJoin's left input is probe side which could start to read data only after
+ * build side has finished, so the Exchange node in HashJoin's left input requires BATCH mode
+ * to block the stream. After this handler is applied, The simplified plan is:
+ * {{{
+ * Calc(select=[a])
+ * |
+ * HashJoin
+ * (build side)/ \(probe side)
+ * (broadcast)Exchange Exchange(exchange_mode=[BATCH]) add BATCH Exchange to breakup deadlock
+ * | |
+ * Calc(b>10) Calc(b<20)
+ * \ /
+ * Limit(global=[true], reuse_id=[1]))
+ * |
+ * Exchange(single)
+ * |
+ * Limit(global=[false])
+ * |
+ * ScanTableSource
+ * }}}
+ */
+class DeadlockBreakupProcessor {
+
+ def process(rootNodes: util.List[ExecNode[_, _]]): util.List[ExecNode[_, _]] = {
+ if (!rootNodes.forall(_.isInstanceOf[BatchExecNode[_]])) {
+ throw new TableException("Only BatchExecNode DAG is supported now")
+ }
+ val finder = new ReuseNodeFinder()
+ rootNodes.foreach(finder.visit)
+ rootNodes.foreach(_.asInstanceOf[BatchExecNode[_]].accept(new DeadlockBreakupVisitor(finder)))
+ rootNodes
+ }
+
+ /**
+ * Find reuse node.
+ * A reuse node has more than one output or is a [[BatchExecBoundedStreamScan]]
+ * which [[DataStream]] object is held by different [[BatchExecBoundedStreamScan]]s.
+ */
+ class ReuseNodeFinder extends ExecNodeVisitorImpl {
+ // map a node object to its visited times.
+ // the visited times of a reused node is greater than one
+ private val visitedTimes = Maps.newIdentityHashMap[ExecNode[_, _], Integer]()
+ // different BatchExecBoundedStreamScans may have same DataStream object
+ // map DataStream object to BatchExecBoundedStreamScans
+ private val mapDataStreamToScan =
+ Maps.newIdentityHashMap[DataStream[_], util.List[BatchExecBoundedStreamScan]]()
+
+ /**
+ * Return true if the visited time of the given node is greater than one,
+ * or the node is a [[BatchExecBoundedStreamScan]] and its [[DataStream]] object is held
+ * by different [[BatchExecBoundedStreamScan]]s. else false.
+ */
+ def isReusedNode(node: ExecNode[_, _]): Boolean = {
+ if (visitedTimes.getOrDefault(node, 0) > 1) {
+ true
+ } else {
+ node match {
+ case scan: BatchExecBoundedStreamScan =>
+ val dataStream = scan.boundedStreamTable.dataStream
+ val scans = mapDataStreamToScan.get(dataStream)
+ scans != null && scans.size() > 1
+ case _ => false
+ }
+ }
+ }
+
+ override def visit(node: ExecNode[_, _]): Unit = {
+ val times = visitedTimes.getOrDefault(node, 0)
+ visitedTimes.put(node, times + 1)
+ node match {
+ case scan: BatchExecBoundedStreamScan =>
+ val dataStream = scan.boundedStreamTable.dataStream
+ val scans = mapDataStreamToScan.getOrElseUpdate(
+ dataStream, new util.ArrayList[BatchExecBoundedStreamScan]())
+ scans.add(scan)
+ case _ => // do nothing
+ }
+ super.visit(node)
+ }
+ }
+
+ class DeadlockBreakupVisitor(finder: ReuseNodeFinder) extends ExecNodeVisitorImpl {
+
+ private def rewriteJoin(
+ join: BatchExecJoinBase,
+ leftIsBuild: Boolean,
+ distribution: FlinkRelDistribution): Unit = {
+ val (buildSideIndex, probeSideIndex) = if (leftIsBuild) (0, 1) else (1, 0)
+ val buildNode = join.getInputNodes.get(buildSideIndex)
+ val probeNode = join.getInputNodes.get(probeSideIndex)
+
+ // 1. find all reused nodes in build side of join.
+ val reusedNodesInBuildSide = findReusedNodesInBuildSide(buildNode, finder)
+ // 2. find all nodes from probe side of join
+ val inputPathsOfProbeSide = buildInputPathsOfProbeSide(
+ probeNode, reusedNodesInBuildSide, finder)
+ // 3. check whether all input paths have a barrier node (e.g. agg, sort)
+ if (inputPathsOfProbeSide.nonEmpty && !hasBarrierNodeInInputPaths(inputPathsOfProbeSide)) {
+ // 4. sets Exchange node(if does not exist, add one) as BATCH mode to break up the deadlock
+ probeNode match {
+ case e: BatchExecExchange =>
+ // TODO create a cloned BatchExecExchange for PIPELINE output
+ e.setRequiredDataExchangeMode(DataExchangeMode.BATCH)
+ case _ =>
+ val probeRel = probeNode.asInstanceOf[RelNode]
+ val traitSet = probeRel.getTraitSet.replace(distribution)
+ val e = new BatchExecExchange(
+ probeRel.getCluster,
+ traitSet,
+ probeRel,
+ distribution)
+ e.setRequiredDataExchangeMode(DataExchangeMode.BATCH)
+ // replace join node's input
+ join.replaceInputNode(probeSideIndex, e)
+ }
+ }
+ }
+
+ override def visit(node: ExecNode[_, _]): Unit = {
+ super.visit(node)
+ node match {
+ case hashJoin: BatchExecHashJoinBase =>
+ val joinInfo = hashJoin.joinInfo
+ val columns = if (hashJoin.leftIsBuild) joinInfo.rightKeys else joinInfo.leftKeys
+ val distribution = FlinkRelDistribution.hash(columns)
+ rewriteJoin(hashJoin, hashJoin.leftIsBuild, distribution)
+ case nestedLoopJoin: BatchExecNestedLoopJoinBase =>
+ rewriteJoin(nestedLoopJoin, nestedLoopJoin.leftIsBuild, FlinkRelDistribution.ANY)
+ case _ => // do nothing
+ }
+ }
+ }
+
+ /**
+ * Find all reused nodes in build side of join.
+ */
+ private def findReusedNodesInBuildSide(
+ buildNode: ExecNode[_, _],
+ finder: ReuseNodeFinder): Set[ExecNode[_, _]] = {
+ val nodesInBuildSide = Sets.newIdentityHashSet[ExecNode[_, _]]()
+ buildNode.accept(new ExecNodeVisitorImpl {
+ override def visit(node: ExecNode[_, _]): Unit = {
+ if (finder.isReusedNode(node)) {
+ nodesInBuildSide.add(node)
+ }
+ super.visit(node)
+ }
+ })
+ nodesInBuildSide.toSet
+ }
+
+ /**
+ * Visit all nodes in probe side of join until to the reused nodes
+ * which are in `reusedNodesInBuildSide` collection.
+ * e.g. (sub-plan reused is enabled)
+ * {{{
+ * hash join
+ * (build side) / \ (probe side)
+ * calc2 agg2
+ * | |
+ * agg1 reused
+ * \ /
+ * calc1 (reuse_id=1)
+ * |
+ * table source
+ * }}}
+ * the input-path of join's probe side is [agg2, reused, calc1].
+ *
+ * e.g. (sub-plan reused is disabled)
+ * {{{
+ * hash join
+ * (build side) / \ (probe side)
+ * calc1 calc2
+ * \ /
+ * scan table
+ * }}}
+ * the input-path of join's probe side is [calc2, scan].
+ */
+ private def buildInputPathsOfProbeSide(
+ probeNode: ExecNode[_, _],
+ reusedNodesInBuildSide: Set[ExecNode[_, _]],
+ finder: ReuseNodeFinder): List[Array[ExecNode[_, _]]] = {
+ val result = new mutable.ListBuffer[Array[ExecNode[_, _]]]()
+ val stack = new mutable.Stack[ExecNode[_, _]]()
+
+ if (reusedNodesInBuildSide.isEmpty) {
+ return result.toList
+ }
+
+ probeNode.accept(new ExecNodeVisitorImpl {
+ override def visit(node: ExecNode[_, _]): Unit = {
+ stack.push(node)
+ if (finder.isReusedNode(node) &&
+ isReusedNodeInBuildSide(node, reusedNodesInBuildSide)) {
+ result.add(stack.toArray.reverse)
+ } else {
+ super.visit(node)
+ }
+ stack.pop()
+ }
+ })
+
+ require(stack.isEmpty)
+ result.toList
+ }
+
+ /**
+ * Returns true if the given node is in `reusedNodesInBuildSide`, else false.
+ * NOTES: We treat different [[BatchExecBoundedStreamScan]]s with same [[DataStream]]
+ * object as the same.
+ */
+ private def isReusedNodeInBuildSide(
+ execNode: ExecNode[_, _],
+ reusedNodesInBuildSide: Set[ExecNode[_, _]]): Boolean = {
+ if (reusedNodesInBuildSide.contains(execNode)) {
+ true
+ } else {
+ execNode match {
+ case scan: BatchExecBoundedStreamScan =>
+ reusedNodesInBuildSide.exists {
+ case reusedScan: BatchExecBoundedStreamScan =>
+ reusedScan.boundedStreamTable.dataStream eq scan.boundedStreamTable.dataStream
+ case _ => false
+ }
+ case _ => false
+ }
+ }
+ }
+
+ /**
+ * Returns true if all input-paths have barrier node (e.g. agg, sort), otherwise false.
+ */
+ private def hasBarrierNodeInInputPaths(
+ inputPathsOfProbeSide: List[Array[ExecNode[_, _]]]): Boolean = {
+ require(inputPathsOfProbeSide.nonEmpty)
+
+ /** Return true if the successor of join in the input-path is build node, otherwise false */
+ def checkJoinBuildSide(
+ buildNode: ExecNode[_, _],
+ idxOfJoin: Int,
+ inputPath: Array[ExecNode[_, _]]): Boolean = {
+ if (idxOfJoin < inputPath.length - 1) {
+ val nextNode = inputPath(idxOfJoin + 1)
+ // next node is build node of hash join
+ buildNode eq nextNode
+ } else {
+ false
+ }
+ }
+
+ inputPathsOfProbeSide.forall {
+ inputPath =>
+ var idx = 0
+ var hasFullDamNode = false
+ // should exclude the reused node (at last position in path)
+ while (!hasFullDamNode && idx < inputPath.length - 1) {
+ val node = inputPath(idx)
+ val nodeDamBehavior = node.asInstanceOf[BatchExecNode[_]].getDamBehavior
+ hasFullDamNode = if (nodeDamBehavior == DamBehavior.FULL_DAM) {
+ true
+ } else {
+ node match {
+ case h: BatchExecHashJoinBase =>
+ val buildSideIndex = if (h.leftIsBuild) 0 else 1
+ val buildNode = h.getInputNodes.get(buildSideIndex)
+ checkJoinBuildSide(buildNode, idx, inputPath)
+ case n: BatchExecNestedLoopJoinBase =>
+ val buildSideIndex = if (n.leftIsBuild) 0 else 1
+ val buildNode = n.getInputNodes.get(buildSideIndex)
+ checkJoinBuildSide(buildNode, idx, inputPath)
+ case _ => false
+ }
+ }
+ idx += 1
+ }
+ hasFullDamNode
+ }
+ }
+
+}
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/reuse/SubplanReuser.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/reuse/SubplanReuser.scala
new file mode 100644
index 0000000..1733ad6
--- /dev/null
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/reuse/SubplanReuser.scala
@@ -0,0 +1,240 @@
+/*
+ * 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.plan.reuse
+
+import org.apache.flink.table.api.{PlannerConfigOptions, TableConfig, TableException}
+import org.apache.flink.table.plan.nodes.calcite.Sink
+import org.apache.flink.table.plan.nodes.logical.FlinkLogicalTableSourceScan
+import org.apache.flink.table.plan.nodes.physical.PhysicalTableSourceScan
+import org.apache.flink.table.plan.util.{DefaultRelShuttle, RelDigestUtil}
+
+import com.google.common.collect.{Maps, Sets}
+import org.apache.calcite.rel.core.{Exchange, TableFunctionScan}
+import org.apache.calcite.rel.{RelNode, RelVisitor}
+
+import java.util
+
+import scala.collection.JavaConversions._
+
+/**
+ * An utility class for finding out duplicated sub-plans by digest and reusing them.
+ *
+ * <p>e.g.
+ * if Project1-Scan1 and Project2-Scan2 have same digest, they could be reused,
+ * and only one of duplicated sub-plan will be retained.
+ * after
+ * {{{
+ * Join Join
+ * / \ / \
+ * Filter1 Filter2 Filter1 Filter2
+ * | | => \ /
+ * Project1 Project2 Project1
+ * | | |
+ * Scan1 Scan2 Scan1
+ * }}}
+ */
+object SubplanReuser {
+
+ /**
+ * Finds duplicated sub-plans and return the reused plan.
+ */
+ def reuseDuplicatedSubplan(rels: Seq[RelNode], tableConfig: TableConfig): Seq[RelNode] = {
+ if (!tableConfig.getConf.getBoolean(
+ PlannerConfigOptions.SQL_OPTIMIZER_REUSE_SUB_PLAN_ENABLED)) {
+ return rels
+ }
+ val tableSourceReuseEnabled = tableConfig.getConf.getBoolean(
+ PlannerConfigOptions.SQL_OPTIMIZER_REUSE_TABLE_SOURCE_ENABLED)
+ val context = new SubplanReuseContext(tableSourceReuseEnabled, rels: _*)
+ val reuseShuttle = new SubplanReuseShuttle(context)
+ rels.map(_.accept(reuseShuttle))
+ }
+
+ /**
+ * The Context holds sub-plan reuse information.
+ *
+ * <p>If two sub-plan ([[RelNode]] tree with leaf node) , even belongs to different tree, have
+ * same digest, they are in a reusable sub-plan group.
+ * In a reusable sub-plan group, the leftmost sub-plan in the earlier visited tree is reused
+ * sub-plan and the remaining will reuse the leftmost one in the earlier visited tree.
+ * <p>Uses reuse id to distinguish different reusable sub-plan group,
+ * the reuse id of each sub-plan is same in a group.
+ *
+ * <p>e.g.
+ * {{{
+ * Join
+ * / \
+ * Filter1 Filter2
+ * | |
+ * Project1 Project2
+ * | |
+ * Scan1 Scan2
+ * }}}
+ * Project1-Scan1 and Project2-Scan2 have same digest, so they are in a reusable sub-plan group.
+ */
+ class SubplanReuseContext(tableSourceReuseEnabled: Boolean, roots: RelNode*) {
+ // mapping a relNode to its digest
+ private val mapRelToDigest = Maps.newIdentityHashMap[RelNode, String]()
+ // mapping the digest to RelNodes
+ private val mapDigestToReusableNodes = new util.HashMap[String, util.List[RelNode]]()
+
+ val visitor = new ReusableSubplanVisitor()
+ roots.map(visitor.go)
+
+ /**
+ * Return the digest of the given rel node.
+ */
+ def getRelDigest(node: RelNode): String = {
+ val digest = mapRelToDigest.get(node)
+ if (digest != null) {
+ digest
+ } else {
+ val newDigest = RelDigestUtil.getDigest(node)
+ mapRelToDigest.put(node, newDigest)
+ newDigest
+ }
+ }
+
+ /**
+ * Returns true if the given node can reuse other node, else false.
+ * The nodes with same digest are reusable,
+ * and the non-head node of node-list can reuse the head node.
+ */
+ def reuseOtherNode(node: RelNode): Boolean = {
+ val reusableNodes = getReusableNodes(node)
+ if (isReusableNodes(reusableNodes)) {
+ node ne reusableNodes.head
+ } else {
+ false
+ }
+ }
+
+ /**
+ * Returns reusable nodes which have same digest.
+ */
+ private def getReusableNodes(node: RelNode): List[RelNode] = {
+ val digest = getRelDigest(node)
+ mapDigestToReusableNodes.getOrDefault(digest, List.empty[RelNode]).toList
+ }
+
+ /**
+ * Returns true if the given nodes can be reused, else false.
+ */
+ private def isReusableNodes(reusableNodes: List[RelNode]): Boolean = {
+ if (reusableNodes.size() > 1) {
+ // Does not reuse nodes which are reusable disabled
+ !isNodeReusableDisabled(reusableNodes.head)
+ } else {
+ false
+ }
+ }
+
+ /**
+ * Returns true if the given node is reusable disabled
+ */
+ private def isNodeReusableDisabled(node: RelNode): Boolean = {
+ node match {
+ // TableSourceScan node can not be reused if reuse TableSource disabled
+ case _: FlinkLogicalTableSourceScan | _: PhysicalTableSourceScan => !tableSourceReuseEnabled
+ // Exchange node can not be reused if its input is reusable disabled
+ case e: Exchange => isNodeReusableDisabled(e.getInput)
+ // TableFunctionScan and sink can not be reused
+ case _: TableFunctionScan | _: Sink => true
+ case _ => false
+ }
+ }
+
+ class ReusableSubplanVisitor extends RelVisitor {
+ private val visitedNodes = Sets.newIdentityHashSet[RelNode]()
+
+ override def visit(node: RelNode, ordinal: Int, parent: RelNode): Unit = {
+ if (visitedNodes.contains(node)) {
+ // does not need to visit a node which is already visited.
+ return
+ }
+ visitedNodes.add(node)
+
+ // the same sub-plan should have same digest value,
+ // uses `explain` with `RelDigestWriterImpl` to get the digest of a sub-plan.
+ val digest = getRelDigest(node)
+ val nodes = mapDigestToReusableNodes.getOrElseUpdate(digest, new util.ArrayList[RelNode]())
+ nodes.add(node)
+ // the node will be reused if there are more than one nodes with same digest,
+ // so there is no need to visit a reused node's inputs.
+ if (!isReusableNodes(nodes.toList)) {
+ super.visit(node, ordinal, parent)
+ }
+ }
+ }
+
+ }
+
+ /**
+ * Rewrite reusable sub-plans with different rel objects to same rel object.
+ *
+ * <p>e.g.
+ * Scan1-Project1 and Scan2-Project2 have same digest, so they can be reused.
+ * {{{
+ * Join Join
+ * / \ / \
+ * Filter1 Filter2 Filter1 Filter2
+ * | | => \ /
+ * Project1 Project2 Project1
+ * | | |
+ * Scan1 Scan2 Scan1
+ * }}}
+ * After rewrote, Scan2-Project2 is replaced by Scan1-Project1.
+ *
+ * <p>NOTES: This is a stateful class, please use same shuttle object to reuse multiple trees.
+ */
+ class SubplanReuseShuttle(context: SubplanReuseContext) extends DefaultRelShuttle {
+ private val mapDigestToNewNode = new util.HashMap[String, RelNode]()
+
+ override def visit(rel: RelNode): RelNode = {
+ val canReuseOtherNode = context.reuseOtherNode(rel)
+ val digest = context.getRelDigest(rel)
+ if (canReuseOtherNode) {
+ val newNode = mapDigestToNewNode.get(digest)
+ if (newNode == null) {
+ throw new TableException("This should not happen")
+ }
+ newNode
+ } else {
+ val newNode = visitInputs(rel)
+ mapDigestToNewNode.put(digest, newNode)
+ newNode
+ }
+ }
+
+ /**
+ * Parent rel need not change, just replaces inputs if any inputs change.
+ */
+ private def visitInputs(rel: RelNode): RelNode = {
+ rel.getInputs.zipWithIndex.foreach {
+ case (input, index) =>
+ val newInput = input.accept(this)
+ if (input ne newInput) {
+ rel.replaceInput(index, newInput)
+ }
+ }
+ rel
+ }
+ }
+
+}
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/rules/physical/batch/BatchExecAggRuleBase.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/rules/physical/batch/BatchExecAggRuleBase.scala
index 04d3081..ee5f637 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/rules/physical/batch/BatchExecAggRuleBase.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/rules/physical/batch/BatchExecAggRuleBase.scala
@@ -25,7 +25,7 @@ import org.apache.flink.table.dataformat.BinaryRow
import org.apache.flink.table.functions.aggfunctions.DeclarativeAggregateFunction
import org.apache.flink.table.functions.utils.UserDefinedFunctionUtils._
import org.apache.flink.table.functions.{AggregateFunction, UserDefinedFunction}
-import org.apache.flink.table.plan.util.{AggregateUtil, RelFieldCollationUtil}
+import org.apache.flink.table.plan.util.{AggregateUtil, FlinkRelOptUtil}
import org.apache.calcite.rel.`type`.RelDataType
import org.apache.calcite.rel.core.Aggregate
@@ -170,7 +170,7 @@ trait BatchExecAggRuleBase {
protected def createRelCollation(groupSet: Array[Int]): RelCollation = {
val fields = new JArrayList[RelFieldCollation]()
for (field <- groupSet) {
- fields.add(RelFieldCollationUtil.of(field))
+ fields.add(FlinkRelOptUtil.ofRelFieldCollation(field))
}
RelCollations.of(fields)
}
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/rules/physical/batch/BatchExecRankRule.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/rules/physical/batch/BatchExecRankRule.scala
index 918211b..f6ef77d 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/rules/physical/batch/BatchExecRankRule.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/rules/physical/batch/BatchExecRankRule.scala
@@ -23,7 +23,7 @@ import org.apache.flink.table.plan.`trait`.FlinkRelDistribution
import org.apache.flink.table.plan.nodes.FlinkConventions
import org.apache.flink.table.plan.nodes.logical.FlinkLogicalRank
import org.apache.flink.table.plan.nodes.physical.batch.BatchExecRank
-import org.apache.flink.table.plan.util.RelFieldCollationUtil
+import org.apache.flink.table.plan.util.FlinkRelOptUtil
import org.apache.flink.table.runtime.rank.{ConstantRankRange, RankType}
import org.apache.calcite.plan.{RelOptRule, RelOptRuleCall}
@@ -64,8 +64,8 @@ class BatchExecRankRule
val cluster = rel.getCluster
val emptyTraits = cluster.getPlanner.emptyTraitSet().replace(FlinkConventions.BATCH_PHYSICAL)
- val sortFieldCollations = rank.partitionKey.asList().map(RelFieldCollationUtil.of(_)) ++
- rank.orderKey.getFieldCollations
+ val sortFieldCollations = rank.partitionKey.asList()
+ .map(FlinkRelOptUtil.ofRelFieldCollation(_)) ++ rank.orderKey.getFieldCollations
val sortCollation = RelCollations.of(sortFieldCollations: _*)
val localRequiredTraitSet = emptyTraits.replace(sortCollation)
val newLocalInput = RelOptRule.convert(rank.getInput, localRequiredTraitSet)
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/rules/physical/batch/BatchExecSortMergeJoinRule.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/rules/physical/batch/BatchExecSortMergeJoinRule.scala
index f0213cd..992a2ff 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/rules/physical/batch/BatchExecSortMergeJoinRule.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/rules/physical/batch/BatchExecSortMergeJoinRule.scala
@@ -24,7 +24,7 @@ import org.apache.flink.table.plan.`trait`.FlinkRelDistribution
import org.apache.flink.table.plan.nodes.FlinkConventions
import org.apache.flink.table.plan.nodes.logical.FlinkLogicalJoin
import org.apache.flink.table.plan.nodes.physical.batch.BatchExecSortMergeJoin
-import org.apache.flink.table.plan.util.RelFieldCollationUtil
+import org.apache.flink.table.plan.util.FlinkRelOptUtil
import org.apache.calcite.plan.RelOptRule.{any, operand}
import org.apache.calcite.plan.{RelOptRule, RelOptRuleCall, RelTraitSet}
@@ -67,7 +67,7 @@ class BatchExecSortMergeJoinRule(joinClass: Class[_ <: Join])
.replace(FlinkConventions.BATCH_PHYSICAL)
.replace(FlinkRelDistribution.hash(shuffleKeys, requireStrict))
if (requireCollation) {
- val fieldCollations = shuffleKeys.map(RelFieldCollationUtil.of(_))
+ val fieldCollations = shuffleKeys.map(FlinkRelOptUtil.ofRelFieldCollation(_))
val relCollation = RelCollations.of(fieldCollations)
traitSet = traitSet.replace(relCollation)
}
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/trait/FlinkRelDistribution.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/trait/FlinkRelDistribution.scala
index 1fc216b..b0cb941 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/trait/FlinkRelDistribution.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/trait/FlinkRelDistribution.scala
@@ -17,7 +17,7 @@
*/
package org.apache.flink.table.plan.`trait`
-import org.apache.flink.table.plan.util.{FlinkRelOptUtil, RelFieldCollationUtil}
+import org.apache.flink.table.plan.util.FlinkRelOptUtil
import com.google.common.collect.{ImmutableList, Ordering}
import org.apache.calcite.plan.{RelMultipleTrait, RelOptPlanner, RelTrait}
@@ -235,7 +235,7 @@ object FlinkRelDistribution {
def range(columns: util.Collection[_ <: Number]): FlinkRelDistribution = {
val keys = ImmutableIntList.copyOf(columns)
val collations = new util.ArrayList[RelFieldCollation]()
- columns.foreach(f => collations.add(RelFieldCollationUtil.of(f.intValue())))
+ columns.foreach(f => collations.add(FlinkRelOptUtil.ofRelFieldCollation(f.intValue())))
val fieldCollations = ImmutableList.copyOf[RelFieldCollation](collations)
canonize(new FlinkRelDistribution(
RelDistribution.Type.RANGE_DISTRIBUTED, keys, Some(fieldCollations)))
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/util/CorrelateUtil.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/util/CorrelateUtil.scala
index 52db54f..1c54f98 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/util/CorrelateUtil.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/util/CorrelateUtil.scala
@@ -112,7 +112,7 @@ object CorrelateUtil {
val reservedFieldsMapping = calcProgram.getExprList.zipWithIndex.filter {
case (_, index) => refs(index) > 0
}.zipWithIndex.map {
- case (((expr, srcIndex), newIndex)) => srcIndex -> newIndex
+ case ((expr, srcIndex), newIndex) => srcIndex -> newIndex
}.toMap
val shiftProjects = calcProgram.getProjectList.map {
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/util/ExecNodePlanDumper.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/util/ExecNodePlanDumper.scala
new file mode 100644
index 0000000..0f5ecfc
--- /dev/null
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/util/ExecNodePlanDumper.scala
@@ -0,0 +1,399 @@
+/*
+ * 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.plan.util
+
+import org.apache.flink.table.plan.`trait`.{AccModeTraitDef, UpdateAsRetractionTraitDef}
+import org.apache.flink.table.plan.nodes.calcite.Sink
+import org.apache.flink.table.plan.nodes.exec.{ExecNode, ExecNodeVisitorImpl}
+import org.apache.flink.table.plan.nodes.physical.stream.StreamPhysicalRel
+
+import com.google.common.collect.{Maps, Sets}
+import org.apache.calcite.rel.RelNode
+import org.apache.calcite.rel.externalize.RelWriterImpl
+import org.apache.calcite.sql.SqlExplainLevel
+import org.apache.calcite.util.Pair
+
+import java.io.{PrintWriter, StringWriter}
+import java.util
+import java.util.concurrent.atomic.AtomicInteger
+import java.util.{ArrayList => JArrayList, List => JList}
+
+import scala.collection.JavaConversions._
+
+/**
+ * An utility class for converting an exec node plan to a string as a tree style.
+ *
+ * The implementation is based on RelNode#explain now.
+ */
+object ExecNodePlanDumper {
+
+ /**
+ * Converts an [[ExecNode]] tree to a string as a tree style.
+ *
+ * @param node the ExecNode to convert
+ * @param detailLevel detailLevel defines detail levels for EXPLAIN PLAN.
+ * @param withExecNodeId whether including ID of ExecNode
+ * @param withRetractTraits whether including Retraction Traits of RelNode corresponding to
+ * an ExecNode (only apply to StreamPhysicalRel node at present)
+ * @param withOutputType whether including output rowType
+ * @return explain plan of ExecNode
+ */
+ def treeToString(
+ node: ExecNode[_, _],
+ detailLevel: SqlExplainLevel = SqlExplainLevel.EXPPLAN_ATTRIBUTES,
+ withExecNodeId: Boolean = false,
+ withRetractTraits: Boolean = false,
+ withOutputType: Boolean = false): String = {
+ doConvertTreeToString(
+ node,
+ detailLevel = detailLevel,
+ withExecNodeId = withExecNodeId,
+ withRetractTraits = withRetractTraits,
+ withOutputType = withOutputType)
+ }
+
+ /**
+ * Converts an [[ExecNode]] DAG to a string as a tree style.
+ *
+ * @param nodes the ExecNodes to convert
+ * @param detailLevel detailLevel defines detail levels for EXPLAIN PLAN.
+ * @param withExecNodeId whether including ID of ExecNode
+ * @param withRetractTraits whether including Retraction Traits of RelNode corresponding to
+ * an ExecNode (only apply to StreamPhysicalRel node at present)
+ * @param withOutputType whether including output rowType
+ * @return explain plan of ExecNode
+ */
+ def dagToString(
+ nodes: Seq[ExecNode[_, _]],
+ detailLevel: SqlExplainLevel = SqlExplainLevel.EXPPLAN_ATTRIBUTES,
+ withExecNodeId: Boolean = false,
+ withRetractTraits: Boolean = false,
+ withOutputType: Boolean = false): String = {
+ if (nodes.length == 1) {
+ return treeToString(
+ nodes.head,
+ detailLevel,
+ withExecNodeId = withExecNodeId,
+ withRetractTraits = withRetractTraits,
+ withOutputType = withOutputType)
+ }
+
+ val reuseInfoBuilder = new ReuseInfoBuilder()
+ nodes.foreach(reuseInfoBuilder.visit)
+ // node sets that stop explain when meet them
+ val stopExplainNodes = Sets.newIdentityHashSet[ExecNode[_, _]]()
+ // mapping node to reuse info, the map value is a tuple2,
+ // the first value of the tuple is reuse id,
+ // the second value is true if the node is first visited else false.
+ val reuseInfoMap = Maps.newIdentityHashMap[ExecNode[_, _], (Integer, Boolean)]()
+ // mapping node object to visited times
+ val mapNodeToVisitedTimes = Maps.newIdentityHashMap[ExecNode[_, _], Int]()
+ val sb = new StringBuilder()
+ val visitor = new ExecNodeVisitorImpl {
+ override def visit(node: ExecNode[_, _]): Unit = {
+ val visitedTimes = mapNodeToVisitedTimes.getOrDefault(node, 0) + 1
+ mapNodeToVisitedTimes.put(node, visitedTimes)
+ if (visitedTimes == 1) {
+ super.visit(node)
+ }
+ val reuseId = reuseInfoBuilder.getReuseId(node)
+ val isReuseNode = reuseId.isDefined
+ if (node.isInstanceOf[Sink] || (isReuseNode && !reuseInfoMap.containsKey(node))) {
+ if (isReuseNode) {
+ reuseInfoMap.put(node, (reuseId.get, true))
+ }
+ val reusePlan = doConvertTreeToString(
+ node,
+ detailLevel = detailLevel,
+ withExecNodeId = withExecNodeId,
+ withRetractTraits = withRetractTraits,
+ withOutputType = withOutputType,
+ stopExplainNodes = Some(stopExplainNodes),
+ reuseInfoMap = Some(reuseInfoMap))
+ sb.append(reusePlan).append(System.lineSeparator)
+ if (isReuseNode) {
+ // update visit info after the reuse node visited
+ stopExplainNodes.add(node)
+ reuseInfoMap.put(node, (reuseId.get, false))
+ }
+ }
+ }
+ }
+
+ nodes.foreach(visitor.visit)
+
+ if (sb.length() > 0) {
+ // delete last line separator
+ sb.deleteCharAt(sb.length - 1)
+ }
+ sb.toString()
+ }
+
+ private def doConvertTreeToString(
+ node: ExecNode[_, _],
+ detailLevel: SqlExplainLevel = SqlExplainLevel.EXPPLAN_ATTRIBUTES,
+ withExecNodeId: Boolean = false,
+ withRetractTraits: Boolean = false,
+ withOutputType: Boolean = false,
+ stopExplainNodes: Option[util.Set[ExecNode[_, _]]] = None,
+ reuseInfoMap: Option[util.IdentityHashMap[ExecNode[_, _], (Integer, Boolean)]] = None
+ ): String = {
+ // TODO refactor this part of code
+ // get ExecNode explain value by RelNode#explain now
+ val sw = new StringWriter
+ val planWriter = new NodeTreeWriterImpl(
+ node,
+ new PrintWriter(sw),
+ explainLevel = detailLevel,
+ withExecNodeId = withExecNodeId,
+ withRetractTraits = withRetractTraits,
+ withOutputType = withOutputType,
+ stopExplainNodes = stopExplainNodes,
+ reuseInfoMap = reuseInfoMap)
+ node.asInstanceOf[RelNode].explain(planWriter)
+ sw.toString
+ }
+}
+
+/**
+ * build reuse id in an ExecNode DAG.
+ */
+class ReuseInfoBuilder extends ExecNodeVisitorImpl {
+ // visited node set
+ private val visitedNodes = Sets.newIdentityHashSet[ExecNode[_, _]]()
+ // mapping reuse node to its reuse id
+ private val mapReuseNodeToReuseId = Maps.newIdentityHashMap[ExecNode[_, _], Integer]()
+ private val reuseIdGenerator = new AtomicInteger(0)
+
+ override def visit(node: ExecNode[_, _]): Unit = {
+ // if a node is visited more than once, this node is a reusable node
+ if (visitedNodes.contains(node)) {
+ if (!mapReuseNodeToReuseId.containsKey(node)) {
+ val reuseId = reuseIdGenerator.incrementAndGet()
+ mapReuseNodeToReuseId.put(node, reuseId)
+ }
+ } else {
+ visitedNodes.add(node)
+ super.visit(node)
+ }
+ }
+
+ /**
+ * Returns reuse id if the given node is a reuse node (that means it has multiple outputs),
+ * else None.
+ */
+ def getReuseId(node: ExecNode[_, _]): Option[Integer] = {
+ if (mapReuseNodeToReuseId.containsKey(node)) {
+ Some(mapReuseNodeToReuseId.get(node))
+ } else {
+ None
+ }
+ }
+}
+
+/**
+ * Convert node tree to string as a tree style.
+ */
+class NodeTreeWriterImpl(
+ node: ExecNode[_, _],
+ pw: PrintWriter,
+ explainLevel: SqlExplainLevel = SqlExplainLevel.EXPPLAN_ATTRIBUTES,
+ withExecNodeId: Boolean = false,
+ withRetractTraits: Boolean = false,
+ withOutputType: Boolean = false,
+ stopExplainNodes: Option[util.Set[ExecNode[_, _]]] = None,
+ reuseInfoMap: Option[util.IdentityHashMap[ExecNode[_, _], (Integer, Boolean)]] = None)
+ extends RelWriterImpl(pw, explainLevel, false) {
+
+ require((stopExplainNodes.isEmpty && reuseInfoMap.isEmpty) ||
+ (stopExplainNodes.isDefined && reuseInfoMap.isDefined))
+
+ // use reuse info based on `reuseInfoMap` if it's not None,
+ // else rebuild it using `ReuseInfoBuilder`
+ class ReuseInfo {
+ // mapping node object to visited times
+ var mapNodeToVisitedTimes: util.Map[ExecNode[_, _], Int] = _
+ var reuseInfoBuilder: ReuseInfoBuilder = _
+
+ if (reuseInfoMap.isEmpty) {
+ reuseInfoBuilder = new ReuseInfoBuilder()
+ reuseInfoBuilder.visit(node)
+ mapNodeToVisitedTimes = Maps.newIdentityHashMap[ExecNode[_, _], Int]()
+ }
+
+ /**
+ * Returns reuse id if the given node is a reuse node, else None.
+ */
+ def getReuseId(node: ExecNode[_, _]): Option[Integer] = {
+ reuseInfoMap match {
+ case Some(map) => if (map.containsKey(node)) Some(map.get(node)._1) else None
+ case _ => reuseInfoBuilder.getReuseId(node)
+ }
+ }
+
+ /**
+ * Returns true if the given node is first visited, else false.
+ */
+ def isFirstVisited(node: ExecNode[_, _]): Boolean = {
+ reuseInfoMap match {
+ case Some(map) => if (map.containsKey(node)) map.get(node)._2 else true
+ case _ => mapNodeToVisitedTimes.get(node) == 1
+ }
+ }
+
+ /**
+ * Updates visited times for given node if `reuseInfoMap` is None.
+ */
+ def addVisitedTimes(node: ExecNode[_, _]): Unit = {
+ reuseInfoMap match {
+ case Some(_) => // do nothing
+ case _ =>
+ val visitedTimes = mapNodeToVisitedTimes.getOrDefault(node, 0) + 1
+ mapNodeToVisitedTimes.put(node, visitedTimes)
+ }
+ }
+ }
+
+ val reuseInfo = new ReuseInfo
+
+ var lastChildren: Seq[Boolean] = Nil
+
+ var depth = 0
+
+ override def explain_(rel: RelNode, values: JList[Pair[String, AnyRef]]): Unit = {
+ val node = rel.asInstanceOf[ExecNode[_, _]]
+ reuseInfo.addVisitedTimes(node)
+ val inputs = rel.getInputs
+ // whether explain input nodes of current node
+ val explainInputs = needExplainInputs(node)
+ val mq = rel.getCluster.getMetadataQuery
+ if (explainInputs && !mq.isVisibleInExplain(rel, explainLevel)) {
+ // render children in place of this, at same level
+ inputs.toSeq.foreach(_.explain(this))
+ return
+ }
+
+ val s = new StringBuilder
+ if (depth > 0) {
+ lastChildren.init.foreach { isLast =>
+ s.append(if (isLast) " " else ": ")
+ }
+ s.append(if (lastChildren.last) "+- " else ":- ")
+ }
+
+ val reuseId = reuseInfo.getReuseId(node)
+ val isReuseNode = reuseId.isDefined
+ val isFirstVisited = reuseInfo.isFirstVisited(node)
+ // whether output detail
+ val printDetail = !isReuseNode || isFirstVisited
+
+ if (isReuseNode && !isFirstVisited) {
+ s.append("Reused")
+ } else {
+ rel.getRelTypeName match {
+ case name if name.startsWith("BatchExec") => s.append(name.substring(9))
+ case name if name.startsWith("StreamExec") => s.append(name.substring(10))
+ case name => s.append(name)
+ }
+ }
+
+ val printValues = new JArrayList[Pair[String, AnyRef]]()
+ if (printDetail) {
+ if (explainLevel != SqlExplainLevel.NO_ATTRIBUTES) {
+ printValues.addAll(values)
+ }
+
+ if (withExecNodeId) {
+ // use RelNode's id now
+ printValues.add(Pair.of("__id__", rel.getId.toString))
+ }
+
+ if (withRetractTraits) {
+ rel match {
+ case streamRel: StreamPhysicalRel =>
+ val traitSet = streamRel.getTraitSet
+ printValues.add(
+ Pair.of("updateAsRetraction",
+ traitSet.getTrait(UpdateAsRetractionTraitDef.INSTANCE)))
+ printValues.add(
+ Pair.of("accMode", traitSet.getTrait(AccModeTraitDef.INSTANCE)))
+ case _ => // ignore
+ }
+ }
+ }
+
+ if (isReuseNode) {
+ if (isFirstVisited) {
+ printValues.add(Pair.of("reuse_id", reuseId.get))
+ } else {
+ printValues.add(Pair.of("reference_id", reuseId.get))
+ }
+ }
+
+ if (!printValues.isEmpty) {
+ var j = 0
+ printValues.toSeq.foreach {
+ case value if value.right.isInstanceOf[RelNode] => // do nothing
+ case value =>
+ if (j == 0) s.append("(") else s.append(", ")
+ j = j + 1
+ s.append(value.left).append("=[").append(value.right).append("]")
+ }
+ if (j > 0) s.append(")")
+ }
+
+ if (withOutputType) {
+ s.append(", rowType=[").append(rel.getRowType.toString).append("]")
+ }
+
+ if (explainLevel == SqlExplainLevel.ALL_ATTRIBUTES && printDetail) {
+ s.append(": rowcount = ")
+ .append(mq.getRowCount(rel))
+ .append(", cumulative cost = ")
+ .append(mq.getCumulativeCost(rel))
+ }
+ pw.println(s)
+ if (explainInputs && inputs.length > 1 && printDetail) {
+ inputs.toSeq.init.foreach { rel =>
+ depth = depth + 1
+ lastChildren = lastChildren :+ false
+ rel.explain(this)
+ depth = depth - 1
+ lastChildren = lastChildren.init
+ }
+ }
+ if (explainInputs && !inputs.isEmpty && printDetail) {
+ depth = depth + 1
+ lastChildren = lastChildren :+ true
+ inputs.toSeq.last.explain(this)
+ depth = depth - 1
+ lastChildren = lastChildren.init
+ }
+ }
+
+ /**
+ * Returns true if `stopExplainNodes` is not None and contains the given node, else false.
+ */
+ private def needExplainInputs(node: ExecNode[_, _]): Boolean = {
+ stopExplainNodes match {
+ case Some(nodes) => !nodes.contains(node)
+ case _ => true
+ }
+ }
+
+}
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/util/FlinkRelOptUtil.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/util/FlinkRelOptUtil.scala
index fc6483f..4ba0dc7 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/util/FlinkRelOptUtil.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/util/FlinkRelOptUtil.scala
@@ -17,8 +17,12 @@
*/
package org.apache.flink.table.plan.util
+import org.apache.flink.table.calcite.FlinkPlannerImpl
+
+import org.apache.calcite.config.NullCollation
import org.apache.calcite.plan.RelOptUtil
-import org.apache.calcite.rel.RelNode
+import org.apache.calcite.rel.RelFieldCollation.{Direction, NullDirection}
+import org.apache.calcite.rel.{RelFieldCollation, RelNode}
import org.apache.calcite.sql.SqlExplainLevel
import java.io.{PrintWriter, StringWriter}
@@ -60,4 +64,56 @@ object FlinkRelOptUtil {
sw.toString
}
+ /**
+ * Returns the null direction if not specified.
+ *
+ * @param direction Direction that a field is ordered in.
+ * @return default null direction
+ */
+ def defaultNullDirection(direction: Direction): NullDirection = {
+ FlinkPlannerImpl.defaultNullCollation match {
+ case NullCollation.FIRST => NullDirection.FIRST
+ case NullCollation.LAST => NullDirection.LAST
+ case NullCollation.LOW =>
+ direction match {
+ case Direction.ASCENDING | Direction.STRICTLY_ASCENDING => NullDirection.FIRST
+ case Direction.DESCENDING | Direction.STRICTLY_DESCENDING => NullDirection.LAST
+ case _ => NullDirection.UNSPECIFIED
+ }
+ case NullCollation.HIGH =>
+ direction match {
+ case Direction.ASCENDING | Direction.STRICTLY_ASCENDING => NullDirection.LAST
+ case Direction.DESCENDING | Direction.STRICTLY_DESCENDING => NullDirection.FIRST
+ case _ => NullDirection.UNSPECIFIED
+ }
+ }
+ }
+
+ /**
+ * Creates a field collation with default direction.
+ *
+ * @param fieldIndex 0-based index of field being sorted
+ * @return the field collation with default direction and given field index.
+ */
+ def ofRelFieldCollation(fieldIndex: Int): RelFieldCollation = {
+ new RelFieldCollation(
+ fieldIndex,
+ FlinkPlannerImpl.defaultCollationDirection,
+ defaultNullDirection(FlinkPlannerImpl.defaultCollationDirection))
+ }
+
+ /**
+ * Creates a field collation.
+ *
+ * @param fieldIndex 0-based index of field being sorted
+ * @param direction Direction of sorting
+ * @param nullDirection Direction of sorting of nulls
+ * @return the field collation.
+ */
+ def ofRelFieldCollation(
+ fieldIndex: Int,
+ direction: RelFieldCollation.Direction,
+ nullDirection: RelFieldCollation.NullDirection): RelFieldCollation = {
+ new RelFieldCollation(fieldIndex, direction, nullDirection)
+ }
}
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/util/OverAggregateUtil.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/util/OverAggregateUtil.scala
index 553c79f..4017b52 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/util/OverAggregateUtil.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/util/OverAggregateUtil.scala
@@ -89,7 +89,7 @@ object OverAggregateUtil {
}
val fields = new JArrayList[RelFieldCollation]()
for (field <- groupCollation ++ orderCollation) {
- fields.add(RelFieldCollationUtil.of(field._1, field._2, field._3))
+ fields.add(FlinkRelOptUtil.ofRelFieldCollation(field._1, field._2, field._3))
}
RelCollations.of(fields)
} else {
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/util/RelDigestUtil.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/util/RelDigestUtil.scala
new file mode 100644
index 0000000..d410bff
--- /dev/null
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/util/RelDigestUtil.scala
@@ -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.plan.util
+
+import org.apache.calcite.rel.RelNode
+import org.apache.calcite.rel.externalize.RelWriterImpl
+import org.apache.calcite.sql.SqlExplainLevel
+import org.apache.calcite.util.Pair
+
+import java.io.{PrintWriter, StringWriter}
+import java.util
+
+import scala.collection.JavaConversions._
+
+/**
+ * Row type is part of the digest for the rare occasion that similar
+ * expressions have different types, e.g.
+ * "WITH
+ * t1 AS (SELECT CAST(a as BIGINT) AS a, SUM(b) AS b FROM x GROUP BY CAST(a as BIGINT)),
+ * t2 AS (SELECT CAST(a as DOUBLE) AS a, SUM(b) AS b FROM x GROUP BY CAST(a as DOUBLE))
+ * SELECT t1.*, t2.* FROM t1, t2 WHERE t1.b = t2.b"
+ *
+ * the physical plan is:
+ * {{{
+ * HashJoin(where=[=(b, b0)], join=[a, b, a0, b0], joinType=[InnerJoin],
+ * isBroadcast=[true], build=[right])
+ * :- HashAggregate(groupBy=[a], select=[a, Final_SUM(sum$0) AS b])
+ * : +- Exchange(distribution=[hash[a]])
+ * : +- LocalHashAggregate(groupBy=[a], select=[a, Partial_SUM(b) AS sum$0])
+ * : +- Calc(select=[CAST(a) AS a, b])
+ * : +- ScanTable(table=[[builtin, default, x]], fields=[a, b, c])
+ * +- Exchange(distribution=[broadcast])
+ * +- HashAggregate(groupBy=[a], select=[a, Final_SUM(sum$0) AS b])
+ * +- Exchange(distribution=[hash[a]])
+ * +- LocalHashAggregate(groupBy=[a], select=[a, Partial_SUM(b) AS sum$0])
+ * +- Calc(select=[CAST(a) AS a, b])
+ * +- ScanTable(table=[[builtin, default, x]], fields=[a, b, c])
+ * }}}
+ *
+ * The sub-plan of `HashAggregate(groupBy=[a], select=[a, Final_SUM(sum$0) AS b])`
+ * are different because `CAST(a) AS a` has different types, where one is BIGINT type
+ * and another is DOUBLE type.
+ *
+ * If use the result of `RelOptUtil.toString(aggregate, SqlExplainLevel.DIGEST_ATTRIBUTES)`
+ * on `HashAggregate(groupBy=[a], select=[a, Final_SUM(sum$0) AS b])` as digest,
+ * we will get incorrect result. So rewrite `explain_` method of `RelWriterImpl` to
+ * add row-type to digest value.
+ */
+class RelDigestWriterImpl(sw: StringWriter)
+ extends RelWriterImpl(new PrintWriter(sw), SqlExplainLevel.DIGEST_ATTRIBUTES, false) {
+
+ override def explain_(rel: RelNode, values: util.List[Pair[String, AnyRef]]): Unit = {
+ val inputs = rel.getInputs
+ val mq = rel.getCluster.getMetadataQuery
+ if (!mq.isVisibleInExplain(rel, getDetailLevel)) {
+ // render children in place of this, at same level
+ inputs.foreach(_.explain(this))
+ return
+ }
+ val s = explainRel(rel, values)
+ pw.println(s)
+ inputs.foreach(_.explain(this))
+ }
+
+ /**
+ * Returns explain result for given rel.
+ */
+ protected def explainRel(rel: RelNode, values: util.List[Pair[String, AnyRef]]): String = {
+ val s = new StringBuilder
+ s.append(rel.getRelTypeName)
+ var j = 0
+ s.append("(")
+ values.foreach {
+ case value if value.right.isInstanceOf[RelNode] => // do nothing
+ case value =>
+ if (j != 0) s.append(", ")
+ j += 1
+ s.append(value.left).append("=[").append(value.right).append("]")
+ }
+ if (j > 0) {
+ s.append(",")
+ }
+ s.append("rowType=[").append(rel.getRowType.toString).append("]")
+ s.append(")")
+ s.toString()
+ }
+
+}
+
+object RelDigestUtil {
+
+ /**
+ * Gets the digest for a rel tree.
+ *
+ * @param rel rel node tree
+ * @return The digest of given rel tree.
+ */
+ def getDigest(rel: RelNode): String = {
+ val sw = new StringWriter
+ rel.explain(new RelDigestWriterImpl(sw))
+ sw.toString
+ }
+
+}
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/util/RelFieldCollationUtil.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/util/RelFieldCollationUtil.scala
deleted file mode 100644
index 19c6827..0000000
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/util/RelFieldCollationUtil.scala
+++ /dev/null
@@ -1,83 +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.plan.util
-
-import org.apache.flink.table.calcite.FlinkPlannerImpl
-
-import org.apache.calcite.config.NullCollation
-import org.apache.calcite.rel.RelFieldCollation
-import org.apache.calcite.rel.RelFieldCollation.{Direction, NullDirection}
-
-/**
- * Utility to create [[RelFieldCollation]] instance.
- */
-object RelFieldCollationUtil {
-
- /**
- * Returns the null direction if not specified.
- *
- * @param direction Direction that a field is ordered in.
- * @return default null direction
- */
- def defaultNullDirection(direction: Direction): NullDirection = {
- FlinkPlannerImpl.defaultNullCollation match {
- case NullCollation.FIRST => NullDirection.FIRST
- case NullCollation.LAST => NullDirection.LAST
- case NullCollation.LOW =>
- direction match {
- case Direction.ASCENDING | Direction.STRICTLY_ASCENDING => NullDirection.FIRST
- case Direction.DESCENDING | Direction.STRICTLY_DESCENDING => NullDirection.LAST
- case _ => NullDirection.UNSPECIFIED
- }
- case NullCollation.HIGH =>
- direction match {
- case Direction.ASCENDING | Direction.STRICTLY_ASCENDING => NullDirection.LAST
- case Direction.DESCENDING | Direction.STRICTLY_DESCENDING => NullDirection.FIRST
- case _ => NullDirection.UNSPECIFIED
- }
- }
- }
-
- /**
- * Creates a field collation with default direction.
- *
- * @param fieldIndex 0-based index of field being sorted
- * @return the field collation with default direction and given field index.
- */
- def of(fieldIndex: Int): RelFieldCollation = {
- new RelFieldCollation(
- fieldIndex,
- FlinkPlannerImpl.defaultCollationDirection,
- defaultNullDirection(FlinkPlannerImpl.defaultCollationDirection))
- }
-
- /**
- * Creates a field collation.
- *
- * @param fieldIndex 0-based index of field being sorted
- * @param direction Direction of sorting
- * @param nullDirection Direction of sorting of nulls
- * @return the field collation.
- */
- def of(
- fieldIndex: Int,
- direction: RelFieldCollation.Direction,
- nullDirection: RelFieldCollation.NullDirection): RelFieldCollation = {
- new RelFieldCollation(fieldIndex, direction, nullDirection)
- }
-}
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/util/RelShuttles.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/util/RelShuttles.scala
new file mode 100644
index 0000000..e7aaae1
--- /dev/null
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/util/RelShuttles.scala
@@ -0,0 +1,148 @@
+/*
+ * 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.plan.util
+
+import org.apache.flink.table.plan.schema.RelTable
+
+import com.google.common.collect.Sets
+import org.apache.calcite.plan.RelOptUtil
+import org.apache.calcite.rel.core.{TableFunctionScan, TableScan}
+import org.apache.calcite.rel.logical._
+import org.apache.calcite.rel.{RelNode, RelShuttle, RelShuttleImpl}
+
+import scala.collection.JavaConversions._
+
+class DefaultRelShuttle extends RelShuttle {
+
+ override def visit(rel: RelNode): RelNode = {
+ var change = false
+ val newInputs = rel.getInputs.map {
+ input =>
+ val newInput = input.accept(this)
+ change = change || (input ne newInput)
+ newInput
+ }
+ if (change) {
+ rel.copy(rel.getTraitSet, newInputs)
+ } else {
+ rel
+ }
+ }
+
+ override def visit(intersect: LogicalIntersect): RelNode = visit(intersect.asInstanceOf[RelNode])
+
+ override def visit(union: LogicalUnion): RelNode = visit(union.asInstanceOf[RelNode])
+
+ override def visit(aggregate: LogicalAggregate): RelNode = visit(aggregate.asInstanceOf[RelNode])
+
+ override def visit(minus: LogicalMinus): RelNode = visit(minus.asInstanceOf[RelNode])
+
+ override def visit(sort: LogicalSort): RelNode = visit(sort.asInstanceOf[RelNode])
+
+ override def visit(`match`: LogicalMatch): RelNode = visit(`match`.asInstanceOf[RelNode])
+
+ override def visit(exchange: LogicalExchange): RelNode = visit(exchange.asInstanceOf[RelNode])
+
+ override def visit(scan: TableScan): RelNode = visit(scan.asInstanceOf[RelNode])
+
+ override def visit(scan: TableFunctionScan): RelNode = visit(scan.asInstanceOf[RelNode])
+
+ override def visit(values: LogicalValues): RelNode = visit(values.asInstanceOf[RelNode])
+
+ override def visit(filter: LogicalFilter): RelNode = visit(filter.asInstanceOf[RelNode])
+
+ override def visit(project: LogicalProject): RelNode = visit(project.asInstanceOf[RelNode])
+
+ override def visit(join: LogicalJoin): RelNode = visit(join.asInstanceOf[RelNode])
+
+ override def visit(correlate: LogicalCorrelate): RelNode = visit(correlate.asInstanceOf[RelNode])
+}
+
+/**
+ * Convert logical table scan to a relational expression.
+ */
+class ExpandTableScanShuttle extends RelShuttleImpl {
+
+ /**
+ * Override this method to use `replaceInput` method instead of `copy` method
+ * if any children change. This will not change any output of LogicalTableScan
+ * when LogicalTableScan is replaced with RelNode tree in its RelTable.
+ */
+ override def visitChild(parent: RelNode, i: Int, child: RelNode): RelNode = {
+ stack.push(parent)
+ try {
+ val child2 = child.accept(this)
+ if (child2 ne child) {
+ parent.replaceInput(i, child2)
+ }
+ parent
+ } finally {
+ stack.pop
+ }
+ }
+
+ /**
+ * Converts [[LogicalTableScan]] the result [[RelNode]] tree by calling [[RelTable]]#toRel
+ */
+ override def visit(scan: TableScan): RelNode = {
+ scan match {
+ case tableScan: LogicalTableScan =>
+ val relTable = tableScan.getTable.unwrap(classOf[RelTable])
+ if (relTable != null) {
+ val rel = relTable.toRel(RelOptUtil.getContext(tableScan.getCluster), tableScan.getTable)
+ rel.accept(this)
+ } else {
+ tableScan
+ }
+ case otherScan => otherScan
+ }
+ }
+}
+
+/**
+ * Rewrite same rel object to different rel objects.
+ *
+ * <p>e.g.
+ * {{{
+ * Join Join
+ * / \ / \
+ * Filter1 Filter2 => Filter1 Filter2
+ * \ / | |
+ * Scan Scan1 Scan2
+ * }}}
+ * After rewrote, Scan1 and Scan2 are different object but have same digest.
+ */
+class SameRelObjectShuttle extends DefaultRelShuttle {
+ private val visitedNodes = Sets.newIdentityHashSet[RelNode]()
+
+ override def visit(node: RelNode): RelNode = {
+ val visited = !visitedNodes.add(node)
+ var change = false
+ val newInputs = node.getInputs.map {
+ input =>
+ val newInput = input.accept(this)
+ change = change || (input ne newInput)
+ newInput
+ }
+ if (change || visited) {
+ node.copy(node.getTraitSet, newInputs)
+ } else {
+ node
+ }
+ }
+}
diff --git a/flink-table/flink-table-planner-blink/src/test/java/org/apache/flink/table/runtime/utils/JavaUserDefinedScalarFunctions.java b/flink-table/flink-table-planner-blink/src/test/java/org/apache/flink/table/runtime/utils/JavaUserDefinedScalarFunctions.java
index 2e11f4f..3d0a892 100644
--- a/flink-table/flink-table-planner-blink/src/test/java/org/apache/flink/table/runtime/utils/JavaUserDefinedScalarFunctions.java
+++ b/flink-table/flink-table-planner-blink/src/test/java/org/apache/flink/table/runtime/utils/JavaUserDefinedScalarFunctions.java
@@ -24,6 +24,7 @@ import org.apache.flink.table.functions.FunctionContext;
import org.apache.flink.table.functions.ScalarFunction;
import java.util.Arrays;
+import java.util.Random;
/**
* Test scalar functions.
@@ -133,4 +134,24 @@ public class JavaUserDefinedScalarFunctions {
}
}
+ /**
+ * Non-deterministic scalar function.
+ */
+ public static class NonDeterministicUdf extends ScalarFunction {
+ Random random = new Random();
+
+ public int eval() {
+ return random.nextInt();
+ }
+
+ public int eval(int v) {
+ return v + random.nextInt();
+ }
+
+ @Override
+ public boolean isDeterministic() {
+ return false;
+ }
+ }
+
}
diff --git a/flink-table/flink-table-planner-blink/src/test/java/org/apache/flink/table/runtime/utils/JavaUserDefinedTableFunctions.java b/flink-table/flink-table-planner-blink/src/test/java/org/apache/flink/table/runtime/utils/JavaUserDefinedTableFunctions.java
index c99d848..9e0c388 100644
--- a/flink-table/flink-table-planner-blink/src/test/java/org/apache/flink/table/runtime/utils/JavaUserDefinedTableFunctions.java
+++ b/flink-table/flink-table-planner-blink/src/test/java/org/apache/flink/table/runtime/utils/JavaUserDefinedTableFunctions.java
@@ -18,8 +18,14 @@
package org.apache.flink.table.runtime.utils;
+import org.apache.flink.api.common.typeinfo.TypeInformation;
+import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.table.functions.TableFunction;
+import org.apache.commons.lang3.StringUtils;
+
+import java.util.Random;
+
/**
* Test functions.
*/
@@ -67,4 +73,70 @@ public class JavaUserDefinedTableFunctions {
collect(sum);
}
}
+
+ /**
+ * String split table function.
+ */
+ public static class StringSplit extends TableFunction<String> {
+
+ public void eval() {
+ String[] strs = { "a", "b", "c" };
+ for (String str : strs) {
+ eval(str);
+ }
+ }
+
+ public void eval(String str) {
+ this.eval(str, ",");
+ }
+
+ public void eval(String str, String separatorChars) {
+ this.eval(str, separatorChars, 0);
+ }
+
+ public void eval(String str, String separatorChars, int startIndex) {
+ if (str != null) {
+ String[] strs = StringUtils.split(str, separatorChars);
+ if (startIndex < 0) {
+ startIndex = 0;
+ }
+ for (int i = startIndex; i < strs.length; ++i) {
+ collect(strs[i]);
+ }
+ }
+ }
+
+ public void eval(byte[] varbinary) {
+ if (varbinary != null) {
+ this.eval(new String(varbinary));
+ }
+ }
+
+ @Override
+ public TypeInformation<String> getResultType() {
+ return Types.STRING;
+ }
+ }
+
+ /**
+ * Non-deterministic table function.
+ */
+ public static class NonDeterministicTableFunc extends TableFunction<String> {
+
+ Random random = new Random();
+
+ public void eval(String str) {
+ String[] values = str.split("#");
+ int endIndex = random.nextInt(values.length);
+ for (int i = 0; i < endIndex; ++i) {
+ collect(values[i]);
+ }
+ }
+
+ @Override
+ public boolean isDeterministic() {
+ return false;
+ }
+ }
+
}
diff --git a/flink-table/flink-table-planner-blink/src/test/resources/digest/testGetDigestWithDynamicFunction.out b/flink-table/flink-table-planner-blink/src/test/resources/digest/testGetDigestWithDynamicFunction.out
new file mode 100644
index 0000000..9cbec5d
--- /dev/null
+++ b/flink-table/flink-table-planner-blink/src/test/resources/digest/testGetDigestWithDynamicFunction.out
@@ -0,0 +1,31 @@
+/*
+ * 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.
+ */
+LogicalIntersect(all=[false],rowType=[RecordType(INTEGER random)])
+LogicalIntersect(all=[false],rowType=[RecordType(INTEGER random)])
+LogicalProject(random=[$0],rowType=[RecordType(INTEGER random)])
+LogicalSort(sort0=[$1], dir0=[ASC-nulls-first], fetch=[1],rowType=[RecordType(INTEGER random, DOUBLE EXPR$1)])
+LogicalProject(random=[$1], EXPR$1=[RAND()],rowType=[RecordType(INTEGER random, DOUBLE EXPR$1)])
+LogicalTableScan(table=[[MyTable]],rowType=[RecordType(VARCHAR(65536) first, INTEGER id, DOUBLE score, VARCHAR(65536) last)])
+LogicalProject(random=[$0],rowType=[RecordType(INTEGER random)])
+LogicalSort(sort0=[$1], dir0=[ASC-nulls-first], fetch=[1],rowType=[RecordType(INTEGER random, DOUBLE EXPR$1)])
+LogicalProject(random=[$1], EXPR$1=[RAND()],rowType=[RecordType(INTEGER random, DOUBLE EXPR$1)])
+LogicalTableScan(table=[[MyTable]],rowType=[RecordType(VARCHAR(65536) first, INTEGER id, DOUBLE score, VARCHAR(65536) last)])
+LogicalProject(random=[$0],rowType=[RecordType(INTEGER random)])
+LogicalSort(sort0=[$1], dir0=[ASC-nulls-first], fetch=[1],rowType=[RecordType(INTEGER random, DOUBLE EXPR$1)])
+LogicalProject(random=[$1], EXPR$1=[RAND()],rowType=[RecordType(INTEGER random, DOUBLE EXPR$1)])
+LogicalTableScan(table=[[MyTable]],rowType=[RecordType(VARCHAR(65536) first, INTEGER id, DOUBLE score, VARCHAR(65536) last)])
diff --git a/flink-table/flink-table-planner-blink/src/test/resources/digest/testGetDigestWithDynamicFunctionView.out b/flink-table/flink-table-planner-blink/src/test/resources/digest/testGetDigestWithDynamicFunctionView.out
new file mode 100644
index 0000000..c48cf89
--- /dev/null
+++ b/flink-table/flink-table-planner-blink/src/test/resources/digest/testGetDigestWithDynamicFunctionView.out
@@ -0,0 +1,34 @@
+/*
+ * 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.
+ */
+LogicalIntersect(all=[false],rowType=[RecordType(INTEGER random)])
+LogicalIntersect(all=[false],rowType=[RecordType(INTEGER random)])
+LogicalProject(random=[$0],rowType=[RecordType(INTEGER random)])
+LogicalProject(random=[$0],rowType=[RecordType(INTEGER random)])
+LogicalSort(sort0=[$1], dir0=[ASC-nulls-first], fetch=[1],rowType=[RecordType(INTEGER random, DOUBLE EXPR$1)])
+LogicalProject(random=[$1], EXPR$1=[RAND()],rowType=[RecordType(INTEGER random, DOUBLE EXPR$1)])
+LogicalTableScan(table=[[MyTable]],rowType=[RecordType(VARCHAR(65536) first, INTEGER id, DOUBLE score, VARCHAR(65536) last)])
+LogicalProject(random=[$0],rowType=[RecordType(INTEGER random)])
+LogicalProject(random=[$0],rowType=[RecordType(INTEGER random)])
+LogicalSort(sort0=[$1], dir0=[ASC-nulls-first], fetch=[1],rowType=[RecordType(INTEGER random, DOUBLE EXPR$1)])
+LogicalProject(random=[$1], EXPR$1=[RAND()],rowType=[RecordType(INTEGER random, DOUBLE EXPR$1)])
+LogicalTableScan(table=[[MyTable]],rowType=[RecordType(VARCHAR(65536) first, INTEGER id, DOUBLE score, VARCHAR(65536) last)])
+LogicalProject(random=[$0],rowType=[RecordType(INTEGER random)])
+LogicalProject(random=[$0],rowType=[RecordType(INTEGER random)])
+LogicalSort(sort0=[$1], dir0=[ASC-nulls-first], fetch=[1],rowType=[RecordType(INTEGER random, DOUBLE EXPR$1)])
+LogicalProject(random=[$1], EXPR$1=[RAND()],rowType=[RecordType(INTEGER random, DOUBLE EXPR$1)])
+LogicalTableScan(table=[[MyTable]],rowType=[RecordType(VARCHAR(65536) first, INTEGER id, DOUBLE score, VARCHAR(65536) last)])
diff --git a/flink-table/flink-table-planner-blink/src/test/resources/org/apache/flink/table/plan/batch/sql/DeadlockBreakupTest.xml b/flink-table/flink-table-planner-blink/src/test/resources/org/apache/flink/table/plan/batch/sql/DeadlockBreakupTest.xml
new file mode 100644
index 0000000..8832f60
--- /dev/null
+++ b/flink-table/flink-table-planner-blink/src/test/resources/org/apache/flink/table/plan/batch/sql/DeadlockBreakupTest.xml
@@ -0,0 +1,317 @@
+<?xml version="1.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.
+-->
+<Root>
+ <TestCase name="testReusedNodeIsBarrierNode">
+ <Resource name="sql">
+ <![CDATA[
+WITH r AS (SELECT c, SUM(a) a, SUM(b) b FROM x GROUP BY c)
+ SELECT * FROM r r1, r r2 WHERE r1.a = r2.b AND r2.a > 1
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(c=[$0], a=[$1], b=[$2], c0=[$3], a0=[$4], b0=[$5])
++- LogicalFilter(condition=[AND(=(CAST($1):BIGINT, $5), >($4, 1))])
+ +- LogicalJoin(condition=[true], joinType=[inner])
+ :- LogicalAggregate(group=[{0}], a=[SUM($1)], b=[SUM($2)])
+ : +- LogicalProject(c=[$2], a=[$0], b=[$1])
+ : +- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+ +- LogicalAggregate(group=[{0}], a=[SUM($1)], b=[SUM($2)])
+ +- LogicalProject(c=[$2], a=[$0], b=[$1])
+ +- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+NestedLoopJoin(joinType=[InnerJoin], where=[=(CAST(a), b0)], select=[c, a, b, c0, a0, b0], build=[right])
+:- Exchange(distribution=[any], exchange_mode=[BATCH])
+: +- HashAggregate(isMerge=[true], groupBy=[c], select=[c, Final_SUM(sum$0) AS a, Final_SUM(sum$1) AS b], reuse_id=[1])
+: +- Exchange(distribution=[hash[c]])
+: +- LocalHashAggregate(groupBy=[c], select=[c, Partial_SUM(a) AS sum$0, Partial_SUM(b) AS sum$1])
+: +- TableSourceScan(table=[[x, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
++- Exchange(distribution=[broadcast])
+ +- Calc(select=[c, a, b], where=[>(a, 1)])
+ +- Reused(reference_id=[1])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSubplanReuse_SetExchangeAsBatch_SortMergeJoin">
+ <Resource name="sql">
+ <![CDATA[
+
+WITH v1 AS (SELECT a, SUM(b) AS b, MAX(c) AS c FROM x GROUP BY a),
+ v2 AS (SELECT * FROM v1 r1, v1 r2 WHERE r1.a = r2.a AND r1.b > 10),
+ v3 AS (SELECT * FROM v1 r1, v1 r2 WHERE r1.a = r2.a AND r1.b < 5)
+
+select * from v2, v3 where v2.c = v3.c
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0], b=[$1], c=[$2], a0=[$3], b0=[$4], c0=[$5], a1=[$6], b1=[$7], c1=[$8], a00=[$9], b00=[$10], c00=[$11])
++- LogicalFilter(condition=[=($2, $8)])
+ +- LogicalJoin(condition=[true], joinType=[inner])
+ :- LogicalProject(a=[$0], b=[$1], c=[$2], a0=[$3], b0=[$4], c0=[$5])
+ : +- LogicalFilter(condition=[AND(=($0, $3), >($1, 10))])
+ : +- LogicalJoin(condition=[true], joinType=[inner])
+ : :- LogicalAggregate(group=[{0}], b=[SUM($1)], c=[MAX($2)])
+ : : +- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+ : +- LogicalAggregate(group=[{0}], b=[SUM($1)], c=[MAX($2)])
+ : +- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+ +- LogicalProject(a=[$0], b=[$1], c=[$2], a0=[$3], b0=[$4], c0=[$5])
+ +- LogicalFilter(condition=[AND(=($0, $3), <($1, 5))])
+ +- LogicalJoin(condition=[true], joinType=[inner])
+ :- LogicalAggregate(group=[{0}], b=[SUM($1)], c=[MAX($2)])
+ : +- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+ +- LogicalAggregate(group=[{0}], b=[SUM($1)], c=[MAX($2)])
+ +- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+HashJoin(joinType=[InnerJoin], where=[=(c, c1)], select=[a, b, c, a0, b0, c0, a1, b1, c1, a00, b00, c00], build=[left])
+:- Exchange(distribution=[hash[c]])
+: +- HashJoin(joinType=[InnerJoin], where=[=(a, a0)], select=[a, b, c, a0, b0, c0], build=[left])
+: :- Exchange(distribution=[hash[a]])
+: : +- Calc(select=[a, b, c], where=[>(b, 10)])
+: : +- SortAggregate(isMerge=[true], groupBy=[a], select=[a, Final_SUM(sum$0) AS b, Final_MAX(max$1) AS c], reuse_id=[1])
+: : +- Sort(orderBy=[a ASC])
+: : +- Exchange(distribution=[hash[a]])
+: : +- LocalSortAggregate(groupBy=[a], select=[a, Partial_SUM(b) AS sum$0, Partial_MAX(c) AS max$1])
+: : +- Sort(orderBy=[a ASC])
+: : +- TableSourceScan(table=[[x, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
+: +- Exchange(distribution=[hash[a]], exchange_mode=[BATCH], reuse_id=[2])
+: +- Reused(reference_id=[1])
++- Exchange(distribution=[hash[c]], exchange_mode=[BATCH])
+ +- HashJoin(joinType=[InnerJoin], where=[=(a, a0)], select=[a, b, c, a0, b0, c0], build=[left])
+ :- Exchange(distribution=[hash[a]])
+ : +- Calc(select=[a, b, c], where=[<(b, 5)])
+ : +- Reused(reference_id=[1])
+ +- Reused(reference_id=[2])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSubplanReuse_AddExchangeAsBatch_BuildLeftSemiHashJoin">
+ <Resource name="sql">
+ <![CDATA[
+WITH r AS (SELECT a, b FROM x LIMIT 10)
+SELECT r1.a, r2.b FROM x r1,
+(SELECT a, b FROM r WHERE a in (select a from x where b > 5)) r2
+WHERE r1.a = r2.a and r1.b = 5
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0], b=[$4])
++- LogicalFilter(condition=[AND(=($0, $3), =($1, 5))])
+ +- LogicalJoin(condition=[true], joinType=[inner])
+ :- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+ +- LogicalProject(a=[$0], b=[$1])
+ +- LogicalFilter(condition=[IN($0, {
+LogicalProject(a=[$0])
+ LogicalFilter(condition=[>($1, 5)])
+ LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+})])
+ +- LogicalSort(fetch=[10])
+ +- LogicalProject(a=[$0], b=[$1])
+ +- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a, b])
++- HashJoin(joinType=[InnerJoin], where=[=(a, a0)], select=[a, a0, b], build=[right])
+ :- Exchange(distribution=[hash[a]], exchange_mode=[BATCH])
+ : +- Calc(select=[a], where=[=(b, 5:BIGINT)])
+ : +- TableSourceScan(table=[[x, source: [TestTableSource(a, b, c)]]], fields=[a, b, c], reuse_id=[1])
+ +- Exchange(distribution=[hash[a]])
+ +- Calc(select=[a, b])
+ +- HashJoin(joinType=[InnerJoin], where=[=(a, a0)], select=[a, b, a0], build=[left])
+ :- Exchange(distribution=[hash[a]])
+ : +- Calc(select=[a, b])
+ : +- Limit(offset=[0], fetch=[10], global=[true])
+ : +- Exchange(distribution=[single])
+ : +- Limit(offset=[0], fetch=[10], global=[false])
+ : +- Reused(reference_id=[1])
+ +- Exchange(distribution=[hash[a]])
+ +- HashAggregate(isMerge=[true], groupBy=[a], select=[a])
+ +- Exchange(distribution=[hash[a]])
+ +- LocalHashAggregate(groupBy=[a], select=[a])
+ +- Calc(select=[a], where=[>(b, 5)])
+ +- Reused(reference_id=[1])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSubplanReuse_AddExchangeAsBatch_HashJoin">
+ <Resource name="sql">
+ <![CDATA[
+WITH r AS (SELECT a FROM x LIMIT 10)
+SELECT r1.a FROM r r1, r r2 WHERE r1.a = r2.a
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0])
++- LogicalFilter(condition=[=($0, $1)])
+ +- LogicalJoin(condition=[true], joinType=[inner])
+ :- LogicalSort(fetch=[10])
+ : +- LogicalProject(a=[$0])
+ : +- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+ +- LogicalSort(fetch=[10])
+ +- LogicalProject(a=[$0])
+ +- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a])
++- HashJoin(joinType=[InnerJoin], where=[=(a, a0)], select=[a, a0], isBroadcast=[true], build=[right])
+ :- Exchange(distribution=[hash[a]], exchange_mode=[BATCH])
+ : +- Calc(select=[a], reuse_id=[1])
+ : +- Limit(offset=[0], fetch=[10], global=[true])
+ : +- Exchange(distribution=[single])
+ : +- Limit(offset=[0], fetch=[10], global=[false])
+ : +- TableSourceScan(table=[[x, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
+ +- Exchange(distribution=[broadcast])
+ +- Reused(reference_id=[1])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSubplanReuse_AddExchangeAsBatch_NestedLoopJoin">
+ <Resource name="sql">
+ <![CDATA[
+WITH r AS (SELECT a FROM x LIMIT 10)
+SELECT r1.a FROM r r1, r r2 WHERE r1.a = r2.a
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0])
++- LogicalFilter(condition=[=($0, $1)])
+ +- LogicalJoin(condition=[true], joinType=[inner])
+ :- LogicalSort(fetch=[10])
+ : +- LogicalProject(a=[$0])
+ : +- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+ +- LogicalSort(fetch=[10])
+ +- LogicalProject(a=[$0])
+ +- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a])
++- NestedLoopJoin(joinType=[InnerJoin], where=[=(a, a0)], select=[a, a0], build=[left])
+ :- Exchange(distribution=[broadcast])
+ : +- Calc(select=[a], reuse_id=[1])
+ : +- Limit(offset=[0], fetch=[10], global=[true])
+ : +- Exchange(distribution=[single])
+ : +- Limit(offset=[0], fetch=[10], global=[false])
+ : +- TableSourceScan(table=[[x, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
+ +- Exchange(distribution=[any], exchange_mode=[BATCH])
+ +- Reused(reference_id=[1])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSubplanReuse_SetExchangeAsBatch">
+ <Resource name="sql">
+ <![CDATA[
+WITH t AS (SELECT x.a AS a, x.b AS b, y.d AS d, y.e AS e FROM x, y WHERE x.a = y.d)
+SELECT t1.*, t2.* FROM t t1, t t2 WHERE t1.b = t2.e AND t1.a < 10 AND t2.a > 5
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0], b=[$1], d=[$2], e=[$3], a0=[$4], b0=[$5], d0=[$6], e0=[$7])
++- LogicalFilter(condition=[AND(=($1, $7), <($0, 10), >($4, 5))])
+ +- LogicalJoin(condition=[true], joinType=[inner])
+ :- LogicalProject(a=[$0], b=[$1], d=[$3], e=[$4])
+ : +- LogicalFilter(condition=[=($0, $3)])
+ : +- LogicalJoin(condition=[true], joinType=[inner])
+ : :- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+ : +- LogicalTableScan(table=[[y, source: [TestTableSource(d, e, f)]]])
+ +- LogicalProject(a=[$0], b=[$1], d=[$3], e=[$4])
+ +- LogicalFilter(condition=[=($0, $3)])
+ +- LogicalJoin(condition=[true], joinType=[inner])
+ :- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+ +- LogicalTableScan(table=[[y, source: [TestTableSource(d, e, f)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+HashJoin(joinType=[InnerJoin], where=[=(b, e0)], select=[a, b, d, e, a0, b0, d0, e0], build=[left])
+:- Exchange(distribution=[hash[b]])
+: +- HashJoin(joinType=[InnerJoin], where=[=(a, d)], select=[a, b, d, e], build=[left])
+: :- Exchange(distribution=[hash[a]])
+: : +- Calc(select=[a, b], where=[<(a, 10)])
+: : +- TableSourceScan(table=[[x, source: [TestTableSource(a, b, c)]]], fields=[a, b, c], reuse_id=[1])
+: +- Exchange(distribution=[hash[d]], reuse_id=[2])
+: +- Calc(select=[d, e])
+: +- TableSourceScan(table=[[y, source: [TestTableSource(d, e, f)]]], fields=[d, e, f])
++- Exchange(distribution=[hash[e]], exchange_mode=[BATCH])
+ +- HashJoin(joinType=[InnerJoin], where=[=(a, d)], select=[a, b, d, e], build=[left])
+ :- Exchange(distribution=[hash[a]])
+ : +- Calc(select=[a, b], where=[>(a, 5)])
+ : +- Reused(reference_id=[1])
+ +- Reused(reference_id=[2])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSubplanReuse_SetExchangeAsBatch_OverAgg">
+ <Resource name="sql">
+ <![CDATA[
+WITH r1 AS (SELECT SUM(a) OVER (PARTITION BY b ORDER BY b) AS a, b, c FROM x),
+ r2 AS (SELECT MAX(a) OVER (PARTITION BY b ORDER BY b
+ RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS a, b, c FROM r1),
+ r3 AS (SELECT MIN(a) OVER (PARTITION BY b ORDER BY b
+ RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS a, b, c FROM r1)
+
+SELECT * FROM r2, r3 WHERE r2.c = r3.c
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0], b=[$1], c=[$2], a0=[$3], b0=[$4], c0=[$5])
++- LogicalFilter(condition=[=($2, $5)])
+ +- LogicalJoin(condition=[true], joinType=[inner])
+ :- LogicalProject(a=[MAX(CASE(>(COUNT($0) OVER (PARTITION BY $1 ORDER BY $1 NULLS FIRST RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW), 0), $SUM0($0) OVER (PARTITION BY $1 ORDER BY $1 NULLS FIRST RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW), null:INTEGER)) OVER (PARTITION BY $1 ORDER BY $1 NULLS FIRST RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)], b=[$1], c=[$2])
+ : +- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+ +- LogicalProject(a=[MIN(CASE(>(COUNT($0) OVER (PARTITION BY $1 ORDER BY $1 NULLS FIRST RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW), 0), $SUM0($0) OVER (PARTITION BY $1 ORDER BY $1 NULLS FIRST RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW), null:INTEGER)) OVER (PARTITION BY $1 ORDER BY $1 NULLS FIRST RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)], b=[$1], c=[$2])
+ +- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+HashJoin(joinType=[InnerJoin], where=[=(c, c0)], select=[a, b, c, a0, b0, c0], build=[left])
+:- Exchange(distribution=[hash[c]])
+: +- Calc(select=[w0$o0 AS a, b, c])
+: +- OverAggregate(partitionBy=[b], orderBy=[b ASC], window#0=[MAX($2) AS w0$o0 RANG BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING], select=[b, c, $2, w0$o0])
+: +- Sort(orderBy=[b ASC], reuse_id=[1])
+: +- Exchange(distribution=[hash[b]])
+: +- Calc(select=[b, c, CASE(>(w0$o0, 0:BIGINT), w0$o1, null:INTEGER) AS $2])
+: +- OverAggregate(partitionBy=[b], orderBy=[b ASC], window#0=[COUNT(a) AS w0$o0, $SUM0(a) AS w0$o1 RANG BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW], select=[a, b, c, w0$o0, w0$o1])
+: +- Sort(orderBy=[b ASC])
+: +- Exchange(distribution=[hash[b]])
+: +- TableSourceScan(table=[[x, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
++- Exchange(distribution=[hash[c]], exchange_mode=[BATCH])
+ +- Calc(select=[w0$o0 AS a, b, c])
+ +- OverAggregate(partitionBy=[b], orderBy=[b ASC], window#0=[MIN($2) AS w0$o0 RANG BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING], select=[b, c, $2, w0$o0])
+ +- Reused(reference_id=[1])
+]]>
+ </Resource>
+ </TestCase>
+</Root>
diff --git a/flink-table/flink-table-planner-blink/src/test/resources/org/apache/flink/table/plan/batch/sql/SubplanReuseTest.xml b/flink-table/flink-table-planner-blink/src/test/resources/org/apache/flink/table/plan/batch/sql/SubplanReuseTest.xml
new file mode 100644
index 0000000..3483b52
--- /dev/null
+++ b/flink-table/flink-table-planner-blink/src/test/resources/org/apache/flink/table/plan/batch/sql/SubplanReuseTest.xml
@@ -0,0 +1,1041 @@
+<?xml version="1.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.
+-->
+<Root>
+ <TestCase name="testBreakupDeadlockOnHashJoin">
+ <Resource name="sql">
+ <![CDATA[
+WITH r AS (SELECT a FROM x LIMIT 10)
+SELECT r1.a FROM r r1, r r2 WHERE r1.a = r2.a
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0])
++- LogicalFilter(condition=[=($0, $1)])
+ +- LogicalJoin(condition=[true], joinType=[inner])
+ :- LogicalSort(fetch=[10])
+ : +- LogicalProject(a=[$0])
+ : +- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+ +- LogicalSort(fetch=[10])
+ +- LogicalProject(a=[$0])
+ +- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a])
++- HashJoin(joinType=[InnerJoin], where=[=(a, a0)], select=[a, a0], isBroadcast=[true], build=[right])
+ :- Exchange(distribution=[hash[a]], exchange_mode=[BATCH])
+ : +- Calc(select=[a], reuse_id=[1])
+ : +- Limit(offset=[0], fetch=[10], global=[true])
+ : +- Exchange(distribution=[single])
+ : +- Limit(offset=[0], fetch=[10], global=[false])
+ : +- TableSourceScan(table=[[x, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
+ +- Exchange(distribution=[broadcast])
+ +- Reused(reference_id=[1])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testBreakupDeadlockOnNestedLoopJoin">
+ <Resource name="sql">
+ <![CDATA[
+WITH r AS (SELECT a FROM x LIMIT 10)
+SELECT r1.a FROM r r1, r r2 WHERE r1.a = r2.a
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0])
++- LogicalFilter(condition=[=($0, $1)])
+ +- LogicalJoin(condition=[true], joinType=[inner])
+ :- LogicalSort(fetch=[10])
+ : +- LogicalProject(a=[$0])
+ : +- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+ +- LogicalSort(fetch=[10])
+ +- LogicalProject(a=[$0])
+ +- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a])
++- NestedLoopJoin(joinType=[InnerJoin], where=[=(a, a0)], select=[a, a0], build=[left])
+ :- Exchange(distribution=[broadcast])
+ : +- Calc(select=[a], reuse_id=[1])
+ : +- Limit(offset=[0], fetch=[10], global=[true])
+ : +- Exchange(distribution=[single])
+ : +- Limit(offset=[0], fetch=[10], global=[false])
+ : +- TableSourceScan(table=[[x, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
+ +- Exchange(distribution=[any], exchange_mode=[BATCH])
+ +- Reused(reference_id=[1])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testDisableReuseTableSource">
+ <Resource name="sql">
+ <![CDATA[
+WITH t AS (SELECT * FROM x, y WHERE x.a = y.d)
+SELECT t1.*, t2.* FROM t t1, t t2 WHERE t1.b = t2.e AND t1.a < 10 AND t2.a > 5
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0], b=[$1], c=[$2], d=[$3], e=[$4], f=[$5], a0=[$6], b0=[$7], c0=[$8], d0=[$9], e0=[$10], f0=[$11])
++- LogicalFilter(condition=[AND(=($1, $10), <($0, 10), >($6, 5))])
+ +- LogicalJoin(condition=[true], joinType=[inner])
+ :- LogicalProject(a=[$0], b=[$1], c=[$2], d=[$3], e=[$4], f=[$5])
+ : +- LogicalFilter(condition=[=($0, $3)])
+ : +- LogicalJoin(condition=[true], joinType=[inner])
+ : :- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+ : +- LogicalTableScan(table=[[y, source: [TestTableSource(d, e, f)]]])
+ +- LogicalProject(a=[$0], b=[$1], c=[$2], d=[$3], e=[$4], f=[$5])
+ +- LogicalFilter(condition=[=($0, $3)])
+ +- LogicalJoin(condition=[true], joinType=[inner])
+ :- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+ +- LogicalTableScan(table=[[y, source: [TestTableSource(d, e, f)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+HashJoin(joinType=[InnerJoin], where=[=(b, e0)], select=[a, b, c, d, e, f, a0, b0, c0, d0, e0, f0], build=[left])
+:- Exchange(distribution=[hash[b]])
+: +- HashJoin(joinType=[InnerJoin], where=[=(a, d)], select=[a, b, c, d, e, f], build=[left])
+: :- Exchange(distribution=[hash[a]])
+: : +- Calc(select=[a, b, c], where=[<(a, 10)])
+: : +- TableSourceScan(table=[[x, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
+: +- Exchange(distribution=[hash[d]])
+: +- TableSourceScan(table=[[y, source: [TestTableSource(d, e, f)]]], fields=[d, e, f])
++- Exchange(distribution=[hash[e]])
+ +- HashJoin(joinType=[InnerJoin], where=[=(a, d)], select=[a, b, c, d, e, f], build=[left])
+ :- Exchange(distribution=[hash[a]])
+ : +- Calc(select=[a, b, c], where=[>(a, 5)])
+ : +- TableSourceScan(table=[[x, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
+ +- Exchange(distribution=[hash[d]])
+ +- TableSourceScan(table=[[y, source: [TestTableSource(d, e, f)]]], fields=[d, e, f])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testEnableReuseTableSource">
+ <Resource name="sql">
+ <![CDATA[
+WITH t AS (SELECT x.a AS a, x.b AS b, y.d AS d, y.e AS e FROM x, y WHERE x.a = y.d)
+SELECT t1.*, t2.* FROM t t1, t t2 WHERE t1.b = t2.e AND t1.a < 10 AND t2.a > 5
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0], b=[$1], d=[$2], e=[$3], a0=[$4], b0=[$5], d0=[$6], e0=[$7])
++- LogicalFilter(condition=[AND(=($1, $7), <($0, 10), >($4, 5))])
+ +- LogicalJoin(condition=[true], joinType=[inner])
+ :- LogicalProject(a=[$0], b=[$1], d=[$3], e=[$4])
+ : +- LogicalFilter(condition=[=($0, $3)])
+ : +- LogicalJoin(condition=[true], joinType=[inner])
+ : :- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+ : +- LogicalTableScan(table=[[y, source: [TestTableSource(d, e, f)]]])
+ +- LogicalProject(a=[$0], b=[$1], d=[$3], e=[$4])
+ +- LogicalFilter(condition=[=($0, $3)])
+ +- LogicalJoin(condition=[true], joinType=[inner])
+ :- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+ +- LogicalTableScan(table=[[y, source: [TestTableSource(d, e, f)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+HashJoin(joinType=[InnerJoin], where=[=(b, e0)], select=[a, b, d, e, a0, b0, d0, e0], build=[left])
+:- Exchange(distribution=[hash[b]])
+: +- HashJoin(joinType=[InnerJoin], where=[=(a, d)], select=[a, b, d, e], build=[left])
+: :- Exchange(distribution=[hash[a]])
+: : +- Calc(select=[a, b], where=[<(a, 10)])
+: : +- TableSourceScan(table=[[x, source: [TestTableSource(a, b, c)]]], fields=[a, b, c], reuse_id=[1])
+: +- Exchange(distribution=[hash[d]], reuse_id=[2])
+: +- Calc(select=[d, e])
+: +- TableSourceScan(table=[[y, source: [TestTableSource(d, e, f)]]], fields=[d, e, f])
++- Exchange(distribution=[hash[e]], exchange_mode=[BATCH])
+ +- HashJoin(joinType=[InnerJoin], where=[=(a, d)], select=[a, b, d, e], build=[left])
+ :- Exchange(distribution=[hash[a]])
+ : +- Calc(select=[a, b], where=[>(a, 5)])
+ : +- Reused(reference_id=[1])
+ +- Reused(reference_id=[2])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testNestedSubplanReuse">
+ <Resource name="sql">
+ <![CDATA[
+WITH v1 AS (
+ SELECT
+ SUM(b) sum_b,
+ AVG(SUM(b)) OVER (PARTITION BY c, e) avg_b,
+ RANK() OVER (PARTITION BY c, e ORDER BY c, e) rn,
+ c, e
+ FROM x, y
+ WHERE x.a = y.d AND c IS NOT NULl AND e > 10
+ GROUP BY c, e
+),
+ v2 AS (
+ SELECT
+ v11.c,
+ v11.e,
+ v11.avg_b,
+ v11.sum_b,
+ v12.sum_b psum,
+ v13.sum_b nsum,
+ v12.avg_b avg_b2
+ FROM v1 v11, v1 v12, v1 v13
+ WHERE v11.c = v12.c AND v11.c = v13.c AND
+ v11.e = v12.e AND v11.e = v13.e AND
+ v11.rn = v12.rn + 1 AND
+ v11.rn = v13.rn - 1
+)
+SELECT * from v2 WHERE c <> '' AND sum_b - avg_b > 3
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(c=[$0], e=[$1], avg_b=[$2], sum_b=[$3], psum=[$4], nsum=[$5], avg_b2=[$6])
++- LogicalFilter(condition=[AND(<>($0, _UTF-16LE''), >(-($3, $2), 3))])
+ +- LogicalProject(c=[$3], e=[$4], avg_b=[$1], sum_b=[$0], psum=[$5], nsum=[$10], avg_b2=[$6])
+ +- LogicalFilter(condition=[AND(=($3, $8), =($3, $13), =($4, $9), =($4, $14), =($2, +($7, 1)), =($2, -($12, 1)))])
+ +- LogicalJoin(condition=[true], joinType=[inner])
+ :- LogicalJoin(condition=[true], joinType=[inner])
+ : :- LogicalProject(sum_b=[$2], avg_b=[/(CAST(CASE(>(COUNT($2) OVER (PARTITION BY $0, $1 RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING), 0), $SUM0($2) OVER (PARTITION BY $0, $1 RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING), null:BIGINT)):DOUBLE, COUNT($2) OVER (PARTITION BY $0, $1 RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING))], rn=[RANK() OVER (PARTITION BY $0, $1 ORDER BY $0 NULLS FIRST, $1 NULLS FIRST RANGE BETWEEN UNBOUNDED PRECEDING [...]
+ : : +- LogicalAggregate(group=[{0, 1}], sum_b=[SUM($2)])
+ : : +- LogicalProject(c=[$2], e=[$4], b=[$1])
+ : : +- LogicalFilter(condition=[AND(=($0, $3), IS NOT NULL($2), >($4, 10))])
+ : : +- LogicalJoin(condition=[true], joinType=[inner])
+ : : :- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+ : : +- LogicalTableScan(table=[[y, source: [TestTableSource(d, e, f)]]])
+ : +- LogicalProject(sum_b=[$2], avg_b=[/(CAST(CASE(>(COUNT($2) OVER (PARTITION BY $0, $1 RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING), 0), $SUM0($2) OVER (PARTITION BY $0, $1 RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING), null:BIGINT)):DOUBLE, COUNT($2) OVER (PARTITION BY $0, $1 RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING))], rn=[RANK() OVER (PARTITION BY $0, $1 ORDER BY $0 NULLS FIRST, $1 NULLS FIRST RANGE BETWEEN UNBOUNDED PRECEDING [...]
+ : +- LogicalAggregate(group=[{0, 1}], sum_b=[SUM($2)])
+ : +- LogicalProject(c=[$2], e=[$4], b=[$1])
+ : +- LogicalFilter(condition=[AND(=($0, $3), IS NOT NULL($2), >($4, 10))])
+ : +- LogicalJoin(condition=[true], joinType=[inner])
+ : :- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+ : +- LogicalTableScan(table=[[y, source: [TestTableSource(d, e, f)]]])
+ +- LogicalProject(sum_b=[$2], avg_b=[/(CAST(CASE(>(COUNT($2) OVER (PARTITION BY $0, $1 RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING), 0), $SUM0($2) OVER (PARTITION BY $0, $1 RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING), null:BIGINT)):DOUBLE, COUNT($2) OVER (PARTITION BY $0, $1 RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING))], rn=[RANK() OVER (PARTITION BY $0, $1 ORDER BY $0 NULLS FIRST, $1 NULLS FIRST RANGE BETWEEN UNBOUNDED PRECEDING AN [...]
+ +- LogicalAggregate(group=[{0, 1}], sum_b=[SUM($2)])
+ +- LogicalProject(c=[$2], e=[$4], b=[$1])
+ +- LogicalFilter(condition=[AND(=($0, $3), IS NOT NULL($2), >($4, 10))])
+ +- LogicalJoin(condition=[true], joinType=[inner])
+ :- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+ +- LogicalTableScan(table=[[y, source: [TestTableSource(d, e, f)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[c, e, avg_b, sum_b, sum_b0 AS psum, sum_b1 AS nsum, avg_b0 AS avg_b2])
++- HashJoin(joinType=[InnerJoin], where=[AND(=(c, c0), =(e, e0), =(rn, -(rn0, 1)))], select=[sum_b, avg_b, rn, c, e, sum_b0, avg_b0, sum_b1, rn0, c0, e0], build=[right])
+ :- Exchange(distribution=[hash[c, e]], exchange_mode=[BATCH])
+ : +- Calc(select=[sum_b, avg_b, rn, c, e, sum_b0, avg_b0])
+ : +- HashJoin(joinType=[InnerJoin], where=[AND(=(c, c0), =(e, e0), =(rn, +(rn0, 1)))], select=[sum_b, avg_b, rn, c, e, sum_b0, avg_b0, rn0, c0, e0], build=[left])
+ : :- Exchange(distribution=[hash[c, e]])
+ : : +- Calc(select=[sum_b, /(CAST(CASE(>(w0$o0, 0:BIGINT), w0$o1, null:BIGINT)), w0$o0) AS avg_b, w1$o0 AS rn, c, e], where=[AND(<>(c, _UTF-16LE'':VARCHAR(65536) CHARACTER SET "UTF-16LE"), >(-(sum_b, /(CAST(CASE(>(w0$o0, 0:BIGINT), w0$o1, null:BIGINT)), w0$o0)), 3))])
+ : : +- OverAggregate(partitionBy=[c, e], orderBy=[], window#0=[COUNT(sum_b) AS w0$o0, $SUM0(sum_b) AS w0$o1 RANG BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING], window#1=[RANK(*) AS w1$o0 RANG BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW], select=[c, e, sum_b, w0$o0, w0$o1, w1$o0], reuse_id=[1])
+ : : +- Sort(orderBy=[c ASC, e ASC])
+ : : +- Exchange(distribution=[hash[c, e]])
+ : : +- HashAggregate(isMerge=[true], groupBy=[c, e], select=[c, e, Final_SUM(sum$0) AS sum_b])
+ : : +- Exchange(distribution=[hash[c, e]])
+ : : +- LocalHashAggregate(groupBy=[c, e], select=[c, e, Partial_SUM($f6) AS sum$0])
+ : : +- Calc(select=[a, c, sum_b, d, e, $f2, *(sum_b, $f2) AS $f6])
+ : : +- HashJoin(joinType=[InnerJoin], where=[=(a, d)], select=[a, c, sum_b, d, e, $f2], build=[right])
+ : : :- Exchange(distribution=[hash[a]])
+ : : : +- HashAggregate(isMerge=[true], groupBy=[a, c], select=[a, c, Final_SUM(sum$0) AS sum_b])
+ : : : +- Exchange(distribution=[hash[a, c]])
+ : : : +- LocalHashAggregate(groupBy=[a, c], select=[a, c, Partial_SUM(b) AS sum$0])
+ : : : +- Calc(select=[a, b, c], where=[IS NOT NULL(c)])
+ : : : +- TableSourceScan(table=[[x, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
+ : : +- Exchange(distribution=[hash[d]])
+ : : +- HashAggregate(isMerge=[true], groupBy=[d, e], select=[d, e, Final_COUNT(count1$0) AS $f2])
+ : : +- Exchange(distribution=[hash[d, e]])
+ : : +- LocalHashAggregate(groupBy=[d, e], select=[d, e, Partial_COUNT(*) AS count1$0])
+ : : +- Calc(select=[d, e], where=[>(e, 10)])
+ : : +- TableSourceScan(table=[[y, source: [TestTableSource(d, e, f)]]], fields=[d, e, f])
+ : +- Exchange(distribution=[hash[c, e]], exchange_mode=[BATCH])
+ : +- Calc(select=[sum_b, /(CAST(CASE(>(w0$o0, 0:BIGINT), w0$o1, null:BIGINT)), w0$o0) AS avg_b, w1$o0 AS rn, c, e])
+ : +- Reused(reference_id=[1])
+ +- Exchange(distribution=[hash[c, e]])
+ +- Calc(select=[sum_b, w1$o0 AS rn, c, e])
+ +- Reused(reference_id=[1])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSubplanReuseOnAggregateWithNonDeterministicAggCall">
+ <Resource name="sql">
+ <![CDATA[
+WITH r AS (SELECT c, MyFirst(a) a, MyLast(b) b FROM x GROUP BY c)
+SELECT * FROM r r1, r r2 WHERE r1.a = r2.b AND r2.a > 1
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(c=[$0], a=[$1], b=[$2], c0=[$3], a0=[$4], b0=[$5])
++- LogicalFilter(condition=[AND(=(CAST($1):BIGINT, $5), >($4, 1))])
+ +- LogicalJoin(condition=[true], joinType=[inner])
+ :- LogicalAggregate(group=[{0}], a=[MyFirst($1)], b=[MyLast($2)])
+ : +- LogicalProject(c=[$2], a=[$0], b=[$1])
+ : +- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+ +- LogicalAggregate(group=[{0}], a=[MyFirst($1)], b=[MyLast($2)])
+ +- LogicalProject(c=[$2], a=[$0], b=[$1])
+ +- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+NestedLoopJoin(joinType=[InnerJoin], where=[=(CAST(a), b0)], select=[c, a, b, c0, a0, b0], build=[right])
+:- Exchange(distribution=[any], exchange_mode=[BATCH])
+: +- SortAggregate(isMerge=[false], groupBy=[c], select=[c, MyFirst(a) AS a, MyLast(b) AS b], reuse_id=[1])
+: +- Sort(orderBy=[c ASC])
+: +- Exchange(distribution=[hash[c]])
+: +- TableSourceScan(table=[[x, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
++- Exchange(distribution=[broadcast])
+ +- Calc(select=[c, a, b], where=[>(a, 1)])
+ +- Reused(reference_id=[1])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSubplanReuseOnCalc">
+ <Resource name="sql">
+ <![CDATA[
+WITH r AS (SELECT a, b, c FROM x WHERE c LIKE 'test%')
+(SELECT r.a, LOWER(c) AS c, y.e FROM r, y WHERE r.a = y.d)
+UNION ALL
+(SELECT r.a, LOWER(c) AS c, y.e FROM r, y WHERE r.a = y.d)
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalUnion(all=[true])
+:- LogicalProject(a=[$0], c=[LOWER($2)], e=[$4])
+: +- LogicalFilter(condition=[=($0, $3)])
+: +- LogicalJoin(condition=[true], joinType=[inner])
+: :- LogicalProject(a=[$0], b=[$1], c=[$2])
+: : +- LogicalFilter(condition=[LIKE($2, _UTF-16LE'test%')])
+: : +- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+: +- LogicalTableScan(table=[[y, source: [TestTableSource(d, e, f)]]])
++- LogicalProject(a=[$0], c=[LOWER($2)], e=[$4])
+ +- LogicalFilter(condition=[=($0, $3)])
+ +- LogicalJoin(condition=[true], joinType=[inner])
+ :- LogicalProject(a=[$0], b=[$1], c=[$2])
+ : +- LogicalFilter(condition=[LIKE($2, _UTF-16LE'test%')])
+ : +- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+ +- LogicalTableScan(table=[[y, source: [TestTableSource(d, e, f)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Union(all=[true], union=[a, c, e])
+:- Calc(select=[a, LOWER(c) AS c, e], reuse_id=[1])
+: +- HashJoin(joinType=[InnerJoin], where=[=(a, d)], select=[a, c, d, e], build=[right])
+: :- Exchange(distribution=[hash[a]])
+: : +- Calc(select=[a, c], where=[LIKE(c, _UTF-16LE'test%')])
+: : +- TableSourceScan(table=[[x, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
+: +- Exchange(distribution=[hash[d]])
+: +- Calc(select=[d, e])
+: +- TableSourceScan(table=[[y, source: [TestTableSource(d, e, f)]]], fields=[d, e, f])
++- Reused(reference_id=[1])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSubplanReuseOnCalcWithNonDeterministicProject">
+ <Resource name="sql">
+ <![CDATA[
+(SELECT a, random_udf() FROM x WHERE a > 10)
+UNION ALL
+(SELECT a, random_udf() FROM x WHERE a > 10)
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalUnion(all=[true])
+:- LogicalProject(a=[$0], EXPR$1=[random_udf()])
+: +- LogicalFilter(condition=[>($0, 10)])
+: +- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
++- LogicalProject(a=[$0], EXPR$1=[random_udf()])
+ +- LogicalFilter(condition=[>($0, 10)])
+ +- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Union(all=[true], union=[a, EXPR$1])
+:- Calc(select=[a, random_udf() AS EXPR$1], where=[>(a, 10)], reuse_id=[1])
+: +- TableSourceScan(table=[[x, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
++- Reused(reference_id=[1])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSubplanReuseOnCalcWithNonDeterministicUdf">
+ <Resource name="sql">
+ <![CDATA[
+(SELECT a FROM x WHERE b > random_udf(a))
+UNION ALL
+(SELECT a FROM x WHERE b > random_udf(a))
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalUnion(all=[true])
+:- LogicalProject(a=[$0])
+: +- LogicalFilter(condition=[>($1, random_udf($0))])
+: +- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
++- LogicalProject(a=[$0])
+ +- LogicalFilter(condition=[>($1, random_udf($0))])
+ +- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Union(all=[true], union=[a])
+:- Calc(select=[a], where=[>(b, random_udf(a))], reuse_id=[1])
+: +- TableSourceScan(table=[[x, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
++- Reused(reference_id=[1])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSubplanReuseOnCorrelate">
+ <Resource name="sql">
+ <![CDATA[
+WITH r AS (SELECT a, b, c, v FROM x, LATERAL TABLE(str_split(c, '-')) AS T(v))
+SELECT * FROM r r1, r r2 WHERE r1.v = r2.v
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0], b=[$1], c=[$2], v=[$3], a0=[$4], b0=[$5], c0=[$6], v0=[$7])
++- LogicalFilter(condition=[=($3, $7)])
+ +- LogicalJoin(condition=[true], joinType=[inner])
+ :- LogicalProject(a=[$0], b=[$1], c=[$2], v=[$3])
+ : +- LogicalCorrelate(correlation=[$cor0], joinType=[inner], requiredColumns=[{2}])
+ : :- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+ : +- LogicalTableFunctionScan(invocation=[str_split($cor0.c, _UTF-16LE'-')], rowType=[RecordType(VARCHAR(65536) f0)], elementType=[class [Ljava.lang.Object;])
+ +- LogicalProject(a=[$0], b=[$1], c=[$2], v=[$3])
+ +- LogicalCorrelate(correlation=[$cor1], joinType=[inner], requiredColumns=[{2}])
+ :- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+ +- LogicalTableFunctionScan(invocation=[str_split($cor1.c, _UTF-16LE'-')], rowType=[RecordType(VARCHAR(65536) f0)], elementType=[class [Ljava.lang.Object;])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+HashJoin(joinType=[InnerJoin], where=[=(f0, f00)], select=[a, b, c, f0, a0, b0, c0, f00], isBroadcast=[true], build=[right])
+:- Correlate(invocation=[str_split($cor0.c, _UTF-16LE'-')], correlate=[table(str_split($cor0.c,_UTF-16LE'-'))], select=[a,b,c,f0], rowType=[RecordType(INTEGER a, BIGINT b, VARCHAR(65536) c, VARCHAR(65536) f0)], joinType=[INNER])
+: +- TableSourceScan(table=[[x, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
++- Exchange(distribution=[broadcast])
+ +- Correlate(invocation=[str_split($cor1.c, _UTF-16LE'-')], correlate=[table(str_split($cor1.c,_UTF-16LE'-'))], select=[a,b,c,f0], rowType=[RecordType(INTEGER a, BIGINT b, VARCHAR(65536) c, VARCHAR(65536) f0)], joinType=[INNER])
+ +- TableSourceScan(table=[[x, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSubplanReuseOnCorrelateWithNonDeterministicUDTF">
+ <Resource name="sql">
+ <![CDATA[
+WITH r AS (SELECT a, b, c, s FROM x, LATERAL TABLE(TableFun(c)) AS T(s))
+SELECT * FROM r r1, r r2 WHERE r1.c = r2.s
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0], b=[$1], c=[$2], s=[$3], a0=[$4], b0=[$5], c0=[$6], s0=[$7])
++- LogicalFilter(condition=[=($2, $7)])
+ +- LogicalJoin(condition=[true], joinType=[inner])
+ :- LogicalProject(a=[$0], b=[$1], c=[$2], s=[$3])
+ : +- LogicalCorrelate(correlation=[$cor0], joinType=[inner], requiredColumns=[{2}])
+ : :- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+ : +- LogicalTableFunctionScan(invocation=[TableFun($cor0.c)], rowType=[RecordType(VARCHAR(65536) f0)], elementType=[class [Ljava.lang.Object;])
+ +- LogicalProject(a=[$0], b=[$1], c=[$2], s=[$3])
+ +- LogicalCorrelate(correlation=[$cor1], joinType=[inner], requiredColumns=[{2}])
+ :- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+ +- LogicalTableFunctionScan(invocation=[TableFun($cor1.c)], rowType=[RecordType(VARCHAR(65536) f0)], elementType=[class [Ljava.lang.Object;])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+NestedLoopJoin(joinType=[InnerJoin], where=[=(c, f00)], select=[a, b, c, f0, a0, b0, c0, f00], build=[left])
+:- Exchange(distribution=[broadcast])
+: +- Correlate(invocation=[TableFun($cor0.c)], correlate=[table(TableFun($cor0.c))], select=[a,b,c,f0], rowType=[RecordType(INTEGER a, BIGINT b, VARCHAR(65536) c, VARCHAR(65536) f0)], joinType=[INNER])
+: +- TableSourceScan(table=[[x, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
++- Correlate(invocation=[TableFun($cor1.c)], correlate=[table(TableFun($cor1.c))], select=[a,b,c,f0], rowType=[RecordType(INTEGER a, BIGINT b, VARCHAR(65536) c, VARCHAR(65536) f0)], joinType=[INNER])
+ +- TableSourceScan(table=[[x, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSubplanReuseOnExchange">
+ <Resource name="sql">
+ <![CDATA[
+WITH r AS (SELECT a, b, c FROM x WHERE c LIKE 'test%')
+SELECT * FROM r, y WHERE a = d AND e > 10
+UNION ALL
+SELECT * FROM r, y WHERE a = d AND f <> ''
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalUnion(all=[true])
+:- LogicalProject(a=[$0], b=[$1], c=[$2], d=[$3], e=[$4], f=[$5])
+: +- LogicalFilter(condition=[AND(=($0, $3), >($4, 10))])
+: +- LogicalJoin(condition=[true], joinType=[inner])
+: :- LogicalProject(a=[$0], b=[$1], c=[$2])
+: : +- LogicalFilter(condition=[LIKE($2, _UTF-16LE'test%')])
+: : +- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+: +- LogicalTableScan(table=[[y, source: [TestTableSource(d, e, f)]]])
++- LogicalProject(a=[$0], b=[$1], c=[$2], d=[$3], e=[$4], f=[$5])
+ +- LogicalFilter(condition=[AND(=($0, $3), <>($5, _UTF-16LE''))])
+ +- LogicalJoin(condition=[true], joinType=[inner])
+ :- LogicalProject(a=[$0], b=[$1], c=[$2])
+ : +- LogicalFilter(condition=[LIKE($2, _UTF-16LE'test%')])
+ : +- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+ +- LogicalTableScan(table=[[y, source: [TestTableSource(d, e, f)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Union(all=[true], union=[a, b, c, d, e, f])
+:- HashJoin(joinType=[InnerJoin], where=[=(a, d)], select=[a, b, c, d, e, f], build=[left])
+: :- Exchange(distribution=[hash[a]], reuse_id=[1])
+: : +- Calc(select=[a, b, c], where=[LIKE(c, _UTF-16LE'test%')])
+: : +- TableSourceScan(table=[[x, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
+: +- Exchange(distribution=[hash[d]])
+: +- Calc(select=[d, e, f], where=[>(e, 10)])
+: +- TableSourceScan(table=[[y, source: [TestTableSource(d, e, f)]]], fields=[d, e, f])
++- HashJoin(joinType=[InnerJoin], where=[=(a, d)], select=[a, b, c, d, e, f], build=[left])
+ :- Reused(reference_id=[1])
+ +- Exchange(distribution=[hash[d]])
+ +- Calc(select=[d, e, f], where=[<>(f, _UTF-16LE'':VARCHAR(65536) CHARACTER SET "UTF-16LE")])
+ +- TableSourceScan(table=[[y, source: [TestTableSource(d, e, f)]]], fields=[d, e, f])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSubplanReuseOnHashAggregate">
+ <Resource name="sql">
+ <![CDATA[
+WITH r AS (SELECT c, SUM(a) a, SUM(b) b FROM x GROUP BY c)
+SELECT * FROM r r1, r r2 WHERE r1.a = r2.b AND r2.a > 1
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(c=[$0], a=[$1], b=[$2], c0=[$3], a0=[$4], b0=[$5])
++- LogicalFilter(condition=[AND(=(CAST($1):BIGINT, $5), >($4, 1))])
+ +- LogicalJoin(condition=[true], joinType=[inner])
+ :- LogicalAggregate(group=[{0}], a=[SUM($1)], b=[SUM($2)])
+ : +- LogicalProject(c=[$2], a=[$0], b=[$1])
+ : +- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+ +- LogicalAggregate(group=[{0}], a=[SUM($1)], b=[SUM($2)])
+ +- LogicalProject(c=[$2], a=[$0], b=[$1])
+ +- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+NestedLoopJoin(joinType=[InnerJoin], where=[=(CAST(a), b0)], select=[c, a, b, c0, a0, b0], build=[right])
+:- Exchange(distribution=[any], exchange_mode=[BATCH])
+: +- HashAggregate(isMerge=[true], groupBy=[c], select=[c, Final_SUM(sum$0) AS a, Final_SUM(sum$1) AS b], reuse_id=[1])
+: +- Exchange(distribution=[hash[c]])
+: +- LocalHashAggregate(groupBy=[c], select=[c, Partial_SUM(a) AS sum$0, Partial_SUM(b) AS sum$1])
+: +- TableSourceScan(table=[[x, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
++- Exchange(distribution=[broadcast])
+ +- Calc(select=[c, a, b], where=[>(a, 1)])
+ +- Reused(reference_id=[1])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSubplanReuseOnHashJoin">
+ <Resource name="sql">
+ <![CDATA[
+WITH r AS (SELECT * FROM x, y WHERE a = d AND c LIKE 'He%')
+SELECT * FROM r r1, r r2 WHERE r1.a = r2.d
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0], b=[$1], c=[$2], d=[$3], e=[$4], f=[$5], a0=[$6], b0=[$7], c0=[$8], d0=[$9], e0=[$10], f0=[$11])
++- LogicalFilter(condition=[=($0, $9)])
+ +- LogicalJoin(condition=[true], joinType=[inner])
+ :- LogicalProject(a=[$0], b=[$1], c=[$2], d=[$3], e=[$4], f=[$5])
+ : +- LogicalFilter(condition=[AND(=($0, $3), LIKE($2, _UTF-16LE'He%'))])
+ : +- LogicalJoin(condition=[true], joinType=[inner])
+ : :- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+ : +- LogicalTableScan(table=[[y, source: [TestTableSource(d, e, f)]]])
+ +- LogicalProject(a=[$0], b=[$1], c=[$2], d=[$3], e=[$4], f=[$5])
+ +- LogicalFilter(condition=[AND(=($0, $3), LIKE($2, _UTF-16LE'He%'))])
+ +- LogicalJoin(condition=[true], joinType=[inner])
+ :- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+ +- LogicalTableScan(table=[[y, source: [TestTableSource(d, e, f)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+HashJoin(joinType=[InnerJoin], where=[=(a, d0)], select=[a, b, c, d, e, f, a0, b0, c0, d0, e0, f0], build=[left])
+:- Exchange(distribution=[hash[a]])
+: +- HashJoin(joinType=[InnerJoin], where=[=(a, d)], select=[a, b, c, d, e, f], build=[left], reuse_id=[1])
+: :- Exchange(distribution=[hash[a]])
+: : +- Calc(select=[a, b, c], where=[LIKE(c, _UTF-16LE'He%')])
+: : +- TableSourceScan(table=[[x, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
+: +- Exchange(distribution=[hash[d]])
+: +- TableSourceScan(table=[[y, source: [TestTableSource(d, e, f)]]], fields=[d, e, f])
++- Exchange(distribution=[hash[d]], exchange_mode=[BATCH])
+ +- Reused(reference_id=[1])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSubplanReuseOnJoin">
+ <Resource name="sql">
+ <![CDATA[
+WITH r AS (SELECT * FROM x FULL OUTER JOIN y ON ABS(a) = ABS(d) OR c = f
+ WHERE b > 1 and e < 2)
+SELECT * FROM r r1, r r2 WHERE r1.a = r2.b
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0], b=[$1], c=[$2], d=[$3], e=[$4], f=[$5], a0=[$6], b0=[$7], c0=[$8], d0=[$9], e0=[$10], f0=[$11])
++- LogicalFilter(condition=[=(CAST($0):BIGINT, $7)])
+ +- LogicalJoin(condition=[true], joinType=[inner])
+ :- LogicalProject(a=[$0], b=[$1], c=[$2], d=[$3], e=[$4], f=[$5])
+ : +- LogicalFilter(condition=[AND(>($1, 1), <($4, 2))])
+ : +- LogicalJoin(condition=[OR(=(ABS($0), ABS($3)), =($2, $5))], joinType=[full])
+ : :- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+ : +- LogicalTableScan(table=[[y, source: [TestTableSource(d, e, f)]]])
+ +- LogicalProject(a=[$0], b=[$1], c=[$2], d=[$3], e=[$4], f=[$5])
+ +- LogicalFilter(condition=[AND(>($1, 1), <($4, 2))])
+ +- LogicalJoin(condition=[OR(=(ABS($0), ABS($3)), =($2, $5))], joinType=[full])
+ :- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+ +- LogicalTableScan(table=[[y, source: [TestTableSource(d, e, f)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+NestedLoopJoin(joinType=[InnerJoin], where=[=(CAST(a), b0)], select=[a, b, c, d, e, f, a0, b0, c0, d0, e0, f0], build=[left])
+:- Exchange(distribution=[broadcast])
+: +- NestedLoopJoin(joinType=[InnerJoin], where=[OR(=(ABS(a), ABS(d)), =(c, f))], select=[a, b, c, d, e, f], build=[left], reuse_id=[1])
+: :- Exchange(distribution=[broadcast])
+: : +- Calc(select=[a, b, c], where=[>(b, 1)])
+: : +- TableSourceScan(table=[[x, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
+: +- Calc(select=[d, e, f], where=[<(e, 2)])
+: +- TableSourceScan(table=[[y, source: [TestTableSource(d, e, f)]]], fields=[d, e, f])
++- Exchange(distribution=[any], exchange_mode=[BATCH])
+ +- Reused(reference_id=[1])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSubplanReuseOnJoinNonDeterministicJoinCondition">
+ <Resource name="sql">
+ <![CDATA[
+WITH r AS (SELECT * FROM x FULL OUTER JOIN y ON random_udf(a) = random_udf(d) OR c = f
+ WHERE b > 1 and e < 2)
+SELECT * FROM r r1, r r2 WHERE r1.a = r2.b
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0], b=[$1], c=[$2], d=[$3], e=[$4], f=[$5], a0=[$6], b0=[$7], c0=[$8], d0=[$9], e0=[$10], f0=[$11])
++- LogicalFilter(condition=[=(CAST($0):BIGINT, $7)])
+ +- LogicalJoin(condition=[true], joinType=[inner])
+ :- LogicalProject(a=[$0], b=[$1], c=[$2], d=[$3], e=[$4], f=[$5])
+ : +- LogicalFilter(condition=[AND(>($1, 1), <($4, 2))])
+ : +- LogicalJoin(condition=[OR(=(random_udf($0), random_udf($3)), =($2, $5))], joinType=[full])
+ : :- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+ : +- LogicalTableScan(table=[[y, source: [TestTableSource(d, e, f)]]])
+ +- LogicalProject(a=[$0], b=[$1], c=[$2], d=[$3], e=[$4], f=[$5])
+ +- LogicalFilter(condition=[AND(>($1, 1), <($4, 2))])
+ +- LogicalJoin(condition=[OR(=(random_udf($0), random_udf($3)), =($2, $5))], joinType=[full])
+ :- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+ +- LogicalTableScan(table=[[y, source: [TestTableSource(d, e, f)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+NestedLoopJoin(joinType=[InnerJoin], where=[=(CAST(a), b0)], select=[a, b, c, d, e, f, a0, b0, c0, d0, e0, f0], build=[left])
+:- Exchange(distribution=[broadcast])
+: +- NestedLoopJoin(joinType=[InnerJoin], where=[OR(=(random_udf(a), random_udf(d)), =(c, f))], select=[a, b, c, d, e, f], build=[left], reuse_id=[1])
+: :- Exchange(distribution=[broadcast])
+: : +- Calc(select=[a, b, c], where=[>(b, 1)])
+: : +- TableSourceScan(table=[[x, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
+: +- Calc(select=[d, e, f], where=[<(e, 2)])
+: +- TableSourceScan(table=[[y, source: [TestTableSource(d, e, f)]]], fields=[d, e, f])
++- Exchange(distribution=[any], exchange_mode=[BATCH])
+ +- Reused(reference_id=[1])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSubplanReuseOnLimit">
+ <Resource name="sql">
+ <![CDATA[
+WITH r AS (SELECT a, b FROM x LIMIT 10)
+SELECT r1.a, r1.b, r2.a FROM r r1, r r2 WHERE r1.a = r2.b
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0], b=[$1], a0=[$2])
++- LogicalFilter(condition=[=(CAST($0):BIGINT, $3)])
+ +- LogicalJoin(condition=[true], joinType=[inner])
+ :- LogicalSort(fetch=[10])
+ : +- LogicalProject(a=[$0], b=[$1])
+ : +- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+ +- LogicalSort(fetch=[10])
+ +- LogicalProject(a=[$0], b=[$1])
+ +- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a, b, a0])
++- NestedLoopJoin(joinType=[InnerJoin], where=[=(CAST(a), b0)], select=[a, b, a0, b0], build=[left])
+ :- Exchange(distribution=[broadcast])
+ : +- Calc(select=[a, b], reuse_id=[1])
+ : +- Limit(offset=[0], fetch=[10], global=[true])
+ : +- Exchange(distribution=[single])
+ : +- Limit(offset=[0], fetch=[10], global=[false])
+ : +- TableSourceScan(table=[[x, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
+ +- Exchange(distribution=[any], exchange_mode=[BATCH])
+ +- Reused(reference_id=[1])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSubplanReuseOnNestedLoopJoin">
+ <Resource name="sql">
+ <![CDATA[
+WITH r AS (SELECT * FROM x, y WHERE a = d AND c LIKE 'He%')
+SELECT * FROM r r1, r r2 WHERE r1.a = r2.d
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0], b=[$1], c=[$2], d=[$3], e=[$4], f=[$5], a0=[$6], b0=[$7], c0=[$8], d0=[$9], e0=[$10], f0=[$11])
++- LogicalFilter(condition=[=($0, $9)])
+ +- LogicalJoin(condition=[true], joinType=[inner])
+ :- LogicalProject(a=[$0], b=[$1], c=[$2], d=[$3], e=[$4], f=[$5])
+ : +- LogicalFilter(condition=[AND(=($0, $3), LIKE($2, _UTF-16LE'He%'))])
+ : +- LogicalJoin(condition=[true], joinType=[inner])
+ : :- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+ : +- LogicalTableScan(table=[[y, source: [TestTableSource(d, e, f)]]])
+ +- LogicalProject(a=[$0], b=[$1], c=[$2], d=[$3], e=[$4], f=[$5])
+ +- LogicalFilter(condition=[AND(=($0, $3), LIKE($2, _UTF-16LE'He%'))])
+ +- LogicalJoin(condition=[true], joinType=[inner])
+ :- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+ +- LogicalTableScan(table=[[y, source: [TestTableSource(d, e, f)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+NestedLoopJoin(joinType=[InnerJoin], where=[=(a, d0)], select=[a, b, c, d, e, f, a0, b0, c0, d0, e0, f0], build=[left])
+:- Exchange(distribution=[broadcast])
+: +- NestedLoopJoin(joinType=[InnerJoin], where=[=(a, d)], select=[a, b, c, d, e, f], build=[left], reuse_id=[1])
+: :- Exchange(distribution=[broadcast])
+: : +- Calc(select=[a, b, c], where=[LIKE(c, _UTF-16LE'He%')])
+: : +- TableSourceScan(table=[[x, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
+: +- TableSourceScan(table=[[y, source: [TestTableSource(d, e, f)]]], fields=[d, e, f])
++- Exchange(distribution=[any], exchange_mode=[BATCH])
+ +- Reused(reference_id=[1])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSubplanReuseOnOverWindow">
+ <Resource name="sql">
+ <![CDATA[
+WITH r AS (SELECT a, b, RANK() OVER (ORDER BY c DESC) FROM x)
+SELECT * FROM r r1, r r2 WHERE r1.a = r2.a AND r1.b < 100 AND r2.b > 10
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0], b=[$1], EXPR$2=[$2], a0=[$3], b0=[$4], EXPR$20=[$5])
++- LogicalFilter(condition=[AND(=($0, $3), <($1, 100), >($4, 10))])
+ +- LogicalJoin(condition=[true], joinType=[inner])
+ :- LogicalProject(a=[$0], b=[$1], EXPR$2=[RANK() OVER (ORDER BY $2 DESC NULLS LAST RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)])
+ : +- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+ +- LogicalProject(a=[$0], b=[$1], EXPR$2=[RANK() OVER (ORDER BY $2 DESC NULLS LAST RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)])
+ +- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+HashJoin(joinType=[InnerJoin], where=[=(a, a0)], select=[a, b, $2, a0, b0, w0$o0], build=[left])
+:- Exchange(distribution=[hash[a]])
+: +- Calc(select=[a, b, w0$o0 AS $2], where=[<(b, 100)])
+: +- OverAggregate(orderBy=[c DESC], window#0=[RANK(*) AS w0$o0 RANG BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW], select=[a, b, c, w0$o0], reuse_id=[1])
+: +- Sort(orderBy=[c DESC])
+: +- Exchange(distribution=[single])
+: +- TableSourceScan(table=[[x, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
++- Exchange(distribution=[hash[a]], exchange_mode=[BATCH])
+ +- Calc(select=[a, b, w0$o0], where=[>(b, 10)])
+ +- Reused(reference_id=[1])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSubplanReuseOnOverWindowWithNonDeterministicAggCall">
+ <Resource name="sql">
+ <![CDATA[
+WITH r AS (SELECT a, b, MyFirst(c) OVER (PARTITION BY c ORDER BY c DESC) FROM x)
+SELECT * FROM r r1, r r2 WHERE r1.a = r2.a AND r1.b < 100 AND r2.b > 10
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0], b=[$1], EXPR$2=[$2], a0=[$3], b0=[$4], EXPR$20=[$5])
++- LogicalFilter(condition=[AND(=($0, $3), <($1, 100), >($4, 10))])
+ +- LogicalJoin(condition=[true], joinType=[inner])
+ :- LogicalProject(a=[$0], b=[$1], EXPR$2=[MyFirst($2) OVER (PARTITION BY $2 ORDER BY $2 DESC NULLS LAST RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)])
+ : +- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+ +- LogicalProject(a=[$0], b=[$1], EXPR$2=[MyFirst($2) OVER (PARTITION BY $2 ORDER BY $2 DESC NULLS LAST RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)])
+ +- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+HashJoin(joinType=[InnerJoin], where=[=(a, a0)], select=[a, b, $2, a0, b0, w0$o0], build=[left])
+:- Exchange(distribution=[hash[a]])
+: +- Calc(select=[a, b, w0$o0 AS $2], where=[<(b, 100)])
+: +- OverAggregate(partitionBy=[c], orderBy=[c DESC], window#0=[MyFirst(c) AS w0$o0 RANG BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW], select=[a, b, c, w0$o0], reuse_id=[1])
+: +- Sort(orderBy=[c DESC])
+: +- Exchange(distribution=[hash[c]])
+: +- TableSourceScan(table=[[x, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
++- Exchange(distribution=[hash[a]], exchange_mode=[BATCH])
+ +- Calc(select=[a, b, w0$o0], where=[>(b, 10)])
+ +- Reused(reference_id=[1])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSubplanReuseOnSort">
+ <Resource name="sql">
+ <![CDATA[
+WITH r AS (SELECT c, SUM(a) a, SUM(b) b FROM x GROUP BY c ORDER BY a, b DESC)
+SELECT * FROM r r1, r r2 WHERE r1.a = r2.a AND r1.a > 1 AND r2.b < 10
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(c=[$0], a=[$1], b=[$2], c0=[$3], a0=[$4], b0=[$5])
++- LogicalFilter(condition=[AND(=($1, $4), >($1, 1), <($5, 10))])
+ +- LogicalJoin(condition=[true], joinType=[inner])
+ :- LogicalAggregate(group=[{0}], a=[SUM($1)], b=[SUM($2)])
+ : +- LogicalProject(c=[$2], a=[$0], b=[$1])
+ : +- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+ +- LogicalAggregate(group=[{0}], a=[SUM($1)], b=[SUM($2)])
+ +- LogicalProject(c=[$2], a=[$0], b=[$1])
+ +- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+HashJoin(joinType=[InnerJoin], where=[=(a, a0)], select=[c, a, b, c0, a0, b0], build=[left])
+:- Exchange(distribution=[hash[a]])
+: +- Calc(select=[c, a, b], where=[>(a, 1)])
+: +- HashAggregate(isMerge=[true], groupBy=[c], select=[c, Final_SUM(sum$0) AS a, Final_SUM(sum$1) AS b], reuse_id=[1])
+: +- Exchange(distribution=[hash[c]])
+: +- LocalHashAggregate(groupBy=[c], select=[c, Partial_SUM(a) AS sum$0, Partial_SUM(b) AS sum$1])
+: +- TableSourceScan(table=[[x, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
++- Exchange(distribution=[hash[a]], exchange_mode=[BATCH])
+ +- Calc(select=[c, a, b], where=[<(b, 10)])
+ +- Reused(reference_id=[1])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSubplanReuseOnSourceWithLimit">
+ <Resource name="sql">
+ <![CDATA[
+WITH r AS (SELECT a, b FROM x LIMIT 10)
+SELECT r1.a, r1.b, r2.a FROM r r1, r r2 WHERE r1.a = r2.b
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0], b=[$1], a0=[$2])
++- LogicalFilter(condition=[=(CAST($0):BIGINT, $3)])
+ +- LogicalJoin(condition=[true], joinType=[inner])
+ :- LogicalSort(fetch=[10])
+ : +- LogicalProject(a=[$0], b=[$1])
+ : +- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+ +- LogicalSort(fetch=[10])
+ +- LogicalProject(a=[$0], b=[$1])
+ +- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a, b, a0])
++- NestedLoopJoin(joinType=[InnerJoin], where=[=(CAST(a), b0)], select=[a, b, a0, b0], build=[left])
+ :- Exchange(distribution=[broadcast])
+ : +- Calc(select=[a, b], reuse_id=[1])
+ : +- Limit(offset=[0], fetch=[10], global=[true])
+ : +- Exchange(distribution=[single])
+ : +- Limit(offset=[0], fetch=[10], global=[false])
+ : +- TableSourceScan(table=[[x, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
+ +- Exchange(distribution=[any], exchange_mode=[BATCH])
+ +- Reused(reference_id=[1])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSubplanReuseOnSortAggregate">
+ <Resource name="sql">
+ <![CDATA[
+WITH r AS (SELECT c, SUM(a) a, SUM(b) b FROM x GROUP BY c)
+SELECT * FROM r r1, r r2 WHERE r1.a = r2.b AND r2.a > 1
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(c=[$0], a=[$1], b=[$2], c0=[$3], a0=[$4], b0=[$5])
++- LogicalFilter(condition=[AND(=(CAST($1):BIGINT, $5), >($4, 1))])
+ +- LogicalJoin(condition=[true], joinType=[inner])
+ :- LogicalAggregate(group=[{0}], a=[SUM($1)], b=[SUM($2)])
+ : +- LogicalProject(c=[$2], a=[$0], b=[$1])
+ : +- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+ +- LogicalAggregate(group=[{0}], a=[SUM($1)], b=[SUM($2)])
+ +- LogicalProject(c=[$2], a=[$0], b=[$1])
+ +- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+NestedLoopJoin(joinType=[InnerJoin], where=[=(CAST(a), b0)], select=[c, a, b, c0, a0, b0], build=[right])
+:- Exchange(distribution=[any], exchange_mode=[BATCH])
+: +- SortAggregate(isMerge=[true], groupBy=[c], select=[c, Final_SUM(sum$0) AS a, Final_SUM(sum$1) AS b], reuse_id=[1])
+: +- Sort(orderBy=[c ASC])
+: +- Exchange(distribution=[hash[c]])
+: +- LocalSortAggregate(groupBy=[c], select=[c, Partial_SUM(a) AS sum$0, Partial_SUM(b) AS sum$1])
+: +- Sort(orderBy=[c ASC])
+: +- TableSourceScan(table=[[x, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
++- Exchange(distribution=[broadcast])
+ +- Calc(select=[c, a, b], where=[>(a, 1)])
+ +- Reused(reference_id=[1])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSubplanReuseOnSortLimit">
+ <Resource name="sql">
+ <![CDATA[
+WITH r AS (SELECT c, SUM(a) a, SUM(b) b FROM x GROUP BY c ORDER BY a, b DESC LIMIT 10)
+SELECT * FROM r r1, r r2 WHERE r1.a = r2.a AND r1.a > 1 AND r2.b < 10
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(c=[$0], a=[$1], b=[$2], c0=[$3], a0=[$4], b0=[$5])
++- LogicalFilter(condition=[AND(=($1, $4), >($1, 1), <($5, 10))])
+ +- LogicalJoin(condition=[true], joinType=[inner])
+ :- LogicalSort(sort0=[$1], sort1=[$2], dir0=[ASC-nulls-first], dir1=[DESC-nulls-last], fetch=[10])
+ : +- LogicalAggregate(group=[{0}], a=[SUM($1)], b=[SUM($2)])
+ : +- LogicalProject(c=[$2], a=[$0], b=[$1])
+ : +- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+ +- LogicalSort(sort0=[$1], sort1=[$2], dir0=[ASC-nulls-first], dir1=[DESC-nulls-last], fetch=[10])
+ +- LogicalAggregate(group=[{0}], a=[SUM($1)], b=[SUM($2)])
+ +- LogicalProject(c=[$2], a=[$0], b=[$1])
+ +- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+NestedLoopJoin(joinType=[InnerJoin], where=[=(a, a0)], select=[c, a, b, c0, a0, b0], build=[left])
+:- Exchange(distribution=[broadcast])
+: +- Calc(select=[c, a, b], where=[>(a, 1)])
+: +- SortLimit(orderBy=[a ASC, b DESC], offset=[0], fetch=[10], global=[true], reuse_id=[1])
+: +- Exchange(distribution=[single])
+: +- SortLimit(orderBy=[a ASC, b DESC], offset=[0], fetch=[10], global=[false])
+: +- HashAggregate(isMerge=[true], groupBy=[c], select=[c, Final_SUM(sum$0) AS a, Final_SUM(sum$1) AS b])
+: +- Exchange(distribution=[hash[c]])
+: +- LocalHashAggregate(groupBy=[c], select=[c, Partial_SUM(a) AS sum$0, Partial_SUM(b) AS sum$1])
+: +- TableSourceScan(table=[[x, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
++- Exchange(distribution=[any], exchange_mode=[BATCH])
+ +- Calc(select=[c, a, b], where=[<(b, 10)])
+ +- Reused(reference_id=[1])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSubplanReuseOnUnion">
+ <Resource name="sql">
+ <![CDATA[
+WITH r AS (SELECT a, c FROM x WHERE b > 10 UNION ALL SELECT d, f FROM y WHERE e < 100)
+SELECT r1.a, r1.c, r2.c FROM r r1, r r2 WHERE r1.a = r2.a
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0], c=[$1], c0=[$3])
++- LogicalFilter(condition=[=($0, $2)])
+ +- LogicalJoin(condition=[true], joinType=[inner])
+ :- LogicalUnion(all=[true])
+ : :- LogicalProject(a=[$0], c=[$2])
+ : : +- LogicalFilter(condition=[>($1, 10)])
+ : : +- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+ : +- LogicalProject(d=[$0], f=[$2])
+ : +- LogicalFilter(condition=[<($1, 100)])
+ : +- LogicalTableScan(table=[[y, source: [TestTableSource(d, e, f)]]])
+ +- LogicalUnion(all=[true])
+ :- LogicalProject(a=[$0], c=[$2])
+ : +- LogicalFilter(condition=[>($1, 10)])
+ : +- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+ +- LogicalProject(d=[$0], f=[$2])
+ +- LogicalFilter(condition=[<($1, 100)])
+ +- LogicalTableScan(table=[[y, source: [TestTableSource(d, e, f)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a, c, c0])
++- HashJoin(joinType=[InnerJoin], where=[=(a, a0)], select=[a, c, a0, c0], build=[left])
+ :- Exchange(distribution=[hash[a]], exchange_mode=[BATCH], reuse_id=[1])
+ : +- Union(all=[true], union=[a, c])
+ : :- Calc(select=[a, c], where=[>(b, 10)])
+ : : +- TableSourceScan(table=[[x, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
+ : +- Calc(select=[d, f], where=[<(e, 100)])
+ : +- TableSourceScan(table=[[y, source: [TestTableSource(d, e, f)]]], fields=[d, e, f])
+ +- Reused(reference_id=[1])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSubplanReuseOnSortMergeJoin">
+ <Resource name="sql">
+ <![CDATA[
+WITH r AS (SELECT * FROM x, y WHERE a = d AND c LIKE 'He%')
+SELECT * FROM r r1, r r2 WHERE r1.a = r2.d
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0], b=[$1], c=[$2], d=[$3], e=[$4], f=[$5], a0=[$6], b0=[$7], c0=[$8], d0=[$9], e0=[$10], f0=[$11])
++- LogicalFilter(condition=[=($0, $9)])
+ +- LogicalJoin(condition=[true], joinType=[inner])
+ :- LogicalProject(a=[$0], b=[$1], c=[$2], d=[$3], e=[$4], f=[$5])
+ : +- LogicalFilter(condition=[AND(=($0, $3), LIKE($2, _UTF-16LE'He%'))])
+ : +- LogicalJoin(condition=[true], joinType=[inner])
+ : :- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+ : +- LogicalTableScan(table=[[y, source: [TestTableSource(d, e, f)]]])
+ +- LogicalProject(a=[$0], b=[$1], c=[$2], d=[$3], e=[$4], f=[$5])
+ +- LogicalFilter(condition=[AND(=($0, $3), LIKE($2, _UTF-16LE'He%'))])
+ +- LogicalJoin(condition=[true], joinType=[inner])
+ :- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+ +- LogicalTableScan(table=[[y, source: [TestTableSource(d, e, f)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+SortMergeJoin(joinType=[InnerJoin], where=[=(a, d0)], select=[a, b, c, d, e, f, a0, b0, c0, d0, e0, f0])
+:- Exchange(distribution=[hash[a]])
+: +- SortMergeJoin(joinType=[InnerJoin], where=[=(a, d)], select=[a, b, c, d, e, f], reuse_id=[1])
+: :- Exchange(distribution=[hash[a]])
+: : +- Calc(select=[a, b, c], where=[LIKE(c, _UTF-16LE'He%')])
+: : +- TableSourceScan(table=[[x, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
+: +- Exchange(distribution=[hash[d]])
+: +- TableSourceScan(table=[[y, source: [TestTableSource(d, e, f)]]], fields=[d, e, f])
++- Exchange(distribution=[hash[d]])
+ +- Reused(reference_id=[1])
+]]>
+ </Resource>
+ </TestCase>
+</Root>
diff --git a/flink-table/flink-table-planner-blink/src/test/resources/org/apache/flink/table/plan/batch/sql/ValuesTest.xml b/flink-table/flink-table-planner-blink/src/test/resources/org/apache/flink/table/plan/batch/sql/ValuesTest.xml
index 27a90f1..c517550 100644
--- a/flink-table/flink-table-planner-blink/src/test/resources/org/apache/flink/table/plan/batch/sql/ValuesTest.xml
+++ b/flink-table/flink-table-planner-blink/src/test/resources/org/apache/flink/table/plan/batch/sql/ValuesTest.xml
@@ -34,9 +34,9 @@ LogicalProject(a=[$0], b=[$1]), rowType=[RecordType(INTEGER a, DECIMAL(20, 1) b)
<![CDATA[
Union(all=[true], union=[EXPR$0, EXPR$1]), rowType=[RecordType(INTEGER EXPR$0, DECIMAL(20, 1) EXPR$1)]
:- Calc(select=[1 AS EXPR$0, 2.0:DECIMAL(20, 1) AS EXPR$1]), rowType=[RecordType(INTEGER EXPR$0, DECIMAL(20, 1) EXPR$1)]
-: +- Values(tuples=[[{ 0 }]], values=[ZERO]), rowType=[RecordType(INTEGER ZERO)]
+: +- Values(tuples=[[{ 0 }]], values=[ZERO], reuse_id=[1]), rowType=[RecordType(INTEGER ZERO)]
+- Calc(select=[3 AS EXPR$0, 4.0:DECIMAL(20, 1) AS EXPR$1]), rowType=[RecordType(INTEGER EXPR$0, DECIMAL(20, 1) EXPR$1)]
- +- Values(tuples=[[{ 0 }]], values=[ZERO]), rowType=[RecordType(INTEGER ZERO)]
+ +- Reused(reference_id=[1]), rowType=[RecordType(INTEGER ZERO)]
]]>
</Resource>
</TestCase>
@@ -76,11 +76,11 @@ LogicalProject(a=[$0], b=[$1])
<![CDATA[
Union(all=[true], union=[EXPR$0, EXPR$1])
:- Calc(select=[1 AS EXPR$0, CAST(2) AS EXPR$1])
-: +- Values(tuples=[[{ 0 }]], values=[ZERO])
+: +- Values(tuples=[[{ 0 }]], values=[ZERO], reuse_id=[1])
:- Calc(select=[3 AS EXPR$0, null:INTEGER AS EXPR$1])
-: +- Values(tuples=[[{ 0 }]], values=[ZERO])
+: +- Reused(reference_id=[1])
+- Calc(select=[4 AS EXPR$0, CAST(5) AS EXPR$1])
- +- Values(tuples=[[{ 0 }]], values=[ZERO])
+ +- Reused(reference_id=[1])
]]>
</Resource>
</TestCase>
diff --git a/flink-table/flink-table-planner-blink/src/test/resources/org/apache/flink/table/plan/batch/sql/agg/GroupingSetsTest.xml b/flink-table/flink-table-planner-blink/src/test/resources/org/apache/flink/table/plan/batch/sql/agg/GroupingSetsTest.xml
index ba55197..ef039af 100644
--- a/flink-table/flink-table-planner-blink/src/test/resources/org/apache/flink/table/plan/batch/sql/agg/GroupingSetsTest.xml
+++ b/flink-table/flink-table-planner-blink/src/test/resources/org/apache/flink/table/plan/batch/sql/agg/GroupingSetsTest.xml
@@ -408,19 +408,16 @@ LogicalSort(sort0=[$0], sort1=[$1], sort2=[$2], dir0=[ASC-nulls-first], dir1=[AS
</Resource>
<Resource name="planAfter">
<![CDATA[
-SortLimit(orderBy=[deptno ASC, job ASC, empno ASC], offset=[0], fetch=[200], global=[true])
-+- Exchange(distribution=[single])
- +- SortLimit(orderBy=[deptno ASC, job ASC, empno ASC], offset=[0], fetch=[200], global=[false])
- +- Calc(select=[deptno, job, empno, ename, sumsal, CASE(=(CASE(=($e, 0:BIGINT), 0:BIGINT, =($e, 3:BIGINT), 1:BIGINT, =($e, 7:BIGINT), 3:BIGINT, 7:BIGINT), 0:BIGINT), _UTF-16LE'grouped by deptno,job,empno,ename':VARCHAR(65536) CHARACTER SET "UTF-16LE", =(CASE(=($e, 0:BIGINT), 0:BIGINT, =($e, 3:BIGINT), 1:BIGINT, =($e, 7:BIGINT), 3:BIGINT, 7:BIGINT), 1:BIGINT), _UTF-16LE'grouped by deptno,job':VARCHAR(65536) CHARACTER SET "UTF-16LE", =(CASE(=($e, 0:BIGINT), 0:BIGINT, =($e, 3:BIGINT), [...]
- +- SortLimit(orderBy=[deptno ASC, job ASC, empno ASC], offset=[0], fetch=[200], global=[true])
- +- Exchange(distribution=[single])
- +- SortLimit(orderBy=[deptno ASC, job ASC, empno ASC], offset=[0], fetch=[200], global=[false])
- +- HashAggregate(isMerge=[true], groupBy=[deptno, job, empno, ename, $e], select=[deptno, job, empno, ename, $e, Final_SUM(sum$0) AS sumsal])
- +- Exchange(distribution=[hash[deptno, job, empno, ename, $e]])
- +- LocalHashAggregate(groupBy=[deptno, job, empno, ename, $e], select=[deptno, job, empno, ename, $e, Partial_SUM(sal) AS sum$0])
- +- Expand(projects=[{deptno=[$0], job=[$1], empno=[$2], ename=[$3], sal=[$4], $e=[0]}, {deptno=[$0], job=[$1], empno=[null], ename=[null], sal=[$4], $e=[3]}, {deptno=[$0], job=[null], empno=[null], ename=[null], sal=[$4], $e=[7]}, {deptno=[null], job=[null], empno=[null], ename=[null], sal=[$4], $e=[15]}], projects=[{deptno, job, empno, ename, sal, 0 AS $e}, {deptno, job, null AS empno, null AS ename, sal, 3 AS $e}, {deptno, null AS job, null AS empno, null AS [...]
- +- Calc(select=[deptno, job, empno, ename, sal])
- +- TableSourceScan(table=[[scott_emp, source: [TestTableSource(empno, ename, job, mgr, hiredate, sal, comm, deptno)]]], fields=[empno, ename, job, mgr, hiredate, sal, comm, deptno])
+Calc(select=[deptno, job, empno, ename, sumsal, CASE(=(CASE(=($e, 0:BIGINT), 0:BIGINT, =($e, 3:BIGINT), 1:BIGINT, =($e, 7:BIGINT), 3:BIGINT, 7:BIGINT), 0:BIGINT), _UTF-16LE'grouped by deptno,job,empno,ename':VARCHAR(65536) CHARACTER SET "UTF-16LE", =(CASE(=($e, 0:BIGINT), 0:BIGINT, =($e, 3:BIGINT), 1:BIGINT, =($e, 7:BIGINT), 3:BIGINT, 7:BIGINT), 1:BIGINT), _UTF-16LE'grouped by deptno,job':VARCHAR(65536) CHARACTER SET "UTF-16LE", =(CASE(=($e, 0:BIGINT), 0:BIGINT, =($e, 3:BIGINT), 1:BIGINT [...]
++- SortLimit(orderBy=[deptno ASC, job ASC, empno ASC], offset=[0], fetch=[200], global=[true])
+ +- Exchange(distribution=[single])
+ +- SortLimit(orderBy=[deptno ASC, job ASC, empno ASC], offset=[0], fetch=[200], global=[false])
+ +- HashAggregate(isMerge=[true], groupBy=[deptno, job, empno, ename, $e], select=[deptno, job, empno, ename, $e, Final_SUM(sum$0) AS sumsal])
+ +- Exchange(distribution=[hash[deptno, job, empno, ename, $e]])
+ +- LocalHashAggregate(groupBy=[deptno, job, empno, ename, $e], select=[deptno, job, empno, ename, $e, Partial_SUM(sal) AS sum$0])
+ +- Expand(projects=[{deptno=[$0], job=[$1], empno=[$2], ename=[$3], sal=[$4], $e=[0]}, {deptno=[$0], job=[$1], empno=[null], ename=[null], sal=[$4], $e=[3]}, {deptno=[$0], job=[null], empno=[null], ename=[null], sal=[$4], $e=[7]}, {deptno=[null], job=[null], empno=[null], ename=[null], sal=[$4], $e=[15]}], projects=[{deptno, job, empno, ename, sal, 0 AS $e}, {deptno, job, null AS empno, null AS ename, sal, 3 AS $e}, {deptno, null AS job, null AS empno, null AS ename, sa [...]
+ +- Calc(select=[deptno, job, empno, ename, sal])
+ +- TableSourceScan(table=[[scott_emp, source: [TestTableSource(empno, ename, job, mgr, hiredate, sal, comm, deptno)]]], fields=[empno, ename, job, mgr, hiredate, sal, comm, deptno])
]]>
</Resource>
</TestCase>
@@ -953,10 +950,10 @@ LogicalSort(sort0=[$1], dir0=[DESC-nulls-last])
</Resource>
<Resource name="planAfter">
<![CDATA[
-SortLimit(orderBy=[c DESC], offset=[0], fetch=[200], global=[true])
-+- Exchange(distribution=[single])
- +- SortLimit(orderBy=[c DESC], offset=[0], fetch=[200], global=[false])
- +- Calc(select=[gender, c])
+Calc(select=[gender, c])
++- SortLimit(orderBy=[c DESC], offset=[0], fetch=[200], global=[true])
+ +- Exchange(distribution=[single])
+ +- SortLimit(orderBy=[c DESC], offset=[0], fetch=[200], global=[false])
+- HashAggregate(isMerge=[true], groupBy=[gender, $e], select=[gender, $e, Final_COUNT(count1$0) AS c])
+- Exchange(distribution=[hash[gender, $e]])
+- LocalHashAggregate(groupBy=[gender, $e], select=[gender, $e, Partial_COUNT(*) AS count1$0])
diff --git a/flink-table/flink-table-planner-blink/src/test/resources/org/apache/flink/table/plan/batch/sql/join/SingleRowJoinTest.xml b/flink-table/flink-table-planner-blink/src/test/resources/org/apache/flink/table/plan/batch/sql/join/SingleRowJoinTest.xml
index 68ae111..2c18a65 100644
--- a/flink-table/flink-table-planner-blink/src/test/resources/org/apache/flink/table/plan/batch/sql/join/SingleRowJoinTest.xml
+++ b/flink-table/flink-table-planner-blink/src/test/resources/org/apache/flink/table/plan/batch/sql/join/SingleRowJoinTest.xml
@@ -35,13 +35,14 @@ LogicalProject(a1=[$0], a2=[$1])
<![CDATA[
Calc(select=[a1, a2])
+- NestedLoopJoin(joinType=[InnerJoin], where=[<(a1, cnt)], select=[a1, a2, cnt], build=[right], singleRowJoin=[true])
- :- TableSourceScan(table=[[A, source: [TestTableSource(a1, a2)]]], fields=[a1, a2])
+ :- Exchange(distribution=[any], exchange_mode=[BATCH])
+ : +- TableSourceScan(table=[[A, source: [TestTableSource(a1, a2)]]], fields=[a1, a2], reuse_id=[1])
+- Exchange(distribution=[broadcast])
+- HashAggregate(isMerge=[true], select=[Final_COUNT(count$0) AS cnt])
+- Exchange(distribution=[single])
+- LocalHashAggregate(select=[Partial_COUNT(a1) AS count$0])
+- Calc(select=[a1])
- +- TableSourceScan(table=[[A, source: [TestTableSource(a1, a2)]]], fields=[a1, a2])
+ +- Reused(reference_id=[1])
]]>
</Resource>
</TestCase>
@@ -147,14 +148,15 @@ LogicalProject(a1=[$0], a_sum=[$2])
<Resource name="planAfter">
<![CDATA[
NestedLoopJoin(joinType=[InnerJoin], where=[true], select=[a1, a_sum], build=[right], singleRowJoin=[true])
-:- Calc(select=[a1])
-: +- TableSourceScan(table=[[A, source: [TestTableSource(a1, a2)]]], fields=[a1, a2])
+:- Exchange(distribution=[any], exchange_mode=[BATCH])
+: +- Calc(select=[a1])
+: +- TableSourceScan(table=[[A, source: [TestTableSource(a1, a2)]]], fields=[a1, a2], reuse_id=[1])
+- Exchange(distribution=[broadcast])
+- Calc(select=[+($f0, $f1) AS a_sum])
+- HashAggregate(isMerge=[true], select=[Final_SUM(sum$0) AS $f0, Final_SUM(sum$1) AS $f1])
+- Exchange(distribution=[single])
+- LocalHashAggregate(select=[Partial_SUM(a1) AS sum$0, Partial_SUM(a2) AS sum$1])
- +- TableSourceScan(table=[[A, source: [TestTableSource(a1, a2)]]], fields=[a1, a2])
+ +- Reused(reference_id=[1])
]]>
</Resource>
</TestCase>
@@ -206,13 +208,14 @@ LogicalProject(a1=[$0], a2=[$1])
<![CDATA[
Calc(select=[a1, a2])
+- NestedLoopJoin(joinType=[InnerJoin], where=[=(CAST(a1), cnt)], select=[a1, a2, cnt], build=[right], singleRowJoin=[true])
- :- TableSourceScan(table=[[A, source: [TestTableSource(a1, a2)]]], fields=[a1, a2])
+ :- Exchange(distribution=[any], exchange_mode=[BATCH])
+ : +- TableSourceScan(table=[[A, source: [TestTableSource(a1, a2)]]], fields=[a1, a2], reuse_id=[1])
+- Exchange(distribution=[broadcast])
+- HashAggregate(isMerge=[true], select=[Final_COUNT(count$0) AS cnt])
+- Exchange(distribution=[single])
+- LocalHashAggregate(select=[Partial_COUNT(a1) AS count$0])
+- Calc(select=[a1])
- +- TableSourceScan(table=[[A, source: [TestTableSource(a1, a2)]]], fields=[a1, a2])
+ +- Reused(reference_id=[1])
]]>
</Resource>
</TestCase>
@@ -271,7 +274,7 @@ Calc(select=[a2, EXPR$1])
:- HashAggregate(isMerge=[true], groupBy=[a2], select=[a2, Final_SUM(sum$0) AS EXPR$1])
: +- Exchange(distribution=[hash[a2]])
: +- LocalHashAggregate(groupBy=[a2], select=[a2, Partial_SUM(a1) AS sum$0])
- : +- TableSourceScan(table=[[A, source: [TestTableSource(a1, a2)]]], fields=[a1, a2])
+ : +- TableSourceScan(table=[[A, source: [TestTableSource(a1, a2)]]], fields=[a1, a2], reuse_id=[1])
+- Exchange(distribution=[broadcast])
+- HashAggregate(isMerge=[true], select=[Final_SINGLE_VALUE(value$0, count$1) AS $f0])
+- Exchange(distribution=[single])
@@ -281,7 +284,7 @@ Calc(select=[a2, EXPR$1])
+- Exchange(distribution=[single])
+- LocalHashAggregate(select=[Partial_SUM(a1) AS sum$0])
+- Calc(select=[a1])
- +- TableSourceScan(table=[[A, source: [TestTableSource(a1, a2)]]], fields=[a1, a2])
+ +- Reused(reference_id=[1])
]]>
</Resource>
</TestCase>
diff --git a/flink-table/flink-table-planner-blink/src/test/resources/org/apache/flink/table/plan/stream/sql/SubplanReuseTest.xml b/flink-table/flink-table-planner-blink/src/test/resources/org/apache/flink/table/plan/stream/sql/SubplanReuseTest.xml
new file mode 100644
index 0000000..0b5d42c
--- /dev/null
+++ b/flink-table/flink-table-planner-blink/src/test/resources/org/apache/flink/table/plan/stream/sql/SubplanReuseTest.xml
@@ -0,0 +1,646 @@
+<?xml version="1.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.
+-->
+<Root>
+ <TestCase name="testSubplanReuseOnCalcWithNonDeterministicUdf">
+ <Resource name="sql">
+ <![CDATA[
+(SELECT a FROM x WHERE b > random_udf(a))
+UNION ALL
+(SELECT a FROM x WHERE b > random_udf(a))
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalUnion(all=[true])
+:- LogicalProject(a=[$0])
+: +- LogicalFilter(condition=[>($1, random_udf($0))])
+: +- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
++- LogicalProject(a=[$0])
+ +- LogicalFilter(condition=[>($1, random_udf($0))])
+ +- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Union(all=[true], union=[a])
+:- Calc(select=[a], where=[>(b, random_udf(a))], reuse_id=[1])
+: +- TableSourceScan(table=[[x, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
++- Reused(reference_id=[1])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testDisableReuseTableSource">
+ <Resource name="sql">
+ <![CDATA[
+WITH t AS (SELECT * FROM x, y WHERE x.a = y.d)
+SELECT t1.*, t2.* FROM t t1, t t2 WHERE t1.b = t2.e AND t1.a < 10 AND t2.a > 5
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0], b=[$1], c=[$2], d=[$3], e=[$4], f=[$5], a0=[$6], b0=[$7], c0=[$8], d0=[$9], e0=[$10], f0=[$11])
++- LogicalFilter(condition=[AND(=($1, $10), <($0, 10), >($6, 5))])
+ +- LogicalJoin(condition=[true], joinType=[inner])
+ :- LogicalProject(a=[$0], b=[$1], c=[$2], d=[$3], e=[$4], f=[$5])
+ : +- LogicalFilter(condition=[=($0, $3)])
+ : +- LogicalJoin(condition=[true], joinType=[inner])
+ : :- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+ : +- LogicalTableScan(table=[[y, source: [TestTableSource(d, e, f)]]])
+ +- LogicalProject(a=[$0], b=[$1], c=[$2], d=[$3], e=[$4], f=[$5])
+ +- LogicalFilter(condition=[=($0, $3)])
+ +- LogicalJoin(condition=[true], joinType=[inner])
+ :- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+ +- LogicalTableScan(table=[[y, source: [TestTableSource(d, e, f)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Join(joinType=[InnerJoin], where=[=(b, e0)], select=[a, b, c, d, e, f, a0, b0, c0, d0, e0, f0])
+:- Exchange(distribution=[hash[b]])
+: +- Join(joinType=[InnerJoin], where=[=(a, d)], select=[a, b, c, d, e, f])
+: :- Exchange(distribution=[hash[a]])
+: : +- Calc(select=[a, b, c], where=[<(a, 10)])
+: : +- TableSourceScan(table=[[x, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
+: +- Exchange(distribution=[hash[d]])
+: +- TableSourceScan(table=[[y, source: [TestTableSource(d, e, f)]]], fields=[d, e, f])
++- Exchange(distribution=[hash[e]])
+ +- Join(joinType=[InnerJoin], where=[=(a, d)], select=[a, b, c, d, e, f])
+ :- Exchange(distribution=[hash[a]])
+ : +- Calc(select=[a, b, c], where=[>(a, 5)])
+ : +- TableSourceScan(table=[[x, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
+ +- Exchange(distribution=[hash[d]])
+ +- TableSourceScan(table=[[y, source: [TestTableSource(d, e, f)]]], fields=[d, e, f])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testEnableReuseTableSource">
+ <Resource name="sql">
+ <![CDATA[
+WITH t AS (SELECT x.a AS a, x.b AS b, y.d AS d, y.e AS e FROM x, y WHERE x.a = y.d)
+SELECT t1.*, t2.* FROM t t1, t t2 WHERE t1.b = t2.e AND t1.a < 10 AND t2.a > 5
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0], b=[$1], d=[$2], e=[$3], a0=[$4], b0=[$5], d0=[$6], e0=[$7])
++- LogicalFilter(condition=[AND(=($1, $7), <($0, 10), >($4, 5))])
+ +- LogicalJoin(condition=[true], joinType=[inner])
+ :- LogicalProject(a=[$0], b=[$1], d=[$3], e=[$4])
+ : +- LogicalFilter(condition=[=($0, $3)])
+ : +- LogicalJoin(condition=[true], joinType=[inner])
+ : :- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+ : +- LogicalTableScan(table=[[y, source: [TestTableSource(d, e, f)]]])
+ +- LogicalProject(a=[$0], b=[$1], d=[$3], e=[$4])
+ +- LogicalFilter(condition=[=($0, $3)])
+ +- LogicalJoin(condition=[true], joinType=[inner])
+ :- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+ +- LogicalTableScan(table=[[y, source: [TestTableSource(d, e, f)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Join(joinType=[InnerJoin], where=[=(b, e0)], select=[a, b, d, e, a0, b0, d0, e0])
+:- Exchange(distribution=[hash[b]])
+: +- Join(joinType=[InnerJoin], where=[=(a, d)], select=[a, b, d, e])
+: :- Exchange(distribution=[hash[a]])
+: : +- Calc(select=[a, b], where=[<(a, 10)])
+: : +- TableSourceScan(table=[[x, source: [TestTableSource(a, b, c)]]], fields=[a, b, c], reuse_id=[1])
+: +- Exchange(distribution=[hash[d]], reuse_id=[2])
+: +- Calc(select=[d, e])
+: +- TableSourceScan(table=[[y, source: [TestTableSource(d, e, f)]]], fields=[d, e, f])
++- Exchange(distribution=[hash[e]])
+ +- Join(joinType=[InnerJoin], where=[=(a, d)], select=[a, b, d, e])
+ :- Exchange(distribution=[hash[a]])
+ : +- Calc(select=[a, b], where=[>(a, 5)])
+ : +- Reused(reference_id=[1])
+ +- Reused(reference_id=[2])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSubplanReuseOnAggregateWithNonDeterministicAggCall">
+ <Resource name="sql">
+ <![CDATA[
+WITH r AS (SELECT c, MyFirst(a) a, MyLast(b) b FROM x GROUP BY c)
+SELECT * FROM r r1, r r2 WHERE r1.a = r2.b AND r2.a > 1
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(c=[$0], a=[$1], b=[$2], c0=[$3], a0=[$4], b0=[$5])
++- LogicalFilter(condition=[AND(=(CAST($1):BIGINT, $5), >($4, 1))])
+ +- LogicalJoin(condition=[true], joinType=[inner])
+ :- LogicalAggregate(group=[{0}], a=[MyFirst($1)], b=[MyLast($2)])
+ : +- LogicalProject(c=[$2], a=[$0], b=[$1])
+ : +- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+ +- LogicalAggregate(group=[{0}], a=[MyFirst($1)], b=[MyLast($2)])
+ +- LogicalProject(c=[$2], a=[$0], b=[$1])
+ +- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Join(joinType=[InnerJoin], where=[=(CAST(a), b0)], select=[c, a, b, c0, a0, b0])
+:- Exchange(distribution=[single])
+: +- GroupAggregate(groupBy=[c], select=[c, MyFirst(a) AS a, MyLast(b) AS b], reuse_id=[1])
+: +- Exchange(distribution=[hash[c]])
+: +- TableSourceScan(table=[[x, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
++- Exchange(distribution=[single])
+ +- Calc(select=[c, a, b], where=[>(a, 1)])
+ +- Reused(reference_id=[1])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSubplanReuseOnCalc">
+ <Resource name="sql">
+ <![CDATA[
+WITH r AS (SELECT a, b, c FROM x WHERE c LIKE 'test%')
+(SELECT r.a, LOWER(c) AS c, y.e FROM r, y WHERE r.a = y.d)
+UNION ALL
+(SELECT r.a, LOWER(c) AS c, y.e FROM r, y WHERE r.a = y.d)
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalUnion(all=[true])
+:- LogicalProject(a=[$0], c=[LOWER($2)], e=[$4])
+: +- LogicalFilter(condition=[=($0, $3)])
+: +- LogicalJoin(condition=[true], joinType=[inner])
+: :- LogicalProject(a=[$0], b=[$1], c=[$2])
+: : +- LogicalFilter(condition=[LIKE($2, _UTF-16LE'test%')])
+: : +- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+: +- LogicalTableScan(table=[[y, source: [TestTableSource(d, e, f)]]])
++- LogicalProject(a=[$0], c=[LOWER($2)], e=[$4])
+ +- LogicalFilter(condition=[=($0, $3)])
+ +- LogicalJoin(condition=[true], joinType=[inner])
+ :- LogicalProject(a=[$0], b=[$1], c=[$2])
+ : +- LogicalFilter(condition=[LIKE($2, _UTF-16LE'test%')])
+ : +- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+ +- LogicalTableScan(table=[[y, source: [TestTableSource(d, e, f)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Union(all=[true], union=[a, c, e])
+:- Calc(select=[a, LOWER(c) AS c, e], reuse_id=[1])
+: +- Join(joinType=[InnerJoin], where=[=(a, d)], select=[a, c, d, e])
+: :- Exchange(distribution=[hash[a]])
+: : +- Calc(select=[a, c], where=[LIKE(c, _UTF-16LE'test%')])
+: : +- TableSourceScan(table=[[x, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
+: +- Exchange(distribution=[hash[d]])
+: +- Calc(select=[d, e])
+: +- TableSourceScan(table=[[y, source: [TestTableSource(d, e, f)]]], fields=[d, e, f])
++- Reused(reference_id=[1])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSubplanReuseOnCalcWithNonDeterministicProject">
+ <Resource name="sql">
+ <![CDATA[
+(SELECT a, random_udf() FROM x WHERE a > 10)
+UNION ALL
+(SELECT a, random_udf() FROM x WHERE a > 10)
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalUnion(all=[true])
+:- LogicalProject(a=[$0], EXPR$1=[random_udf()])
+: +- LogicalFilter(condition=[>($0, 10)])
+: +- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
++- LogicalProject(a=[$0], EXPR$1=[random_udf()])
+ +- LogicalFilter(condition=[>($0, 10)])
+ +- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Union(all=[true], union=[a, EXPR$1])
+:- Calc(select=[a, random_udf() AS EXPR$1], where=[>(a, 10)], reuse_id=[1])
+: +- TableSourceScan(table=[[x, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
++- Reused(reference_id=[1])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSubplanReuseOnCorrelate">
+ <Resource name="sql">
+ <![CDATA[
+WITH r AS (SELECT a, b, c, v FROM x, LATERAL TABLE(str_split(c, '-')) AS T(v))
+SELECT * FROM r r1, r r2 WHERE r1.v = r2.v
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0], b=[$1], c=[$2], v=[$3], a0=[$4], b0=[$5], c0=[$6], v0=[$7])
++- LogicalFilter(condition=[=($3, $7)])
+ +- LogicalJoin(condition=[true], joinType=[inner])
+ :- LogicalProject(a=[$0], b=[$1], c=[$2], v=[$3])
+ : +- LogicalCorrelate(correlation=[$cor0], joinType=[inner], requiredColumns=[{2}])
+ : :- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+ : +- LogicalTableFunctionScan(invocation=[str_split($cor0.c, _UTF-16LE'-')], rowType=[RecordType(VARCHAR(65536) f0)], elementType=[class [Ljava.lang.Object;])
+ +- LogicalProject(a=[$0], b=[$1], c=[$2], v=[$3])
+ +- LogicalCorrelate(correlation=[$cor1], joinType=[inner], requiredColumns=[{2}])
+ :- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+ +- LogicalTableFunctionScan(invocation=[str_split($cor1.c, _UTF-16LE'-')], rowType=[RecordType(VARCHAR(65536) f0)], elementType=[class [Ljava.lang.Object;])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Join(joinType=[InnerJoin], where=[=(f0, f00)], select=[a, b, c, f0, a0, b0, c0, f00])
+:- Exchange(distribution=[hash[f0]])
+: +- Correlate(invocation=[str_split($cor0.c, _UTF-16LE'-')], correlate=[table(str_split($cor0.c,_UTF-16LE'-'))], select=[a,b,c,f0], rowType=[RecordType(INTEGER a, BIGINT b, VARCHAR(65536) c, VARCHAR(65536) f0)], joinType=[INNER])
+: +- TableSourceScan(table=[[x, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
++- Exchange(distribution=[hash[f0]])
+ +- Correlate(invocation=[str_split($cor1.c, _UTF-16LE'-')], correlate=[table(str_split($cor1.c,_UTF-16LE'-'))], select=[a,b,c,f0], rowType=[RecordType(INTEGER a, BIGINT b, VARCHAR(65536) c, VARCHAR(65536) f0)], joinType=[INNER])
+ +- TableSourceScan(table=[[x, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSubplanReuseOnCorrelateWithNonDeterministicUDTF">
+ <Resource name="sql">
+ <![CDATA[
+WITH r AS (SELECT a, b, c, s FROM x, LATERAL TABLE(TableFun(c)) AS T(s))
+SELECT * FROM r r1, r r2 WHERE r1.c = r2.s
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0], b=[$1], c=[$2], s=[$3], a0=[$4], b0=[$5], c0=[$6], s0=[$7])
++- LogicalFilter(condition=[=($2, $7)])
+ +- LogicalJoin(condition=[true], joinType=[inner])
+ :- LogicalProject(a=[$0], b=[$1], c=[$2], s=[$3])
+ : +- LogicalCorrelate(correlation=[$cor0], joinType=[inner], requiredColumns=[{2}])
+ : :- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+ : +- LogicalTableFunctionScan(invocation=[TableFun($cor0.c)], rowType=[RecordType(VARCHAR(65536) f0)], elementType=[class [Ljava.lang.Object;])
+ +- LogicalProject(a=[$0], b=[$1], c=[$2], s=[$3])
+ +- LogicalCorrelate(correlation=[$cor1], joinType=[inner], requiredColumns=[{2}])
+ :- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+ +- LogicalTableFunctionScan(invocation=[TableFun($cor1.c)], rowType=[RecordType(VARCHAR(65536) f0)], elementType=[class [Ljava.lang.Object;])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Join(joinType=[InnerJoin], where=[=(c, f00)], select=[a, b, c, f0, a0, b0, c0, f00])
+:- Exchange(distribution=[hash[c]])
+: +- Correlate(invocation=[TableFun($cor0.c)], correlate=[table(TableFun($cor0.c))], select=[a,b,c,f0], rowType=[RecordType(INTEGER a, BIGINT b, VARCHAR(65536) c, VARCHAR(65536) f0)], joinType=[INNER])
+: +- TableSourceScan(table=[[x, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
++- Exchange(distribution=[hash[f0]])
+ +- Correlate(invocation=[TableFun($cor1.c)], correlate=[table(TableFun($cor1.c))], select=[a,b,c,f0], rowType=[RecordType(INTEGER a, BIGINT b, VARCHAR(65536) c, VARCHAR(65536) f0)], joinType=[INNER])
+ +- TableSourceScan(table=[[x, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSubplanReuseOnExchange">
+ <Resource name="sql">
+ <![CDATA[
+WITH r AS (SELECT a, b, c FROM x WHERE c LIKE 'test%')
+SELECT * FROM r, y WHERE a = d AND e > 10
+UNION ALL
+SELECT * FROM r, y WHERE a = d AND f <> ''
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalUnion(all=[true])
+:- LogicalProject(a=[$0], b=[$1], c=[$2], d=[$3], e=[$4], f=[$5])
+: +- LogicalFilter(condition=[AND(=($0, $3), >($4, 10))])
+: +- LogicalJoin(condition=[true], joinType=[inner])
+: :- LogicalProject(a=[$0], b=[$1], c=[$2])
+: : +- LogicalFilter(condition=[LIKE($2, _UTF-16LE'test%')])
+: : +- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+: +- LogicalTableScan(table=[[y, source: [TestTableSource(d, e, f)]]])
++- LogicalProject(a=[$0], b=[$1], c=[$2], d=[$3], e=[$4], f=[$5])
+ +- LogicalFilter(condition=[AND(=($0, $3), <>($5, _UTF-16LE''))])
+ +- LogicalJoin(condition=[true], joinType=[inner])
+ :- LogicalProject(a=[$0], b=[$1], c=[$2])
+ : +- LogicalFilter(condition=[LIKE($2, _UTF-16LE'test%')])
+ : +- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+ +- LogicalTableScan(table=[[y, source: [TestTableSource(d, e, f)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Union(all=[true], union=[a, b, c, d, e, f])
+:- Join(joinType=[InnerJoin], where=[=(a, d)], select=[a, b, c, d, e, f])
+: :- Exchange(distribution=[hash[a]], reuse_id=[1])
+: : +- Calc(select=[a, b, c], where=[LIKE(c, _UTF-16LE'test%')])
+: : +- TableSourceScan(table=[[x, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
+: +- Exchange(distribution=[hash[d]])
+: +- Calc(select=[d, e, f], where=[>(e, 10)])
+: +- TableSourceScan(table=[[y, source: [TestTableSource(d, e, f)]]], fields=[d, e, f])
++- Join(joinType=[InnerJoin], where=[=(a, d)], select=[a, b, c, d, e, f])
+ :- Reused(reference_id=[1])
+ +- Exchange(distribution=[hash[d]])
+ +- Calc(select=[d, e, f], where=[<>(f, _UTF-16LE'':VARCHAR(65536) CHARACTER SET "UTF-16LE")])
+ +- TableSourceScan(table=[[y, source: [TestTableSource(d, e, f)]]], fields=[d, e, f])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSubplanReuseOnGroupAggregate">
+ <Resource name="sql">
+ <![CDATA[
+WITH r AS (SELECT c, SUM(a) a, SUM(b) b FROM x GROUP BY c)
+SELECT * FROM r r1, r r2 WHERE r1.a = r2.b AND r2.a > 1
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(c=[$0], a=[$1], b=[$2], c0=[$3], a0=[$4], b0=[$5])
++- LogicalFilter(condition=[AND(=(CAST($1):BIGINT, $5), >($4, 1))])
+ +- LogicalJoin(condition=[true], joinType=[inner])
+ :- LogicalAggregate(group=[{0}], a=[SUM($1)], b=[SUM($2)])
+ : +- LogicalProject(c=[$2], a=[$0], b=[$1])
+ : +- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+ +- LogicalAggregate(group=[{0}], a=[SUM($1)], b=[SUM($2)])
+ +- LogicalProject(c=[$2], a=[$0], b=[$1])
+ +- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Join(joinType=[InnerJoin], where=[=(CAST(a), b0)], select=[c, a, b, c0, a0, b0])
+:- Exchange(distribution=[single])
+: +- GroupAggregate(groupBy=[c], select=[c, SUM(a) AS a, SUM(b) AS b], reuse_id=[1])
+: +- Exchange(distribution=[hash[c]])
+: +- TableSourceScan(table=[[x, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
++- Exchange(distribution=[single])
+ +- Calc(select=[c, a, b], where=[>(a, 1)])
+ +- Reused(reference_id=[1])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSubplanReuseOnJoin">
+ <Resource name="sql">
+ <![CDATA[
+WITH r AS (SELECT * FROM x FULL OUTER JOIN y ON ABS(a) = ABS(d) OR c = f
+ WHERE b > 1 and e < 2)
+
+SELECT a, b FROM r
+UNION ALL
+SELECT a, b * 2 AS b FROM r
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalUnion(all=[true])
+:- LogicalProject(a=[$0], b=[$1])
+: +- LogicalFilter(condition=[AND(>($1, 1), <($4, 2))])
+: +- LogicalJoin(condition=[OR(=(ABS($0), ABS($3)), =($2, $5))], joinType=[full])
+: :- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+: +- LogicalTableScan(table=[[y, source: [TestTableSource(d, e, f)]]])
++- LogicalProject(a=[$0], b=[*($1, 2)])
+ +- LogicalFilter(condition=[AND(>($1, 1), <($4, 2))])
+ +- LogicalJoin(condition=[OR(=(ABS($0), ABS($3)), =($2, $5))], joinType=[full])
+ :- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+ +- LogicalTableScan(table=[[y, source: [TestTableSource(d, e, f)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Union(all=[true], union=[a, b])
+:- Calc(select=[a, b])
+: +- Join(joinType=[InnerJoin], where=[OR(=(ABS(a), ABS(d)), =(c, f))], select=[a, b, c, d, f], reuse_id=[1])
+: :- Exchange(distribution=[single])
+: : +- Calc(select=[a, b, c], where=[>(b, 1)])
+: : +- TableSourceScan(table=[[x, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
+: +- Exchange(distribution=[single])
+: +- Calc(select=[d, f], where=[<(e, 2)])
+: +- TableSourceScan(table=[[y, source: [TestTableSource(d, e, f)]]], fields=[d, e, f])
++- Calc(select=[a, *(b, 2) AS b])
+ +- Reused(reference_id=[1])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSubplanReuseOnJoinNonDeterministicJoinCondition">
+ <Resource name="sql">
+ <![CDATA[
+WITH r AS (SELECT * FROM x FULL OUTER JOIN y ON random_udf(a) = random_udf(d) OR c = f
+ WHERE b > 1 and e < 2)
+
+SELECT a, b FROM r
+UNION ALL
+SELECT a, b * 2 AS b FROM r
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalUnion(all=[true])
+:- LogicalProject(a=[$0], b=[$1])
+: +- LogicalFilter(condition=[AND(>($1, 1), <($4, 2))])
+: +- LogicalJoin(condition=[OR(=(random_udf($0), random_udf($3)), =($2, $5))], joinType=[full])
+: :- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+: +- LogicalTableScan(table=[[y, source: [TestTableSource(d, e, f)]]])
++- LogicalProject(a=[$0], b=[*($1, 2)])
+ +- LogicalFilter(condition=[AND(>($1, 1), <($4, 2))])
+ +- LogicalJoin(condition=[OR(=(random_udf($0), random_udf($3)), =($2, $5))], joinType=[full])
+ :- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+ +- LogicalTableScan(table=[[y, source: [TestTableSource(d, e, f)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Union(all=[true], union=[a, b])
+:- Calc(select=[a, b])
+: +- Join(joinType=[InnerJoin], where=[OR(=(random_udf(a), random_udf(d)), =(c, f))], select=[a, b, c, d, f], reuse_id=[1])
+: :- Exchange(distribution=[single])
+: : +- Calc(select=[a, b, c], where=[>(b, 1)])
+: : +- TableSourceScan(table=[[x, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
+: +- Exchange(distribution=[single])
+: +- Calc(select=[d, f], where=[<(e, 2)])
+: +- TableSourceScan(table=[[y, source: [TestTableSource(d, e, f)]]], fields=[d, e, f])
++- Calc(select=[a, *(b, 2) AS b])
+ +- Reused(reference_id=[1])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSubplanReuseOnOverWindow">
+ <Resource name="sql">
+ <![CDATA[
+WITH r AS (SELECT a, b, RANK() OVER (ORDER BY c DESC) FROM x)
+SELECT * FROM r r1, r r2 WHERE r1.a = r2.a AND r1.b < 100 AND r2.b > 10
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0], b=[$1], EXPR$2=[$2], a0=[$3], b0=[$4], EXPR$20=[$5])
++- LogicalFilter(condition=[AND(=($0, $3), <($1, 100), >($4, 10))])
+ +- LogicalJoin(condition=[true], joinType=[inner])
+ :- LogicalProject(a=[$0], b=[$1], EXPR$2=[RANK() OVER (ORDER BY $2 DESC NULLS LAST RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)])
+ : +- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+ +- LogicalProject(a=[$0], b=[$1], EXPR$2=[RANK() OVER (ORDER BY $2 DESC NULLS LAST RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)])
+ +- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Join(joinType=[InnerJoin], where=[=(a, a0)], select=[a, b, $2, a0, b0, w0$o0])
+:- Exchange(distribution=[hash[a]])
+: +- Calc(select=[a, b, w0$o0 AS $2], where=[<(b, 100)])
+: +- OverAggregate(orderBy=[c DESC], window=[ RANG BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW], select=[a, b, c, RANK(*) AS w0$o0], reuse_id=[1])
+: +- Exchange(distribution=[single])
+: +- TableSourceScan(table=[[x, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
++- Exchange(distribution=[hash[a]])
+ +- Calc(select=[a, b, w0$o0], where=[>(b, 10)])
+ +- Reused(reference_id=[1])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSubplanReuseOnLimit">
+ <Resource name="sql">
+ <![CDATA[
+WITH r AS (SELECT a, b FROM x LIMIT 10)
+
+SELECT a, b FROM r WHERE a > 10
+UNION ALL
+SELECT a, b * 2 AS b FROM r WHERE b < 10
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalUnion(all=[true])
+:- LogicalProject(a=[$0], b=[$1])
+: +- LogicalFilter(condition=[>($0, 10)])
+: +- LogicalSort(fetch=[10])
+: +- LogicalProject(a=[$0], b=[$1])
+: +- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
++- LogicalProject(a=[$0], b=[*($1, 2)])
+ +- LogicalFilter(condition=[<($1, 10)])
+ +- LogicalSort(fetch=[10])
+ +- LogicalProject(a=[$0], b=[$1])
+ +- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Union(all=[true], union=[a, b])
+:- Calc(select=[a, b], where=[>(a, 10)])
+: +- Limit(offset=[0], fetch=[10], reuse_id=[1])
+: +- Exchange(distribution=[single])
+: +- TableSourceScan(table=[[x, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
++- Calc(select=[a, *(b, 2) AS b], where=[<(b, 10)])
+ +- Reused(reference_id=[1])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSubplanReuseOnOverWindowWithNonDeterministicAggCall">
+ <Resource name="sql">
+ <![CDATA[
+WITH r AS (SELECT a, b, MyFirst(c) OVER (PARTITION BY c ORDER BY c DESC) FROM x)
+SELECT * FROM r r1, r r2 WHERE r1.a = r2.a AND r1.b < 100 AND r2.b > 10
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0], b=[$1], EXPR$2=[$2], a0=[$3], b0=[$4], EXPR$20=[$5])
++- LogicalFilter(condition=[AND(=($0, $3), <($1, 100), >($4, 10))])
+ +- LogicalJoin(condition=[true], joinType=[inner])
+ :- LogicalProject(a=[$0], b=[$1], EXPR$2=[MyFirst($2) OVER (PARTITION BY $2 ORDER BY $2 DESC NULLS LAST RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)])
+ : +- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+ +- LogicalProject(a=[$0], b=[$1], EXPR$2=[MyFirst($2) OVER (PARTITION BY $2 ORDER BY $2 DESC NULLS LAST RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)])
+ +- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Join(joinType=[InnerJoin], where=[=(a, a0)], select=[a, b, $2, a0, b0, w0$o0])
+:- Exchange(distribution=[hash[a]])
+: +- Calc(select=[a, b, w0$o0 AS $2], where=[<(b, 100)])
+: +- OverAggregate(partitionBy=[c], orderBy=[c DESC], window=[ RANG BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW], select=[a, b, c, MyFirst(c) AS w0$o0], reuse_id=[1])
+: +- Exchange(distribution=[hash[c]])
+: +- TableSourceScan(table=[[x, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
++- Exchange(distribution=[hash[a]])
+ +- Calc(select=[a, b, w0$o0], where=[>(b, 10)])
+ +- Reused(reference_id=[1])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSubplanReuseOnSort">
+ <Resource name="sql">
+ <![CDATA[
+WITH r AS (SELECT c, SUM(a) a, SUM(b) b FROM x GROUP BY c ORDER BY a, b DESC)
+SELECT * FROM r r1, r r2 WHERE r1.a = r2.a AND r1.a > 1 AND r2.b < 10
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(c=[$0], a=[$1], b=[$2], c0=[$3], a0=[$4], b0=[$5])
++- LogicalFilter(condition=[AND(=($1, $4), >($1, 1), <($5, 10))])
+ +- LogicalJoin(condition=[true], joinType=[inner])
+ :- LogicalAggregate(group=[{0}], a=[SUM($1)], b=[SUM($2)])
+ : +- LogicalProject(c=[$2], a=[$0], b=[$1])
+ : +- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+ +- LogicalAggregate(group=[{0}], a=[SUM($1)], b=[SUM($2)])
+ +- LogicalProject(c=[$2], a=[$0], b=[$1])
+ +- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Join(joinType=[InnerJoin], where=[=(a, a0)], select=[c, a, b, c0, a0, b0])
+:- Exchange(distribution=[hash[a]])
+: +- Calc(select=[c, a, b], where=[>(a, 1)])
+: +- GroupAggregate(groupBy=[c], select=[c, SUM(a) AS a, SUM(b) AS b], reuse_id=[1])
+: +- Exchange(distribution=[hash[c]])
+: +- TableSourceScan(table=[[x, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
++- Exchange(distribution=[hash[a]])
+ +- Calc(select=[c, a, b], where=[<(b, 10)])
+ +- Reused(reference_id=[1])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSubplanReuseOnSortLimit">
+ <Resource name="sql">
+ <![CDATA[
+WITH r AS (SELECT c, SUM(a) a, SUM(b) b FROM x GROUP BY c ORDER BY a, b DESC LIMIT 10)
+
+SELECT a, b FROM r WHERE a > 10
+UNION ALL
+SELECT a, b * 2 AS b FROM r WHERE b < 10
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalUnion(all=[true])
+:- LogicalProject(a=[$1], b=[$2])
+: +- LogicalFilter(condition=[>($1, 10)])
+: +- LogicalSort(sort0=[$1], sort1=[$2], dir0=[ASC-nulls-first], dir1=[DESC-nulls-last], fetch=[10])
+: +- LogicalAggregate(group=[{0}], a=[SUM($1)], b=[SUM($2)])
+: +- LogicalProject(c=[$2], a=[$0], b=[$1])
+: +- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
++- LogicalProject(a=[$1], b=[*($2, 2)])
+ +- LogicalFilter(condition=[<($2, 10)])
+ +- LogicalSort(sort0=[$1], sort1=[$2], dir0=[ASC-nulls-first], dir1=[DESC-nulls-last], fetch=[10])
+ +- LogicalAggregate(group=[{0}], a=[SUM($1)], b=[SUM($2)])
+ +- LogicalProject(c=[$2], a=[$0], b=[$1])
+ +- LogicalTableScan(table=[[x, source: [TestTableSource(a, b, c)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Union(all=[true], union=[a, b])
+:- Calc(select=[a, b], where=[>(a, 10)])
+: +- SortLimit(orderBy=[a ASC, b DESC], offset=[0], fetch=[10], reuse_id=[1])
+: +- Exchange(distribution=[single])
+: +- GroupAggregate(groupBy=[c], select=[c, SUM(a) AS a, SUM(b) AS b])
+: +- Exchange(distribution=[hash[c]])
+: +- TableSourceScan(table=[[x, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
++- Calc(select=[a, *(b, 2) AS b], where=[<(b, 10)])
+ +- Reused(reference_id=[1])
+]]>
+ </Resource>
+ </TestCase>
+</Root>
diff --git a/flink-table/flink-table-planner-blink/src/test/resources/org/apache/flink/table/plan/stream/sql/ValuesTest.xml b/flink-table/flink-table-planner-blink/src/test/resources/org/apache/flink/table/plan/stream/sql/ValuesTest.xml
index b1e17d4..d2ec0f4 100644
--- a/flink-table/flink-table-planner-blink/src/test/resources/org/apache/flink/table/plan/stream/sql/ValuesTest.xml
+++ b/flink-table/flink-table-planner-blink/src/test/resources/org/apache/flink/table/plan/stream/sql/ValuesTest.xml
@@ -34,9 +34,9 @@ LogicalProject(a=[$0], b=[$1]), rowType=[RecordType(INTEGER a, DECIMAL(20, 1) b)
<![CDATA[
Union(all=[true], union=[EXPR$0, EXPR$1]), rowType=[RecordType(INTEGER EXPR$0, DECIMAL(20, 1) EXPR$1)]
:- Calc(select=[1 AS EXPR$0, 2.0:DECIMAL(20, 1) AS EXPR$1]), rowType=[RecordType(INTEGER EXPR$0, DECIMAL(20, 1) EXPR$1)]
-: +- Values(tuples=[[{ 0 }]]), rowType=[RecordType(INTEGER ZERO)]
+: +- Values(tuples=[[{ 0 }]], reuse_id=[1]), rowType=[RecordType(INTEGER ZERO)]
+- Calc(select=[3 AS EXPR$0, 4.0:DECIMAL(20, 1) AS EXPR$1]), rowType=[RecordType(INTEGER EXPR$0, DECIMAL(20, 1) EXPR$1)]
- +- Values(tuples=[[{ 0 }]]), rowType=[RecordType(INTEGER ZERO)]
+ +- Reused(reference_id=[1]), rowType=[RecordType(INTEGER ZERO)]
]]>
</Resource>
</TestCase>
@@ -76,11 +76,11 @@ LogicalProject(a=[$0], b=[$1])
<![CDATA[
Union(all=[true], union=[EXPR$0, EXPR$1])
:- Calc(select=[1 AS EXPR$0, CAST(2) AS EXPR$1])
-: +- Values(tuples=[[{ 0 }]])
+: +- Values(tuples=[[{ 0 }]], reuse_id=[1])
:- Calc(select=[3 AS EXPR$0, null:INTEGER AS EXPR$1])
-: +- Values(tuples=[[{ 0 }]])
+: +- Reused(reference_id=[1])
+- Calc(select=[4 AS EXPR$0, CAST(5) AS EXPR$1])
- +- Values(tuples=[[{ 0 }]])
+ +- Reused(reference_id=[1])
]]>
</Resource>
</TestCase>
diff --git a/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/plan/batch/sql/DeadlockBreakupTest.scala b/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/plan/batch/sql/DeadlockBreakupTest.scala
new file mode 100644
index 0000000..178d5e0
--- /dev/null
+++ b/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/plan/batch/sql/DeadlockBreakupTest.scala
@@ -0,0 +1,188 @@
+/*
+ * 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.plan.batch.sql
+
+import org.apache.flink.api.scala._
+import org.apache.flink.table.api.{PlannerConfigOptions, TableConfigOptions, ValidationException}
+import org.apache.flink.table.util.TableTestBase
+
+import org.junit.{Before, Test}
+
+class DeadlockBreakupTest extends TableTestBase {
+
+ private val util = batchTestUtil()
+
+ @Before
+ def before(): Unit = {
+ util.addTableSource[(Int, Long, String)]("x", 'a, 'b, 'c)
+ util.addTableSource[(Int, Long, String)]("y", 'd, 'e, 'f)
+ // TODO DataStream as Table is not supported now
+ // util.addDataStream[(Int, Long, String)]("t", 'a, 'b, 'c)
+ }
+
+ @Test
+ def testSubplanReuse_SetExchangeAsBatch(): Unit = {
+ util.tableEnv.getConfig.getConf.setBoolean(
+ PlannerConfigOptions.SQL_OPTIMIZER_REUSE_SUB_PLAN_ENABLED, true)
+ util.tableEnv.getConfig.getConf.setBoolean(
+ PlannerConfigOptions.SQL_OPTIMIZER_REUSE_TABLE_SOURCE_ENABLED, true)
+ val sqlQuery =
+ """
+ |WITH t AS (SELECT x.a AS a, x.b AS b, y.d AS d, y.e AS e FROM x, y WHERE x.a = y.d)
+ |SELECT t1.*, t2.* FROM t t1, t t2 WHERE t1.b = t2.e AND t1.a < 10 AND t2.a > 5
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test
+ def testSubplanReuse_AddExchangeAsBatch_HashJoin(): Unit = {
+ util.tableEnv.getConfig.getConf.setBoolean(
+ PlannerConfigOptions.SQL_OPTIMIZER_REUSE_SUB_PLAN_ENABLED, true)
+ util.tableEnv.getConfig.getConf.setBoolean(
+ PlannerConfigOptions.SQL_OPTIMIZER_REUSE_TABLE_SOURCE_ENABLED, true)
+ util.tableEnv.getConfig.getConf.setString(
+ TableConfigOptions.SQL_EXEC_DISABLED_OPERATORS, "NestedLoopJoin,SortMergeJoin")
+ val sqlQuery =
+ """
+ |WITH r AS (SELECT a FROM x LIMIT 10)
+ |SELECT r1.a FROM r r1, r r2 WHERE r1.a = r2.a
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test
+ def testSubplanReuse_AddExchangeAsBatch_NestedLoopJoin(): Unit = {
+ util.tableEnv.getConfig.getConf.setBoolean(
+ PlannerConfigOptions.SQL_OPTIMIZER_REUSE_SUB_PLAN_ENABLED, true)
+ util.tableEnv.getConfig.getConf.setBoolean(
+ PlannerConfigOptions.SQL_OPTIMIZER_REUSE_TABLE_SOURCE_ENABLED, false)
+ util.tableEnv.getConfig.getConf.setString(
+ TableConfigOptions.SQL_EXEC_DISABLED_OPERATORS, "HashJoin,SortMergeJoin")
+ val sqlQuery =
+ """
+ |WITH r AS (SELECT a FROM x LIMIT 10)
+ |SELECT r1.a FROM r r1, r r2 WHERE r1.a = r2.a
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test
+ def testSubplanReuse_SetExchangeAsBatch_SortMergeJoin(): Unit = {
+ util.tableEnv.getConfig.getConf.setBoolean(
+ PlannerConfigOptions.SQL_OPTIMIZER_REUSE_SUB_PLAN_ENABLED, true)
+ util.tableEnv.getConfig.getConf.setString(
+ TableConfigOptions.SQL_EXEC_DISABLED_OPERATORS, "NestedLoopJoin")
+ util.tableEnv.getConfig.getConf.setLong(
+ PlannerConfigOptions.SQL_OPTIMIZER_HASH_JOIN_BROADCAST_THRESHOLD, -1)
+ val sqlQuery =
+ """
+ |
+ |WITH v1 AS (SELECT a, SUM(b) AS b, MAX(c) AS c FROM x GROUP BY a),
+ | v2 AS (SELECT * FROM v1 r1, v1 r2 WHERE r1.a = r2.a AND r1.b > 10),
+ | v3 AS (SELECT * FROM v1 r1, v1 r2 WHERE r1.a = r2.a AND r1.b < 5)
+ |
+ |select * from v2, v3 where v2.c = v3.c
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test
+ def testSubplanReuse_AddExchangeAsBatch_BuildLeftSemiHashJoin(): Unit = {
+ // TODO re-check the plan after semi-join is supported
+ util.tableEnv.getConfig.getConf.setBoolean(
+ PlannerConfigOptions.SQL_OPTIMIZER_REUSE_SUB_PLAN_ENABLED, true)
+ util.tableEnv.getConfig.getConf.setBoolean(
+ PlannerConfigOptions.SQL_OPTIMIZER_REUSE_TABLE_SOURCE_ENABLED, true)
+ util.tableEnv.getConfig.getConf.setLong(
+ PlannerConfigOptions.SQL_OPTIMIZER_HASH_JOIN_BROADCAST_THRESHOLD, -1)
+ util.tableEnv.getConfig.getConf.setString(
+ TableConfigOptions.SQL_EXEC_DISABLED_OPERATORS, "NestedLoopJoin,SortMergeJoin")
+ val sqlQuery =
+ """
+ |WITH r AS (SELECT a, b FROM x LIMIT 10)
+ |SELECT r1.a, r2.b FROM x r1,
+ |(SELECT a, b FROM r WHERE a in (select a from x where b > 5)) r2
+ |WHERE r1.a = r2.a and r1.b = 5
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test
+ def testSubplanReuse_SetExchangeAsBatch_OverAgg(): Unit = {
+ util.tableEnv.getConfig.getConf.setBoolean(
+ PlannerConfigOptions.SQL_OPTIMIZER_REUSE_SUB_PLAN_ENABLED, true)
+ val sqlQuery =
+ """
+ |WITH r1 AS (SELECT SUM(a) OVER (PARTITION BY b ORDER BY b) AS a, b, c FROM x),
+ | r2 AS (SELECT MAX(a) OVER (PARTITION BY b ORDER BY b
+ | RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS a, b, c FROM r1),
+ | r3 AS (SELECT MIN(a) OVER (PARTITION BY b ORDER BY b
+ | RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS a, b, c FROM r1)
+ |
+ |SELECT * FROM r2, r3 WHERE r2.c = r3.c
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test
+ def testReusedNodeIsBarrierNode(): Unit = {
+ util.tableEnv.getConfig.getConf.setBoolean(
+ PlannerConfigOptions.SQL_OPTIMIZER_REUSE_SUB_PLAN_ENABLED, true)
+ util.tableEnv.getConfig.getConf.setBoolean(
+ PlannerConfigOptions.SQL_OPTIMIZER_REUSE_TABLE_SOURCE_ENABLED, false)
+ util.tableEnv.getConfig.getConf.setString(
+ TableConfigOptions.SQL_EXEC_DISABLED_OPERATORS, "HashJoin,SortMergeJoin")
+ val sqlQuery =
+ """
+ |WITH r AS (SELECT c, SUM(a) a, SUM(b) b FROM x GROUP BY c)
+ | SELECT * FROM r r1, r r2 WHERE r1.a = r2.b AND r2.a > 1
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test(expected = classOf[ValidationException])
+ // TODO DataStream registered as Table is not supported now
+ def testDataStreamReuse_SetExchangeAsBatch(): Unit = {
+ util.tableEnv.getConfig.getConf.setBoolean(
+ PlannerConfigOptions.SQL_OPTIMIZER_REUSE_SUB_PLAN_ENABLED, false)
+ util.tableEnv.getConfig.getConf.setLong(
+ PlannerConfigOptions.SQL_OPTIMIZER_HASH_JOIN_BROADCAST_THRESHOLD, -1)
+ val sqlQuery = "SELECT * FROM t t1, t t2 WHERE t1.a = t2.a AND t1.b > 10 AND t2.c LIKE 'Test%'"
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test(expected = classOf[ValidationException])
+ // TODO DataStream registered as Table is not supported now
+ def testDataStreamReuse_AddExchangeAsBatch_NestedLoopJoin(): Unit = {
+ util.tableEnv.getConfig.getConf.setBoolean(
+ PlannerConfigOptions.SQL_OPTIMIZER_REUSE_SUB_PLAN_ENABLED, false)
+ val sqlQuery = "SELECT * FROM t t1, t t2 WHERE t1.a = t2.b"
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test(expected = classOf[ValidationException])
+ // TODO DataStream registered as Table is not supported now
+ def testDataStreamReuse_AddExchangeAsBatch_HashJoin(): Unit = {
+ util.tableEnv.getConfig.getConf.setBoolean(
+ PlannerConfigOptions.SQL_OPTIMIZER_REUSE_SUB_PLAN_ENABLED, false)
+ val sqlQuery = "SELECT * FROM t INTERSECT SELECT * FROM t"
+ util.verifyPlan(sqlQuery)
+ }
+
+}
diff --git a/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/plan/batch/sql/SubplanReuseTest.scala b/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/plan/batch/sql/SubplanReuseTest.scala
new file mode 100644
index 0000000..2bf4d43
--- /dev/null
+++ b/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/plan/batch/sql/SubplanReuseTest.scala
@@ -0,0 +1,445 @@
+/*
+ * 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.plan.batch.sql
+
+import org.apache.flink.api.scala._
+import org.apache.flink.table.api.{OperatorType, PlannerConfigOptions, TableConfigOptions, TableException}
+import org.apache.flink.table.functions.aggfunctions.FirstValueAggFunction.IntFirstValueAggFunction
+import org.apache.flink.table.functions.aggfunctions.LastValueAggFunction.LongLastValueAggFunction
+import org.apache.flink.table.runtime.utils.JavaUserDefinedScalarFunctions.NonDeterministicUdf
+import org.apache.flink.table.runtime.utils.JavaUserDefinedTableFunctions.{NonDeterministicTableFunc, StringSplit}
+import org.apache.flink.table.util.TableTestBase
+
+import org.junit.{Before, Test}
+
+class SubplanReuseTest extends TableTestBase {
+
+ private val util = batchTestUtil()
+
+ @Before
+ def before(): Unit = {
+ util.tableEnv.getConfig.getConf.setBoolean(
+ PlannerConfigOptions.SQL_OPTIMIZER_REUSE_SUB_PLAN_ENABLED, true)
+ util.tableEnv.getConfig.getConf.setBoolean(
+ PlannerConfigOptions.SQL_OPTIMIZER_REUSE_TABLE_SOURCE_ENABLED, false)
+ util.addTableSource[(Int, Long, String)]("x", 'a, 'b, 'c)
+ util.addTableSource[(Int, Long, String)]("y", 'd, 'e, 'f)
+ }
+
+ @Test
+ def testDisableSubplanReuse(): Unit = {
+ util.tableEnv.getConfig.getConf.setBoolean(
+ PlannerConfigOptions.SQL_OPTIMIZER_REUSE_SUB_PLAN_ENABLED, false)
+ val sqlQuery =
+ """
+ |WITH r AS (
+ | SELECT a, SUM(b) as b, SUM(e) as e FROM x, y WHERE a = d AND c > 100 GROUP BY a
+ |)
+ |SELECT r1.a, r1.b, r2.e FROM r r1, r r2 WHERE r1.b > 10 AND r2.e < 20 AND r1.a = r2.a
+ """.stripMargin
+ util.verifyPlanNotExpected(sqlQuery, "Reused")
+ }
+
+ @Test(expected = classOf[AssertionError])
+ // TODO after CALCITE-3020 fixed, remove expected exception
+ def testSubplanReuseWithDifferentRowType(): Unit = {
+ util.tableEnv.getConfig.getConf.setBoolean(
+ PlannerConfigOptions.SQL_OPTIMIZER_REUSE_TABLE_SOURCE_ENABLED, false)
+ // can not reuse because of different row-type
+ val sqlQuery =
+ """
+ |WITH t1 AS (SELECT CAST(a as BIGINT) AS a, SUM(b) AS b FROM x GROUP BY CAST(a as BIGINT)),
+ | t2 AS (SELECT CAST(a as DOUBLE) AS a, SUM(b) AS b FROM x GROUP BY CAST(a as DOUBLE))
+ |SELECT t1.*, t2.* FROM t1, t2 WHERE t1.b = t2.b
+ """.stripMargin
+ util.verifyPlanNotExpected(sqlQuery, "Reused")
+ }
+
+ @Test
+ def testEnableReuseTableSource(): Unit = {
+ util.tableEnv.getConfig.getConf.setBoolean(
+ PlannerConfigOptions.SQL_OPTIMIZER_REUSE_TABLE_SOURCE_ENABLED, true)
+ val sqlQuery =
+ """
+ |WITH t AS (SELECT x.a AS a, x.b AS b, y.d AS d, y.e AS e FROM x, y WHERE x.a = y.d)
+ |SELECT t1.*, t2.* FROM t t1, t t2 WHERE t1.b = t2.e AND t1.a < 10 AND t2.a > 5
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test
+ def testDisableReuseTableSource(): Unit = {
+ util.tableEnv.getConfig.getConf.setBoolean(
+ PlannerConfigOptions.SQL_OPTIMIZER_REUSE_TABLE_SOURCE_ENABLED, false)
+ val sqlQuery =
+ """
+ |WITH t AS (SELECT * FROM x, y WHERE x.a = y.d)
+ |SELECT t1.*, t2.* FROM t t1, t t2 WHERE t1.b = t2.e AND t1.a < 10 AND t2.a > 5
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test
+ def testSubplanReuseOnSourceWithLimit(): Unit = {
+ // TODO re-check this plan after PushLimitIntoTableSourceScanRule is introduced
+ util.tableEnv.getConfig.getConf.setBoolean(
+ PlannerConfigOptions.SQL_OPTIMIZER_REUSE_TABLE_SOURCE_ENABLED, true)
+ util.tableEnv.getConfig.getConf.setString(
+ TableConfigOptions.SQL_EXEC_DISABLED_OPERATORS, "HashJoin,SortMergeJoin")
+ val sqlQuery =
+ """
+ |WITH r AS (SELECT a, b FROM x LIMIT 10)
+ |SELECT r1.a, r1.b, r2.a FROM r r1, r r2 WHERE r1.a = r2.b
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+
+
+ @Test(expected = classOf[TableException])
+ def testSubplanReuseOnDataStreamTable(): Unit = {
+ util.addDataStream[(Int, Long, String)]("t", 'a, 'b, 'c)
+ val sqlQuery =
+ """
+ |(SELECT a FROM t WHERE a > 10)
+ |UNION ALL
+ |(SELECT a FROM t WHERE b > 10)
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test
+ def testSubplanReuseOnCalc(): Unit = {
+ util.tableEnv.getConfig.getConf.setString(
+ TableConfigOptions.SQL_EXEC_DISABLED_OPERATORS, "NestedLoopJoin,SortMergeJoin")
+ val sqlQuery =
+ """
+ |WITH r AS (SELECT a, b, c FROM x WHERE c LIKE 'test%')
+ |(SELECT r.a, LOWER(c) AS c, y.e FROM r, y WHERE r.a = y.d)
+ |UNION ALL
+ |(SELECT r.a, LOWER(c) AS c, y.e FROM r, y WHERE r.a = y.d)
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test
+ def testSubplanReuseOnCalcWithNonDeterministicProject(): Unit = {
+ util.tableEnv.registerFunction("random_udf", new NonDeterministicUdf())
+
+ val sqlQuery =
+ """
+ |(SELECT a, random_udf() FROM x WHERE a > 10)
+ |UNION ALL
+ |(SELECT a, random_udf() FROM x WHERE a > 10)
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test
+ def testSubplanReuseOnCalcWithNonDeterministicUdf(): Unit = {
+ util.tableEnv.registerFunction("random_udf", new NonDeterministicUdf())
+
+ val sqlQuery =
+ """
+ |(SELECT a FROM x WHERE b > random_udf(a))
+ |UNION ALL
+ |(SELECT a FROM x WHERE b > random_udf(a))
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test
+ def testSubplanReuseOnExchange(): Unit = {
+ util.tableEnv.getConfig.getConf.setString(
+ TableConfigOptions.SQL_EXEC_DISABLED_OPERATORS, "NestedLoopJoin,SortMergeJoin")
+ val sqlQuery =
+ """
+ |WITH r AS (SELECT a, b, c FROM x WHERE c LIKE 'test%')
+ |SELECT * FROM r, y WHERE a = d AND e > 10
+ |UNION ALL
+ |SELECT * FROM r, y WHERE a = d AND f <> ''
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test
+ def testSubplanReuseOnHashAggregate(): Unit = {
+ util.tableEnv.getConfig.getConf.setString(
+ TableConfigOptions.SQL_EXEC_DISABLED_OPERATORS, OperatorType.SortAgg.toString)
+ val sqlQuery =
+ """
+ |WITH r AS (SELECT c, SUM(a) a, SUM(b) b FROM x GROUP BY c)
+ |SELECT * FROM r r1, r r2 WHERE r1.a = r2.b AND r2.a > 1
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test
+ def testSubplanReuseOnSortAggregate(): Unit = {
+ util.tableEnv.getConfig.getConf.setString(
+ TableConfigOptions.SQL_EXEC_DISABLED_OPERATORS, OperatorType.HashAgg.toString)
+ val sqlQuery =
+ """
+ |WITH r AS (SELECT c, SUM(a) a, SUM(b) b FROM x GROUP BY c)
+ |SELECT * FROM r r1, r r2 WHERE r1.a = r2.b AND r2.a > 1
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test
+ def testSubplanReuseOnAggregateWithNonDeterministicAggCall(): Unit = {
+ // IntFirstValueAggFunction and LongLastValueAggFunction are deterministic
+ util.tableEnv.registerFunction("MyFirst", new IntFirstValueAggFunction)
+ util.tableEnv.registerFunction("MyLast", new LongLastValueAggFunction)
+
+ val sqlQuery =
+ """
+ |WITH r AS (SELECT c, MyFirst(a) a, MyLast(b) b FROM x GROUP BY c)
+ |SELECT * FROM r r1, r r2 WHERE r1.a = r2.b AND r2.a > 1
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test
+ def testSubplanReuseOnSort(): Unit = {
+ util.tableEnv.getConfig.getConf.setBoolean(TableConfigOptions.SQL_EXEC_SORT_RANGE_ENABLED, true)
+ val sqlQuery =
+ """
+ |WITH r AS (SELECT c, SUM(a) a, SUM(b) b FROM x GROUP BY c ORDER BY a, b DESC)
+ |SELECT * FROM r r1, r r2 WHERE r1.a = r2.a AND r1.a > 1 AND r2.b < 10
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test
+ def testSubplanReuseOnLimit(): Unit = {
+ util.tableEnv.getConfig.getConf.setString(
+ TableConfigOptions.SQL_EXEC_DISABLED_OPERATORS, "HashJoin,SortMergeJoin")
+ val sqlQuery =
+ """
+ |WITH r AS (SELECT a, b FROM x LIMIT 10)
+ |SELECT r1.a, r1.b, r2.a FROM r r1, r r2 WHERE r1.a = r2.b
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test
+ def testSubplanReuseOnSortLimit(): Unit = {
+ val sqlQuery =
+ """
+ |WITH r AS (SELECT c, SUM(a) a, SUM(b) b FROM x GROUP BY c ORDER BY a, b DESC LIMIT 10)
+ |SELECT * FROM r r1, r r2 WHERE r1.a = r2.a AND r1.a > 1 AND r2.b < 10
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test
+ def testSubplanReuseOnUnion(): Unit = {
+ val sqlQuery =
+ """
+ |WITH r AS (SELECT a, c FROM x WHERE b > 10 UNION ALL SELECT d, f FROM y WHERE e < 100)
+ |SELECT r1.a, r1.c, r2.c FROM r r1, r r2 WHERE r1.a = r2.a
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test
+ def testSubplanReuseOnJoin(): Unit = {
+ val sqlQuery =
+ """
+ |WITH r AS (SELECT * FROM x FULL OUTER JOIN y ON ABS(a) = ABS(d) OR c = f
+ | WHERE b > 1 and e < 2)
+ |SELECT * FROM r r1, r r2 WHERE r1.a = r2.b
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test
+ def testSubplanReuseOnSortMergeJoin(): Unit = {
+ util.tableEnv.getConfig.getConf.setString(
+ TableConfigOptions.SQL_EXEC_DISABLED_OPERATORS, "HashJoin,NestedLoopJoin")
+ util.tableEnv.getConfig.getConf.setBoolean(
+ PlannerConfigOptions.SQL_OPTIMIZER_SMJ_REMOVE_SORT_ENABLED, true)
+ val sqlQuery =
+ """
+ |WITH r AS (SELECT * FROM x, y WHERE a = d AND c LIKE 'He%')
+ |SELECT * FROM r r1, r r2 WHERE r1.a = r2.d
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test
+ def testSubplanReuseOnHashJoin(): Unit = {
+ util.tableEnv.getConfig.getConf.setString(
+ TableConfigOptions.SQL_EXEC_DISABLED_OPERATORS, "NestedLoopJoin,SortMergeJoin")
+ val sqlQuery =
+ """
+ |WITH r AS (SELECT * FROM x, y WHERE a = d AND c LIKE 'He%')
+ |SELECT * FROM r r1, r r2 WHERE r1.a = r2.d
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test
+ def testSubplanReuseOnNestedLoopJoin(): Unit = {
+ util.tableEnv.getConfig.getConf.setString(
+ TableConfigOptions.SQL_EXEC_DISABLED_OPERATORS, "HashJoin,SortMergeJoin")
+ val sqlQuery =
+ """
+ |WITH r AS (SELECT * FROM x, y WHERE a = d AND c LIKE 'He%')
+ |SELECT * FROM r r1, r r2 WHERE r1.a = r2.d
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test
+ def testSubplanReuseOnJoinNonDeterministicJoinCondition(): Unit = {
+ util.tableEnv.registerFunction("random_udf", new NonDeterministicUdf)
+ val sqlQuery =
+ """
+ |WITH r AS (SELECT * FROM x FULL OUTER JOIN y ON random_udf(a) = random_udf(d) OR c = f
+ | WHERE b > 1 and e < 2)
+ |SELECT * FROM r r1, r r2 WHERE r1.a = r2.b
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test
+ def testSubplanReuseOnOverWindow(): Unit = {
+ val sqlQuery =
+ """
+ |WITH r AS (SELECT a, b, RANK() OVER (ORDER BY c DESC) FROM x)
+ |SELECT * FROM r r1, r r2 WHERE r1.a = r2.a AND r1.b < 100 AND r2.b > 10
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test
+ def testSubplanReuseOnOverWindowWithNonDeterministicAggCall(): Unit = {
+ // IntFirstValueAggFunction is deterministic
+ util.tableEnv.registerFunction("MyFirst", new IntFirstValueAggFunction)
+
+ val sqlQuery =
+ """
+ |WITH r AS (SELECT a, b, MyFirst(c) OVER (PARTITION BY c ORDER BY c DESC) FROM x)
+ |SELECT * FROM r r1, r r2 WHERE r1.a = r2.a AND r1.b < 100 AND r2.b > 10
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test
+ def testSubplanReuseOnCorrelate(): Unit = {
+ util.addFunction("str_split", new StringSplit())
+ util.tableEnv.getConfig.getConf.setString(
+ TableConfigOptions.SQL_EXEC_DISABLED_OPERATORS, "NestedLoopJoin,SortMergeJoin")
+ val sqlQuery =
+ """
+ |WITH r AS (SELECT a, b, c, v FROM x, LATERAL TABLE(str_split(c, '-')) AS T(v))
+ |SELECT * FROM r r1, r r2 WHERE r1.v = r2.v
+ """.stripMargin
+ // TODO the sub-plan of Correlate should be reused,
+ // however the digests of Correlates are different
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test
+ def testSubplanReuseOnCorrelateWithNonDeterministicUDTF(): Unit = {
+ util.tableEnv.registerFunction("TableFun", new NonDeterministicTableFunc)
+
+ val sqlQuery =
+ """
+ |WITH r AS (SELECT a, b, c, s FROM x, LATERAL TABLE(TableFun(c)) AS T(s))
+ |SELECT * FROM r r1, r r2 WHERE r1.c = r2.s
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test(expected = classOf[TableException])
+ // INTERSECT is not supported now
+ def testSubplanReuseWithDynamicFunction(): Unit = {
+ val sqlQuery = util.tableEnv.sqlQuery(
+ """
+ |(SELECT a AS random FROM x ORDER BY rand() LIMIT 1)
+ |INTERSECT
+ |(SELECT a AS random FROM x ORDER BY rand() LIMIT 1)
+ |INTERSECT
+ |(SELECT a AS random FROM x ORDER BY rand() LIMIT 1)
+ """.stripMargin)
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test
+ def testNestedSubplanReuse(): Unit = {
+ util.tableEnv.getConfig.getConf.setString(
+ TableConfigOptions.SQL_EXEC_DISABLED_OPERATORS, "NestedLoopJoin,SortMergeJoin,SortAgg")
+ val sqlQuery =
+ """
+ |WITH v1 AS (
+ | SELECT
+ | SUM(b) sum_b,
+ | AVG(SUM(b)) OVER (PARTITION BY c, e) avg_b,
+ | RANK() OVER (PARTITION BY c, e ORDER BY c, e) rn,
+ | c, e
+ | FROM x, y
+ | WHERE x.a = y.d AND c IS NOT NULl AND e > 10
+ | GROUP BY c, e
+ |),
+ | v2 AS (
+ | SELECT
+ | v11.c,
+ | v11.e,
+ | v11.avg_b,
+ | v11.sum_b,
+ | v12.sum_b psum,
+ | v13.sum_b nsum,
+ | v12.avg_b avg_b2
+ | FROM v1 v11, v1 v12, v1 v13
+ | WHERE v11.c = v12.c AND v11.c = v13.c AND
+ | v11.e = v12.e AND v11.e = v13.e AND
+ | v11.rn = v12.rn + 1 AND
+ | v11.rn = v13.rn - 1
+ |)
+ |SELECT * from v2 WHERE c <> '' AND sum_b - avg_b > 3
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test
+ def testBreakupDeadlockOnHashJoin(): Unit = {
+ util.tableEnv.getConfig.getConf.setString(
+ TableConfigOptions.SQL_EXEC_DISABLED_OPERATORS, "NestedLoopJoin,SortMergeJoin")
+ val sqlQuery =
+ """
+ |WITH r AS (SELECT a FROM x LIMIT 10)
+ |SELECT r1.a FROM r r1, r r2 WHERE r1.a = r2.a
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test
+ def testBreakupDeadlockOnNestedLoopJoin(): Unit = {
+ util.tableEnv.getConfig.getConf.setString(
+ TableConfigOptions.SQL_EXEC_DISABLED_OPERATORS, "HashJoin,SortMergeJoin")
+ val sqlQuery =
+ """
+ |WITH r AS (SELECT a FROM x LIMIT 10)
+ |SELECT r1.a FROM r r1, r r2 WHERE r1.a = r2.a
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+}
diff --git a/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/plan/stream/sql/SubplanReuseTest.scala b/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/plan/stream/sql/SubplanReuseTest.scala
new file mode 100644
index 0000000..a4db284
--- /dev/null
+++ b/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/plan/stream/sql/SubplanReuseTest.scala
@@ -0,0 +1,301 @@
+/*
+ * 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.plan.stream.sql
+
+import org.apache.flink.api.scala._
+import org.apache.flink.table.api.{PlannerConfigOptions, TableConfigOptions, TableException}
+import org.apache.flink.table.functions.aggfunctions.FirstValueAggFunction.IntFirstValueAggFunction
+import org.apache.flink.table.functions.aggfunctions.LastValueAggFunction.LongLastValueAggFunction
+import org.apache.flink.table.runtime.utils.JavaUserDefinedScalarFunctions.NonDeterministicUdf
+import org.apache.flink.table.runtime.utils.JavaUserDefinedTableFunctions.{NonDeterministicTableFunc, StringSplit}
+import org.apache.flink.table.util.TableTestBase
+
+import org.junit.{Before, Test}
+
+class SubplanReuseTest extends TableTestBase {
+
+ private val util = streamTestUtil()
+
+ @Before
+ def before(): Unit = {
+ util.tableEnv.getConfig.getConf.setBoolean(
+ PlannerConfigOptions.SQL_OPTIMIZER_REUSE_SUB_PLAN_ENABLED, true)
+ util.tableEnv.getConfig.getConf.setBoolean(
+ PlannerConfigOptions.SQL_OPTIMIZER_REUSE_TABLE_SOURCE_ENABLED, false)
+ util.addTableSource[(Int, Long, String)]("x", 'a, 'b, 'c)
+ util.addTableSource[(Int, Long, String)]("y", 'd, 'e, 'f)
+ }
+
+ @Test
+ def testDisableSubplanReuse(): Unit = {
+ util.tableEnv.getConfig.getConf.setBoolean(
+ PlannerConfigOptions.SQL_OPTIMIZER_REUSE_SUB_PLAN_ENABLED, false)
+ val sqlQuery =
+ """
+ |WITH r AS (
+ | SELECT a, SUM(b) as b, SUM(e) as e FROM x, y WHERE a = d AND c > 100 GROUP BY a
+ |)
+ |SELECT r1.a, r1.b, r2.e FROM r r1, r r2 WHERE r1.b > 10 AND r2.e < 20 AND r1.a = r2.a
+ """.stripMargin
+ util.verifyPlanNotExpected(sqlQuery, "Reused")
+ }
+
+ @Test(expected = classOf[AssertionError])
+ // TODO after CALCITE-3020 fixed, remove expected exception
+ def testSubplanReuseWithDifferentRowType(): Unit = {
+ util.tableEnv.getConfig.getConf.setBoolean(
+ PlannerConfigOptions.SQL_OPTIMIZER_REUSE_TABLE_SOURCE_ENABLED, false)
+ // can not reuse because of different row-type
+ val sqlQuery =
+ """
+ |WITH t1 AS (SELECT CAST(a as BIGINT) AS a, SUM(b) AS b FROM x GROUP BY CAST(a as BIGINT)),
+ | t2 AS (SELECT CAST(a as DOUBLE) AS a, SUM(b) AS b FROM x GROUP BY CAST(a as DOUBLE))
+ |SELECT t1.*, t2.* FROM t1, t2 WHERE t1.b = t2.b
+ """.stripMargin
+ util.verifyPlanNotExpected(sqlQuery, "Reused")
+ }
+
+ @Test
+ def testEnableReuseTableSource(): Unit = {
+ util.tableEnv.getConfig.getConf.setBoolean(
+ PlannerConfigOptions.SQL_OPTIMIZER_REUSE_TABLE_SOURCE_ENABLED, true)
+ val sqlQuery =
+ """
+ |WITH t AS (SELECT x.a AS a, x.b AS b, y.d AS d, y.e AS e FROM x, y WHERE x.a = y.d)
+ |SELECT t1.*, t2.* FROM t t1, t t2 WHERE t1.b = t2.e AND t1.a < 10 AND t2.a > 5
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test
+ def testDisableReuseTableSource(): Unit = {
+ util.tableEnv.getConfig.getConf.setBoolean(
+ PlannerConfigOptions.SQL_OPTIMIZER_REUSE_TABLE_SOURCE_ENABLED, false)
+ val sqlQuery =
+ """
+ |WITH t AS (SELECT * FROM x, y WHERE x.a = y.d)
+ |SELECT t1.*, t2.* FROM t t1, t t2 WHERE t1.b = t2.e AND t1.a < 10 AND t2.a > 5
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test
+ def testSubplanReuseOnCalc(): Unit = {
+ val sqlQuery =
+ """
+ |WITH r AS (SELECT a, b, c FROM x WHERE c LIKE 'test%')
+ |(SELECT r.a, LOWER(c) AS c, y.e FROM r, y WHERE r.a = y.d)
+ |UNION ALL
+ |(SELECT r.a, LOWER(c) AS c, y.e FROM r, y WHERE r.a = y.d)
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test
+ def testSubplanReuseOnCalcWithNonDeterministicProject(): Unit = {
+ util.tableEnv.registerFunction("random_udf", new NonDeterministicUdf())
+
+ val sqlQuery =
+ """
+ |(SELECT a, random_udf() FROM x WHERE a > 10)
+ |UNION ALL
+ |(SELECT a, random_udf() FROM x WHERE a > 10)
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test
+ def testSubplanReuseOnCalcWithNonDeterministicUdf(): Unit = {
+ util.tableEnv.registerFunction("random_udf", new NonDeterministicUdf())
+
+ val sqlQuery =
+ """
+ |(SELECT a FROM x WHERE b > random_udf(a))
+ |UNION ALL
+ |(SELECT a FROM x WHERE b > random_udf(a))
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test
+ def testSubplanReuseOnExchange(): Unit = {
+ val sqlQuery =
+ """
+ |WITH r AS (SELECT a, b, c FROM x WHERE c LIKE 'test%')
+ |SELECT * FROM r, y WHERE a = d AND e > 10
+ |UNION ALL
+ |SELECT * FROM r, y WHERE a = d AND f <> ''
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test
+ def testSubplanReuseOnGroupAggregate(): Unit = {
+ val sqlQuery =
+ """
+ |WITH r AS (SELECT c, SUM(a) a, SUM(b) b FROM x GROUP BY c)
+ |SELECT * FROM r r1, r r2 WHERE r1.a = r2.b AND r2.a > 1
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test
+ def testSubplanReuseOnAggregateWithNonDeterministicAggCall(): Unit = {
+ // IntFirstValueAggFunction and LongLastValueAggFunction are deterministic
+ util.tableEnv.registerFunction("MyFirst", new IntFirstValueAggFunction)
+ util.tableEnv.registerFunction("MyLast", new LongLastValueAggFunction)
+
+ val sqlQuery =
+ """
+ |WITH r AS (SELECT c, MyFirst(a) a, MyLast(b) b FROM x GROUP BY c)
+ |SELECT * FROM r r1, r r2 WHERE r1.a = r2.b AND r2.a > 1
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test
+ def testSubplanReuseOnSort(): Unit = {
+ val sqlQuery =
+ """
+ |WITH r AS (SELECT c, SUM(a) a, SUM(b) b FROM x GROUP BY c ORDER BY a, b DESC)
+ |SELECT * FROM r r1, r r2 WHERE r1.a = r2.a AND r1.a > 1 AND r2.b < 10
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test
+ def testSubplanReuseOnLimit(): Unit = {
+ util.tableEnv.getConfig.getConf.setString(
+ TableConfigOptions.SQL_EXEC_DISABLED_OPERATORS, "HashJoin,SortMergeJoin")
+ val sqlQuery =
+ """
+ |WITH r AS (SELECT a, b FROM x LIMIT 10)
+ |
+ |SELECT a, b FROM r WHERE a > 10
+ |UNION ALL
+ |SELECT a, b * 2 AS b FROM r WHERE b < 10
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test
+ def testSubplanReuseOnSortLimit(): Unit = {
+ val sqlQuery =
+ """
+ |WITH r AS (SELECT c, SUM(a) a, SUM(b) b FROM x GROUP BY c ORDER BY a, b DESC LIMIT 10)
+ |
+ |SELECT a, b FROM r WHERE a > 10
+ |UNION ALL
+ |SELECT a, b * 2 AS b FROM r WHERE b < 10
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test
+ def testSubplanReuseOnJoin(): Unit = {
+ val sqlQuery =
+ """
+ |WITH r AS (SELECT * FROM x FULL OUTER JOIN y ON ABS(a) = ABS(d) OR c = f
+ | WHERE b > 1 and e < 2)
+ |
+ |SELECT a, b FROM r
+ |UNION ALL
+ |SELECT a, b * 2 AS b FROM r
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test
+ def testSubplanReuseOnJoinNonDeterministicJoinCondition(): Unit = {
+ util.tableEnv.registerFunction("random_udf", new NonDeterministicUdf)
+ val sqlQuery =
+ """
+ |WITH r AS (SELECT * FROM x FULL OUTER JOIN y ON random_udf(a) = random_udf(d) OR c = f
+ | WHERE b > 1 and e < 2)
+ |
+ |SELECT a, b FROM r
+ |UNION ALL
+ |SELECT a, b * 2 AS b FROM r
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test
+ def testSubplanReuseOnOverWindow(): Unit = {
+ val sqlQuery =
+ """
+ |WITH r AS (SELECT a, b, RANK() OVER (ORDER BY c DESC) FROM x)
+ |SELECT * FROM r r1, r r2 WHERE r1.a = r2.a AND r1.b < 100 AND r2.b > 10
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test
+ def testSubplanReuseOnOverWindowWithNonDeterministicAggCall(): Unit = {
+ // IntFirstValueAggFunction is deterministic
+ util.tableEnv.registerFunction("MyFirst", new IntFirstValueAggFunction)
+
+ val sqlQuery =
+ """
+ |WITH r AS (SELECT a, b, MyFirst(c) OVER (PARTITION BY c ORDER BY c DESC) FROM x)
+ |SELECT * FROM r r1, r r2 WHERE r1.a = r2.a AND r1.b < 100 AND r2.b > 10
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test
+ def testSubplanReuseOnCorrelate(): Unit = {
+ util.addFunction("str_split", new StringSplit())
+ val sqlQuery =
+ """
+ |WITH r AS (SELECT a, b, c, v FROM x, LATERAL TABLE(str_split(c, '-')) AS T(v))
+ |SELECT * FROM r r1, r r2 WHERE r1.v = r2.v
+ """.stripMargin
+ // TODO the sub-plan of Correlate should be reused,
+ // however the digests of Correlates are different
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test
+ def testSubplanReuseOnCorrelateWithNonDeterministicUDTF(): Unit = {
+ util.tableEnv.registerFunction("TableFun", new NonDeterministicTableFunc)
+
+ val sqlQuery =
+ """
+ |WITH r AS (SELECT a, b, c, s FROM x, LATERAL TABLE(TableFun(c)) AS T(s))
+ |SELECT * FROM r r1, r r2 WHERE r1.c = r2.s
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test(expected = classOf[TableException])
+ // INTERSECT is not supported now
+ def testSubplanReuseWithDynamicFunction(): Unit = {
+ val sqlQuery = util.tableEnv.sqlQuery(
+ """
+ |(SELECT a AS random FROM x ORDER BY rand() LIMIT 1)
+ |INTERSECT
+ |(SELECT a AS random FROM x ORDER BY rand() LIMIT 1)
+ |INTERSECT
+ |(SELECT a AS random FROM x ORDER BY rand() LIMIT 1)
+ """.stripMargin)
+ util.verifyPlan(sqlQuery)
+ }
+
+}
diff --git a/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/plan/util/RelDigestUtilTest.scala b/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/plan/util/RelDigestUtilTest.scala
new file mode 100644
index 0000000..fdc87e8
--- /dev/null
+++ b/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/plan/util/RelDigestUtilTest.scala
@@ -0,0 +1,108 @@
+/*
+ * 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.plan.util
+
+import org.apache.flink.api.common.typeinfo.BasicTypeInfo.{DOUBLE_TYPE_INFO, INT_TYPE_INFO, STRING_TYPE_INFO}
+import org.apache.flink.api.java.typeutils.RowTypeInfo
+import org.apache.flink.streaming.api.scala.StreamExecutionEnvironment
+import org.apache.flink.table.api.{TableConfig, TableEnvironment, TableImpl}
+import org.apache.flink.table.runtime.utils.BatchTableEnvUtil
+import org.apache.flink.table.runtime.utils.BatchTestBase.row
+
+import org.junit.Assert.assertEquals
+import org.junit.{Before, Test}
+
+import scala.collection.Seq
+import scala.io.Source
+
+class RelDigestUtilTest {
+
+ var tableEnv: TableEnvironment = _
+
+ @Before
+ def before(): Unit = {
+ val conf = new TableConfig()
+ val env = StreamExecutionEnvironment.getExecutionEnvironment
+ val tEnv = TableEnvironment.getBatchTableEnvironment(env, conf)
+ BatchTableEnvUtil.registerCollection(
+ tEnv,
+ "MyTable",
+ Seq(row("Mike", 1, 12.3, "Smith")),
+ new RowTypeInfo(STRING_TYPE_INFO, INT_TYPE_INFO, DOUBLE_TYPE_INFO, STRING_TYPE_INFO),
+ "first, id, score, last")
+ tableEnv = tEnv
+ }
+
+ @Test
+ def testGetDigestWithDynamicFunction(): Unit = {
+ val table = tableEnv.sqlQuery(
+ """
+ |(SELECT id AS random FROM MyTable ORDER BY rand() LIMIT 1)
+ |INTERSECT
+ |(SELECT id AS random FROM MyTable ORDER BY rand() LIMIT 1)
+ |INTERSECT
+ |(SELECT id AS random FROM MyTable ORDER BY rand() LIMIT 1)
+ """.stripMargin)
+ val rel = table.asInstanceOf[TableImpl].getRelNode
+ val expected = readFromResource("testGetDigestWithDynamicFunction.out")
+ assertEquals(expected, RelDigestUtil.getDigest(rel))
+ }
+
+ @Test
+ def testGetDigestWithDynamicFunctionView(): Unit = {
+ val view = tableEnv.sqlQuery("SELECT id AS random FROM MyTable ORDER BY rand() LIMIT 1")
+ tableEnv.registerTable("MyView", view)
+ val table = tableEnv.sqlQuery(
+ """
+ |(SELECT * FROM MyView)
+ |INTERSECT
+ |(SELECT * FROM MyView)
+ |INTERSECT
+ |(SELECT * FROM MyView)
+ """.stripMargin)
+ val rel = table.asInstanceOf[TableImpl].getRelNode.accept(new ExpandTableScanShuttle())
+ val expected = readFromResource("testGetDigestWithDynamicFunctionView.out")
+ assertEquals(expected, RelDigestUtil.getDigest(rel))
+ }
+
+ private def readFromResource(name: String): String = {
+ val inputStream = getClass.getResource("/digest/" + name).getFile
+ val fullContent = Source.fromFile(inputStream).mkString
+ val license =
+ """/*
+ | * 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.
+ | */
+ |""".stripMargin
+ fullContent.replace(license, "")
+ }
+
+}
diff --git a/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/runtime/batch/sql/CorrelateITCase2.scala b/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/runtime/batch/sql/CorrelateITCase2.scala
index bedd956..09b7af3 100644
--- a/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/runtime/batch/sql/CorrelateITCase2.scala
+++ b/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/runtime/batch/sql/CorrelateITCase2.scala
@@ -18,16 +18,14 @@
package org.apache.flink.table.runtime.batch.sql
-import org.apache.flink.api.common.typeinfo.TypeInformation
import org.apache.flink.api.scala._
import org.apache.flink.api.scala.typeutils.Types
import org.apache.flink.table.api.TableConfigOptions
-import org.apache.flink.table.functions.TableFunction
-import org.apache.flink.table.runtime.utils.TestData._
import org.apache.flink.table.runtime.utils.BatchTestBase
import org.apache.flink.table.runtime.utils.BatchTestBase._
+import org.apache.flink.table.runtime.utils.JavaUserDefinedTableFunctions.StringSplit
+import org.apache.flink.table.runtime.utils.TestData._
-import org.apache.commons.lang3.StringUtils
import org.junit.{Before, Ignore, Test}
import scala.collection.Seq
@@ -268,41 +266,3 @@ class CorrelateITCase2 extends BatchTestBase {
))
}
}
-
-class StringSplit extends TableFunction[String] {
- def eval(): Unit = {
- Array("a", "b", "c").foreach(collect)
- }
-
- def eval(str: String): Unit = {
- if (null != str) {
- StringUtils.split(str, ",").foreach(collect)
- }
- }
-
- def eval(str: String, splitChar: String): Unit = {
- if (null != str && null != splitChar) {
- StringUtils.split(str, splitChar).foreach(collect)
- }
- }
-
- def eval(str: String, splitChar: String, startIndex: Int): Unit = {
- if (null != str && null != splitChar) {
- val result = StringUtils.split(str, splitChar)
- val idx = if (startIndex <= 0) 0 else startIndex
- if (idx < result.length) {
- result.drop(idx).foreach(collect)
- }
- }
- }
-
- def eval(varbinary: Array[Byte]): Unit = {
- if (null != varbinary) {
- StringUtils.split(new String(varbinary), ",").foreach(collect)
- }
- }
-
- override def getResultType: TypeInformation[String] = {
- Types.STRING
- }
-}
diff --git a/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/runtime/batch/sql/MiscITCase.scala b/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/runtime/batch/sql/MiscITCase.scala
index 54557ae..82d0f78 100644
--- a/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/runtime/batch/sql/MiscITCase.scala
+++ b/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/runtime/batch/sql/MiscITCase.scala
@@ -509,7 +509,7 @@ class MiscITCase extends BatchTestBase {
)
}
- @Test(expected = classOf[ClassCastException])
+ @Test(expected = classOf[TableException])
def testCompareFunctionWithSubquery(): Unit = {
checkResult("SELECT " +
"b IN (3, 4, 5)," +
diff --git a/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/runtime/batch/sql/agg/GroupingSetsITCase.scala b/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/runtime/batch/sql/agg/GroupingSetsITCase.scala
index ae3262f..a252f40 100644
--- a/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/runtime/batch/sql/agg/GroupingSetsITCase.scala
+++ b/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/runtime/batch/sql/agg/GroupingSetsITCase.scala
@@ -19,7 +19,7 @@
package org.apache.flink.table.runtime.batch.sql.agg
import org.apache.flink.api.java.typeutils.RowTypeInfo
-import org.apache.flink.table.api.{TableConfigOptions, Types}
+import org.apache.flink.table.api.{TableConfigOptions, TableException, Types}
import org.apache.flink.table.runtime.utils.BatchTestBase
import org.apache.flink.table.runtime.utils.BatchTestBase.row
import org.apache.flink.table.runtime.utils.TestData._
@@ -236,7 +236,7 @@ class GroupingSetsITCase extends BatchTestBase {
}
// TODO remove expected exception after BatchExecHashJoin extends ExecNode
- @Test(expected = classOf[ClassCastException])
+ @Test(expected = classOf[TableException])
def testCubeAndJoin(): Unit = {
checkResult(
"select e.deptno, e.gender, min(e.ename) as min_name " +
diff --git a/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/runtime/stream/sql/CorrelateITCase.scala b/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/runtime/stream/sql/CorrelateITCase.scala
index 97601af..8ea664e 100644
--- a/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/runtime/stream/sql/CorrelateITCase.scala
+++ b/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/runtime/stream/sql/CorrelateITCase.scala
@@ -19,8 +19,8 @@ package org.apache.flink.table.runtime.stream.sql
import org.apache.flink.api.scala._
import org.apache.flink.table.api.scala._
-import org.apache.flink.table.runtime.batch.sql.StringSplit
import org.apache.flink.table.runtime.utils.JavaUserDefinedScalarFunctions.UdfWithOpen
+import org.apache.flink.table.runtime.utils.JavaUserDefinedTableFunctions.StringSplit
import org.apache.flink.table.runtime.utils.{StreamingTestBase, TestSinkUtil, TestingAppendSink, TestingAppendTableSink}
import org.apache.flink.types.Row
diff --git a/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/util/TableTestBase.scala b/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/util/TableTestBase.scala
index b8e3760..77dcd09 100644
--- a/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/util/TableTestBase.scala
+++ b/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/util/TableTestBase.scala
@@ -31,15 +31,16 @@ import org.apache.flink.table.api.scala.{BatchTableEnvironment => ScalaBatchTabl
import org.apache.flink.table.calcite.CalciteConfig
import org.apache.flink.table.dataformat.BaseRow
import org.apache.flink.table.functions.{AggregateFunction, ScalarFunction, TableFunction}
+import org.apache.flink.table.plan.nodes.exec.ExecNode
import org.apache.flink.table.plan.optimize.program.{FlinkBatchProgram, FlinkStreamProgram}
-import org.apache.flink.table.plan.util.FlinkRelOptUtil
+import org.apache.flink.table.plan.util.{ExecNodePlanDumper, FlinkRelOptUtil}
import org.apache.flink.table.sources.{BatchTableSource, StreamTableSource}
import org.apache.flink.table.typeutils.BaseRowTypeInfo
import org.apache.calcite.rel.RelNode
import org.apache.calcite.sql.SqlExplainLevel
import org.apache.commons.lang3.SystemUtils
-import org.junit.Assert.assertEquals
+import org.junit.Assert.{assertEquals, assertTrue}
import org.junit.Rule
import org.junit.rules.{ExpectedException, TestName}
@@ -209,6 +210,30 @@ abstract class TableTestUtil(test: TableTestBase) {
printPlanBefore = true)
}
+ def verifyPlanWithType(table: Table): Unit = {
+ doVerifyPlan(
+ table,
+ explainLevel = SqlExplainLevel.EXPPLAN_ATTRIBUTES,
+ withRowType = true,
+ printPlanBefore = true)
+ }
+
+ def verifyPlanNotExpected(sql: String, notExpected: String*): Unit = {
+ verifyPlanNotExpected(getTableEnv.sqlQuery(sql), notExpected: _*)
+ }
+
+ def verifyPlanNotExpected(table: Table, notExpected: String*): Unit = {
+ val relNode = table.asInstanceOf[TableImpl].getRelNode
+ val optimizedPlan = getOptimizedPlan(
+ relNode,
+ explainLevel = SqlExplainLevel.EXPPLAN_ATTRIBUTES,
+ withRetractTraits = false,
+ withRowType = false)
+ val result = notExpected.forall(!optimizedPlan.contains(_))
+ val message = s"\nactual plan:\n$optimizedPlan\nnot expected:\n${notExpected.mkString(", ")}"
+ assertTrue(message, result)
+ }
+
def verifyExplain(): Unit = doVerifyExplain()
def verifyExplain(sql: String): Unit = {
@@ -314,12 +339,24 @@ abstract class TableTestUtil(test: TableTestBase) {
explainLevel: SqlExplainLevel,
withRetractTraits: Boolean,
withRowType: Boolean): String = {
- val optimized = getTableEnv.optimize(relNode)
- FlinkRelOptUtil.toString(
- optimized,
- detailLevel = explainLevel,
- withRetractTraits = withRetractTraits,
- withRowType = withRowType)
+ val tEnv = getTableEnv
+ val optimized = tEnv.optimize(relNode)
+ optimized match {
+ case execNode: ExecNode[_, _] =>
+ val optimizedNodes = tEnv.translateNodeDag(Seq(execNode))
+ require(optimizedNodes.length == 1)
+ ExecNodePlanDumper.treeToString(
+ optimizedNodes.head,
+ detailLevel = explainLevel,
+ withRetractTraits = withRetractTraits,
+ withOutputType = withRowType)
+ case _ =>
+ FlinkRelOptUtil.toString(
+ optimized,
+ detailLevel = explainLevel,
+ withRetractTraits = withRetractTraits,
+ withRowType = withRowType)
+ }
}
/* Stage {id} is ignored, because id keeps incrementing in test class
@@ -421,7 +458,9 @@ case class BatchTableTestUtil(test: TableTestBase) extends TableTestUtil(test) {
// TODO implements this method when a DataStream could be converted into a Table
override def addDataStream[T: TypeInformation](
- name: String, fields: Symbol*): Table = ???
+ name: String, fields: Symbol*): Table = {
+ throw new TableException("Implements this")
+ }
def buildBatchProgram(firstProgramNameToRemove: String): Unit = {
val program = FlinkBatchProgram.buildProgram(tableEnv.getConfig.getConf)