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/15 08:56:46 UTC
[flink] branch master updated: [FLINK-12168][table-planner-blink]
Support e2e limit, sortLimit, rank, union in blink batch (#8156)
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 068a0ed [FLINK-12168][table-planner-blink] Support e2e limit, sortLimit, rank, union in blink batch (#8156)
068a0ed is described below
commit 068a0ede2463db9c92e4dc097a26796bd97fbffa
Author: Jingsong Lee <lz...@aliyun.com>
AuthorDate: Mon Apr 15 16:56:34 2019 +0800
[FLINK-12168][table-planner-blink] Support e2e limit, sortLimit, rank, union in blink batch (#8156)
---
.../codegen/agg/batch/HashAggCodeGenHelper.scala | 3 +-
.../codegen/sort/ComparatorCodeGenerator.scala | 84 ++++++++++++
.../codegen/{ => sort}/SortCodeGenerator.scala | 33 +----
.../plan/nodes/physical/batch/BatchExecLimit.scala | 42 +++++-
.../plan/nodes/physical/batch/BatchExecRank.scala | 71 ++++++++++-
.../plan/nodes/physical/batch/BatchExecSort.scala | 2 +-
.../nodes/physical/batch/BatchExecSortLimit.scala | 58 ++++++++-
.../physical/batch/BatchExecSortMergeJoin.scala | 3 +-
.../plan/nodes/physical/batch/BatchExecUnion.scala | 21 ++-
.../flink/table/codegen/SortCodeGeneratorTest.java | 1 +
.../apache/flink/table/util/BaseRowTestUtil.java | 5 +
.../flink/table/runtime/batch/sql/CalcITCase.scala | 3 -
.../table/runtime/batch/sql/CorrelateITCase.scala | 1 -
.../table/runtime/batch/sql/CorrelateITCase2.scala | 4 +-
.../table/runtime/batch/sql/DecimalITCase.scala | 53 ++++++--
.../table/runtime/batch/sql/LimitITCase.scala | 120 +++++++++++++++++
.../flink/table/runtime/batch/sql/RankITCase.scala | 142 +++++++++++++++++++++
.../table/runtime/batch/sql/SortLimitITCase.scala | 129 +++++++++++++++++++
.../table/runtime/batch/sql/UnionITCase.scala | 141 ++++++++++++++++++++
.../batch/sql/agg/AggregateITCaseBase.scala | 1 -
.../table/runtime/batch/sql/join/JoinITCase.scala | 1 -
.../runtime/batch/sql/join/OuterJoinITCase.scala | 5 +-
.../flink/table/runtime/utils/BatchTestBase.scala | 26 +++-
.../flink/table/runtime/sort/LimitOperator.java | 63 +++++++++
.../flink/table/runtime/sort/RankOperator.java | 112 ++++++++++++++++
.../table/runtime/sort/SortLimitOperator.java | 110 ++++++++++++++++
26 files changed, 1167 insertions(+), 67 deletions(-)
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/codegen/agg/batch/HashAggCodeGenHelper.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/codegen/agg/batch/HashAggCodeGenHelper.scala
index 64aeb81..f968c06 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/codegen/agg/batch/HashAggCodeGenHelper.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/codegen/agg/batch/HashAggCodeGenHelper.scala
@@ -25,7 +25,8 @@ import org.apache.flink.table.`type`.{InternalType, RowType}
import org.apache.flink.table.api.TableConfig
import org.apache.flink.table.codegen.CodeGenUtils.{binaryRowFieldSetAccess, binaryRowSetNull}
import org.apache.flink.table.codegen.agg.batch.AggCodeGenHelper.buildAggregateArgsMapping
-import org.apache.flink.table.codegen.{CodeGenUtils, CodeGeneratorContext, ExprCodeGenerator, GenerateUtils, GeneratedExpression, OperatorCodeGenerator, SortCodeGenerator}
+import org.apache.flink.table.codegen.sort.SortCodeGenerator
+import org.apache.flink.table.codegen.{CodeGenUtils, CodeGeneratorContext, ExprCodeGenerator, GenerateUtils, GeneratedExpression, OperatorCodeGenerator}
import org.apache.flink.table.dataformat.{BaseRow, BinaryRow, GenericRow, JoinedRow}
import org.apache.flink.table.expressions.{CallExpression, Expression, ExpressionVisitor, FieldReferenceExpression, ResolvedAggInputReference, RexNodeConverter, SymbolExpression, TypeLiteralExpression, UnresolvedReferenceExpression, ValueLiteralExpression}
import org.apache.flink.table.functions.aggfunctions.DeclarativeAggregateFunction
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/codegen/sort/ComparatorCodeGenerator.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/codegen/sort/ComparatorCodeGenerator.scala
new file mode 100644
index 0000000..02c3778
--- /dev/null
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/codegen/sort/ComparatorCodeGenerator.scala
@@ -0,0 +1,84 @@
+/*
+ * 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.codegen.sort
+
+import org.apache.flink.table.`type`.InternalType
+import org.apache.flink.table.api.TableConfig
+import org.apache.flink.table.codegen.CodeGenUtils.{BASE_ROW, newName}
+import org.apache.flink.table.codegen.Indenter.toISC
+import org.apache.flink.table.codegen.{CodeGeneratorContext, GenerateUtils}
+import org.apache.flink.table.generated.{GeneratedRecordComparator, RecordComparator}
+
+/**
+ * A code generator for generating [[RecordComparator]].
+ */
+object ComparatorCodeGenerator {
+
+ /**
+ * Generates a [[RecordComparator]] that can be passed to a Java compiler.
+ *
+ * @param conf Table config.
+ * @param name Class name of the function.
+ * Does not need to be unique but has to be a valid Java class identifier.
+ * @param keys key positions describe which fields are keys in what order.
+ * @param keyTypes types for the key fields, in the same order as the key fields.
+ * @param orders sorting orders for the key fields.
+ * @param nullsIsLast Ordering of nulls.
+ * @return A GeneratedRecordComparator
+ */
+ def gen(
+ conf: TableConfig,
+ name: String,
+ keys: Array[Int],
+ keyTypes: Array[InternalType],
+ orders: Array[Boolean],
+ nullsIsLast: Array[Boolean]): GeneratedRecordComparator = {
+ val className = newName(name)
+ val baseClass = classOf[RecordComparator]
+
+ val ctx = new CodeGeneratorContext(conf)
+ val compareCode = GenerateUtils.generateRowCompare(
+ ctx, keys, keyTypes, orders, nullsIsLast, "o1", "o2")
+
+ val code =
+ j"""
+ public class $className implements ${baseClass.getCanonicalName} {
+
+ private final Object[] references;
+ ${ctx.reuseMemberCode()}
+
+ public $className(Object[] references) {
+ this.references = references;
+ ${ctx.reuseInitCode()}
+ ${ctx.reuseOpenCode()}
+ }
+
+ @Override
+ public int compare($BASE_ROW o1, $BASE_ROW o2) {
+ $compareCode
+ return 0;
+ }
+
+ }
+ """.stripMargin
+
+ new GeneratedRecordComparator(className, code, ctx.references.toArray)
+ }
+
+}
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/codegen/SortCodeGenerator.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/codegen/sort/SortCodeGenerator.scala
similarity index 94%
rename from flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/codegen/SortCodeGenerator.scala
rename to flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/codegen/sort/SortCodeGenerator.scala
index 0f6b2d2..a3fefe1 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/codegen/SortCodeGenerator.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/codegen/sort/SortCodeGenerator.scala
@@ -16,7 +16,7 @@
* limitations under the License.
*/
-package org.apache.flink.table.codegen
+package org.apache.flink.table.codegen.sort
import org.apache.flink.table.`type`.{DateType, DecimalType, InternalType, InternalTypes, PrimitiveType, TimeType, TimestampType}
import org.apache.flink.table.api.TableConfig
@@ -379,36 +379,7 @@ class SortCodeGenerator(
* @return A GeneratedRecordComparator
*/
def generateRecordComparator(name: String): GeneratedRecordComparator = {
- val className = newName(name)
- val baseClass = classOf[RecordComparator]
-
- val ctx = new CodeGeneratorContext(conf)
- val compareCode = GenerateUtils.generateRowCompare(
- ctx, keys, keyTypes, orders, nullsIsLast, "o1", "o2")
-
- val code =
- j"""
- public class $className implements ${baseClass.getCanonicalName} {
-
- private final Object[] references;
- ${ctx.reuseMemberCode()}
-
- public $className(Object[] references) {
- this.references = references;
- ${ctx.reuseInitCode()}
- ${ctx.reuseOpenCode()}
- }
-
- @Override
- public int compare($BASE_ROW o1, $BASE_ROW o2) {
- $compareCode
- return 0;
- }
-
- }
- """.stripMargin
-
- new GeneratedRecordComparator(className, code, ctx.references.toArray)
+ ComparatorCodeGenerator.gen(conf, name, keys, keyTypes, orders, nullsIsLast)
}
def getter(t: InternalType, index: Int): String = {
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecLimit.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecLimit.scala
index 163b6b0..7e73156 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecLimit.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecLimit.scala
@@ -17,9 +17,16 @@
*/
package org.apache.flink.table.plan.nodes.physical.batch
+import org.apache.flink.runtime.operators.DamBehavior
+import org.apache.flink.streaming.api.transformations.{OneInputTransformation, StreamTransformation}
+import org.apache.flink.table.api.BatchTableEnvironment
+import org.apache.flink.table.dataformat.BaseRow
import org.apache.flink.table.plan.cost.FlinkCost._
import org.apache.flink.table.plan.cost.FlinkCostFactory
-import org.apache.flink.table.plan.util.{FlinkRelOptUtil, RelExplainUtil}
+import org.apache.flink.table.plan.nodes.exec.{BatchExecNode, ExecNode}
+import org.apache.flink.table.plan.util.FlinkRelOptUtil
+import org.apache.flink.table.plan.util.RelExplainUtil.fetchToString
+import org.apache.flink.table.runtime.sort.LimitOperator
import org.apache.calcite.plan.{RelOptCluster, RelOptCost, RelOptPlanner, RelTraitSet}
import org.apache.calcite.rel._
@@ -27,6 +34,10 @@ import org.apache.calcite.rel.core.Sort
import org.apache.calcite.rel.metadata.RelMetadataQuery
import org.apache.calcite.rex.RexNode
+import java.util
+
+import scala.collection.JavaConversions._
+
/**
* Batch physical RelNode for [[Sort]].
*
@@ -46,7 +57,8 @@ class BatchExecLimit(
traitSet.getTrait(RelCollationTraitDef.INSTANCE),
offset,
fetch)
- with BatchPhysicalRel {
+ with BatchPhysicalRel
+ with BatchExecNode[BaseRow] {
private lazy val limitStart: Long = FlinkRelOptUtil.getLimitStart(offset)
private lazy val limitEnd: Long = FlinkRelOptUtil.getLimitEnd(offset, fetch)
@@ -63,7 +75,7 @@ class BatchExecLimit(
override def explainTerms(pw: RelWriter): RelWriter = {
pw.input("input", getInput)
.item("offset", limitStart)
- .item("fetch", RelExplainUtil.fetchToString(fetch))
+ .item("fetch", fetchToString(fetch))
.item("global", isGlobal)
}
@@ -73,4 +85,28 @@ class BatchExecLimit(
val costFactory = planner.getCostFactory.asInstanceOf[FlinkCostFactory]
costFactory.makeCost(rowCount, cpuCost, 0, 0, 0)
}
+
+ override def getDamBehavior: DamBehavior = DamBehavior.PIPELINED
+
+ override def getInputNodes: util.List[ExecNode[BatchTableEnvironment, _]] =
+ List(getInput.asInstanceOf[ExecNode[BatchTableEnvironment, _]])
+
+ override def translateToPlanInternal(
+ tableEnv: BatchTableEnvironment): StreamTransformation[BaseRow] = {
+ val input = getInputNodes.get(0).translateToPlan(tableEnv)
+ .asInstanceOf[StreamTransformation[BaseRow]]
+ val inputType = input.getOutputType
+ val operator = new LimitOperator(isGlobal, limitStart, limitEnd)
+ new OneInputTransformation(
+ input,
+ getOperatorName,
+ operator,
+ inputType,
+ if (isGlobal) 1 else input.getParallelism)
+ }
+
+ private def getOperatorName = {
+ val prefix = if (isGlobal) "Global" else "Local"
+ s"${prefix}Limit(offset: $limitStart, fetch: ${fetchToString(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 d21e975..84f05aa 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
@@ -18,11 +18,18 @@
package org.apache.flink.table.plan.nodes.physical.batch
-import org.apache.flink.table.api.TableException
+import org.apache.flink.runtime.operators.DamBehavior
+import org.apache.flink.streaming.api.transformations.{OneInputTransformation, StreamTransformation}
+import org.apache.flink.table.api.{BatchTableEnvironment, TableException}
+import org.apache.flink.table.calcite.FlinkTypeFactory
+import org.apache.flink.table.codegen.sort.ComparatorCodeGenerator
+import org.apache.flink.table.dataformat.BaseRow
import org.apache.flink.table.plan.cost.{FlinkCost, FlinkCostFactory}
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.nodes.exec.{BatchExecNode, ExecNode}
import org.apache.flink.table.plan.util.RelExplainUtil
+import org.apache.flink.table.runtime.sort.RankOperator
import org.apache.calcite.plan._
import org.apache.calcite.rel._
@@ -60,7 +67,8 @@ class BatchExecRank(
rankRange,
rankNumberType,
outputRankNumber)
- with BatchPhysicalRel {
+ with BatchPhysicalRel
+ with BatchExecNode[BaseRow] {
require(rankType == RankType.RANK, "Only RANK is supported now")
val (rankStart, rankEnd) = rankRange match {
@@ -103,4 +111,63 @@ class BatchExecRank(
val costFactory = planner.getCostFactory.asInstanceOf[FlinkCostFactory]
costFactory.makeCost(rowCount, cpuCost, 0, 0, memCost)
}
+
+ override def getDamBehavior: DamBehavior = DamBehavior.PIPELINED
+
+ override def getInputNodes: util.List[ExecNode[BatchTableEnvironment, _]] =
+ List(getInput.asInstanceOf[ExecNode[BatchTableEnvironment, _]])
+
+ override def translateToPlanInternal(
+ tableEnv: BatchTableEnvironment): StreamTransformation[BaseRow] = {
+ val input = getInputNodes.get(0).translateToPlan(tableEnv)
+ .asInstanceOf[StreamTransformation[BaseRow]]
+ val outputType = FlinkTypeFactory.toInternalRowType(getRowType)
+ val partitionBySortingKeys = partitionKey.toArray
+ // The collation for the partition-by fields is inessential here, we only use the
+ // comparator to distinguish different groups.
+ // (order[is_asc], null_is_last)
+ val partitionBySortCollation = partitionBySortingKeys.map(_ => (true, true))
+
+ // The collation for the order-by fields is inessential here, we only use the
+ // comparator to distinguish order-by fields change.
+ // (order[is_asc], null_is_last)
+ val orderByCollation = orderKey.getFieldCollations.map(_ => (true, true)).toArray
+ val orderByKeys = orderKey.getFieldCollations.map(_.getFieldIndex).toArray
+
+ val inputType = FlinkTypeFactory.toInternalRowType(getInput.getRowType)
+ //operator needn't cache data
+ val operator = new RankOperator(
+ ComparatorCodeGenerator.gen(
+ tableEnv.getConfig,
+ "PartitionByComparator",
+ partitionBySortingKeys,
+ partitionBySortingKeys.map(inputType.getTypeAt),
+ partitionBySortCollation.map(_._1),
+ partitionBySortCollation.map(_._2)),
+ ComparatorCodeGenerator.gen(
+ tableEnv.getConfig,
+ "OrderByComparator",
+ orderByKeys,
+ orderByKeys.map(inputType.getTypeAt),
+ orderByCollation.map(_._1),
+ orderByCollation.map(_._2)),
+ rankStart,
+ rankEnd,
+ outputRankNumber)
+
+ new OneInputTransformation(
+ input,
+ getOperatorName,
+ operator,
+ outputType.toTypeInfo,
+ input.getParallelism)
+ }
+
+ private def getOperatorName: String = {
+ if (isGlobal) {
+ "GlobalRank"
+ } else {
+ "LocalRank"
+ }
+ }
}
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecSort.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecSort.scala
index 7bf4385..5e9766f 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecSort.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecSort.scala
@@ -22,7 +22,7 @@ import org.apache.flink.streaming.api.operators.OneInputStreamOperator
import org.apache.flink.streaming.api.transformations.{OneInputTransformation, StreamTransformation}
import org.apache.flink.table.api.{BatchTableEnvironment, TableConfigOptions}
import org.apache.flink.table.calcite.FlinkTypeFactory
-import org.apache.flink.table.codegen.SortCodeGenerator
+import org.apache.flink.table.codegen.sort.SortCodeGenerator
import org.apache.flink.table.dataformat.BaseRow
import org.apache.flink.table.plan.cost.{FlinkCost, FlinkCostFactory}
import org.apache.flink.table.plan.nodes.exec.{BatchExecNode, ExecNode}
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecSortLimit.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecSortLimit.scala
index 6e097a7..0f04862 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecSortLimit.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecSortLimit.scala
@@ -17,8 +17,17 @@
*/
package org.apache.flink.table.plan.nodes.physical.batch
+import org.apache.flink.runtime.operators.DamBehavior
+import org.apache.flink.streaming.api.transformations.{OneInputTransformation, StreamTransformation}
+import org.apache.flink.table.`type`.TypeConverters.createInternalTypeFromTypeInfo
+import org.apache.flink.table.api.{BatchTableEnvironment, TableException}
+import org.apache.flink.table.codegen.sort.ComparatorCodeGenerator
+import org.apache.flink.table.dataformat.BaseRow
import org.apache.flink.table.plan.cost.{FlinkCost, FlinkCostFactory}
-import org.apache.flink.table.plan.util.{FlinkRelOptUtil, RelExplainUtil}
+import org.apache.flink.table.plan.nodes.exec.{BatchExecNode, ExecNode}
+import org.apache.flink.table.plan.util.{FlinkRelOptUtil, RelExplainUtil, SortUtil}
+import org.apache.flink.table.runtime.sort.SortLimitOperator
+import org.apache.flink.table.typeutils.BaseRowTypeInfo
import org.apache.calcite.plan.{RelOptCluster, RelOptCost, RelOptPlanner, RelTraitSet}
import org.apache.calcite.rel.core.Sort
@@ -26,6 +35,10 @@ import org.apache.calcite.rel.metadata.RelMetadataQuery
import org.apache.calcite.rel.{RelCollation, RelNode, RelWriter}
import org.apache.calcite.rex.{RexLiteral, RexNode}
+import java.util
+
+import scala.collection.JavaConversions._
+
/**
* Batch physical RelNode for [[Sort]].
*
@@ -44,11 +57,15 @@ class BatchExecSortLimit(
fetch: RexNode,
isGlobal: Boolean)
extends Sort(cluster, traitSet, inputRel, sortCollation, offset, fetch)
- with BatchPhysicalRel {
+ with BatchPhysicalRel
+ with BatchExecNode[BaseRow] {
private val limitStart: Long = FlinkRelOptUtil.getLimitStart(offset)
private val limitEnd: Long = FlinkRelOptUtil.getLimitEnd(offset, fetch)
+ private val (keys, orders, nullsIsLast) = SortUtil.getKeysAndOrders(
+ sortCollation.getFieldCollations)
+
override def copy(
traitSet: RelTraitSet,
newInput: RelNode,
@@ -92,4 +109,41 @@ class BatchExecSortLimit(
costFactory.makeCost(rowCount, cpuCost, 0, 0, memCost)
}
+ override def getDamBehavior: DamBehavior = DamBehavior.FULL_DAM
+
+ override def getInputNodes: util.List[ExecNode[BatchTableEnvironment, _]] =
+ List(getInput.asInstanceOf[ExecNode[BatchTableEnvironment, _]])
+
+ override def translateToPlanInternal(
+ tableEnv: BatchTableEnvironment): StreamTransformation[BaseRow] = {
+ if (limitEnd == Long.MaxValue) {
+ throw new TableException("Not support limitEnd is max value now!")
+ }
+
+ val input = getInputNodes.get(0).translateToPlan(tableEnv)
+ .asInstanceOf[StreamTransformation[BaseRow]]
+ val inputType = input.getOutputType.asInstanceOf[BaseRowTypeInfo]
+ val types = inputType.getFieldTypes.map(createInternalTypeFromTypeInfo)
+
+ // generate comparator
+ val genComparator = ComparatorCodeGenerator.gen(
+ tableEnv.getConfig, "SortLimitComparator", keys, keys.map(types(_)), orders, nullsIsLast)
+
+ // TODO If input is ordered, there is no need to use the heap.
+ val operator = new SortLimitOperator(isGlobal, limitStart, limitEnd, genComparator)
+
+ new OneInputTransformation(
+ input,
+ getOperatorName,
+ operator,
+ inputType,
+ if (isGlobal) 1 else input.getParallelism)
+ }
+
+ private def getOperatorName = {
+ s"${if (isGlobal) "Global" else "Local"}SortLimit(" +
+ s"orderBy: [${RelExplainUtil.collationToString(sortCollation, getRowType)}], " +
+ s"offset: $limitStart, " +
+ s"fetch: ${RelExplainUtil.fetchToString(fetch)})"
+ }
}
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecSortMergeJoin.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecSortMergeJoin.scala
index bfa5f12..9dc5877 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecSortMergeJoin.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecSortMergeJoin.scala
@@ -23,7 +23,8 @@ import org.apache.flink.table.`type`.{RowType, TypeConverters}
import org.apache.flink.table.api.{BatchTableEnvironment, TableConfigOptions}
import org.apache.flink.table.calcite.FlinkTypeFactory
import org.apache.flink.table.codegen.ProjectionCodeGenerator.generateProjection
-import org.apache.flink.table.codegen.{CodeGeneratorContext, SortCodeGenerator}
+import org.apache.flink.table.codegen.CodeGeneratorContext
+import org.apache.flink.table.codegen.sort.SortCodeGenerator
import org.apache.flink.table.dataformat.BaseRow
import org.apache.flink.table.plan.FlinkJoinRelType
import org.apache.flink.table.plan.cost.{FlinkCost, FlinkCostFactory}
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecUnion.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecUnion.scala
index 914884f..6800462 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecUnion.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecUnion.scala
@@ -17,6 +17,12 @@
*/
package org.apache.flink.table.plan.nodes.physical.batch
+import org.apache.flink.runtime.operators.DamBehavior
+import org.apache.flink.streaming.api.transformations.{StreamTransformation, UnionTransformation}
+import org.apache.flink.table.api.BatchTableEnvironment
+import org.apache.flink.table.dataformat.BaseRow
+import org.apache.flink.table.plan.nodes.exec.{BatchExecNode, ExecNode}
+
import org.apache.calcite.plan.{RelOptCluster, RelTraitSet}
import org.apache.calcite.rel.`type`.RelDataType
import org.apache.calcite.rel.core.{SetOp, Union}
@@ -36,7 +42,8 @@ class BatchExecUnion(
all: Boolean,
outputRowType: RelDataType)
extends Union(cluster, traitSet, inputRels, all)
- with BatchPhysicalRel {
+ with BatchPhysicalRel
+ with BatchExecNode[BaseRow] {
require(all, "Only support union all now")
@@ -51,4 +58,16 @@ class BatchExecUnion(
.item("union", getRowType.getFieldNames.mkString(", "))
}
+ override def getDamBehavior: DamBehavior = DamBehavior.PIPELINED
+
+ override def getInputNodes: util.List[ExecNode[BatchTableEnvironment, _]] =
+ getInputs.map(_.asInstanceOf[ExecNode[BatchTableEnvironment, _]])
+
+ override def translateToPlanInternal(
+ tableEnv: BatchTableEnvironment): StreamTransformation[BaseRow] = {
+ val transformations = getInputNodes.map {
+ input => input.translateToPlan(tableEnv).asInstanceOf[StreamTransformation[BaseRow]]
+ }
+ new UnionTransformation(transformations)
+ }
}
diff --git a/flink-table/flink-table-planner-blink/src/test/java/org/apache/flink/table/codegen/SortCodeGeneratorTest.java b/flink-table/flink-table-planner-blink/src/test/java/org/apache/flink/table/codegen/SortCodeGeneratorTest.java
index d5695e3..cb111cf 100644
--- a/flink-table/flink-table-planner-blink/src/test/java/org/apache/flink/table/codegen/SortCodeGeneratorTest.java
+++ b/flink-table/flink-table-planner-blink/src/test/java/org/apache/flink/table/codegen/SortCodeGeneratorTest.java
@@ -28,6 +28,7 @@ import org.apache.flink.core.memory.MemorySegment;
import org.apache.flink.core.memory.MemorySegmentFactory;
import org.apache.flink.runtime.operators.sort.QuickSort;
import org.apache.flink.table.api.TableConfig;
+import org.apache.flink.table.codegen.sort.SortCodeGenerator;
import org.apache.flink.table.dataformat.BinaryArray;
import org.apache.flink.table.dataformat.BinaryGeneric;
import org.apache.flink.table.dataformat.BinaryRow;
diff --git a/flink-table/flink-table-planner-blink/src/test/java/org/apache/flink/table/util/BaseRowTestUtil.java b/flink-table/flink-table-planner-blink/src/test/java/org/apache/flink/table/util/BaseRowTestUtil.java
index f144000..d69dcc8 100644
--- a/flink-table/flink-table-planner-blink/src/test/java/org/apache/flink/table/util/BaseRowTestUtil.java
+++ b/flink-table/flink-table-planner-blink/src/test/java/org/apache/flink/table/util/BaseRowTestUtil.java
@@ -19,6 +19,7 @@
package org.apache.flink.table.util;
import org.apache.flink.table.dataformat.BaseRow;
+import org.apache.flink.table.dataformat.BinaryWriter;
import org.apache.flink.table.dataformat.GenericRow;
import org.apache.flink.table.dataformat.TypeGetterSetters;
import org.apache.flink.table.type.InternalType;
@@ -91,4 +92,8 @@ public class BaseRowTestUtil {
}
}
+ public static void write(BinaryWriter writer, int pos, Object o, InternalType type) {
+ BinaryWriter.write(writer, pos, o, type);
+ }
+
}
diff --git a/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/runtime/batch/sql/CalcITCase.scala b/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/runtime/batch/sql/CalcITCase.scala
index 84a8ed9..2cc265f 100644
--- a/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/runtime/batch/sql/CalcITCase.scala
+++ b/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/runtime/batch/sql/CalcITCase.scala
@@ -182,7 +182,6 @@ class CalcITCase extends BatchTestBase {
data3)
}
- @Ignore // TODO support like
@Test
def testFilterOnString(): Unit = {
checkResult(
@@ -498,7 +497,6 @@ class CalcITCase extends BatchTestBase {
Seq(row("Hi")))
}
- @Ignore // TODO support substring
@Test
def testComplexInLargeValues(): Unit = {
checkResult(
@@ -578,7 +576,6 @@ class CalcITCase extends BatchTestBase {
)
}
- @Ignore // TODO support decimal with precision and scale
@Test
def testRowTypeWithDecimal(): Unit = {
val d = Decimal.castFrom(2.0002, 5, 4).toBigDecimal
diff --git a/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/runtime/batch/sql/CorrelateITCase.scala b/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/runtime/batch/sql/CorrelateITCase.scala
index 3570cd9..ebfd507 100644
--- a/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/runtime/batch/sql/CorrelateITCase.scala
+++ b/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/runtime/batch/sql/CorrelateITCase.scala
@@ -116,7 +116,6 @@ class CorrelateITCase extends BatchTestBase {
row("Anna#44", "Anna", 44)))
}
- @Ignore // TODO support substring
@Test
def testUserDefinedTableFunctionWithScalarFunction(): Unit = {
tEnv.registerFunction("func", new TableFunc1)
diff --git a/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/runtime/batch/sql/CorrelateITCase2.scala b/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/runtime/batch/sql/CorrelateITCase2.scala
index f1506f7..bedd956 100644
--- a/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/runtime/batch/sql/CorrelateITCase2.scala
+++ b/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/runtime/batch/sql/CorrelateITCase2.scala
@@ -90,7 +90,7 @@ class CorrelateITCase2 extends BatchTestBase {
)
}
- @Ignore // TODO Introduce FlinkRelMdSize to let RowSize not null
+ @Ignore
@Test
def testConstantTableFunc2(): Unit = {
tEnv.registerFunction("str_split", new StringSplit())
@@ -136,7 +136,7 @@ class CorrelateITCase2 extends BatchTestBase {
)
}
- @Ignore // TODO support substring
+ @Ignore
@Test
def testConstantTableFuncWithSubString(): Unit = {
tEnv.registerFunction("str_split", new StringSplit())
diff --git a/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/runtime/batch/sql/DecimalITCase.scala b/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/runtime/batch/sql/DecimalITCase.scala
index 613bef0..c99d8ee 100644
--- a/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/runtime/batch/sql/DecimalITCase.scala
+++ b/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/runtime/batch/sql/DecimalITCase.scala
@@ -20,6 +20,7 @@ package org.apache.flink.table.runtime.batch.sql
import org.apache.flink.api.common.typeinfo.{BasicTypeInfo, TypeInformation}
import org.apache.flink.api.java.typeutils.RowTypeInfo
+import org.apache.flink.table.api.TableConfigOptions
import org.apache.flink.table.runtime.utils.BatchTestBase.row
import org.apache.flink.table.runtime.utils.BatchTestBase
import org.apache.flink.table.typeutils.BigDecimalTypeInfo
@@ -546,7 +547,6 @@ class DecimalITCase extends BatchTestBase {
s1r(toDegrees(0.12), toRadians(0.12)))
}
- @Ignore
@Test
def testAggSum(): Unit = {
@@ -566,7 +566,6 @@ class DecimalITCase extends BatchTestBase {
s1r(null))
}
- @Ignore
@Test
def testAggAvg(): Unit = {
@@ -766,11 +765,10 @@ class DecimalITCase extends BatchTestBase {
s1r(true, true, true, true, true, true))
}
- @Ignore
@Test
- def testJoin(): Unit = {
-
- // join on equality of two numeric types
+ def testJoin1(): Unit = {
+ tEnv.getConfig.getConf.setString(
+ TableConfigOptions.SQL_EXEC_DISABLED_OPERATORS, "HashJoin, NestedLoopJoin")
checkQuery1(
Seq(DECIMAL(8, 2), DECIMAL(8, 4), INT, DOUBLE),
@@ -778,6 +776,12 @@ class DecimalITCase extends BatchTestBase {
"select count(*) from Table1 A, Table1 B where A.f0=B.f0",
Seq(LONG),
s1r(1L))
+ }
+
+ @Test
+ def testJoin2(): Unit = {
+ tEnv.getConfig.getConf.setString(
+ TableConfigOptions.SQL_EXEC_DISABLED_OPERATORS, "HashJoin, NestedLoopJoin")
checkQuery1(
Seq(DECIMAL(8, 2), DECIMAL(8, 4), INT, DOUBLE),
@@ -785,6 +789,13 @@ class DecimalITCase extends BatchTestBase {
"select count(*) from Table1 A, Table1 B where A.f0=B.f1",
Seq(LONG),
s1r(1L))
+ }
+
+ @Test
+ def testJoin3(): Unit = {
+ tEnv.getConfig.getConf.setString(
+ TableConfigOptions.SQL_EXEC_DISABLED_OPERATORS, "HashJoin, NestedLoopJoin")
+
checkQuery1(
Seq(DECIMAL(8, 2), DECIMAL(8, 4), INT, DOUBLE),
s1r(d"1", d"1", 1, 1.0),
@@ -792,18 +803,38 @@ class DecimalITCase extends BatchTestBase {
Seq(LONG),
s1r(1L))
+ }
+
+ @Test
+ def testJoin4(): Unit = {
+ tEnv.getConfig.getConf.setString(
+ TableConfigOptions.SQL_EXEC_DISABLED_OPERATORS, "HashJoin, NestedLoopJoin")
+
checkQuery1(
Seq(DECIMAL(8, 2), DECIMAL(8, 4), INT, DOUBLE),
s1r(d"1", d"1", 1, 1.0),
"select count(*) from Table1 A, Table1 B where A.f0=B.f2",
Seq(LONG),
s1r(1L))
+ }
+
+ @Test
+ def testJoin5(): Unit = {
+ tEnv.getConfig.getConf.setString(
+ TableConfigOptions.SQL_EXEC_DISABLED_OPERATORS, "HashJoin, NestedLoopJoin")
+
checkQuery1(
Seq(DECIMAL(8, 2), DECIMAL(8, 4), INT, DOUBLE),
s1r(d"1", d"1", 1, 1.0),
"select count(*) from Table1 A, Table1 B where A.f2=B.f0",
Seq(LONG),
s1r(1L))
+ }
+
+ @Test
+ def testJoin6(): Unit = {
+ tEnv.getConfig.getConf.setString(
+ TableConfigOptions.SQL_EXEC_DISABLED_OPERATORS, "HashJoin, NestedLoopJoin")
checkQuery1(
Seq(DECIMAL(8, 2), DECIMAL(8, 4), INT, DOUBLE),
@@ -811,6 +842,12 @@ class DecimalITCase extends BatchTestBase {
"select count(*) from Table1 A, Table1 B where A.f0=B.f3",
Seq(LONG),
s1r(1L))
+ }
+
+ @Test
+ def testJoin7(): Unit = {
+ tEnv.getConfig.getConf.setString(
+ TableConfigOptions.SQL_EXEC_DISABLED_OPERATORS, "HashJoin, NestedLoopJoin")
checkQuery1(
Seq(DECIMAL(8, 2), DECIMAL(8, 4), INT, DOUBLE),
s1r(d"1", d"1", 1, 1.0),
@@ -830,9 +867,9 @@ class DecimalITCase extends BatchTestBase {
Seq(row(2L), row(1L), row(1L)))
}
- @Ignore
@Test
def testOrderBy(): Unit = {
+ env.setParallelism(1) // set sink parallelism to 1
checkQuery1(
Seq(DECIMAL(8, 2)),
Seq(row(d"1"), row(d"3"), row(d"1.0"), row(d"2")),
@@ -842,7 +879,6 @@ class DecimalITCase extends BatchTestBase {
isSorted = true)
}
- @Ignore
@Test
def testSimpleNull(): Unit = {
checkQuery1(
@@ -874,7 +910,6 @@ class DecimalITCase extends BatchTestBase {
s1r(d"100.000", d"100.000000", d"1${10}"))
}
- @Ignore
@Test
def testAggMinGroupBy(): Unit = {
diff --git a/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/runtime/batch/sql/LimitITCase.scala b/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/runtime/batch/sql/LimitITCase.scala
new file mode 100644
index 0000000..ef7ce80
--- /dev/null
+++ b/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/runtime/batch/sql/LimitITCase.scala
@@ -0,0 +1,120 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.table.runtime.batch.sql
+
+import org.apache.flink.table.api.TableConfigOptions
+import org.apache.flink.table.runtime.utils.BatchTestBase
+import org.apache.flink.table.runtime.utils.TestData._
+
+import org.junit._
+
+class LimitITCase extends BatchTestBase {
+
+ @Before
+ def before(): Unit = {
+ tEnv.getConfig.getConf.setInteger(TableConfigOptions.SQL_RESOURCE_DEFAULT_PARALLELISM, 3)
+ registerCollection("Table3", data3, type3, nullablesOfData3, "a, b, c")
+
+ // TODO support LimitableTableSource
+// val rowType = new RowTypeInfo(type3.getFieldTypes, Array("a", "b", "c"))
+// tEnv.registerTableSource("LimitTable", new TestLimitableTableSource(data3, rowType))
+ }
+
+ @Test
+ def testOffsetAndFetch(): Unit = {
+ checkSize(
+ "SELECT * FROM Table3 OFFSET 2 ROWS FETCH NEXT 5 ROWS ONLY",
+ 5)
+ }
+
+ @Test
+ def testOffsetAndLimit(): Unit = {
+ checkSize(
+ "SELECT * FROM Table3 LIMIT 10 OFFSET 2",
+ 10)
+ }
+
+ @Test
+ def testFetch(): Unit = {
+ checkSize(
+ "SELECT * FROM Table3 FETCH NEXT 10 ROWS ONLY",
+ 10)
+ }
+
+ @Ignore
+ @Test
+ def testFetchWithLimitTable(): Unit = {
+ checkSize(
+ "SELECT * FROM LimitTable FETCH NEXT 10 ROWS ONLY",
+ 10)
+ }
+
+ @Test
+ def testFetchFirst(): Unit = {
+ checkSize(
+ "SELECT * FROM Table3 FETCH FIRST 10 ROWS ONLY",
+ 10)
+ }
+
+ @Ignore
+ @Test
+ def testFetchFirstWithLimitTable(): Unit = {
+ checkSize(
+ "SELECT * FROM LimitTable FETCH FIRST 10 ROWS ONLY",
+ 10)
+ }
+
+ @Test
+ def testLimit(): Unit = {
+ checkSize(
+ "SELECT * FROM Table3 LIMIT 5",
+ 5)
+ }
+
+ @Ignore
+ @Test
+ def testLimitWithLimitTable(): Unit = {
+ checkSize(
+ "SELECT * FROM LimitTable LIMIT 5",
+ 5)
+ }
+
+ @Ignore
+ @Test
+ def testTableLimitWithLimitTable(): Unit = {
+ Assert.assertEquals(
+ executeQuery(tEnv.scan("LimitTable").fetch(5)).size,
+ 5)
+ }
+
+ @Test
+ def testLessThanOffset(): Unit = {
+ checkSize(
+ "SELECT * FROM Table3 OFFSET 2 ROWS FETCH NEXT 50 ROWS ONLY",
+ 19)
+ }
+
+ @Ignore
+ @Test(expected = classOf[AssertionError])
+ def testLessThanOffsetWithLimitSource(): Unit = {
+ checkSize(
+ "SELECT * FROM LimitTable OFFSET 2 ROWS FETCH NEXT 50 ROWS ONLY",
+ 19)
+ }
+}
diff --git a/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/runtime/batch/sql/RankITCase.scala b/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/runtime/batch/sql/RankITCase.scala
new file mode 100644
index 0000000..2d529f4
--- /dev/null
+++ b/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/runtime/batch/sql/RankITCase.scala
@@ -0,0 +1,142 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.table.runtime.batch.sql
+
+import org.apache.flink.table.api.TableConfigOptions
+import org.apache.flink.table.runtime.utils.BatchTestBase
+import org.apache.flink.table.runtime.utils.BatchTestBase.row
+import org.apache.flink.table.runtime.utils.TestData._
+
+import org.junit._
+
+import scala.collection.Seq
+
+class RankITCase extends BatchTestBase {
+
+ @Before
+ def before(): Unit = {
+ tEnv.getConfig.getConf.setInteger(TableConfigOptions.SQL_RESOURCE_DEFAULT_PARALLELISM, 3)
+ registerCollection("Table3", data3, type3, nullablesOfData3, "a, b, c")
+ registerCollection("Table5", data5, type5, nullablesOfData5, "a, b, c, d, e")
+ registerCollection("Table2", data2_1, INT_DOUBLE, "a, b")
+ }
+
+ @Test
+ def testRankValueFilterWithUpperValue(): Unit = {
+ checkResult(
+ "SELECT * FROM (" +
+ "SELECT a, b, RANK() OVER (PARTITION BY b ORDER BY a) rk FROM Table3) t " +
+ "WHERE rk <= 2",
+ Seq(row(1, 1, 1), row(2, 2, 1), row(3, 2, 2), row(4, 3, 1), row(5, 3, 2), row(7, 4, 1),
+ row(8, 4, 2), row(11, 5, 1), row(12, 5, 2), row(16, 6, 1), row(17, 6, 2)))
+
+ checkResult(
+ "SELECT * FROM (" +
+ "SELECT a, b, RANK() OVER (PARTITION BY a ORDER BY e) rk FROM Table5) t " +
+ "WHERE rk <= 3",
+ Seq(row(1, 1, 1), row(2, 3, 1), row(2, 2, 2), row(3, 4, 1), row(3, 5, 1), row(3, 6, 3),
+ row(4, 8, 1), row(4, 9, 1), row(4, 7, 3), row(4, 10, 3),
+ row(5, 11, 1), row(5, 14, 2), row(5, 15, 2)))
+
+ checkResult(
+ "SELECT * FROM (" +
+ "SELECT a, b, RANK() OVER (PARTITION BY a ORDER BY b DESC) rk FROM Table2) t " +
+ "WHERE rk <= 2",
+ Seq(row(1, 2.0, 1), row(1, 2.0, 1), row(2, 1.0, 1), row(2, 1.0, 1), row(3, 3.0, 1),
+ row(6, null, 1), row(null, 5.0, 1), row(null, null, 2)))
+ }
+
+ @Test
+ def testRankValueFilterWithRange(): Unit = {
+ checkResult(
+ "SELECT * FROM (" +
+ "SELECT a, b, RANK() OVER (PARTITION BY b ORDER BY a) rk FROM Table3) t " +
+ "WHERE rk <= 4 and rk > 1",
+ Seq(row(3, 2, 2), row(5, 3, 2), row(6, 3, 3), row(8, 4, 2), row(9, 4, 3), row(10, 4, 4),
+ row(12, 5, 2), row(13, 5, 3), row(14, 5, 4), row(17, 6, 2), row(18, 6, 3), row(19, 6, 4)))
+
+ checkResult(
+ "SELECT a, b FROM (" +
+ "SELECT a, b, RANK() OVER (PARTITION BY b ORDER BY a) rk FROM Table3) t " +
+ "WHERE rk <= 3 and rk > -2",
+ Seq(row(1, 1), row(2, 2), row(3, 2), row(4, 3), row(5, 3), row(6, 3), row(7, 4), row(8, 4),
+ row(9, 4), row(11, 5), row(12, 5), row(13, 5), row(16, 6), row(17, 6), row(18, 6)))
+
+ checkResult(
+ "SELECT * FROM (" +
+ "SELECT a, b, RANK() OVER (PARTITION BY a ORDER BY e) rk FROM Table5) t " +
+ "WHERE rk <= 3 and rk >= 2",
+ Seq(row(2, 2, 2), row(3, 6, 3), row(4, 7, 3), row(4, 10, 3), row(5, 14, 2), row(5, 15, 2)))
+ }
+
+ @Ignore
+ @Test
+ def testRankValueFilterWithLowerValue(): Unit = {
+ checkResult("SELECT * FROM (" +
+ "SELECT a, b, RANK() OVER (PARTITION BY b ORDER BY a, c) rk FROM Table3) t " +
+ "WHERE rk > 2",
+ Seq(row(6, 3, 3), row(9, 4, 3), row(10, 4, 4), row(13, 5, 3), row(14, 5, 4), row(15, 5, 5),
+ row(18, 6, 3), row(19, 6, 4), row(20, 6, 5), row(21, 6, 6)))
+
+ checkResult("SELECT * FROM (" +
+ "SELECT a, b, RANK() OVER (PARTITION BY a ORDER BY e) rk FROM Table5) t " +
+ "WHERE rk > 2",
+ Seq(row(3, 6, 3), row(4, 10, 3), row(4, 7, 3), row(5, 12, 4), row(5, 13, 4)))
+ }
+
+ @Test
+ def testRankValueFilterWithEquals(): Unit = {
+ checkResult("SELECT * FROM (" +
+ "SELECT a, b, RANK() OVER (PARTITION BY b ORDER BY a, c) rk FROM Table3) t " +
+ "WHERE rk = 2",
+ Seq(row(3, 2, 2), row(5, 3, 2), row(8, 4, 2), row(12, 5, 2), row(17, 6, 2)))
+ }
+
+ @Test
+ def testWithoutPartitionBy(): Unit = {
+ checkResult("SELECT * FROM (" +
+ "SELECT a, b, RANK() OVER (ORDER BY a) rk FROM Table3) t " +
+ "WHERE rk < 5",
+ Seq(row(1, 1, 1), row(2, 2, 2), row(3, 2, 3), row(4, 3, 4)))
+
+ checkResult("SELECT a, b FROM (" +
+ "SELECT a, b, RANK() OVER (ORDER BY e DESC) rk FROM Table5) t " +
+ "WHERE rk < 5 and a > 2",
+ Seq(row(3, 6), row(5, 12), row(5, 13), row(3, 4), row(3, 5), row(4, 7),
+ row(4, 10), row(5, 14), row(5, 15)))
+
+ checkResult("SELECT * FROM (" +
+ "SELECT a, b, RANK() OVER (ORDER BY a DESC) rk FROM Table2) t " +
+ "WHERE rk < 5",
+ Seq(row(6, null, 1), row(3, 3.0, 2), row(2, 1.0, 3), row(2, 1.0, 3)))
+ }
+
+ @Test
+ def testMultiSameRankFunctionsWithSameGroup(): Unit = {
+ checkResult("SELECT * FROM (" +
+ "SELECT a, b, " +
+ "RANK() OVER (PARTITION BY b ORDER BY a) rk1, " +
+ "RANK() OVER (PARTITION BY b ORDER BY a) rk2 FROM Table3) t " +
+ "WHERE rk1 < 3",
+ Seq(row(1, 1, 1, 1), row(2, 2, 1, 1), row(3, 2, 2, 2), row(4, 3, 1, 1),
+ row(5, 3, 2, 2), row(7, 4, 1, 1), row(8, 4, 2, 2), row(11, 5, 1, 1),
+ row(12, 5, 2, 2), row(16, 6, 1, 1), row(17, 6, 2, 2)))
+ }
+
+}
diff --git a/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/runtime/batch/sql/SortLimitITCase.scala b/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/runtime/batch/sql/SortLimitITCase.scala
new file mode 100644
index 0000000..6d51d21
--- /dev/null
+++ b/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/runtime/batch/sql/SortLimitITCase.scala
@@ -0,0 +1,129 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.table.runtime.batch.sql
+
+import org.apache.flink.table.api.TableConfigOptions
+import org.apache.flink.table.runtime.utils.BatchTestBase
+import org.apache.flink.table.runtime.utils.TestData._
+import org.apache.flink.types.Row
+
+import org.junit._
+
+class SortLimitITCase extends BatchTestBase {
+
+ @Before
+ def before(): Unit = {
+ tEnv.getConfig.getConf.setInteger(TableConfigOptions.SQL_RESOURCE_DEFAULT_PARALLELISM, 3)
+ env.setParallelism(1) // set sink parallelism to 1
+ registerCollection("Table3", data3, type3, "a, b, c")
+ }
+
+ @Test
+ def testOrderByWithOffsetAndFetch(): Unit = {
+ testOrderByWithOffsetAndFetch(true)
+ testOrderByWithOffsetAndFetch(false)
+ }
+
+ private def testOrderByWithOffsetAndFetch(order: Boolean): Unit = {
+
+ val sqlOrder = if (order) "ASC" else "DESC"
+
+ val expected = data3.sortBy((x : Row) =>
+ if (order) x.getField(0).asInstanceOf[Int]
+ else -x.getField(0).asInstanceOf[Int]).slice(2, 7)
+
+ checkResult(
+ s"SELECT * FROM Table3 ORDER BY a $sqlOrder OFFSET 2 ROWS FETCH NEXT 5 ROWS ONLY",
+ expected,
+ isSorted = true)
+ }
+
+ @Test
+ def testOrderByLimit(): Unit = {
+ testOrderByLimit(order1 = true, order2 = false)
+ testOrderByLimit(order1 = false, order2 = false)
+ testOrderByLimit(order1 = true, order2 = true)
+ testOrderByLimit(order1 = false, order2 = true)
+ }
+
+ private def testOrderByLimit(order1: Boolean, order2: Boolean): Unit = {
+
+ val sqlOrder1 = if (order1) "ASC" else "DESC"
+ val sqlOrder2 = if (order2) "ASC" else "DESC"
+
+ val expected = data3.sortBy((x : Row) => (
+ if (order2) {
+ x.getField(1).asInstanceOf[Long]
+ } else {
+ -x.getField(1).asInstanceOf[Long]
+ },
+ if (order1) {
+ x.getField(0).asInstanceOf[Int]
+ } else {
+ -x.getField(0).asInstanceOf[Int]
+ })).slice(0, 5)
+
+ checkResult(
+ s"SELECT * FROM Table3 ORDER BY b $sqlOrder2, a $sqlOrder1 LIMIT 5",
+ expected,
+ isSorted = true)
+ }
+
+ @Test
+ def testOrderByLessThanOffset(): Unit = {
+
+ val expected = data3.sortBy((x : Row) =>
+ x.getField(0).asInstanceOf[Int]).slice(2, data3.size)
+
+ checkResult(
+ s"SELECT * FROM Table3 ORDER BY a ASC OFFSET 2 ROWS FETCH NEXT 50 ROWS ONLY",
+ expected,
+ isSorted = true)
+ }
+
+ @Test
+ def testOrderByLimitBehindField(): Unit = {
+ val expected = data3.sortBy((x : Row) => x.getField(2).asInstanceOf[String]).slice(0, 5)
+
+ checkResult(
+ s"SELECT * FROM Table3 ORDER BY c LIMIT 5",
+ expected,
+ isSorted = true)
+ }
+
+ @Test
+ def testOrderBehindField(): Unit = {
+ tEnv.getConfig.getConf.setInteger(TableConfigOptions.SQL_RESOURCE_DEFAULT_PARALLELISM, 1)
+ val expected = data3.sortBy((x : Row) => x.getField(2).asInstanceOf[String])
+
+ checkResult(
+ s"SELECT * FROM Table3 ORDER BY c",
+ expected,
+ isSorted = true)
+ }
+
+ @Test
+ def testOrderByRepeatedFields(): Unit = {
+ val expected = data3.sortBy((x : Row) => x.getField(0).asInstanceOf[Int]).slice(0, 5)
+ checkResult(
+ s"SELECT * FROM Table3 ORDER BY a, a, a LIMIT 5",
+ expected,
+ isSorted = true)
+ }
+}
diff --git a/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/runtime/batch/sql/UnionITCase.scala b/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/runtime/batch/sql/UnionITCase.scala
new file mode 100644
index 0000000..874a132
--- /dev/null
+++ b/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/runtime/batch/sql/UnionITCase.scala
@@ -0,0 +1,141 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.table.runtime.batch.sql
+
+import org.apache.flink.api.common.typeinfo.BasicTypeInfo.{INT_TYPE_INFO, LONG_TYPE_INFO, STRING_TYPE_INFO}
+import org.apache.flink.table.`type`.InternalTypes
+import org.apache.flink.table.api.{PlannerConfigOptions, TableConfigOptions}
+import org.apache.flink.table.dataformat.BinaryString.fromString
+import org.apache.flink.table.runtime.utils.BatchTestBase
+import org.apache.flink.table.runtime.utils.BatchTestBase.{binaryRow, row}
+import org.apache.flink.table.runtime.utils.TestData._
+import org.apache.flink.table.typeutils.BaseRowTypeInfo
+
+import org.junit._
+
+import scala.collection.Seq
+
+class UnionITCase extends BatchTestBase {
+
+ val type6 = new BaseRowTypeInfo(
+ InternalTypes.INT, InternalTypes.LONG, InternalTypes.STRING)
+
+ val data6 = Seq(
+ binaryRow(type6.getInternalTypes, 1, 1L, fromString("Hi")),
+ binaryRow(type6.getInternalTypes, 2, 2L, fromString("Hello")),
+ binaryRow(type6.getInternalTypes, 3, 2L, fromString("Hello world")),
+ binaryRow(type6.getInternalTypes, 4, 3L, fromString("Hello world, how are you?"))
+ )
+
+ @Before
+ def before(): Unit = {
+ tEnv.getConfig.getConf.setInteger(TableConfigOptions.SQL_RESOURCE_DEFAULT_PARALLELISM, 3)
+ registerCollection("Table3", smallData3, type3, nullablesOfSmallData3, "a, b, c")
+ registerCollection("Table5", data5, type5, nullablesOfData5, "d, e, f, g, h")
+ registerCollection("Table6", data6, type6, Array(false, false, false), "a, b, c")
+ tEnv.getConfig.getConf.setString(
+ TableConfigOptions.SQL_EXEC_DISABLED_OPERATORS, "HashAgg")
+ }
+
+ @Test
+ def testUnionWithDifferentRowtype(): Unit = {
+ checkResult(
+ "SELECT a FROM (SELECT * FROM Table3 t1 UNION ALL (SELECT * FROM Table6 t2))",
+ Seq(
+ row("1"),
+ row("1"),
+ row("2"),
+ row("2"),
+ row("3"),
+ row("3"),
+ row("4")))
+ }
+
+ @Test
+ def testUnionAll(): Unit = {
+ checkResult(
+ "SELECT t1.c FROM Table3 t1 UNION ALL (SELECT t2.c FROM Table3 t2)",
+ Seq(
+ row("Hi"),
+ row("Hi"),
+ row("Hello"),
+ row("Hello"),
+ row("Hello world"),
+ row("Hello world")))
+ }
+
+ @Test
+ def testUnion(): Unit = {
+ checkResult(
+ "SELECT t1.c FROM Table3 t1 UNION (SELECT t2.c FROM Table3 t2)",
+ Seq(
+ row("Hi"),
+ row("Hello"),
+ row("Hello world")))
+ }
+
+ @Test
+ def testUnionWithFilter(): Unit = {
+ checkResult(
+ "SELECT c FROM (" +
+ "SELECT * FROM Table3 UNION ALL (SELECT d, e, g FROM Table5))" +
+ "WHERE b < 2",
+ Seq(
+ row("Hi"),
+ row("Hallo")))
+ }
+
+ @Test
+ def testUnionWithAggregation(): Unit = {
+ checkResult(
+ "SELECT count(c) FROM (" +
+ "SELECT * FROM Table3 UNION ALL (SELECT d, e, g FROM Table5))",
+ Seq(row(18)))
+ }
+
+ /**
+ * Test different types of two union inputs(One is GenericRow, the other is BinaryRow).
+ */
+ @Test
+ def testJoinAfterDifferentTypeUnionAll(): Unit = {
+ tEnv.getConfig.getConf.setLong(
+ PlannerConfigOptions.SQL_OPTIMIZER_HASH_JOIN_BROADCAST_THRESHOLD, -1)
+ tEnv.getConfig.getConf.setString(
+ TableConfigOptions.SQL_EXEC_DISABLED_OPERATORS, "HashJoin, NestedLoopJoin")
+ checkResult(
+ "SELECT a, c, g FROM (SELECT t1.a, t1.b, t1.c FROM Table3 t1 UNION ALL" +
+ "(SELECT a, b, c FROM Table3 ORDER BY a, b, c)), Table5 WHERE b = e",
+ Seq(
+ row(1, "Hi", "Hallo"),
+ row(1, "Hi", "Hallo"),
+ row(2, "Hello", "Hallo Welt"),
+ row(2, "Hello", "Hallo Welt"),
+ row(3, "Hello world", "Hallo Welt"),
+ row(3, "Hello world", "Hallo Welt")
+ ))
+ }
+
+ @Test
+ def testUnionOfMultiInputs(): Unit = {
+ checkResult(
+ "select max(v) as x, min(v) as n from \n" +
+ "(values cast(-86.4 as double), cast(-100 as double), cast(2 as double)) as t(v)",
+ Seq(row(2.0, -100.0)))
+ }
+}
diff --git a/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/runtime/batch/sql/agg/AggregateITCaseBase.scala b/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/runtime/batch/sql/agg/AggregateITCaseBase.scala
index f3318a3..1ed9623 100644
--- a/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/runtime/batch/sql/agg/AggregateITCaseBase.scala
+++ b/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/runtime/batch/sql/agg/AggregateITCaseBase.scala
@@ -836,7 +836,6 @@ abstract class AggregateITCaseBase(testName: String) extends BatchTestBase {
)
}
- @Ignore
@Test
def testLimitPlusAgg(): Unit = {
checkQuery(
diff --git a/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/runtime/batch/sql/join/JoinITCase.scala b/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/runtime/batch/sql/join/JoinITCase.scala
index 0b63b03..8db382b 100644
--- a/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/runtime/batch/sql/join/JoinITCase.scala
+++ b/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/runtime/batch/sql/join/JoinITCase.scala
@@ -485,7 +485,6 @@ class JoinITCase() extends BatchTestBase with JoinITCaseBase {
}
// join with agg
- @Ignore
@Test
def testJoinWithAggregation(): Unit = {
checkResult(
diff --git a/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/runtime/batch/sql/join/OuterJoinITCase.scala b/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/runtime/batch/sql/join/OuterJoinITCase.scala
index bd59f5e..b21f322 100644
--- a/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/runtime/batch/sql/join/OuterJoinITCase.scala
+++ b/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/runtime/batch/sql/join/OuterJoinITCase.scala
@@ -24,7 +24,7 @@ import org.apache.flink.table.runtime.utils.BatchTestBase
import org.apache.flink.table.runtime.utils.BatchTestBase.row
import org.apache.flink.table.runtime.utils.TestData._
-import org.junit.{Before, Ignore, Test}
+import org.junit.{Before, Test}
import scala.collection.Seq
@@ -198,7 +198,6 @@ class OuterJoinITCase extends BatchTestBase with JoinITCaseBase {
row(6, "F", null, null) :: Nil)
}
- @Ignore
@Test
def testLeftUpperAndLowerWithAgg(): Unit = {
checkResult(
@@ -262,7 +261,6 @@ class OuterJoinITCase extends BatchTestBase with JoinITCaseBase {
}
- @Ignore
@Test
def testRightUpperAndLowerWithAgg(): Unit = {
checkResult(
@@ -330,7 +328,6 @@ class OuterJoinITCase extends BatchTestBase with JoinITCaseBase {
}
}
- @Ignore
@Test
def testFullUpperAndLowerWithAgg(): Unit = {
if (expectedJoinType != NestedLoopJoin && expectedJoinType != BroadcastHashJoin) {
diff --git a/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/runtime/utils/BatchTestBase.scala b/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/runtime/utils/BatchTestBase.scala
index 175c659..b570a7a 100644
--- a/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/runtime/utils/BatchTestBase.scala
+++ b/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/runtime/utils/BatchTestBase.scala
@@ -23,12 +23,14 @@ import org.apache.flink.api.java.tuple.Tuple
import org.apache.flink.configuration.Configuration
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment
import org.apache.flink.streaming.api.scala.{StreamExecutionEnvironment => ScalaExecEnv}
+import org.apache.flink.table.`type`.InternalType
import org.apache.flink.table.api.java.{BatchTableEnvironment => JavaBatchTableEnv}
import org.apache.flink.table.api.scala.{BatchTableEnvironment => ScalaBatchTableEnv}
import org.apache.flink.table.api.{SqlParserException, Table, TableConfig, TableConfigOptions, TableEnvironment, TableImpl}
import org.apache.flink.table.functions.AggregateFunction
+import org.apache.flink.table.dataformat.{BinaryRow, BinaryRowWriter}
import org.apache.flink.table.plan.util.FlinkRelOptUtil
-import org.apache.flink.table.util.DiffRepository
+import org.apache.flink.table.util.{BaseRowTestUtil, DiffRepository}
import org.apache.flink.test.util.AbstractTestBase
import org.apache.flink.types.Row
@@ -382,10 +384,10 @@ class BatchTestBase extends AbstractTestBase {
BatchTableEnvUtil.registerCollection(tEnv, tableName, data.asScala, typeInfo, fields)
}
- def registerCollection(
+ def registerCollection[T](
tableName: String,
- data: Iterable[Row],
- typeInfo: TypeInformation[Row],
+ data: Iterable[T],
+ typeInfo: TypeInformation[T],
fieldNullables: Array[Boolean],
fields: String): Unit = {
BatchTableEnvUtil.registerCollection(tEnv, tableName, data, typeInfo, fields, fieldNullables)
@@ -422,6 +424,22 @@ object BatchTestBase {
row
}
+ def binaryRow(types: Array[InternalType], fields: Any*): BinaryRow = {
+ assertEquals(
+ "Filed count inconsistent with type information",
+ fields.length,
+ types.length)
+ val row = new BinaryRow(fields.length)
+ val writer = new BinaryRowWriter(row)
+ writer.reset()
+ fields.zipWithIndex.foreach { case (field, index) =>
+ if (field == null) writer.setNullAt(index)
+ else BaseRowTestUtil.write(writer, index, field, types(index))
+ }
+ writer.complete()
+ row
+ }
+
def initConfigForTest(conf: TableConfig): TableConfig = {
// TODO prepare for some resource config
conf.getConf.setInteger(TableConfigOptions.SQL_RESOURCE_DEFAULT_PARALLELISM, PARALLELISM)
diff --git a/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/sort/LimitOperator.java b/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/sort/LimitOperator.java
new file mode 100644
index 0000000..3b61c2a
--- /dev/null
+++ b/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/sort/LimitOperator.java
@@ -0,0 +1,63 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.table.runtime.sort;
+
+import org.apache.flink.streaming.api.operators.OneInputStreamOperator;
+import org.apache.flink.streaming.runtime.streamrecord.StreamRecord;
+import org.apache.flink.table.dataformat.BaseRow;
+import org.apache.flink.table.runtime.TableStreamOperator;
+import org.apache.flink.table.runtime.util.StreamRecordCollector;
+import org.apache.flink.util.Collector;
+
+/**
+ * Operator for limit.
+ * TODO support stopEarly.
+ */
+public class LimitOperator extends TableStreamOperator<BaseRow>
+ implements OneInputStreamOperator<BaseRow, BaseRow> {
+
+ private final boolean isGlobal;
+ private final long limitStart;
+ private final long limitEnd;
+
+ private transient Collector<BaseRow> collector;
+ private transient int count = 0;
+
+ public LimitOperator(boolean isGlobal, long limitStart, long limitEnd) {
+ this.isGlobal = isGlobal;
+ this.limitStart = limitStart;
+ this.limitEnd = limitEnd;
+ }
+
+ @Override
+ public void open() throws Exception {
+ super.open();
+ this.collector = new StreamRecordCollector<>(output);
+ }
+
+ @Override
+ public void processElement(StreamRecord<BaseRow> element) throws Exception {
+ if (count < limitEnd) {
+ count++;
+ if (!isGlobal || count > limitStart) {
+ collector.collect(element.getValue());
+ }
+ }
+ }
+}
diff --git a/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/sort/RankOperator.java b/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/sort/RankOperator.java
new file mode 100644
index 0000000..d43497e
--- /dev/null
+++ b/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/sort/RankOperator.java
@@ -0,0 +1,112 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.table.runtime.sort;
+
+import org.apache.flink.streaming.api.operators.OneInputStreamOperator;
+import org.apache.flink.streaming.runtime.streamrecord.StreamRecord;
+import org.apache.flink.table.dataformat.BaseRow;
+import org.apache.flink.table.dataformat.GenericRow;
+import org.apache.flink.table.dataformat.JoinedRow;
+import org.apache.flink.table.generated.GeneratedRecordComparator;
+import org.apache.flink.table.generated.RecordComparator;
+import org.apache.flink.table.runtime.TableStreamOperator;
+import org.apache.flink.table.runtime.util.StreamRecordCollector;
+import org.apache.flink.table.typeutils.AbstractRowSerializer;
+
+/**
+ * Rank operator to compute top N.
+ */
+public class RankOperator extends TableStreamOperator<BaseRow> implements OneInputStreamOperator<BaseRow, BaseRow> {
+
+ private GeneratedRecordComparator partitionByGenComp;
+ private GeneratedRecordComparator orderByGenComp;
+ private final long rankStart;
+ private final long rankEnd;
+ private final boolean outputRankFunColumn;
+
+ private transient RecordComparator partitionByComp;
+ private transient RecordComparator orderByComp;
+ private transient long rowNum;
+ private transient long rank;
+ private transient GenericRow rankValueRow;
+ private transient JoinedRow joinedRow;
+ private transient BaseRow lastInput;
+ private transient StreamRecordCollector<BaseRow> collector;
+ private transient AbstractRowSerializer<BaseRow> inputSer;
+
+ public RankOperator(
+ GeneratedRecordComparator partitionByGenComp, GeneratedRecordComparator orderByGenComp,
+ long rankStart, long rankEnd, boolean outputRankFunColumn) {
+ this.partitionByGenComp = partitionByGenComp;
+ this.orderByGenComp = orderByGenComp;
+ this.rankStart = rankStart;
+ this.rankEnd = rankEnd;
+ this.outputRankFunColumn = outputRankFunColumn;
+ }
+
+ @Override
+ public void open() throws Exception {
+ super.open();
+
+ ClassLoader cl = getUserCodeClassloader();
+ inputSer = (AbstractRowSerializer) getOperatorConfig().getTypeSerializerIn1(cl);
+
+ partitionByComp = partitionByGenComp.newInstance(cl);
+ partitionByGenComp = null;
+
+ orderByComp = orderByGenComp.newInstance(cl);
+ orderByGenComp = null;
+
+ if (outputRankFunColumn) {
+ joinedRow = new JoinedRow();
+ rankValueRow = new GenericRow(1);
+ }
+
+ collector = new StreamRecordCollector<>(output);
+ }
+
+ @Override
+ public void processElement(StreamRecord<BaseRow> element) throws Exception {
+ BaseRow input = element.getValue();
+ // add 1 when meets a new row
+ rowNum += 1L;
+ if (lastInput == null || partitionByComp.compare(lastInput, input) != 0) {
+ // reset rank value and row number value for new group
+ rank = 1L;
+ rowNum = 1L;
+ } else if (orderByComp.compare(lastInput, input) != 0) {
+ // set rank value as row number value if order-by value is change in a group
+ rank = rowNum;
+ }
+
+ emitInternal(input);
+ lastInput = inputSer.copy(input);
+ }
+
+ private void emitInternal(BaseRow element) {
+ if (rank >= rankStart && rank <= rankEnd) {
+ if (outputRankFunColumn) {
+ rankValueRow.setLong(0, rank);
+ collector.collect(joinedRow.replace(element, rankValueRow));
+ } else {
+ collector.collect(element);
+ }
+ }
+ }
+}
diff --git a/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/sort/SortLimitOperator.java b/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/sort/SortLimitOperator.java
new file mode 100644
index 0000000..f3ceff6
--- /dev/null
+++ b/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/sort/SortLimitOperator.java
@@ -0,0 +1,110 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.table.runtime.sort;
+
+import org.apache.flink.streaming.api.operators.OneInputStreamOperator;
+import org.apache.flink.streaming.runtime.streamrecord.StreamRecord;
+import org.apache.flink.table.dataformat.BaseRow;
+import org.apache.flink.table.generated.GeneratedRecordComparator;
+import org.apache.flink.table.generated.RecordComparator;
+import org.apache.flink.table.runtime.TableStreamOperator;
+import org.apache.flink.table.runtime.util.StreamRecordCollector;
+import org.apache.flink.table.typeutils.AbstractRowSerializer;
+import org.apache.flink.util.Collector;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.PriorityQueue;
+
+/**
+ * Operator for sort limit.
+ */
+public class SortLimitOperator extends TableStreamOperator<BaseRow>
+ implements OneInputStreamOperator<BaseRow, BaseRow> {
+
+ private final boolean isGlobal;
+ private final long limitStart;
+ private final long limitEnd;
+ private GeneratedRecordComparator genComparator;
+
+ private transient PriorityQueue<BaseRow> heap;
+ private transient Collector<BaseRow> collector;
+ private transient RecordComparator comparator;
+ private transient AbstractRowSerializer<BaseRow> inputSer;
+
+ public SortLimitOperator(
+ boolean isGlobal, long limitStart, long limitEnd, GeneratedRecordComparator genComparator) {
+ this.isGlobal = isGlobal;
+ this.limitStart = limitStart;
+ this.limitEnd = limitEnd;
+ this.genComparator = genComparator;
+ }
+
+ @Override
+ public void open() throws Exception {
+ super.open();
+
+ inputSer = (AbstractRowSerializer) getOperatorConfig().getTypeSerializerIn1(getUserCodeClassloader());
+ comparator = genComparator.newInstance(getUserCodeClassloader());
+ genComparator = null;
+
+ // reverse the comparision.
+ heap = new PriorityQueue<>((int) limitEnd, (o1, o2) -> comparator.compare(o2, o1));
+ this.collector = new StreamRecordCollector<>(output);
+ }
+
+ @Override
+ public void processElement(StreamRecord<BaseRow> element) throws Exception {
+ BaseRow record = element.getValue();
+
+ // Need copy element, because we will store record in heap.
+ if (heap.size() >= limitEnd) {
+ BaseRow peek = heap.peek();
+ if (comparator.compare(peek, record) > 0) {
+ heap.poll();
+ heap.add(inputSer.copy(record));
+ } // else fail, this record don't need insert to the heap.
+ } else {
+ heap.add(inputSer.copy(record));
+ }
+ }
+
+ public void endInput() throws Exception {
+ if (isGlobal) {
+ // Global sort, we need sort the results and pick records in limitStart to limitEnd.
+ List<BaseRow> list = new ArrayList<>(heap);
+ list.sort((o1, o2) -> comparator.compare(o1, o2));
+
+ int maxIndex = (int) Math.min(limitEnd, list.size());
+ for (int i = (int) limitStart; i < maxIndex; i++) {
+ collector.collect(list.get(i));
+ }
+ } else {
+ for (BaseRow row : heap) {
+ collector.collect(row);
+ }
+ }
+ }
+
+ @Override
+ public void close() throws Exception {
+ endInput(); // TODO remove it.
+ super.close();
+ }
+}