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/01 08:24:14 UTC
[flink] branch master updated: [FLINK-12018][table-planner-blink]
Add support for generating optimized logical plan for Sort and Rank
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 3dabd68 [FLINK-12018][table-planner-blink] Add support for generating optimized logical plan for Sort and Rank
3dabd68 is described below
commit 3dabd68d18212acba9b25925f698ee344672bd56
Author: godfreyhe <go...@163.com>
AuthorDate: Tue Mar 26 16:22:49 2019 +0800
[FLINK-12018][table-planner-blink] Add support for generating optimized logical plan for Sort and Rank
This closes #8051
---
.../flink/table/api/PlannerConfigOptions.java | 41 +
.../flink/table/api/BatchTableEnvironment.scala | 15 +-
.../flink/table/api/StreamTableEnvironment.scala | 159 ++-
.../apache/flink/table/api/TableEnvironment.scala | 26 +-
.../flink/table/calcite/FlinkRelBuilder.scala | 9 +-
.../table/calcite/FlinkRelOptClusterFactory.scala | 7 +-
.../flink/table/calcite/FlinkTypeFactory.scala | 5 +
.../cost/FlinkDefaultRelMetadataProvider.scala | 33 +
.../flink/table/plan/cost/FlinkRelMdSize.scala | 44 +
.../table/plan/nodes/calcite/LogicalRank.scala | 44 +-
.../flink/table/plan/nodes/calcite/Rank.scala | 107 +-
.../plan/nodes/logical/FlinkLogicalRank.scala | 69 +-
.../plan/nodes/logical/FlinkLogicalSort.scala | 28 +-
.../plan/nodes/physical/batch/BatchExecRank.scala | 44 +-
...stLastRow.scala => StreamExecDeduplicate.scala} | 16 +-
...{StreamExecSort.scala => StreamExecLimit.scala} | 40 +-
.../nodes/physical/stream/StreamExecRank.scala | 108 +-
.../nodes/physical/stream/StreamExecSort.scala | 15 +-
.../physical/stream/StreamExecSortLimit.scala | 101 ++
.../optimize/program/FlinkChainedProgram.scala | 4 +-
.../plan/optimize/program/FlinkGroupProgram.scala | 4 +-
.../plan/optimize/program/FlinkStreamProgram.scala | 10 +
.../optimize/program/FlinkVolcanoProgram.scala | 18 +-
.../table/plan/rules/FlinkBatchRuleSets.scala | 15 +-
.../table/plan/rules/FlinkStreamRuleSets.scala | 16 +
.../plan/rules/logical/FlinkLogicalRankRule.scala | 269 +++++
.../rules/physical/FlinkExpandConversionRule.scala | 166 +++
.../rules/physical/batch/BatchExecLimitRule.scala | 108 ++
.../rules/physical/batch/BatchExecRankRule.scala | 119 ++
.../physical/batch/BatchExecSortLimitRule.scala | 109 ++
.../rules/physical/batch/BatchExecSortRule.scala | 76 ++
.../stream/StreamExecDeduplicateRule.scala | 135 +++
.../physical/stream/StreamExecLimitRule.scala | 70 ++
.../rules/physical/stream/StreamExecRankRule.scala | 75 ++
.../physical/stream/StreamExecSortLimitRule.scala | 69 ++
.../rules/physical/stream/StreamExecSortRule.scala | 68 ++
.../stream/StreamExecTemporalSortRule.scala | 91 ++
.../flink/table/plan/schema/InlineTable.scala | 30 +-
.../flink/table/plan/util/FlinkRelOptUtil.scala | 6 +-
.../flink/table/plan/util/FlinkRexUtil.scala | 307 ++++-
.../table/plan/util/RankProcessStrategy.scala | 90 ++
.../apache/flink/table/plan/util/RankUtil.scala | 294 +++++
.../flink/table/plan/batch/sql/LimitTest.xml | 226 ++++
.../apache/flink/table/plan/batch/sql/RankTest.xml | 217 ++++
.../flink/table/plan/batch/sql/SortLimitTest.xml | 217 ++++
.../apache/flink/table/plan/batch/sql/SortTest.xml | 115 ++
.../FlinkLogicalRankRuleForConstantRangeTest.xml | 379 ++++++
.../FlinkLogicalRankRuleForRangeEndTest.xml | 331 ++++++
.../flink/table/plan/stream/sql/LimitTest.xml | 697 +++++++++++
.../flink/table/plan/stream/sql/RankTest.xml | 355 ++++++
.../flink/table/plan/stream/sql/SortLimitTest.xml | 1254 ++++++++++++++++++++
.../flink/table/plan/stream/sql/SortTest.xml | 206 ++++
.../flink/table/plan/batch/sql/LimitTest.scala | 93 ++
.../flink/table/plan/batch/sql/RankTest.scala | 170 +++
.../flink/table/plan/batch/sql/SortLimitTest.scala | 98 ++
.../flink/table/plan/batch/sql/SortTest.scala | 69 ++
.../FlinkLogicalRankRuleForConstantRangeTest.scala | 210 ++++
.../FlinkLogicalRankRuleForRangeEndTest.scala | 195 +++
.../plan/schema/TimeIndicatorRelDataTypeTest.scala | 42 +
.../flink/table/plan/stream/sql/LimitTest.scala | 212 ++++
.../flink/table/plan/stream/sql/RankTest.scala | 730 ++++++++++++
.../table/plan/stream/sql/SortLimitTest.scala | 326 +++++
.../flink/table/plan/stream/sql/SortTest.scala | 77 ++
.../flink/table/plan/util/FlinkRexUtilTest.scala | 407 +++++++
.../apache/flink/table/util/TableTestBase.scala | 108 +-
.../apache/flink/table/api/TableConfigOptions.java | 12 +
.../org/apache/flink/table/type/InternalTypes.java | 20 +
67 files changed, 9518 insertions(+), 308 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
new file mode 100644
index 0000000..0710887
--- /dev/null
+++ b/flink-table/flink-table-planner-blink/src/main/java/org/apache/flink/table/api/PlannerConfigOptions.java
@@ -0,0 +1,41 @@
+/*
+ * 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.api;
+
+import org.apache.flink.configuration.ConfigOption;
+
+import static org.apache.flink.configuration.ConfigOptions.key;
+
+/**
+ * This class holds configuration constants used by Flink's table planner module.
+ */
+public class PlannerConfigOptions {
+
+ // ------------------------------------------------------------------------
+ // Optimizer Options
+ // ------------------------------------------------------------------------
+
+ public static final ConfigOption<Integer> SQL_OPTIMIZER_CNF_NODES_LIMIT =
+ key("sql.optimizer.cnf.nodes.limit")
+ .defaultValue(-1)
+ .withDescription("When converting to conjunctive normal form (CNF), fail if the expression" +
+ " exceeds this threshold; the threshold is expressed in terms of number of nodes " +
+ "(only count RexCall node, including leaves and interior nodes). Negative number to" +
+ " use the default threshold: double of number of nodes.");
+}
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 8991aef..4d30195 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
@@ -21,10 +21,9 @@ import org.apache.flink.configuration.Configuration
import org.apache.flink.streaming.api.datastream.DataStream
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment
import org.apache.flink.streaming.api.transformations.StreamTransformation
-import org.apache.flink.table.calcite.FlinkRelBuilder
+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.`trait`.FlinkRelDistributionTraitDef
import org.apache.flink.table.plan.optimize.{BatchOptimizer, Optimizer}
import org.apache.flink.table.plan.schema.{BatchTableSourceTable, TableSourceSinkTable, TableSourceTable}
import org.apache.flink.table.plan.stats.FlinkStatistic
@@ -32,7 +31,7 @@ import org.apache.flink.table.plan.util.FlinkRelOptUtil
import org.apache.flink.table.sinks._
import org.apache.flink.table.sources._
-import org.apache.calcite.plan.ConventionTraitDef
+import org.apache.calcite.plan.{ConventionTraitDef, RelTrait, RelTraitDef}
import org.apache.calcite.rel.RelCollationTraitDef
import org.apache.calcite.sql.SqlExplainLevel
@@ -59,16 +58,14 @@ class BatchTableEnvironment(
override def queryConfig: QueryConfig = new BatchQueryConfig
- override protected def getOptimizer: Optimizer = new BatchOptimizer(this)
-
- // the builder for Calcite RelNodes, Calcite's representation of a relational expression tree.
- override protected def createRelBuilder: FlinkRelBuilder = FlinkRelBuilder.create(
- frameworkConfig,
+ override protected def getTraitDefs: Array[RelTraitDef[_ <: RelTrait]] = {
Array(
ConventionTraitDef.INSTANCE,
FlinkRelDistributionTraitDef.INSTANCE,
RelCollationTraitDef.INSTANCE)
- )
+ }
+
+ override protected def getOptimizer: Optimizer = new BatchOptimizer(this)
/**
* Checks if the chosen table name is valid.
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/api/StreamTableEnvironment.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/api/StreamTableEnvironment.scala
index abb82ce..4844265 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/api/StreamTableEnvironment.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/api/StreamTableEnvironment.scala
@@ -19,6 +19,7 @@
package org.apache.flink.table.api
import org.apache.flink.api.common.typeinfo.TypeInformation
+import org.apache.flink.api.common.typeutils.CompositeType
import org.apache.flink.configuration.Configuration
import org.apache.flink.runtime.state.filesystem.FsStateBackend
import org.apache.flink.runtime.state.memory.MemoryStateBackend
@@ -26,21 +27,20 @@ import org.apache.flink.streaming.api.TimeCharacteristic
import org.apache.flink.streaming.api.datastream.DataStream
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment
import org.apache.flink.streaming.api.transformations.StreamTransformation
-import org.apache.flink.table.calcite.FlinkRelBuilder
+import org.apache.flink.table.`type`.{InternalType, InternalTypes, RowType, TypeConverters}
import org.apache.flink.table.dataformat.BaseRow
+import org.apache.flink.table.plan.`trait`.{AccModeTraitDef, FlinkRelDistributionTraitDef, MiniBatchIntervalTraitDef, UpdateAsRetractionTraitDef}
import org.apache.flink.table.plan.nodes.calcite.LogicalSink
import org.apache.flink.table.plan.nodes.exec.{ExecNode, StreamExecNode}
import org.apache.flink.table.plan.optimize.{Optimizer, StreamOptimizer}
import org.apache.flink.table.plan.schema._
import org.apache.flink.table.plan.stats.FlinkStatistic
-import org.apache.flink.table.plan.`trait`.{AccModeTraitDef, FlinkRelDistributionTraitDef, MiniBatchIntervalTraitDef, UpdateAsRetractionTraitDef}
import org.apache.flink.table.plan.util.FlinkRelOptUtil
import org.apache.flink.table.sinks.{DataStreamTableSink, TableSink}
import org.apache.flink.table.sources.{StreamTableSource, TableSource}
-import org.apache.flink.table.typeutils.TimeIndicatorTypeInfo
+import org.apache.flink.table.typeutils.{TimeIndicatorTypeInfo, TypeCheckUtils}
-import org.apache.calcite.plan.ConventionTraitDef
-import org.apache.calcite.rel.RelCollationTraitDef
+import org.apache.calcite.plan.{ConventionTraitDef, RelTrait, RelTraitDef}
import org.apache.calcite.sql.SqlExplainLevel
import _root_.scala.collection.JavaConversions._
@@ -75,6 +75,15 @@ abstract class StreamTableEnvironment(
override def queryConfig: StreamQueryConfig = new StreamQueryConfig
+ override protected def getTraitDefs: Array[RelTraitDef[_ <: RelTrait]] = {
+ Array(
+ ConventionTraitDef.INSTANCE,
+ FlinkRelDistributionTraitDef.INSTANCE,
+ MiniBatchIntervalTraitDef.INSTANCE,
+ UpdateAsRetractionTraitDef.INSTANCE,
+ AccModeTraitDef.INSTANCE)
+ }
+
override protected def getOptimizer: Optimizer = new StreamOptimizer(this)
/**
@@ -92,18 +101,6 @@ abstract class StreamTableEnvironment(
}
}
- // the builder for Calcite RelNodes, Calcite's representation of a relational expression tree.
- override protected def createRelBuilder: FlinkRelBuilder = FlinkRelBuilder.create(
- frameworkConfig,
- Array(
- ConventionTraitDef.INSTANCE,
- FlinkRelDistributionTraitDef.INSTANCE,
- RelCollationTraitDef.INSTANCE,
- MiniBatchIntervalTraitDef.INSTANCE,
- UpdateAsRetractionTraitDef.INSTANCE,
- AccModeTraitDef.INSTANCE)
- )
-
/**
* Merge global job parameters and table config parameters,
* and set the merged result to GlobalJobParameters
@@ -288,14 +285,12 @@ abstract class StreamTableEnvironment(
dataStream: DataStream[T],
fields: Array[String]): Unit = {
- val streamType = dataStream.getType
-
// get field names and types for all non-replaced fields
- val (fieldNames, fieldIndexes) = getFieldInfo[T](streamType, fields)
+ val (fieldNames, fieldIndexes) = getFieldInfo(dataStream.getType, fields)
// TODO: validate and extract time attributes after we introduce [Expression],
// return None currently
- val (rowtime, proctime) = (None, None)
+ val (rowtime, proctime) = validateAndExtractTimeAttributes(dataStream.getType, fields)
// check if event-time is enabled
if (rowtime.isDefined && execEnv.getStreamTimeCharacteristic != TimeCharacteristic.EventTime) {
@@ -317,6 +312,128 @@ abstract class StreamTableEnvironment(
}
/**
+ * Checks for at most one rowtime and proctime attribute.
+ * Returns the time attributes.
+ *
+ * @return rowtime attribute and proctime attribute
+ */
+ // TODO: we should support Expression fields after we introduce [Expression]
+ private[flink] def validateAndExtractTimeAttributes(
+ streamType: TypeInformation[_],
+ fields: Array[String]): (Option[(Int, String)], Option[(Int, String)]) = {
+
+ val (isRefByPos, fieldTypes) = streamType match {
+ case c: CompositeType[_] =>
+ // determine schema definition mode (by position or by name)
+ (isReferenceByPosition(c, fields), (0 until c.getArity).map(i => c.getTypeAt(i)).toArray)
+ case t: TypeInformation[_] =>
+ (false, Array(t))
+ }
+
+ var fieldNames: List[String] = Nil
+ var rowtime: Option[(Int, String)] = None
+ var proctime: Option[(Int, String)] = None
+
+ def checkRowtimeType(typeInfo: TypeInformation[_]): Unit = {
+ val t = TypeConverters.createInternalTypeFromTypeInfo(typeInfo)
+ if (!(TypeCheckUtils.isLong(t) || TypeCheckUtils.isTimePoint(t))) {
+ throw new TableException(
+ s"The rowtime attribute can only replace a field with a valid time type, " +
+ s"such as Timestamp or Long. But was: $typeInfo")
+ }
+ }
+
+ def extractRowtime(idx: Int, name: String, origName: Option[String]): Unit = {
+ if (rowtime.isDefined) {
+ throw new TableException(
+ "The rowtime attribute can only be defined once in a table schema.")
+ } else {
+ // if the fields are referenced by position,
+ // it is possible to replace an existing field or append the time attribute at the end
+ if (isRefByPos) {
+ // aliases are not permitted
+ if (origName.isDefined) {
+ throw new TableException(
+ s"Invalid alias '${origName.get}' because fields are referenced by position.")
+ }
+ // check type of field that is replaced
+ if (idx < fieldTypes.length) {
+ checkRowtimeType(fieldTypes(idx))
+ }
+ }
+ // check reference-by-name
+ else {
+ val aliasOrName = origName.getOrElse(name)
+ streamType match {
+ // both alias and reference must have a valid type if they replace a field
+ case ct: CompositeType[_] if ct.hasField(aliasOrName) =>
+ val t = ct.getTypeAt(ct.getFieldIndex(aliasOrName))
+ checkRowtimeType(t)
+ // alias could not be found
+ case _ if origName.isDefined =>
+ throw new TableException(s"Alias '${origName.get}' must reference an existing field.")
+ case _ => // ok
+ }
+ }
+
+ rowtime = Some(idx, name)
+ }
+ }
+
+ def extractProctime(idx: Int, name: String): Unit = {
+ if (proctime.isDefined) {
+ throw new TableException(
+ "The proctime attribute can only be defined once in a table schema.")
+ } else {
+ // if the fields are referenced by position,
+ // it is only possible to append the time attribute at the end
+ if (isRefByPos) {
+
+ // check that proctime is only appended
+ if (idx < fieldTypes.length) {
+ throw new TableException(
+ "The proctime attribute can only be appended to the table schema and not replace " +
+ s"an existing field. Please move '$name' to the end of the schema.")
+ }
+ }
+ // check reference-by-name
+ else {
+ streamType match {
+ // proctime attribute must not replace a field
+ case ct: CompositeType[_] if ct.hasField(name) =>
+ throw new TableException(
+ s"The proctime attribute '$name' must not replace an existing field.")
+ case _ => // ok
+ }
+ }
+ proctime = Some(idx, name)
+ }
+ }
+
+ fields.zipWithIndex.foreach {
+ case ("rowtime", idx) =>
+ extractRowtime(idx, "rowtime", None)
+
+ case ("proctime", idx) =>
+ extractProctime(idx, "proctime")
+
+ case (name, _) => fieldNames = name :: fieldNames
+ }
+
+ if (rowtime.isDefined && fieldNames.contains(rowtime.get._2)) {
+ throw new TableException(
+ "The rowtime attribute may not have the same name as an another field.")
+ }
+
+ if (proctime.isDefined && fieldNames.contains(proctime.get._2)) {
+ throw new TableException(
+ "The proctime attribute may not have the same name as an another field.")
+ }
+
+ (rowtime, proctime)
+ }
+
+ /**
* Registers an internal [[StreamTableSource]] in this [[TableEnvironment]]'s catalog without
* name checking. Registered tables can be referenced in SQL queries.
*
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 14ab1b1..a7d86b3 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
@@ -21,7 +21,7 @@ package org.apache.flink.table.api
import org.apache.flink.annotation.VisibleForTesting
import org.apache.flink.api.common.typeinfo.TypeInformation
import org.apache.flink.api.common.typeutils.CompositeType
-import org.apache.flink.api.java.typeutils.{RowTypeInfo, _}
+import org.apache.flink.api.java.typeutils._
import org.apache.flink.api.scala.typeutils.CaseClassTypeInfo
import org.apache.flink.streaming.api.environment.{StreamExecutionEnvironment => JavaStreamExecEnv}
import org.apache.flink.streaming.api.scala.{StreamExecutionEnvironment => ScalaStreamExecEnv}
@@ -48,7 +48,7 @@ import org.apache.flink.types.Row
import org.apache.calcite.config.Lex
import org.apache.calcite.jdbc.CalciteSchema
-import org.apache.calcite.plan.RelOptPlanner
+import org.apache.calcite.plan.{RelOptPlanner, RelTrait, RelTraitDef}
import org.apache.calcite.rel.RelNode
import org.apache.calcite.schema.SchemaPlus
import org.apache.calcite.schema.impl.AbstractTable
@@ -94,10 +94,11 @@ abstract class TableEnvironment(val config: TableConfig) {
// set the executor to evaluate constant expressions
// .executor(new ExpressionReducer(config))
.context(new FlinkContextImpl(config))
+ .traitDefs(getTraitDefs: _*)
.build
// the builder for Calcite RelNodes, Calcite's representation of a relational expression tree.
- protected lazy val relBuilder: FlinkRelBuilder = createRelBuilder
+ protected lazy val relBuilder: FlinkRelBuilder = FlinkRelBuilder.create(frameworkConfig)
// the planner instance used to optimize queries of this TableEnvironment
private lazy val planner: RelOptPlanner = relBuilder.getPlanner
@@ -165,8 +166,8 @@ abstract class TableEnvironment(val config: TableConfig) {
/** Returns the [[QueryConfig]] depends on the concrete type of this TableEnvironment. */
private[flink] def queryConfig: QueryConfig
- /** Returns specific [[FlinkRelBuilder]] depends on the concrete type of this TableEnvironment. */
- protected def createRelBuilder: FlinkRelBuilder
+ /** Returns specific RelTraitDefs depends on the concrete type of this TableEnvironment. */
+ protected def getTraitDefs: Array[RelTraitDef[_ <: RelTrait]]
/** Returns specific query [[Optimizer]] depends on the concrete type of this TableEnvironment. */
protected def getOptimizer: Optimizer
@@ -671,12 +672,15 @@ abstract class TableEnvironment(val config: TableConfig) {
// determine schema definition mode (by position or by name)
val isRefByPos = isReferenceByPosition(t, fields)
- fields.zipWithIndex flatMap { case (name, idx) =>
- if (isRefByPos) {
- Some((idx, name))
- } else {
- referenceByName(name, t).map((_, name))
- }
+ fields.zipWithIndex flatMap {
+ case ("proctime" | "rowtime", _) =>
+ None
+ case (name, idx) =>
+ if (isRefByPos) {
+ Some((idx, name))
+ } else {
+ referenceByName(name, t).map((_, name))
+ }
}
case p: PojoTypeInfo[A] =>
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/calcite/FlinkRelBuilder.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/calcite/FlinkRelBuilder.scala
index ef9ca4c..f902e1e 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/calcite/FlinkRelBuilder.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/calcite/FlinkRelBuilder.scala
@@ -29,6 +29,8 @@ import org.apache.calcite.tools.{FrameworkConfig, RelBuilder}
import java.util.{Collections, Properties}
+import scala.collection.JavaConversions._
+
/**
* Flink specific [[RelBuilder]] that changes the default type factory to a [[FlinkTypeFactory]].
*/
@@ -53,10 +55,7 @@ class FlinkRelBuilder(
object FlinkRelBuilder {
- def create(
- config: FrameworkConfig,
- traitDefs: Array[RelTraitDef[_ <: RelTrait]] = Array(ConventionTraitDef.INSTANCE)
- ): FlinkRelBuilder = {
+ def create(config: FrameworkConfig): FlinkRelBuilder = {
// create Flink type factory
val typeSystem = config.getTypeSystem
@@ -66,7 +65,7 @@ object FlinkRelBuilder {
val context = config.getContext
val planner = new VolcanoPlanner(config.getCostFactory, context)
planner.setExecutor(config.getExecutor)
- traitDefs.foreach(planner.addRelTraitDef)
+ config.getTraitDefs.foreach(planner.addRelTraitDef)
val cluster = FlinkRelOptClusterFactory.create(planner, new RexBuilder(typeFactory))
val calciteSchema = CalciteSchema.from(config.getDefaultSchema)
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/calcite/FlinkRelOptClusterFactory.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/calcite/FlinkRelOptClusterFactory.scala
index 7bd6992..810df72 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/calcite/FlinkRelOptClusterFactory.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/calcite/FlinkRelOptClusterFactory.scala
@@ -18,8 +18,10 @@
package org.apache.flink.table.calcite
+import org.apache.flink.table.plan.cost.FlinkDefaultRelMetadataProvider
+
import org.apache.calcite.plan.{RelOptCluster, RelOptPlanner}
-import org.apache.calcite.rel.metadata.{DefaultRelMetadataProvider, JaninoRelMetadataProvider, RelMetadataQuery}
+import org.apache.calcite.rel.metadata.{JaninoRelMetadataProvider, RelMetadataQuery}
import org.apache.calcite.rex.RexBuilder
/**
@@ -29,8 +31,7 @@ object FlinkRelOptClusterFactory {
def create(planner: RelOptPlanner, rexBuilder: RexBuilder): RelOptCluster = {
val cluster = RelOptCluster.create(planner, rexBuilder)
- // TODO: create a Flink specific metadata provider [FlinkDefaultRelMetadataProvider]
- cluster.setMetadataProvider(DefaultRelMetadataProvider.INSTANCE)
+ cluster.setMetadataProvider(FlinkDefaultRelMetadataProvider.INSTANCE)
// just set metadataProvider is not enough, see
// https://www.mail-archive.com/dev@calcite.apache.org/msg00930.html
RelMetadataQuery.THREAD_PROVIDERS.set(
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/calcite/FlinkTypeFactory.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/calcite/FlinkTypeFactory.scala
index 163d0a7..567c413 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/calcite/FlinkTypeFactory.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/calcite/FlinkTypeFactory.scala
@@ -386,6 +386,11 @@ object FlinkTypeFactory {
case _ => false
}
+ def isProctimeIndicatorType(relDataType: RelDataType): Boolean = relDataType match {
+ case ti: TimeIndicatorRelDataType if !ti.isEventTime => true
+ case _ => false
+ }
+
def toInternalType(relDataType: RelDataType): InternalType = relDataType.getSqlTypeName match {
case BOOLEAN => InternalTypes.BOOLEAN
case TINYINT => InternalTypes.BYTE
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/cost/FlinkDefaultRelMetadataProvider.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/cost/FlinkDefaultRelMetadataProvider.scala
new file mode 100644
index 0000000..2d39f21
--- /dev/null
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/cost/FlinkDefaultRelMetadataProvider.scala
@@ -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.cost
+
+import com.google.common.collect.ImmutableList
+import org.apache.calcite.rel.metadata.{ChainedRelMetadataProvider, DefaultRelMetadataProvider, RelMetadataProvider}
+
+
+object FlinkDefaultRelMetadataProvider {
+
+ val INSTANCE: RelMetadataProvider = ChainedRelMetadataProvider.of(
+ ImmutableList.of(
+ FlinkRelMdSize.SOURCE,
+ DefaultRelMetadataProvider.INSTANCE
+ )
+ )
+}
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/cost/FlinkRelMdSize.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/cost/FlinkRelMdSize.scala
new file mode 100644
index 0000000..db76652
--- /dev/null
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/cost/FlinkRelMdSize.scala
@@ -0,0 +1,44 @@
+/*
+ * 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.cost
+
+import org.apache.calcite.rel.RelNode
+import org.apache.calcite.rel.metadata.{ReflectiveRelMetadataProvider, RelMdSize, RelMetadataProvider, RelMetadataQuery}
+import org.apache.calcite.util.BuiltInMethod
+
+import java.lang.Double
+import java.util
+
+import scala.collection.JavaConversions._
+
+class FlinkRelMdSize extends RelMdSize {
+
+ override def averageColumnSizes(rel: RelNode, mq: RelMetadataQuery): util.List[Double] = {
+ rel.getRowType.getFieldList.map(f => averageTypeValueSize(f.getType)).toList
+ }
+}
+
+object FlinkRelMdSize {
+ private val INSTANCE = new FlinkRelMdSize
+
+ val SOURCE: RelMetadataProvider = ReflectiveRelMetadataProvider.reflectiveSource(
+ INSTANCE,
+ BuiltInMethod.AVERAGE_COLUMN_SIZES.method,
+ BuiltInMethod.AVERAGE_ROW_SIZE.method)
+}
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/calcite/LogicalRank.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/calcite/LogicalRank.scala
index c5eb9ab..de4238e 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/calcite/LogicalRank.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/calcite/LogicalRank.scala
@@ -18,9 +18,11 @@
package org.apache.flink.table.plan.nodes.calcite
+import org.apache.flink.table.plan.nodes.calcite.RankType.RankType
+
import org.apache.calcite.plan.{Convention, RelOptCluster, RelTraitSet}
+import org.apache.calcite.rel.`type`.RelDataTypeField
import org.apache.calcite.rel.{RelCollation, RelNode}
-import org.apache.calcite.sql.SqlRankFunction
import org.apache.calcite.util.ImmutableBitSet
import java.util
@@ -36,28 +38,34 @@ final class LogicalRank(
cluster: RelOptCluster,
traitSet: RelTraitSet,
input: RelNode,
- rankFunction: SqlRankFunction,
partitionKey: ImmutableBitSet,
- sortCollation: RelCollation,
- rankRange: RankRange)
+ orderKey: RelCollation,
+ rankType: RankType,
+ rankRange: RankRange,
+ rankNumberType: RelDataTypeField,
+ outputRankNumber: Boolean)
extends Rank(
cluster,
traitSet,
input,
- rankFunction,
partitionKey,
- sortCollation,
- rankRange) {
+ orderKey,
+ rankType,
+ rankRange,
+ rankNumberType,
+ outputRankNumber) {
override def copy(traitSet: RelTraitSet, inputs: util.List[RelNode]): RelNode = {
new LogicalRank(
cluster,
traitSet,
inputs.head,
- rankFunction,
partitionKey,
- sortCollation,
- rankRange
+ orderKey,
+ rankType,
+ rankRange,
+ rankNumberType,
+ outputRankNumber
)
}
}
@@ -66,19 +74,23 @@ object LogicalRank {
def create(
input: RelNode,
- rankFunction: SqlRankFunction,
partitionKey: ImmutableBitSet,
- sortCollation: RelCollation,
- rankRange: RankRange): LogicalRank = {
+ orderKey: RelCollation,
+ rankType: RankType,
+ rankRange: RankRange,
+ rankNumberType: RelDataTypeField,
+ outputRankNumber: Boolean): LogicalRank = {
val traits = input.getCluster.traitSetOf(Convention.NONE)
new LogicalRank(
input.getCluster,
traits,
input,
- rankFunction,
partitionKey,
- sortCollation,
- rankRange
+ orderKey,
+ rankType,
+ rankRange,
+ rankNumberType,
+ outputRankNumber
)
}
}
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/calcite/Rank.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/calcite/Rank.scala
index 76dd99a..9e19e02 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/calcite/Rank.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/calcite/Rank.scala
@@ -19,59 +19,56 @@
package org.apache.flink.table.plan.nodes.calcite
import org.apache.flink.table.api.TableException
+import org.apache.flink.table.plan.nodes.calcite.RankType.RankType
import org.apache.flink.table.plan.util._
import org.apache.calcite.plan.{RelOptCluster, RelOptCost, RelOptPlanner, RelTraitSet}
-import org.apache.calcite.rel.`type`.RelDataType
+import org.apache.calcite.rel.`type`.{RelDataType, RelDataTypeField}
import org.apache.calcite.rel.metadata.RelMetadataQuery
import org.apache.calcite.rel.{RelCollation, RelNode, RelWriter, SingleRel}
-import org.apache.calcite.sql.SqlRankFunction
-import org.apache.calcite.sql.`type`.SqlTypeName
import org.apache.calcite.util.{ImmutableBitSet, NumberUtil}
-import java.util
-
import scala.collection.JavaConversions._
/**
- * Relational expression that returns the rows in which the rank function value of each row
+ * Relational expression that returns the rows in which the rank number of each row
* is in the given range.
*
- * <p>NOTES: Different from [[org.apache.calcite.sql.fun.SqlStdOperatorTable.RANK]],
- * [[Rank]] is a Relational expression, not a window function.
- *
- * <p>[[Rank]] will output rank function value as its last column.
- *
- * <p>This RelNode only handles single rank function, is an optimization for some cases. e.g.
- * <ol>
- * <li>
- * single rank function (on `OVER`) with filter in a SQL query statement
- * </li>
- * <li>
- * `ORDER BY` with `LIMIT` in a SQL query statement
- * (equivalent to `ROW_NUMBER` with filter and project)
- * </li>
- * </ol>
+ * The node is an optimization of `OVER` for some special cases,
+ * e.g.
+ * {{{
+ * SELECT * FROM (
+ * SELECT a, b, RANK() OVER (PARTITION BY b ORDER BY c) rk FROM MyTable) t
+ * WHERE rk < 10
+ * }}}
+ * can be converted to this node.
*
- * @param cluster cluster that this relational expression belongs to
- * @param traitSet the traits of this rel
- * @param input input relational expression
- * @param rankFunction rank function, including: CUME_DIST, DENSE_RANK, PERCENT_RANK, RANK,
- * ROW_NUMBER
- * @param partitionKey partition keys (may be empty)
- * @param sortCollation order keys for rank function
- * @param rankRange the expected range of rank function value
+ * @param cluster cluster that this relational expression belongs to
+ * @param traitSet the traits of this rel
+ * @param input input relational expression
+ * @param partitionKey partition keys (may be empty)
+ * @param orderKey order keys (should not empty)
+ * @param rankType rank type to define how exactly generate rank number
+ * @param rankRange the expected range of rank number value
+ * @param rankNumberType the field type of rank number
+ * @param outputRankNumber whether output rank number
*/
abstract class Rank(
cluster: RelOptCluster,
traitSet: RelTraitSet,
input: RelNode,
- val rankFunction: SqlRankFunction,
val partitionKey: ImmutableBitSet,
- val sortCollation: RelCollation,
- val rankRange: RankRange)
+ val orderKey: RelCollation,
+ val rankType: RankType,
+ val rankRange: RankRange,
+ val rankNumberType: RelDataTypeField,
+ val outputRankNumber: Boolean)
extends SingleRel(cluster, traitSet, input) {
+ if (orderKey.getFieldCollations.isEmpty) {
+ throw new TableException("orderKey should not be empty.")
+ }
+
rankRange match {
case r: ConstantRankRange =>
if (r.rankEnd <= 0) {
@@ -91,15 +88,14 @@ abstract class Rank(
}
override def deriveRowType(): RelDataType = {
+ if (!outputRankNumber) {
+ return input.getRowType
+ }
+ // output row type = input row type + rank number type
val typeFactory = cluster.getRexBuilder.getTypeFactory
val typeBuilder = typeFactory.builder()
input.getRowType.getFieldList.foreach(typeBuilder.add)
- // rank function column is always the last column, and its type is BIGINT NOT NULL
- val allFieldNames = new util.HashSet[String]()
- allFieldNames.addAll(input.getRowType.getFieldNames)
- val rankFieldName = FlinkRelOptUtil.buildUniqueFieldName(allFieldNames, "rk")
- val bigIntType = typeFactory.createSqlType(SqlTypeName.BIGINT)
- typeBuilder.add(rankFieldName, typeFactory.createTypeWithNullability(bigIntType, false))
+ typeBuilder.add(rankNumberType)
typeBuilder.build()
}
@@ -108,10 +104,10 @@ abstract class Rank(
case (name, idx) => s"$name=$$$idx"
}.mkString(", ")
super.explainTerms(pw)
- .item("rankFunction", rankFunction)
+ .item("rankType", rankType)
.item("rankRange", rankRange.toString())
.item("partitionBy", partitionKey.map(i => s"$$$i").mkString(","))
- .item("orderBy", RelExplainUtil.collationToString(sortCollation))
+ .item("orderBy", RelExplainUtil.collationToString(orderKey))
.item("select", select)
}
@@ -139,6 +135,37 @@ abstract class Rank(
}
+/**
+ * An enumeration of rank type, usable to tell the [[Rank]] node how exactly generate rank number.
+ */
+object RankType extends Enumeration {
+ type RankType = Value
+
+ /**
+ * Returns a unique sequential number for each row within the partition based on the order,
+ * starting at 1 for the first row in each partition and without repeating or skipping
+ * numbers in the ranking result of each partition. If there are duplicate values within the
+ * row set, the ranking numbers will be assigned arbitrarily.
+ */
+ val ROW_NUMBER: RankType.Value = Value
+
+ /**
+ * Returns a unique rank number for each distinct row within the partition based on the order,
+ * starting at 1 for the first row in each partition, with the same rank for duplicate values
+ * and leaving gaps between the ranks; this gap appears in the sequence after the duplicate
+ * values.
+ */
+ val RANK: RankType.Value = Value
+
+ /**
+ * is similar to the RANK by generating a unique rank number for each distinct row
+ * within the partition based on the order, starting at 1 for the first row in each partition,
+ * ranking the rows with equal values with the same rank number, except that it does not skip
+ * any rank, leaving no gaps between the ranks.
+ */
+ val DENSE_RANK: RankType.Value = Value
+}
+
sealed trait RankRange extends Serializable {
def toString(inputFieldNames: Seq[String]): String
}
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/logical/FlinkLogicalRank.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/logical/FlinkLogicalRank.scala
index 84750ea..806dadf 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/logical/FlinkLogicalRank.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/logical/FlinkLogicalRank.scala
@@ -18,14 +18,14 @@
package org.apache.flink.table.plan.nodes.logical
import org.apache.flink.table.plan.nodes.FlinkConventions
+import org.apache.flink.table.plan.nodes.calcite.RankType.RankType
import org.apache.flink.table.plan.nodes.calcite.{LogicalRank, Rank, RankRange}
import org.apache.flink.table.plan.util.RelExplainUtil
import org.apache.calcite.plan._
-import org.apache.calcite.rel.`type`.RelDataType
+import org.apache.calcite.rel.`type`.RelDataTypeField
import org.apache.calcite.rel.convert.ConverterRule
import org.apache.calcite.rel.{RelCollation, RelNode, RelWriter}
-import org.apache.calcite.sql.SqlRankFunction
import org.apache.calcite.util.ImmutableBitSet
import java.util
@@ -40,29 +40,31 @@ class FlinkLogicalRank(
cluster: RelOptCluster,
traitSet: RelTraitSet,
input: RelNode,
- rankFunction: SqlRankFunction,
partitionKey: ImmutableBitSet,
- sortCollation: RelCollation,
+ orderKey: RelCollation,
+ rankType: RankType,
rankRange: RankRange,
- val outputRankFunColumn: Boolean)
- extends Rank(cluster, traitSet, input, rankFunction, partitionKey, sortCollation, rankRange)
+ rankNumberType: RelDataTypeField,
+ outputRankNumber: Boolean)
+ extends Rank(
+ cluster,
+ traitSet,
+ input,
+ partitionKey,
+ orderKey,
+ rankType,
+ rankRange,
+ rankNumberType,
+ outputRankNumber)
with FlinkLogicalRel {
- override def deriveRowType(): RelDataType = {
- if (outputRankFunColumn) {
- super.deriveRowType()
- } else {
- input.getRowType
- }
- }
-
override def explainTerms(pw: RelWriter): RelWriter = {
val inputFieldNames = input.getRowType.getFieldNames
pw.item("input", getInput)
- .item("rankFunction", rankFunction)
- .item("partitionBy", partitionKey.map(inputFieldNames.get(_)).mkString(","))
- .item("orderBy", RelExplainUtil.collationToString(sortCollation, input.getRowType))
+ .item("rankType", rankType)
.item("rankRange", rankRange.toString(inputFieldNames))
+ .item("partitionBy", partitionKey.map(inputFieldNames.get(_)).mkString(","))
+ .item("orderBy", RelExplainUtil.collationToString(orderKey, input.getRowType))
.item("select", getRowType.getFieldNames.mkString(", "))
}
@@ -71,11 +73,12 @@ class FlinkLogicalRank(
cluster,
traitSet,
inputs.get(0),
- rankFunction,
partitionKey,
- sortCollation,
+ orderKey,
+ rankType,
rankRange,
- outputRankFunColumn)
+ rankNumberType,
+ outputRankNumber)
}
}
@@ -90,11 +93,12 @@ private class FlinkLogicalRankConverter extends ConverterRule(
val newInput = RelOptRule.convert(rank.getInput, FlinkConventions.LOGICAL)
FlinkLogicalRank.create(
newInput,
- rank.rankFunction,
rank.partitionKey,
- rank.sortCollation,
+ rank.orderKey,
+ rank.rankType,
rank.rankRange,
- outputRankFunColumn = true
+ rank.rankNumberType,
+ rank.outputRankNumber
)
}
}
@@ -104,14 +108,23 @@ object FlinkLogicalRank {
def create(
input: RelNode,
- rankFunction: SqlRankFunction,
partitionKey: ImmutableBitSet,
- sortCollation: RelCollation,
+ orderKey: RelCollation,
+ rankType: RankType,
rankRange: RankRange,
- outputRankFunColumn: Boolean): FlinkLogicalRank = {
+ rankNumberType: RelDataTypeField,
+ outputRankNumber: Boolean): FlinkLogicalRank = {
val cluster = input.getCluster
val traits = cluster.traitSet().replace(FlinkConventions.LOGICAL).simplify()
- new FlinkLogicalRank(cluster, traits, input, rankFunction, partitionKey,
- sortCollation, rankRange, outputRankFunColumn)
+ new FlinkLogicalRank(
+ cluster,
+ traits,
+ input,
+ partitionKey,
+ orderKey,
+ rankType,
+ rankRange,
+ rankNumberType,
+ outputRankNumber)
}
}
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/logical/FlinkLogicalSort.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/logical/FlinkLogicalSort.scala
index f2be6f5..eb5768f 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/logical/FlinkLogicalSort.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/logical/FlinkLogicalSort.scala
@@ -18,8 +18,10 @@
package org.apache.flink.table.plan.nodes.logical
+import org.apache.flink.table.api.TableConfigOptions
+import org.apache.flink.table.calcite.FlinkContext
import org.apache.flink.table.plan.nodes.FlinkConventions
-import org.apache.flink.table.plan.util.{FlinkRelOptUtil, RelExplainUtil}
+import org.apache.flink.table.plan.util.FlinkRelOptUtil
import org.apache.calcite.plan._
import org.apache.calcite.rel.convert.ConverterRule
@@ -28,6 +30,7 @@ import org.apache.calcite.rel.logical.LogicalSort
import org.apache.calcite.rel.metadata.RelMetadataQuery
import org.apache.calcite.rel.{RelCollation, RelCollationTraitDef, RelNode}
import org.apache.calcite.rex.{RexLiteral, RexNode}
+import org.apache.calcite.sql.`type`.SqlTypeName
/**
* Sub-class of [[Sort]] that is a relational expression which imposes
@@ -38,9 +41,9 @@ class FlinkLogicalSort(
traits: RelTraitSet,
child: RelNode,
collation: RelCollation,
- offset: RexNode,
- fetch: RexNode)
- extends Sort(cluster, traits, child, collation, offset, fetch)
+ sortOffset: RexNode,
+ sortFetch: RexNode)
+ extends Sort(cluster, traits, child, collation, sortOffset, sortFetch)
with FlinkLogicalRel {
private lazy val limitStart: Long = FlinkRelOptUtil.getLimitStart(offset)
@@ -100,8 +103,21 @@ class FlinkLogicalSortBatchConverter extends ConverterRule(
override def convert(rel: RelNode): RelNode = {
val sort = rel.asInstanceOf[LogicalSort]
val newInput = RelOptRule.convert(sort.getInput, FlinkConventions.LOGICAL)
- // TODO supports range sort
- FlinkLogicalSort.create(newInput, sort.getCollation, sort.offset, sort.fetch)
+ val config = sort.getCluster.getPlanner.getContext.asInstanceOf[FlinkContext].getTableConfig
+ val enableRangeSort = config.getConf.getBoolean(TableConfigOptions.SQL_EXEC_SORT_RANGE_ENABLED)
+ val limitValue = config.getConf.getInteger(TableConfigOptions.SQL_EXEC_SORT_DEFAULT_LIMIT)
+ val (offset, fetch) = if (sort.fetch == null && sort.offset == null
+ && !enableRangeSort && limitValue > 0) {
+ //force the sort add limit
+ val rexBuilder = rel.getCluster.getRexBuilder
+ val intType = rexBuilder.getTypeFactory.createSqlType(SqlTypeName.INTEGER)
+ val offset = rexBuilder.makeLiteral(0, intType, true)
+ val fetch = rexBuilder.makeLiteral(limitValue, intType, true)
+ (offset, fetch)
+ } else {
+ (sort.offset, sort.fetch)
+ }
+ FlinkLogicalSort.create(newInput, sort.getCollation, offset, fetch)
}
}
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 ad63540..d21e975 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
@@ -20,14 +20,14 @@ package org.apache.flink.table.plan.nodes.physical.batch
import org.apache.flink.table.api.TableException
import org.apache.flink.table.plan.cost.{FlinkCost, FlinkCostFactory}
-import org.apache.flink.table.plan.nodes.calcite.{ConstantRankRange, Rank, RankRange}
+import org.apache.flink.table.plan.nodes.calcite.RankType.RankType
+import org.apache.flink.table.plan.nodes.calcite.{ConstantRankRange, Rank, RankRange, RankType}
import org.apache.flink.table.plan.util.RelExplainUtil
import org.apache.calcite.plan._
import org.apache.calcite.rel._
-import org.apache.calcite.rel.`type`.RelDataType
+import org.apache.calcite.rel.`type`.RelDataTypeField
import org.apache.calcite.rel.metadata.RelMetadataQuery
-import org.apache.calcite.sql.{SqlKind, SqlRankFunction}
import org.apache.calcite.util.ImmutableBitSet
import java.util
@@ -36,51 +36,49 @@ import scala.collection.JavaConversions._
/**
* Batch physical RelNode for [[Rank]].
+ *
+ * This node supports two-stage(local and global) rank to reduce data-shuffling.
*/
class BatchExecRank(
cluster: RelOptCluster,
traitSet: RelTraitSet,
inputRel: RelNode,
- rankFunction: SqlRankFunction,
partitionKey: ImmutableBitSet,
- sortCollation: RelCollation,
+ orderKey: RelCollation,
+ rankType: RankType,
rankRange: RankRange,
- val outputRankFunColumn: Boolean,
+ rankNumberType: RelDataTypeField,
+ outputRankNumber: Boolean,
val isGlobal: Boolean)
extends Rank(
cluster,
traitSet,
inputRel,
- rankFunction,
partitionKey,
- sortCollation,
- rankRange)
+ orderKey,
+ rankType,
+ rankRange,
+ rankNumberType,
+ outputRankNumber)
with BatchPhysicalRel {
- require(rankFunction.kind == SqlKind.RANK, "Only RANK function is supported now")
+ require(rankType == RankType.RANK, "Only RANK is supported now")
val (rankStart, rankEnd) = rankRange match {
case r: ConstantRankRange => (r.rankStart, r.rankEnd)
case o => throw new TableException(s"$o is not supported now")
}
- override def deriveRowType(): RelDataType = {
- if (outputRankFunColumn) {
- super.deriveRowType()
- } else {
- inputRel.getRowType
- }
- }
-
override def copy(traitSet: RelTraitSet, inputs: util.List[RelNode]): RelNode = {
new BatchExecRank(
cluster,
traitSet,
inputs.get(0),
- rankFunction,
partitionKey,
- sortCollation,
+ orderKey,
+ rankType,
rankRange,
- outputRankFunColumn,
+ rankNumberType,
+ outputRankNumber,
isGlobal
)
}
@@ -88,10 +86,10 @@ class BatchExecRank(
override def explainTerms(pw: RelWriter): RelWriter = {
val inputRowType = inputRel.getRowType
pw.item("input", getInput)
- .item("rankFunction", rankFunction)
+ .item("rankType", rankType)
.item("rankRange", rankRange.toString(inputRowType.getFieldNames))
.item("partitionBy", RelExplainUtil.fieldToString(partitionKey.toArray, inputRowType))
- .item("orderBy", RelExplainUtil.collationToString(sortCollation, inputRowType))
+ .item("orderBy", RelExplainUtil.collationToString(orderKey, inputRowType))
.item("global", isGlobal)
.item("select", getRowType.getFieldNames.mkString(", "))
}
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecFirstLastRow.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecDeduplicate.scala
similarity index 85%
rename from flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecFirstLastRow.scala
rename to flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecDeduplicate.scala
index c819704..e76af21 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecFirstLastRow.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecDeduplicate.scala
@@ -24,25 +24,25 @@ import org.apache.calcite.rel.{RelNode, RelWriter, SingleRel}
import java.util
-import scala.collection.JavaConversions._
-
/**
* Stream physical RelNode which deduplicate on keys and keeps only first row or last row.
+ * This node is an optimization of [[StreamExecRank]] for some special cases.
+ * Compared to [[StreamExecRank]], this node could use mini-batch and access less state.
* <p>NOTES: only supports sort on proctime now.
*/
-class StreamExecFirstLastRow(
+class StreamExecDeduplicate(
cluster: RelOptCluster,
traitSet: RelTraitSet,
inputRel: RelNode,
uniqueKeys: Array[Int],
isRowtime: Boolean,
- isLastRowMode: Boolean)
+ keepLastRow: Boolean)
extends SingleRel(cluster, traitSet, inputRel)
with StreamPhysicalRel {
def getUniqueKeys: Array[Int] = uniqueKeys
- override def producesUpdates: Boolean = isLastRowMode
+ override def producesUpdates: Boolean = keepLastRow
override def needsUpdatesAsRetraction(input: RelNode): Boolean = true
@@ -55,20 +55,20 @@ class StreamExecFirstLastRow(
override def deriveRowType(): RelDataType = getInput.getRowType
override def copy(traitSet: RelTraitSet, inputs: util.List[RelNode]): RelNode = {
- new StreamExecFirstLastRow(
+ new StreamExecDeduplicate(
cluster,
traitSet,
inputs.get(0),
uniqueKeys,
isRowtime,
- isLastRowMode)
+ keepLastRow)
}
override def explainTerms(pw: RelWriter): RelWriter = {
val fieldNames = getRowType.getFieldNames
val orderString = if (isRowtime) "ROWTIME" else "PROCTIME"
super.explainTerms(pw)
- .item("mode", if (isLastRowMode) "LastRow" else "FirstRow")
+ .item("keepLastRow", keepLastRow)
.item("key", uniqueKeys.map(fieldNames.get).mkString(", "))
.item("order", orderString)
}
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/StreamExecLimit.scala
similarity index 63%
copy from flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecSort.scala
copy to flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecLimit.scala
index 2a366c3..a2dd903 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/StreamExecLimit.scala
@@ -15,11 +15,9 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package org.apache.flink.table.plan.nodes.physical.stream
-import org.apache.flink.annotation.Experimental
-import org.apache.flink.table.plan.util.RelExplainUtil
+import org.apache.flink.table.plan.util.{FlinkRelOptUtil, RelExplainUtil}
import org.apache.calcite.plan.{RelOptCluster, RelTraitSet}
import org.apache.calcite.rel._
@@ -29,25 +27,26 @@ import org.apache.calcite.rex.RexNode
/**
* Stream physical RelNode for [[Sort]].
*
- * <p><b>NOTES:</b> This class is used for testing now.
- *
- * @see [[StreamExecRank]] which must be with `limit` order by.
- * @see [[StreamExecTemporalSort]] which must be time-ascending-order sort without `limit`.
- *
- * <p>e.g.
- * <p>''SELECT * FROM TABLE ORDER BY ROWTIME, a'' will be converted to [[StreamExecTemporalSort]]
- * <p>''SELECT * FROM TABLE ORDER BY a LIMIT 2'' will be converted to [[StreamExecRank]]
- * <p>''SELECT * FROM TABLE ORDER BY a, ROWTIME'' will be converted to [[StreamExecSort]]
+ * This node will output `limit` records beginning with the first `offset` records without sort.
*/
-@Experimental
-class StreamExecSort(
+class StreamExecLimit(
cluster: RelOptCluster,
traitSet: RelTraitSet,
inputRel: RelNode,
- sortCollation: RelCollation)
- extends Sort(cluster, traitSet, inputRel, sortCollation)
+ offset: RexNode,
+ fetch: RexNode)
+ extends Sort(
+ cluster,
+ traitSet,
+ inputRel,
+ RelCollations.EMPTY,
+ offset,
+ fetch)
with StreamPhysicalRel {
+ private lazy val limitStart: Long = FlinkRelOptUtil.getLimitStart(offset)
+ private lazy val limitEnd: Long = FlinkRelOptUtil.getLimitEnd(offset, fetch)
+
override def producesUpdates: Boolean = false
override def needsUpdatesAsRetraction(input: RelNode): Boolean = false
@@ -60,16 +59,17 @@ class StreamExecSort(
override def copy(
traitSet: RelTraitSet,
- input: RelNode,
+ newInput: RelNode,
newCollation: RelCollation,
offset: RexNode,
fetch: RexNode): Sort = {
- new StreamExecSort(cluster, traitSet, input, newCollation)
+ new StreamExecLimit(cluster, traitSet, newInput, offset, fetch)
}
override def explainTerms(pw: RelWriter): RelWriter = {
- pw.input("input", getInput())
- .item("orderBy", RelExplainUtil.collationToString(sortCollation, getRowType))
+ pw.input("input", getInput)
+ .item("offset", limitStart)
+ .item("fetch", RelExplainUtil.fetchToString(fetch))
}
}
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 eb6b9e9..ac833b5 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
@@ -17,14 +17,13 @@
*/
package org.apache.flink.table.plan.nodes.physical.stream
-import org.apache.flink.table.plan.`trait`.TraitUtil
+import org.apache.flink.table.plan.nodes.calcite.RankType.RankType
import org.apache.flink.table.plan.nodes.calcite.{Rank, RankRange}
-import org.apache.flink.table.plan.util.{RelExplainUtil, UpdatingPlanChecker}
+import org.apache.flink.table.plan.util.{RankProcessStrategy, RelExplainUtil, RetractStrategy}
import org.apache.calcite.plan.{RelOptCluster, RelTraitSet}
import org.apache.calcite.rel._
-import org.apache.calcite.rel.`type`.RelDataType
-import org.apache.calcite.sql.SqlRankFunction
+import org.apache.calcite.rel.`type`.RelDataTypeField
import org.apache.calcite.util.ImmutableBitSet
import java.util
@@ -33,35 +32,36 @@ import scala.collection.JavaConversions._
/**
* Stream physical RelNode for [[Rank]].
- *
- * @see [[StreamExecTemporalSort]] which must be time-ascending-order sort without `limit`.
- * @see [[StreamExecSort]] which can be used for testing now, its sort key can be any type.
*/
class StreamExecRank(
cluster: RelOptCluster,
traitSet: RelTraitSet,
inputRel: RelNode,
- rankFunction: SqlRankFunction,
partitionKey: ImmutableBitSet,
- sortCollation: RelCollation,
+ orderKey: RelCollation,
+ rankType: RankType,
rankRange: RankRange,
- val outputRankFunColumn: Boolean)
+ rankNumberType: RelDataTypeField,
+ outputRankNumber: Boolean)
extends Rank(
cluster,
traitSet,
inputRel,
- rankFunction,
partitionKey,
- sortCollation,
- rankRange)
+ orderKey,
+ rankType,
+ rankRange,
+ rankNumberType,
+ outputRankNumber)
with StreamPhysicalRel {
/** please uses [[getStrategy]] instead of this field */
- private var strategy: RankStrategy = _
+ private var strategy: RankProcessStrategy = _
- def getStrategy(forceRecompute: Boolean = false): RankStrategy = {
+ def getStrategy(forceRecompute: Boolean = false): RankProcessStrategy = {
if (strategy == null || forceRecompute) {
- strategy = analyzeRankStrategy
+ strategy = RankProcessStrategy.analyzeRankProcessStrategy(
+ inputRel, partitionKey, orderKey, cluster.getMetadataQuery)
}
strategy
}
@@ -69,7 +69,7 @@ class StreamExecRank(
override def producesUpdates = true
override def needsUpdatesAsRetraction(input: RelNode): Boolean = {
- getStrategy(forceRecompute = true) == RetractRank
+ getStrategy(forceRecompute = true) == RetractStrategy
}
override def consumesRetractions = true
@@ -78,89 +78,27 @@ class StreamExecRank(
override def requireWatermark: Boolean = false
- override def deriveRowType(): RelDataType = {
- if (outputRankFunColumn) {
- super.deriveRowType()
- } else {
- inputRel.getRowType
- }
- }
-
override def copy(traitSet: RelTraitSet, inputs: util.List[RelNode]): RelNode = {
new StreamExecRank(
cluster,
traitSet,
inputs.get(0),
- rankFunction,
partitionKey,
- sortCollation,
+ orderKey,
+ rankType,
rankRange,
- outputRankFunColumn)
+ rankNumberType,
+ outputRankNumber)
}
override def explainTerms(pw: RelWriter): RelWriter = {
val inputRowType = inputRel.getRowType
pw.input("input", getInput)
.item("strategy", getStrategy())
- .item("rankFunction", rankFunction.getKind)
+ .item("rankType", rankType)
.item("rankRange", rankRange.toString(inputRowType.getFieldNames))
.item("partitionBy", RelExplainUtil.fieldToString(partitionKey.toArray, inputRowType))
- .item("orderBy", RelExplainUtil.collationToString(sortCollation, inputRowType))
+ .item("orderBy", RelExplainUtil.collationToString(orderKey, inputRowType))
.item("select", getRowType.getFieldNames.mkString(", "))
}
-
- private def analyzeRankStrategy: RankStrategy = {
- val rankInput = getInput
- val mq = cluster.getMetadataQuery
- val isUpdateStream = !UpdatingPlanChecker.isAppendOnly(rankInput)
-
- if (isUpdateStream) {
- val inputIsAccRetract = TraitUtil.isAccRetract(rankInput)
- val uniqueKeys = mq.getUniqueKeys(rankInput)
- if (inputIsAccRetract || uniqueKeys == null || uniqueKeys.isEmpty
- // unique key should contains partition key
- || !uniqueKeys.exists(k => k.contains(partitionKey))) {
- // input is AccRetract or extract the unique keys failed,
- // and we fall back to using retract rank
- RetractRank
- } else {
- // TODO get `isMonotonic` value by RelModifiedMonotonicity handler
- val isMonotonic = false
-
- if (isMonotonic) {
- //FIXME choose a set of primary key
- UpdateFastRank(uniqueKeys.iterator().next().toArray)
- } else {
- val fieldCollations = sortCollation.getFieldCollations
- if (fieldCollations.length == 1) {
- // single sort key in update stream scenario (no monotonic)
- // we can utilize unary rank function to speed up processing
- UnaryUpdateRank(uniqueKeys.iterator().next().toArray)
- } else {
- // no other choices, have to use retract rank
- RetractRank
- }
- }
- }
- } else {
- AppendFastRank
- }
- }
-}
-
-/**
- * Base class of Strategy to choose different process function.
- */
-sealed trait RankStrategy
-
-case object AppendFastRank extends RankStrategy
-
-case object RetractRank extends RankStrategy
-
-case class UpdateFastRank(primaryKeys: Array[Int]) extends RankStrategy {
- override def toString: String = "UpdateFastRank" + primaryKeys.mkString("[", ",", "]")
-}
-
-case class UnaryUpdateRank(primaryKeys: Array[Int]) extends RankStrategy {
- override def toString: String = "UnaryUpdateRank" + primaryKeys.mkString("[", ",", "]")
}
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 2a366c3..a40c126 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
@@ -29,15 +29,14 @@ import org.apache.calcite.rex.RexNode
/**
* Stream physical RelNode for [[Sort]].
*
- * <p><b>NOTES:</b> This class is used for testing now.
+ * <b>NOTES:</b> This class is used for testing with bounded source now.
+ * If a query is converted to this node in product environment, an exception will be thrown.
*
- * @see [[StreamExecRank]] which must be with `limit` order by.
* @see [[StreamExecTemporalSort]] which must be time-ascending-order sort without `limit`.
*
- * <p>e.g.
- * <p>''SELECT * FROM TABLE ORDER BY ROWTIME, a'' will be converted to [[StreamExecTemporalSort]]
- * <p>''SELECT * FROM TABLE ORDER BY a LIMIT 2'' will be converted to [[StreamExecRank]]
- * <p>''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(
@@ -48,6 +47,10 @@ class StreamExecSort(
extends Sort(cluster, traitSet, inputRel, sortCollation)
with StreamPhysicalRel {
+ /**
+ * this node will not produce or consume retraction message
+ * due to it starts sending data to output after all input data has come.
+ */
override def producesUpdates: Boolean = false
override def needsUpdatesAsRetraction(input: RelNode): Boolean = false
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
new file mode 100644
index 0000000..66dba73
--- /dev/null
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/stream/StreamExecSortLimit.scala
@@ -0,0 +1,101 @@
+/*
+ * 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.physical.stream
+
+import org.apache.flink.table.plan.util.{FlinkRelOptUtil, RankProcessStrategy, RelExplainUtil, RetractStrategy}
+
+import org.apache.calcite.plan.{RelOptCluster, RelTraitSet}
+import org.apache.calcite.rel.core.Sort
+import org.apache.calcite.rel.metadata.RelMetadataQuery
+import org.apache.calcite.rel.{RelCollation, RelNode, RelWriter}
+import org.apache.calcite.rex.{RexLiteral, RexNode}
+import org.apache.calcite.util.ImmutableBitSet
+
+/**
+ * Stream physical RelNode for [[Sort]].
+ *
+ * This RelNode take the `limit` elements beginning with the first `offset` elements.
+ **/
+class StreamExecSortLimit(
+ cluster: RelOptCluster,
+ traitSet: RelTraitSet,
+ inputRel: RelNode,
+ sortCollation: RelCollation,
+ offset: RexNode,
+ fetch: RexNode)
+ extends Sort(cluster, traitSet, inputRel, sortCollation, offset, fetch)
+ with StreamPhysicalRel {
+
+ private val limitStart: Long = FlinkRelOptUtil.getLimitStart(offset)
+ private val limitEnd: Long = FlinkRelOptUtil.getLimitEnd(offset, fetch)
+
+ /** please uses [[getStrategy]] instead of this field */
+ private var strategy: RankProcessStrategy = _
+
+ def getStrategy(forceRecompute: Boolean = false): RankProcessStrategy = {
+ if (strategy == null || forceRecompute) {
+ strategy = RankProcessStrategy.analyzeRankProcessStrategy(
+ inputRel, ImmutableBitSet.of(), sortCollation, cluster.getMetadataQuery)
+ }
+ strategy
+ }
+
+ override def producesUpdates = true
+
+ override def needsUpdatesAsRetraction(input: RelNode): Boolean = {
+ getStrategy(forceRecompute = true) == RetractStrategy
+ }
+
+ override def consumesRetractions = true
+
+ override def producesRetractions: Boolean = false
+
+ override def requireWatermark: Boolean = false
+
+ override def copy(
+ traitSet: RelTraitSet,
+ newInput: RelNode,
+ newCollation: RelCollation,
+ offset: RexNode,
+ fetch: RexNode): Sort = {
+ new StreamExecSortLimit(cluster, traitSet, newInput, newCollation, offset, fetch)
+ }
+
+ override def explainTerms(pw: RelWriter): RelWriter = {
+ pw.input("input", getInput)
+ .item("orderBy", RelExplainUtil.collationToString(sortCollation, getRowType))
+ .item("offset", limitStart)
+ .item("fetch", RelExplainUtil.fetchToString(fetch))
+ }
+
+ override def estimateRowCount(mq: RelMetadataQuery): Double = {
+ val inputRows = mq.getRowCount(this.getInput)
+ if (inputRows == null) {
+ inputRows
+ } else {
+ val rowCount = (inputRows - limitStart).max(1.0)
+ if (fetch != null) {
+ rowCount.min(RexLiteral.intValue(fetch))
+ } else {
+ rowCount
+ }
+ }
+ }
+
+ // TODO check `fetch` is not null in translateToPlan
+}
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/optimize/program/FlinkChainedProgram.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/optimize/program/FlinkChainedProgram.scala
index b389e7e..8595bca 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/optimize/program/FlinkChainedProgram.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/optimize/program/FlinkChainedProgram.scala
@@ -19,10 +19,10 @@
package org.apache.flink.table.plan.optimize.program
import org.apache.flink.table.api.TableException
+import org.apache.flink.table.plan.util.FlinkRelOptUtil
import org.apache.flink.table.util.Logging
import org.apache.flink.util.Preconditions
-import org.apache.calcite.plan.RelOptUtil
import org.apache.calcite.rel.RelNode
import java.util
@@ -64,7 +64,7 @@ class FlinkChainedProgram[OC <: FlinkOptimizeContext]
if (LOG.isDebugEnabled) {
LOG.debug(s"optimize $name cost ${end - start} ms.\n" +
- s"optimize result: \n${RelOptUtil.toString(result)}")
+ s"optimize result: \n${FlinkRelOptUtil.toString(result)}")
}
result
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/optimize/program/FlinkGroupProgram.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/optimize/program/FlinkGroupProgram.scala
index 9360e31..69c97c0 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/optimize/program/FlinkGroupProgram.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/optimize/program/FlinkGroupProgram.scala
@@ -18,10 +18,10 @@
package org.apache.flink.table.plan.optimize.program
+import org.apache.flink.table.plan.util.FlinkRelOptUtil
import org.apache.flink.table.util.Logging
import org.apache.flink.util.Preconditions
-import org.apache.calcite.plan.RelOptUtil
import org.apache.calcite.rel.RelNode
import java.util
@@ -65,7 +65,7 @@ class FlinkGroupProgram[OC <: FlinkOptimizeContext] extends FlinkOptimizeProgram
if (LOG.isDebugEnabled) {
LOG.debug(s"optimize $description cost ${end - start} ms.\n" +
- s"optimize result:\n ${RelOptUtil.toString(result)}")
+ s"optimize result:\n ${FlinkRelOptUtil.toString(result)}")
}
result
}
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/optimize/program/FlinkStreamProgram.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/optimize/program/FlinkStreamProgram.scala
index f15220e..361928e 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/optimize/program/FlinkStreamProgram.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/optimize/program/FlinkStreamProgram.scala
@@ -35,6 +35,7 @@ object FlinkStreamProgram {
val DEFAULT_REWRITE = "default_rewrite"
val PREDICATE_PUSHDOWN = "predicate_pushdown"
val LOGICAL = "logical"
+ val LOGICAL_REWRITE = "logical_rewrite"
val PHYSICAL = "physical"
def buildProgram(config: Configuration): FlinkChainedProgram[StreamOptimizeContext] = {
@@ -97,6 +98,15 @@ object FlinkStreamProgram {
.setRequiredOutputTraits(Array(FlinkConventions.LOGICAL))
.build())
+ // logical rewrite
+ chainedProgram.addLast(
+ LOGICAL_REWRITE,
+ FlinkHepRuleSetProgramBuilder.newBuilder
+ .setHepRulesExecutionType(HEP_RULES_EXECUTION_TYPE.RULE_SEQUENCE)
+ .setHepMatchOrder(HepMatchOrder.BOTTOM_UP)
+ .add(FlinkStreamRuleSets.LOGICAL_REWRITE)
+ .build())
+
// optimize the physical plan
chainedProgram.addLast(
PHYSICAL,
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/optimize/program/FlinkVolcanoProgram.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/optimize/program/FlinkVolcanoProgram.scala
index 7c85c5e..57bc111 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/optimize/program/FlinkVolcanoProgram.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/optimize/program/FlinkVolcanoProgram.scala
@@ -19,11 +19,12 @@
package org.apache.flink.table.plan.optimize.program
import org.apache.flink.table.api.TableException
+import org.apache.flink.table.plan.util.FlinkRelOptUtil
import org.apache.flink.util.Preconditions
import com.google.common.collect.ImmutableList
import org.apache.calcite.plan.RelOptPlanner.CannotPlanException
-import org.apache.calcite.plan.{RelOptUtil, RelTrait}
+import org.apache.calcite.plan.RelTrait
import org.apache.calcite.rel.RelNode
import org.apache.calcite.tools.{Programs, RuleSet}
@@ -64,23 +65,24 @@ class FlinkVolcanoProgram[OC <: FlinkOptimizeContext] extends FlinkRuleSetProgra
case e: CannotPlanException =>
throw new TableException(
s"Cannot generate a valid execution plan for the given query: \n\n" +
- s"${RelOptUtil.toString(root)}\n" +
+ s"${FlinkRelOptUtil.toString(root)}\n" +
s"This exception indicates that the query uses an unsupported SQL feature.\n" +
- s"Please check the documentation for the set of currently supported SQL features.")
+ s"Please check the documentation for the set of currently supported SQL features.", e)
case t: TableException =>
throw new TableException(
s"Cannot generate a valid execution plan for the given query: \n\n" +
- s"${RelOptUtil.toString(root)}\n" +
+ s"${FlinkRelOptUtil.toString(root)}\n" +
s"${t.getMessage}\n" +
- s"Please check the documentation for the set of currently supported SQL features.")
+ s"Please check the documentation for the set of currently supported SQL features.", t)
case a: AssertionError =>
throw new AssertionError(s"Sql optimization: Assertion error: ${a.getMessage}", a)
case r: RuntimeException if r.getCause.isInstanceOf[TableException] =>
throw new TableException(
s"Sql optimization: Cannot generate a valid execution plan for the given query: \n\n" +
- s"${RelOptUtil.toString(root)}\n" +
- s"${r.getMessage}\n" +
- s"Please check the documentation for the set of currently supported SQL features.")
+ s"${FlinkRelOptUtil.toString(root)}\n" +
+ s"${r.getCause.getMessage}\n" +
+ s"Please check the documentation for the set of currently supported SQL features.",
+ r.getCause)
}
}
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/rules/FlinkBatchRuleSets.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/rules/FlinkBatchRuleSets.scala
index 28b8a9a..a675ff7 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/rules/FlinkBatchRuleSets.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/rules/FlinkBatchRuleSets.scala
@@ -20,6 +20,7 @@ package org.apache.flink.table.plan.rules
import org.apache.flink.table.plan.nodes.logical._
import org.apache.flink.table.plan.rules.logical._
+import org.apache.flink.table.plan.rules.physical.FlinkExpandConversionRule
import org.apache.flink.table.plan.rules.physical.batch._
import org.apache.calcite.rel.core.RelFactories
@@ -64,6 +65,9 @@ object FlinkBatchRuleSets {
val DEFAULT_REWRITE_RULES: RuleSet = RuleSets.ofList((
REDUCE_EXPRESSION_RULES.asScala ++
List(
+ // slices a project into sections which contain window agg functions
+ // and sections which do not.
+ ProjectToWindowRule.PROJECT,
//ensure union set operator have the same row type
new CoerceInputsRule(classOf[LogicalUnion], false),
//ensure intersect set operator have the same row type
@@ -162,6 +166,9 @@ object FlinkBatchRuleSets {
// remove unnecessary sort rule
SortRemoveRule.INSTANCE,
+ // rank rules
+ FlinkLogicalRankRule.CONSTANT_RANGE_INSTANCE,
+
// calc rules
FilterCalcMergeRule.INSTANCE,
ProjectCalcMergeRule.INSTANCE,
@@ -205,13 +212,17 @@ object FlinkBatchRuleSets {
* RuleSet to do physical optimize for batch
*/
val PHYSICAL_OPT_RULES: RuleSet = RuleSets.ofList(
+ FlinkExpandConversionRule.BATCH_INSTANCE,
BatchExecBoundedStreamScanRule.INSTANCE,
BatchExecScanTableSourceRule.INSTANCE,
BatchExecValuesRule.INSTANCE,
BatchExecCalcRule.INSTANCE,
BatchExecUnionRule.INSTANCE,
- BatchExecSinkRule.INSTANCE,
+ BatchExecSortRule.INSTANCE,
+ BatchExecLimitRule.INSTANCE,
+ BatchExecSortLimitRule.INSTANCE,
+ BatchExecRankRule.INSTANCE,
BatchExecCorrelateRule.INSTANCE,
- BatchExecUnionRule.INSTANCE
+ BatchExecSinkRule.INSTANCE
)
}
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/rules/FlinkStreamRuleSets.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/rules/FlinkStreamRuleSets.scala
index 9e84399..659b0e0 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/rules/FlinkStreamRuleSets.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/rules/FlinkStreamRuleSets.scala
@@ -20,6 +20,7 @@ package org.apache.flink.table.plan.rules
import org.apache.flink.table.plan.nodes.logical._
import org.apache.flink.table.plan.rules.logical._
+import org.apache.flink.table.plan.rules.physical.FlinkExpandConversionRule
import org.apache.flink.table.plan.rules.physical.stream._
import org.apache.calcite.rel.core.RelFactories
@@ -208,14 +209,29 @@ object FlinkStreamRuleSets {
).asJava)
/**
+ * RuleSet to od rewrite on FlinkLogicalRel for Stream
+ */
+ val LOGICAL_REWRITE: RuleSet = RuleSets.ofList(
+ // transform over window to topn node
+ FlinkLogicalRankRule.INSTANCE
+ )
+
+ /**
* RuleSet to do physical optimize for stream
*/
val PHYSICAL_OPT_RULES: RuleSet = RuleSets.ofList(
+ FlinkExpandConversionRule.STREAM_INSTANCE,
StreamExecDataStreamScanRule.INSTANCE,
StreamExecTableSourceScanRule.INSTANCE,
StreamExecValuesRule.INSTANCE,
StreamExecCalcRule.INSTANCE,
StreamExecUnionRule.INSTANCE,
+ StreamExecSortRule.INSTANCE,
+ StreamExecLimitRule.INSTANCE,
+ StreamExecSortLimitRule.INSTANCE,
+ StreamExecRankRule.INSTANCE,
+ StreamExecTemporalSortRule.INSTANCE,
+ StreamExecDeduplicateRule.RANK_INSTANCE,
StreamExecCorrelateRule.INSTANCE,
StreamExecSinkRule.INSTANCE
)
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/rules/logical/FlinkLogicalRankRule.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/rules/logical/FlinkLogicalRankRule.scala
new file mode 100644
index 0000000..3a53e2c
--- /dev/null
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/rules/logical/FlinkLogicalRankRule.scala
@@ -0,0 +1,269 @@
+/*
+ * 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.rules.logical
+
+import org.apache.flink.table.api.TableException
+import org.apache.flink.table.calcite.FlinkContext
+import org.apache.flink.table.plan.nodes.calcite.{ConstantRankRange, ConstantRankRangeWithoutEnd, RankType}
+import org.apache.flink.table.plan.nodes.logical.{FlinkLogicalCalc, FlinkLogicalOverWindow, FlinkLogicalRank}
+import org.apache.flink.table.plan.util.RankUtil
+
+import org.apache.calcite.plan.RelOptRule.{any, operand}
+import org.apache.calcite.plan.{RelOptRule, RelOptRuleCall, RelOptUtil}
+import org.apache.calcite.rel.`type`.RelDataTypeField
+import org.apache.calcite.rex.{RexInputRef, RexProgramBuilder, RexUtil}
+import org.apache.calcite.sql.fun.SqlStdOperatorTable
+import org.apache.calcite.sql.{SqlKind, SqlRankFunction}
+
+import scala.collection.JavaConversions._
+
+/**
+ * Planner rule that matches a [[FlinkLogicalCalc]] on a [[FlinkLogicalOverWindow]],
+ * and converts them into a [[FlinkLogicalRank]].
+ */
+abstract class FlinkLogicalRankRuleBase
+ extends RelOptRule(
+ operand(classOf[FlinkLogicalCalc],
+ operand(classOf[FlinkLogicalOverWindow], any()))) {
+
+ override def onMatch(call: RelOptRuleCall): Unit = {
+ val calc: FlinkLogicalCalc = call.rel(0)
+ val window: FlinkLogicalOverWindow = call.rel(1)
+ val group = window.groups.get(0)
+ val rankFun = group.aggCalls.get(0).getOperator.asInstanceOf[SqlRankFunction]
+
+ // the rank function is the last field of LogicalWindow
+ val rankFieldIndex = window.getRowType.getFieldCount - 1
+ val condition = calc.getProgram.getCondition
+ val predicate = calc.getProgram.expandLocalRef(condition)
+
+ val config = calc.getCluster.getPlanner.getContext.asInstanceOf[FlinkContext].getTableConfig
+ val (rankRange, remainingPreds) = RankUtil.extractRankRange(
+ predicate,
+ rankFieldIndex,
+ calc.getCluster.getRexBuilder,
+ config)
+ require(rankRange.isDefined)
+
+ val cluster = window.getCluster
+ val rexBuilder = cluster.getRexBuilder
+
+ val calcProgram = calc.getProgram
+ val exprList = calcProgram.getProjectList.map(calcProgram.expandLocalRef)
+
+ val inputFields = RelOptUtil.InputFinder.bits(exprList, null).toList
+ // TODO use the field name specified by user
+ // the field name may be dropped by `ProjectToWindowRule`. so use field name in calc
+ // if the calc output rank number directly, otherwise use field name in window now
+ val outputRankNumber = inputFields.contains(rankFieldIndex)
+ var rankNumberType: Option[RelDataTypeField] = None
+ if (outputRankNumber) {
+ exprList.zipWithIndex.foreach {
+ case (ref: RexInputRef, index) if ref.getIndex == rankFieldIndex =>
+ rankNumberType = Some(calc.getRowType.getFieldList.get(index))
+ case _ => // do nothing
+ }
+ }
+ if (rankNumberType.isEmpty) {
+ rankNumberType = Some(window.getRowType.getFieldList.get(rankFieldIndex))
+ }
+ require(rankNumberType.isDefined)
+
+ rankRange match {
+ case Some(ConstantRankRange(_, rankEnd)) if rankEnd <= 0 =>
+ throw new TableException(s"Rank end should not less than zero, but now is $rankEnd")
+ case _ => // do nothing
+ }
+
+ val rankType = rankFun match {
+ case SqlStdOperatorTable.RANK => RankType.RANK
+ case SqlStdOperatorTable.ROW_NUMBER => RankType.ROW_NUMBER
+ case SqlStdOperatorTable.DENSE_RANK => RankType.DENSE_RANK
+ case _ => throw new TableException(s"Unsupported rank function: $rankFun")
+ }
+
+ val rank = new FlinkLogicalRank(
+ cluster,
+ window.getTraitSet,
+ window.getInput,
+ group.keys,
+ group.orderKeys,
+ rankType,
+ rankRange.get,
+ rankNumberType.get,
+ outputRankNumber)
+
+ val rankRowType = rank.getRowType
+
+ val newRel = if (RexUtil.isIdentity(exprList, rankRowType) && remainingPreds.isEmpty) {
+ // project is trivial and filter is empty, remove the Calc
+ rank
+ } else {
+ val programBuilder = RexProgramBuilder.create(
+ rexBuilder,
+ rankRowType,
+ calcProgram.getExprList,
+ calcProgram.getProjectList,
+ remainingPreds.orNull,
+ calc.getRowType,
+ true, // normalize
+ null) // simplify
+
+ calc.copy(calc.getTraitSet, rank, programBuilder.getProgram)
+ }
+ call.transformTo(newRel)
+ }
+}
+
+/**
+ * This rule handles [[SqlRankFunction]] and rank range with end.
+ *
+ * The following two example queries could be converted to Rank by this rule:
+ * 1. constant range (rn <= 2):
+ * {{{
+ * SELECT * FROM (
+ * SELECT a, b, ROW_NUMBER() OVER (PARTITION BY b ORDER BY a) rn FROM MyTable) t
+ * WHERE rn <= 2
+ * }}}
+ * 2. variable range (rk < a):
+ * {{{
+ * SELECT * FROM (
+ * SELECT a, b, RANK() OVER (PARTITION BY b ORDER BY c) rk FROM MyTable) t
+ * WHERE rk < a
+ * }}}
+ */
+class FlinkLogicalRankRuleForRangeEnd extends FlinkLogicalRankRuleBase {
+
+ override def matches(call: RelOptRuleCall): Boolean = {
+ val calc: FlinkLogicalCalc = call.rel(0)
+ val window: FlinkLogicalOverWindow = call.rel(1)
+
+ if (window.groups.size > 1) {
+ // only accept one window
+ return false
+ }
+
+ val group = window.groups.get(0)
+ if (group.aggCalls.size > 1) {
+ // only accept one agg call
+ return false
+ }
+
+ val agg = group.aggCalls.get(0)
+ if (!agg.getOperator.isInstanceOf[SqlRankFunction]) {
+ // only accept SqlRankFunction for Rank
+ return false
+ }
+
+ if (group.lowerBound.isUnbounded && group.upperBound.isCurrentRow) {
+ val condition = calc.getProgram.getCondition
+ if (condition != null) {
+ val predicate = calc.getProgram.expandLocalRef(condition)
+ // the rank function is the last field of FlinkLogicalOverWindow
+ val rankFieldIndex = window.getRowType.getFieldCount - 1
+ val config = calc.getCluster.getPlanner.getContext.asInstanceOf[FlinkContext].getTableConfig
+ val (rankRange, remainingPreds) = RankUtil.extractRankRange(
+ predicate,
+ rankFieldIndex,
+ calc.getCluster.getRexBuilder,
+ config)
+
+ rankRange match {
+ case Some(_: ConstantRankRangeWithoutEnd) =>
+ throw new TableException(
+ "Rank end is not specified. Currently rank only support TopN, " +
+ "which means the rank end must be specified.")
+ case _ => // do nothing
+ }
+
+ // remaining predicate must not access rank field attributes
+ val remainingPredsAccessRank = remainingPreds.isDefined &&
+ RankUtil.accessesRankField(remainingPreds.get, rankFieldIndex)
+
+ rankRange.isDefined && !remainingPredsAccessRank
+ } else {
+ false
+ }
+ } else {
+ false
+ }
+ }
+}
+
+/**
+ * This rule only handles RANK function and constant rank range.
+ *
+ * The following example query could be converted to Rank by this rule:
+ * SELECT * FROM (
+ * SELECT a, b, RANK() OVER (PARTITION BY b ORDER BY a) rk FROM MyTable) t
+ * WHERE rk <= 2
+ */
+class FlinkLogicalRankRuleForConstantRange extends FlinkLogicalRankRuleBase {
+ override def matches(call: RelOptRuleCall): Boolean = {
+ val calc: FlinkLogicalCalc = call.rel(0)
+ val window: FlinkLogicalOverWindow = call.rel(1)
+
+ if (window.groups.size > 1) {
+ // only accept one window
+ return false
+ }
+
+ val group = window.groups.get(0)
+ if (group.aggCalls.size > 1) {
+ // only accept one agg call
+ return false
+ }
+
+ val agg = group.aggCalls.get(0)
+ if (agg.getOperator.kind != SqlKind.RANK) {
+ // only accept RANK function
+ return false
+ }
+
+ if (group.lowerBound.isUnbounded && group.upperBound.isCurrentRow) {
+ val condition = calc.getProgram.getCondition
+ if (condition != null) {
+ val predicate = calc.getProgram.expandLocalRef(condition)
+ // the rank function is the last field of FlinkLogicalOverWindow
+ val rankFieldIndex = window.getRowType.getFieldCount - 1
+ val config = calc.getCluster.getPlanner.getContext.asInstanceOf[FlinkContext].getTableConfig
+ val (rankRange, remainingPreds) = RankUtil.extractRankRange(
+ predicate,
+ rankFieldIndex,
+ calc.getCluster.getRexBuilder,
+ config)
+
+ // remaining predicate must not access rank field attributes
+ val remainingPredsAccessRank = remainingPreds.isDefined &&
+ RankUtil.accessesRankField(remainingPreds.get, rankFieldIndex)
+
+ // only support constant rank range
+ rankRange.exists(_.isInstanceOf[ConstantRankRange]) && !remainingPredsAccessRank
+ } else {
+ false
+ }
+ } else {
+ false
+ }
+ }
+}
+
+object FlinkLogicalRankRule {
+ val INSTANCE = new FlinkLogicalRankRuleForRangeEnd
+ val CONSTANT_RANGE_INSTANCE = new FlinkLogicalRankRuleForConstantRange
+}
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/rules/physical/FlinkExpandConversionRule.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/rules/physical/FlinkExpandConversionRule.scala
new file mode 100644
index 0000000..9b7d61a
--- /dev/null
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/rules/physical/FlinkExpandConversionRule.scala
@@ -0,0 +1,166 @@
+/*
+ * 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.rules.physical
+
+import org.apache.flink.table.api.TableException
+import org.apache.flink.table.plan.`trait`._
+import org.apache.flink.table.plan.nodes.FlinkConventions
+import org.apache.flink.table.plan.nodes.physical.batch.{BatchExecExchange, BatchExecSort, BatchPhysicalRel}
+import org.apache.flink.table.plan.nodes.physical.stream.StreamExecExchange
+import org.apache.flink.table.plan.rules.physical.FlinkExpandConversionRule._
+
+import org.apache.calcite.plan.RelOptRule._
+import org.apache.calcite.plan._
+import org.apache.calcite.plan.volcano.AbstractConverter
+import org.apache.calcite.rel.RelDistribution.Type._
+import org.apache.calcite.rel.{RelCollation, RelCollationTraitDef, RelCollations, RelNode}
+
+/**
+ * Rule which converts an [[AbstractConverter]] to a RelNode which satisfies the target traits.
+ */
+class FlinkExpandConversionRule(flinkConvention: Convention)
+ extends RelOptRule(
+ operand(classOf[AbstractConverter],
+ operand(classOf[RelNode], any)),
+ "FlinkExpandConversionRule") {
+
+ override def matches(call: RelOptRuleCall): Boolean = {
+ val toTraitSet = call.rel(0).asInstanceOf[AbstractConverter].getTraitSet
+ val fromTraitSet = call.rel(1).asInstanceOf[RelNode].getTraitSet
+ toTraitSet.contains(flinkConvention) &&
+ fromTraitSet.contains(flinkConvention) &&
+ !fromTraitSet.satisfies(toTraitSet)
+ }
+
+ override def onMatch(call: RelOptRuleCall): Unit = {
+ val converter: AbstractConverter = call.rel(0)
+ val child: RelNode = call.rel(1)
+ val toTraitSet = converter.getTraitSet
+ // try to satisfy required trait by itself.
+ satisfyTraitsBySelf(child, toTraitSet, call)
+ // try to push down required traits to children.
+ satisfyTraitsByInput(child, toTraitSet, call)
+ }
+
+ private def satisfyTraitsBySelf(
+ node: RelNode,
+ requiredTraits: RelTraitSet,
+ call: RelOptRuleCall): Unit = {
+ var transformedNode = node
+ val definedTraitDefs = call.getPlanner.getRelTraitDefs
+ if (definedTraitDefs.contains(FlinkRelDistributionTraitDef.INSTANCE)) {
+ val toDistribution = requiredTraits.getTrait(FlinkRelDistributionTraitDef.INSTANCE)
+ transformedNode = satisfyDistribution(flinkConvention, transformedNode, toDistribution)
+ }
+ if (definedTraitDefs.contains(RelCollationTraitDef.INSTANCE)) {
+ val toCollation = requiredTraits.getTrait(RelCollationTraitDef.INSTANCE)
+ transformedNode = satisfyCollation(flinkConvention, transformedNode, toCollation)
+ }
+ checkSatisfyRequiredTrait(transformedNode, requiredTraits)
+ call.transformTo(transformedNode)
+ }
+
+ private def satisfyTraitsByInput(
+ node: RelNode,
+ requiredTraits: RelTraitSet,
+ call: RelOptRuleCall): Unit = {
+ node match {
+ case batchRel: BatchPhysicalRel =>
+ var otherChoice = batchRel.satisfyTraitsByInput(requiredTraits)
+ if (otherChoice != null) {
+ // It is possible only push down distribution instead of push down both distribution and
+ // collation. So it is necessary to check whether collation satisfy requirement.
+ val requiredCollation = requiredTraits.getTrait(RelCollationTraitDef.INSTANCE)
+ otherChoice = satisfyCollation(flinkConvention, otherChoice, requiredCollation)
+ checkSatisfyRequiredTrait(otherChoice, requiredTraits)
+ call.transformTo(otherChoice)
+ }
+ case _ => // ignore
+ }
+ }
+
+ private def checkSatisfyRequiredTrait(node: RelNode, requiredTraits: RelTraitSet): Unit = {
+ if (!node.getTraitSet.satisfies(requiredTraits)) {
+ throw new RuntimeException(
+ "the node which is converted by FlinkExpandConversionRule can't satisfied the target " +
+ s"traits!\nnode traits: ${node.getTraitSet}\nrequired traits: $requiredTraits")
+ }
+ }
+
+}
+
+object FlinkExpandConversionRule {
+ val BATCH_INSTANCE = new FlinkExpandConversionRule(FlinkConventions.BATCH_PHYSICAL)
+ val STREAM_INSTANCE = new FlinkExpandConversionRule(FlinkConventions.STREAM_PHYSICAL)
+
+ def satisfyDistribution(
+ flinkConvention: Convention,
+ node: RelNode,
+ requiredDistribution: FlinkRelDistribution): RelNode = {
+ val fromTraitSet = node.getTraitSet
+ val fromDistribution = fromTraitSet.getTrait(FlinkRelDistributionTraitDef.INSTANCE)
+ if (!fromDistribution.satisfies(requiredDistribution)) {
+ requiredDistribution.getType match {
+ case SINGLETON | HASH_DISTRIBUTED | RANGE_DISTRIBUTED |
+ BROADCAST_DISTRIBUTED | RANDOM_DISTRIBUTED =>
+ flinkConvention match {
+ case FlinkConventions.BATCH_PHYSICAL =>
+ // replace collation with empty since distribution destroy collation
+ val traitSet = fromTraitSet
+ .replace(requiredDistribution)
+ .replace(flinkConvention)
+ .replace(RelCollations.EMPTY)
+ new BatchExecExchange(node.getCluster, traitSet, node, requiredDistribution)
+ case FlinkConventions.STREAM_PHYSICAL =>
+ val updateAsRetraction = fromTraitSet.getTrait(UpdateAsRetractionTraitDef.INSTANCE)
+ val accMode = fromTraitSet.getTrait(AccModeTraitDef.INSTANCE)
+ // replace collation with empty since distribution destroy collation
+ val traitSet = fromTraitSet
+ .replace(requiredDistribution)
+ .replace(flinkConvention)
+ .replace(RelCollations.EMPTY)
+ .replace(updateAsRetraction)
+ .replace(accMode)
+ new StreamExecExchange(node.getCluster, traitSet, node, requiredDistribution)
+ case _ => throw new TableException(s"Unsupported convention: $flinkConvention")
+ }
+ case _ => throw new TableException(s"Unsupported type: ${requiredDistribution.getType}")
+ }
+ } else {
+ node
+ }
+ }
+
+ def satisfyCollation(
+ flinkConvention: Convention,
+ node: RelNode,
+ requiredCollation: RelCollation): RelNode = {
+ val fromCollation = node.getTraitSet.getTrait(RelCollationTraitDef.INSTANCE)
+ if (!fromCollation.satisfies(requiredCollation)) {
+ val traitSet = node.getTraitSet.replace(requiredCollation).replace(flinkConvention)
+ val sortCollation = RelCollationTraitDef.INSTANCE.canonize(requiredCollation)
+ flinkConvention match {
+ case FlinkConventions.BATCH_PHYSICAL =>
+ new BatchExecSort(node.getCluster, traitSet, node, sortCollation)
+ case _ => throw new TableException(s"Unsupported convention: $flinkConvention")
+ }
+ } else {
+ node
+ }
+ }
+}
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/rules/physical/batch/BatchExecLimitRule.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/rules/physical/batch/BatchExecLimitRule.scala
new file mode 100644
index 0000000..8be9e72
--- /dev/null
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/rules/physical/batch/BatchExecLimitRule.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.rules.physical.batch
+
+import org.apache.flink.table.plan.`trait`.FlinkRelDistribution
+import org.apache.flink.table.plan.nodes.FlinkConventions
+import org.apache.flink.table.plan.nodes.logical.FlinkLogicalSort
+import org.apache.flink.table.plan.nodes.physical.batch.BatchExecLimit
+import org.apache.flink.table.plan.util.FlinkRelOptUtil
+
+import org.apache.calcite.plan.{RelOptRule, RelOptRuleCall}
+import org.apache.calcite.rel.RelNode
+import org.apache.calcite.rel.convert.ConverterRule
+import org.apache.calcite.rex.RexLiteral
+import org.apache.calcite.sql.`type`.SqlTypeName
+
+/**
+ * Rule that matches [[FlinkLogicalSort]] with empty sort fields,
+ * and converts it to
+ * {{{
+ * BatchExecLimit (global)
+ * +- BatchExecExchange (singleton)
+ * +- BatchExecLimit (local)
+ * +- input of sort
+ * }}}
+ * when fetch is not null, or
+ * {{{
+ * BatchExecLimit
+ * +- BatchExecExchange (singleton)
+ * +- input of sort
+ * }}}
+ * when fetch is null.
+ */
+class BatchExecLimitRule
+ extends ConverterRule(
+ classOf[FlinkLogicalSort],
+ FlinkConventions.LOGICAL,
+ FlinkConventions.BATCH_PHYSICAL,
+ "BatchExecLimitRule") {
+
+ override def matches(call: RelOptRuleCall): Boolean = {
+ val sort: FlinkLogicalSort = call.rel(0)
+ // only matches Sort with empty sort fields and non-null fetch
+ val fetch = sort.fetch
+ sort.getCollation.getFieldCollations.isEmpty &&
+ (fetch == null || fetch != null && RexLiteral.intValue(fetch) < Long.MaxValue)
+ }
+
+ override def convert(rel: RelNode): RelNode = {
+ val sort = rel.asInstanceOf[FlinkLogicalSort]
+ val input = sort.getInput
+
+ val traitSet = input.getTraitSet.replace(FlinkConventions.BATCH_PHYSICAL)
+ val newLocalInput = RelOptRule.convert(input, traitSet)
+
+ // if fetch is null, there is no need to create local BatchExecLimit
+ val inputOfExchange = if (sort.fetch != null) {
+ val providedLocalTraitSet = traitSet
+ val limit = FlinkRelOptUtil.getLimitEnd(sort.offset, sort.fetch)
+ val rexBuilder = sort.getCluster.getRexBuilder
+ val intType = rexBuilder.getTypeFactory.createSqlType(SqlTypeName.INTEGER)
+ // for local BatchExecLimit, offset is always 0, and fetch is `limit`
+ new BatchExecLimit(
+ rel.getCluster,
+ providedLocalTraitSet,
+ newLocalInput,
+ rexBuilder.makeLiteral(0, intType, true),
+ rexBuilder.makeLiteral(limit, intType, true), // TODO use Long type for limit ?
+ false)
+ } else {
+ newLocalInput
+ }
+
+ // require SINGLETON exchange
+ val newTraitSet = traitSet.replace(FlinkRelDistribution.SINGLETON)
+ val newInput = RelOptRule.convert(inputOfExchange, newTraitSet)
+
+ // create global BatchExecLimit
+ val providedGlobalTraitSet = newTraitSet
+ new BatchExecLimit(
+ rel.getCluster,
+ providedGlobalTraitSet,
+ newInput,
+ sort.offset,
+ sort.fetch,
+ true)
+ }
+}
+
+object BatchExecLimitRule {
+ val INSTANCE: RelOptRule = new BatchExecLimitRule
+}
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
new file mode 100644
index 0000000..1e8950b
--- /dev/null
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/rules/physical/batch/BatchExecRankRule.scala
@@ -0,0 +1,119 @@
+/*
+ * 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.rules.physical.batch
+
+import org.apache.flink.table.api.TableException
+import org.apache.flink.table.plan.`trait`.FlinkRelDistribution
+import org.apache.flink.table.plan.nodes.FlinkConventions
+import org.apache.flink.table.plan.nodes.calcite.{ConstantRankRange, RankType}
+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.calcite.plan.{RelOptRule, RelOptRuleCall}
+import org.apache.calcite.rel.convert.ConverterRule
+import org.apache.calcite.rel.{RelCollations, RelNode}
+
+import scala.collection.JavaConversions._
+
+/**
+ * Rule that matches [[FlinkLogicalRank]] with rank function and constant rank range,
+ * and converts it to
+ * {{{
+ * BatchExecRank (global)
+ * +- BatchExecExchange (singleton if partition keys is empty, else hash)
+ * +- BatchExecRank (local)
+ * +- input of rank
+ * }}}
+ */
+class BatchExecRankRule
+ extends ConverterRule(
+ classOf[FlinkLogicalRank],
+ FlinkConventions.LOGICAL,
+ FlinkConventions.BATCH_PHYSICAL,
+ "BatchExecRankRule") {
+
+ override def matches(call: RelOptRuleCall): Boolean = {
+ val rank: FlinkLogicalRank = call.rel(0)
+ // Only support rank() now
+ rank.rankType == RankType.RANK && rank.rankRange.isInstanceOf[ConstantRankRange]
+ }
+
+ def convert(rel: RelNode): RelNode = {
+ val rank = rel.asInstanceOf[FlinkLogicalRank]
+ val (_, rankEnd) = rank.rankRange match {
+ case r: ConstantRankRange => (r.rankStart, r.rankEnd)
+ case o => throw new TableException(s"$o is not supported now")
+ }
+
+ 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 sortCollation = RelCollations.of(sortFieldCollations: _*)
+ val localRequiredTraitSet = emptyTraits.replace(sortCollation)
+ val newLocalInput = RelOptRule.convert(rank.getInput, localRequiredTraitSet)
+
+ // create local BatchExecRank
+ val localRankRange = ConstantRankRange(1, rankEnd) // local rank always start from 1
+ val localRank = new BatchExecRank(
+ cluster,
+ emptyTraits,
+ newLocalInput,
+ rank.partitionKey,
+ rank.orderKey,
+ rank.rankType,
+ localRankRange,
+ rank.rankNumberType,
+ outputRankNumber = false,
+ isGlobal = false
+ )
+
+ // create local BatchExecRank
+ val globalRequiredDistribution = if (rank.partitionKey.isEmpty) {
+ FlinkRelDistribution.SINGLETON
+ } else {
+ FlinkRelDistribution.hash(rank.partitionKey.toList, requireStrict = false)
+ }
+
+ val globalRequiredTraitSet = emptyTraits
+ .replace(globalRequiredDistribution)
+ .replace(sortCollation)
+
+ // require SINGLETON or HASH exchange
+ val newGlobalInput = RelOptRule.convert(localRank, globalRequiredTraitSet)
+ val globalRank = new BatchExecRank(
+ cluster,
+ emptyTraits,
+ newGlobalInput,
+ rank.partitionKey,
+ rank.orderKey,
+ rank.rankType,
+ rank.rankRange,
+ rank.rankNumberType,
+ rank.outputRankNumber,
+ isGlobal = true
+ )
+ globalRank
+ }
+}
+
+object BatchExecRankRule {
+ val INSTANCE: RelOptRule = new BatchExecRankRule
+}
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/rules/physical/batch/BatchExecSortLimitRule.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/rules/physical/batch/BatchExecSortLimitRule.scala
new file mode 100644
index 0000000..633698a
--- /dev/null
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/rules/physical/batch/BatchExecSortLimitRule.scala
@@ -0,0 +1,109 @@
+/*
+ * 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.rules.physical.batch
+
+import org.apache.flink.table.plan.`trait`.FlinkRelDistribution
+import org.apache.flink.table.plan.nodes.FlinkConventions
+import org.apache.flink.table.plan.nodes.logical.FlinkLogicalSort
+import org.apache.flink.table.plan.nodes.physical.batch.BatchExecSortLimit
+import org.apache.flink.table.plan.util.FlinkRelOptUtil
+
+import org.apache.calcite.plan.{RelOptRule, RelOptRuleCall}
+import org.apache.calcite.rel.RelNode
+import org.apache.calcite.rel.convert.ConverterRule
+import org.apache.calcite.sql.`type`.SqlTypeName
+
+/**
+ * Rule that matches [[FlinkLogicalSort]] with non-empty sort fields and non-null fetch or offset,
+ * and converts it to
+ * {{{
+ * BatchExecSortLimit (global)
+ * +- BatchExecExchange (singleton)
+ * +- BatchExecSortLimit (local)
+ * +- input of sort
+ * }}}
+ * when fetch is not null, or
+ * {{{
+ * BatchExecSortLimit (global)
+ * +- BatchExecExchange (singleton)
+ * +- input of sort
+ * }}}
+ * when fetch is null
+ */
+class BatchExecSortLimitRule
+ extends ConverterRule(
+ classOf[FlinkLogicalSort],
+ FlinkConventions.LOGICAL,
+ FlinkConventions.BATCH_PHYSICAL,
+ "BatchExecSortLimitRule") {
+
+ override def matches(call: RelOptRuleCall): Boolean = {
+ val sort: FlinkLogicalSort = call.rel(0)
+ // only matches Sort with non-empty sort fields and non-null fetch
+ !sort.getCollation.getFieldCollations.isEmpty && (sort.fetch != null || sort.offset != null)
+ }
+
+ override def convert(rel: RelNode): RelNode = {
+ val sort = rel.asInstanceOf[FlinkLogicalSort]
+ // create local BatchExecSortLimit
+ val localRequiredTrait = sort.getInput.getTraitSet.replace(FlinkConventions.BATCH_PHYSICAL)
+ val localInput = RelOptRule.convert(sort.getInput, localRequiredTrait)
+
+ // if fetch is null, there is no need to create local BatchExecSortLimit
+ val inputOfExchange = if (sort.fetch != null) {
+ val limit = FlinkRelOptUtil.getLimitEnd(sort.offset, sort.fetch)
+ val rexBuilder = sort.getCluster.getRexBuilder
+ val intType = rexBuilder.getTypeFactory.createSqlType(SqlTypeName.INTEGER)
+ val providedLocalTraitSet = localRequiredTrait.replace(sort.getCollation)
+ // for local BatchExecSortLimit, offset is always 0, and fetch is `limit`
+ new BatchExecSortLimit(
+ rel.getCluster,
+ providedLocalTraitSet,
+ localInput,
+ sort.getCollation,
+ rexBuilder.makeLiteral(0, intType, true),
+ rexBuilder.makeLiteral(limit, intType, true),
+ false)
+ } else {
+ localInput
+ }
+
+ // require SINGLETON exchange
+ val requiredTrait = rel.getCluster.getPlanner.emptyTraitSet()
+ .replace(FlinkConventions.BATCH_PHYSICAL)
+ .replace(FlinkRelDistribution.SINGLETON)
+ val newInput = RelOptRule.convert(inputOfExchange, requiredTrait)
+
+ // create global BatchExecSortLimit
+ val providedGlobalTraitSet = requiredTrait.replace(sort.getCollation)
+ new BatchExecSortLimit(
+ rel.getCluster,
+ providedGlobalTraitSet,
+ newInput,
+ sort.getCollation,
+ sort.offset,
+ sort.fetch,
+ true
+ )
+ }
+}
+
+object BatchExecSortLimitRule {
+ val INSTANCE: RelOptRule = new BatchExecSortLimitRule
+}
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/rules/physical/batch/BatchExecSortRule.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/rules/physical/batch/BatchExecSortRule.scala
new file mode 100644
index 0000000..e906e70
--- /dev/null
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/rules/physical/batch/BatchExecSortRule.scala
@@ -0,0 +1,76 @@
+/*
+ * 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.rules.physical.batch
+
+import org.apache.flink.table.api.TableConfigOptions
+import org.apache.flink.table.calcite.FlinkContext
+import org.apache.flink.table.plan.`trait`.FlinkRelDistribution
+import org.apache.flink.table.plan.nodes.FlinkConventions
+import org.apache.flink.table.plan.nodes.logical.FlinkLogicalSort
+import org.apache.flink.table.plan.nodes.physical.batch.BatchExecSort
+
+import org.apache.calcite.plan.{RelOptRule, RelOptRuleCall}
+import org.apache.calcite.rel.RelNode
+import org.apache.calcite.rel.convert.ConverterRule
+
+/**
+ * Rule that matches [[FlinkLogicalSort]] which sort fields is non-empty and both `fetch` and
+ * `offset` are null, and converts it to [[BatchExecSort]].
+ */
+class BatchExecSortRule extends ConverterRule(
+ classOf[FlinkLogicalSort],
+ FlinkConventions.LOGICAL,
+ FlinkConventions.BATCH_PHYSICAL,
+ "BatchExecSortRule") {
+
+ override def matches(call: RelOptRuleCall): Boolean = {
+ val sort: FlinkLogicalSort = call.rel(0)
+ // only matches Sort without fetch and offset
+ !sort.getCollation.getFieldCollations.isEmpty && sort.fetch == null && sort.offset == null
+ }
+
+ override def convert(rel: RelNode): RelNode = {
+ val sort: FlinkLogicalSort = rel.asInstanceOf[FlinkLogicalSort]
+ val input = sort.getInput
+ val config = sort.getCluster.getPlanner.getContext.asInstanceOf[FlinkContext].getTableConfig
+ val enableRangeSort = config.getConf.getBoolean(TableConfigOptions.SQL_EXEC_SORT_RANGE_ENABLED)
+ val distribution = if (enableRangeSort) {
+ FlinkRelDistribution.range(sort.getCollation.getFieldCollations)
+ } else {
+ FlinkRelDistribution.SINGLETON
+ }
+ val requiredTraitSet = input.getTraitSet
+ .replace(distribution)
+ .replace(FlinkConventions.BATCH_PHYSICAL)
+ val providedTraitSet = sort.getTraitSet
+ .replace(distribution)
+ .replace(FlinkConventions.BATCH_PHYSICAL)
+
+ val newInput = RelOptRule.convert(input, requiredTraitSet)
+ new BatchExecSort(
+ sort.getCluster,
+ providedTraitSet,
+ newInput,
+ sort.getCollation)
+ }
+}
+
+object BatchExecSortRule {
+ val INSTANCE: RelOptRule = new BatchExecSortRule
+}
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/rules/physical/stream/StreamExecDeduplicateRule.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/rules/physical/stream/StreamExecDeduplicateRule.scala
new file mode 100644
index 0000000..b07ba7a
--- /dev/null
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/rules/physical/stream/StreamExecDeduplicateRule.scala
@@ -0,0 +1,135 @@
+/*
+ * 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.rules.physical.stream
+
+import org.apache.flink.table.calcite.FlinkTypeFactory
+import org.apache.flink.table.plan.`trait`.FlinkRelDistribution
+import org.apache.flink.table.plan.nodes.FlinkConventions
+import org.apache.flink.table.plan.nodes.calcite.{ConstantRankRange, RankType}
+import org.apache.flink.table.plan.nodes.logical.FlinkLogicalRank
+import org.apache.flink.table.plan.nodes.physical.stream.{StreamExecDeduplicate, StreamExecRank}
+
+import org.apache.calcite.plan.{RelOptRule, RelOptRuleCall}
+import org.apache.calcite.rel.`type`.RelDataType
+import org.apache.calcite.rel.convert.ConverterRule
+import org.apache.calcite.rel.{RelCollation, RelNode}
+
+/**
+ * Rule that matches [[FlinkLogicalRank]] which is sorted by proc-time attribute and
+ * limits 1 and its rank type is ROW_NUMBER, and converts it to [[StreamExecDeduplicate]].
+ *
+ * NOTES: Queries that can be converted to [[StreamExecDeduplicate]] could be converted to
+ * [[StreamExecRank]] too. [[StreamExecDeduplicate]] is more efficient than [[StreamExecRank]]
+ * due to mini-batch and less state access.
+ *
+ * e.g.
+ * 1. {{{
+ * SELECT a, b, c FROM (
+ * SELECT a, b, c, proctime,
+ * ROW_NUMBER() OVER (PARTITION BY a ORDER BY proctime ASC) as row_num
+ * FROM MyTable
+ * ) WHERE row_num <= 1
+ * }}} will be converted to StreamExecDeduplicate which keeps first row.
+ * 2. {{{
+ * SELECT a, b, c FROM (
+ * SELECT a, b, c, proctime,
+ * ROW_NUMBER() OVER (PARTITION BY a ORDER BY proctime DESC) as row_num
+ * FROM MyTable
+ * ) WHERE row_num <= 1
+ * }}} will be converted to StreamExecDeduplicate which keeps last row.
+ */
+class StreamExecDeduplicateRule
+ extends ConverterRule(
+ classOf[FlinkLogicalRank],
+ FlinkConventions.LOGICAL,
+ FlinkConventions.STREAM_PHYSICAL,
+ "StreamExecDeduplicateRule") {
+
+ override def matches(call: RelOptRuleCall): Boolean = {
+ val rank: FlinkLogicalRank = call.rel(0)
+ StreamExecDeduplicateRule.canConvertToDeduplicate(rank)
+ }
+
+ override def convert(rel: RelNode): RelNode = {
+ val rank = rel.asInstanceOf[FlinkLogicalRank]
+ val fieldCollation = rank.orderKey.getFieldCollations.get(0)
+ val fieldType = rank.getInput.getRowType.getFieldList.get(fieldCollation.getFieldIndex).getType
+ val isRowtime = FlinkTypeFactory.isRowtimeIndicatorType(fieldType)
+
+ val requiredDistribution = FlinkRelDistribution.hash(rank.partitionKey.toList)
+ val requiredTraitSet = rel.getCluster.getPlanner.emptyTraitSet()
+ .replace(FlinkConventions.STREAM_PHYSICAL)
+ .replace(requiredDistribution)
+ val convInput: RelNode = RelOptRule.convert(rank.getInput, requiredTraitSet)
+
+ // order by timeIndicator desc ==> lastRow, otherwise is firstRow
+ val isLastRow = fieldCollation.direction.isDescending
+ val providedTraitSet = rel.getTraitSet.replace(FlinkConventions.STREAM_PHYSICAL)
+ new StreamExecDeduplicate(
+ rel.getCluster,
+ providedTraitSet,
+ convInput,
+ rank.partitionKey.toArray,
+ isRowtime,
+ isLastRow)
+ }
+}
+
+object StreamExecDeduplicateRule {
+
+ val RANK_INSTANCE = new StreamExecDeduplicateRule
+
+ /**
+ * Whether the given rank could be converted to [[StreamExecDeduplicate]].
+ *
+ * Returns true if the given rank is sorted by proc-time attribute and limits 1
+ * and its RankFunction is ROW_NUMBER, else false.
+ *
+ * @param rank The [[FlinkLogicalRank]] node
+ * @return True if the input rank could be converted to [[StreamExecDeduplicate]]
+ */
+ def canConvertToDeduplicate(rank: FlinkLogicalRank): Boolean = {
+ val sortCollation = rank.orderKey
+ val rankRange = rank.rankRange
+
+ val isRowNumberType = rank.rankType == RankType.ROW_NUMBER
+
+ val isLimit1 = rankRange match {
+ case ConstantRankRange(rankStart, rankEnd) => rankStart == 1 && rankEnd == 1
+ case _ => false
+ }
+
+ val inputRowType = rank.getInput.getRowType
+ val isSortOnProctime = sortOnProcTimeAttribute(sortCollation, inputRowType)
+
+ !rank.outputRankNumber && isLimit1 && isSortOnProctime && isRowNumberType
+ }
+
+ private def sortOnProcTimeAttribute(
+ sortCollation: RelCollation,
+ inputRowType: RelDataType): Boolean = {
+ if (sortCollation.getFieldCollations.size() != 1) {
+ false
+ } else {
+ val firstSortField = sortCollation.getFieldCollations.get(0)
+ val fieldType = inputRowType.getFieldList.get(firstSortField.getFieldIndex).getType
+ FlinkTypeFactory.isProctimeIndicatorType(fieldType)
+ }
+ }
+}
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/rules/physical/stream/StreamExecLimitRule.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/rules/physical/stream/StreamExecLimitRule.scala
new file mode 100644
index 0000000..1660124
--- /dev/null
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/rules/physical/stream/StreamExecLimitRule.scala
@@ -0,0 +1,70 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.table.plan.rules.physical.stream
+
+import org.apache.flink.table.plan.`trait`.FlinkRelDistribution
+import org.apache.flink.table.plan.nodes.FlinkConventions
+import org.apache.flink.table.plan.nodes.logical.FlinkLogicalSort
+import org.apache.flink.table.plan.nodes.physical.stream.StreamExecLimit
+
+import org.apache.calcite.plan.{RelOptRule, RelOptRuleCall}
+import org.apache.calcite.rel.RelNode
+import org.apache.calcite.rel.convert.ConverterRule
+
+/**
+ * Rule that matches [[FlinkLogicalSort]] with empty sort fields,
+ * and converts it to [[StreamExecLimit]].
+ */
+class StreamExecLimitRule
+ extends ConverterRule(
+ classOf[FlinkLogicalSort],
+ FlinkConventions.LOGICAL,
+ FlinkConventions.STREAM_PHYSICAL,
+ "StreamExecLimitRule") {
+
+ override def matches(call: RelOptRuleCall): Boolean = {
+ val sort: FlinkLogicalSort = call.rel(0)
+ // only matches Sort with empty sort fields
+ sort.getCollation.getFieldCollations.isEmpty
+}
+
+ override def convert(rel: RelNode): RelNode = {
+ val sort = rel.asInstanceOf[FlinkLogicalSort]
+ val input = sort.getInput
+
+ // require SINGLETON exchange
+ val newTraitSet = input.getTraitSet
+ .replace(FlinkConventions.STREAM_PHYSICAL)
+ .replace(FlinkRelDistribution.SINGLETON)
+ val newInput = RelOptRule.convert(input, newTraitSet)
+
+ // create StreamExecLimit
+ val providedGlobalTraitSet = newTraitSet
+ new StreamExecLimit(
+ rel.getCluster,
+ providedGlobalTraitSet,
+ newInput,
+ sort.offset,
+ sort.fetch)
+ }
+}
+
+object StreamExecLimitRule {
+ val INSTANCE: RelOptRule = new StreamExecLimitRule
+}
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/rules/physical/stream/StreamExecRankRule.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/rules/physical/stream/StreamExecRankRule.scala
new file mode 100644
index 0000000..90eac04
--- /dev/null
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/rules/physical/stream/StreamExecRankRule.scala
@@ -0,0 +1,75 @@
+/*
+ * 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.rules.physical.stream
+
+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.stream.{StreamExecDeduplicate, StreamExecRank}
+
+import org.apache.calcite.plan.{RelOptRule, RelOptRuleCall}
+import org.apache.calcite.rel.RelNode
+import org.apache.calcite.rel.convert.ConverterRule
+
+/**
+ * Rule that converts [[FlinkLogicalRank]] with fetch to [[StreamExecRank]].
+ * NOTES: the rank can not be converted to [[StreamExecDeduplicate]].
+ */
+class StreamExecRankRule
+ extends ConverterRule(
+ classOf[FlinkLogicalRank],
+ FlinkConventions.LOGICAL,
+ FlinkConventions.STREAM_PHYSICAL,
+ "StreamExecRankRule") {
+
+ override def matches(call: RelOptRuleCall): Boolean = {
+ val rank: FlinkLogicalRank = call.rel(0)
+ !StreamExecDeduplicateRule.canConvertToDeduplicate(rank)
+ }
+
+ override def convert(rel: RelNode): RelNode = {
+ val rank = rel.asInstanceOf[FlinkLogicalRank]
+ val input = rank.getInput
+ val requiredDistribution = if (!rank.partitionKey.isEmpty) {
+ FlinkRelDistribution.hash(rank.partitionKey.toList)
+ } else {
+ FlinkRelDistribution.SINGLETON
+ }
+ val requiredTraitSet = input.getTraitSet
+ .replace(FlinkConventions.STREAM_PHYSICAL)
+ .replace(requiredDistribution)
+ val providedTraitSet = rank.getTraitSet.replace(FlinkConventions.STREAM_PHYSICAL)
+ val newInput: RelNode = RelOptRule.convert(input, requiredTraitSet)
+
+ new StreamExecRank(
+ rank.getCluster,
+ providedTraitSet,
+ newInput,
+ rank.partitionKey,
+ rank.orderKey,
+ rank.rankType,
+ rank.rankRange,
+ rank.rankNumberType,
+ rank.outputRankNumber)
+ }
+}
+
+object StreamExecRankRule {
+ val INSTANCE: RelOptRule = new StreamExecRankRule
+}
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/rules/physical/stream/StreamExecSortLimitRule.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/rules/physical/stream/StreamExecSortLimitRule.scala
new file mode 100644
index 0000000..4387bdd
--- /dev/null
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/rules/physical/stream/StreamExecSortLimitRule.scala
@@ -0,0 +1,69 @@
+/*
+ * 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.rules.physical.stream
+
+import org.apache.flink.table.plan.`trait`.FlinkRelDistribution
+import org.apache.flink.table.plan.nodes.FlinkConventions
+import org.apache.flink.table.plan.nodes.logical.FlinkLogicalSort
+import org.apache.flink.table.plan.nodes.physical.stream.StreamExecSortLimit
+
+import org.apache.calcite.plan.{RelOptRule, RelOptRuleCall}
+import org.apache.calcite.rel.RelNode
+import org.apache.calcite.rel.convert.ConverterRule
+
+/**
+ * Rule that matches [[FlinkLogicalSort]] with non-empty sort fields and non-null fetch or offset,
+ * and converts it to [[StreamExecSortLimit]].
+ */
+class StreamExecSortLimitRule
+ extends ConverterRule(
+ classOf[FlinkLogicalSort],
+ FlinkConventions.LOGICAL,
+ FlinkConventions.STREAM_PHYSICAL,
+ "StreamExecSortLimitRule") {
+
+ override def matches(call: RelOptRuleCall): Boolean = {
+ val sort: FlinkLogicalSort = call.rel(0)
+ // only matches Sort with non-empty sort fields and non-null fetch
+ !sort.getCollation.getFieldCollations.isEmpty && (sort.fetch != null || sort.offset != null)
+ }
+
+ override def convert(rel: RelNode): RelNode = {
+ val sort: FlinkLogicalSort = rel.asInstanceOf[FlinkLogicalSort]
+ val input = sort.getInput
+ val requiredTraitSet = input.getTraitSet
+ .replace(FlinkRelDistribution.SINGLETON)
+ .replace(FlinkConventions.STREAM_PHYSICAL)
+ val providedTraitSet = sort.getTraitSet
+ .replace(FlinkRelDistribution.SINGLETON)
+ .replace(FlinkConventions.STREAM_PHYSICAL)
+
+ val newInput: RelNode = RelOptRule.convert(input, requiredTraitSet)
+ new StreamExecSortLimit(
+ rel.getCluster,
+ providedTraitSet,
+ newInput,
+ sort.collation,
+ sort.offset,
+ sort.fetch)
+ }
+}
+
+object StreamExecSortLimitRule {
+ val INSTANCE: RelOptRule = new StreamExecSortLimitRule
+}
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/rules/physical/stream/StreamExecSortRule.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/rules/physical/stream/StreamExecSortRule.scala
new file mode 100644
index 0000000..06fd50c
--- /dev/null
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/rules/physical/stream/StreamExecSortRule.scala
@@ -0,0 +1,68 @@
+/*
+ * 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.rules.physical.stream
+
+import org.apache.flink.table.plan.`trait`.FlinkRelDistribution
+import org.apache.flink.table.plan.nodes.FlinkConventions
+import org.apache.flink.table.plan.nodes.logical.FlinkLogicalSort
+import org.apache.flink.table.plan.nodes.physical.stream.StreamExecSort
+
+import org.apache.calcite.plan.{RelOptRule, RelOptRuleCall}
+import org.apache.calcite.rel.RelNode
+import org.apache.calcite.rel.convert.ConverterRule
+import org.apache.calcite.rex.RexLiteral
+
+/**
+ * Rule that matches [[FlinkLogicalSort]] which `fetch` is null or `fetch` is 0,
+ * and converts it to [[StreamExecSort]].
+ */
+class StreamExecSortRule
+ extends ConverterRule(
+ classOf[FlinkLogicalSort],
+ FlinkConventions.LOGICAL,
+ FlinkConventions.STREAM_PHYSICAL,
+ "StreamExecSortRule") {
+
+ override def matches(call: RelOptRuleCall): Boolean = {
+ val sort: FlinkLogicalSort = call.rel(0)
+ !sort.getCollation.getFieldCollations.isEmpty && sort.fetch == null && sort.offset == null &&
+ !StreamExecTemporalSortRule.canConvertToTemporalSort(sort)
+ }
+
+ override def convert(rel: RelNode): RelNode = {
+ val sort: FlinkLogicalSort = rel.asInstanceOf[FlinkLogicalSort]
+ val input = sort.getInput(0)
+ val requiredTraitSet = input.getTraitSet
+ .replace(FlinkRelDistribution.SINGLETON)
+ .replace(FlinkConventions.STREAM_PHYSICAL)
+ val providedTraitSet = sort.getTraitSet
+ .replace(FlinkRelDistribution.SINGLETON)
+ .replace(FlinkConventions.STREAM_PHYSICAL)
+
+ val newInput: RelNode = RelOptRule.convert(input, requiredTraitSet)
+ new StreamExecSort(
+ rel.getCluster,
+ providedTraitSet,
+ newInput,
+ sort.collation)
+ }
+}
+
+object StreamExecSortRule {
+ val INSTANCE: RelOptRule = new StreamExecSortRule
+}
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/rules/physical/stream/StreamExecTemporalSortRule.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/rules/physical/stream/StreamExecTemporalSortRule.scala
new file mode 100644
index 0000000..bdd4abb
--- /dev/null
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/rules/physical/stream/StreamExecTemporalSortRule.scala
@@ -0,0 +1,91 @@
+/*
+ * 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.rules.physical.stream
+
+import org.apache.flink.table.calcite.FlinkTypeFactory
+import org.apache.flink.table.plan.nodes.FlinkConventions
+import org.apache.flink.table.plan.nodes.logical.FlinkLogicalSort
+import org.apache.flink.table.plan.nodes.physical.stream.StreamExecTemporalSort
+
+import org.apache.calcite.plan.{RelOptRule, RelOptRuleCall, RelTraitSet}
+import org.apache.calcite.rel.RelFieldCollation.Direction
+import org.apache.calcite.rel.RelNode
+import org.apache.calcite.rel.convert.ConverterRule
+
+/**
+ * Rule that matches [[FlinkLogicalSort]] which is sorted by time attribute in ascending order
+ * and its `fetch` and `offset` are null, and converts it to [[StreamExecTemporalSort]].
+ */
+class StreamExecTemporalSortRule
+ extends ConverterRule(
+ classOf[FlinkLogicalSort],
+ FlinkConventions.LOGICAL,
+ FlinkConventions.STREAM_PHYSICAL,
+ "StreamExecTemporalSortRule") {
+
+ override def matches(call: RelOptRuleCall): Boolean = {
+ val sort: FlinkLogicalSort = call.rel(0)
+ StreamExecTemporalSortRule.canConvertToTemporalSort(sort)
+ }
+
+ override def convert(rel: RelNode): RelNode = {
+ val sort: FlinkLogicalSort = rel.asInstanceOf[FlinkLogicalSort]
+ val input = sort.getInput()
+ val traitSet: RelTraitSet = rel.getTraitSet.replace(FlinkConventions.STREAM_PHYSICAL)
+ val convInput: RelNode = RelOptRule.convert(input, FlinkConventions.STREAM_PHYSICAL)
+
+ new StreamExecTemporalSort(
+ rel.getCluster,
+ traitSet,
+ convInput,
+ sort.collation)
+ }
+
+}
+
+object StreamExecTemporalSortRule {
+ val INSTANCE: RelOptRule = new StreamExecTemporalSortRule
+
+ /**
+ * Whether the given sort could be converted to [[StreamExecTemporalSort]].
+ *
+ * Return true if the given sort is sorted by time attribute in ascending order
+ * and its `fetch` and `offset` are null, else false.
+ *
+ * @param sort the [[FlinkLogicalSort]] node
+ * @return True if the input sort could be converted to [[StreamExecTemporalSort]]
+ */
+ def canConvertToTemporalSort(sort: FlinkLogicalSort): Boolean = {
+ val fieldCollations = sort.collation.getFieldCollations
+ if (sort.fetch != null || sort.offset != null) {
+ return false
+ }
+
+ if (fieldCollations.isEmpty) {
+ false
+ } else {
+ // get type of first sort field
+ val firstSortField = fieldCollations.get(0)
+ val inputRowType = sort.getInput.getRowType
+ val firstSortFieldType = inputRowType.getFieldList.get(firstSortField.getFieldIndex).getType
+ // checks if first sort attribute is time attribute type and order is ascending
+ FlinkTypeFactory.isTimeIndicatorType(firstSortFieldType) &&
+ firstSortField.direction == Direction.ASCENDING
+ }
+ }
+}
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/schema/InlineTable.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/schema/InlineTable.scala
index 84d3977..f363056 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/schema/InlineTable.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/schema/InlineTable.scala
@@ -19,7 +19,7 @@
package org.apache.flink.table.plan.schema
import org.apache.flink.api.common.typeinfo.TypeInformation
-import org.apache.flink.table.`type`.{InternalType, RowType, TypeConverters}
+import org.apache.flink.table.`type`.{InternalType, InternalTypes, RowType, TypeConverters}
import org.apache.flink.table.api.TableException
import org.apache.flink.table.calcite.FlinkTypeFactory
import org.apache.flink.table.plan.stats.FlinkStatistic
@@ -65,11 +65,33 @@ abstract class InlineTable[T](
s"Arity of type (" + rt.getFieldNames.deep + ") " +
"must not be greater than number of field names " + fieldNames.deep + ".")
}
- fieldIndexes.map(i => rt.getTypeAt(i))
+ fieldIndexes.map {
+ case InternalTypes.ROWTIME_STREAM_MARKER =>
+ InternalTypes.ROWTIME_INDICATOR
+ case InternalTypes.PROCTIME_STREAM_MARKER =>
+ InternalTypes.PROCTIME_INDICATOR
+ case InternalTypes.ROWTIME_BATCH_MARKER =>
+ InternalTypes.TIMESTAMP
+ case InternalTypes.PROCTIME_BATCH_MARKER =>
+ InternalTypes.TIMESTAMP
+ case i => rt.getTypeAt(i)
+ }
case t: InternalType =>
- val cnt = fieldIndexes.length
- val types = Array(t)
+ var cnt = 0
+ val types = fieldIndexes.map {
+ case InternalTypes.ROWTIME_STREAM_MARKER =>
+ InternalTypes.ROWTIME_INDICATOR
+ case InternalTypes.PROCTIME_STREAM_MARKER =>
+ InternalTypes.PROCTIME_INDICATOR
+ case InternalTypes.ROWTIME_BATCH_MARKER =>
+ InternalTypes.TIMESTAMP
+ case InternalTypes.PROCTIME_BATCH_MARKER =>
+ InternalTypes.TIMESTAMP
+ case _ =>
+ cnt += 1
+ t
+ }
// ensure that the atomic type is matched at most once.
if (cnt > 1) {
throw new TableException(
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 86c3522..34ca30f 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
@@ -47,7 +47,7 @@ object FlinkRelOptUtil {
* @param detailLevel detailLevel defines detail levels for EXPLAIN PLAN.
* @param withIdPrefix whether including ID of RelNode as prefix
* @param withRetractTraits whether including Retraction Traits of RelNode (only apply to
- * StreamPhysicalRel node at present)
+ * StreamPhysicalRel node at present)
* @param withRowType whether including output rowType
* @return explain plan of RelNode
*/
@@ -122,7 +122,8 @@ object FlinkRelOptUtil {
if (fetch != null) {
getLimitStart(offset) + RexLiteral.intValue(fetch)
} else {
- Long.MaxValue
+ // TODO return Long.MaxValue when providing FlinkRelMdRowCount on Sort ?
+ Integer.MAX_VALUE
}
}
@@ -247,5 +248,4 @@ object FlinkRelOptUtil {
JoinInfo.of(left, right, condition)
}
}
-
}
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/util/FlinkRexUtil.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/util/FlinkRexUtil.scala
index ad0d5b9..33ff255 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/util/FlinkRexUtil.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/util/FlinkRexUtil.scala
@@ -17,10 +17,21 @@
*/
package org.apache.flink.table.plan.util
+import com.google.common.base.Function
+import com.google.common.collect.{ImmutableList, Lists}
+import org.apache.calcite.plan.{RelOptPredicateList, RelOptUtil}
import org.apache.calcite.rel.`type`.RelDataType
import org.apache.calcite.rex._
+import org.apache.calcite.sql.SqlKind
+import org.apache.calcite.sql.fun.SqlStdOperatorTable
+import org.apache.calcite.sql.fun.SqlStdOperatorTable._
+import org.apache.calcite.util.{ControlFlowException, Util}
+
+import java.lang.Iterable
+import java.util
import scala.collection.JavaConversions._
+import scala.collection.mutable
/**
* Utility methods concerning [[RexNode]].
@@ -28,6 +39,267 @@ import scala.collection.JavaConversions._
object FlinkRexUtil {
/**
+ * Similar to [[RexUtil#toCnf(RexBuilder, Int, RexNode)]]; it lets you
+ * specify a threshold in the number of nodes that can be created out of
+ * the conversion. however, if the threshold is a negative number,
+ * this method will give a default threshold value that is double of
+ * the number of RexCall in the given node.
+ *
+ * <p>If the number of resulting RexCalls exceeds that threshold,
+ * stops conversion and returns the original expression.
+ *
+ * <p>Leaf nodes(e.g. RexInputRef) in the expression do not count towards the threshold.
+ *
+ * <p>We strongly discourage use the [[RexUtil#toCnf(RexBuilder, RexNode)]] and
+ * [[RexUtil#toCnf(RexBuilder, Int, RexNode)]], because there are many bad case when using
+ * [[RexUtil#toCnf(RexBuilder, RexNode)]], such as predicate in TPC-DS q41.sql will be
+ * converted to extremely complex expression (including 736450 RexCalls); and we can not give
+ * an appropriate value for `maxCnfNodeCount` when using
+ * [[RexUtil#toCnf(RexBuilder, Int, RexNode)]].
+ */
+ def toCnf(rexBuilder: RexBuilder, maxCnfNodeCount: Int, rex: RexNode): RexNode = {
+ val maxCnfNodeCnt = if (maxCnfNodeCount < 0) {
+ getNumberOfRexCall(rex) * 2
+ } else {
+ maxCnfNodeCount
+ }
+ new CnfHelper(rexBuilder, maxCnfNodeCnt).toCnf(rex)
+ }
+
+ /**
+ * Get the number of RexCall in the given node.
+ */
+ private def getNumberOfRexCall(rex: RexNode): Int = {
+ var numberOfNodes = 0
+ rex.accept(new RexVisitorImpl[Unit](true) {
+ override def visitCall(call: RexCall): Unit = {
+ numberOfNodes += 1
+ super.visitCall(call)
+ }
+ })
+ numberOfNodes
+ }
+
+ /** Helps [[toCnf]] */
+ private class CnfHelper(rexBuilder: RexBuilder, maxNodeCount: Int) {
+
+ /** Exception to catch when we pass the limit. */
+ @SuppressWarnings(Array("serial"))
+ private class OverflowError extends ControlFlowException {
+ }
+
+ @SuppressWarnings(Array("ThrowableInstanceNeverThrown"))
+ private val INSTANCE = new OverflowError
+
+ private val ADD_NOT = new Function[RexNode, RexNode]() {
+ override def apply(input: RexNode): RexNode =
+ rexBuilder.makeCall(input.getType, SqlStdOperatorTable.NOT, ImmutableList.of(input))
+ }
+
+ def toCnf(rex: RexNode): RexNode = try {
+ toCnf2(rex)
+ } catch {
+ case e: OverflowError =>
+ Util.swallow(e, null)
+ rex
+ }
+
+ private def toCnf2(rex: RexNode): RexNode = {
+ rex.getKind match {
+ case SqlKind.AND =>
+ val cnfOperands: util.List[RexNode] = Lists.newArrayList()
+ val operands = RexUtil.flattenAnd(rex.asInstanceOf[RexCall].operands)
+ operands.foreach { node =>
+ val cnf = toCnf2(node)
+ cnf.getKind match {
+ case SqlKind.AND =>
+ cnfOperands.addAll(cnf.asInstanceOf[RexCall].operands)
+ case _ =>
+ cnfOperands.add(cnf)
+ }
+ }
+ val node = and(cnfOperands)
+ checkCnfRexCallCount(node)
+ node
+ case SqlKind.OR =>
+ val operands = RexUtil.flattenOr(rex.asInstanceOf[RexCall].operands)
+ val head = operands.head
+ val headCnf = toCnf2(head)
+ val headCnfs: util.List[RexNode] = RelOptUtil.conjunctions(headCnf)
+ val tail = or(Util.skip(operands))
+ val tailCnf: RexNode = toCnf2(tail)
+ val tailCnfs: util.List[RexNode] = RelOptUtil.conjunctions(tailCnf)
+ val list: util.List[RexNode] = Lists.newArrayList()
+ headCnfs.foreach { h =>
+ tailCnfs.foreach {
+ t => list.add(or(ImmutableList.of(h, t)))
+ }
+ }
+ val node = and(list)
+ checkCnfRexCallCount(node)
+ node
+ case SqlKind.NOT =>
+ val arg = rex.asInstanceOf[RexCall].operands.head
+ arg.getKind match {
+ case SqlKind.NOT =>
+ toCnf2(arg.asInstanceOf[RexCall].operands.head)
+ case SqlKind.OR =>
+ val operands = arg.asInstanceOf[RexCall].operands
+ toCnf2(and(Lists.transform(RexUtil.flattenOr(operands), ADD_NOT)))
+ case SqlKind.AND =>
+ val operands = arg.asInstanceOf[RexCall].operands
+ toCnf2(or(Lists.transform(RexUtil.flattenAnd(operands), ADD_NOT)))
+ case _ => rex
+ }
+ case _ => rex
+ }
+ }
+
+ private def checkCnfRexCallCount(node: RexNode): Unit = {
+ // TODO use more efficient solution to get number of RexCall in CNF node
+ if (maxNodeCount >= 0 && getNumberOfRexCall(node) > maxNodeCount) {
+ throw INSTANCE
+ }
+ }
+
+ private def and(nodes: Iterable[_ <: RexNode]): RexNode =
+ RexUtil.composeConjunction(rexBuilder, nodes, false)
+
+ private def or(nodes: Iterable[_ <: RexNode]): RexNode =
+ RexUtil.composeDisjunction(rexBuilder, nodes)
+ }
+
+ /**
+ * Merges same expressions and then simplifies the result expression by [[RexSimplify]].
+ *
+ * Examples for merging same expressions:
+ * 1. a = b AND b = a -> a = b
+ * 2. a = b OR b = a -> a = b
+ * 3. (a > b AND c < 10) AND b < a -> a > b AND c < 10
+ * 4. (a > b OR c < 10) OR b < a -> a > b OR c < 10
+ * 5. a = a, a >= a, a <= a -> true
+ * 6. a <> a, a > a, a < a -> false
+ */
+ def simplify(rexBuilder: RexBuilder, expr: RexNode): RexNode = {
+ if (expr.isAlwaysTrue || expr.isAlwaysFalse) {
+ return expr
+ }
+
+ val exprShuttle = new EquivalentExprShuttle(rexBuilder)
+ val equiExpr = expr.accept(exprShuttle)
+ val exprMerger = new SameExprMerger(rexBuilder)
+ val sameExprMerged = exprMerger.mergeSameExpr(equiExpr)
+ val binaryComparisonExprReduced = sameExprMerged.accept(
+ new BinaryComparisonExprReducer(rexBuilder))
+
+ val rexSimplify = new RexSimplify(rexBuilder, RelOptPredicateList.EMPTY, true, RexUtil.EXECUTOR)
+ rexSimplify.simplify(binaryComparisonExprReduced)
+ }
+
+ val BINARY_COMPARISON: util.Set[SqlKind] = util.EnumSet.of(
+ SqlKind.EQUALS, SqlKind.NOT_EQUALS,
+ SqlKind.GREATER_THAN, SqlKind.GREATER_THAN_OR_EQUAL,
+ SqlKind.LESS_THAN, SqlKind.LESS_THAN_OR_EQUAL)
+
+ private class BinaryComparisonExprReducer(rexBuilder: RexBuilder) extends RexShuttle {
+ override def visitCall(call: RexCall): RexNode = {
+ val kind = call.getOperator.getKind
+ if (!kind.belongsTo(BINARY_COMPARISON)) {
+ super.visitCall(call)
+ } else {
+ val operand0 = call.getOperands.get(0)
+ val operand1 = call.getOperands.get(1)
+ (operand0, operand1) match {
+ case (op0: RexInputRef, op1: RexInputRef) if op0.getIndex == op1.getIndex =>
+ kind match {
+ case SqlKind.EQUALS | SqlKind.LESS_THAN_OR_EQUAL | SqlKind.GREATER_THAN_OR_EQUAL =>
+ rexBuilder.makeLiteral(true)
+ case SqlKind.NOT_EQUALS | SqlKind.LESS_THAN | SqlKind.GREATER_THAN =>
+ rexBuilder.makeLiteral(false)
+ case _ => super.visitCall(call)
+ }
+ case _ => super.visitCall(call)
+ }
+ }
+ }
+ }
+
+ private class SameExprMerger(rexBuilder: RexBuilder) extends RexShuttle {
+ private val sameExprMap = mutable.HashMap[String, RexNode]()
+
+ private def mergeSameExpr(expr: RexNode, equiExpr: RexLiteral): RexNode = {
+ if (sameExprMap.contains(expr.toString)) {
+ equiExpr
+ } else {
+ sameExprMap.put(expr.toString, expr)
+ expr
+ }
+ }
+
+ def mergeSameExpr(expr: RexNode): RexNode = {
+ // merges same expressions in the operands of AND and OR
+ // e.g. a = b AND a = b -> a = b AND true
+ // a = b OR a = b -> a = b OR false
+ val newExpr1 = expr.accept(this)
+
+ // merges same expressions in conjunctions
+ // e.g. (a > b AND c < 10) AND a > b -> a > b AND c < 10 AND true
+ sameExprMap.clear()
+ val newConjunctions = RelOptUtil.conjunctions(newExpr1).map {
+ ex => mergeSameExpr(ex, rexBuilder.makeLiteral(true))
+ }
+ val newExpr2 = newConjunctions.size match {
+ case 0 => newExpr1 // true AND true
+ case 1 => newConjunctions.head
+ case _ => rexBuilder.makeCall(AND, newConjunctions: _*)
+ }
+
+ // merges same expressions in disjunctions
+ // e.g. (a > b OR c < 10) OR a > b -> a > b OR c < 10 OR false
+ sameExprMap.clear()
+ val newDisjunctions = RelOptUtil.disjunctions(newExpr2).map {
+ ex => mergeSameExpr(ex, rexBuilder.makeLiteral(false))
+ }
+ val newExpr3 = newDisjunctions.size match {
+ case 0 => newExpr2 // false OR false
+ case 1 => newDisjunctions.head
+ case _ => rexBuilder.makeCall(OR, newDisjunctions: _*)
+ }
+ newExpr3
+ }
+
+ override def visitCall(call: RexCall): RexNode = {
+ val newCall = call.getOperator match {
+ case AND | OR =>
+ sameExprMap.clear()
+ val newOperands = call.getOperands.map {
+ op =>
+ val value = if (call.getOperator == AND) true else false
+ mergeSameExpr(op, rexBuilder.makeLiteral(value))
+ }
+ call.clone(call.getType, newOperands)
+ case _ => call
+ }
+ super.visitCall(newCall)
+ }
+ }
+
+ /**
+ * Find all inputRefs.
+ * @return InputRef HashSet.
+ */
+ private[flink] def findAllInputRefs(node: RexNode): util.HashSet[RexInputRef] = {
+ val set = new util.HashSet[RexInputRef]
+ node.accept(new RexVisitorImpl[Void](true) {
+ override def visitInputRef(inputRef: RexInputRef): Void = {
+ set.add(inputRef)
+ null
+ }
+ })
+ set
+ }
+
+ /**
* Adjust the condition's field indices according to mapOldToNewIndex.
*
* @param c The condition to be adjusted.
@@ -49,9 +321,42 @@ object FlinkRexUtil {
if (ref.getIndex == inputRef.getIndex && (ref.getType eq inputRef.getType)) {
inputRef
} else {
- // re-use old object, to prevent needless expr cloning
+ // re-use old object, to prevent needless expr cloning
ref
}
}
})
+
+ private class EquivalentExprShuttle(rexBuilder: RexBuilder) extends RexShuttle {
+ private val equiExprMap = mutable.HashMap[String, RexNode]()
+
+ override def visitCall(call: RexCall): RexNode = {
+ call.getOperator match {
+ case EQUALS | NOT_EQUALS | GREATER_THAN | LESS_THAN |
+ GREATER_THAN_OR_EQUAL | LESS_THAN_OR_EQUAL =>
+ val swapped = swapOperands(call)
+ if (equiExprMap.contains(swapped.toString)) {
+ swapped
+ } else {
+ equiExprMap.put(call.toString, call)
+ call
+ }
+ case _ => super.visitCall(call)
+ }
+ }
+
+ private def swapOperands(call: RexCall): RexCall = {
+ val newOp = call.getOperator match {
+ case EQUALS | NOT_EQUALS => call.getOperator
+ case GREATER_THAN => LESS_THAN
+ case GREATER_THAN_OR_EQUAL => LESS_THAN_OR_EQUAL
+ case LESS_THAN => GREATER_THAN
+ case LESS_THAN_OR_EQUAL => GREATER_THAN_OR_EQUAL
+ case _ => throw new IllegalArgumentException(s"Unsupported operator: ${call.getOperator}")
+ }
+ val operands = call.getOperands
+ rexBuilder.makeCall(newOp, operands.last, operands.head).asInstanceOf[RexCall]
+ }
+ }
+
}
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/util/RankProcessStrategy.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/util/RankProcessStrategy.scala
new file mode 100644
index 0000000..f4f26f9
--- /dev/null
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/util/RankProcessStrategy.scala
@@ -0,0 +1,90 @@
+/*
+ * 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`.TraitUtil
+
+import org.apache.calcite.rel.metadata.RelMetadataQuery
+import org.apache.calcite.rel.{RelCollation, RelNode}
+import org.apache.calcite.util.ImmutableBitSet
+
+import scala.collection.JavaConversions._
+
+/**
+ * Base class of Strategy to choose different rank process function.
+ */
+sealed trait RankProcessStrategy
+
+case object AppendFastStrategy extends RankProcessStrategy
+
+case object RetractStrategy extends RankProcessStrategy
+
+case class UpdateFastStrategy(primaryKeys: Array[Int]) extends RankProcessStrategy {
+ override def toString: String = "UpdateFastStrategy" + primaryKeys.mkString("[", ",", "]")
+}
+
+case class UnaryUpdateStrategy(primaryKeys: Array[Int]) extends RankProcessStrategy {
+ override def toString: String = "UnaryUpdateStrategy" + primaryKeys.mkString("[", ",", "]")
+}
+
+object RankProcessStrategy {
+
+ /**
+ * Gets [[RankProcessStrategy]] based on input, partitionKey and orderKey.
+ */
+ def analyzeRankProcessStrategy(
+ input: RelNode,
+ partitionKey: ImmutableBitSet,
+ orderKey: RelCollation,
+ mq: RelMetadataQuery): RankProcessStrategy = {
+
+ val fieldCollations = orderKey.getFieldCollations
+ val isUpdateStream = !UpdatingPlanChecker.isAppendOnly(input)
+
+ if (isUpdateStream) {
+ val inputIsAccRetract = TraitUtil.isAccRetract(input)
+ val uniqueKeys = mq.getUniqueKeys(input)
+ if (inputIsAccRetract || uniqueKeys == null || uniqueKeys.isEmpty
+ // unique key should contains partition key
+ || !uniqueKeys.exists(k => k.contains(partitionKey))) {
+ // input is AccRetract or extract the unique keys failed,
+ // and we fall back to using retract rank
+ RetractStrategy
+ } else {
+ // TODO get `isMonotonic` value by RelModifiedMonotonicity handler
+ val isMonotonic = false
+
+ if (isMonotonic) {
+ //FIXME choose a set of primary key
+ UpdateFastStrategy(uniqueKeys.iterator().next().toArray)
+ } else {
+ if (fieldCollations.length == 1) {
+ // single sort key in update stream scenario (no monotonic)
+ // we can utilize unary rank function to speed up processing
+ UnaryUpdateStrategy(uniqueKeys.iterator().next().toArray)
+ } else {
+ // no other choices, have to use retract rank
+ RetractStrategy
+ }
+ }
+ }
+ } else {
+ AppendFastStrategy
+ }
+ }
+}
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/util/RankUtil.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/util/RankUtil.scala
new file mode 100644
index 0000000..338564c
--- /dev/null
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/util/RankUtil.scala
@@ -0,0 +1,294 @@
+/*
+ * 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.api.{PlannerConfigOptions, TableConfig}
+import org.apache.flink.table.plan.nodes.calcite.{ConstantRankRange, ConstantRankRangeWithoutEnd, Rank, RankRange, VariableRankRange}
+
+import org.apache.calcite.plan.RelOptUtil
+import org.apache.calcite.rex.{RexBuilder, RexCall, RexInputRef, RexLiteral, RexNode, RexUtil}
+import org.apache.calcite.sql.SqlKind
+
+import scala.collection.JavaConversions._
+
+/**
+ * Util for [[Rank]]s.
+ */
+object RankUtil {
+
+ private[this] case class LimitPredicate(rankOnLeftSide: Boolean, pred: RexCall)
+
+ private[this] sealed trait Boundary
+
+ private[this] case class LowerBoundary(lower: Long) extends Boundary
+
+ private[this] case class UpperBoundary(upper: Long) extends Boundary
+
+ private[this] case class BothBoundary(lower: Long, upper: Long) extends Boundary
+
+ private[this] case class InputRefBoundary(inputFieldIndex: Int) extends Boundary
+
+ private[this] sealed trait BoundDefine
+
+ private[this] object Lower extends BoundDefine // defined lower bound
+ private[this] object Upper extends BoundDefine // defined upper bound
+ private[this] object Both extends BoundDefine // defined lower and uppper bound
+
+ /**
+ * Extracts the TopN offset and fetch bounds from a predicate.
+ *
+ * @param predicate predicate
+ * @param rankFieldIndex the index of rank field
+ * @param rexBuilder RexBuilder
+ * @param config TableConfig
+ * @return A Tuple2 of extracted rank range and remaining predicates.
+ */
+ def extractRankRange(
+ predicate: RexNode,
+ rankFieldIndex: Int,
+ rexBuilder: RexBuilder,
+ config: TableConfig): (Option[RankRange], Option[RexNode]) = {
+
+ // Converts the condition to conjunctive normal form (CNF)
+ val cnfNodeCount = config.getConf.getInteger(PlannerConfigOptions.SQL_OPTIMIZER_CNF_NODES_LIMIT)
+ val cnfCondition = FlinkRexUtil.toCnf(rexBuilder, cnfNodeCount, predicate)
+
+ // split the condition into sort limit condition and other condition
+ val (limitPreds: Seq[LimitPredicate], otherPreds: Seq[RexNode]) = cnfCondition match {
+ case c: RexCall if c.getKind == SqlKind.AND =>
+ c.getOperands
+ .map(identifyLimitPredicate(_, rankFieldIndex))
+ .foldLeft((Seq[LimitPredicate](), Seq[RexNode]())) {
+ (preds, analyzed) =>
+ analyzed match {
+ case Left(limitPred) => (preds._1 :+ limitPred, preds._2)
+ case Right(otherPred) => (preds._1, preds._2 :+ otherPred)
+ }
+ }
+ case rex: RexNode =>
+ identifyLimitPredicate(rex, rankFieldIndex) match {
+ case Left(limitPred) => (Seq(limitPred), Seq())
+ case Right(otherPred) => (Seq(), Seq(otherPred))
+ }
+ case _ =>
+ return (None, Some(predicate))
+ }
+
+ if (limitPreds.isEmpty) {
+ // no valid TopN bounds.
+ return (None, Some(predicate))
+ }
+
+ val sortBounds = limitPreds.map(computeWindowBoundFromPredicate(_, rexBuilder, config))
+ val rankRange = sortBounds match {
+ case Seq(Some(LowerBoundary(x)), Some(UpperBoundary(y))) =>
+ ConstantRankRange(x, y)
+ case Seq(Some(UpperBoundary(x)), Some(LowerBoundary(y))) =>
+ ConstantRankRange(y, x)
+ case Seq(Some(LowerBoundary(x))) =>
+ // only offset
+ ConstantRankRangeWithoutEnd(x)
+ case Seq(Some(UpperBoundary(x))) =>
+ // rankStart starts from one
+ ConstantRankRange(1, x)
+ case Seq(Some(BothBoundary(x, y))) =>
+ // nth rank
+ ConstantRankRange(x, y)
+ case Seq(Some(InputRefBoundary(x))) =>
+ VariableRankRange(x)
+ case _ =>
+ // TopN requires at least one rank comparison predicate
+ return (None, Some(predicate))
+ }
+
+ val remainCondition = otherPreds match {
+ case Seq() => None
+ case _ => Some(otherPreds.reduceLeft((l, r) => RelOptUtil.andJoinFilters(rexBuilder, l, r)))
+ }
+
+ (Some(rankRange), remainCondition)
+ }
+
+ /**
+ * Analyzes a predicate and identifies whether it is a valid predicate for a TopN.
+ * A valid TopN predicate is a comparison predicate (<, <=, =>, >) or equal predicate
+ * that accesses rank fields of input rel node, the rank field reference must be on
+ * one side of the condition alone.
+ *
+ * Examples:
+ * - rank <= 10 => valid (Top 10)
+ * - rank + 1 <= 10 => invalid: rank is not alone in the condition
+ * - rank == 10 => valid (10th)
+ * - rank <= rank + 2 => invalid: rank on same side
+ *
+ * @return Either a valid time predicate (Left) or a valid non-time predicate (Right)
+ */
+ private def identifyLimitPredicate(
+ pred: RexNode,
+ rankFieldIndex: Int): Either[LimitPredicate, RexNode] = pred match {
+ case c: RexCall =>
+ c.getKind match {
+ case SqlKind.GREATER_THAN |
+ SqlKind.GREATER_THAN_OR_EQUAL |
+ SqlKind.LESS_THAN |
+ SqlKind.LESS_THAN_OR_EQUAL |
+ SqlKind.EQUALS =>
+
+ val leftTerm = c.getOperands.head
+ val rightTerm = c.getOperands.last
+
+ if (isRankFieldRef(leftTerm, rankFieldIndex) &&
+ !accessesRankField(rightTerm, rankFieldIndex)) {
+ Left(LimitPredicate(rankOnLeftSide = true, c))
+ } else if (isRankFieldRef(rightTerm, rankFieldIndex) &&
+ !accessesRankField(leftTerm, rankFieldIndex)) {
+ Left(LimitPredicate(rankOnLeftSide = false, c))
+ } else {
+ Right(pred)
+ }
+
+ // not a comparison predicate.
+ case _ => Right(pred)
+ }
+ case _ => Right(pred)
+ }
+
+ // checks if the expression is the rank field reference
+ def isRankFieldRef(expr: RexNode, rankFieldIndex: Int): Boolean = expr match {
+ case i: RexInputRef => i.getIndex == rankFieldIndex
+ case _ => false
+ }
+
+ /**
+ * Checks if an expression accesses a rank field.
+ *
+ * @param expr The expression to check.
+ * @param rankFieldIndex The rank field index.
+ * @return True, if the expression accesses a time attribute. False otherwise.
+ */
+ def accessesRankField(expr: RexNode, rankFieldIndex: Int): Boolean = expr match {
+ case i: RexInputRef => i.getIndex == rankFieldIndex
+ case c: RexCall => c.operands.exists(accessesRankField(_, rankFieldIndex))
+ case _ => false
+ }
+
+ /**
+ * Computes the absolute bound on the left operand of a comparison expression and
+ * whether the bound is an upper or lower bound.
+ *
+ * @return sort boundary (lower boundary, upper boundary)
+ */
+ private def computeWindowBoundFromPredicate(
+ limitPred: LimitPredicate,
+ rexBuilder: RexBuilder,
+ config: TableConfig): Option[Boundary] = {
+
+ val bound: BoundDefine = limitPred.pred.getKind match {
+ case SqlKind.GREATER_THAN | SqlKind.GREATER_THAN_OR_EQUAL if limitPred.rankOnLeftSide =>
+ Lower
+ case SqlKind.GREATER_THAN | SqlKind.GREATER_THAN_OR_EQUAL if !limitPred.rankOnLeftSide =>
+ Upper
+ case SqlKind.LESS_THAN | SqlKind.LESS_THAN_OR_EQUAL if limitPred.rankOnLeftSide =>
+ Upper
+ case SqlKind.LESS_THAN | SqlKind.LESS_THAN_OR_EQUAL if !limitPred.rankOnLeftSide =>
+ Lower
+ case SqlKind.EQUALS =>
+ Both
+ }
+
+ val predExpression = if (limitPred.rankOnLeftSide) {
+ limitPred.pred.operands.get(1)
+ } else {
+ limitPred.pred.operands.get(0)
+ }
+
+ (predExpression, bound) match {
+ case (r: RexInputRef, Upper | Both) => Some(InputRefBoundary(r.getIndex))
+ case (_: RexInputRef, Lower) => None
+ case _ =>
+ // reduce predicate to constants to compute bounds
+ val literal = reduceComparisonPredicate(limitPred, rexBuilder, config)
+ if (literal.isEmpty) {
+ None
+ } else {
+ // compute boundary
+ val tmpBoundary: Long = literal.get
+ val boundary = limitPred.pred.getKind match {
+ case SqlKind.LESS_THAN if limitPred.rankOnLeftSide =>
+ tmpBoundary - 1
+ case SqlKind.LESS_THAN =>
+ tmpBoundary + 1
+ case SqlKind.GREATER_THAN if limitPred.rankOnLeftSide =>
+ tmpBoundary + 1
+ case SqlKind.GREATER_THAN =>
+ tmpBoundary - 1
+ case _ =>
+ tmpBoundary
+ }
+ bound match {
+ case Lower => Some(LowerBoundary(boundary))
+ case Upper => Some(UpperBoundary(boundary))
+ case Both => Some(BothBoundary(boundary, boundary))
+ }
+ }
+ }
+ }
+
+ /**
+ * Replaces the rank aggregate reference on of a predicate by a zero literal and
+ * reduces the expressions on both sides to a long literal.
+ *
+ * @param limitPred The limit predicate which both sides are reduced.
+ * @param rexBuilder A RexBuilder
+ * @param config A TableConfig.
+ * @return The values of the reduced literals on both sides of the comparison predicate.
+ */
+ private def reduceComparisonPredicate(
+ limitPred: LimitPredicate,
+ rexBuilder: RexBuilder,
+ config: TableConfig): Option[Long] = {
+
+ val expression = if (limitPred.rankOnLeftSide) {
+ limitPred.pred.operands.get(1)
+ } else {
+ limitPred.pred.operands.get(0)
+ }
+
+ if (!RexUtil.isConstant(expression)) {
+ return None
+ }
+
+ // TODO reduce expression after ExpressionReducer introduced
+ // reduce expression to literal
+ // val exprReducer = new ExpressionReducer(config)
+ // val originList = new util.ArrayList[RexNode]()
+ // originList.add(expression)
+ // val reduceList = new util.ArrayList[RexNode]()
+ // exprReducer.reduce(rexBuilder, originList, reduceList)
+
+ // extract bounds from reduced literal
+ val literals = Array(expression).map {
+ case literal: RexLiteral => Some(literal.getValue2.asInstanceOf[Long])
+ case _ => None
+ }
+
+ literals.head
+ }
+
+}
diff --git a/flink-table/flink-table-planner-blink/src/test/resources/org/apache/flink/table/plan/batch/sql/LimitTest.xml b/flink-table/flink-table-planner-blink/src/test/resources/org/apache/flink/table/plan/batch/sql/LimitTest.xml
new file mode 100644
index 0000000..731f1b5
--- /dev/null
+++ b/flink-table/flink-table-planner-blink/src/test/resources/org/apache/flink/table/plan/batch/sql/LimitTest.xml
@@ -0,0 +1,226 @@
+<?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="testFetch0WithoutOffset">
+ <Resource name="sql">
+ <![CDATA[SELECT a, c FROM MyTable FETCH FIRST 0 ROWS ONLY]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalSort(fetch=[0])
++- LogicalProject(a=[$0], c=[$2])
+ +- LogicalTableScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a, c])
++- Limit(offset=[0], fetch=[0], global=[true])
+ +- Exchange(distribution=[single])
+ +- Limit(offset=[0], fetch=[0], global=[false])
+ +- TableSourceScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testFetchWithOffset">
+ <Resource name="sql">
+ <![CDATA[SELECT a, c FROM MyTable OFFSET 10 ROWS FETCH NEXT 10 ROWS ONLY]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalSort(offset=[10], fetch=[10])
++- LogicalProject(a=[$0], c=[$2])
+ +- LogicalTableScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a, c])
++- Limit(offset=[10], fetch=[10], global=[true])
+ +- Exchange(distribution=[single])
+ +- Limit(offset=[0], fetch=[20], global=[false])
+ +- TableSourceScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testFetchWithoutOffset">
+ <Resource name="sql">
+ <![CDATA[SELECT a, c FROM MyTable FETCH FIRST 10 ROWS ONLY]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalSort(fetch=[10])
++- LogicalProject(a=[$0], c=[$2])
+ +- LogicalTableScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a, c])
++- Limit(offset=[0], fetch=[10], global=[true])
+ +- Exchange(distribution=[single])
+ +- Limit(offset=[0], fetch=[10], global=[false])
+ +- TableSourceScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testLimit0WithOffset">
+ <Resource name="sql">
+ <![CDATA[SELECT a, c FROM MyTable LIMIT 0 OFFSET 10]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalSort(offset=[10], fetch=[0])
++- LogicalProject(a=[$0], c=[$2])
+ +- LogicalTableScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a, c])
++- Limit(offset=[10], fetch=[0], global=[true])
+ +- Exchange(distribution=[single])
+ +- Limit(offset=[0], fetch=[10], global=[false])
+ +- TableSourceScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testLimitWithOffset">
+ <Resource name="sql">
+ <![CDATA[SELECT a, c FROM MyTable LIMIT 10 OFFSET 1]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalSort(offset=[1], fetch=[10])
++- LogicalProject(a=[$0], c=[$2])
+ +- LogicalTableScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a, c])
++- Limit(offset=[1], fetch=[10], global=[true])
+ +- Exchange(distribution=[single])
+ +- Limit(offset=[0], fetch=[11], global=[false])
+ +- TableSourceScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testLimit0WithOffset0">
+ <Resource name="sql">
+ <![CDATA[SELECT a, c FROM MyTable LIMIT 0 OFFSET 0]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalSort(offset=[0], fetch=[0])
++- LogicalProject(a=[$0], c=[$2])
+ +- LogicalTableScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a, c])
++- Limit(offset=[0], fetch=[0], global=[true])
+ +- Exchange(distribution=[single])
+ +- Limit(offset=[0], fetch=[0], global=[false])
+ +- TableSourceScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testLimit0WithoutOffset">
+ <Resource name="sql">
+ <![CDATA[SELECT * FROM MyTable LIMIT 0]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalSort(fetch=[0])
++- LogicalProject(a=[$0], b=[$1], c=[$2])
+ +- LogicalTableScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Limit(offset=[0], fetch=[0], global=[true])
++- Exchange(distribution=[single])
+ +- Limit(offset=[0], fetch=[0], global=[false])
+ +- TableSourceScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testLimitWithOffset0">
+ <Resource name="sql">
+ <![CDATA[SELECT a, c FROM MyTable LIMIT 10 OFFSET 0]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalSort(offset=[0], fetch=[10])
++- LogicalProject(a=[$0], c=[$2])
+ +- LogicalTableScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a, c])
++- Limit(offset=[0], fetch=[10], global=[true])
+ +- Exchange(distribution=[single])
+ +- Limit(offset=[0], fetch=[10], global=[false])
+ +- TableSourceScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testOnlyOffset">
+ <Resource name="sql">
+ <![CDATA[SELECT a, c FROM MyTable OFFSET 10 ROWS]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalSort(offset=[10])
++- LogicalProject(a=[$0], c=[$2])
+ +- LogicalTableScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a, c])
++- Limit(offset=[10], fetch=[unlimited], global=[true])
+ +- Exchange(distribution=[single])
+ +- TableSourceScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testLimitWithoutOffset">
+ <Resource name="sql">
+ <![CDATA[SELECT * FROM MyTable LIMIT 5]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalSort(fetch=[5])
++- LogicalProject(a=[$0], b=[$1], c=[$2])
+ +- LogicalTableScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Limit(offset=[0], fetch=[5], global=[true])
++- Exchange(distribution=[single])
+ +- Limit(offset=[0], fetch=[5], global=[false])
+ +- TableSourceScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
+]]>
+ </Resource>
+ </TestCase>
+</Root>
diff --git a/flink-table/flink-table-planner-blink/src/test/resources/org/apache/flink/table/plan/batch/sql/RankTest.xml b/flink-table/flink-table-planner-blink/src/test/resources/org/apache/flink/table/plan/batch/sql/RankTest.xml
new file mode 100644
index 0000000..8ca38b1
--- /dev/null
+++ b/flink-table/flink-table-planner-blink/src/test/resources/org/apache/flink/table/plan/batch/sql/RankTest.xml
@@ -0,0 +1,217 @@
+<?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="testDuplicateRankFunctionColumnName">
+ <Resource name="sql">
+ <![CDATA[
+SELECT * FROM (
+ SELECT a, b, RANK() OVER (PARTITION BY b ORDER BY a) rk FROM MyTable2) t
+WHERE rk < 10
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0], b=[$1], rk=[$2])
++- LogicalFilter(condition=[<($2, 10)])
+ +- LogicalProject(a=[$0], b=[$1], rk=[RANK() OVER (PARTITION BY $1 ORDER BY $0 NULLS FIRST RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)])
+ +- LogicalTableScan(table=[[MyTable2, source: [TestTableSource(a, b, rk)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a, b, w0$o0 AS $2])
++- Rank(rankType=[RANK], rankRange=[rankStart=1, rankEnd=9], partitionBy=[b], orderBy=[a ASC], global=[true], select=[a, b, rk, w0$o0])
+ +- Sort(orderBy=[b ASC, a ASC])
+ +- Exchange(distribution=[hash[b]])
+ +- Rank(rankType=[RANK], rankRange=[rankStart=1, rankEnd=9], partitionBy=[b], orderBy=[a ASC], global=[false], select=[a, b, rk])
+ +- Sort(orderBy=[b ASC, a ASC])
+ +- TableSourceScan(table=[[MyTable2, source: [TestTableSource(a, b, rk)]]], fields=[a, b, rk])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testMultiSameRankFunctionsWithSameGroup">
+ <Resource name="sql">
+ <![CDATA[
+SELECT * FROM (
+ SELECT a, b,
+ RANK() OVER (PARTITION BY b ORDER BY a) rk1,
+ RANK() OVER (PARTITION BY b ORDER BY a) rk2 FROM MyTable) t
+WHERE rk1 < 10
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0], b=[$1], rk1=[$2], rk2=[$3])
++- LogicalFilter(condition=[<($2, 10)])
+ +- LogicalProject(a=[$0], b=[$1], rk1=[RANK() OVER (PARTITION BY $1 ORDER BY $0 NULLS FIRST RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)], rk2=[RANK() OVER (PARTITION BY $1 ORDER BY $0 NULLS FIRST RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)])
+ +- LogicalTableScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a, b, w0$o0 AS rk1, w0$o0 AS rk2])
++- Rank(rankType=[RANK], rankRange=[rankStart=1, rankEnd=9], partitionBy=[b], orderBy=[a ASC], global=[true], select=[a, b, c, w0$o0])
+ +- Sort(orderBy=[b ASC, a ASC])
+ +- Exchange(distribution=[hash[b]])
+ +- Rank(rankType=[RANK], rankRange=[rankStart=1, rankEnd=9], partitionBy=[b], orderBy=[a ASC], global=[false], select=[a, b, c])
+ +- Sort(orderBy=[b ASC, a ASC])
+ +- TableSourceScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testRankFunctionInMiddle">
+ <Resource name="sql">
+ <![CDATA[
+SELECT * FROM (
+ SELECT a, RANK() OVER (PARTITION BY a ORDER BY a) rk, b, c FROM MyTable) t
+WHERE rk < 10
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0], rk=[$1], b=[$2], c=[$3])
++- LogicalFilter(condition=[<($1, 10)])
+ +- LogicalProject(a=[$0], rk=[RANK() OVER (PARTITION BY $0 ORDER BY $0 NULLS FIRST RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)], b=[$1], c=[$2])
+ +- LogicalTableScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a, w0$o0 AS rk, b, c])
++- Rank(rankType=[RANK], rankRange=[rankStart=1, rankEnd=9], partitionBy=[a], orderBy=[a ASC], global=[true], select=[a, b, c, w0$o0])
+ +- Sort(orderBy=[a ASC])
+ +- Exchange(distribution=[hash[a]])
+ +- Rank(rankType=[RANK], rankRange=[rankStart=1, rankEnd=9], partitionBy=[a], orderBy=[a ASC], global=[false], select=[a, b, c])
+ +- Sort(orderBy=[a ASC])
+ +- TableSourceScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testRankValueFilterWithEquals">
+ <Resource name="sql">
+ <![CDATA[
+SELECT * FROM (
+ SELECT a, b, RANK() OVER (PARTITION BY b ORDER BY a, c) rk FROM MyTable) t
+WHERE rk = 2
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0], b=[$1], rk=[$2])
++- LogicalFilter(condition=[=($2, 2)])
+ +- LogicalProject(a=[$0], b=[$1], rk=[RANK() OVER (PARTITION BY $1 ORDER BY $0 NULLS FIRST, $2 NULLS FIRST RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)])
+ +- LogicalTableScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a, b, w0$o0 AS $2])
++- Rank(rankType=[RANK], rankRange=[rankStart=2, rankEnd=2], partitionBy=[b], orderBy=[a ASC, c ASC], global=[true], select=[a, b, c, w0$o0])
+ +- Sort(orderBy=[b ASC, a ASC, c ASC])
+ +- Exchange(distribution=[hash[b]])
+ +- Rank(rankType=[RANK], rankRange=[rankStart=1, rankEnd=2], partitionBy=[b], orderBy=[a ASC, c ASC], global=[false], select=[a, b, c])
+ +- Sort(orderBy=[b ASC, a ASC, c ASC])
+ +- TableSourceScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testRankValueFilterWithRange">
+ <Resource name="sql">
+ <![CDATA[
+SELECT * FROM (
+ SELECT a, b, RANK() OVER (PARTITION BY b, c ORDER BY a) rk FROM MyTable) t
+WHERE rk <= 2 AND rk > -2
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0], b=[$1], rk=[$2])
++- LogicalFilter(condition=[AND(<=($2, 2), >($2, -2))])
+ +- LogicalProject(a=[$0], b=[$1], rk=[RANK() OVER (PARTITION BY $1, $2 ORDER BY $0 NULLS FIRST RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)])
+ +- LogicalTableScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a, b, w0$o0 AS $2])
++- Rank(rankType=[RANK], rankRange=[rankStart=-1, rankEnd=2], partitionBy=[b, c], orderBy=[a ASC], global=[true], select=[a, b, c, w0$o0])
+ +- Sort(orderBy=[b ASC, c ASC, a ASC])
+ +- Exchange(distribution=[hash[b, c]])
+ +- Rank(rankType=[RANK], rankRange=[rankStart=1, rankEnd=2], partitionBy=[b, c], orderBy=[a ASC], global=[false], select=[a, b, c])
+ +- Sort(orderBy=[b ASC, c ASC, a ASC])
+ +- TableSourceScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testRankValueFilterWithUpperValue">
+ <Resource name="sql">
+ <![CDATA[
+SELECT * FROM (
+ SELECT a, b, RANK() OVER (PARTITION BY b ORDER BY a) rk FROM MyTable) t
+WHERE rk <= 2 AND a > 10
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0], b=[$1], rk=[$2])
++- LogicalFilter(condition=[AND(<=($2, 2), >($0, 10))])
+ +- LogicalProject(a=[$0], b=[$1], rk=[RANK() OVER (PARTITION BY $1 ORDER BY $0 NULLS FIRST RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)])
+ +- LogicalTableScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a, b, w0$o0], where=[>(a, 10)])
++- Rank(rankType=[RANK], rankRange=[rankStart=1, rankEnd=2], partitionBy=[b], orderBy=[a ASC], global=[true], select=[a, b, c, w0$o0])
+ +- Sort(orderBy=[b ASC, a ASC])
+ +- Exchange(distribution=[hash[b]])
+ +- Rank(rankType=[RANK], rankRange=[rankStart=1, rankEnd=2], partitionBy=[b], orderBy=[a ASC], global=[false], select=[a, b, c])
+ +- Sort(orderBy=[b ASC, a ASC])
+ +- TableSourceScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testWithoutPartitionBy">
+ <Resource name="sql">
+ <![CDATA[
+SELECT * FROM (
+ SELECT a, b, RANK() OVER (ORDER BY a) rk FROM MyTable) t
+WHERE rk < 10
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0], b=[$1], rk=[$2])
++- LogicalFilter(condition=[<($2, 10)])
+ +- LogicalProject(a=[$0], b=[$1], rk=[RANK() OVER (ORDER BY $0 NULLS FIRST RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)])
+ +- LogicalTableScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a, b, w0$o0 AS $2])
++- Rank(rankType=[RANK], rankRange=[rankStart=1, rankEnd=9], partitionBy=[], orderBy=[a ASC], global=[true], select=[a, b, c, w0$o0])
+ +- Sort(orderBy=[a ASC])
+ +- Exchange(distribution=[single])
+ +- Rank(rankType=[RANK], rankRange=[rankStart=1, rankEnd=9], partitionBy=[], orderBy=[a ASC], global=[false], select=[a, b, c])
+ +- Sort(orderBy=[a ASC])
+ +- TableSourceScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
+]]>
+ </Resource>
+ </TestCase>
+</Root>
diff --git a/flink-table/flink-table-planner-blink/src/test/resources/org/apache/flink/table/plan/batch/sql/SortLimitTest.xml b/flink-table/flink-table-planner-blink/src/test/resources/org/apache/flink/table/plan/batch/sql/SortLimitTest.xml
new file mode 100644
index 0000000..e4f1be9
--- /dev/null
+++ b/flink-table/flink-table-planner-blink/src/test/resources/org/apache/flink/table/plan/batch/sql/SortLimitTest.xml
@@ -0,0 +1,217 @@
+<?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="testNoneRangeSortWithOffsetLimit">
+ <Resource name="sql">
+ <![CDATA[SELECT * FROM MyTable ORDER BY a DESC, b LIMIT 10 OFFSET 1]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalSort(sort0=[$0], sort1=[$1], dir0=[DESC-nulls-last], dir1=[ASC-nulls-first], offset=[1], fetch=[10])
++- LogicalProject(a=[$0], b=[$1], c=[$2])
+ +- LogicalTableScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+SortLimit(orderBy=[a DESC, b ASC], offset=[1], fetch=[10], global=[true])
++- Exchange(distribution=[single])
+ +- SortLimit(orderBy=[a DESC, b ASC], offset=[0], fetch=[11], global=[false])
+ +- TableSourceScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testNoneRangeSortWithOffsetLimit0">
+ <Resource name="sql">
+ <![CDATA[SELECT * FROM MyTable ORDER BY a DESC, b LIMIT 0 OFFSET 1]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalSort(sort0=[$0], sort1=[$1], dir0=[DESC-nulls-last], dir1=[ASC-nulls-first], offset=[1], fetch=[0])
++- LogicalProject(a=[$0], b=[$1], c=[$2])
+ +- LogicalTableScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+SortLimit(orderBy=[a DESC, b ASC], offset=[1], fetch=[0], global=[true])
++- Exchange(distribution=[single])
+ +- SortLimit(orderBy=[a DESC, b ASC], offset=[0], fetch=[1], global=[false])
+ +- TableSourceScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testNonRangeSortOnlyWithOffset">
+ <Resource name="sql">
+ <![CDATA[SELECT * FROM MyTable ORDER BY a DESC OFFSET 10 ROWS]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalSort(sort0=[$0], dir0=[DESC-nulls-last], offset=[10])
++- LogicalProject(a=[$0], b=[$1], c=[$2])
+ +- LogicalTableScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+SortLimit(orderBy=[a DESC], offset=[10], fetch=[unlimited], global=[true])
++- Exchange(distribution=[single])
+ +- TableSourceScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testNonRangeSortWithLimit0">
+ <Resource name="sql">
+ <![CDATA[SELECT * FROM MyTable ORDER BY a DESC LIMIT 0]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalSort(sort0=[$0], dir0=[DESC-nulls-last], fetch=[0])
++- LogicalProject(a=[$0], b=[$1], c=[$2])
+ +- LogicalTableScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+SortLimit(orderBy=[a DESC], offset=[0], fetch=[0], global=[true])
++- Exchange(distribution=[single])
+ +- SortLimit(orderBy=[a DESC], offset=[0], fetch=[0], global=[false])
+ +- TableSourceScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testNonRangeSortWithoutOffset">
+ <Resource name="sql">
+ <![CDATA[SELECT * FROM MyTable ORDER BY a DESC LIMIT 5]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalSort(sort0=[$0], dir0=[DESC-nulls-last], fetch=[5])
++- LogicalProject(a=[$0], b=[$1], c=[$2])
+ +- LogicalTableScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+SortLimit(orderBy=[a DESC], offset=[0], fetch=[5], global=[true])
++- Exchange(distribution=[single])
+ +- SortLimit(orderBy=[a DESC], offset=[0], fetch=[5], global=[false])
+ +- TableSourceScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testRangeSortOnlyWithOffset">
+ <Resource name="sql">
+ <![CDATA[SELECT * FROM MyTable ORDER BY a DESC OFFSET 10 ROWS]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalSort(sort0=[$0], dir0=[DESC-nulls-last], offset=[10])
++- LogicalProject(a=[$0], b=[$1], c=[$2])
+ +- LogicalTableScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+SortLimit(orderBy=[a DESC], offset=[10], fetch=[unlimited], global=[true])
++- Exchange(distribution=[single])
+ +- TableSourceScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testRangeSortOnWithLimit0">
+ <Resource name="sql">
+ <![CDATA[SELECT * FROM MyTable ORDER BY a DESC LIMIT 0]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalSort(sort0=[$0], dir0=[DESC-nulls-last], fetch=[0])
++- LogicalProject(a=[$0], b=[$1], c=[$2])
+ +- LogicalTableScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+SortLimit(orderBy=[a DESC], offset=[0], fetch=[0], global=[true])
++- Exchange(distribution=[single])
+ +- SortLimit(orderBy=[a DESC], offset=[0], fetch=[0], global=[false])
+ +- TableSourceScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testRangeSortOnWithoutOffset">
+ <Resource name="sql">
+ <![CDATA[SELECT * FROM MyTable ORDER BY a DESC LIMIT 5]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalSort(sort0=[$0], dir0=[DESC-nulls-last], fetch=[5])
++- LogicalProject(a=[$0], b=[$1], c=[$2])
+ +- LogicalTableScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+SortLimit(orderBy=[a DESC], offset=[0], fetch=[5], global=[true])
++- Exchange(distribution=[single])
+ +- SortLimit(orderBy=[a DESC], offset=[0], fetch=[5], global=[false])
+ +- TableSourceScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testRangeSortWithOffsetLimit">
+ <Resource name="sql">
+ <![CDATA[SELECT * FROM MyTable ORDER BY a DESC, b LIMIT 10 OFFSET 1]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalSort(sort0=[$0], sort1=[$1], dir0=[DESC-nulls-last], dir1=[ASC-nulls-first], offset=[1], fetch=[10])
++- LogicalProject(a=[$0], b=[$1], c=[$2])
+ +- LogicalTableScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+SortLimit(orderBy=[a DESC, b ASC], offset=[1], fetch=[10], global=[true])
++- Exchange(distribution=[single])
+ +- SortLimit(orderBy=[a DESC, b ASC], offset=[0], fetch=[11], global=[false])
+ +- TableSourceScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testRangeSortWithOffsetLimit0">
+ <Resource name="sql">
+ <![CDATA[SELECT * FROM MyTable ORDER BY a DESC, b LIMIT 0 OFFSET 1]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalSort(sort0=[$0], sort1=[$1], dir0=[DESC-nulls-last], dir1=[ASC-nulls-first], offset=[1], fetch=[0])
++- LogicalProject(a=[$0], b=[$1], c=[$2])
+ +- LogicalTableScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+SortLimit(orderBy=[a DESC, b ASC], offset=[1], fetch=[0], global=[true])
++- Exchange(distribution=[single])
+ +- SortLimit(orderBy=[a DESC, b ASC], offset=[0], fetch=[1], global=[false])
+ +- TableSourceScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
+]]>
+ </Resource>
+ </TestCase>
+</Root>
diff --git a/flink-table/flink-table-planner-blink/src/test/resources/org/apache/flink/table/plan/batch/sql/SortTest.xml b/flink-table/flink-table-planner-blink/src/test/resources/org/apache/flink/table/plan/batch/sql/SortTest.xml
new file mode 100644
index 0000000..b2d7e99
--- /dev/null
+++ b/flink-table/flink-table-planner-blink/src/test/resources/org/apache/flink/table/plan/batch/sql/SortTest.xml
@@ -0,0 +1,115 @@
+<?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="testNonRangeSortOnMultiFieldsWithoutForceLimit">
+ <Resource name="sql">
+ <![CDATA[SELECT * FROM MyTable ORDER BY a DESC, b]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalSort(sort0=[$0], sort1=[$1], dir0=[DESC-nulls-last], dir1=[ASC-nulls-first])
++- LogicalProject(a=[$0], b=[$1], c=[$2])
+ +- LogicalTableScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Sort(orderBy=[a DESC, b ASC])
++- Exchange(distribution=[single])
+ +- TableSourceScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testRangeSortWithForceLimit">
+ <Resource name="sql">
+ <![CDATA[SELECT * FROM MyTable ORDER BY a DESC]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalSort(sort0=[$0], dir0=[DESC-nulls-last])
++- LogicalProject(a=[$0], b=[$1], c=[$2])
+ +- LogicalTableScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Sort(orderBy=[a DESC])
++- Exchange(distribution=[range[a DESC]])
+ +- TableSourceScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testNonRangeSortOnSingleFieldWithoutForceLimit">
+ <Resource name="sql">
+ <![CDATA[SELECT * FROM MyTable ORDER BY a DESC]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalSort(sort0=[$0], dir0=[DESC-nulls-last])
++- LogicalProject(a=[$0], b=[$1], c=[$2])
+ +- LogicalTableScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Sort(orderBy=[a DESC])
++- Exchange(distribution=[single])
+ +- TableSourceScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testRangeSortWithoutForceLimit">
+ <Resource name="sql">
+ <![CDATA[SELECT * FROM MyTable ORDER BY a DESC]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalSort(sort0=[$0], dir0=[DESC-nulls-last])
++- LogicalProject(a=[$0], b=[$1], c=[$2])
+ +- LogicalTableScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Sort(orderBy=[a DESC])
++- Exchange(distribution=[range[a DESC]])
+ +- TableSourceScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testNonRangeSortWithForceLimit">
+ <Resource name="sql">
+ <![CDATA[SELECT * FROM MyTable ORDER BY a DESC]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalSort(sort0=[$0], dir0=[DESC-nulls-last])
++- LogicalProject(a=[$0], b=[$1], c=[$2])
+ +- LogicalTableScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+SortLimit(orderBy=[a DESC], offset=[0], fetch=[200], global=[true])
++- Exchange(distribution=[single])
+ +- SortLimit(orderBy=[a DESC], offset=[0], fetch=[200], global=[false])
+ +- TableSourceScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
+]]>
+ </Resource>
+ </TestCase>
+</Root>
diff --git a/flink-table/flink-table-planner-blink/src/test/resources/org/apache/flink/table/plan/rules/logical/FlinkLogicalRankRuleForConstantRangeTest.xml b/flink-table/flink-table-planner-blink/src/test/resources/org/apache/flink/table/plan/rules/logical/FlinkLogicalRankRuleForConstantRangeTest.xml
new file mode 100644
index 0000000..7910a18
--- /dev/null
+++ b/flink-table/flink-table-planner-blink/src/test/resources/org/apache/flink/table/plan/rules/logical/FlinkLogicalRankRuleForConstantRangeTest.xml
@@ -0,0 +1,379 @@
+<?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="testDuplicateRankFunctionColumnName">
+ <Resource name="sql">
+ <![CDATA[
+SELECT * FROM (
+ SELECT a, b, RANK() OVER (PARTITION BY b ORDER BY a) rk FROM MyTable2) t
+WHERE rk < 10
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0], b=[$1], rk=[$2])
++- LogicalFilter(condition=[<($2, 10)])
+ +- LogicalProject(a=[$0], b=[$1], rk=[RANK() OVER (PARTITION BY $1 ORDER BY $0 NULLS FIRST RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)])
+ +- LogicalTableScan(table=[[MyTable2, source: [TestTableSource(a, b, rk)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+FlinkLogicalCalc(select=[a, b, w0$o0 AS $2])
++- FlinkLogicalRank(rankType=[RANK], rankRange=[rankStart=1, rankEnd=9], partitionBy=[b], orderBy=[a ASC], select=[a, b, rk, w0$o0])
+ +- FlinkLogicalTableSourceScan(table=[[MyTable2, source: [TestTableSource(a, b, rk)]]], fields=[a, b, rk])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testMultiDiffRankFunctions">
+ <Resource name="sql">
+ <![CDATA[
+SELECT * FROM (
+ SELECT a, b,
+ RANK() OVER (PARTITION BY b ORDER BY a) rk,
+ ROW_NUMBER() OVER (PARTITION BY b ORDER BY a) rn FROM MyTable) t
+WHERE rk < 10
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0], b=[$1], rk=[$2], rn=[$3])
++- LogicalFilter(condition=[<($2, 10)])
+ +- LogicalProject(a=[$0], b=[$1], rk=[RANK() OVER (PARTITION BY $1 ORDER BY $0 NULLS FIRST RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)], rn=[ROW_NUMBER() OVER (PARTITION BY $1 ORDER BY $0 NULLS FIRST ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)])
+ +- LogicalTableScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+FlinkLogicalCalc(select=[a, b, w0$o0, w1$o0], where=[<(w0$o0, 10)])
++- FlinkLogicalOverWindow(window#0=[window(partition {1} order by [0 ASC-nulls-first] range between UNBOUNDED PRECEDING and CURRENT ROW aggs [RANK()])], window#1=[window(partition {1} order by [0 ASC-nulls-first] rows between UNBOUNDED PRECEDING and CURRENT ROW aggs [ROW_NUMBER()])])
+ +- FlinkLogicalTableSourceScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testMultiSameRankFunctionsWithDiffGroup">
+ <Resource name="sql">
+ <![CDATA[
+SELECT * FROM (
+ SELECT a, b,
+ RANK() OVER (PARTITION BY b ORDER BY a) rk1,
+ RANK() OVER (PARTITION BY c ORDER BY a) rk2 FROM MyTable) t
+WHERE rk1 < 10
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0], b=[$1], rk1=[$2], rk2=[$3])
++- LogicalFilter(condition=[<($2, 10)])
+ +- LogicalProject(a=[$0], b=[$1], rk1=[RANK() OVER (PARTITION BY $1 ORDER BY $0 NULLS FIRST RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)], rk2=[RANK() OVER (PARTITION BY $2 ORDER BY $0 NULLS FIRST RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)])
+ +- LogicalTableScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+FlinkLogicalCalc(select=[a, b, w0$o0, w1$o0], where=[<(w0$o0, 10)])
++- FlinkLogicalOverWindow(window#0=[window(partition {1} order by [0 ASC-nulls-first] range between UNBOUNDED PRECEDING and CURRENT ROW aggs [RANK()])], window#1=[window(partition {2} order by [0 ASC-nulls-first] range between UNBOUNDED PRECEDING and CURRENT ROW aggs [RANK()])])
+ +- FlinkLogicalTableSourceScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testMultiSameRankFunctionsWithSameGroup">
+ <Resource name="sql">
+ <![CDATA[
+SELECT * FROM (
+ SELECT a, b,
+ RANK() OVER (PARTITION BY b ORDER BY a) rk1,
+ RANK() OVER (PARTITION BY b ORDER BY a) rk2 FROM MyTable) t
+WHERE rk1 < 10
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0], b=[$1], rk1=[$2], rk2=[$3])
++- LogicalFilter(condition=[<($2, 10)])
+ +- LogicalProject(a=[$0], b=[$1], rk1=[RANK() OVER (PARTITION BY $1 ORDER BY $0 NULLS FIRST RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)], rk2=[RANK() OVER (PARTITION BY $1 ORDER BY $0 NULLS FIRST RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)])
+ +- LogicalTableScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+FlinkLogicalCalc(select=[a, b, w0$o0 AS rk1, w0$o0 AS rk2])
++- FlinkLogicalRank(rankType=[RANK], rankRange=[rankStart=1, rankEnd=9], partitionBy=[b], orderBy=[a ASC], select=[a, b, c, w0$o0])
+ +- FlinkLogicalTableSourceScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testRankValueFilterWithEquals">
+ <Resource name="sql">
+ <![CDATA[
+SELECT * FROM (
+ SELECT a, b, RANK() OVER (PARTITION BY b ORDER BY a, c) rk FROM MyTable) t
+WHERE rk = 2
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0], b=[$1], rk=[$2])
++- LogicalFilter(condition=[=($2, 2)])
+ +- LogicalProject(a=[$0], b=[$1], rk=[RANK() OVER (PARTITION BY $1 ORDER BY $0 NULLS FIRST, $2 NULLS FIRST RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)])
+ +- LogicalTableScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+FlinkLogicalCalc(select=[a, b, w0$o0 AS $2])
++- FlinkLogicalRank(rankType=[RANK], rankRange=[rankStart=2, rankEnd=2], partitionBy=[b], orderBy=[a ASC, c ASC], select=[a, b, c, w0$o0])
+ +- FlinkLogicalTableSourceScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testRankValueFilterWithLowerValue">
+ <Resource name="sql">
+ <![CDATA[
+SELECT * FROM (
+ SELECT a, b, RANK() OVER (PARTITION BY b ORDER BY a, c) rk FROM MyTable) t
+WHERE rk > 2
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0], b=[$1], rk=[$2])
++- LogicalFilter(condition=[>($2, 2)])
+ +- LogicalProject(a=[$0], b=[$1], rk=[RANK() OVER (PARTITION BY $1 ORDER BY $0 NULLS FIRST, $2 NULLS FIRST RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)])
+ +- LogicalTableScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+FlinkLogicalCalc(select=[a, b, w0$o0], where=[>(w0$o0, 2)])
++- FlinkLogicalOverWindow(window#0=[window(partition {1} order by [0 ASC-nulls-first, 2 ASC-nulls-first] range between UNBOUNDED PRECEDING and CURRENT ROW aggs [RANK()])])
+ +- FlinkLogicalTableSourceScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testRankValueFilterWithRange">
+ <Resource name="sql">
+ <![CDATA[
+SELECT * FROM (
+ SELECT a, b, RANK() OVER (PARTITION BY b, c ORDER BY a) rk FROM MyTable) t
+WHERE rk <= 2 AND rk > -2
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0], b=[$1], rk=[$2])
++- LogicalFilter(condition=[AND(<=($2, 2), >($2, -2))])
+ +- LogicalProject(a=[$0], b=[$1], rk=[RANK() OVER (PARTITION BY $1, $2 ORDER BY $0 NULLS FIRST RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)])
+ +- LogicalTableScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+FlinkLogicalCalc(select=[a, b, w0$o0 AS $2])
++- FlinkLogicalRank(rankType=[RANK], rankRange=[rankStart=-1, rankEnd=2], partitionBy=[b,c], orderBy=[a ASC], select=[a, b, c, w0$o0])
+ +- FlinkLogicalTableSourceScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testRankValueFilterWithUpperValue">
+ <Resource name="sql">
+ <![CDATA[
+SELECT * FROM (
+ SELECT a, b, RANK() OVER (PARTITION BY b ORDER BY a) rk FROM MyTable) t
+WHERE rk <= 2 AND a > 10
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0], b=[$1], rk=[$2])
++- LogicalFilter(condition=[AND(<=($2, 2), >($0, 10))])
+ +- LogicalProject(a=[$0], b=[$1], rk=[RANK() OVER (PARTITION BY $1 ORDER BY $0 NULLS FIRST RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)])
+ +- LogicalTableScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+FlinkLogicalCalc(select=[a, b, w0$o0], where=[>(a, 10)])
++- FlinkLogicalRank(rankType=[RANK], rankRange=[rankStart=1, rankEnd=2], partitionBy=[b], orderBy=[a ASC], select=[a, b, c, w0$o0])
+ +- FlinkLogicalTableSourceScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testRowNumberFunc">
+ <Resource name="sql">
+ <![CDATA[
+SELECT * FROM (
+ SELECT a, b, ROW_NUMBER() OVER (PARTITION BY b ORDER BY a) rn FROM MyTable) t
+WHERE rn <= 2
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0], b=[$1], rn=[$2])
++- LogicalFilter(condition=[<=($2, 2)])
+ +- LogicalProject(a=[$0], b=[$1], rn=[ROW_NUMBER() OVER (PARTITION BY $1 ORDER BY $0 NULLS FIRST ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)])
+ +- LogicalTableScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+FlinkLogicalCalc(select=[a, b, w0$o0], where=[<=(w0$o0, 2)])
++- FlinkLogicalOverWindow(window#0=[window(partition {1} order by [0 ASC-nulls-first] rows between UNBOUNDED PRECEDING and CURRENT ROW aggs [ROW_NUMBER()])])
+ +- FlinkLogicalTableSourceScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testRankValueFilterWithVariableField1">
+ <Resource name="sql">
+ <![CDATA[
+SELECT * FROM (
+ SELECT a, b, RANK() OVER (PARTITION BY b ORDER BY c) rk FROM MyTable) t
+WHERE rk < a
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0], b=[$1], rk=[$2])
++- LogicalFilter(condition=[<($2, $0)])
+ +- LogicalProject(a=[$0], b=[$1], rk=[RANK() OVER (PARTITION BY $1 ORDER BY $2 NULLS FIRST RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)])
+ +- LogicalTableScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+FlinkLogicalCalc(select=[a, b, w0$o0], where=[<(w0$o0, a)])
++- FlinkLogicalOverWindow(window#0=[window(partition {1} order by [2 ASC-nulls-first] range between UNBOUNDED PRECEDING and CURRENT ROW aggs [RANK()])])
+ +- FlinkLogicalTableSourceScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testRankValueFilterWithVariableField2">
+ <Resource name="sql">
+ <![CDATA[
+SELECT * FROM (
+ SELECT a, b, RANK() OVER (PARTITION BY b ORDER BY c) rk FROM MyTable) t
+WHERE rk > a
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0], b=[$1], rk=[$2])
++- LogicalFilter(condition=[>($2, $0)])
+ +- LogicalProject(a=[$0], b=[$1], rk=[RANK() OVER (PARTITION BY $1 ORDER BY $2 NULLS FIRST RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)])
+ +- LogicalTableScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+FlinkLogicalCalc(select=[a, b, w0$o0], where=[>(w0$o0, a)])
++- FlinkLogicalOverWindow(window#0=[window(partition {1} order by [2 ASC-nulls-first] range between UNBOUNDED PRECEDING and CURRENT ROW aggs [RANK()])])
+ +- FlinkLogicalTableSourceScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testRankValueFilterWithVariableField3">
+ <Resource name="sql">
+ <![CDATA[
+SELECT * FROM (
+ SELECT a, b, RANK() OVER (PARTITION BY b ORDER BY c) rk FROM MyTable) t
+WHERE rk < a and b > 5
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0], b=[$1], rk=[$2])
++- LogicalFilter(condition=[AND(<($2, $0), >(CAST($1):BIGINT, 5))])
+ +- LogicalProject(a=[$0], b=[$1], rk=[RANK() OVER (PARTITION BY $1 ORDER BY $2 NULLS FIRST RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)])
+ +- LogicalTableScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+FlinkLogicalCalc(select=[a, b, w0$o0], where=[AND(<(w0$o0, a), >(CAST(b), 5))])
++- FlinkLogicalOverWindow(window#0=[window(partition {1} order by [2 ASC-nulls-first] range between UNBOUNDED PRECEDING and CURRENT ROW aggs [RANK()])])
+ +- FlinkLogicalTableSourceScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testRankValueFilterWithVariableField4">
+ <Resource name="sql">
+ <![CDATA[
+SELECT * FROM (
+ SELECT a, b, RANK() OVER (PARTITION BY a ORDER BY c) rk FROM MyTable) t
+WHERE rk = b
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0], b=[$1], rk=[$2])
++- LogicalFilter(condition=[=($2, $1)])
+ +- LogicalProject(a=[$0], b=[$1], rk=[RANK() OVER (PARTITION BY $0 ORDER BY $2 NULLS FIRST RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)])
+ +- LogicalTableScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+FlinkLogicalCalc(select=[a, b, w0$o0], where=[=(w0$o0, b)])
++- FlinkLogicalOverWindow(window#0=[window(partition {0} order by [2 ASC-nulls-first] range between UNBOUNDED PRECEDING and CURRENT ROW aggs [RANK()])])
+ +- FlinkLogicalTableSourceScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testWithoutPartitionBy">
+ <Resource name="sql">
+ <![CDATA[
+SELECT * FROM (
+ SELECT a, b, RANK() OVER (ORDER BY a) rk FROM MyTable) t
+WHERE rk < 10
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0], b=[$1], rk=[$2])
++- LogicalFilter(condition=[<($2, 10)])
+ +- LogicalProject(a=[$0], b=[$1], rk=[RANK() OVER (ORDER BY $0 NULLS FIRST RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)])
+ +- LogicalTableScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+FlinkLogicalCalc(select=[a, b, w0$o0 AS $2])
++- FlinkLogicalRank(rankType=[RANK], rankRange=[rankStart=1, rankEnd=9], partitionBy=[], orderBy=[a ASC], select=[a, b, c, w0$o0])
+ +- FlinkLogicalTableSourceScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testWithoutFilter">
+ <Resource name="sql">
+ <![CDATA[SELECT a, b, RANK() OVER (PARTITION BY b ORDER BY a) rk FROM MyTable]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0], b=[$1], rk=[RANK() OVER (PARTITION BY $1 ORDER BY $0 NULLS FIRST RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)])
++- LogicalTableScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+FlinkLogicalCalc(select=[a, b, w0$o0 AS $2])
++- FlinkLogicalOverWindow(window#0=[window(partition {1} order by [0 ASC-nulls-first] range between UNBOUNDED PRECEDING and CURRENT ROW aggs [RANK()])])
+ +- FlinkLogicalTableSourceScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
+]]>
+ </Resource>
+ </TestCase>
+</Root>
diff --git a/flink-table/flink-table-planner-blink/src/test/resources/org/apache/flink/table/plan/rules/logical/FlinkLogicalRankRuleForRangeEndTest.xml b/flink-table/flink-table-planner-blink/src/test/resources/org/apache/flink/table/plan/rules/logical/FlinkLogicalRankRuleForRangeEndTest.xml
new file mode 100644
index 0000000..99811e5
--- /dev/null
+++ b/flink-table/flink-table-planner-blink/src/test/resources/org/apache/flink/table/plan/rules/logical/FlinkLogicalRankRuleForRangeEndTest.xml
@@ -0,0 +1,331 @@
+<?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="testMultiDiffRankFunctions">
+ <Resource name="sql">
+ <![CDATA[
+SELECT * FROM (
+ SELECT a, b,
+ RANK() OVER (PARTITION BY b ORDER BY a) rk,
+ ROW_NUMBER() OVER (PARTITION BY b ORDER BY a) rn FROM MyTable) t
+WHERE rk < 10
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0], b=[$1], rk=[$2], rn=[$3])
++- LogicalFilter(condition=[<($2, 10)])
+ +- LogicalProject(a=[$0], b=[$1], rk=[RANK() OVER (PARTITION BY $1 ORDER BY $0 NULLS FIRST RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)], rn=[ROW_NUMBER() OVER (PARTITION BY $1 ORDER BY $0 NULLS FIRST ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)])
+ +- LogicalTableScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+FlinkLogicalCalc(select=[a, b, w0$o0, w1$o0], where=[<(w0$o0, 10)])
++- FlinkLogicalOverWindow(window#0=[window(partition {1} order by [0 ASC-nulls-first] range between UNBOUNDED PRECEDING and CURRENT ROW aggs [RANK()])], window#1=[window(partition {1} order by [0 ASC-nulls-first] rows between UNBOUNDED PRECEDING and CURRENT ROW aggs [ROW_NUMBER()])])
+ +- FlinkLogicalTableSourceScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testMultiSameRankFunctionsWithDiffGroup">
+ <Resource name="sql">
+ <![CDATA[
+SELECT * FROM (
+ SELECT a, b,
+ RANK() OVER (PARTITION BY b ORDER BY a) rk1,
+ RANK() OVER (PARTITION BY c ORDER BY a) rk2 FROM MyTable) t
+WHERE rk1 < 10
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0], b=[$1], rk1=[$2], rk2=[$3])
++- LogicalFilter(condition=[<($2, 10)])
+ +- LogicalProject(a=[$0], b=[$1], rk1=[RANK() OVER (PARTITION BY $1 ORDER BY $0 NULLS FIRST RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)], rk2=[RANK() OVER (PARTITION BY $2 ORDER BY $0 NULLS FIRST RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)])
+ +- LogicalTableScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+FlinkLogicalCalc(select=[a, b, w0$o0, w1$o0], where=[<(w0$o0, 10)])
++- FlinkLogicalOverWindow(window#0=[window(partition {1} order by [0 ASC-nulls-first] range between UNBOUNDED PRECEDING and CURRENT ROW aggs [RANK()])], window#1=[window(partition {2} order by [0 ASC-nulls-first] range between UNBOUNDED PRECEDING and CURRENT ROW aggs [RANK()])])
+ +- FlinkLogicalTableSourceScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testMultiSameRankFunctionsWithSameGroup">
+ <Resource name="sql">
+ <![CDATA[
+SELECT * FROM (
+ SELECT a, b,
+ RANK() OVER (PARTITION BY b ORDER BY a) rk1,
+ RANK() OVER (PARTITION BY b ORDER BY a) rk2 FROM MyTable) t
+WHERE rk1 < 10
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0], b=[$1], rk1=[$2], rk2=[$3])
++- LogicalFilter(condition=[<($2, 10)])
+ +- LogicalProject(a=[$0], b=[$1], rk1=[RANK() OVER (PARTITION BY $1 ORDER BY $0 NULLS FIRST RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)], rk2=[RANK() OVER (PARTITION BY $1 ORDER BY $0 NULLS FIRST RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)])
+ +- LogicalTableScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+FlinkLogicalCalc(select=[a, b, rk2 AS rk1, rk2])
++- FlinkLogicalRank(rankType=[RANK], rankRange=[rankStart=1, rankEnd=9], partitionBy=[b], orderBy=[a ASC], select=[a, b, c, rk2])
+ +- FlinkLogicalTableSourceScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testRankValueFilterWithEquals">
+ <Resource name="sql">
+ <![CDATA[
+SELECT * FROM (
+ SELECT a, b, RANK() OVER (PARTITION BY b ORDER BY a, c) rk FROM MyTable) t
+WHERE rk = 2
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0], b=[$1], rk=[$2])
++- LogicalFilter(condition=[=($2, 2)])
+ +- LogicalProject(a=[$0], b=[$1], rk=[RANK() OVER (PARTITION BY $1 ORDER BY $0 NULLS FIRST, $2 NULLS FIRST RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)])
+ +- LogicalTableScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+FlinkLogicalCalc(select=[a, b, w0$o0])
++- FlinkLogicalRank(rankType=[RANK], rankRange=[rankStart=2, rankEnd=2], partitionBy=[b], orderBy=[a ASC, c ASC], select=[a, b, c, w0$o0])
+ +- FlinkLogicalTableSourceScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testRankValueFilterWithRange">
+ <Resource name="sql">
+ <![CDATA[
+SELECT * FROM (
+ SELECT a, b, RANK() OVER (PARTITION BY b, c ORDER BY a) rk FROM MyTable) t
+WHERE rk <= 2 AND rk > -2
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0], b=[$1], rk=[$2])
++- LogicalFilter(condition=[AND(<=($2, 2), >($2, -2))])
+ +- LogicalProject(a=[$0], b=[$1], rk=[RANK() OVER (PARTITION BY $1, $2 ORDER BY $0 NULLS FIRST RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)])
+ +- LogicalTableScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+FlinkLogicalCalc(select=[a, b, w0$o0])
++- FlinkLogicalRank(rankType=[RANK], rankRange=[rankStart=-1, rankEnd=2], partitionBy=[b,c], orderBy=[a ASC], select=[a, b, c, w0$o0])
+ +- FlinkLogicalTableSourceScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testRankValueFilterWithUpperValue">
+ <Resource name="sql">
+ <![CDATA[
+SELECT * FROM (
+ SELECT a, b, RANK() OVER (PARTITION BY b ORDER BY a) rk FROM MyTable) t
+WHERE rk <= 2 AND a > 10
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0], b=[$1], rk=[$2])
++- LogicalFilter(condition=[AND(<=($2, 2), >($0, 10))])
+ +- LogicalProject(a=[$0], b=[$1], rk=[RANK() OVER (PARTITION BY $1 ORDER BY $0 NULLS FIRST RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)])
+ +- LogicalTableScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+FlinkLogicalCalc(select=[a, b, w0$o0], where=[>(a, 10)])
++- FlinkLogicalRank(rankType=[RANK], rankRange=[rankStart=1, rankEnd=2], partitionBy=[b], orderBy=[a ASC], select=[a, b, c, w0$o0])
+ +- FlinkLogicalTableSourceScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testRowNumberFunc">
+ <Resource name="sql">
+ <![CDATA[
+SELECT * FROM (
+ SELECT a, b, ROW_NUMBER() OVER (PARTITION BY b ORDER BY a) rn FROM MyTable) t
+WHERE rn <= 2
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0], b=[$1], rn=[$2])
++- LogicalFilter(condition=[<=($2, 2)])
+ +- LogicalProject(a=[$0], b=[$1], rn=[ROW_NUMBER() OVER (PARTITION BY $1 ORDER BY $0 NULLS FIRST ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)])
+ +- LogicalTableScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+FlinkLogicalCalc(select=[a, b, w0$o0])
++- FlinkLogicalRank(rankType=[ROW_NUMBER], rankRange=[rankStart=1, rankEnd=2], partitionBy=[b], orderBy=[a ASC], select=[a, b, c, w0$o0])
+ +- FlinkLogicalTableSourceScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testRankValueFilterWithVariableField1">
+ <Resource name="sql">
+ <![CDATA[
+SELECT * FROM (
+ SELECT a, b, RANK() OVER (PARTITION BY b ORDER BY c) rk FROM MyTable) t
+WHERE rk < a
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0], b=[$1], rk=[$2])
++- LogicalFilter(condition=[<($2, $0)])
+ +- LogicalProject(a=[$0], b=[$1], rk=[RANK() OVER (PARTITION BY $1 ORDER BY $2 NULLS FIRST RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)])
+ +- LogicalTableScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+FlinkLogicalCalc(select=[a, b, w0$o0])
++- FlinkLogicalRank(rankType=[RANK], rankRange=[rankEnd=a], partitionBy=[b], orderBy=[c ASC], select=[a, b, c, w0$o0])
+ +- FlinkLogicalTableSourceScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testRankValueFilterWithVariableField2">
+ <Resource name="sql">
+ <![CDATA[
+SELECT * FROM (
+ SELECT a, b, RANK() OVER (PARTITION BY b ORDER BY c) rk FROM MyTable) t
+WHERE rk > a
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0], b=[$1], rk=[$2])
++- LogicalFilter(condition=[>($2, $0)])
+ +- LogicalProject(a=[$0], b=[$1], rk=[RANK() OVER (PARTITION BY $1 ORDER BY $2 NULLS FIRST RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)])
+ +- LogicalTableScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+FlinkLogicalCalc(select=[a, b, w0$o0], where=[>(w0$o0, a)])
++- FlinkLogicalOverWindow(window#0=[window(partition {1} order by [2 ASC-nulls-first] range between UNBOUNDED PRECEDING and CURRENT ROW aggs [RANK()])])
+ +- FlinkLogicalTableSourceScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testRankValueFilterWithVariableField3">
+ <Resource name="sql">
+ <![CDATA[
+SELECT * FROM (
+ SELECT a, b, RANK() OVER (PARTITION BY b ORDER BY c) rk FROM MyTable) t
+WHERE rk < a and b > 5
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0], b=[$1], rk=[$2])
++- LogicalFilter(condition=[AND(<($2, $0), >(CAST($1):BIGINT, 5))])
+ +- LogicalProject(a=[$0], b=[$1], rk=[RANK() OVER (PARTITION BY $1 ORDER BY $2 NULLS FIRST RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)])
+ +- LogicalTableScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+FlinkLogicalCalc(select=[a, b, w0$o0], where=[>(CAST(b), 5)])
++- FlinkLogicalRank(rankType=[RANK], rankRange=[rankEnd=a], partitionBy=[b], orderBy=[c ASC], select=[a, b, c, w0$o0])
+ +- FlinkLogicalTableSourceScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testRankValueFilterWithVariableField4">
+ <Resource name="sql">
+ <![CDATA[
+SELECT * FROM (
+ SELECT a, b, RANK() OVER (PARTITION BY a ORDER BY c) rk FROM MyTable) t
+WHERE rk = b
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0], b=[$1], rk=[$2])
++- LogicalFilter(condition=[=($2, $1)])
+ +- LogicalProject(a=[$0], b=[$1], rk=[RANK() OVER (PARTITION BY $0 ORDER BY $2 NULLS FIRST RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)])
+ +- LogicalTableScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+FlinkLogicalCalc(select=[a, b, w0$o0])
++- FlinkLogicalRank(rankType=[RANK], rankRange=[rankEnd=b], partitionBy=[a], orderBy=[c ASC], select=[a, b, c, w0$o0])
+ +- FlinkLogicalTableSourceScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testWithoutPartitionBy">
+ <Resource name="sql">
+ <![CDATA[
+SELECT * FROM (
+ SELECT a, b, RANK() OVER (ORDER BY a) rk FROM MyTable) t
+WHERE rk < 10
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0], b=[$1], rk=[$2])
++- LogicalFilter(condition=[<($2, 10)])
+ +- LogicalProject(a=[$0], b=[$1], rk=[RANK() OVER (ORDER BY $0 NULLS FIRST RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)])
+ +- LogicalTableScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+FlinkLogicalCalc(select=[a, b, w0$o0])
++- FlinkLogicalRank(rankType=[RANK], rankRange=[rankStart=1, rankEnd=9], partitionBy=[], orderBy=[a ASC], select=[a, b, c, w0$o0])
+ +- FlinkLogicalTableSourceScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testWithoutFilter">
+ <Resource name="sql">
+ <![CDATA[SELECT a, b, RANK() OVER (PARTITION BY b ORDER BY a) rk FROM MyTable]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0], b=[$1], rk=[RANK() OVER (PARTITION BY $1 ORDER BY $0 NULLS FIRST RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)])
++- LogicalTableScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+FlinkLogicalCalc(select=[a, b, w0$o0 AS $2])
++- FlinkLogicalOverWindow(window#0=[window(partition {1} order by [0 ASC-nulls-first] range between UNBOUNDED PRECEDING and CURRENT ROW aggs [RANK()])])
+ +- FlinkLogicalTableSourceScan(table=[[MyTable, source: [TestTableSource(a, b, c)]]], fields=[a, b, c])
+]]>
+ </Resource>
+ </TestCase>
+</Root>
diff --git a/flink-table/flink-table-planner-blink/src/test/resources/org/apache/flink/table/plan/stream/sql/LimitTest.xml b/flink-table/flink-table-planner-blink/src/test/resources/org/apache/flink/table/plan/stream/sql/LimitTest.xml
new file mode 100644
index 0000000..414b1a1
--- /dev/null
+++ b/flink-table/flink-table-planner-blink/src/test/resources/org/apache/flink/table/plan/stream/sql/LimitTest.xml
@@ -0,0 +1,697 @@
+<?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="testFetch0WithoutOffset">
+ <Resource name="sql">
+ <![CDATA[SELECT a, c FROM MyTable FETCH FIRST 0 ROWS ONLY]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalSort(fetch=[0])
++- LogicalProject(a=[$0], c=[$2])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a, c])
++- Limit(offset=[0], fetch=[0])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testFetchWithOffset">
+ <Resource name="sql">
+ <![CDATA[SELECT a, c FROM MyTable OFFSET 10 ROWS FETCH NEXT 10 ROWS ONLY]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalSort(offset=[10], fetch=[10])
++- LogicalProject(a=[$0], c=[$2])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a, c])
++- Limit(offset=[10], fetch=[10])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testFetchWithoutOffset">
+ <Resource name="sql">
+ <![CDATA[SELECT a, c FROM MyTable FETCH FIRST 10 ROWS ONLY]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalSort(fetch=[10])
++- LogicalProject(a=[$0], c=[$2])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a, c])
++- Limit(offset=[0], fetch=[10])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testLimit0WithOffset">
+ <Resource name="sql">
+ <![CDATA[SELECT a, c FROM MyTable LIMIT 0 OFFSET 10]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalSort(offset=[10], fetch=[0])
++- LogicalProject(a=[$0], c=[$2])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a, c])
++- Limit(offset=[10], fetch=[0])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testLimit0WithOffset0">
+ <Resource name="sql">
+ <![CDATA[SELECT a, c FROM MyTable LIMIT 0 OFFSET 0]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalSort(offset=[0], fetch=[0])
++- LogicalProject(a=[$0], c=[$2])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a, c])
++- Limit(offset=[0], fetch=[0])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testLimit0WithoutOffset">
+ <Resource name="sql">
+ <![CDATA[SELECT * FROM MyTable LIMIT 0]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalSort(fetch=[0])
++- LogicalProject(a=[$0], b=[$1], c=[$2], proctime=[$3], rowtime=[$4])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Limit(offset=[0], fetch=[0])
++- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testLimit0WithProcessingTime">
+ <Resource name="sql">
+ <![CDATA[SELECT proctime, c FROM MyTable LIMIT 0]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalSort(fetch=[0])
++- LogicalProject(proctime=[$3], c=[$2])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[proctime, c])
++- Limit(offset=[0], fetch=[0])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testLimit0WithProcessingTimeDesc">
+ <Resource name="sql">
+ <![CDATA[SELECT proctime desc, c FROM MyTable LIMIT 0]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalSort(fetch=[0])
++- LogicalProject(desc=[$3], c=[$2])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[proctime AS desc, c])
++- Limit(offset=[0], fetch=[0])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testLimit0WithProcessingTimeDescSecond">
+ <Resource name="sql">
+ <![CDATA[SELECT c, proctime desc FROM MyTable LIMIT 0]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalSort(fetch=[0])
++- LogicalProject(c=[$2], desc=[$3])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[c, proctime AS desc])
++- Limit(offset=[0], fetch=[0])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testLimit0WithProcessingTimeSecond">
+ <Resource name="sql">
+ <![CDATA[SELECT c, proctime FROM MyTable LIMIT 0]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalSort(fetch=[0])
++- LogicalProject(c=[$2], proctime=[$3])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[c, proctime])
++- Limit(offset=[0], fetch=[0])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testLimit0WithRowTime">
+ <Resource name="sql">
+ <![CDATA[SELECT rowtime, c FROM MyTable LIMIT 0]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalSort(fetch=[0])
++- LogicalProject(rowtime=[$4], c=[$2])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[rowtime, c])
++- Limit(offset=[0], fetch=[0])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testLimit0WithRowTimeDesc">
+ <Resource name="sql">
+ <![CDATA[SELECT rowtime desc, c FROM MyTable LIMIT 0]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalSort(fetch=[0])
++- LogicalProject(desc=[$4], c=[$2])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[rowtime AS desc, c])
++- Limit(offset=[0], fetch=[0])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testLimit0WithRowTimeDescSecond">
+ <Resource name="sql">
+ <![CDATA[SELECT c, rowtime desc FROM MyTable LIMIT 0]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalSort(fetch=[0])
++- LogicalProject(c=[$2], desc=[$4])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[c, rowtime AS desc])
++- Limit(offset=[0], fetch=[0])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testLimit0WithRowTimeSecond">
+ <Resource name="sql">
+ <![CDATA[SELECT c, rowtime FROM MyTable LIMIT 0]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalSort(fetch=[0])
++- LogicalProject(c=[$2], rowtime=[$4])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[c, rowtime])
++- Limit(offset=[0], fetch=[0])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testLimitWithOffset">
+ <Resource name="sql">
+ <![CDATA[SELECT a, c FROM MyTable LIMIT 10 OFFSET 1]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalSort(offset=[1], fetch=[10])
++- LogicalProject(a=[$0], c=[$2])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a, c])
++- Limit(offset=[1], fetch=[10])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testLimitWithOffset0">
+ <Resource name="sql">
+ <![CDATA[SELECT a, c FROM MyTable LIMIT 10 OFFSET 0]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalSort(offset=[0], fetch=[10])
++- LogicalProject(a=[$0], c=[$2])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a, c])
++- Limit(offset=[0], fetch=[10])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testLimitWithoutOffset">
+ <Resource name="sql">
+ <![CDATA[SELECT * FROM MyTable LIMIT 5]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalSort(fetch=[5])
++- LogicalProject(a=[$0], b=[$1], c=[$2], proctime=[$3], rowtime=[$4])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Limit(offset=[0], fetch=[5])
++- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testLimitWithProcessingTime">
+ <Resource name="sql">
+ <![CDATA[SELECT proctime, c FROM MyTable LIMIT 2]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalSort(fetch=[2])
++- LogicalProject(proctime=[$3], c=[$2])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[proctime, c])
++- Limit(offset=[0], fetch=[2])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testLimitWithProcessingTimeDesc">
+ <Resource name="sql">
+ <![CDATA[SELECT proctime desc, c FROM MyTable LIMIT 2]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalSort(fetch=[2])
++- LogicalProject(desc=[$3], c=[$2])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[proctime AS desc, c])
++- Limit(offset=[0], fetch=[2])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testLimitWithProcessingTimeDescSecond">
+ <Resource name="sql">
+ <![CDATA[SELECT c, proctime desc FROM MyTable LIMIT 2]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalSort(fetch=[2])
++- LogicalProject(c=[$2], desc=[$3])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[c, proctime AS desc])
++- Limit(offset=[0], fetch=[2])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testLimitWithProcessingTimeSecond">
+ <Resource name="sql">
+ <![CDATA[SELECT c, proctime FROM MyTable LIMIT 2]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalSort(fetch=[2])
++- LogicalProject(c=[$2], proctime=[$3])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[c, proctime])
++- Limit(offset=[0], fetch=[2])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testLimitWithRowTime">
+ <Resource name="sql">
+ <![CDATA[SELECT rowtime, c FROM MyTable LIMIT 2]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalSort(fetch=[2])
++- LogicalProject(rowtime=[$4], c=[$2])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[rowtime, c])
++- Limit(offset=[0], fetch=[2])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testLimitWithRowTimeDesc">
+ <Resource name="sql">
+ <![CDATA[SELECT rowtime desc, c FROM MyTable LIMIT 2]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalSort(fetch=[2])
++- LogicalProject(desc=[$4], c=[$2])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[rowtime AS desc, c])
++- Limit(offset=[0], fetch=[2])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testLimitWithRowTimeDescSecond">
+ <Resource name="sql">
+ <![CDATA[SELECT c, rowtime desc FROM MyTable LIMIT 2]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalSort(fetch=[2])
++- LogicalProject(c=[$2], desc=[$4])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[c, rowtime AS desc])
++- Limit(offset=[0], fetch=[2])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testLimitWithRowTimeSecond">
+ <Resource name="sql">
+ <![CDATA[SELECT c, rowtime FROM MyTable LIMIT 2]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalSort(fetch=[2])
++- LogicalProject(c=[$2], rowtime=[$4])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[c, rowtime])
++- Limit(offset=[0], fetch=[2])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testOffsetWithProcessingTime">
+ <Resource name="sql">
+ <![CDATA[SELECT proctime, c FROM MyTable OFFSET 2]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalSort(offset=[2])
++- LogicalProject(proctime=[$3], c=[$2])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[proctime, c])
++- Limit(offset=[2], fetch=[unlimited])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testOffsetWithRowTimeDesc">
+ <Resource name="sql">
+ <![CDATA[SELECT rowtime desc, c FROM MyTable OFFSET 2]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalSort(offset=[2])
++- LogicalProject(desc=[$4], c=[$2])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[rowtime AS desc, c])
++- Limit(offset=[2], fetch=[unlimited])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testOffsetWithProcessingTimeDesc">
+ <Resource name="sql">
+ <![CDATA[SELECT proctime desc, c FROM MyTable OFFSET 2]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalSort(offset=[2])
++- LogicalProject(desc=[$3], c=[$2])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[proctime AS desc, c])
++- Limit(offset=[2], fetch=[unlimited])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testOffsetWithProcessingTimeDescSecond">
+ <Resource name="sql">
+ <![CDATA[SELECT c, proctime desc FROM MyTable OFFSET 2]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalSort(offset=[2])
++- LogicalProject(c=[$2], desc=[$3])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[c, proctime AS desc])
++- Limit(offset=[2], fetch=[unlimited])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testOffsetWithProcessingTimeSecond">
+ <Resource name="sql">
+ <![CDATA[SELECT c, proctime FROM MyTable OFFSET 2]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalSort(offset=[2])
++- LogicalProject(c=[$2], proctime=[$3])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[c, proctime])
++- Limit(offset=[2], fetch=[unlimited])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testOffsetWithRowTime">
+ <Resource name="sql">
+ <![CDATA[SELECT rowtime, c FROM MyTable OFFSET 2]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalSort(offset=[2])
++- LogicalProject(rowtime=[$4], c=[$2])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[rowtime, c])
++- Limit(offset=[2], fetch=[unlimited])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testOffsetWithRowTimeDescSecond">
+ <Resource name="sql">
+ <![CDATA[SELECT c, rowtime desc FROM MyTable OFFSET 2]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalSort(offset=[2])
++- LogicalProject(c=[$2], desc=[$4])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[c, rowtime AS desc])
++- Limit(offset=[2], fetch=[unlimited])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testOnlyOffset">
+ <Resource name="sql">
+ <![CDATA[SELECT a, c FROM MyTable OFFSET 10 ROWS]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalSort(offset=[10])
++- LogicalProject(a=[$0], c=[$2])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a, c])
++- Limit(offset=[10], fetch=[unlimited])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testOffsetWithRowTimeSecond">
+ <Resource name="sql">
+ <![CDATA[SELECT c, rowtime FROM MyTable OFFSET 2]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalSort(offset=[2])
++- LogicalProject(c=[$2], rowtime=[$4])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[c, rowtime])
++- Limit(offset=[2], fetch=[unlimited])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+</Root>
diff --git a/flink-table/flink-table-planner-blink/src/test/resources/org/apache/flink/table/plan/stream/sql/RankTest.xml b/flink-table/flink-table-planner-blink/src/test/resources/org/apache/flink/table/plan/stream/sql/RankTest.xml
new file mode 100644
index 0000000..d6864a5
--- /dev/null
+++ b/flink-table/flink-table-planner-blink/src/test/resources/org/apache/flink/table/plan/stream/sql/RankTest.xml
@@ -0,0 +1,355 @@
+<?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="testRankEndLessThan1">
+ <Resource name="sql">
+ <![CDATA[
+SELECT *
+FROM (
+ SELECT a, b, c,
+ ROW_NUMBER() OVER (PARTITION BY a ORDER BY b DESC) as row_num
+ FROM MyTable)
+WHERE row_num <= 1
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0], b=[$1], c=[$2], row_num=[$3])
++- LogicalFilter(condition=[<=($3, 1)])
+ +- LogicalProject(a=[$0], b=[$1], c=[$2], row_num=[ROW_NUMBER() OVER (PARTITION BY $0 ORDER BY $1 DESC NULLS LAST ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a, b, c, w0$o0])
++- Rank(strategy=[AppendFastStrategy], rankType=[ROW_NUMBER], rankRange=[rankStart=1, rankEnd=1], partitionBy=[a], orderBy=[b DESC], select=[a, b, c, proctime, rowtime, w0$o0])
+ +- Exchange(distribution=[hash[a]])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testRankFunctionInMiddle">
+ <Resource name="sql">
+ <![CDATA[
+SELECT * FROM (
+ SELECT a, RANK() OVER (PARTITION BY a ORDER BY a) rk, b, c FROM MyTable) t
+WHERE rk < 10
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0], rk=[$1], b=[$2], c=[$3])
++- LogicalFilter(condition=[<($1, 10)])
+ +- LogicalProject(a=[$0], rk=[RANK() OVER (PARTITION BY $0 ORDER BY $0 NULLS FIRST RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)], b=[$1], c=[$2])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a, rk, b, c])
++- Rank(strategy=[AppendFastStrategy], rankType=[RANK], rankRange=[rankStart=1, rankEnd=9], partitionBy=[a], orderBy=[a ASC], select=[a, b, c, proctime, rowtime, rk])
+ +- Exchange(distribution=[hash[a]])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testRankWithRankEndLessThan1OrderByProctimeAsc">
+ <Resource name="sql">
+ <![CDATA[
+SELECT a, b, c
+FROM (
+ SELECT a, b, c, proctime,
+ RANK() OVER (PARTITION BY a ORDER BY proctime ASC) as rk
+ FROM MyTable)
+WHERE rk <= 1
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0], b=[$1], c=[$2])
++- LogicalFilter(condition=[<=($4, 1)])
+ +- LogicalProject(a=[$0], b=[$1], c=[$2], proctime=[$3], rk=[RANK() OVER (PARTITION BY $0 ORDER BY $3 NULLS FIRST RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a, b, c])
++- Rank(strategy=[AppendFastStrategy], rankType=[RANK], rankRange=[rankStart=1, rankEnd=1], partitionBy=[a], orderBy=[proctime ASC], select=[a, b, c, proctime, rowtime])
+ +- Exchange(distribution=[hash[a]])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testRowNumberWithRankEndLessThan1OrderByRowtimeAsc">
+ <Resource name="sql">
+ <![CDATA[
+SELECT a, b, c
+FROM (
+ SELECT a, b, c, rowtime,
+ ROW_NUMBER() OVER (PARTITION BY a ORDER BY rowtime ASC) as row_num
+ FROM MyTable)
+WHERE row_num <= 1
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0], b=[$1], c=[$2])
++- LogicalFilter(condition=[<=($4, 1)])
+ +- LogicalProject(a=[$0], b=[$1], c=[$2], rowtime=[$4], row_num=[ROW_NUMBER() OVER (PARTITION BY $0 ORDER BY $4 NULLS FIRST ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a, b, c])
++- Rank(strategy=[AppendFastStrategy], rankType=[ROW_NUMBER], rankRange=[rankStart=1, rankEnd=1], partitionBy=[a], orderBy=[rowtime ASC], select=[a, b, c, proctime, rowtime])
+ +- Exchange(distribution=[hash[a]])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testRankWithRankEndLessThan1OrderByProctimeDesc">
+ <Resource name="sql">
+ <![CDATA[
+SELECT a, b, c
+FROM (
+ SELECT a, b, c, proctime,
+ RANK() OVER (PARTITION BY a ORDER BY proctime DESC) as rk
+ FROM MyTable)
+WHERE rk <= 1
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0], b=[$1], c=[$2])
++- LogicalFilter(condition=[<=($4, 1)])
+ +- LogicalProject(a=[$0], b=[$1], c=[$2], proctime=[$3], rk=[RANK() OVER (PARTITION BY $0 ORDER BY $3 DESC NULLS LAST RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a, b, c])
++- Rank(strategy=[AppendFastStrategy], rankType=[RANK], rankRange=[rankStart=1, rankEnd=1], partitionBy=[a], orderBy=[proctime DESC], select=[a, b, c, proctime, rowtime])
+ +- Exchange(distribution=[hash[a]])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testRowNumberWithRankEndLessThan1OrderByProctimeAsc">
+ <Resource name="sql">
+ <![CDATA[
+SELECT a, b, c
+FROM (
+ SELECT a, b, c, proctime,
+ ROW_NUMBER() OVER (PARTITION BY a ORDER BY proctime ASC) as row_num
+ FROM MyTable)
+WHERE row_num <= 1
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0], b=[$1], c=[$2])
++- LogicalFilter(condition=[<=($4, 1)])
+ +- LogicalProject(a=[$0], b=[$1], c=[$2], proctime=[$3], row_num=[ROW_NUMBER() OVER (PARTITION BY $0 ORDER BY $3 NULLS FIRST ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a, b, c])
++- Deduplicate(keepLastRow=[false], key=[a], order=[PROCTIME])
+ +- Exchange(distribution=[hash[a]])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testRowNumberWithRankEndLessThan1OrderByProctimeDesc">
+ <Resource name="sql">
+ <![CDATA[
+SELECT a, b, c
+FROM (
+ SELECT a, b, c, proctime,
+ ROW_NUMBER() OVER (PARTITION BY a ORDER BY proctime DESC) as row_num
+ FROM MyTable)
+WHERE row_num <= 1
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0], b=[$1], c=[$2])
++- LogicalFilter(condition=[<=($4, 1)])
+ +- LogicalProject(a=[$0], b=[$1], c=[$2], proctime=[$3], row_num=[ROW_NUMBER() OVER (PARTITION BY $0 ORDER BY $3 DESC NULLS LAST ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a, b, c])
++- Deduplicate(keepLastRow=[true], key=[a], order=[PROCTIME])
+ +- Exchange(distribution=[hash[a]])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testRowNumberWithRankEndLessThan1OrderByRowtimeDesc">
+ <Resource name="sql">
+ <![CDATA[
+SELECT a, b, c
+FROM (
+ SELECT a, b, c, rowtime,
+ ROW_NUMBER() OVER (PARTITION BY a ORDER BY rowtime DESC) as row_num
+ FROM MyTable)
+WHERE row_num <= 1
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0], b=[$1], c=[$2])
++- LogicalFilter(condition=[<=($4, 1)])
+ +- LogicalProject(a=[$0], b=[$1], c=[$2], rowtime=[$4], row_num=[ROW_NUMBER() OVER (PARTITION BY $0 ORDER BY $4 DESC NULLS LAST ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a, b, c])
++- Rank(strategy=[AppendFastStrategy], rankType=[ROW_NUMBER], rankRange=[rankStart=1, rankEnd=1], partitionBy=[a], orderBy=[rowtime DESC], select=[a, b, c, proctime, rowtime])
+ +- Exchange(distribution=[hash[a]])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testTopN2">
+ <Resource name="sql">
+ <![CDATA[
+SELECT *
+FROM (
+ SELECT a, b, c,
+ ROW_NUMBER() OVER (PARTITION BY a ORDER BY b DESC) as row_num
+ FROM MyTable)
+WHERE 10 >= row_num
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0], b=[$1], c=[$2], row_num=[$3])
++- LogicalFilter(condition=[>=(10, $3)])
+ +- LogicalProject(a=[$0], b=[$1], c=[$2], row_num=[ROW_NUMBER() OVER (PARTITION BY $0 ORDER BY $1 DESC NULLS LAST ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a, b, c, w0$o0], updateAsRetraction=[false], accMode=[Acc])
++- Rank(strategy=[AppendFastStrategy], rankType=[ROW_NUMBER], rankRange=[rankStart=1, rankEnd=10], partitionBy=[a], orderBy=[b DESC], select=[a, b, c, proctime, rowtime, w0$o0], updateAsRetraction=[false], accMode=[Acc])
+ +- Exchange(distribution=[hash[a]], updateAsRetraction=[false], accMode=[Acc])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime], updateAsRetraction=[false], accMode=[Acc])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testTopN">
+ <Resource name="sql">
+ <![CDATA[
+SELECT *
+FROM (
+ SELECT a, b, c,
+ ROW_NUMBER() OVER (PARTITION BY a ORDER BY b DESC) as row_num
+ FROM MyTable)
+WHERE row_num <= 10
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0], b=[$1], c=[$2], row_num=[$3])
++- LogicalFilter(condition=[<=($3, 10)])
+ +- LogicalProject(a=[$0], b=[$1], c=[$2], row_num=[ROW_NUMBER() OVER (PARTITION BY $0 ORDER BY $1 DESC NULLS LAST ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a, b, c, w0$o0], updateAsRetraction=[false], accMode=[Acc])
++- Rank(strategy=[AppendFastStrategy], rankType=[ROW_NUMBER], rankRange=[rankStart=1, rankEnd=10], partitionBy=[a], orderBy=[b DESC], select=[a, b, c, proctime, rowtime, w0$o0], updateAsRetraction=[false], accMode=[Acc])
+ +- Exchange(distribution=[hash[a]], updateAsRetraction=[false], accMode=[Acc])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime], updateAsRetraction=[false], accMode=[Acc])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testTopNWithFilter">
+ <Resource name="sql">
+ <![CDATA[
+SELECT row_num, a, c
+FROM (
+ SELECT a, b, c,
+ ROW_NUMBER() OVER (PARTITION BY a ORDER BY b DESC) as row_num
+ FROM MyTable
+ WHERE c > 1000)
+WHERE row_num <= 10 AND b IS NOT NULL
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(row_num=[$3], a=[$0], c=[$2])
++- LogicalFilter(condition=[AND(<=($3, 10), IS NOT NULL($1))])
+ +- LogicalProject(a=[$0], b=[$1], c=[$2], row_num=[ROW_NUMBER() OVER (PARTITION BY $0 ORDER BY $1 DESC NULLS LAST ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)])
+ +- LogicalFilter(condition=[>($2, 1000)])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[row_num, a, c], where=[IS NOT NULL(b)], updateAsRetraction=[false], accMode=[Acc])
++- Rank(strategy=[AppendFastStrategy], rankType=[ROW_NUMBER], rankRange=[rankStart=1, rankEnd=10], partitionBy=[a], orderBy=[b DESC], select=[a, b, c, proctime, rowtime, row_num], updateAsRetraction=[false], accMode=[Acc])
+ +- Exchange(distribution=[hash[a]], updateAsRetraction=[false], accMode=[Acc])
+ +- Calc(select=[a, b, c, proctime, rowtime], where=[>(c, 1000)], updateAsRetraction=[false], accMode=[Acc])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime], updateAsRetraction=[false], accMode=[Acc])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testTopNth">
+ <Resource name="sql">
+ <![CDATA[
+SELECT *
+FROM (
+ SELECT a, b, c,
+ ROW_NUMBER() OVER (PARTITION BY a ORDER BY b DESC) as row_num
+ FROM MyTable)
+WHERE row_num = 10
+ ]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0], b=[$1], c=[$2], row_num=[$3])
++- LogicalFilter(condition=[=($3, 10)])
+ +- LogicalProject(a=[$0], b=[$1], c=[$2], row_num=[ROW_NUMBER() OVER (PARTITION BY $0 ORDER BY $1 DESC NULLS LAST ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a, b, c, w0$o0], updateAsRetraction=[false], accMode=[Acc])
++- Rank(strategy=[AppendFastStrategy], rankType=[ROW_NUMBER], rankRange=[rankStart=10, rankEnd=10], partitionBy=[a], orderBy=[b DESC], select=[a, b, c, proctime, rowtime, w0$o0], updateAsRetraction=[false], accMode=[Acc])
+ +- Exchange(distribution=[hash[a]], updateAsRetraction=[false], accMode=[Acc])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime], updateAsRetraction=[false], accMode=[Acc])
+]]>
+ </Resource>
+ </TestCase>
+</Root>
diff --git a/flink-table/flink-table-planner-blink/src/test/resources/org/apache/flink/table/plan/stream/sql/SortLimitTest.xml b/flink-table/flink-table-planner-blink/src/test/resources/org/apache/flink/table/plan/stream/sql/SortLimitTest.xml
new file mode 100644
index 0000000..13cc89e
--- /dev/null
+++ b/flink-table/flink-table-planner-blink/src/test/resources/org/apache/flink/table/plan/stream/sql/SortLimitTest.xml
@@ -0,0 +1,1254 @@
+<?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="testOrderByFetch">
+ <Resource name="sql">
+ <![CDATA[SELECT * FROM MyTable ORDER BY a, b DESC FETCH FIRST 10 ROWS ONLY]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalSort(sort0=[$0], sort1=[$1], dir0=[ASC-nulls-first], dir1=[DESC-nulls-last], fetch=[10])
++- LogicalProject(a=[$0], b=[$1], c=[$2], proctime=[$3], rowtime=[$4])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+SortLimit(orderBy=[a ASC, b DESC], offset=[0], fetch=[10], updateAsRetraction=[false], accMode=[Acc])
++- Exchange(distribution=[single], updateAsRetraction=[false], accMode=[Acc])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime], updateAsRetraction=[false], accMode=[Acc])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testOrderByLimit">
+ <Resource name="sql">
+ <![CDATA[SELECT * FROM MyTable ORDER BY a, b DESC LIMIT 10]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalSort(sort0=[$0], sort1=[$1], dir0=[ASC-nulls-first], dir1=[DESC-nulls-last], fetch=[10])
++- LogicalProject(a=[$0], b=[$1], c=[$2], proctime=[$3], rowtime=[$4])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+SortLimit(orderBy=[a ASC, b DESC], offset=[0], fetch=[10], updateAsRetraction=[false], accMode=[Acc])
++- Exchange(distribution=[single], updateAsRetraction=[false], accMode=[Acc])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime], updateAsRetraction=[false], accMode=[Acc])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSortProcessingTimeAscWithLimit1">
+ <Resource name="sql">
+ <![CDATA[SELECT a FROM MyTable ORDER BY proctime LIMIT 1]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0])
++- LogicalSort(sort0=[$1], dir0=[ASC-nulls-first], fetch=[1])
+ +- LogicalProject(a=[$0], proctime=[$3])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a])
++- SortLimit(orderBy=[proctime ASC], offset=[0], fetch=[1])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSortProcessingTimeAscWithOffSet0AndLimit1">
+ <Resource name="sql">
+ <![CDATA[SELECT a FROM MyTable ORDER BY proctime LIMIT 1 OFFSET 0]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0])
++- LogicalSort(sort0=[$1], dir0=[ASC-nulls-first], offset=[0], fetch=[1])
+ +- LogicalProject(a=[$0], proctime=[$3])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a])
++- SortLimit(orderBy=[proctime ASC], offset=[0], fetch=[1])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSortProcessingTimeAscWithOffSet1AndLimit1">
+ <Resource name="sql">
+ <![CDATA[SELECT a FROM MyTable ORDER BY proctime LIMIT 1 OFFSET 1]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0])
++- LogicalSort(sort0=[$1], dir0=[ASC-nulls-first], offset=[1], fetch=[1])
+ +- LogicalProject(a=[$0], proctime=[$3])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a])
++- SortLimit(orderBy=[proctime ASC], offset=[1], fetch=[1])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSortProcessingTimeDescWithLimit">
+ <Resource name="sql">
+ <![CDATA[SELECT a FROM MyTable ORDER BY proctime desc, c LIMIT 2]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0])
++- LogicalSort(sort0=[$1], sort1=[$2], dir0=[DESC-nulls-last], dir1=[ASC-nulls-first], fetch=[2])
+ +- LogicalProject(a=[$0], proctime=[$3], c=[$2])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a])
++- SortLimit(orderBy=[proctime DESC, c ASC], offset=[0], fetch=[2])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSortProcessingTimeDescWithOffset">
+ <Resource name="sql">
+ <![CDATA[SELECT a FROM MyTable ORDER BY proctime desc, c OFFSET 2]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0])
++- LogicalSort(sort0=[$1], sort1=[$2], dir0=[DESC-nulls-last], dir1=[ASC-nulls-first], offset=[2])
+ +- LogicalProject(a=[$0], proctime=[$3], c=[$2])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a])
++- SortLimit(orderBy=[proctime DESC, c ASC], offset=[2], fetch=[unlimited])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSortProcessingTimeDescWithOffSet0AndLimit1">
+ <Resource name="sql">
+ <![CDATA[SELECT a FROM MyTable ORDER BY proctime DESC LIMIT 1 OFFSET 0]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0])
++- LogicalSort(sort0=[$1], dir0=[DESC-nulls-last], offset=[0], fetch=[1])
+ +- LogicalProject(a=[$0], proctime=[$3])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a])
++- SortLimit(orderBy=[proctime DESC], offset=[0], fetch=[1])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSortProcessingTimeDescWithOffSet1AndLimit1">
+ <Resource name="sql">
+ <![CDATA[SELECT a FROM MyTable ORDER BY proctime desc LIMIT 1 OFFSET 1]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0])
++- LogicalSort(sort0=[$1], dir0=[DESC-nulls-last], offset=[1], fetch=[1])
+ +- LogicalProject(a=[$0], proctime=[$3])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a])
++- SortLimit(orderBy=[proctime DESC], offset=[1], fetch=[1])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSortProcessingTimeFirstAscWithLimit0">
+ <Resource name="sql">
+ <![CDATA[SELECT a FROM MyTable ORDER BY proctime, c LIMIT 0]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0])
++- LogicalSort(sort0=[$1], sort1=[$2], dir0=[ASC-nulls-first], dir1=[ASC-nulls-first], fetch=[0])
+ +- LogicalProject(a=[$0], proctime=[$3], c=[$2])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a])
++- SortLimit(orderBy=[proctime ASC, c ASC], offset=[0], fetch=[0])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSortProcessingTimeFirstAscWithLimit1">
+ <Resource name="sql">
+ <![CDATA[SELECT a FROM MyTable ORDER BY proctime, c LIMIT 1]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0])
++- LogicalSort(sort0=[$1], sort1=[$2], dir0=[ASC-nulls-first], dir1=[ASC-nulls-first], fetch=[1])
+ +- LogicalProject(a=[$0], proctime=[$3], c=[$2])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a])
++- SortLimit(orderBy=[proctime ASC, c ASC], offset=[0], fetch=[1])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSortProcessingTimeFirstAscWithOffSet1AndLimit0">
+ <Resource name="sql">
+ <![CDATA[SELECT a FROM MyTable ORDER BY proctime, c LIMIT 0 OFFSET 1]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0])
++- LogicalSort(sort0=[$1], sort1=[$2], dir0=[ASC-nulls-first], dir1=[ASC-nulls-first], offset=[1], fetch=[0])
+ +- LogicalProject(a=[$0], proctime=[$3], c=[$2])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a])
++- SortLimit(orderBy=[proctime ASC, c ASC], offset=[1], fetch=[0])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSortProcessingTimeFirstAscWithOffSet1AndLimit1">
+ <Resource name="sql">
+ <![CDATA[SELECT a FROM MyTable ORDER BY proctime, c LIMIT 1 OFFSET 1]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0])
++- LogicalSort(sort0=[$1], sort1=[$2], dir0=[ASC-nulls-first], dir1=[ASC-nulls-first], offset=[1], fetch=[1])
+ +- LogicalProject(a=[$0], proctime=[$3], c=[$2])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a])
++- SortLimit(orderBy=[proctime ASC, c ASC], offset=[1], fetch=[1])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSortProcessingTimeFirstDescWithLimit0">
+ <Resource name="sql">
+ <![CDATA[SELECT a FROM MyTable ORDER BY proctime desc LIMIT 0]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0])
++- LogicalSort(sort0=[$1], dir0=[DESC-nulls-last], fetch=[0])
+ +- LogicalProject(a=[$0], proctime=[$3])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a])
++- SortLimit(orderBy=[proctime DESC], offset=[0], fetch=[0])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSortProcessingTimeFirstDescWithLimit1">
+ <Resource name="sql">
+ <![CDATA[SELECT a FROM MyTable ORDER BY proctime DESC LIMIT 1]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0])
++- LogicalSort(sort0=[$1], dir0=[DESC-nulls-last], fetch=[1])
+ +- LogicalProject(a=[$0], proctime=[$3])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a])
++- SortLimit(orderBy=[proctime DESC], offset=[0], fetch=[1])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSortProcessingTimeFirstDescWithOffSet0AndLimit1">
+ <Resource name="sql">
+ <![CDATA[SELECT a FROM MyTable ORDER BY proctime, c desc LIMIT 1 OFFSET 0]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0])
++- LogicalSort(sort0=[$1], sort1=[$2], dir0=[ASC-nulls-first], dir1=[DESC-nulls-last], offset=[0], fetch=[1])
+ +- LogicalProject(a=[$0], proctime=[$3], c=[$2])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a])
++- SortLimit(orderBy=[proctime ASC, c DESC], offset=[0], fetch=[1])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSortProcessingTimeFirstDescWithOffSet1AndLimit1">
+ <Resource name="sql">
+ <![CDATA[SELECT a FROM MyTable ORDER BY proctime, c desc LIMIT 1 OFFSET 1]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0])
++- LogicalSort(sort0=[$1], sort1=[$2], dir0=[ASC-nulls-first], dir1=[DESC-nulls-last], offset=[1], fetch=[1])
+ +- LogicalProject(a=[$0], proctime=[$3], c=[$2])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a])
++- SortLimit(orderBy=[proctime ASC, c DESC], offset=[1], fetch=[1])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSortProcessingTimeSecondAscWithLimit1">
+ <Resource name="sql">
+ <![CDATA[SELECT a FROM MyTable ORDER BY c, proctime LIMIT 1]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0])
++- LogicalSort(sort0=[$1], sort1=[$2], dir0=[ASC-nulls-first], dir1=[ASC-nulls-first], fetch=[1])
+ +- LogicalProject(a=[$0], c=[$2], proctime=[$3])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a])
++- SortLimit(orderBy=[c ASC, proctime ASC], offset=[0], fetch=[1])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSortProcessingTimeSecondDescWithLimit">
+ <Resource name="sql">
+ <![CDATA[SELECT a FROM MyTable ORDER BY c, proctime desc LIMIT 2]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0])
++- LogicalSort(sort0=[$1], sort1=[$2], dir0=[ASC-nulls-first], dir1=[DESC-nulls-last], fetch=[2])
+ +- LogicalProject(a=[$0], c=[$2], proctime=[$3])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a])
++- SortLimit(orderBy=[c ASC, proctime DESC], offset=[0], fetch=[2])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSortProcessingTimeSecondDescWithLimit0">
+ <Resource name="sql">
+ <![CDATA[SELECT a FROM MyTable ORDER BY c, proctime desc LIMIT 0]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0])
++- LogicalSort(sort0=[$1], sort1=[$2], dir0=[ASC-nulls-first], dir1=[DESC-nulls-last], fetch=[0])
+ +- LogicalProject(a=[$0], c=[$2], proctime=[$3])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a])
++- SortLimit(orderBy=[c ASC, proctime DESC], offset=[0], fetch=[0])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSortProcessingTimeSecondDescWithLimit1">
+ <Resource name="sql">
+ <![CDATA[SELECT a FROM MyTable ORDER BY c, proctime desc LIMIT 1]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0])
++- LogicalSort(sort0=[$1], sort1=[$2], dir0=[ASC-nulls-first], dir1=[DESC-nulls-last], fetch=[1])
+ +- LogicalProject(a=[$0], c=[$2], proctime=[$3])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a])
++- SortLimit(orderBy=[c ASC, proctime DESC], offset=[0], fetch=[1])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSortProcessingTimeSecondDescWithOffset">
+ <Resource name="sql">
+ <![CDATA[SELECT a FROM MyTable ORDER BY c, proctime desc OFFSET 2]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0])
++- LogicalSort(sort0=[$1], sort1=[$2], dir0=[ASC-nulls-first], dir1=[DESC-nulls-last], offset=[2])
+ +- LogicalProject(a=[$0], c=[$2], proctime=[$3])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a])
++- SortLimit(orderBy=[c ASC, proctime DESC], offset=[2], fetch=[unlimited])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSortProcessingTimeSecondWithLimit">
+ <Resource name="sql">
+ <![CDATA[SELECT a FROM MyTable ORDER BY c, proctime LIMIT 2]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0])
++- LogicalSort(sort0=[$1], sort1=[$2], dir0=[ASC-nulls-first], dir1=[ASC-nulls-first], fetch=[2])
+ +- LogicalProject(a=[$0], c=[$2], proctime=[$3])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a])
++- SortLimit(orderBy=[c ASC, proctime ASC], offset=[0], fetch=[2])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSortProcessingTimeSecondWithOffset">
+ <Resource name="sql">
+ <![CDATA[SELECT a FROM MyTable ORDER BY c, proctime OFFSET 2]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0])
++- LogicalSort(sort0=[$1], sort1=[$2], dir0=[ASC-nulls-first], dir1=[ASC-nulls-first], offset=[2])
+ +- LogicalProject(a=[$0], c=[$2], proctime=[$3])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a])
++- SortLimit(orderBy=[c ASC, proctime ASC], offset=[2], fetch=[unlimited])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSortProcessingTimeWithLimit">
+ <Resource name="sql">
+ <![CDATA[SELECT a FROM MyTable ORDER BY proctime, c LIMIT 2]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0])
++- LogicalSort(sort0=[$1], sort1=[$2], dir0=[ASC-nulls-first], dir1=[ASC-nulls-first], fetch=[2])
+ +- LogicalProject(a=[$0], proctime=[$3], c=[$2])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a])
++- SortLimit(orderBy=[proctime ASC, c ASC], offset=[0], fetch=[2])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSortProcessingTimeWithOffset">
+ <Resource name="sql">
+ <![CDATA[SELECT a FROM MyTable ORDER BY proctime, c OFFSET 2]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0])
++- LogicalSort(sort0=[$1], sort1=[$2], dir0=[ASC-nulls-first], dir1=[ASC-nulls-first], offset=[2])
+ +- LogicalProject(a=[$0], proctime=[$3], c=[$2])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a])
++- SortLimit(orderBy=[proctime ASC, c ASC], offset=[2], fetch=[unlimited])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSortRowTimeAscWithLimit0">
+ <Resource name="sql">
+ <![CDATA[SELECT a FROM MyTable ORDER BY rowtime LIMIT 0]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0])
++- LogicalSort(sort0=[$1], dir0=[ASC-nulls-first], fetch=[0])
+ +- LogicalProject(a=[$0], rowtime=[$4])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a])
++- SortLimit(orderBy=[rowtime ASC], offset=[0], fetch=[0])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSortRowTimeAscWithLimit1">
+ <Resource name="sql">
+ <![CDATA[SELECT a FROM MyTable ORDER BY rowtime LIMIT 1]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0])
++- LogicalSort(sort0=[$1], dir0=[ASC-nulls-first], fetch=[1])
+ +- LogicalProject(a=[$0], rowtime=[$4])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a])
++- SortLimit(orderBy=[rowtime ASC], offset=[0], fetch=[1])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSortRowTimeAscWithOffSet0AndLimit0">
+ <Resource name="sql">
+ <![CDATA[SELECT a FROM MyTable ORDER BY rowtime LIMIT 0 OFFSET 0]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0])
++- LogicalSort(sort0=[$1], dir0=[ASC-nulls-first], offset=[0], fetch=[0])
+ +- LogicalProject(a=[$0], rowtime=[$4])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a])
++- SortLimit(orderBy=[rowtime ASC], offset=[0], fetch=[0])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSortRowTimeAscWithOffSet0AndLimit1">
+ <Resource name="sql">
+ <![CDATA[SELECT a FROM MyTable ORDER BY rowtime LIMIT 1 OFFSET 0]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0])
++- LogicalSort(sort0=[$1], dir0=[ASC-nulls-first], offset=[0], fetch=[1])
+ +- LogicalProject(a=[$0], rowtime=[$4])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a])
++- SortLimit(orderBy=[rowtime ASC], offset=[0], fetch=[1])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSortRowTimeAscWithOffSet1AndLimit0">
+ <Resource name="sql">
+ <![CDATA[SELECT a FROM MyTable ORDER BY rowtime LIMIT 0 OFFSET 1]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0])
++- LogicalSort(sort0=[$1], dir0=[ASC-nulls-first], offset=[1], fetch=[0])
+ +- LogicalProject(a=[$0], rowtime=[$4])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a])
++- SortLimit(orderBy=[rowtime ASC], offset=[1], fetch=[0])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSortRowTimeAscWithOffSet1AndLimit1">
+ <Resource name="sql">
+ <![CDATA[SELECT a FROM MyTable ORDER BY rowtime LIMIT 1 OFFSET 1]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0])
++- LogicalSort(sort0=[$1], dir0=[ASC-nulls-first], offset=[1], fetch=[1])
+ +- LogicalProject(a=[$0], rowtime=[$4])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a])
++- SortLimit(orderBy=[rowtime ASC], offset=[1], fetch=[1])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSortRowTimeDescSecondWithLimit">
+ <Resource name="sql">
+ <![CDATA[SELECT a FROM MyTable ORDER BY c, rowtime desc LIMIT 2]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0])
++- LogicalSort(sort0=[$1], sort1=[$2], dir0=[ASC-nulls-first], dir1=[DESC-nulls-last], fetch=[2])
+ +- LogicalProject(a=[$0], c=[$2], rowtime=[$4])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a])
++- SortLimit(orderBy=[c ASC, rowtime DESC], offset=[0], fetch=[2])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSortRowTimeDescSecondWithOffset">
+ <Resource name="sql">
+ <![CDATA[SELECT a FROM MyTable ORDER BY c, rowtime desc OFFSET 2]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0])
++- LogicalSort(sort0=[$1], sort1=[$2], dir0=[ASC-nulls-first], dir1=[DESC-nulls-last], offset=[2])
+ +- LogicalProject(a=[$0], c=[$2], rowtime=[$4])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a])
++- SortLimit(orderBy=[c ASC, rowtime DESC], offset=[2], fetch=[unlimited])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSortRowTimeDescWithLimit">
+ <Resource name="sql">
+ <![CDATA[SELECT a FROM MyTable ORDER BY rowtime desc, c LIMIT 2]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0])
++- LogicalSort(sort0=[$1], sort1=[$2], dir0=[DESC-nulls-last], dir1=[ASC-nulls-first], fetch=[2])
+ +- LogicalProject(a=[$0], rowtime=[$4], c=[$2])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a])
++- SortLimit(orderBy=[rowtime DESC, c ASC], offset=[0], fetch=[2])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSortRowTimeDescWithOffset">
+ <Resource name="sql">
+ <![CDATA[SELECT a FROM MyTable ORDER BY rowtime desc, c OFFSET 2]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0])
++- LogicalSort(sort0=[$1], sort1=[$2], dir0=[DESC-nulls-last], dir1=[ASC-nulls-first], offset=[2])
+ +- LogicalProject(a=[$0], rowtime=[$4], c=[$2])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a])
++- SortLimit(orderBy=[rowtime DESC, c ASC], offset=[2], fetch=[unlimited])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSortRowTimeDescWithOffSet0AndLimit0">
+ <Resource name="sql">
+ <![CDATA[SELECT a FROM MyTable ORDER BY rowtime desc LIMIT 0 OFFSET 0]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0])
++- LogicalSort(sort0=[$1], dir0=[DESC-nulls-last], offset=[0], fetch=[0])
+ +- LogicalProject(a=[$0], rowtime=[$4])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a])
++- SortLimit(orderBy=[rowtime DESC], offset=[0], fetch=[0])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSortRowTimeDescWithOffSet0AndLimit1">
+ <Resource name="sql">
+ <![CDATA[SELECT a FROM MyTable ORDER BY rowtime DESC LIMIT 1 OFFSET 0]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0])
++- LogicalSort(sort0=[$1], dir0=[DESC-nulls-last], offset=[0], fetch=[1])
+ +- LogicalProject(a=[$0], rowtime=[$4])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a])
++- SortLimit(orderBy=[rowtime DESC], offset=[0], fetch=[1])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSortRowTimeDescWithOffSet1AndLimit0">
+ <Resource name="sql">
+ <![CDATA[SELECT a FROM MyTable ORDER BY rowtime desc LIMIT 0 OFFSET 1]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0])
++- LogicalSort(sort0=[$1], dir0=[DESC-nulls-last], offset=[1], fetch=[0])
+ +- LogicalProject(a=[$0], rowtime=[$4])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a])
++- SortLimit(orderBy=[rowtime DESC], offset=[1], fetch=[0])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSortRowTimeDescWithOffSet1AndLimit1">
+ <Resource name="sql">
+ <![CDATA[SELECT a FROM MyTable ORDER BY rowtime desc LIMIT 1 OFFSET 1]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0])
++- LogicalSort(sort0=[$1], dir0=[DESC-nulls-last], offset=[1], fetch=[1])
+ +- LogicalProject(a=[$0], rowtime=[$4])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a])
++- SortLimit(orderBy=[rowtime DESC], offset=[1], fetch=[1])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSortRowTimeFirstAscWithLimit0">
+ <Resource name="sql">
+ <![CDATA[SELECT a FROM MyTable ORDER BY rowtime, c LIMIT 0]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0])
++- LogicalSort(sort0=[$1], sort1=[$2], dir0=[ASC-nulls-first], dir1=[ASC-nulls-first], fetch=[0])
+ +- LogicalProject(a=[$0], rowtime=[$4], c=[$2])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a])
++- SortLimit(orderBy=[rowtime ASC, c ASC], offset=[0], fetch=[0])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSortRowTimeFirstAscWithLimit1">
+ <Resource name="sql">
+ <![CDATA[SELECT a FROM MyTable ORDER BY rowtime, c LIMIT 1]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0])
++- LogicalSort(sort0=[$1], sort1=[$2], dir0=[ASC-nulls-first], dir1=[ASC-nulls-first], fetch=[1])
+ +- LogicalProject(a=[$0], rowtime=[$4], c=[$2])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a])
++- SortLimit(orderBy=[rowtime ASC, c ASC], offset=[0], fetch=[1])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSortRowTimeFirstAscWithOffSet1AndLimit0">
+ <Resource name="sql">
+ <![CDATA[SELECT a FROM MyTable ORDER BY rowtime, c LIMIT 0 OFFSET 1]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0])
++- LogicalSort(sort0=[$1], sort1=[$2], dir0=[ASC-nulls-first], dir1=[ASC-nulls-first], offset=[1], fetch=[0])
+ +- LogicalProject(a=[$0], rowtime=[$4], c=[$2])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a])
++- SortLimit(orderBy=[rowtime ASC, c ASC], offset=[1], fetch=[0])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSortRowTimeFirstAscWithOffSet1AndLimit1">
+ <Resource name="sql">
+ <![CDATA[SELECT a FROM MyTable ORDER BY rowtime, c LIMIT 1 OFFSET 1]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0])
++- LogicalSort(sort0=[$1], sort1=[$2], dir0=[ASC-nulls-first], dir1=[ASC-nulls-first], offset=[1], fetch=[1])
+ +- LogicalProject(a=[$0], rowtime=[$4], c=[$2])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a])
++- SortLimit(orderBy=[rowtime ASC, c ASC], offset=[1], fetch=[1])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSortRowTimeFirstDescWithLimit0">
+ <Resource name="sql">
+ <![CDATA[SELECT a FROM MyTable ORDER BY rowtime DESC LIMIT 0]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0])
++- LogicalSort(sort0=[$1], dir0=[DESC-nulls-last], fetch=[0])
+ +- LogicalProject(a=[$0], rowtime=[$4])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a])
++- SortLimit(orderBy=[rowtime DESC], offset=[0], fetch=[0])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSortRowTimeFirstDescWithLimit1">
+ <Resource name="sql">
+ <![CDATA[SELECT a FROM MyTable ORDER BY rowtime DESC LIMIT 1]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0])
++- LogicalSort(sort0=[$1], dir0=[DESC-nulls-last], fetch=[1])
+ +- LogicalProject(a=[$0], rowtime=[$4])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a])
++- SortLimit(orderBy=[rowtime DESC], offset=[0], fetch=[1])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSortRowTimeFirstDescWithOffSet1AndLimit0">
+ <Resource name="sql">
+ <![CDATA[SELECT a FROM MyTable ORDER BY rowtime, c desc LIMIT 0 OFFSET 1]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0])
++- LogicalSort(sort0=[$1], sort1=[$2], dir0=[ASC-nulls-first], dir1=[DESC-nulls-last], offset=[1], fetch=[0])
+ +- LogicalProject(a=[$0], rowtime=[$4], c=[$2])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a])
++- SortLimit(orderBy=[rowtime ASC, c DESC], offset=[1], fetch=[0])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSortRowTimeFirstDescWithOffSet1AndLimit1">
+ <Resource name="sql">
+ <![CDATA[SELECT a FROM MyTable ORDER BY rowtime, c desc LIMIT 1 OFFSET 1]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0])
++- LogicalSort(sort0=[$1], sort1=[$2], dir0=[ASC-nulls-first], dir1=[DESC-nulls-last], offset=[1], fetch=[1])
+ +- LogicalProject(a=[$0], rowtime=[$4], c=[$2])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a])
++- SortLimit(orderBy=[rowtime ASC, c DESC], offset=[1], fetch=[1])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSortRowTimeSecondAscWithLimit0">
+ <Resource name="sql">
+ <![CDATA[SELECT a FROM MyTable ORDER BY c, rowtime LIMIT 0]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0])
++- LogicalSort(sort0=[$1], sort1=[$2], dir0=[ASC-nulls-first], dir1=[ASC-nulls-first], fetch=[0])
+ +- LogicalProject(a=[$0], c=[$2], rowtime=[$4])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a])
++- SortLimit(orderBy=[c ASC, rowtime ASC], offset=[0], fetch=[0])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSortRowTimeSecondAscWithLimit1">
+ <Resource name="sql">
+ <![CDATA[SELECT a FROM MyTable ORDER BY c, rowtime LIMIT 1]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0])
++- LogicalSort(sort0=[$1], sort1=[$2], dir0=[ASC-nulls-first], dir1=[ASC-nulls-first], fetch=[1])
+ +- LogicalProject(a=[$0], c=[$2], rowtime=[$4])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a])
++- SortLimit(orderBy=[c ASC, rowtime ASC], offset=[0], fetch=[1])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSortRowTimeSecondDescWithLimit0">
+ <Resource name="sql">
+ <![CDATA[SELECT a FROM MyTable ORDER BY c, rowtime DESC LIMIT 0]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0])
++- LogicalSort(sort0=[$1], sort1=[$2], dir0=[ASC-nulls-first], dir1=[DESC-nulls-last], fetch=[0])
+ +- LogicalProject(a=[$0], c=[$2], rowtime=[$4])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a])
++- SortLimit(orderBy=[c ASC, rowtime DESC], offset=[0], fetch=[0])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSortRowTimeSecondDescWithLimit1">
+ <Resource name="sql">
+ <![CDATA[SELECT a FROM MyTable ORDER BY c, rowtime DESC LIMIT 1]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0])
++- LogicalSort(sort0=[$1], sort1=[$2], dir0=[ASC-nulls-first], dir1=[DESC-nulls-last], fetch=[1])
+ +- LogicalProject(a=[$0], c=[$2], rowtime=[$4])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a])
++- SortLimit(orderBy=[c ASC, rowtime DESC], offset=[0], fetch=[1])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSortRowTimeSecondWithLimit">
+ <Resource name="sql">
+ <![CDATA[SELECT a FROM MyTable ORDER BY c, rowtime LIMIT 2]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0])
++- LogicalSort(sort0=[$1], sort1=[$2], dir0=[ASC-nulls-first], dir1=[ASC-nulls-first], fetch=[2])
+ +- LogicalProject(a=[$0], c=[$2], rowtime=[$4])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a])
++- SortLimit(orderBy=[c ASC, rowtime ASC], offset=[0], fetch=[2])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSortRowTimeSecondWithOffset">
+ <Resource name="sql">
+ <![CDATA[SELECT a FROM MyTable ORDER BY c, rowtime OFFSET 2]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0])
++- LogicalSort(sort0=[$1], sort1=[$2], dir0=[ASC-nulls-first], dir1=[ASC-nulls-first], offset=[2])
+ +- LogicalProject(a=[$0], c=[$2], rowtime=[$4])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a])
++- SortLimit(orderBy=[c ASC, rowtime ASC], offset=[2], fetch=[unlimited])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSortWithoutTimeWithLimit">
+ <Resource name="sql">
+ <![CDATA[SELECT a FROM MyTable ORDER BY c LIMIT 2]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0])
++- LogicalSort(sort0=[$1], dir0=[ASC-nulls-first], fetch=[2])
+ +- LogicalProject(a=[$0], c=[$2])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a])
++- SortLimit(orderBy=[c ASC], offset=[0], fetch=[2])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSortRowTimeWithLimit">
+ <Resource name="sql">
+ <![CDATA[SELECT a FROM MyTable ORDER BY rowtime, c LIMIT 2]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0])
++- LogicalSort(sort0=[$1], sort1=[$2], dir0=[ASC-nulls-first], dir1=[ASC-nulls-first], fetch=[2])
+ +- LogicalProject(a=[$0], rowtime=[$4], c=[$2])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a])
++- SortLimit(orderBy=[rowtime ASC, c ASC], offset=[0], fetch=[2])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSortRowTimeWithOffset">
+ <Resource name="sql">
+ <![CDATA[SELECT a FROM MyTable ORDER BY rowtime, c OFFSET 2]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0])
++- LogicalSort(sort0=[$1], sort1=[$2], dir0=[ASC-nulls-first], dir1=[ASC-nulls-first], offset=[2])
+ +- LogicalProject(a=[$0], rowtime=[$4], c=[$2])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a])
++- SortLimit(orderBy=[rowtime ASC, c ASC], offset=[2], fetch=[unlimited])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSortWithoutTimeWithLimit0">
+ <Resource name="sql">
+ <![CDATA[SELECT a FROM MyTable ORDER BY c LIMIT 0]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0])
++- LogicalSort(sort0=[$1], dir0=[ASC-nulls-first], fetch=[0])
+ +- LogicalProject(a=[$0], c=[$2])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a])
++- SortLimit(orderBy=[c ASC], offset=[0], fetch=[0])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSortWithoutTimeWithOffset">
+ <Resource name="sql">
+ <![CDATA[SELECT a FROM MyTable ORDER BY c OFFSET 2]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0])
++- LogicalSort(sort0=[$1], dir0=[ASC-nulls-first], offset=[2])
+ +- LogicalProject(a=[$0], c=[$2])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a])
++- SortLimit(orderBy=[c ASC], offset=[2], fetch=[unlimited])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+</Root>
diff --git a/flink-table/flink-table-planner-blink/src/test/resources/org/apache/flink/table/plan/stream/sql/SortTest.xml b/flink-table/flink-table-planner-blink/src/test/resources/org/apache/flink/table/plan/stream/sql/SortTest.xml
new file mode 100644
index 0000000..e48b558
--- /dev/null
+++ b/flink-table/flink-table-planner-blink/src/test/resources/org/apache/flink/table/plan/stream/sql/SortTest.xml
@@ -0,0 +1,206 @@
+<?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="testSortProcessingTime">
+ <Resource name="sql">
+ <![CDATA[SELECT a FROM MyTable ORDER BY proctime, c]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0])
++- LogicalSort(sort0=[$1], sort1=[$2], dir0=[ASC-nulls-first], dir1=[ASC-nulls-first])
+ +- LogicalProject(a=[$0], proctime=[$3], c=[$2])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a])
++- TemporalSort(orderBy=[proctime ASC, c ASC])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSortProcessingTimeDesc">
+ <Resource name="sql">
+ <![CDATA[SELECT a FROM MyTable ORDER BY proctime desc, c]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0])
++- LogicalSort(sort0=[$1], sort1=[$2], dir0=[DESC-nulls-last], dir1=[ASC-nulls-first])
+ +- LogicalProject(a=[$0], proctime=[$3], c=[$2])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a])
++- Sort(orderBy=[proctime DESC, c ASC])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSortRowTimeSecondDesc">
+ <Resource name="sql">
+ <![CDATA[SELECT a FROM MyTable ORDER BY c, rowtime desc]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0])
++- LogicalSort(sort0=[$1], sort1=[$2], dir0=[ASC-nulls-first], dir1=[DESC-nulls-last])
+ +- LogicalProject(a=[$0], c=[$2], rowtime=[$4])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a])
++- Sort(orderBy=[c ASC, rowtime DESC])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSortProcessingTimeSecond">
+ <Resource name="sql">
+ <![CDATA[SELECT a FROM MyTable ORDER BY c, proctime]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0])
++- LogicalSort(sort0=[$1], sort1=[$2], dir0=[ASC-nulls-first], dir1=[ASC-nulls-first])
+ +- LogicalProject(a=[$0], c=[$2], proctime=[$3])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a])
++- Sort(orderBy=[c ASC, proctime ASC])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSortProcessingTimeSecondDesc">
+ <Resource name="sql">
+ <![CDATA[SELECT a FROM MyTable ORDER BY c, proctime desc]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0])
++- LogicalSort(sort0=[$1], sort1=[$2], dir0=[ASC-nulls-first], dir1=[DESC-nulls-last])
+ +- LogicalProject(a=[$0], c=[$2], proctime=[$3])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a])
++- Sort(orderBy=[c ASC, proctime DESC])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSortRowTime">
+ <Resource name="sql">
+ <![CDATA[SELECT a FROM MyTable ORDER BY rowtime, c]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0])
++- LogicalSort(sort0=[$1], sort1=[$2], dir0=[ASC-nulls-first], dir1=[ASC-nulls-first])
+ +- LogicalProject(a=[$0], rowtime=[$4], c=[$2])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a])
++- TemporalSort(orderBy=[rowtime ASC, c ASC])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSortRowTimeSecond">
+ <Resource name="sql">
+ <![CDATA[SELECT a FROM MyTable ORDER BY c, rowtime]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0])
++- LogicalSort(sort0=[$1], sort1=[$2], dir0=[ASC-nulls-first], dir1=[ASC-nulls-first])
+ +- LogicalProject(a=[$0], c=[$2], rowtime=[$4])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a])
++- Sort(orderBy=[c ASC, rowtime ASC])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSortWithoutTime">
+ <Resource name="sql">
+ <![CDATA[SELECT a FROM MyTable ORDER BY c]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0])
++- LogicalSort(sort0=[$1], dir0=[ASC-nulls-first])
+ +- LogicalProject(a=[$0], c=[$2])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a])
++- Sort(orderBy=[c ASC])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+ <TestCase name="testSortRowTimeDesc">
+ <Resource name="sql">
+ <![CDATA[SELECT a FROM MyTable ORDER BY rowtime desc, c]]>
+ </Resource>
+ <Resource name="planBefore">
+ <![CDATA[
+LogicalProject(a=[$0])
++- LogicalSort(sort0=[$1], sort1=[$2], dir0=[DESC-nulls-last], dir1=[ASC-nulls-first])
+ +- LogicalProject(a=[$0], rowtime=[$4], c=[$2])
+ +- LogicalTableScan(table=[[MyTable]])
+]]>
+ </Resource>
+ <Resource name="planAfter">
+ <![CDATA[
+Calc(select=[a])
++- Sort(orderBy=[rowtime DESC, c ASC])
+ +- Exchange(distribution=[single])
+ +- DataStreamScan(table=[[_DataStreamTable_0]], fields=[a, b, c, proctime, rowtime])
+]]>
+ </Resource>
+ </TestCase>
+</Root>
diff --git a/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/plan/batch/sql/LimitTest.scala b/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/plan/batch/sql/LimitTest.scala
new file mode 100644
index 0000000..0cfcfe7
--- /dev/null
+++ b/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/plan/batch/sql/LimitTest.scala
@@ -0,0 +1,93 @@
+/*
+ * 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.SqlParserException
+import org.apache.flink.table.util.TableTestBase
+
+import org.junit.Test
+
+class LimitTest extends TableTestBase {
+
+ private val util = batchTestUtil()
+ util.addTableSource[(Int, Long, String)]("MyTable", 'a, 'b, 'c)
+ // TODO optimize `limit 0`
+
+ @Test
+ def testLimitWithoutOffset(): Unit = {
+ util.verifyPlan("SELECT * FROM MyTable LIMIT 5")
+ }
+
+ @Test
+ def testLimit0WithoutOffset(): Unit = {
+ util.verifyPlan("SELECT * FROM MyTable LIMIT 0")
+ }
+
+ @Test(expected = classOf[SqlParserException])
+ def testNegativeLimitWithoutOffset(): Unit = {
+ util.verifyPlan("SELECT * FROM MyTable LIMIT -1")
+ }
+
+ @Test
+ def testLimitWithOffset(): Unit = {
+ util.verifyPlan("SELECT a, c FROM MyTable LIMIT 10 OFFSET 1")
+ }
+
+ @Test
+ def testLimitWithOffset0(): Unit = {
+ util.verifyPlan("SELECT a, c FROM MyTable LIMIT 10 OFFSET 0")
+ }
+
+ @Test
+ def testLimit0WithOffset0(): Unit = {
+ util.verifyPlan("SELECT a, c FROM MyTable LIMIT 0 OFFSET 0")
+ }
+
+ @Test
+ def testLimit0WithOffset(): Unit = {
+ util.verifyPlan("SELECT a, c FROM MyTable LIMIT 0 OFFSET 10")
+ }
+
+ @Test(expected = classOf[SqlParserException])
+ def testLimitWithNegativeOffset(): Unit = {
+ util.verifyPlan("SELECT a, c FROM MyTable LIMIT 10 OFFSET -1")
+ }
+
+ @Test
+ def testFetchWithOffset(): Unit = {
+ util.verifyPlan("SELECT a, c FROM MyTable OFFSET 10 ROWS FETCH NEXT 10 ROWS ONLY")
+ }
+
+ @Test
+ def testFetchWithoutOffset(): Unit = {
+ util.verifyPlan("SELECT a, c FROM MyTable FETCH FIRST 10 ROWS ONLY")
+ }
+
+ @Test
+ def testFetch0WithoutOffset(): Unit = {
+ util.verifyPlan("SELECT a, c FROM MyTable FETCH FIRST 0 ROWS ONLY")
+ }
+
+ @Test
+ def testOnlyOffset(): Unit = {
+ util.verifyPlan("SELECT a, c FROM MyTable OFFSET 10 ROWS")
+ }
+
+}
diff --git a/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/plan/batch/sql/RankTest.scala b/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/plan/batch/sql/RankTest.scala
new file mode 100644
index 0000000..4f26b1d
--- /dev/null
+++ b/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/plan/batch/sql/RankTest.scala
@@ -0,0 +1,170 @@
+/*
+ * 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.ValidationException
+import org.apache.flink.table.util.TableTestBase
+
+import org.junit.Test
+
+class RankTest extends TableTestBase {
+
+ private val util = batchTestUtil()
+ util.addTableSource[(Int, String, Long)]("MyTable", 'a, 'b, 'c)
+
+ @Test(expected = classOf[RuntimeException])
+ def testRowNumberWithoutOrderBy(): Unit = {
+ val sqlQuery =
+ """
+ |SELECT ROW_NUMBER() over (partition by a) FROM MyTable
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test(expected = classOf[RuntimeException])
+ def testRowNumberWithMultiGroups(): Unit = {
+ val sqlQuery =
+ """
+ |SELECT ROW_NUMBER() over (partition by a order by b) as a,
+ | ROW_NUMBER() over (partition by b) as b
+ | FROM MyTable
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test(expected = classOf[ValidationException])
+ def testRankWithoutOrderBy(): Unit = {
+ val sqlQuery =
+ """
+ |SELECT RANK() over (partition by a) FROM MyTable
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test(expected = classOf[ValidationException])
+ def testRankWithMultiGroups(): Unit = {
+ val sqlQuery =
+ """
+ |SELECT RANK() over (partition by a order by b) as a,
+ | RANK() over (partition by b) as b
+ | FROM MyTable
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test(expected = classOf[ValidationException])
+ def testDenseRankWithoutOrderBy(): Unit = {
+ val sqlQuery =
+ """
+ |SELECT dense_rank() over (partition by a) FROM MyTable
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test(expected = classOf[ValidationException])
+ def testDenseRankWithMultiGroups(): Unit = {
+ val sqlQuery =
+ """
+ |SELECT DENSE_RANK() over (partition by a order by b) as a,
+ | DENSE_RANK() over (partition by b) as b
+ | FROM MyTable
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test
+ def testRankValueFilterWithUpperValue(): Unit = {
+ val sqlQuery =
+ """
+ |SELECT * FROM (
+ | SELECT a, b, RANK() OVER (PARTITION BY b ORDER BY a) rk FROM MyTable) t
+ |WHERE rk <= 2 AND a > 10
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test
+ def testRankValueFilterWithRange(): Unit = {
+ val sqlQuery =
+ """
+ |SELECT * FROM (
+ | SELECT a, b, RANK() OVER (PARTITION BY b, c ORDER BY a) rk FROM MyTable) t
+ |WHERE rk <= 2 AND rk > -2
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test
+ def testRankValueFilterWithEquals(): Unit = {
+ val sqlQuery =
+ """
+ |SELECT * FROM (
+ | SELECT a, b, RANK() OVER (PARTITION BY b ORDER BY a, c) rk FROM MyTable) t
+ |WHERE rk = 2
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test
+ def testWithoutPartitionBy(): Unit = {
+ val sqlQuery =
+ """
+ |SELECT * FROM (
+ | SELECT a, b, RANK() OVER (ORDER BY a) rk FROM MyTable) t
+ |WHERE rk < 10
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test
+ def testMultiSameRankFunctionsWithSameGroup(): Unit = {
+ val sqlQuery =
+ """
+ |SELECT * FROM (
+ | SELECT a, b,
+ | RANK() OVER (PARTITION BY b ORDER BY a) rk1,
+ | RANK() OVER (PARTITION BY b ORDER BY a) rk2 FROM MyTable) t
+ |WHERE rk1 < 10
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test
+ def testDuplicateRankFunctionColumnName(): Unit = {
+ util.addTableSource[(Int, Long, String)]("MyTable2", 'a, 'b, 'rk)
+ val sqlQuery =
+ """
+ |SELECT * FROM (
+ | SELECT a, b, RANK() OVER (PARTITION BY b ORDER BY a) rk FROM MyTable2) t
+ |WHERE rk < 10
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test
+ def testRankFunctionInMiddle(): Unit = {
+ val sqlQuery =
+ """
+ |SELECT * FROM (
+ | SELECT a, RANK() OVER (PARTITION BY a ORDER BY a) rk, b, c FROM MyTable) t
+ |WHERE rk < 10
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+}
diff --git a/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/plan/batch/sql/SortLimitTest.scala b/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/plan/batch/sql/SortLimitTest.scala
new file mode 100644
index 0000000..4ebdf44
--- /dev/null
+++ b/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/plan/batch/sql/SortLimitTest.scala
@@ -0,0 +1,98 @@
+/*
+ * 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.TableConfigOptions
+import org.apache.flink.table.util.TableTestBase
+
+import org.junit.Test
+
+class SortLimitTest extends TableTestBase {
+
+ private val util = batchTestUtil()
+ util.addTableSource[(Int, Long, String)]("MyTable", 'a, 'b, 'c)
+ util.tableEnv.getConfig.getConf.setInteger(TableConfigOptions.SQL_EXEC_SORT_DEFAULT_LIMIT, 200)
+ // TODO optimize `limit 0`
+
+ @Test
+ def testNonRangeSortWithoutOffset(): Unit = {
+ util.tableEnv.getConfig.getConf.setBoolean(
+ TableConfigOptions.SQL_EXEC_SORT_RANGE_ENABLED, false)
+ util.verifyPlan("SELECT * FROM MyTable ORDER BY a DESC LIMIT 5")
+ }
+
+ @Test
+ def testNonRangeSortWithLimit0(): Unit = {
+ util.tableEnv.getConfig.getConf.setBoolean(
+ TableConfigOptions.SQL_EXEC_SORT_RANGE_ENABLED, false)
+ util.verifyPlan("SELECT * FROM MyTable ORDER BY a DESC LIMIT 0")
+ }
+
+ @Test
+ def testNonRangeSortOnlyWithOffset(): Unit = {
+ util.tableEnv.getConfig.getConf.setBoolean(
+ TableConfigOptions.SQL_EXEC_SORT_RANGE_ENABLED, false)
+ util.verifyPlan("SELECT * FROM MyTable ORDER BY a DESC OFFSET 10 ROWS")
+ }
+
+ @Test
+ def testNoneRangeSortWithOffsetLimit(): Unit = {
+ util.tableEnv.getConfig.getConf.setBoolean(
+ TableConfigOptions.SQL_EXEC_SORT_RANGE_ENABLED, false)
+ util.verifyPlan("SELECT * FROM MyTable ORDER BY a DESC, b LIMIT 10 OFFSET 1")
+ }
+
+ @Test
+ def testNoneRangeSortWithOffsetLimit0(): Unit = {
+ util.tableEnv.getConfig.getConf.setBoolean(
+ TableConfigOptions.SQL_EXEC_SORT_RANGE_ENABLED, false)
+ util.verifyPlan("SELECT * FROM MyTable ORDER BY a DESC, b LIMIT 0 OFFSET 1")
+ }
+
+ @Test
+ def testRangeSortOnWithoutOffset(): Unit = {
+ util.tableEnv.getConfig.getConf.setBoolean(TableConfigOptions.SQL_EXEC_SORT_RANGE_ENABLED, true)
+ util.verifyPlan("SELECT * FROM MyTable ORDER BY a DESC LIMIT 5")
+ }
+
+ @Test
+ def testRangeSortOnWithLimit0(): Unit = {
+ util.tableEnv.getConfig.getConf.setBoolean(TableConfigOptions.SQL_EXEC_SORT_RANGE_ENABLED, true)
+ util.verifyPlan("SELECT * FROM MyTable ORDER BY a DESC LIMIT 0")
+ }
+
+ @Test
+ def testRangeSortOnlyWithOffset(): Unit = {
+ util.tableEnv.getConfig.getConf.setBoolean(TableConfigOptions.SQL_EXEC_SORT_RANGE_ENABLED, true)
+ util.verifyPlan("SELECT * FROM MyTable ORDER BY a DESC OFFSET 10 ROWS")
+ }
+
+ @Test
+ def testRangeSortWithOffsetLimit(): Unit = {
+ util.tableEnv.getConfig.getConf.setBoolean(TableConfigOptions.SQL_EXEC_SORT_RANGE_ENABLED, true)
+ util.verifyPlan("SELECT * FROM MyTable ORDER BY a DESC, b LIMIT 10 OFFSET 1")
+ }
+
+ @Test
+ def testRangeSortWithOffsetLimit0(): Unit = {
+ util.tableEnv.getConfig.getConf.setBoolean(TableConfigOptions.SQL_EXEC_SORT_RANGE_ENABLED, true)
+ util.verifyPlan("SELECT * FROM MyTable ORDER BY a DESC, b LIMIT 0 OFFSET 1")
+ }
+}
diff --git a/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/plan/batch/sql/SortTest.scala b/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/plan/batch/sql/SortTest.scala
new file mode 100644
index 0000000..7bf9402
--- /dev/null
+++ b/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/plan/batch/sql/SortTest.scala
@@ -0,0 +1,69 @@
+/*
+ * 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.TableConfigOptions
+import org.apache.flink.table.util.TableTestBase
+
+import org.junit.Test
+
+class SortTest extends TableTestBase {
+
+ private val util = batchTestUtil()
+ util.addTableSource[(Int, Long, String)]("MyTable", 'a, 'b, 'c)
+
+ @Test
+ def testNonRangeSortOnSingleFieldWithoutForceLimit(): Unit = {
+ util.tableEnv.getConfig.getConf.setBoolean(
+ TableConfigOptions.SQL_EXEC_SORT_RANGE_ENABLED, false)
+ util.tableEnv.getConfig.getConf.setInteger(TableConfigOptions.SQL_EXEC_SORT_DEFAULT_LIMIT, -1)
+ util.verifyPlan("SELECT * FROM MyTable ORDER BY a DESC")
+ }
+
+ @Test
+ def testNonRangeSortOnMultiFieldsWithoutForceLimit(): Unit = {
+ util.tableEnv.getConfig.getConf.setBoolean(
+ TableConfigOptions.SQL_EXEC_SORT_RANGE_ENABLED, false)
+ util.tableEnv.getConfig.getConf.setInteger(TableConfigOptions.SQL_EXEC_SORT_DEFAULT_LIMIT, -1)
+ util.verifyPlan("SELECT * FROM MyTable ORDER BY a DESC, b")
+ }
+
+ @Test
+ def testNonRangeSortWithForceLimit(): Unit = {
+ util.tableEnv.getConfig.getConf.setBoolean(
+ TableConfigOptions.SQL_EXEC_SORT_RANGE_ENABLED, false)
+ util.tableEnv.getConfig.getConf.setInteger(TableConfigOptions.SQL_EXEC_SORT_DEFAULT_LIMIT, 200)
+ util.verifyPlan("SELECT * FROM MyTable ORDER BY a DESC")
+ }
+
+ @Test
+ def testRangeSortWithoutForceLimit(): Unit = {
+ util.tableEnv.getConfig.getConf.setBoolean(TableConfigOptions.SQL_EXEC_SORT_RANGE_ENABLED, true)
+ util.tableEnv.getConfig.getConf.setInteger(TableConfigOptions.SQL_EXEC_SORT_DEFAULT_LIMIT, -1)
+ util.verifyPlan("SELECT * FROM MyTable ORDER BY a DESC")
+ }
+
+ @Test
+ def testRangeSortWithForceLimit(): Unit = {
+ util.tableEnv.getConfig.getConf.setBoolean(TableConfigOptions.SQL_EXEC_SORT_RANGE_ENABLED, true)
+ util.tableEnv.getConfig.getConf.setInteger(TableConfigOptions.SQL_EXEC_SORT_DEFAULT_LIMIT, 200)
+ util.verifyPlan("SELECT * FROM MyTable ORDER BY a DESC")
+ }
+}
diff --git a/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/plan/rules/logical/FlinkLogicalRankRuleForConstantRangeTest.scala b/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/plan/rules/logical/FlinkLogicalRankRuleForConstantRangeTest.scala
new file mode 100644
index 0000000..fab61c2
--- /dev/null
+++ b/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/plan/rules/logical/FlinkLogicalRankRuleForConstantRangeTest.scala
@@ -0,0 +1,210 @@
+/*
+ * 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.rules.logical
+
+import org.apache.flink.api.scala._
+import org.apache.flink.table.plan.optimize.program.FlinkBatchProgram
+import org.apache.flink.table.util.TableTestBase
+
+import org.junit.Test
+
+/**
+ * Test for [[FlinkLogicalRankRuleForConstantRange]].
+ */
+class FlinkLogicalRankRuleForConstantRangeTest extends TableTestBase {
+
+ private val util = batchTestUtil()
+ util.addTableSource[(Int, String, Long)]("MyTable", 'a, 'b, 'c)
+ util.buildBatchProgram(FlinkBatchProgram.PHYSICAL)
+
+ @Test
+ def testRowNumberFunc(): Unit = {
+ // can not be converted to Rank
+ val sqlQuery =
+ """
+ |SELECT * FROM (
+ | SELECT a, b, ROW_NUMBER() OVER (PARTITION BY b ORDER BY a) rn FROM MyTable) t
+ |WHERE rn <= 2
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test
+ def testWithoutFilter(): Unit = {
+ // can not be converted to Rank
+ util.verifyPlan("SELECT a, b, RANK() OVER (PARTITION BY b ORDER BY a) rk FROM MyTable")
+ }
+
+ @Test
+ def testRankValueFilterWithUpperValue(): Unit = {
+ val sqlQuery =
+ """
+ |SELECT * FROM (
+ | SELECT a, b, RANK() OVER (PARTITION BY b ORDER BY a) rk FROM MyTable) t
+ |WHERE rk <= 2 AND a > 10
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test
+ def testRankValueFilterWithRange(): Unit = {
+ val sqlQuery =
+ """
+ |SELECT * FROM (
+ | SELECT a, b, RANK() OVER (PARTITION BY b, c ORDER BY a) rk FROM MyTable) t
+ |WHERE rk <= 2 AND rk > -2
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test
+ def testRankValueFilterWithLowerValue(): Unit = {
+ // can not be converted to Rank
+ val sqlQuery =
+ """
+ |SELECT * FROM (
+ | SELECT a, b, RANK() OVER (PARTITION BY b ORDER BY a, c) rk FROM MyTable) t
+ |WHERE rk > 2
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test
+ def testRankValueFilterWithEquals(): Unit = {
+ val sqlQuery =
+ """
+ |SELECT * FROM (
+ | SELECT a, b, RANK() OVER (PARTITION BY b ORDER BY a, c) rk FROM MyTable) t
+ |WHERE rk = 2
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test
+ def testRankValueFilterWithVariableField1(): Unit = {
+ // can not be converted to Rank
+ val sqlQuery =
+ """
+ |SELECT * FROM (
+ | SELECT a, b, RANK() OVER (PARTITION BY b ORDER BY c) rk FROM MyTable) t
+ |WHERE rk < a
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test
+ def testRankValueFilterWithVariableField2(): Unit = {
+ // can not be converted to Rank
+ val sqlQuery =
+ """
+ |SELECT * FROM (
+ | SELECT a, b, RANK() OVER (PARTITION BY b ORDER BY c) rk FROM MyTable) t
+ |WHERE rk > a
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test
+ def testRankValueFilterWithVariableField3(): Unit = {
+ // can not be converted to Rank
+ val sqlQuery =
+ """
+ |SELECT * FROM (
+ | SELECT a, b, RANK() OVER (PARTITION BY b ORDER BY c) rk FROM MyTable) t
+ |WHERE rk < a and b > 5
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test
+ def testRankValueFilterWithVariableField4(): Unit = {
+ // can not be converted to Rank
+ val sqlQuery =
+ """
+ |SELECT * FROM (
+ | SELECT a, b, RANK() OVER (PARTITION BY a ORDER BY c) rk FROM MyTable) t
+ |WHERE rk = b
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test
+ def testWithoutPartitionBy(): Unit = {
+ val sqlQuery =
+ """
+ |SELECT * FROM (
+ | SELECT a, b, RANK() OVER (ORDER BY a) rk FROM MyTable) t
+ |WHERE rk < 10
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test
+ def testMultiSameRankFunctionsWithSameGroup(): Unit = {
+ val sqlQuery =
+ """
+ |SELECT * FROM (
+ | SELECT a, b,
+ | RANK() OVER (PARTITION BY b ORDER BY a) rk1,
+ | RANK() OVER (PARTITION BY b ORDER BY a) rk2 FROM MyTable) t
+ |WHERE rk1 < 10
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test
+ def testMultiSameRankFunctionsWithDiffGroup(): Unit = {
+ // can not be converted to Rank
+ val sqlQuery =
+ """
+ |SELECT * FROM (
+ | SELECT a, b,
+ | RANK() OVER (PARTITION BY b ORDER BY a) rk1,
+ | RANK() OVER (PARTITION BY c ORDER BY a) rk2 FROM MyTable) t
+ |WHERE rk1 < 10
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test
+ def testMultiDiffRankFunctions(): Unit = {
+ // can not be converted to Rank
+ val sqlQuery =
+ """
+ |SELECT * FROM (
+ | SELECT a, b,
+ | RANK() OVER (PARTITION BY b ORDER BY a) rk,
+ | ROW_NUMBER() OVER (PARTITION BY b ORDER BY a) rn FROM MyTable) t
+ |WHERE rk < 10
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test
+ def testDuplicateRankFunctionColumnName(): Unit = {
+ util.addTableSource[(Int, Long, String)]("MyTable2", 'a, 'b, 'rk)
+ val sqlQuery =
+ """
+ |SELECT * FROM (
+ | SELECT a, b, RANK() OVER (PARTITION BY b ORDER BY a) rk FROM MyTable2) t
+ |WHERE rk < 10
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+}
diff --git a/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/plan/rules/logical/FlinkLogicalRankRuleForRangeEndTest.scala b/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/plan/rules/logical/FlinkLogicalRankRuleForRangeEndTest.scala
new file mode 100644
index 0000000..1e62608
--- /dev/null
+++ b/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/plan/rules/logical/FlinkLogicalRankRuleForRangeEndTest.scala
@@ -0,0 +1,195 @@
+/*
+ * 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.rules.logical
+
+import org.apache.flink.api.scala._
+import org.apache.flink.table.api.TableException
+import org.apache.flink.table.plan.optimize.program.FlinkStreamProgram
+import org.apache.flink.table.util.TableTestBase
+
+import org.junit.Test
+
+/**
+ * Test for [[FlinkLogicalRankRuleForRangeEnd]].
+ */
+class FlinkLogicalRankRuleForRangeEndTest extends TableTestBase {
+ private val util = streamTestUtil()
+ util.addTableSource[(Int, String, Long)]("MyTable", 'a, 'b, 'c)
+ util.buildStreamProgram(FlinkStreamProgram.PHYSICAL)
+
+ @Test
+ def testRowNumberFunc(): Unit = {
+ val sqlQuery =
+ """
+ |SELECT * FROM (
+ | SELECT a, b, ROW_NUMBER() OVER (PARTITION BY b ORDER BY a) rn FROM MyTable) t
+ |WHERE rn <= 2
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test
+ def testWithoutFilter(): Unit = {
+ // can not be converted to Rank
+ util.verifyPlan("SELECT a, b, RANK() OVER (PARTITION BY b ORDER BY a) rk FROM MyTable")
+ }
+
+ @Test
+ def testRankValueFilterWithUpperValue(): Unit = {
+ val sqlQuery =
+ """
+ |SELECT * FROM (
+ | SELECT a, b, RANK() OVER (PARTITION BY b ORDER BY a) rk FROM MyTable) t
+ |WHERE rk <= 2 AND a > 10
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test
+ def testRankValueFilterWithRange(): Unit = {
+ val sqlQuery =
+ """
+ |SELECT * FROM (
+ | SELECT a, b, RANK() OVER (PARTITION BY b, c ORDER BY a) rk FROM MyTable) t
+ |WHERE rk <= 2 AND rk > -2
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test
+ def testRankValueFilterWithLowerValue(): Unit = {
+ val sqlQuery =
+ """
+ |SELECT * FROM (
+ | SELECT a, b, RANK() OVER (PARTITION BY b ORDER BY a, c) rk FROM MyTable) t
+ |WHERE rk > 2
+ """.stripMargin
+ thrown.expectMessage("Rank end is not specified.")
+ thrown.expect(classOf[TableException])
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test
+ def testRankValueFilterWithEquals(): Unit = {
+ val sqlQuery =
+ """
+ |SELECT * FROM (
+ | SELECT a, b, RANK() OVER (PARTITION BY b ORDER BY a, c) rk FROM MyTable) t
+ |WHERE rk = 2
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test
+ def testRankValueFilterWithVariableField1(): Unit = {
+ val sqlQuery =
+ """
+ |SELECT * FROM (
+ | SELECT a, b, RANK() OVER (PARTITION BY b ORDER BY c) rk FROM MyTable) t
+ |WHERE rk < a
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test
+ def testRankValueFilterWithVariableField2(): Unit = {
+ // can not be converted to Rank
+ val sqlQuery =
+ """
+ |SELECT * FROM (
+ | SELECT a, b, RANK() OVER (PARTITION BY b ORDER BY c) rk FROM MyTable) t
+ |WHERE rk > a
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test
+ def testRankValueFilterWithVariableField3(): Unit = {
+ val sqlQuery =
+ """
+ |SELECT * FROM (
+ | SELECT a, b, RANK() OVER (PARTITION BY b ORDER BY c) rk FROM MyTable) t
+ |WHERE rk < a and b > 5
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test
+ def testRankValueFilterWithVariableField4(): Unit = {
+ val sqlQuery =
+ """
+ |SELECT * FROM (
+ | SELECT a, b, RANK() OVER (PARTITION BY a ORDER BY c) rk FROM MyTable) t
+ |WHERE rk = b
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test
+ def testWithoutPartitionBy(): Unit = {
+ val sqlQuery =
+ """
+ |SELECT * FROM (
+ | SELECT a, b, RANK() OVER (ORDER BY a) rk FROM MyTable) t
+ |WHERE rk < 10
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test
+ def testMultiSameRankFunctionsWithSameGroup(): Unit = {
+ val sqlQuery =
+ """
+ |SELECT * FROM (
+ | SELECT a, b,
+ | RANK() OVER (PARTITION BY b ORDER BY a) rk1,
+ | RANK() OVER (PARTITION BY b ORDER BY a) rk2 FROM MyTable) t
+ |WHERE rk1 < 10
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test
+ def testMultiSameRankFunctionsWithDiffGroup(): Unit = {
+ // can not be converted to Rank
+ val sqlQuery =
+ """
+ |SELECT * FROM (
+ | SELECT a, b,
+ | RANK() OVER (PARTITION BY b ORDER BY a) rk1,
+ | RANK() OVER (PARTITION BY c ORDER BY a) rk2 FROM MyTable) t
+ |WHERE rk1 < 10
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test
+ def testMultiDiffRankFunctions(): Unit = {
+ // can not be converted to Rank
+ val sqlQuery =
+ """
+ |SELECT * FROM (
+ | SELECT a, b,
+ | RANK() OVER (PARTITION BY b ORDER BY a) rk,
+ | ROW_NUMBER() OVER (PARTITION BY b ORDER BY a) rn FROM MyTable) t
+ |WHERE rk < 10
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+}
diff --git a/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/plan/schema/TimeIndicatorRelDataTypeTest.scala b/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/plan/schema/TimeIndicatorRelDataTypeTest.scala
new file mode 100644
index 0000000..287662b
--- /dev/null
+++ b/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/plan/schema/TimeIndicatorRelDataTypeTest.scala
@@ -0,0 +1,42 @@
+/*
+ * 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.schema
+
+import org.apache.flink.table.calcite.{FlinkTypeFactory, FlinkTypeSystem}
+
+import org.junit.Assert.assertEquals
+import org.junit.Test
+
+/**
+ * Tests for TimeIndicatorRelDataType.
+ */
+class TimeIndicatorRelDataTypeTest {
+
+ @Test
+ def testGenerateTypeString() {
+ val typeFactory = new FlinkTypeFactory(new FlinkTypeSystem)
+ assertEquals(
+ "TIME ATTRIBUTE(PROCTIME) NOT NULL",
+ typeFactory.createProctimeIndicatorType().getFullTypeString)
+ assertEquals(
+ "TIME ATTRIBUTE(ROWTIME) NOT NULL",
+ typeFactory.createRowtimeIndicatorType().getFullTypeString)
+ }
+
+}
diff --git a/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/plan/stream/sql/LimitTest.scala b/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/plan/stream/sql/LimitTest.scala
new file mode 100644
index 0000000..fe440f4
--- /dev/null
+++ b/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/plan/stream/sql/LimitTest.scala
@@ -0,0 +1,212 @@
+/*
+ * 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.SqlParserException
+import org.apache.flink.table.util.TableTestBase
+
+import org.junit.Test
+
+class LimitTest extends TableTestBase {
+
+ private val util = streamTestUtil()
+ util.addDataStream[(Int, String, Long)]("MyTable", 'a, 'b, 'c, 'proctime, 'rowtime)
+ // TODO optimize `limit 0`
+
+ @Test
+ def testLimitWithoutOffset(): Unit = {
+ util.verifyPlan("SELECT * FROM MyTable LIMIT 5")
+ }
+
+ @Test
+ def testLimit0WithoutOffset(): Unit = {
+ util.verifyPlan("SELECT * FROM MyTable LIMIT 0")
+ }
+
+ @Test(expected = classOf[SqlParserException])
+ def testNegativeLimitWithoutOffset(): Unit = {
+ util.verifyPlan("SELECT * FROM MyTable LIMIT -1")
+ }
+
+ @Test
+ def testLimitWithOffset(): Unit = {
+ util.verifyPlan("SELECT a, c FROM MyTable LIMIT 10 OFFSET 1")
+ }
+
+ @Test
+ def testLimitWithOffset0(): Unit = {
+ util.verifyPlan("SELECT a, c FROM MyTable LIMIT 10 OFFSET 0")
+ }
+
+ @Test
+ def testLimit0WithOffset0(): Unit = {
+ util.verifyPlan("SELECT a, c FROM MyTable LIMIT 0 OFFSET 0")
+ }
+
+ @Test
+ def testLimit0WithOffset(): Unit = {
+ util.verifyPlan("SELECT a, c FROM MyTable LIMIT 0 OFFSET 10")
+ }
+
+ @Test(expected = classOf[SqlParserException])
+ def testLimitWithNegativeOffset(): Unit = {
+ util.verifyPlan("SELECT a, c FROM MyTable LIMIT 10 OFFSET -1")
+ }
+
+ @Test
+ def testFetchWithOffset(): Unit = {
+ util.verifyPlan("SELECT a, c FROM MyTable OFFSET 10 ROWS FETCH NEXT 10 ROWS ONLY")
+ }
+
+ @Test
+ def testFetchWithoutOffset(): Unit = {
+ util.verifyPlan("SELECT a, c FROM MyTable FETCH FIRST 10 ROWS ONLY")
+ }
+
+ @Test
+ def testFetch0WithoutOffset(): Unit = {
+ util.verifyPlan("SELECT a, c FROM MyTable FETCH FIRST 0 ROWS ONLY")
+ }
+
+ @Test
+ def testOnlyOffset(): Unit = {
+ util.verifyPlan("SELECT a, c FROM MyTable OFFSET 10 ROWS")
+ }
+
+ @Test
+ def testLimitWithRowTime(): Unit = {
+ util.verifyPlan("SELECT rowtime, c FROM MyTable LIMIT 2")
+ }
+
+ @Test
+ def testLimit0WithRowTime(): Unit = {
+ util.verifyPlan("SELECT rowtime, c FROM MyTable LIMIT 0")
+ }
+
+ @Test
+ def testOffsetWithRowTime(): Unit = {
+ util.verifyPlan("SELECT rowtime, c FROM MyTable OFFSET 2")
+ }
+
+ @Test
+ def testLimit0WithProcessingTime(): Unit = {
+ util.verifyPlan("SELECT proctime, c FROM MyTable LIMIT 0")
+ }
+
+ @Test
+ def testLimitWithProcessingTime(): Unit = {
+ util.verifyPlan("SELECT proctime, c FROM MyTable LIMIT 2")
+ }
+
+ @Test
+ def testOffsetWithProcessingTime(): Unit = {
+ util.verifyPlan("SELECT proctime, c FROM MyTable OFFSET 2")
+ }
+
+ @Test
+ def testLimit0WithRowTimeSecond(): Unit = {
+ util.verifyPlan("SELECT c, rowtime FROM MyTable LIMIT 0")
+ }
+
+ @Test
+ def testLimitWithRowTimeSecond(): Unit = {
+ util.verifyPlan("SELECT c, rowtime FROM MyTable LIMIT 2")
+ }
+
+ @Test
+ def testOffsetWithRowTimeSecond(): Unit = {
+ util.verifyPlan("SELECT c, rowtime FROM MyTable OFFSET 2")
+ }
+
+ @Test
+ def testLimit0WithProcessingTimeSecond(): Unit = {
+ util.verifyPlan("SELECT c, proctime FROM MyTable LIMIT 0")
+ }
+
+ @Test
+ def testLimitWithProcessingTimeSecond(): Unit = {
+ util.verifyPlan("SELECT c, proctime FROM MyTable LIMIT 2")
+ }
+
+ @Test
+ def testOffsetWithProcessingTimeSecond(): Unit = {
+ util.verifyPlan("SELECT c, proctime FROM MyTable OFFSET 2")
+ }
+
+ @Test
+ def testLimit0WithRowTimeDesc(): Unit = {
+ util.verifyPlan("SELECT rowtime desc, c FROM MyTable LIMIT 0")
+ }
+
+ @Test
+ def testLimitWithRowTimeDesc(): Unit = {
+ util.verifyPlan("SELECT rowtime desc, c FROM MyTable LIMIT 2")
+ }
+
+ @Test
+ def testOffsetWithRowTimeDesc(): Unit = {
+ util.verifyPlan("SELECT rowtime desc, c FROM MyTable OFFSET 2")
+ }
+
+ @Test
+ def testLimit0WithProcessingTimeDesc(): Unit = {
+ util.verifyPlan("SELECT proctime desc, c FROM MyTable LIMIT 0")
+ }
+
+ @Test
+ def testLimitWithProcessingTimeDesc(): Unit = {
+ util.verifyPlan("SELECT proctime desc, c FROM MyTable LIMIT 2")
+ }
+
+ @Test
+ def testOffsetWithProcessingTimeDesc(): Unit = {
+ util.verifyPlan("SELECT proctime desc, c FROM MyTable OFFSET 2")
+ }
+
+ @Test
+ def testLimit0WithRowTimeDescSecond(): Unit = {
+ util.verifyPlan("SELECT c, rowtime desc FROM MyTable LIMIT 0")
+ }
+
+ @Test
+ def testLimitWithRowTimeDescSecond(): Unit = {
+ util.verifyPlan("SELECT c, rowtime desc FROM MyTable LIMIT 2")
+ }
+
+ @Test
+ def testOffsetWithRowTimeDescSecond(): Unit = {
+ util.verifyPlan("SELECT c, rowtime desc FROM MyTable OFFSET 2")
+ }
+
+ @Test
+ def testLimit0WithProcessingTimeDescSecond(): Unit = {
+ util.verifyPlan("SELECT c, proctime desc FROM MyTable LIMIT 0")
+ }
+
+ @Test
+ def testLimitWithProcessingTimeDescSecond(): Unit = {
+ util.verifyPlan("SELECT c, proctime desc FROM MyTable LIMIT 2")
+ }
+
+ @Test
+ def testOffsetWithProcessingTimeDescSecond(): Unit = {
+ util.verifyPlan("SELECT c, proctime desc FROM MyTable OFFSET 2")
+ }
+}
diff --git a/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/plan/stream/sql/RankTest.scala b/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/plan/stream/sql/RankTest.scala
new file mode 100644
index 0000000..6078f79
--- /dev/null
+++ b/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/plan/stream/sql/RankTest.scala
@@ -0,0 +1,730 @@
+/*
+ * 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.{TableException, ValidationException}
+import org.apache.flink.table.util.TableTestBase
+
+import org.junit.Test
+
+class RankTest extends TableTestBase {
+
+ private val util = streamTestUtil()
+ util.addDataStream[(Int, String, Long)]("MyTable", 'a, 'b, 'c, 'proctime, 'rowtime)
+
+ @Test
+ def testRankEndMustSpecified(): Unit = {
+ val sql =
+ """
+ |SELECT *
+ |FROM (
+ | SELECT a, b, c,
+ | ROW_NUMBER() OVER (PARTITION BY a ORDER BY b DESC) as rank_num
+ | FROM MyTable)
+ |WHERE rank_num >= 10
+ """.stripMargin
+
+ thrown.expectMessage("Rank end is not specified.")
+ thrown.expect(classOf[TableException])
+ util.verifyPlan(sql)
+ }
+
+ @Test
+ def testRankEndLessThanZero(): Unit = {
+ val sql =
+ """
+ |SELECT *
+ |FROM (
+ | SELECT a, b, c,
+ | ROW_NUMBER() OVER (PARTITION BY a ORDER BY b DESC) as rank_num
+ | FROM MyTable)
+ |WHERE rank_num <= 0
+ """.stripMargin
+
+ thrown.expectMessage("Rank end should not less than zero")
+ thrown.expect(classOf[TableException])
+ util.verifyPlan(sql)
+ }
+
+ @Test
+ def testRankEndLessThan1(): Unit = {
+ val sql =
+ """
+ |SELECT *
+ |FROM (
+ | SELECT a, b, c,
+ | ROW_NUMBER() OVER (PARTITION BY a ORDER BY b DESC) as row_num
+ | FROM MyTable)
+ |WHERE row_num <= 1
+ """.stripMargin
+
+ util.verifyPlan(sql)
+ }
+
+ @Test
+ def testRankFunctionInMiddle(): Unit = {
+ val sqlQuery =
+ """
+ |SELECT * FROM (
+ | SELECT a, RANK() OVER (PARTITION BY a ORDER BY a) rk, b, c FROM MyTable) t
+ |WHERE rk < 10
+ """.stripMargin
+ util.verifyPlan(sqlQuery)
+ }
+
+ @Test
+ def testRowNumberWithRankEndLessThan1OrderByProctimeAsc(): Unit = {
+ // be converted to StreamExecDeduplicate
+ val sql =
+ """
+ |SELECT a, b, c
+ |FROM (
+ | SELECT a, b, c, proctime,
+ | ROW_NUMBER() OVER (PARTITION BY a ORDER BY proctime ASC) as row_num
+ | FROM MyTable)
+ |WHERE row_num <= 1
+ """.stripMargin
+
+ util.verifyPlan(sql)
+ }
+
+ @Test
+ def testRowNumberWithRankEndLessThan1OrderByProctimeDesc(): Unit = {
+ // be converted to StreamExecDeduplicate
+ val sql =
+ """
+ |SELECT a, b, c
+ |FROM (
+ | SELECT a, b, c, proctime,
+ | ROW_NUMBER() OVER (PARTITION BY a ORDER BY proctime DESC) as row_num
+ | FROM MyTable)
+ |WHERE row_num <= 1
+ """.stripMargin
+
+ util.verifyPlan(sql)
+ }
+
+ @Test
+ def testRowNumberWithRankEndLessThan1OrderByRowtimeAsc(): Unit = {
+ // can not be converted to StreamExecDeduplicate
+ val sql =
+ """
+ |SELECT a, b, c
+ |FROM (
+ | SELECT a, b, c, rowtime,
+ | ROW_NUMBER() OVER (PARTITION BY a ORDER BY rowtime ASC) as row_num
+ | FROM MyTable)
+ |WHERE row_num <= 1
+ """.stripMargin
+
+ util.verifyPlan(sql)
+ }
+
+ @Test
+ def testRowNumberWithRankEndLessThan1OrderByRowtimeDesc(): Unit = {
+ // can not be converted to StreamExecDeduplicate
+ val sql =
+ """
+ |SELECT a, b, c
+ |FROM (
+ | SELECT a, b, c, rowtime,
+ | ROW_NUMBER() OVER (PARTITION BY a ORDER BY rowtime DESC) as row_num
+ | FROM MyTable)
+ |WHERE row_num <= 1
+ """.stripMargin
+
+ util.verifyPlan(sql)
+ }
+
+ @Test
+ def testRankWithRankEndLessThan1OrderByProctimeAsc(): Unit = {
+ // can not be converted to StreamExecDeduplicate
+ val sql =
+ """
+ |SELECT a, b, c
+ |FROM (
+ | SELECT a, b, c, proctime,
+ | RANK() OVER (PARTITION BY a ORDER BY proctime ASC) as rk
+ | FROM MyTable)
+ |WHERE rk <= 1
+ """.stripMargin
+
+ util.verifyPlan(sql)
+ }
+
+ @Test
+ def testRankWithRankEndLessThan1OrderByProctimeDesc(): Unit = {
+ // can not be converted to StreamExecDeduplicate
+ val sql =
+ """
+ |SELECT a, b, c
+ |FROM (
+ | SELECT a, b, c, proctime,
+ | RANK() OVER (PARTITION BY a ORDER BY proctime DESC) as rk
+ | FROM MyTable)
+ |WHERE rk <= 1
+ """.stripMargin
+
+ util.verifyPlan(sql)
+ }
+
+ @Test(expected = classOf[RuntimeException])
+ def testRowNumberWithOutOrderBy(): Unit = {
+ val sql =
+ """
+ |SELECT *
+ |FROM (
+ | SELECT a, ROW_NUMBER() OVER (PARTITION BY b) as row_num
+ | FROM MyTable)
+ |WHERE row_num <= a
+ """.stripMargin
+ util.verifyPlan(sql)
+ }
+
+ @Test(expected = classOf[ValidationException])
+ def testRankWithOutOrderBy(): Unit = {
+ val sql =
+ """
+ |SELECT *
+ |FROM (
+ | SELECT a, RANK() OVER (PARTITION BY b) as rk
+ | FROM MyTable)
+ |WHERE rk <= a
+ """.stripMargin
+ util.verifyPlan(sql)
+ }
+
+ @Test(expected = classOf[ValidationException])
+ def testDenseRankWithOutOrderBy(): Unit = {
+ val sql =
+ """
+ |SELECT *
+ |FROM (
+ | SELECT a, DENSE_RANK() OVER (PARTITION BY b) as rk
+ | FROM MyTable)
+ |WHERE rk <= a
+ """.stripMargin
+ util.verifyPlan(sql)
+ }
+
+ @Test(expected = classOf[RuntimeException])
+ def testRowNumberWithMultiGroups(): Unit = {
+ val sql =
+ """
+ |SELECT *
+ |FROM (
+ | SELECT a, ROW_NUMBER() OVER (PARTITION BY b ORDER BY a) as row_num,
+ | ROW_NUMBER() OVER (PARTITION BY a) as row_num1
+ | FROM MyTable)
+ |WHERE row_num <= a
+ """.stripMargin
+ util.verifyPlan(sql)
+ }
+
+ @Test(expected = classOf[ValidationException])
+ def testRankWithMultiGroups(): Unit = {
+ val sql =
+ """
+ |SELECT *
+ |FROM (
+ | SELECT a, RANK() OVER (PARTITION BY b ORDER BY a) as rk,
+ | RANK() OVER (PARTITION BY a) as rk1
+ | FROM MyTable)
+ |WHERE rk <= a
+ """.stripMargin
+ util.verifyPlan(sql)
+ }
+
+ @Test(expected = classOf[ValidationException])
+ def testDenseRankWithMultiGroups(): Unit = {
+ val sql =
+ """
+ |SELECT *
+ |FROM (
+ | SELECT a, DENSE_RANK() OVER (PARTITION BY b ORDER BY a) as rk,
+ | DENSE_RANK() OVER (PARTITION BY a) as rk1
+ | FROM MyTable)
+ |WHERE rk <= a
+ """.stripMargin
+ util.verifyPlan(sql)
+ }
+
+ @Test
+ def testTopN(): Unit = {
+ val sql =
+ """
+ |SELECT *
+ |FROM (
+ | SELECT a, b, c,
+ | ROW_NUMBER() OVER (PARTITION BY a ORDER BY b DESC) as row_num
+ | FROM MyTable)
+ |WHERE row_num <= 10
+ """.stripMargin
+
+ util.verifyPlanWithTrait(sql)
+ }
+
+ @Test
+ def testTopN2(): Unit = {
+ // change the rank_num filter direction
+ val sql =
+ """
+ |SELECT *
+ |FROM (
+ | SELECT a, b, c,
+ | ROW_NUMBER() OVER (PARTITION BY a ORDER BY b DESC) as row_num
+ | FROM MyTable)
+ |WHERE 10 >= row_num
+ """.stripMargin
+
+ util.verifyPlanWithTrait(sql)
+ }
+
+ @Test
+ def testTopNth(): Unit = {
+ val sql =
+ """
+ |SELECT *
+ |FROM (
+ | SELECT a, b, c,
+ | ROW_NUMBER() OVER (PARTITION BY a ORDER BY b DESC) as row_num
+ | FROM MyTable)
+ |WHERE row_num = 10
+ """.stripMargin
+
+ util.verifyPlanWithTrait(sql)
+ }
+
+ @Test
+ def testTopNWithFilter(): Unit = {
+ val sql =
+ """
+ |SELECT row_num, a, c
+ |FROM (
+ | SELECT a, b, c,
+ | ROW_NUMBER() OVER (PARTITION BY a ORDER BY b DESC) as row_num
+ | FROM MyTable
+ | WHERE c > 1000)
+ |WHERE row_num <= 10 AND b IS NOT NULL
+ """.stripMargin
+
+ util.verifyPlanWithTrait(sql)
+ }
+
+ @Test(expected = classOf[TableException])
+ // FIXME remove expected exception after agg rules added
+ def testTopNAfterAgg(): Unit = {
+ val subquery =
+ """
+ |SELECT a, b, SUM(c) as sum_c
+ |FROM MyTable
+ |GROUP BY a, b
+ """.stripMargin
+
+ val sql =
+ s"""
+ |SELECT *
+ |FROM (
+ | SELECT a, b, sum_c,
+ | ROW_NUMBER() OVER (PARTITION BY b ORDER BY sum_c DESC) as row_num
+ | FROM ($subquery))
+ |WHERE row_num <= 10
+ """.stripMargin
+
+ util.verifyPlanWithTrait(sql)
+ }
+
+ @Test(expected = classOf[ValidationException])
+ // FIXME remove expected exception after LAST_VALUE added
+ def testTopNWithKeyChanged(): Unit = {
+ val subquery =
+ """
+ |SELECT a, last_value(b) as b, SUM(c) as sum_c
+ |FROM MyTable
+ |GROUP BY a
+ """.stripMargin
+
+ val sql =
+ s"""
+ |SELECT *
+ |FROM (
+ | SELECT a, b, sum_c,
+ | ROW_NUMBER() OVER (PARTITION BY b ORDER BY sum_c DESC) as row_num
+ | FROM ($subquery))
+ |WHERE row_num <= 10
+ """.stripMargin
+
+ util.verifyPlanWithTrait(sql)
+ }
+
+ @Test(expected = classOf[TableException])
+ // FIXME remove expected exception after agg rules added
+ def testUnarySortTopNOnString(): Unit = {
+ util.addTableSource[(String, Int, String)]("T", 'category, 'shopId, 'price)
+ val sql =
+ """
+ |SELECT *
+ |FROM (
+ | SELECT category, shopId, max_price,
+ | ROW_NUMBER() OVER (PARTITION BY category ORDER BY max_price ASC) as row_num
+ | FROM (
+ | SELECT category, shopId, MAX(price) as max_price
+ | FROM T
+ | GROUP BY category, shopId
+ | ))
+ |WHERE row_num <= 3
+ """.stripMargin
+
+ util.verifyPlanWithTrait(sql)
+ }
+
+ @Test(expected = classOf[TableException])
+ // FIXME remove expected exception after agg rules added
+ def testTopNOrderByCount(): Unit = {
+ val subquery =
+ """
+ |SELECT a, b, COUNT(*) as count_c
+ |FROM MyTable
+ |GROUP BY a, b
+ """.stripMargin
+
+ val sql =
+ s"""
+ |SELECT *
+ |FROM (
+ | SELECT a, b, count_c,
+ | ROW_NUMBER() OVER (PARTITION BY b ORDER BY count_c DESC) as row_num
+ | FROM ($subquery))
+ |WHERE row_num <= 10
+ """.stripMargin
+
+ val sql2 =
+ s"""
+ |SELECT max(a) FROM ($sql)
+ """.stripMargin
+
+ util.verifyPlanWithTrait(sql2)
+ }
+
+ @Test(expected = classOf[TableException])
+ // FIXME remove expected exception after agg rules added
+ def testTopNOrderBySumWithCond(): Unit = {
+ val subquery =
+ """
+ |SELECT a, b, SUM(c) AS sum_c
+ |FROM MyTable
+ |WHERE c >= 0
+ |GROUP BY a, b
+ """.stripMargin
+
+ val sql =
+ s"""
+ |SELECT *
+ |FROM (
+ | SELECT a, b, sum_c,
+ | ROW_NUMBER() OVER (PARTITION BY b ORDER BY sum_c DESC) AS row_num
+ | FROM ($subquery))
+ |WHERE row_num <= 10
+ """.stripMargin
+
+ util.verifyPlanWithTrait(sql)
+ }
+
+ @Test(expected = classOf[TableException])
+ // FIXME remove expected exception after agg rules added
+ def testTopNOrderBySumWithCaseWhen(): Unit = {
+ val subquery =
+ """
+ |SELECT a, b, SUM(CASE WHEN c > 10 THEN 1 WHEN c < 0 THEN 0 ELSE null END) AS sum_c
+ |FROM MyTable
+ |GROUP BY a, b
+ """.stripMargin
+
+ val sql =
+ s"""
+ |SELECT *
+ |FROM (
+ | SELECT a, b, sum_c,
+ | ROW_NUMBER() OVER (PARTITION BY b ORDER BY sum_c DESC) AS row_num
+ | FROM ($subquery))
+ |WHERE row_num <= 10
+ """.stripMargin
+
+ util.verifyPlan(sql)
+ }
+
+ @Test(expected = classOf[TableException])
+ // FIXME remove expected exception after IF added
+ def testTopNOrderBySumWithIf(): Unit = {
+ val subquery =
+ """
+ |SELECT a, b, SUM(IF(c > 10, 1, 0)) as sum_c
+ |FROM MyTable
+ |GROUP BY a, b
+ """.stripMargin
+
+ val sql =
+ s"""
+ |SELECT *
+ |FROM (
+ | SELECT a, b, sum_c,
+ | ROW_NUMBER() OVER (PARTITION BY b ORDER BY sum_c DESC) as row_num
+ | FROM ($subquery))
+ |WHERE row_num <= 10
+ """.stripMargin
+
+ util.verifyPlan(sql)
+ }
+
+ @Test(expected = classOf[TableException])
+ // FIXME remove expected exception after agg rules added
+ def testTopNOrderBySumWithFilterClause(): Unit = {
+ val subquery =
+ """
+ |SELECT a, b, SUM(c) filter (where c >= 0 and a < 0) as sum_c
+ |FROM MyTable
+ |GROUP BY a, b
+ """.stripMargin
+
+ val sql =
+ s"""
+ |SELECT *
+ |FROM (
+ | SELECT a, b, sum_c,
+ | ROW_NUMBER() OVER (PARTITION BY b ORDER BY sum_c DESC) AS row_num
+ | FROM ($subquery))
+ |WHERE row_num <= 10
+ """.stripMargin
+
+ util.verifyPlan(sql)
+ }
+
+ @Test(expected = classOf[TableException])
+ // FIXME remove expected exception after agg rules added
+ def testTopNOrderBySumWithFilterClause2(): Unit = {
+ val subquery =
+ """
+ |SELECT a, b, SUM(c) FILTER (WHERE c <= 0 AND a < 0) AS sum_c
+ |FROM MyTable
+ |GROUP BY a, b
+ """.stripMargin
+
+ val sql =
+ s"""
+ |SELECT *
+ |FROM (
+ | SELECT a, b, sum_c,
+ | ROW_NUMBER() OVER (PARTITION BY b ORDER BY sum_c ASC) AS row_num
+ | FROM ($subquery))
+ |WHERE row_num <= 10
+ """.stripMargin
+
+ util.verifyPlan(sql)
+ }
+
+ @Test(expected = classOf[TableException])
+ // FIXME remove expected exception after agg rules added
+ def testTopNOrderByCountAndOtherField(): Unit = {
+ val subquery =
+ """
+ |SELECT a, b, COUNT(*) AS count_c
+ |FROM MyTable
+ |GROUP BY a, b
+ """.stripMargin
+
+ val sql =
+ s"""
+ |SELECT *
+ |FROM (
+ | SELECT a, b, count_c,
+ | ROW_NUMBER() OVER (PARTITION BY b ORDER BY count_c DESC, a ASC) AS row_num
+ | FROM ($subquery))
+ |WHERE row_num <= 10
+ """.stripMargin
+
+ util.verifyPlanWithTrait(sql)
+ }
+
+ @Test(expected = classOf[TableException])
+ // FIXME remove expected exception after agg rules added
+ def testTopNWithGroupByConstantKey(): Unit = {
+ val subquery =
+ """
+ |SELECT a, b, COUNT(*) AS count_c
+ |FROM (
+ |SELECT *, 'cn' AS cn
+ |FROM MyTable
+ |)
+ |GROUP BY a, b, cn
+ """.stripMargin
+
+ val sql =
+ s"""
+ |SELECT *
+ |FROM (
+ | SELECT a, b, count_c,
+ | ROW_NUMBER() OVER (PARTITION BY a ORDER BY count_c DESC) AS row_num
+ | FROM ($subquery))
+ |WHERE row_num <= 10
+ """.stripMargin
+
+ util.verifyPlanWithTrait(sql)
+ }
+
+ @Test(expected = classOf[ValidationException])
+ // FIXME remove expected exception after INCR_SUM added
+ def testTopNOrderByIncrSum(): Unit = {
+ val subquery =
+ """
+ |SELECT a, b, incr_sum(c) as sum_c
+ |FROM MyTable
+ |GROUP BY a, b
+ """.stripMargin
+
+ val sql =
+ s"""
+ |SELECT *
+ |FROM (
+ | SELECT a, b, sum_c,
+ | ROW_NUMBER() OVER (PARTITION BY b ORDER BY sum_c DESC) AS row_num
+ | FROM ($subquery))
+ |WHERE row_num <= 10
+ """.stripMargin
+
+ util.verifyPlanWithTrait(sql)
+ }
+
+ @Test(expected = classOf[TableException])
+ // FIXME remove expected exception after agg rules added
+ def testNestedTopN(): Unit = {
+ val subquery =
+ """
+ |SELECT a, b, COUNT(*) as count_c
+ |FROM (
+ |SELECT *, 'cn' as cn
+ |FROM MyTable
+ |)
+ |GROUP BY a, b, cn
+ """.stripMargin
+
+ val subquery2 =
+ s"""
+ |SELECT *
+ |FROM (
+ | SELECT a, b, count_c,
+ | ROW_NUMBER() OVER (PARTITION BY a ORDER BY count_c DESC) AS row_num
+ | FROM ($subquery))
+ |WHERE row_num <= 10
+ """.stripMargin
+
+ val sql =
+ s"""
+ |SELECT *
+ |FROM (
+ | SELECT a, b, count_c,
+ | ROW_NUMBER() OVER (ORDER BY count_c DESC) as rank_num
+ | FROM ($subquery2))
+ |WHERE rank_num <= 10
+ """.stripMargin
+
+ util.verifyPlanWithTrait(sql)
+ }
+
+ @Test(expected = classOf[ValidationException])
+ // FIXME remove expected exception after ADD added
+ def testTopNForVariableSize(): Unit = {
+ val subquery =
+ """
+ |SELECT a, b, add(max_c) as c
+ |FROM (
+ | SELECT MAX(a) as a, b, MAX(c) as max_c
+ | FROM MyTable
+ | GROUP BY b
+ |)
+ """.stripMargin
+
+ val sql =
+ s"""
+ |SELECT *
+ |FROM (
+ | SELECT a, b, c,
+ | ROW_NUMBER() OVER (PARTITION BY b ORDER BY c DESC) as row_num
+ | FROM ($subquery))
+ |WHERE row_num <= a
+ """.stripMargin
+
+ util.verifyPlanWithTrait(sql)
+ }
+
+ @Test(expected = classOf[ValidationException])
+ // FIXME remove expected exception after INCR_SUM added
+ def testTopNWithoutRowNumber2(): Unit = {
+ util.addTableSource[(String, String, String, String, Long, String, Long, String)](
+ "stream_source",
+ 'seller_id, 'sku_id, 'venture, 'stat_date, 'trd_amt, 'trd_buyer_id, 'log_pv, 'log_visitor_id)
+
+ val group_sql =
+ """
+ |SELECT
+ | seller_id
+ | ,sku_id
+ | ,venture
+ | ,stat_date
+ | ,incr_sum(trd_amt) AS amt_dtr
+ | ,COUNT(DISTINCT trd_buyer_id) AS byr_cnt_dtr
+ | ,SUM(log_pv) AS pv_dtr
+ | ,COUNT(DISTINCT log_visitor_id) AS uv_dtr
+ |FROM stream_source
+ |GROUP BY seller_id,sku_id,venture,stat_date
+ """.stripMargin
+
+ val sql =
+ s"""
+ |SELECT
+ | CONCAT(seller_id, venture, stat_date, sku_id) as rowkey,
... 1084 lines suppressed ...