You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@flink.apache.org by GitBox <gi...@apache.org> on 2020/07/23 02:20:21 UTC

[GitHub] [flink] liuyongvs opened a new pull request #12964: [FLINK-17426][blink plannger] Dynamic Source supportsLimit pushdown

liuyongvs opened a new pull request #12964:
URL: https://github.com/apache/flink/pull/12964


   ## What is the purpose of the change
   
   - make the DynamicSource supports LimitPushDown Rule
   
   ## Verifying this change
   
   This change added tests and can be verified as follows:
   
   - Added LimitTest to verify the plan
   - Extended LimitITCase (only batch)to verify the result limit projection
   - make the TestValueSource supports LimitPushDown
   
   ## Does this pull request potentially affect one of the following parts:
   
   - Dependencies (does it add or upgrade a dependency): ( no)
   - The public API, i.e., is any changed class annotated with @Public(Evolving): (no)
   - The serializers: ( no)
   - The runtime per-record code paths (performance sensitive): (no)
   - Anything that affects deployment or recovery: JobManager (and its components), Checkpointing, Kubernetes/Yarn/Mesos, ZooKeeper: (no)
   - The S3 file system connector: (no)
   
   ## Documentation
   
   - Does this pull request introduce a new feature? (yes)
   - If yes, how is the feature documented? (JavaDocs)
   


----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

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



[GitHub] [flink] flinkbot edited a comment on pull request #12964: [FLINK-17426][blink plannger] Dynamic Source supportsLimit pushdown

Posted by GitBox <gi...@apache.org>.
flinkbot edited a comment on pull request #12964:
URL: https://github.com/apache/flink/pull/12964#issuecomment-662793989


   <!--
   Meta data
   {
     "version" : 1,
     "metaDataEntries" : [ {
       "hash" : "984b8a182e5a5cc64a9e1957710e9b9fd4768a56",
       "status" : "SUCCESS",
       "url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=4751",
       "triggerID" : "984b8a182e5a5cc64a9e1957710e9b9fd4768a56",
       "triggerType" : "PUSH"
     }, {
       "hash" : "0324c22a9b2c85f04481966b2a78f72e92b9c88c",
       "status" : "PENDING",
       "url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=4917",
       "triggerID" : "0324c22a9b2c85f04481966b2a78f72e92b9c88c",
       "triggerType" : "PUSH"
     } ]
   }-->
   ## CI report:
   
   * 984b8a182e5a5cc64a9e1957710e9b9fd4768a56 Azure: [SUCCESS](https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=4751) 
   * 0324c22a9b2c85f04481966b2a78f72e92b9c88c Azure: [PENDING](https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=4917) 
   
   <details>
   <summary>Bot commands</summary>
     The @flinkbot bot supports the following commands:
   
    - `@flinkbot run travis` re-run the last Travis build
    - `@flinkbot run azure` re-run the last Azure build
   </details>


----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

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



[GitHub] [flink] liuyongvs commented on a change in pull request #12964: [FLINK-17426][blink plannger] Dynamic Source supportsLimit pushdown

Posted by GitBox <gi...@apache.org>.
liuyongvs commented on a change in pull request #12964:
URL: https://github.com/apache/flink/pull/12964#discussion_r459913928



##########
File path: flink-table/flink-table-planner-blink/src/main/java/org/apache/flink/table/planner/plan/rules/logical/PushLimitIntoTableSourceScanRule.java
##########
@@ -0,0 +1,121 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.table.planner.plan.rules.logical;
+
+import org.apache.flink.table.connector.source.DynamicTableSource;
+import org.apache.flink.table.connector.source.abilities.SupportsLimitPushDown;
+import org.apache.flink.table.plan.stats.TableStats;
+import org.apache.flink.table.planner.plan.nodes.logical.FlinkLogicalSort;
+import org.apache.flink.table.planner.plan.nodes.logical.FlinkLogicalTableSourceScan;
+import org.apache.flink.table.planner.plan.schema.FlinkPreparingTableBase;
+import org.apache.flink.table.planner.plan.schema.TableSourceTable;
+import org.apache.flink.table.planner.plan.stats.FlinkStatistic;
+
+import org.apache.calcite.plan.RelOptRule;
+import org.apache.calcite.plan.RelOptRuleCall;
+import org.apache.calcite.rel.core.Sort;
+import org.apache.calcite.rex.RexLiteral;
+
+import java.util.Arrays;
+import java.util.Collections;
+
+/**
+ * Planner rule that tries to push limit into a {@link FlinkLogicalTableSourceScan},
+ * which table is a {@link TableSourceTable}. And the table source in the table is a {@link SupportsLimitPushDown}.
+ * The original limit will still be retained.
+ * The reasons why the limit still be retained:
+ * 1.If the source is required to return the exact number of limit number, the implementation
+ * of the source is highly required. The source is required to accurately control the record
+ * number of split, and the parallelism setting also need to be adjusted accordingly.
+ * 2.When remove the limit, maybe filter will be pushed down to the source after limit pushed
+ * down. The source need know it should do limit first and do the filter later, it is hard to
+ * implement.
+ * 3.We can support limit with offset, we can push down offset + fetch to table source.
+ */
+public class PushLimitIntoTableSourceScanRule extends RelOptRule {

Review comment:
       the unit test is LimitTest.




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

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



[GitHub] [flink] liuyongvs commented on a change in pull request #12964: [FLINK-17426][blink plannger] Dynamic Source supportsLimit pushdown

Posted by GitBox <gi...@apache.org>.
liuyongvs commented on a change in pull request #12964:
URL: https://github.com/apache/flink/pull/12964#discussion_r459913464



##########
File path: flink-table/flink-table-planner-blink/src/main/java/org/apache/flink/table/planner/plan/rules/logical/PushLimitIntoTableSourceScanRule.java
##########
@@ -0,0 +1,121 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.table.planner.plan.rules.logical;
+
+import org.apache.flink.table.connector.source.DynamicTableSource;
+import org.apache.flink.table.connector.source.abilities.SupportsLimitPushDown;
+import org.apache.flink.table.plan.stats.TableStats;
+import org.apache.flink.table.planner.plan.nodes.logical.FlinkLogicalSort;
+import org.apache.flink.table.planner.plan.nodes.logical.FlinkLogicalTableSourceScan;
+import org.apache.flink.table.planner.plan.schema.FlinkPreparingTableBase;
+import org.apache.flink.table.planner.plan.schema.TableSourceTable;
+import org.apache.flink.table.planner.plan.stats.FlinkStatistic;
+
+import org.apache.calcite.plan.RelOptRule;
+import org.apache.calcite.plan.RelOptRuleCall;
+import org.apache.calcite.rel.core.Sort;
+import org.apache.calcite.rex.RexLiteral;
+
+import java.util.Arrays;
+import java.util.Collections;
+
+/**
+ * Planner rule that tries to push limit into a {@link FlinkLogicalTableSourceScan},
+ * which table is a {@link TableSourceTable}. And the table source in the table is a {@link SupportsLimitPushDown}.
+ * The original limit will still be retained.
+ * The reasons why the limit still be retained:
+ * 1.If the source is required to return the exact number of limit number, the implementation
+ * of the source is highly required. The source is required to accurately control the record
+ * number of split, and the parallelism setting also need to be adjusted accordingly.
+ * 2.When remove the limit, maybe filter will be pushed down to the source after limit pushed
+ * down. The source need know it should do limit first and do the filter later, it is hard to
+ * implement.
+ * 3.We can support limit with offset, we can push down offset + fetch to table source.
+ */
+public class PushLimitIntoTableSourceScanRule extends RelOptRule {
+	public static final PushLimitIntoTableSourceScanRule INSTANCE = new PushLimitIntoTableSourceScanRule();
+
+	public PushLimitIntoTableSourceScanRule() {
+		super(operand(FlinkLogicalSort.class,
+			operand(FlinkLogicalTableSourceScan.class, none())),
+			"PushLimitIntoTableSourceScanRule");
+	}
+
+	@Override
+	public boolean matches(RelOptRuleCall call) {
+		Sort sort = call.rel(0);
+		TableSourceTable tableSourceTable = call.rel(1).getTable().unwrap(TableSourceTable.class);
+
+		// a limit can be pushed down only if it satisfies the two conditions: 1) do not have order by keys, 2) have limit.
+		boolean onlyLimit = sort.getCollation().getFieldCollations().isEmpty() && sort.fetch != null;
+		return onlyLimit
+			&& tableSourceTable != null
+			&& tableSourceTable.tableSource() instanceof SupportsLimitPushDown
+			&& !Arrays.stream(tableSourceTable.extraDigests()).anyMatch(str -> str.startsWith("limit=["));

Review comment:
       ok

##########
File path: flink-table/flink-table-planner-blink/src/main/java/org/apache/flink/table/planner/plan/rules/logical/PushLimitIntoTableSourceScanRule.java
##########
@@ -0,0 +1,121 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.table.planner.plan.rules.logical;
+
+import org.apache.flink.table.connector.source.DynamicTableSource;
+import org.apache.flink.table.connector.source.abilities.SupportsLimitPushDown;
+import org.apache.flink.table.plan.stats.TableStats;
+import org.apache.flink.table.planner.plan.nodes.logical.FlinkLogicalSort;
+import org.apache.flink.table.planner.plan.nodes.logical.FlinkLogicalTableSourceScan;
+import org.apache.flink.table.planner.plan.schema.FlinkPreparingTableBase;
+import org.apache.flink.table.planner.plan.schema.TableSourceTable;
+import org.apache.flink.table.planner.plan.stats.FlinkStatistic;
+
+import org.apache.calcite.plan.RelOptRule;
+import org.apache.calcite.plan.RelOptRuleCall;
+import org.apache.calcite.rel.core.Sort;
+import org.apache.calcite.rex.RexLiteral;
+
+import java.util.Arrays;
+import java.util.Collections;
+
+/**
+ * Planner rule that tries to push limit into a {@link FlinkLogicalTableSourceScan},
+ * which table is a {@link TableSourceTable}. And the table source in the table is a {@link SupportsLimitPushDown}.
+ * The original limit will still be retained.
+ * The reasons why the limit still be retained:
+ * 1.If the source is required to return the exact number of limit number, the implementation
+ * of the source is highly required. The source is required to accurately control the record
+ * number of split, and the parallelism setting also need to be adjusted accordingly.
+ * 2.When remove the limit, maybe filter will be pushed down to the source after limit pushed
+ * down. The source need know it should do limit first and do the filter later, it is hard to
+ * implement.
+ * 3.We can support limit with offset, we can push down offset + fetch to table source.
+ */
+public class PushLimitIntoTableSourceScanRule extends RelOptRule {
+	public static final PushLimitIntoTableSourceScanRule INSTANCE = new PushLimitIntoTableSourceScanRule();
+
+	public PushLimitIntoTableSourceScanRule() {
+		super(operand(FlinkLogicalSort.class,
+			operand(FlinkLogicalTableSourceScan.class, none())),
+			"PushLimitIntoTableSourceScanRule");
+	}
+
+	@Override
+	public boolean matches(RelOptRuleCall call) {
+		Sort sort = call.rel(0);
+		TableSourceTable tableSourceTable = call.rel(1).getTable().unwrap(TableSourceTable.class);
+
+		// a limit can be pushed down only if it satisfies the two conditions: 1) do not have order by keys, 2) have limit.
+		boolean onlyLimit = sort.getCollation().getFieldCollations().isEmpty() && sort.fetch != null;
+		return onlyLimit
+			&& tableSourceTable != null
+			&& tableSourceTable.tableSource() instanceof SupportsLimitPushDown
+			&& !Arrays.stream(tableSourceTable.extraDigests()).anyMatch(str -> str.startsWith("limit=["));
+	}
+
+	@Override
+	public void onMatch(RelOptRuleCall call) {
+		Sort sort = call.rel(0);
+		FlinkLogicalTableSourceScan scan = call.rel(1);
+		TableSourceTable tableSourceTable = scan.getTable().unwrap(TableSourceTable.class);
+		int offset = sort.offset == null ? 0 : RexLiteral.intValue(sort.offset);
+		int limit = offset + RexLiteral.intValue(sort.fetch);
+
+		TableSourceTable newTableSourceTable = applyLimit(limit, tableSourceTable);
+
+		FlinkLogicalTableSourceScan newScan = FlinkLogicalTableSourceScan.create(scan.getCluster(), newTableSourceTable);
+		call.transformTo(sort.copy(sort.getTraitSet(), Collections.singletonList(newScan)));

Review comment:
       ok

##########
File path: flink-table/flink-table-planner-blink/src/test/java/org/apache/flink/table/planner/factories/TestValuesTableFactory.java
##########
@@ -359,7 +361,7 @@ private ChangelogMode parseChangelogMode(String string) {
 	/**
 	 * Values {@link DynamicTableSource} for testing.
 	 */
-	private static class TestValuesTableSource implements ScanTableSource, LookupTableSource, SupportsProjectionPushDown, SupportsFilterPushDown {
+	private static class TestValuesTableSource implements ScanTableSource, LookupTableSource, SupportsProjectionPushDown, SupportsFilterPushDown, SupportsLimitPushDown {

Review comment:
       ok




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

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



[GitHub] [flink] godfreyhe commented on a change in pull request #12964: [FLINK-17426][blink plannger] Dynamic Source supportsLimit pushdown

Posted by GitBox <gi...@apache.org>.
godfreyhe commented on a change in pull request #12964:
URL: https://github.com/apache/flink/pull/12964#discussion_r459961065



##########
File path: flink-table/flink-table-planner-blink/src/main/java/org/apache/flink/table/planner/plan/rules/logical/PushLimitIntoTableSourceScanRule.java
##########
@@ -0,0 +1,121 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.table.planner.plan.rules.logical;
+
+import org.apache.flink.table.connector.source.DynamicTableSource;
+import org.apache.flink.table.connector.source.abilities.SupportsLimitPushDown;
+import org.apache.flink.table.plan.stats.TableStats;
+import org.apache.flink.table.planner.plan.nodes.logical.FlinkLogicalSort;
+import org.apache.flink.table.planner.plan.nodes.logical.FlinkLogicalTableSourceScan;
+import org.apache.flink.table.planner.plan.schema.FlinkPreparingTableBase;
+import org.apache.flink.table.planner.plan.schema.TableSourceTable;
+import org.apache.flink.table.planner.plan.stats.FlinkStatistic;
+
+import org.apache.calcite.plan.RelOptRule;
+import org.apache.calcite.plan.RelOptRuleCall;
+import org.apache.calcite.rel.core.Sort;
+import org.apache.calcite.rex.RexLiteral;
+
+import java.util.Arrays;
+import java.util.Collections;
+
+/**
+ * Planner rule that tries to push limit into a {@link FlinkLogicalTableSourceScan},
+ * which table is a {@link TableSourceTable}. And the table source in the table is a {@link SupportsLimitPushDown}.
+ * The original limit will still be retained.
+ * The reasons why the limit still be retained:
+ * 1.If the source is required to return the exact number of limit number, the implementation
+ * of the source is highly required. The source is required to accurately control the record
+ * number of split, and the parallelism setting also need to be adjusted accordingly.
+ * 2.When remove the limit, maybe filter will be pushed down to the source after limit pushed
+ * down. The source need know it should do limit first and do the filter later, it is hard to
+ * implement.
+ * 3.We can support limit with offset, we can push down offset + fetch to table source.
+ */
+public class PushLimitIntoTableSourceScanRule extends RelOptRule {

Review comment:
       Rule test is different from plan test. Rule test focuses on the new rule you implement and only a few must-involved rules can be added to the rule set to help the test. Plan test will verify the plan based on whole rule sets.




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

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



[GitHub] [flink] godfreyhe commented on a change in pull request #12964: [FLINK-17426][blink plannger] Dynamic Source supportsLimit pushdown

Posted by GitBox <gi...@apache.org>.
godfreyhe commented on a change in pull request #12964:
URL: https://github.com/apache/flink/pull/12964#discussion_r459959326



##########
File path: flink-table/flink-table-planner-blink/src/main/java/org/apache/flink/table/planner/plan/rules/logical/PushLimitIntoTableSourceScanRule.java
##########
@@ -0,0 +1,121 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.table.planner.plan.rules.logical;
+
+import org.apache.flink.table.connector.source.DynamicTableSource;
+import org.apache.flink.table.connector.source.abilities.SupportsLimitPushDown;
+import org.apache.flink.table.plan.stats.TableStats;
+import org.apache.flink.table.planner.plan.nodes.logical.FlinkLogicalSort;
+import org.apache.flink.table.planner.plan.nodes.logical.FlinkLogicalTableSourceScan;
+import org.apache.flink.table.planner.plan.schema.FlinkPreparingTableBase;
+import org.apache.flink.table.planner.plan.schema.TableSourceTable;
+import org.apache.flink.table.planner.plan.stats.FlinkStatistic;
+
+import org.apache.calcite.plan.RelOptRule;
+import org.apache.calcite.plan.RelOptRuleCall;
+import org.apache.calcite.rel.core.Sort;
+import org.apache.calcite.rex.RexLiteral;
+
+import java.util.Arrays;
+import java.util.Collections;
+
+/**
+ * Planner rule that tries to push limit into a {@link FlinkLogicalTableSourceScan},
+ * which table is a {@link TableSourceTable}. And the table source in the table is a {@link SupportsLimitPushDown}.
+ * The original limit will still be retained.
+ * The reasons why the limit still be retained:
+ * 1.If the source is required to return the exact number of limit number, the implementation
+ * of the source is highly required. The source is required to accurately control the record
+ * number of split, and the parallelism setting also need to be adjusted accordingly.
+ * 2.When remove the limit, maybe filter will be pushed down to the source after limit pushed
+ * down. The source need know it should do limit first and do the filter later, it is hard to
+ * implement.
+ * 3.We can support limit with offset, we can push down offset + fetch to table source.
+ */
+public class PushLimitIntoTableSourceScanRule extends RelOptRule {
+	public static final PushLimitIntoTableSourceScanRule INSTANCE = new PushLimitIntoTableSourceScanRule();
+
+	public PushLimitIntoTableSourceScanRule() {
+		super(operand(FlinkLogicalSort.class,
+			operand(FlinkLogicalTableSourceScan.class, none())),
+			"PushLimitIntoTableSourceScanRule");
+	}
+
+	@Override
+	public boolean matches(RelOptRuleCall call) {
+		Sort sort = call.rel(0);
+		TableSourceTable tableSourceTable = call.rel(1).getTable().unwrap(TableSourceTable.class);
+
+		// a limit can be pushed down only if it satisfies the two conditions: 1) do not have order by keys, 2) have limit.
+		boolean onlyLimit = sort.getCollation().getFieldCollations().isEmpty() && sort.fetch != null;
+		return onlyLimit
+			&& tableSourceTable != null
+			&& tableSourceTable.tableSource() instanceof SupportsLimitPushDown
+			&& !Arrays.stream(tableSourceTable.extraDigests()).anyMatch(str -> str.startsWith("limit=["));
+	}
+
+	@Override
+	public void onMatch(RelOptRuleCall call) {
+		Sort sort = call.rel(0);
+		FlinkLogicalTableSourceScan scan = call.rel(1);
+		TableSourceTable tableSourceTable = scan.getTable().unwrap(TableSourceTable.class);
+		int offset = sort.offset == null ? 0 : RexLiteral.intValue(sort.offset);
+		int limit = offset + RexLiteral.intValue(sort.fetch);
+
+		TableSourceTable newTableSourceTable = applyLimit(limit, tableSourceTable);
+
+		FlinkLogicalTableSourceScan newScan = FlinkLogicalTableSourceScan.create(scan.getCluster(), newTableSourceTable);
+		call.transformTo(sort.copy(sort.getTraitSet(), Collections.singletonList(newScan)));
+	}
+
+	private TableSourceTable applyLimit(
+		long limit,
+		FlinkPreparingTableBase relOptTable) {
+		TableSourceTable oldTableSourceTable = relOptTable.unwrap(TableSourceTable.class);
+		DynamicTableSource newTableSource = oldTableSourceTable.tableSource().copy();
+		((SupportsLimitPushDown) newTableSource).applyLimit(limit);
+
+		FlinkStatistic statistic = relOptTable.getStatistic();
+		long newRowCount = 0;
+		if (statistic.getRowCount() != null) {
+			newRowCount = Math.min(limit, statistic.getRowCount().longValue());
+		} else {
+			newRowCount = limit;
+		}
+		// update TableStats after limit push down
+		TableStats newTableStats = new TableStats(newRowCount);
+		FlinkStatistic newStatistic = FlinkStatistic.builder()
+			.statistic(statistic)
+			.tableStats(newTableStats)
+			.build();
+
+		// update extraDigests
+		String[] newExtraDigests = new String[0];
+		if (limit > 0) {

Review comment:
       We can't rely on other rules to ensure the correctness of this rule, we must make sure each rule itself is correct.




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

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



[GitHub] [flink] liuyongvs commented on pull request #12964: [FLINK-17426][blink plannger] Dynamic Source supportsLimit pushdown

Posted by GitBox <gi...@apache.org>.
liuyongvs commented on pull request #12964:
URL: https://github.com/apache/flink/pull/12964#issuecomment-662851070


   Hi @godfreyhe @wuchong ,it is here, thanks for your review.


----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

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



[GitHub] [flink] flinkbot edited a comment on pull request #12964: [FLINK-17426][blink plannger] Dynamic Source supportsLimit pushdown

Posted by GitBox <gi...@apache.org>.
flinkbot edited a comment on pull request #12964:
URL: https://github.com/apache/flink/pull/12964#issuecomment-662793989


   <!--
   Meta data
   {
     "version" : 1,
     "metaDataEntries" : [ {
       "hash" : "984b8a182e5a5cc64a9e1957710e9b9fd4768a56",
       "status" : "SUCCESS",
       "url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=4751",
       "triggerID" : "984b8a182e5a5cc64a9e1957710e9b9fd4768a56",
       "triggerType" : "PUSH"
     }, {
       "hash" : "0324c22a9b2c85f04481966b2a78f72e92b9c88c",
       "status" : "UNKNOWN",
       "url" : "TBD",
       "triggerID" : "0324c22a9b2c85f04481966b2a78f72e92b9c88c",
       "triggerType" : "PUSH"
     } ]
   }-->
   ## CI report:
   
   * 984b8a182e5a5cc64a9e1957710e9b9fd4768a56 Azure: [SUCCESS](https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=4751) 
   * 0324c22a9b2c85f04481966b2a78f72e92b9c88c UNKNOWN
   
   <details>
   <summary>Bot commands</summary>
     The @flinkbot bot supports the following commands:
   
    - `@flinkbot run travis` re-run the last Travis build
    - `@flinkbot run azure` re-run the last Azure build
   </details>


----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

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



[GitHub] [flink] liuyongvs commented on a change in pull request #12964: [FLINK-17426][blink planner] Dynamic Source supportsLimit pushdown

Posted by GitBox <gi...@apache.org>.
liuyongvs commented on a change in pull request #12964:
URL: https://github.com/apache/flink/pull/12964#discussion_r462766978



##########
File path: flink-table/flink-table-planner-blink/src/test/resources/org/apache/flink/table/planner/plan/rules/logical/PushLimitIntoTableSourceScanRuleTest.xml
##########
@@ -0,0 +1,171 @@
+<?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="testCanPushdownLimitWithoutOffset">
+		<Resource name="sql">
+			<![CDATA[SELECT a, c FROM LimitTable LIMIT 5]]>
+		</Resource>
+		<Resource name="planBefore">
+			<![CDATA[
+LogicalSort(fetch=[5])
++- LogicalProject(a=[$0], c=[$2])
+   +- LogicalTableScan(table=[[default_catalog, default_database, LimitTable]])
+]]>
+		</Resource>
+		<Resource name="planAfter">
+			<![CDATA[
+LogicalProject(a=[$0], c=[$2])
++- FlinkLogicalSort(fetch=[5])
+   +- FlinkLogicalTableSourceScan(table=[[default_catalog, default_database, LimitTable, limit=[5]]], fields=[a, b, c])
+]]>
+		</Resource>
+	</TestCase>
+	<TestCase name="testCanPushdownFetchWithOffset">
+		<Resource name="sql">
+			<![CDATA[SELECT a, c FROM LimitTable 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=[[default_catalog, default_database, LimitTable]])
+]]>
+		</Resource>
+		<Resource name="planAfter">
+			<![CDATA[
+LogicalProject(a=[$0], c=[$2])
++- FlinkLogicalSort(offset=[10], fetch=[10])
+   +- FlinkLogicalTableSourceScan(table=[[default_catalog, default_database, LimitTable, limit=[20]]], fields=[a, b, c])
+]]>
+		</Resource>
+	</TestCase>
+	<TestCase name="testCanPushdownFetchWithoutOffset">
+		<Resource name="sql">
+			<![CDATA[SELECT a, c FROM LimitTable FETCH FIRST 10 ROWS ONLY]]>
+		</Resource>
+		<Resource name="planBefore">
+			<![CDATA[
+LogicalSort(fetch=[10])
++- LogicalProject(a=[$0], c=[$2])
+   +- LogicalTableScan(table=[[default_catalog, default_database, LimitTable]])
+]]>
+		</Resource>
+		<Resource name="planAfter">
+			<![CDATA[
+LogicalProject(a=[$0], c=[$2])
++- FlinkLogicalSort(fetch=[10])
+   +- FlinkLogicalTableSourceScan(table=[[default_catalog, default_database, LimitTable, limit=[10]]], fields=[a, b, c])
+]]>
+		</Resource>
+	</TestCase>
+	<TestCase name="testCannotPushDownWithOrderBy">
+		<Resource name="sql">
+			<![CDATA[SELECT a, c FROM LimitTable ORDER BY c LIMIT 10]]>
+		</Resource>
+		<Resource name="planBefore">
+			<![CDATA[
+LogicalSort(sort0=[$1], dir0=[ASC-nulls-first], fetch=[10])
++- LogicalProject(a=[$0], c=[$2])
+   +- LogicalTableScan(table=[[default_catalog, default_database, LimitTable]])
+]]>
+		</Resource>
+		<Resource name="planAfter">
+			<![CDATA[
+LogicalProject(a=[$0], c=[$2])
++- FlinkLogicalSort(sort0=[$2], dir0=[ASC-nulls-first], fetch=[10])
+   +- FlinkLogicalTableSourceScan(table=[[default_catalog, default_database, LimitTable]], fields=[a, b, c])
+]]>
+		</Resource>
+	</TestCase>
+	<TestCase name="testCanPushdownLimitWithOffset">
+		<Resource name="sql">
+			<![CDATA[SELECT a, c FROM LimitTable LIMIT 10 OFFSET 1]]>
+		</Resource>
+		<Resource name="planBefore">
+			<![CDATA[
+LogicalSort(offset=[1], fetch=[10])
++- LogicalProject(a=[$0], c=[$2])
+   +- LogicalTableScan(table=[[default_catalog, default_database, LimitTable]])
+]]>
+		</Resource>
+		<Resource name="planAfter">
+			<![CDATA[
+LogicalProject(a=[$0], c=[$2])
++- FlinkLogicalSort(offset=[1], fetch=[10])
+   +- FlinkLogicalTableSourceScan(table=[[default_catalog, default_database, LimitTable, limit=[11]]], fields=[a, b, c])
+]]>
+		</Resource>
+	</TestCase>
+	<TestCase name="testLimitWithoutOffset">
+		<Resource name="sql">
+			<![CDATA[SELECT * FROM LimitTable LIMIT 5]]>
+		</Resource>
+		<Resource name="planBefore">
+			<![CDATA[
+LogicalSort(fetch=[5])
++- LogicalProject(a=[$0], b=[$1], c=[$2])
+   +- LogicalTableScan(table=[[default_catalog, default_database, LimitTable]])
+]]>
+		</Resource>
+		<Resource name="planAfter">
+			<![CDATA[
+LogicalProject(a=[$0], b=[$1], c=[$2])
++- FlinkLogicalSort(fetch=[5])
+   +- FlinkLogicalTableSourceScan(table=[[default_catalog, default_database, LimitTable, source: [limit: 5]]], fields=[a, b, c])

Review comment:
       sorry, it should be removed. i have replace the testLimitWithoutOffset by  testCanPushdownLimitWithoutOffset. And forgot to remove it. 

##########
File path: flink-table/flink-table-planner-blink/src/main/java/org/apache/flink/table/planner/plan/rules/logical/PushLimitIntoTableSourceScanRule.java
##########
@@ -0,0 +1,122 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.table.planner.plan.rules.logical;
+
+import org.apache.flink.table.connector.source.DynamicTableSource;
+import org.apache.flink.table.connector.source.abilities.SupportsLimitPushDown;
+import org.apache.flink.table.plan.stats.TableStats;
+import org.apache.flink.table.planner.plan.nodes.logical.FlinkLogicalSort;
+import org.apache.flink.table.planner.plan.nodes.logical.FlinkLogicalTableSourceScan;
+import org.apache.flink.table.planner.plan.schema.FlinkPreparingTableBase;
+import org.apache.flink.table.planner.plan.schema.TableSourceTable;
+import org.apache.flink.table.planner.plan.stats.FlinkStatistic;
+
+import org.apache.calcite.plan.RelOptRule;
+import org.apache.calcite.plan.RelOptRuleCall;
+import org.apache.calcite.rel.core.Sort;
+import org.apache.calcite.rex.RexLiteral;
+
+import java.util.Arrays;
+import java.util.Collections;
+
+/**
+ * Planner rule that tries to push limit into a {@link FlinkLogicalTableSourceScan},
+ * which table is a {@link TableSourceTable}. And the table source in the table is a {@link SupportsLimitPushDown}.
+ * The original limit will still be retained.
+ * The reasons why the limit still be retained:
+ * 1.If the source is required to return the exact number of limit number, the implementation
+ * of the source is highly required. The source is required to accurately control the record
+ * number of split, and the parallelism setting also need to be adjusted accordingly.
+ * 2.When remove the limit, maybe filter will be pushed down to the source after limit pushed
+ * down. The source need know it should do limit first and do the filter later, it is hard to
+ * implement.
+ * 3.We can support limit with offset, we can push down offset + fetch to table source.
+ */
+public class PushLimitIntoTableSourceScanRule extends RelOptRule {
+	public static final PushLimitIntoTableSourceScanRule INSTANCE = new PushLimitIntoTableSourceScanRule();
+
+	public PushLimitIntoTableSourceScanRule() {
+		super(operand(FlinkLogicalSort.class,
+			operand(FlinkLogicalTableSourceScan.class, none())),
+			"PushLimitIntoTableSourceScanRule");
+	}
+
+	@Override
+	public boolean matches(RelOptRuleCall call) {
+		Sort sort = call.rel(0);
+		TableSourceTable tableSourceTable = call.rel(1).getTable().unwrap(TableSourceTable.class);
+
+		// a limit can be pushed down only if it satisfies the two conditions: 1) do not have order by keys, 2) have limit.
+		boolean onlyLimit = sort.getCollation().getFieldCollations().isEmpty() && sort.fetch != null;
+		return onlyLimit
+			&& tableSourceTable != null
+			&& tableSourceTable.tableSource() instanceof SupportsLimitPushDown
+			&& Arrays.stream(tableSourceTable.extraDigests()).noneMatch(str -> str.startsWith("limit=["));
+	}
+
+	@Override
+	public void onMatch(RelOptRuleCall call) {
+		Sort sort = call.rel(0);
+		FlinkLogicalTableSourceScan scan = call.rel(1);
+		TableSourceTable tableSourceTable = scan.getTable().unwrap(TableSourceTable.class);
+		int offset = sort.offset == null ? 0 : RexLiteral.intValue(sort.offset);
+		int limit = offset + RexLiteral.intValue(sort.fetch);
+
+		TableSourceTable newTableSourceTable = applyLimit(limit, tableSourceTable);
+
+		FlinkLogicalTableSourceScan newScan = FlinkLogicalTableSourceScan.create(scan.getCluster(), newTableSourceTable);
+		Sort newSort = sort.copy(sort.getTraitSet(), Collections.singletonList(newScan));
+		call.transformTo(newSort);
+	}
+
+	private TableSourceTable applyLimit(
+		long limit,
+		FlinkPreparingTableBase relOptTable) {
+		TableSourceTable oldTableSourceTable = relOptTable.unwrap(TableSourceTable.class);
+		DynamicTableSource newTableSource = oldTableSourceTable.tableSource().copy();
+		((SupportsLimitPushDown) newTableSource).applyLimit(limit);
+
+		FlinkStatistic statistic = relOptTable.getStatistic();
+		long newRowCount = 0;
+		if (statistic.getRowCount() != null) {
+			newRowCount = Math.min(limit, statistic.getRowCount().longValue());
+		} else {
+			newRowCount = limit;
+		}
+		// update TableStats after limit push down
+		TableStats newTableStats = new TableStats(newRowCount);
+		FlinkStatistic newStatistic = FlinkStatistic.builder()
+			.statistic(statistic)
+			.tableStats(newTableStats)
+			.build();
+
+		// update extraDigests
+		String[] newExtraDigests = new String[0];
+		if (limit >= 0) {

Review comment:
       good idea

##########
File path: flink-table/flink-table-planner-blink/src/main/java/org/apache/flink/table/planner/plan/rules/logical/PushLimitIntoTableSourceScanRule.java
##########
@@ -0,0 +1,122 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.table.planner.plan.rules.logical;
+
+import org.apache.flink.table.connector.source.DynamicTableSource;
+import org.apache.flink.table.connector.source.abilities.SupportsLimitPushDown;
+import org.apache.flink.table.plan.stats.TableStats;
+import org.apache.flink.table.planner.plan.nodes.logical.FlinkLogicalSort;
+import org.apache.flink.table.planner.plan.nodes.logical.FlinkLogicalTableSourceScan;
+import org.apache.flink.table.planner.plan.schema.FlinkPreparingTableBase;
+import org.apache.flink.table.planner.plan.schema.TableSourceTable;
+import org.apache.flink.table.planner.plan.stats.FlinkStatistic;
+
+import org.apache.calcite.plan.RelOptRule;
+import org.apache.calcite.plan.RelOptRuleCall;
+import org.apache.calcite.rel.core.Sort;
+import org.apache.calcite.rex.RexLiteral;
+
+import java.util.Arrays;
+import java.util.Collections;
+
+/**
+ * Planner rule that tries to push limit into a {@link FlinkLogicalTableSourceScan},
+ * which table is a {@link TableSourceTable}. And the table source in the table is a {@link SupportsLimitPushDown}.
+ * The original limit will still be retained.
+ * The reasons why the limit still be retained:
+ * 1.If the source is required to return the exact number of limit number, the implementation
+ * of the source is highly required. The source is required to accurately control the record
+ * number of split, and the parallelism setting also need to be adjusted accordingly.
+ * 2.When remove the limit, maybe filter will be pushed down to the source after limit pushed
+ * down. The source need know it should do limit first and do the filter later, it is hard to
+ * implement.
+ * 3.We can support limit with offset, we can push down offset + fetch to table source.
+ */
+public class PushLimitIntoTableSourceScanRule extends RelOptRule {
+	public static final PushLimitIntoTableSourceScanRule INSTANCE = new PushLimitIntoTableSourceScanRule();
+
+	public PushLimitIntoTableSourceScanRule() {
+		super(operand(FlinkLogicalSort.class,
+			operand(FlinkLogicalTableSourceScan.class, none())),
+			"PushLimitIntoTableSourceScanRule");
+	}
+
+	@Override
+	public boolean matches(RelOptRuleCall call) {
+		Sort sort = call.rel(0);
+		TableSourceTable tableSourceTable = call.rel(1).getTable().unwrap(TableSourceTable.class);
+
+		// a limit can be pushed down only if it satisfies the two conditions: 1) do not have order by keys, 2) have limit.
+		boolean onlyLimit = sort.getCollation().getFieldCollations().isEmpty() && sort.fetch != null;
+		return onlyLimit
+			&& tableSourceTable != null
+			&& tableSourceTable.tableSource() instanceof SupportsLimitPushDown
+			&& Arrays.stream(tableSourceTable.extraDigests()).noneMatch(str -> str.startsWith("limit=["));
+	}
+
+	@Override
+	public void onMatch(RelOptRuleCall call) {
+		Sort sort = call.rel(0);
+		FlinkLogicalTableSourceScan scan = call.rel(1);
+		TableSourceTable tableSourceTable = scan.getTable().unwrap(TableSourceTable.class);
+		int offset = sort.offset == null ? 0 : RexLiteral.intValue(sort.offset);
+		int limit = offset + RexLiteral.intValue(sort.fetch);
+
+		TableSourceTable newTableSourceTable = applyLimit(limit, tableSourceTable);
+
+		FlinkLogicalTableSourceScan newScan = FlinkLogicalTableSourceScan.create(scan.getCluster(), newTableSourceTable);
+		Sort newSort = sort.copy(sort.getTraitSet(), Collections.singletonList(newScan));
+		call.transformTo(newSort);
+	}
+
+	private TableSourceTable applyLimit(
+		long limit,
+		FlinkPreparingTableBase relOptTable) {
+		TableSourceTable oldTableSourceTable = relOptTable.unwrap(TableSourceTable.class);
+		DynamicTableSource newTableSource = oldTableSourceTable.tableSource().copy();
+		((SupportsLimitPushDown) newTableSource).applyLimit(limit);
+
+		FlinkStatistic statistic = relOptTable.getStatistic();
+		long newRowCount = 0;
+		if (statistic.getRowCount() != null) {
+			newRowCount = Math.min(limit, statistic.getRowCount().longValue());
+		} else {
+			newRowCount = limit;
+		}
+		// update TableStats after limit push down
+		TableStats newTableStats = new TableStats(newRowCount);
+		FlinkStatistic newStatistic = FlinkStatistic.builder()
+			.statistic(statistic)
+			.tableStats(newTableStats)
+			.build();
+
+		// update extraDigests
+		String[] newExtraDigests = new String[0];
+		if (limit >= 0) {

Review comment:
       good idea

##########
File path: flink-table/flink-table-planner-blink/src/main/java/org/apache/flink/table/planner/plan/rules/logical/PushLimitIntoTableSourceScanRule.java
##########
@@ -0,0 +1,122 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.table.planner.plan.rules.logical;
+
+import org.apache.flink.table.connector.source.DynamicTableSource;
+import org.apache.flink.table.connector.source.abilities.SupportsLimitPushDown;
+import org.apache.flink.table.plan.stats.TableStats;
+import org.apache.flink.table.planner.plan.nodes.logical.FlinkLogicalSort;
+import org.apache.flink.table.planner.plan.nodes.logical.FlinkLogicalTableSourceScan;
+import org.apache.flink.table.planner.plan.schema.FlinkPreparingTableBase;
+import org.apache.flink.table.planner.plan.schema.TableSourceTable;
+import org.apache.flink.table.planner.plan.stats.FlinkStatistic;
+
+import org.apache.calcite.plan.RelOptRule;
+import org.apache.calcite.plan.RelOptRuleCall;
+import org.apache.calcite.rel.core.Sort;
+import org.apache.calcite.rex.RexLiteral;
+
+import java.util.Arrays;
+import java.util.Collections;
+
+/**
+ * Planner rule that tries to push limit into a {@link FlinkLogicalTableSourceScan},
+ * which table is a {@link TableSourceTable}. And the table source in the table is a {@link SupportsLimitPushDown}.
+ * The original limit will still be retained.
+ * The reasons why the limit still be retained:
+ * 1.If the source is required to return the exact number of limit number, the implementation
+ * of the source is highly required. The source is required to accurately control the record
+ * number of split, and the parallelism setting also need to be adjusted accordingly.
+ * 2.When remove the limit, maybe filter will be pushed down to the source after limit pushed
+ * down. The source need know it should do limit first and do the filter later, it is hard to
+ * implement.
+ * 3.We can support limit with offset, we can push down offset + fetch to table source.
+ */
+public class PushLimitIntoTableSourceScanRule extends RelOptRule {
+	public static final PushLimitIntoTableSourceScanRule INSTANCE = new PushLimitIntoTableSourceScanRule();
+
+	public PushLimitIntoTableSourceScanRule() {
+		super(operand(FlinkLogicalSort.class,
+			operand(FlinkLogicalTableSourceScan.class, none())),
+			"PushLimitIntoTableSourceScanRule");
+	}
+
+	@Override
+	public boolean matches(RelOptRuleCall call) {
+		Sort sort = call.rel(0);
+		TableSourceTable tableSourceTable = call.rel(1).getTable().unwrap(TableSourceTable.class);
+
+		// a limit can be pushed down only if it satisfies the two conditions: 1) do not have order by keys, 2) have limit.
+		boolean onlyLimit = sort.getCollation().getFieldCollations().isEmpty() && sort.fetch != null;
+		return onlyLimit
+			&& tableSourceTable != null
+			&& tableSourceTable.tableSource() instanceof SupportsLimitPushDown
+			&& Arrays.stream(tableSourceTable.extraDigests()).noneMatch(str -> str.startsWith("limit=["));
+	}
+
+	@Override
+	public void onMatch(RelOptRuleCall call) {
+		Sort sort = call.rel(0);
+		FlinkLogicalTableSourceScan scan = call.rel(1);
+		TableSourceTable tableSourceTable = scan.getTable().unwrap(TableSourceTable.class);
+		int offset = sort.offset == null ? 0 : RexLiteral.intValue(sort.offset);
+		int limit = offset + RexLiteral.intValue(sort.fetch);
+
+		TableSourceTable newTableSourceTable = applyLimit(limit, tableSourceTable);
+
+		FlinkLogicalTableSourceScan newScan = FlinkLogicalTableSourceScan.create(scan.getCluster(), newTableSourceTable);
+		Sort newSort = sort.copy(sort.getTraitSet(), Collections.singletonList(newScan));
+		call.transformTo(newSort);
+	}
+
+	private TableSourceTable applyLimit(
+		long limit,
+		FlinkPreparingTableBase relOptTable) {
+		TableSourceTable oldTableSourceTable = relOptTable.unwrap(TableSourceTable.class);
+		DynamicTableSource newTableSource = oldTableSourceTable.tableSource().copy();
+		((SupportsLimitPushDown) newTableSource).applyLimit(limit);
+
+		FlinkStatistic statistic = relOptTable.getStatistic();
+		long newRowCount = 0;
+		if (statistic.getRowCount() != null) {
+			newRowCount = Math.min(limit, statistic.getRowCount().longValue());
+		} else {
+			newRowCount = limit;
+		}
+		// update TableStats after limit push down
+		TableStats newTableStats = new TableStats(newRowCount);
+		FlinkStatistic newStatistic = FlinkStatistic.builder()
+			.statistic(statistic)
+			.tableStats(newTableStats)
+			.build();
+
+		// update extraDigests
+		String[] newExtraDigests = new String[0];
+		if (limit >= 0) {

Review comment:
       Yeap, calcite fetch member is null when it doesn't have limit currently. And calcite doesn't support mysql  limit x,y syntax.  If it supports, limit 5, -1. The -1 represents the end. That is to say [offset5, end).
   So the calcite may transform -1 to fetch null when it supports in parser. And we don't need to limit >=0.
   So i just do as you say, remove the limit >= 0 and  don't add limitation in matches.




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

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



[GitHub] [flink] flinkbot edited a comment on pull request #12964: [FLINK-17426][blink plannger] Dynamic Source supportsLimit pushdown

Posted by GitBox <gi...@apache.org>.
flinkbot edited a comment on pull request #12964:
URL: https://github.com/apache/flink/pull/12964#issuecomment-662793989


   <!--
   Meta data
   {
     "version" : 1,
     "metaDataEntries" : [ {
       "hash" : "984b8a182e5a5cc64a9e1957710e9b9fd4768a56",
       "status" : "PENDING",
       "url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=4751",
       "triggerID" : "984b8a182e5a5cc64a9e1957710e9b9fd4768a56",
       "triggerType" : "PUSH"
     } ]
   }-->
   ## CI report:
   
   * 984b8a182e5a5cc64a9e1957710e9b9fd4768a56 Azure: [PENDING](https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=4751) 
   
   <details>
   <summary>Bot commands</summary>
     The @flinkbot bot supports the following commands:
   
    - `@flinkbot run travis` re-run the last Travis build
    - `@flinkbot run azure` re-run the last Azure build
   </details>


----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

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



[GitHub] [flink] godfreyhe commented on a change in pull request #12964: [FLINK-17426][blink plannger] Dynamic Source supportsLimit pushdown

Posted by GitBox <gi...@apache.org>.
godfreyhe commented on a change in pull request #12964:
URL: https://github.com/apache/flink/pull/12964#discussion_r461439479



##########
File path: flink-table/flink-table-planner-blink/src/main/java/org/apache/flink/table/planner/plan/rules/logical/PushLimitIntoTableSourceScanRule.java
##########
@@ -0,0 +1,122 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.table.planner.plan.rules.logical;
+
+import org.apache.flink.table.connector.source.DynamicTableSource;
+import org.apache.flink.table.connector.source.abilities.SupportsLimitPushDown;
+import org.apache.flink.table.plan.stats.TableStats;
+import org.apache.flink.table.planner.plan.nodes.logical.FlinkLogicalSort;
+import org.apache.flink.table.planner.plan.nodes.logical.FlinkLogicalTableSourceScan;
+import org.apache.flink.table.planner.plan.schema.FlinkPreparingTableBase;
+import org.apache.flink.table.planner.plan.schema.TableSourceTable;
+import org.apache.flink.table.planner.plan.stats.FlinkStatistic;
+
+import org.apache.calcite.plan.RelOptRule;
+import org.apache.calcite.plan.RelOptRuleCall;
+import org.apache.calcite.rel.core.Sort;
+import org.apache.calcite.rex.RexLiteral;
+
+import java.util.Arrays;
+import java.util.Collections;
+
+/**
+ * Planner rule that tries to push limit into a {@link FlinkLogicalTableSourceScan},
+ * which table is a {@link TableSourceTable}. And the table source in the table is a {@link SupportsLimitPushDown}.
+ * The original limit will still be retained.
+ * The reasons why the limit still be retained:
+ * 1.If the source is required to return the exact number of limit number, the implementation
+ * of the source is highly required. The source is required to accurately control the record
+ * number of split, and the parallelism setting also need to be adjusted accordingly.
+ * 2.When remove the limit, maybe filter will be pushed down to the source after limit pushed
+ * down. The source need know it should do limit first and do the filter later, it is hard to
+ * implement.
+ * 3.We can support limit with offset, we can push down offset + fetch to table source.
+ */
+public class PushLimitIntoTableSourceScanRule extends RelOptRule {
+	public static final PushLimitIntoTableSourceScanRule INSTANCE = new PushLimitIntoTableSourceScanRule();
+
+	public PushLimitIntoTableSourceScanRule() {
+		super(operand(FlinkLogicalSort.class,
+			operand(FlinkLogicalTableSourceScan.class, none())),
+			"PushLimitIntoTableSourceScanRule");
+	}
+
+	@Override
+	public boolean matches(RelOptRuleCall call) {
+		Sort sort = call.rel(0);
+		TableSourceTable tableSourceTable = call.rel(1).getTable().unwrap(TableSourceTable.class);
+
+		// a limit can be pushed down only if it satisfies the two conditions: 1) do not have order by keys, 2) have limit.
+		boolean onlyLimit = sort.getCollation().getFieldCollations().isEmpty() && sort.fetch != null;
+		return onlyLimit
+			&& tableSourceTable != null
+			&& tableSourceTable.tableSource() instanceof SupportsLimitPushDown
+			&& Arrays.stream(tableSourceTable.extraDigests()).noneMatch(str -> str.startsWith("limit=["));
+	}
+
+	@Override
+	public void onMatch(RelOptRuleCall call) {
+		Sort sort = call.rel(0);
+		FlinkLogicalTableSourceScan scan = call.rel(1);
+		TableSourceTable tableSourceTable = scan.getTable().unwrap(TableSourceTable.class);
+		int offset = sort.offset == null ? 0 : RexLiteral.intValue(sort.offset);
+		int limit = offset + RexLiteral.intValue(sort.fetch);
+
+		TableSourceTable newTableSourceTable = applyLimit(limit, tableSourceTable);
+
+		FlinkLogicalTableSourceScan newScan = FlinkLogicalTableSourceScan.create(scan.getCluster(), newTableSourceTable);
+		Sort newSort = sort.copy(sort.getTraitSet(), Collections.singletonList(newScan));
+		call.transformTo(newSort);
+	}
+
+	private TableSourceTable applyLimit(
+		long limit,
+		FlinkPreparingTableBase relOptTable) {
+		TableSourceTable oldTableSourceTable = relOptTable.unwrap(TableSourceTable.class);
+		DynamicTableSource newTableSource = oldTableSourceTable.tableSource().copy();
+		((SupportsLimitPushDown) newTableSource).applyLimit(limit);
+
+		FlinkStatistic statistic = relOptTable.getStatistic();
+		long newRowCount = 0;
+		if (statistic.getRowCount() != null) {
+			newRowCount = Math.min(limit, statistic.getRowCount().longValue());
+		} else {
+			newRowCount = limit;
+		}
+		// update TableStats after limit push down
+		TableStats newTableStats = new TableStats(newRowCount);
+		FlinkStatistic newStatistic = FlinkStatistic.builder()
+			.statistic(statistic)
+			.tableStats(newTableStats)
+			.build();
+
+		// update extraDigests
+		String[] newExtraDigests = new String[0];
+		if (limit >= 0) {

Review comment:
       how about we remove the `if` ?

##########
File path: flink-table/flink-table-planner-blink/src/test/resources/org/apache/flink/table/planner/plan/rules/logical/PushLimitIntoLegacyTableSourceScanRuleTest.xml
##########
@@ -0,0 +1,171 @@
+<?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="testCanPushdownLimitWithoutOffset">
+		<Resource name="sql">
+			<![CDATA[SELECT * FROM LimitTable LIMIT 5]]>
+		</Resource>
+		<Resource name="planBefore">
+			<![CDATA[
+LogicalSort(fetch=[5])
++- LogicalProject(a=[$0], b=[$1], c=[$2])
+   +- LogicalTableScan(table=[[default_catalog, default_database, LimitTable]])
+]]>
+		</Resource>
+		<Resource name="planAfter">
+			<![CDATA[
+LogicalProject(a=[$0], b=[$1], c=[$2])
++- FlinkLogicalSort(fetch=[5])
+   +- FlinkLogicalLegacyTableSourceScan(table=[[default_catalog, default_database, LimitTable, source: [limit: 5]]], fields=[a, b, c])

Review comment:
       why the digest pattern is not `limit=5` ?

##########
File path: flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/planner/plan/rules/logical/PushLimitIntoLegacyTableSourceScanRuleTest.scala
##########
@@ -0,0 +1,116 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.flink.table.planner.plan.rules.logical
+
+import org.apache.calcite.plan.hep.HepMatchOrder
+import org.apache.calcite.rel.rules.SortProjectTransposeRule
+import org.apache.calcite.tools.RuleSets
+import org.apache.flink.table.api.SqlParserException
+import org.apache.flink.table.planner.plan.nodes.logical.{FlinkLogicalLegacyTableSourceScan, FlinkLogicalSort}
+import org.apache.flink.table.planner.plan.optimize.program.{FlinkBatchProgram, FlinkHepRuleSetProgramBuilder, HEP_RULES_EXECUTION_TYPE}
+import org.apache.flink.table.planner.utils.{TableConfigUtils, TableTestBase}
+import org.junit.{Before, Test}
+
+/**
+ * Test for [[PushLimitIntoLegacyTableSourceScanRule]].
+ */
+class PushLimitIntoLegacyTableSourceScanRuleTest extends TableTestBase {
+  protected val util = batchTestUtil()
+
+  @Before
+  def setup(): Unit = {
+    util.buildBatchProgram(FlinkBatchProgram.DEFAULT_REWRITE)
+    val calciteConfig = TableConfigUtils.getCalciteConfig(util.tableEnv.getConfig)
+    calciteConfig.getBatchProgram.get.addLast(
+      "rules",
+      FlinkHepRuleSetProgramBuilder.newBuilder
+        .setHepRulesExecutionType(HEP_RULES_EXECUTION_TYPE.RULE_COLLECTION)
+        .setHepMatchOrder(HepMatchOrder.BOTTOM_UP)
+        .add(RuleSets.ofList(PushLimitIntoLegacyTableSourceScanRule.INSTANCE,
+          SortProjectTransposeRule.INSTANCE,
+          // converts calcite rel(RelNode) to flink rel(FlinkRelNode)
+          FlinkLogicalSort.BATCH_CONVERTER,
+          FlinkLogicalLegacyTableSourceScan.CONVERTER))
+        .build()
+    )
+
+    val ddl =
+      s"""
+         |CREATE TABLE LimitTable (
+         |  a int,
+         |  b bigint,
+         |  c string
+         |) WITH (
+         |  'connector.type' = 'TestLimitableTableSource',
+         |  'is-bounded' = 'true'
+         |)
+       """.stripMargin
+    util.tableEnv.executeSql(ddl)
+  }
+
+  @Test(expected = classOf[SqlParserException])
+  def testLimitWithNegativeOffset(): Unit = {
+    util.verifyPlan("SELECT a, c FROM LimitTable LIMIT 10 OFFSET -1")
+  }
+
+  @Test(expected = classOf[SqlParserException])
+  def testNegativeLimitWithoutOffset(): Unit = {
+    util.verifyPlan("SELECT * FROM LimitTable LIMIT -1")
+  }
+
+  @Test(expected = classOf[SqlParserException])
+  def testMysqlLimit(): Unit = {
+    util.verifyPlan("SELECT a, c FROM LimitTable LIMIT 1, 10")
+  }
+
+  @Test
+  def testCanPushdownLimitWithoutOffset(): Unit = {
+    util.verifyPlan("SELECT * FROM LimitTable LIMIT 5")
+  }
+
+  @Test
+  def testCanPushdownLimitWithOffset(): Unit = {
+    util.verifyPlan("SELECT a, c FROM LimitTable LIMIT 10 OFFSET 1")
+  }
+
+  @Test
+  def testCanPushdownFetchWithOffset(): Unit = {
+    util.verifyPlan("SELECT a, c FROM LimitTable OFFSET 10 ROWS FETCH NEXT 10 ROWS ONLY")
+  }
+
+  @Test
+  def testCanPushdownFetchWithoutOffset(): Unit = {
+    util.verifyPlan("SELECT a, c FROM LimitTable FETCH FIRST 10 ROWS ONLY")
+  }
+
+  @Test
+  def testCannotPushDownWithoutLimit(): Unit = {

Review comment:
       nit: unify the case of `Pushdown` ?




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

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



[GitHub] [flink] flinkbot commented on pull request #12964: [FLINK-17426][blink plannger] Dynamic Source supportsLimit pushdown

Posted by GitBox <gi...@apache.org>.
flinkbot commented on pull request #12964:
URL: https://github.com/apache/flink/pull/12964#issuecomment-662788621


   Thanks a lot for your contribution to the Apache Flink project. I'm the @flinkbot. I help the community
   to review your pull request. We will use this comment to track the progress of the review.
   
   
   ## Automated Checks
   Last check on commit 984b8a182e5a5cc64a9e1957710e9b9fd4768a56 (Thu Jul 23 02:22:57 UTC 2020)
   
   **Warnings:**
    * No documentation files were touched! Remember to keep the Flink docs up to date!
   
   
   <sub>Mention the bot in a comment to re-run the automated checks.</sub>
   ## Review Progress
   
   * ā“ 1. The [description] looks good.
   * ā“ 2. There is [consensus] that the contribution should go into to Flink.
   * ā“ 3. Needs [attention] from.
   * ā“ 4. The change fits into the overall [architecture].
   * ā“ 5. Overall code [quality] is good.
   
   Please see the [Pull Request Review Guide](https://flink.apache.org/contributing/reviewing-prs.html) for a full explanation of the review process.<details>
    The Bot is tracking the review progress through labels. Labels are applied according to the order of the review items. For consensus, approval by a Flink committer of PMC member is required <summary>Bot commands</summary>
     The @flinkbot bot supports the following commands:
   
    - `@flinkbot approve description` to approve one or more aspects (aspects: `description`, `consensus`, `architecture` and `quality`)
    - `@flinkbot approve all` to approve all aspects
    - `@flinkbot approve-until architecture` to approve everything until `architecture`
    - `@flinkbot attention @username1 [@username2 ..]` to require somebody's attention
    - `@flinkbot disapprove architecture` to remove an approval you gave earlier
   </details>


----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

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



[GitHub] [flink] flinkbot edited a comment on pull request #12964: [FLINK-17426][blink planner] Dynamic Source supportsLimit pushdown

Posted by GitBox <gi...@apache.org>.
flinkbot edited a comment on pull request #12964:
URL: https://github.com/apache/flink/pull/12964#issuecomment-662793989


   <!--
   Meta data
   {
     "version" : 1,
     "metaDataEntries" : [ {
       "hash" : "984b8a182e5a5cc64a9e1957710e9b9fd4768a56",
       "status" : "DELETED",
       "url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=4751",
       "triggerID" : "984b8a182e5a5cc64a9e1957710e9b9fd4768a56",
       "triggerType" : "PUSH"
     }, {
       "hash" : "0324c22a9b2c85f04481966b2a78f72e92b9c88c",
       "status" : "DELETED",
       "url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=4917",
       "triggerID" : "0324c22a9b2c85f04481966b2a78f72e92b9c88c",
       "triggerType" : "PUSH"
     }, {
       "hash" : "141bd8e09efe79e55398adbdd0916592231fdfbf",
       "status" : "DELETED",
       "url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=4958",
       "triggerID" : "141bd8e09efe79e55398adbdd0916592231fdfbf",
       "triggerType" : "PUSH"
     }, {
       "hash" : "34dd37d992e9d3c3a0bf92e660575571d83b407c",
       "status" : "SUCCESS",
       "url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=5034",
       "triggerID" : "34dd37d992e9d3c3a0bf92e660575571d83b407c",
       "triggerType" : "PUSH"
     } ]
   }-->
   ## CI report:
   
   * 34dd37d992e9d3c3a0bf92e660575571d83b407c Azure: [SUCCESS](https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=5034) 
   
   <details>
   <summary>Bot commands</summary>
     The @flinkbot bot supports the following commands:
   
    - `@flinkbot run travis` re-run the last Travis build
    - `@flinkbot run azure` re-run the last Azure build
   </details>


----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

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



[GitHub] [flink] liuyongvs commented on a change in pull request #12964: [FLINK-17426][blink plannger] Dynamic Source supportsLimit pushdown

Posted by GitBox <gi...@apache.org>.
liuyongvs commented on a change in pull request #12964:
URL: https://github.com/apache/flink/pull/12964#discussion_r459916120



##########
File path: flink-table/flink-table-planner-blink/src/main/java/org/apache/flink/table/planner/plan/rules/logical/PushLimitIntoTableSourceScanRule.java
##########
@@ -0,0 +1,121 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.table.planner.plan.rules.logical;
+
+import org.apache.flink.table.connector.source.DynamicTableSource;
+import org.apache.flink.table.connector.source.abilities.SupportsLimitPushDown;
+import org.apache.flink.table.plan.stats.TableStats;
+import org.apache.flink.table.planner.plan.nodes.logical.FlinkLogicalSort;
+import org.apache.flink.table.planner.plan.nodes.logical.FlinkLogicalTableSourceScan;
+import org.apache.flink.table.planner.plan.schema.FlinkPreparingTableBase;
+import org.apache.flink.table.planner.plan.schema.TableSourceTable;
+import org.apache.flink.table.planner.plan.stats.FlinkStatistic;
+
+import org.apache.calcite.plan.RelOptRule;
+import org.apache.calcite.plan.RelOptRuleCall;
+import org.apache.calcite.rel.core.Sort;
+import org.apache.calcite.rex.RexLiteral;
+
+import java.util.Arrays;
+import java.util.Collections;
+
+/**
+ * Planner rule that tries to push limit into a {@link FlinkLogicalTableSourceScan},
+ * which table is a {@link TableSourceTable}. And the table source in the table is a {@link SupportsLimitPushDown}.
+ * The original limit will still be retained.
+ * The reasons why the limit still be retained:
+ * 1.If the source is required to return the exact number of limit number, the implementation
+ * of the source is highly required. The source is required to accurately control the record
+ * number of split, and the parallelism setting also need to be adjusted accordingly.
+ * 2.When remove the limit, maybe filter will be pushed down to the source after limit pushed
+ * down. The source need know it should do limit first and do the filter later, it is hard to
+ * implement.
+ * 3.We can support limit with offset, we can push down offset + fetch to table source.
+ */
+public class PushLimitIntoTableSourceScanRule extends RelOptRule {
+	public static final PushLimitIntoTableSourceScanRule INSTANCE = new PushLimitIntoTableSourceScanRule();
+
+	public PushLimitIntoTableSourceScanRule() {
+		super(operand(FlinkLogicalSort.class,
+			operand(FlinkLogicalTableSourceScan.class, none())),
+			"PushLimitIntoTableSourceScanRule");
+	}
+
+	@Override
+	public boolean matches(RelOptRuleCall call) {
+		Sort sort = call.rel(0);
+		TableSourceTable tableSourceTable = call.rel(1).getTable().unwrap(TableSourceTable.class);
+
+		// a limit can be pushed down only if it satisfies the two conditions: 1) do not have order by keys, 2) have limit.
+		boolean onlyLimit = sort.getCollation().getFieldCollations().isEmpty() && sort.fetch != null;
+		return onlyLimit
+			&& tableSourceTable != null
+			&& tableSourceTable.tableSource() instanceof SupportsLimitPushDown
+			&& !Arrays.stream(tableSourceTable.extraDigests()).anyMatch(str -> str.startsWith("limit=["));
+	}
+
+	@Override
+	public void onMatch(RelOptRuleCall call) {
+		Sort sort = call.rel(0);
+		FlinkLogicalTableSourceScan scan = call.rel(1);
+		TableSourceTable tableSourceTable = scan.getTable().unwrap(TableSourceTable.class);
+		int offset = sort.offset == null ? 0 : RexLiteral.intValue(sort.offset);
+		int limit = offset + RexLiteral.intValue(sort.fetch);
+
+		TableSourceTable newTableSourceTable = applyLimit(limit, tableSourceTable);
+
+		FlinkLogicalTableSourceScan newScan = FlinkLogicalTableSourceScan.create(scan.getCluster(), newTableSourceTable);
+		call.transformTo(sort.copy(sort.getTraitSet(), Collections.singletonList(newScan)));
+	}
+
+	private TableSourceTable applyLimit(
+		long limit,
+		FlinkPreparingTableBase relOptTable) {
+		TableSourceTable oldTableSourceTable = relOptTable.unwrap(TableSourceTable.class);
+		DynamicTableSource newTableSource = oldTableSourceTable.tableSource().copy();
+		((SupportsLimitPushDown) newTableSource).applyLimit(limit);
+
+		FlinkStatistic statistic = relOptTable.getStatistic();
+		long newRowCount = 0;
+		if (statistic.getRowCount() != null) {
+			newRowCount = Math.min(limit, statistic.getRowCount().longValue());
+		} else {
+			newRowCount = limit;
+		}
+		// update TableStats after limit push down
+		TableStats newTableStats = new TableStats(newRowCount);
+		FlinkStatistic newStatistic = FlinkStatistic.builder()
+			.statistic(statistic)
+			.tableStats(newTableStats)
+			.build();
+
+		// update extraDigests
+		String[] newExtraDigests = new String[0];
+		if (limit > 0) {

Review comment:
       But it will look strange, like this limit=[0] And this rule FlinkLimit0RemoveRule will remove it. 




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

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



[GitHub] [flink] wuchong merged pull request #12964: [FLINK-17426][blink planner] Dynamic Source supportsLimit pushdown

Posted by GitBox <gi...@apache.org>.
wuchong merged pull request #12964:
URL: https://github.com/apache/flink/pull/12964


   


----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

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



[GitHub] [flink] flinkbot edited a comment on pull request #12964: [FLINK-17426][blink plannger] Dynamic Source supportsLimit pushdown

Posted by GitBox <gi...@apache.org>.
flinkbot edited a comment on pull request #12964:
URL: https://github.com/apache/flink/pull/12964#issuecomment-662793989


   <!--
   Meta data
   {
     "version" : 1,
     "metaDataEntries" : [ {
       "hash" : "984b8a182e5a5cc64a9e1957710e9b9fd4768a56",
       "status" : "SUCCESS",
       "url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=4751",
       "triggerID" : "984b8a182e5a5cc64a9e1957710e9b9fd4768a56",
       "triggerType" : "PUSH"
     } ]
   }-->
   ## CI report:
   
   * 984b8a182e5a5cc64a9e1957710e9b9fd4768a56 Azure: [SUCCESS](https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=4751) 
   
   <details>
   <summary>Bot commands</summary>
     The @flinkbot bot supports the following commands:
   
    - `@flinkbot run travis` re-run the last Travis build
    - `@flinkbot run azure` re-run the last Azure build
   </details>


----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

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



[GitHub] [flink] flinkbot commented on pull request #12964: [FLINK-17426][blink plannger] Dynamic Source supportsLimit pushdown

Posted by GitBox <gi...@apache.org>.
flinkbot commented on pull request #12964:
URL: https://github.com/apache/flink/pull/12964#issuecomment-662793989


   <!--
   Meta data
   {
     "version" : 1,
     "metaDataEntries" : [ {
       "hash" : "984b8a182e5a5cc64a9e1957710e9b9fd4768a56",
       "status" : "UNKNOWN",
       "url" : "TBD",
       "triggerID" : "984b8a182e5a5cc64a9e1957710e9b9fd4768a56",
       "triggerType" : "PUSH"
     } ]
   }-->
   ## CI report:
   
   * 984b8a182e5a5cc64a9e1957710e9b9fd4768a56 UNKNOWN
   
   <details>
   <summary>Bot commands</summary>
     The @flinkbot bot supports the following commands:
   
    - `@flinkbot run travis` re-run the last Travis build
    - `@flinkbot run azure` re-run the last Azure build
   </details>


----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

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



[GitHub] [flink] flinkbot edited a comment on pull request #12964: [FLINK-17426][blink planner] Dynamic Source supportsLimit pushdown

Posted by GitBox <gi...@apache.org>.
flinkbot edited a comment on pull request #12964:
URL: https://github.com/apache/flink/pull/12964#issuecomment-662793989






----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

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



[GitHub] [flink] liuyongvs commented on a change in pull request #12964: [FLINK-17426][blink plannger] Dynamic Source supportsLimit pushdown

Posted by GitBox <gi...@apache.org>.
liuyongvs commented on a change in pull request #12964:
URL: https://github.com/apache/flink/pull/12964#discussion_r461479018



##########
File path: flink-table/flink-table-planner-blink/src/test/resources/org/apache/flink/table/planner/plan/rules/logical/PushLimitIntoLegacyTableSourceScanRuleTest.xml
##########
@@ -0,0 +1,171 @@
+<?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="testCanPushdownLimitWithoutOffset">
+		<Resource name="sql">
+			<![CDATA[SELECT * FROM LimitTable LIMIT 5]]>
+		</Resource>
+		<Resource name="planBefore">
+			<![CDATA[
+LogicalSort(fetch=[5])
++- LogicalProject(a=[$0], b=[$1], c=[$2])
+   +- LogicalTableScan(table=[[default_catalog, default_database, LimitTable]])
+]]>
+		</Resource>
+		<Resource name="planAfter">
+			<![CDATA[
+LogicalProject(a=[$0], b=[$1], c=[$2])
++- FlinkLogicalSort(fetch=[5])
+   +- FlinkLogicalLegacyTableSourceScan(table=[[default_catalog, default_database, LimitTable, source: [limit: 5]]], fields=[a, b, c])

Review comment:
       This is PushLimitInto**Legacy**TableSourceScanRuleTest, which is legacy Rule.And read the code of TestLegacyLimitableTableSource.explainSource. You can compare the PushProjectIntoLegacyTableSourceScanRuleTest and PushProjectIntoTableSourceScanRuleTest. And there are the same.
   new: LogicalTableScan(table=[[default_catalog, default_database, MyTable, project=[a, c]]])
   Legacy: LogicalTableScan(table=[[default_catalog, default_database, MyTable, source: [TestSource(physical fields: a, c)]]])

##########
File path: flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/planner/plan/rules/logical/PushLimitIntoLegacyTableSourceScanRuleTest.scala
##########
@@ -0,0 +1,116 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.flink.table.planner.plan.rules.logical
+
+import org.apache.calcite.plan.hep.HepMatchOrder
+import org.apache.calcite.rel.rules.SortProjectTransposeRule
+import org.apache.calcite.tools.RuleSets
+import org.apache.flink.table.api.SqlParserException
+import org.apache.flink.table.planner.plan.nodes.logical.{FlinkLogicalLegacyTableSourceScan, FlinkLogicalSort}
+import org.apache.flink.table.planner.plan.optimize.program.{FlinkBatchProgram, FlinkHepRuleSetProgramBuilder, HEP_RULES_EXECUTION_TYPE}
+import org.apache.flink.table.planner.utils.{TableConfigUtils, TableTestBase}
+import org.junit.{Before, Test}
+
+/**
+ * Test for [[PushLimitIntoLegacyTableSourceScanRule]].
+ */
+class PushLimitIntoLegacyTableSourceScanRuleTest extends TableTestBase {
+  protected val util = batchTestUtil()
+
+  @Before
+  def setup(): Unit = {
+    util.buildBatchProgram(FlinkBatchProgram.DEFAULT_REWRITE)
+    val calciteConfig = TableConfigUtils.getCalciteConfig(util.tableEnv.getConfig)
+    calciteConfig.getBatchProgram.get.addLast(
+      "rules",
+      FlinkHepRuleSetProgramBuilder.newBuilder
+        .setHepRulesExecutionType(HEP_RULES_EXECUTION_TYPE.RULE_COLLECTION)
+        .setHepMatchOrder(HepMatchOrder.BOTTOM_UP)
+        .add(RuleSets.ofList(PushLimitIntoLegacyTableSourceScanRule.INSTANCE,
+          SortProjectTransposeRule.INSTANCE,
+          // converts calcite rel(RelNode) to flink rel(FlinkRelNode)
+          FlinkLogicalSort.BATCH_CONVERTER,
+          FlinkLogicalLegacyTableSourceScan.CONVERTER))
+        .build()
+    )
+
+    val ddl =
+      s"""
+         |CREATE TABLE LimitTable (
+         |  a int,
+         |  b bigint,
+         |  c string
+         |) WITH (
+         |  'connector.type' = 'TestLimitableTableSource',
+         |  'is-bounded' = 'true'
+         |)
+       """.stripMargin
+    util.tableEnv.executeSql(ddl)
+  }
+
+  @Test(expected = classOf[SqlParserException])
+  def testLimitWithNegativeOffset(): Unit = {
+    util.verifyPlan("SELECT a, c FROM LimitTable LIMIT 10 OFFSET -1")
+  }
+
+  @Test(expected = classOf[SqlParserException])
+  def testNegativeLimitWithoutOffset(): Unit = {
+    util.verifyPlan("SELECT * FROM LimitTable LIMIT -1")
+  }
+
+  @Test(expected = classOf[SqlParserException])
+  def testMysqlLimit(): Unit = {
+    util.verifyPlan("SELECT a, c FROM LimitTable LIMIT 1, 10")
+  }
+
+  @Test
+  def testCanPushdownLimitWithoutOffset(): Unit = {
+    util.verifyPlan("SELECT * FROM LimitTable LIMIT 5")
+  }
+
+  @Test
+  def testCanPushdownLimitWithOffset(): Unit = {
+    util.verifyPlan("SELECT a, c FROM LimitTable LIMIT 10 OFFSET 1")
+  }
+
+  @Test
+  def testCanPushdownFetchWithOffset(): Unit = {
+    util.verifyPlan("SELECT a, c FROM LimitTable OFFSET 10 ROWS FETCH NEXT 10 ROWS ONLY")
+  }
+
+  @Test
+  def testCanPushdownFetchWithoutOffset(): Unit = {
+    util.verifyPlan("SELECT a, c FROM LimitTable FETCH FIRST 10 ROWS ONLY")
+  }
+
+  @Test
+  def testCannotPushDownWithoutLimit(): Unit = {

Review comment:
       ok

##########
File path: flink-table/flink-table-planner-blink/src/main/java/org/apache/flink/table/planner/plan/rules/logical/PushLimitIntoTableSourceScanRule.java
##########
@@ -0,0 +1,122 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.table.planner.plan.rules.logical;
+
+import org.apache.flink.table.connector.source.DynamicTableSource;
+import org.apache.flink.table.connector.source.abilities.SupportsLimitPushDown;
+import org.apache.flink.table.plan.stats.TableStats;
+import org.apache.flink.table.planner.plan.nodes.logical.FlinkLogicalSort;
+import org.apache.flink.table.planner.plan.nodes.logical.FlinkLogicalTableSourceScan;
+import org.apache.flink.table.planner.plan.schema.FlinkPreparingTableBase;
+import org.apache.flink.table.planner.plan.schema.TableSourceTable;
+import org.apache.flink.table.planner.plan.stats.FlinkStatistic;
+
+import org.apache.calcite.plan.RelOptRule;
+import org.apache.calcite.plan.RelOptRuleCall;
+import org.apache.calcite.rel.core.Sort;
+import org.apache.calcite.rex.RexLiteral;
+
+import java.util.Arrays;
+import java.util.Collections;
+
+/**
+ * Planner rule that tries to push limit into a {@link FlinkLogicalTableSourceScan},
+ * which table is a {@link TableSourceTable}. And the table source in the table is a {@link SupportsLimitPushDown}.
+ * The original limit will still be retained.
+ * The reasons why the limit still be retained:
+ * 1.If the source is required to return the exact number of limit number, the implementation
+ * of the source is highly required. The source is required to accurately control the record
+ * number of split, and the parallelism setting also need to be adjusted accordingly.
+ * 2.When remove the limit, maybe filter will be pushed down to the source after limit pushed
+ * down. The source need know it should do limit first and do the filter later, it is hard to
+ * implement.
+ * 3.We can support limit with offset, we can push down offset + fetch to table source.
+ */
+public class PushLimitIntoTableSourceScanRule extends RelOptRule {
+	public static final PushLimitIntoTableSourceScanRule INSTANCE = new PushLimitIntoTableSourceScanRule();
+
+	public PushLimitIntoTableSourceScanRule() {
+		super(operand(FlinkLogicalSort.class,
+			operand(FlinkLogicalTableSourceScan.class, none())),
+			"PushLimitIntoTableSourceScanRule");
+	}
+
+	@Override
+	public boolean matches(RelOptRuleCall call) {
+		Sort sort = call.rel(0);
+		TableSourceTable tableSourceTable = call.rel(1).getTable().unwrap(TableSourceTable.class);
+
+		// a limit can be pushed down only if it satisfies the two conditions: 1) do not have order by keys, 2) have limit.
+		boolean onlyLimit = sort.getCollation().getFieldCollations().isEmpty() && sort.fetch != null;
+		return onlyLimit
+			&& tableSourceTable != null
+			&& tableSourceTable.tableSource() instanceof SupportsLimitPushDown
+			&& Arrays.stream(tableSourceTable.extraDigests()).noneMatch(str -> str.startsWith("limit=["));
+	}
+
+	@Override
+	public void onMatch(RelOptRuleCall call) {
+		Sort sort = call.rel(0);
+		FlinkLogicalTableSourceScan scan = call.rel(1);
+		TableSourceTable tableSourceTable = scan.getTable().unwrap(TableSourceTable.class);
+		int offset = sort.offset == null ? 0 : RexLiteral.intValue(sort.offset);
+		int limit = offset + RexLiteral.intValue(sort.fetch);
+
+		TableSourceTable newTableSourceTable = applyLimit(limit, tableSourceTable);
+
+		FlinkLogicalTableSourceScan newScan = FlinkLogicalTableSourceScan.create(scan.getCluster(), newTableSourceTable);
+		Sort newSort = sort.copy(sort.getTraitSet(), Collections.singletonList(newScan));
+		call.transformTo(newSort);
+	}
+
+	private TableSourceTable applyLimit(
+		long limit,
+		FlinkPreparingTableBase relOptTable) {
+		TableSourceTable oldTableSourceTable = relOptTable.unwrap(TableSourceTable.class);
+		DynamicTableSource newTableSource = oldTableSourceTable.tableSource().copy();
+		((SupportsLimitPushDown) newTableSource).applyLimit(limit);
+
+		FlinkStatistic statistic = relOptTable.getStatistic();
+		long newRowCount = 0;
+		if (statistic.getRowCount() != null) {
+			newRowCount = Math.min(limit, statistic.getRowCount().longValue());
+		} else {
+			newRowCount = limit;
+		}
+		// update TableStats after limit push down
+		TableStats newTableStats = new TableStats(newRowCount);
+		FlinkStatistic newStatistic = FlinkStatistic.builder()
+			.statistic(statistic)
+			.tableStats(newTableStats)
+			.build();
+
+		// update extraDigests
+		String[] newExtraDigests = new String[0];
+		if (limit >= 0) {

Review comment:
       I think it can not remove it. Although, it doesn't have problem now. But if the calcite supports this syntax limit x,y, which is the mysql limit offset syntax. y represents limit, which can be negative, such as -1 , you can refer this https://www.cnblogs.com/acm-bingzi/p/msqlLimit.html.
   And you can also read the code of calcite FlinkSqlParserImpl.OrderedQueryOrExpr, where has some comments.
   That is the reason why i add this test testMysqlLimit.

##########
File path: flink-table/flink-table-planner-blink/src/main/java/org/apache/flink/table/planner/plan/rules/logical/PushLimitIntoTableSourceScanRule.java
##########
@@ -0,0 +1,122 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.table.planner.plan.rules.logical;
+
+import org.apache.flink.table.connector.source.DynamicTableSource;
+import org.apache.flink.table.connector.source.abilities.SupportsLimitPushDown;
+import org.apache.flink.table.plan.stats.TableStats;
+import org.apache.flink.table.planner.plan.nodes.logical.FlinkLogicalSort;
+import org.apache.flink.table.planner.plan.nodes.logical.FlinkLogicalTableSourceScan;
+import org.apache.flink.table.planner.plan.schema.FlinkPreparingTableBase;
+import org.apache.flink.table.planner.plan.schema.TableSourceTable;
+import org.apache.flink.table.planner.plan.stats.FlinkStatistic;
+
+import org.apache.calcite.plan.RelOptRule;
+import org.apache.calcite.plan.RelOptRuleCall;
+import org.apache.calcite.rel.core.Sort;
+import org.apache.calcite.rex.RexLiteral;
+
+import java.util.Arrays;
+import java.util.Collections;
+
+/**
+ * Planner rule that tries to push limit into a {@link FlinkLogicalTableSourceScan},
+ * which table is a {@link TableSourceTable}. And the table source in the table is a {@link SupportsLimitPushDown}.
+ * The original limit will still be retained.
+ * The reasons why the limit still be retained:
+ * 1.If the source is required to return the exact number of limit number, the implementation
+ * of the source is highly required. The source is required to accurately control the record
+ * number of split, and the parallelism setting also need to be adjusted accordingly.
+ * 2.When remove the limit, maybe filter will be pushed down to the source after limit pushed
+ * down. The source need know it should do limit first and do the filter later, it is hard to
+ * implement.
+ * 3.We can support limit with offset, we can push down offset + fetch to table source.
+ */
+public class PushLimitIntoTableSourceScanRule extends RelOptRule {
+	public static final PushLimitIntoTableSourceScanRule INSTANCE = new PushLimitIntoTableSourceScanRule();
+
+	public PushLimitIntoTableSourceScanRule() {
+		super(operand(FlinkLogicalSort.class,
+			operand(FlinkLogicalTableSourceScan.class, none())),
+			"PushLimitIntoTableSourceScanRule");
+	}
+
+	@Override
+	public boolean matches(RelOptRuleCall call) {
+		Sort sort = call.rel(0);
+		TableSourceTable tableSourceTable = call.rel(1).getTable().unwrap(TableSourceTable.class);
+
+		// a limit can be pushed down only if it satisfies the two conditions: 1) do not have order by keys, 2) have limit.
+		boolean onlyLimit = sort.getCollation().getFieldCollations().isEmpty() && sort.fetch != null;
+		return onlyLimit
+			&& tableSourceTable != null
+			&& tableSourceTable.tableSource() instanceof SupportsLimitPushDown
+			&& Arrays.stream(tableSourceTable.extraDigests()).noneMatch(str -> str.startsWith("limit=["));
+	}
+
+	@Override
+	public void onMatch(RelOptRuleCall call) {
+		Sort sort = call.rel(0);
+		FlinkLogicalTableSourceScan scan = call.rel(1);
+		TableSourceTable tableSourceTable = scan.getTable().unwrap(TableSourceTable.class);
+		int offset = sort.offset == null ? 0 : RexLiteral.intValue(sort.offset);
+		int limit = offset + RexLiteral.intValue(sort.fetch);
+
+		TableSourceTable newTableSourceTable = applyLimit(limit, tableSourceTable);
+
+		FlinkLogicalTableSourceScan newScan = FlinkLogicalTableSourceScan.create(scan.getCluster(), newTableSourceTable);
+		Sort newSort = sort.copy(sort.getTraitSet(), Collections.singletonList(newScan));
+		call.transformTo(newSort);
+	}
+
+	private TableSourceTable applyLimit(
+		long limit,
+		FlinkPreparingTableBase relOptTable) {
+		TableSourceTable oldTableSourceTable = relOptTable.unwrap(TableSourceTable.class);
+		DynamicTableSource newTableSource = oldTableSourceTable.tableSource().copy();
+		((SupportsLimitPushDown) newTableSource).applyLimit(limit);
+
+		FlinkStatistic statistic = relOptTable.getStatistic();
+		long newRowCount = 0;
+		if (statistic.getRowCount() != null) {
+			newRowCount = Math.min(limit, statistic.getRowCount().longValue());
+		} else {
+			newRowCount = limit;
+		}
+		// update TableStats after limit push down
+		TableStats newTableStats = new TableStats(newRowCount);
+		FlinkStatistic newStatistic = FlinkStatistic.builder()
+			.statistic(statistic)
+			.tableStats(newTableStats)
+			.build();
+
+		// update extraDigests
+		String[] newExtraDigests = new String[0];
+		if (limit >= 0) {

Review comment:
       I think it can not be removed. Although, it doesn't have problem now. But if the calcite supports this syntax limit x,y, which is the mysql limit offset syntax. y represents limit, which can be negative, such as -1 , you can refer this https://www.cnblogs.com/acm-bingzi/p/msqlLimit.html.
   And you can also read the code of calcite FlinkSqlParserImpl.OrderedQueryOrExpr, where has some comments.
   That is the reason why i add this test testMysqlLimit.

##########
File path: flink-table/flink-table-planner-blink/src/test/resources/org/apache/flink/table/planner/plan/rules/logical/PushLimitIntoLegacyTableSourceScanRuleTest.xml
##########
@@ -0,0 +1,171 @@
+<?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="testCanPushdownLimitWithoutOffset">
+		<Resource name="sql">
+			<![CDATA[SELECT * FROM LimitTable LIMIT 5]]>
+		</Resource>
+		<Resource name="planBefore">
+			<![CDATA[
+LogicalSort(fetch=[5])
++- LogicalProject(a=[$0], b=[$1], c=[$2])
+   +- LogicalTableScan(table=[[default_catalog, default_database, LimitTable]])
+]]>
+		</Resource>
+		<Resource name="planAfter">
+			<![CDATA[
+LogicalProject(a=[$0], b=[$1], c=[$2])
++- FlinkLogicalSort(fetch=[5])
+   +- FlinkLogicalLegacyTableSourceScan(table=[[default_catalog, default_database, LimitTable, source: [limit: 5]]], fields=[a, b, c])

Review comment:
       This is PushLimitInto**Legacy**TableSourceScanRuleTest, which is legacy Rule.And read the code of TestLegacyLimitableTableSource.explainSource. You can compare the PushProjectIntoLegacyTableSourceScanRuleTest and PushProjectIntoTableSourceScanRuleTest. And there are the same.
   **new:** LogicalTableScan(table=[[default_catalog, default_database, MyTable, project=[a, c]]])
   **Legacy:** LogicalTableScan(table=[[default_catalog, default_database, MyTable, source: [TestSource(physical fields: a, c)]]])




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

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



[GitHub] [flink] godfreyhe commented on a change in pull request #12964: [FLINK-17426][blink planner] Dynamic Source supportsLimit pushdown

Posted by GitBox <gi...@apache.org>.
godfreyhe commented on a change in pull request #12964:
URL: https://github.com/apache/flink/pull/12964#discussion_r462813556



##########
File path: flink-table/flink-table-planner-blink/src/main/java/org/apache/flink/table/planner/plan/rules/logical/PushLimitIntoTableSourceScanRule.java
##########
@@ -0,0 +1,118 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.table.planner.plan.rules.logical;
+
+import org.apache.flink.table.connector.source.DynamicTableSource;
+import org.apache.flink.table.connector.source.abilities.SupportsLimitPushDown;
+import org.apache.flink.table.plan.stats.TableStats;
+import org.apache.flink.table.planner.plan.nodes.logical.FlinkLogicalSort;
+import org.apache.flink.table.planner.plan.nodes.logical.FlinkLogicalTableSourceScan;
+import org.apache.flink.table.planner.plan.schema.FlinkPreparingTableBase;
+import org.apache.flink.table.planner.plan.schema.TableSourceTable;
+import org.apache.flink.table.planner.plan.stats.FlinkStatistic;
+
+import org.apache.calcite.plan.RelOptRule;
+import org.apache.calcite.plan.RelOptRuleCall;
+import org.apache.calcite.rel.core.Sort;
+import org.apache.calcite.rex.RexLiteral;
+
+import java.util.Arrays;
+import java.util.Collections;
+
+/**
+ * Planner rule that tries to push limit into a {@link FlinkLogicalTableSourceScan},
+ * which table is a {@link TableSourceTable}. And the table source in the table is a {@link SupportsLimitPushDown}.
+ * The original limit will still be retained.
+ * The reasons why the limit still be retained:
+ * 1.If the source is required to return the exact number of limit number, the implementation
+ * of the source is highly required. The source is required to accurately control the record
+ * number of split, and the parallelism setting also need to be adjusted accordingly.
+ * 2.When remove the limit, maybe filter will be pushed down to the source after limit pushed
+ * down. The source need know it should do limit first and do the filter later, it is hard to
+ * implement.
+ * 3.We can support limit with offset, we can push down offset + fetch to table source.
+ */
+public class PushLimitIntoTableSourceScanRule extends RelOptRule {
+	public static final PushLimitIntoTableSourceScanRule INSTANCE = new PushLimitIntoTableSourceScanRule();
+
+	public PushLimitIntoTableSourceScanRule() {
+		super(operand(FlinkLogicalSort.class,
+			operand(FlinkLogicalTableSourceScan.class, none())),
+			"PushLimitIntoTableSourceScanRule");
+	}
+
+	@Override
+	public boolean matches(RelOptRuleCall call) {
+		Sort sort = call.rel(0);
+		TableSourceTable tableSourceTable = call.rel(1).getTable().unwrap(TableSourceTable.class);
+
+		// a limit can be pushed down only if it satisfies the two conditions: 1) do not have order by keys, 2) have limit.
+		boolean onlyLimit = sort.getCollation().getFieldCollations().isEmpty() && sort.fetch != null;
+		return onlyLimit
+			&& tableSourceTable != null
+			&& tableSourceTable.tableSource() instanceof SupportsLimitPushDown
+			&& Arrays.stream(tableSourceTable.extraDigests()).noneMatch(str -> str.startsWith("limit=["));
+	}
+
+	@Override
+	public void onMatch(RelOptRuleCall call) {
+		Sort sort = call.rel(0);
+		FlinkLogicalTableSourceScan scan = call.rel(1);
+		TableSourceTable tableSourceTable = scan.getTable().unwrap(TableSourceTable.class);
+		int offset = sort.offset == null ? 0 : RexLiteral.intValue(sort.offset);
+		int limit = offset + RexLiteral.intValue(sort.fetch);
+
+		TableSourceTable newTableSourceTable = applyLimit(limit, tableSourceTable);
+
+		FlinkLogicalTableSourceScan newScan = FlinkLogicalTableSourceScan.create(scan.getCluster(), newTableSourceTable);
+		Sort newSort = sort.copy(sort.getTraitSet(), Collections.singletonList(newScan));
+		call.transformTo(newSort);
+	}
+
+	private TableSourceTable applyLimit(
+		long limit,
+		FlinkPreparingTableBase relOptTable) {
+		TableSourceTable oldTableSourceTable = relOptTable.unwrap(TableSourceTable.class);
+		DynamicTableSource newTableSource = oldTableSourceTable.tableSource().copy();
+		((SupportsLimitPushDown) newTableSource).applyLimit(limit);
+
+		FlinkStatistic statistic = relOptTable.getStatistic();
+		long newRowCount = 0;
+		if (statistic.getRowCount() != null) {
+			newRowCount = Math.min(limit, statistic.getRowCount().longValue());
+		} else {
+			newRowCount = limit;
+		}
+		// update TableStats after limit push down
+		TableStats newTableStats = new TableStats(newRowCount);
+		FlinkStatistic newStatistic = FlinkStatistic.builder()
+			.statistic(statistic)
+			.tableStats(newTableStats)

Review comment:
       nit:  -> `.tableStats(new TableStats(newRowCount))`

##########
File path: flink-table/flink-table-planner-blink/src/main/java/org/apache/flink/table/planner/plan/rules/logical/PushLimitIntoTableSourceScanRule.java
##########
@@ -0,0 +1,118 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.table.planner.plan.rules.logical;
+
+import org.apache.flink.table.connector.source.DynamicTableSource;
+import org.apache.flink.table.connector.source.abilities.SupportsLimitPushDown;
+import org.apache.flink.table.plan.stats.TableStats;
+import org.apache.flink.table.planner.plan.nodes.logical.FlinkLogicalSort;
+import org.apache.flink.table.planner.plan.nodes.logical.FlinkLogicalTableSourceScan;
+import org.apache.flink.table.planner.plan.schema.FlinkPreparingTableBase;
+import org.apache.flink.table.planner.plan.schema.TableSourceTable;
+import org.apache.flink.table.planner.plan.stats.FlinkStatistic;
+
+import org.apache.calcite.plan.RelOptRule;
+import org.apache.calcite.plan.RelOptRuleCall;
+import org.apache.calcite.rel.core.Sort;
+import org.apache.calcite.rex.RexLiteral;
+
+import java.util.Arrays;
+import java.util.Collections;
+
+/**
+ * Planner rule that tries to push limit into a {@link FlinkLogicalTableSourceScan},
+ * which table is a {@link TableSourceTable}. And the table source in the table is a {@link SupportsLimitPushDown}.
+ * The original limit will still be retained.
+ * The reasons why the limit still be retained:
+ * 1.If the source is required to return the exact number of limit number, the implementation
+ * of the source is highly required. The source is required to accurately control the record
+ * number of split, and the parallelism setting also need to be adjusted accordingly.
+ * 2.When remove the limit, maybe filter will be pushed down to the source after limit pushed
+ * down. The source need know it should do limit first and do the filter later, it is hard to
+ * implement.
+ * 3.We can support limit with offset, we can push down offset + fetch to table source.
+ */
+public class PushLimitIntoTableSourceScanRule extends RelOptRule {
+	public static final PushLimitIntoTableSourceScanRule INSTANCE = new PushLimitIntoTableSourceScanRule();
+
+	public PushLimitIntoTableSourceScanRule() {
+		super(operand(FlinkLogicalSort.class,
+			operand(FlinkLogicalTableSourceScan.class, none())),
+			"PushLimitIntoTableSourceScanRule");
+	}
+
+	@Override
+	public boolean matches(RelOptRuleCall call) {
+		Sort sort = call.rel(0);
+		TableSourceTable tableSourceTable = call.rel(1).getTable().unwrap(TableSourceTable.class);
+
+		// a limit can be pushed down only if it satisfies the two conditions: 1) do not have order by keys, 2) have limit.
+		boolean onlyLimit = sort.getCollation().getFieldCollations().isEmpty() && sort.fetch != null;
+		return onlyLimit
+			&& tableSourceTable != null
+			&& tableSourceTable.tableSource() instanceof SupportsLimitPushDown
+			&& Arrays.stream(tableSourceTable.extraDigests()).noneMatch(str -> str.startsWith("limit=["));
+	}
+
+	@Override
+	public void onMatch(RelOptRuleCall call) {
+		Sort sort = call.rel(0);
+		FlinkLogicalTableSourceScan scan = call.rel(1);
+		TableSourceTable tableSourceTable = scan.getTable().unwrap(TableSourceTable.class);
+		int offset = sort.offset == null ? 0 : RexLiteral.intValue(sort.offset);
+		int limit = offset + RexLiteral.intValue(sort.fetch);
+
+		TableSourceTable newTableSourceTable = applyLimit(limit, tableSourceTable);
+
+		FlinkLogicalTableSourceScan newScan = FlinkLogicalTableSourceScan.create(scan.getCluster(), newTableSourceTable);
+		Sort newSort = sort.copy(sort.getTraitSet(), Collections.singletonList(newScan));
+		call.transformTo(newSort);
+	}
+
+	private TableSourceTable applyLimit(
+		long limit,
+		FlinkPreparingTableBase relOptTable) {
+		TableSourceTable oldTableSourceTable = relOptTable.unwrap(TableSourceTable.class);
+		DynamicTableSource newTableSource = oldTableSourceTable.tableSource().copy();
+		((SupportsLimitPushDown) newTableSource).applyLimit(limit);
+
+		FlinkStatistic statistic = relOptTable.getStatistic();
+		long newRowCount = 0;
+		if (statistic.getRowCount() != null) {
+			newRowCount = Math.min(limit, statistic.getRowCount().longValue());
+		} else {
+			newRowCount = limit;
+		}
+		// update TableStats after limit push down
+		TableStats newTableStats = new TableStats(newRowCount);
+		FlinkStatistic newStatistic = FlinkStatistic.builder()
+			.statistic(statistic)
+			.tableStats(newTableStats)
+			.build();
+
+		// update extraDigests
+		String[] newExtraDigests = new String[]{"limit=[" + limit + "]"};
+
+		return oldTableSourceTable.copy(
+			newTableSource,
+			newStatistic,
+			newExtraDigests

Review comment:
       nit: `newExtraDigests` is only used once, just move `new String[] {"limit=[" + limit + "]"}` into here. 




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

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



[GitHub] [flink] flinkbot edited a comment on pull request #12964: [FLINK-17426][blink planner] Dynamic Source supportsLimit pushdown

Posted by GitBox <gi...@apache.org>.
flinkbot edited a comment on pull request #12964:
URL: https://github.com/apache/flink/pull/12964#issuecomment-662793989


   <!--
   Meta data
   {
     "version" : 1,
     "metaDataEntries" : [ {
       "hash" : "984b8a182e5a5cc64a9e1957710e9b9fd4768a56",
       "status" : "DELETED",
       "url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=4751",
       "triggerID" : "984b8a182e5a5cc64a9e1957710e9b9fd4768a56",
       "triggerType" : "PUSH"
     }, {
       "hash" : "0324c22a9b2c85f04481966b2a78f72e92b9c88c",
       "status" : "DELETED",
       "url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=4917",
       "triggerID" : "0324c22a9b2c85f04481966b2a78f72e92b9c88c",
       "triggerType" : "PUSH"
     }, {
       "hash" : "141bd8e09efe79e55398adbdd0916592231fdfbf",
       "status" : "SUCCESS",
       "url" : "https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=4958",
       "triggerID" : "141bd8e09efe79e55398adbdd0916592231fdfbf",
       "triggerType" : "PUSH"
     }, {
       "hash" : "34dd37d992e9d3c3a0bf92e660575571d83b407c",
       "status" : "UNKNOWN",
       "url" : "TBD",
       "triggerID" : "34dd37d992e9d3c3a0bf92e660575571d83b407c",
       "triggerType" : "PUSH"
     } ]
   }-->
   ## CI report:
   
   * 141bd8e09efe79e55398adbdd0916592231fdfbf Azure: [SUCCESS](https://dev.azure.com/apache-flink/98463496-1af2-4620-8eab-a2ecc1a2e6fe/_build/results?buildId=4958) 
   * 34dd37d992e9d3c3a0bf92e660575571d83b407c UNKNOWN
   
   <details>
   <summary>Bot commands</summary>
     The @flinkbot bot supports the following commands:
   
    - `@flinkbot run travis` re-run the last Travis build
    - `@flinkbot run azure` re-run the last Azure build
   </details>


----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

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



[GitHub] [flink] godfreyhe commented on a change in pull request #12964: [FLINK-17426][blink plannger] Dynamic Source supportsLimit pushdown

Posted by GitBox <gi...@apache.org>.
godfreyhe commented on a change in pull request #12964:
URL: https://github.com/apache/flink/pull/12964#discussion_r459873010



##########
File path: flink-table/flink-table-planner-blink/src/main/java/org/apache/flink/table/planner/plan/rules/logical/PushLimitIntoTableSourceScanRule.java
##########
@@ -0,0 +1,121 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.table.planner.plan.rules.logical;
+
+import org.apache.flink.table.connector.source.DynamicTableSource;
+import org.apache.flink.table.connector.source.abilities.SupportsLimitPushDown;
+import org.apache.flink.table.plan.stats.TableStats;
+import org.apache.flink.table.planner.plan.nodes.logical.FlinkLogicalSort;
+import org.apache.flink.table.planner.plan.nodes.logical.FlinkLogicalTableSourceScan;
+import org.apache.flink.table.planner.plan.schema.FlinkPreparingTableBase;
+import org.apache.flink.table.planner.plan.schema.TableSourceTable;
+import org.apache.flink.table.planner.plan.stats.FlinkStatistic;
+
+import org.apache.calcite.plan.RelOptRule;
+import org.apache.calcite.plan.RelOptRuleCall;
+import org.apache.calcite.rel.core.Sort;
+import org.apache.calcite.rex.RexLiteral;
+
+import java.util.Arrays;
+import java.util.Collections;
+
+/**
+ * Planner rule that tries to push limit into a {@link FlinkLogicalTableSourceScan},
+ * which table is a {@link TableSourceTable}. And the table source in the table is a {@link SupportsLimitPushDown}.
+ * The original limit will still be retained.
+ * The reasons why the limit still be retained:
+ * 1.If the source is required to return the exact number of limit number, the implementation
+ * of the source is highly required. The source is required to accurately control the record
+ * number of split, and the parallelism setting also need to be adjusted accordingly.
+ * 2.When remove the limit, maybe filter will be pushed down to the source after limit pushed
+ * down. The source need know it should do limit first and do the filter later, it is hard to
+ * implement.
+ * 3.We can support limit with offset, we can push down offset + fetch to table source.
+ */
+public class PushLimitIntoTableSourceScanRule extends RelOptRule {
+	public static final PushLimitIntoTableSourceScanRule INSTANCE = new PushLimitIntoTableSourceScanRule();
+
+	public PushLimitIntoTableSourceScanRule() {
+		super(operand(FlinkLogicalSort.class,
+			operand(FlinkLogicalTableSourceScan.class, none())),
+			"PushLimitIntoTableSourceScanRule");
+	}
+
+	@Override
+	public boolean matches(RelOptRuleCall call) {
+		Sort sort = call.rel(0);
+		TableSourceTable tableSourceTable = call.rel(1).getTable().unwrap(TableSourceTable.class);
+
+		// a limit can be pushed down only if it satisfies the two conditions: 1) do not have order by keys, 2) have limit.
+		boolean onlyLimit = sort.getCollation().getFieldCollations().isEmpty() && sort.fetch != null;
+		return onlyLimit
+			&& tableSourceTable != null
+			&& tableSourceTable.tableSource() instanceof SupportsLimitPushDown
+			&& !Arrays.stream(tableSourceTable.extraDigests()).anyMatch(str -> str.startsWith("limit=["));

Review comment:
       nit: simpler way: use `noneMatch` instead of ! + anyMatch.
   btw, it's better we can also update the `matches` method of `PushFilterIntoTableSourceScanRule`

##########
File path: flink-table/flink-table-planner-blink/src/main/java/org/apache/flink/table/planner/plan/rules/logical/PushLimitIntoTableSourceScanRule.java
##########
@@ -0,0 +1,121 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.table.planner.plan.rules.logical;
+
+import org.apache.flink.table.connector.source.DynamicTableSource;
+import org.apache.flink.table.connector.source.abilities.SupportsLimitPushDown;
+import org.apache.flink.table.plan.stats.TableStats;
+import org.apache.flink.table.planner.plan.nodes.logical.FlinkLogicalSort;
+import org.apache.flink.table.planner.plan.nodes.logical.FlinkLogicalTableSourceScan;
+import org.apache.flink.table.planner.plan.schema.FlinkPreparingTableBase;
+import org.apache.flink.table.planner.plan.schema.TableSourceTable;
+import org.apache.flink.table.planner.plan.stats.FlinkStatistic;
+
+import org.apache.calcite.plan.RelOptRule;
+import org.apache.calcite.plan.RelOptRuleCall;
+import org.apache.calcite.rel.core.Sort;
+import org.apache.calcite.rex.RexLiteral;
+
+import java.util.Arrays;
+import java.util.Collections;
+
+/**
+ * Planner rule that tries to push limit into a {@link FlinkLogicalTableSourceScan},
+ * which table is a {@link TableSourceTable}. And the table source in the table is a {@link SupportsLimitPushDown}.
+ * The original limit will still be retained.
+ * The reasons why the limit still be retained:
+ * 1.If the source is required to return the exact number of limit number, the implementation
+ * of the source is highly required. The source is required to accurately control the record
+ * number of split, and the parallelism setting also need to be adjusted accordingly.
+ * 2.When remove the limit, maybe filter will be pushed down to the source after limit pushed
+ * down. The source need know it should do limit first and do the filter later, it is hard to
+ * implement.
+ * 3.We can support limit with offset, we can push down offset + fetch to table source.
+ */
+public class PushLimitIntoTableSourceScanRule extends RelOptRule {
+	public static final PushLimitIntoTableSourceScanRule INSTANCE = new PushLimitIntoTableSourceScanRule();
+
+	public PushLimitIntoTableSourceScanRule() {
+		super(operand(FlinkLogicalSort.class,
+			operand(FlinkLogicalTableSourceScan.class, none())),
+			"PushLimitIntoTableSourceScanRule");
+	}
+
+	@Override
+	public boolean matches(RelOptRuleCall call) {
+		Sort sort = call.rel(0);
+		TableSourceTable tableSourceTable = call.rel(1).getTable().unwrap(TableSourceTable.class);
+
+		// a limit can be pushed down only if it satisfies the two conditions: 1) do not have order by keys, 2) have limit.
+		boolean onlyLimit = sort.getCollation().getFieldCollations().isEmpty() && sort.fetch != null;
+		return onlyLimit
+			&& tableSourceTable != null
+			&& tableSourceTable.tableSource() instanceof SupportsLimitPushDown
+			&& !Arrays.stream(tableSourceTable.extraDigests()).anyMatch(str -> str.startsWith("limit=["));
+	}
+
+	@Override
+	public void onMatch(RelOptRuleCall call) {
+		Sort sort = call.rel(0);
+		FlinkLogicalTableSourceScan scan = call.rel(1);
+		TableSourceTable tableSourceTable = scan.getTable().unwrap(TableSourceTable.class);
+		int offset = sort.offset == null ? 0 : RexLiteral.intValue(sort.offset);
+		int limit = offset + RexLiteral.intValue(sort.fetch);
+
+		TableSourceTable newTableSourceTable = applyLimit(limit, tableSourceTable);
+
+		FlinkLogicalTableSourceScan newScan = FlinkLogicalTableSourceScan.create(scan.getCluster(), newTableSourceTable);
+		call.transformTo(sort.copy(sort.getTraitSet(), Collections.singletonList(newScan)));
+	}
+
+	private TableSourceTable applyLimit(
+		long limit,
+		FlinkPreparingTableBase relOptTable) {
+		TableSourceTable oldTableSourceTable = relOptTable.unwrap(TableSourceTable.class);
+		DynamicTableSource newTableSource = oldTableSourceTable.tableSource().copy();
+		((SupportsLimitPushDown) newTableSource).applyLimit(limit);
+
+		FlinkStatistic statistic = relOptTable.getStatistic();
+		long newRowCount = 0;
+		if (statistic.getRowCount() != null) {
+			newRowCount = Math.min(limit, statistic.getRowCount().longValue());
+		} else {
+			newRowCount = limit;
+		}
+		// update TableStats after limit push down
+		TableStats newTableStats = new TableStats(newRowCount);
+		FlinkStatistic newStatistic = FlinkStatistic.builder()
+			.statistic(statistic)
+			.tableStats(newTableStats)
+			.build();
+
+		// update extraDigests
+		String[] newExtraDigests = new String[0];
+		if (limit > 0) {

Review comment:
       we should update the digest anyway, otherwise the rule will be applied endless loop if limit is 0.

##########
File path: flink-table/flink-table-planner-blink/src/main/java/org/apache/flink/table/planner/plan/rules/logical/PushLimitIntoTableSourceScanRule.java
##########
@@ -0,0 +1,121 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.table.planner.plan.rules.logical;
+
+import org.apache.flink.table.connector.source.DynamicTableSource;
+import org.apache.flink.table.connector.source.abilities.SupportsLimitPushDown;
+import org.apache.flink.table.plan.stats.TableStats;
+import org.apache.flink.table.planner.plan.nodes.logical.FlinkLogicalSort;
+import org.apache.flink.table.planner.plan.nodes.logical.FlinkLogicalTableSourceScan;
+import org.apache.flink.table.planner.plan.schema.FlinkPreparingTableBase;
+import org.apache.flink.table.planner.plan.schema.TableSourceTable;
+import org.apache.flink.table.planner.plan.stats.FlinkStatistic;
+
+import org.apache.calcite.plan.RelOptRule;
+import org.apache.calcite.plan.RelOptRuleCall;
+import org.apache.calcite.rel.core.Sort;
+import org.apache.calcite.rex.RexLiteral;
+
+import java.util.Arrays;
+import java.util.Collections;
+
+/**
+ * Planner rule that tries to push limit into a {@link FlinkLogicalTableSourceScan},
+ * which table is a {@link TableSourceTable}. And the table source in the table is a {@link SupportsLimitPushDown}.
+ * The original limit will still be retained.
+ * The reasons why the limit still be retained:
+ * 1.If the source is required to return the exact number of limit number, the implementation
+ * of the source is highly required. The source is required to accurately control the record
+ * number of split, and the parallelism setting also need to be adjusted accordingly.
+ * 2.When remove the limit, maybe filter will be pushed down to the source after limit pushed
+ * down. The source need know it should do limit first and do the filter later, it is hard to
+ * implement.
+ * 3.We can support limit with offset, we can push down offset + fetch to table source.
+ */
+public class PushLimitIntoTableSourceScanRule extends RelOptRule {
+	public static final PushLimitIntoTableSourceScanRule INSTANCE = new PushLimitIntoTableSourceScanRule();
+
+	public PushLimitIntoTableSourceScanRule() {
+		super(operand(FlinkLogicalSort.class,
+			operand(FlinkLogicalTableSourceScan.class, none())),
+			"PushLimitIntoTableSourceScanRule");
+	}
+
+	@Override
+	public boolean matches(RelOptRuleCall call) {
+		Sort sort = call.rel(0);
+		TableSourceTable tableSourceTable = call.rel(1).getTable().unwrap(TableSourceTable.class);
+
+		// a limit can be pushed down only if it satisfies the two conditions: 1) do not have order by keys, 2) have limit.
+		boolean onlyLimit = sort.getCollation().getFieldCollations().isEmpty() && sort.fetch != null;
+		return onlyLimit
+			&& tableSourceTable != null
+			&& tableSourceTable.tableSource() instanceof SupportsLimitPushDown
+			&& !Arrays.stream(tableSourceTable.extraDigests()).anyMatch(str -> str.startsWith("limit=["));
+	}
+
+	@Override
+	public void onMatch(RelOptRuleCall call) {
+		Sort sort = call.rel(0);
+		FlinkLogicalTableSourceScan scan = call.rel(1);
+		TableSourceTable tableSourceTable = scan.getTable().unwrap(TableSourceTable.class);
+		int offset = sort.offset == null ? 0 : RexLiteral.intValue(sort.offset);
+		int limit = offset + RexLiteral.intValue(sort.fetch);
+
+		TableSourceTable newTableSourceTable = applyLimit(limit, tableSourceTable);
+
+		FlinkLogicalTableSourceScan newScan = FlinkLogicalTableSourceScan.create(scan.getCluster(), newTableSourceTable);
+		call.transformTo(sort.copy(sort.getTraitSet(), Collections.singletonList(newScan)));

Review comment:
       It's better we can put `sort.copy(sort.getTraitSet(), Collections.singletonList(newScan))` in a single line, which could make debugging more easy.

##########
File path: flink-table/flink-table-planner-blink/src/test/java/org/apache/flink/table/planner/factories/TestValuesTableFactory.java
##########
@@ -359,7 +361,7 @@ private ChangelogMode parseChangelogMode(String string) {
 	/**
 	 * Values {@link DynamicTableSource} for testing.
 	 */
-	private static class TestValuesTableSource implements ScanTableSource, LookupTableSource, SupportsProjectionPushDown, SupportsFilterPushDown {
+	private static class TestValuesTableSource implements ScanTableSource, LookupTableSource, SupportsProjectionPushDown, SupportsFilterPushDown, SupportsLimitPushDown {

Review comment:
       this line is too long...

##########
File path: flink-table/flink-table-planner-blink/src/main/java/org/apache/flink/table/planner/plan/rules/logical/PushLimitIntoTableSourceScanRule.java
##########
@@ -0,0 +1,121 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.table.planner.plan.rules.logical;
+
+import org.apache.flink.table.connector.source.DynamicTableSource;
+import org.apache.flink.table.connector.source.abilities.SupportsLimitPushDown;
+import org.apache.flink.table.plan.stats.TableStats;
+import org.apache.flink.table.planner.plan.nodes.logical.FlinkLogicalSort;
+import org.apache.flink.table.planner.plan.nodes.logical.FlinkLogicalTableSourceScan;
+import org.apache.flink.table.planner.plan.schema.FlinkPreparingTableBase;
+import org.apache.flink.table.planner.plan.schema.TableSourceTable;
+import org.apache.flink.table.planner.plan.stats.FlinkStatistic;
+
+import org.apache.calcite.plan.RelOptRule;
+import org.apache.calcite.plan.RelOptRuleCall;
+import org.apache.calcite.rel.core.Sort;
+import org.apache.calcite.rex.RexLiteral;
+
+import java.util.Arrays;
+import java.util.Collections;
+
+/**
+ * Planner rule that tries to push limit into a {@link FlinkLogicalTableSourceScan},
+ * which table is a {@link TableSourceTable}. And the table source in the table is a {@link SupportsLimitPushDown}.
+ * The original limit will still be retained.
+ * The reasons why the limit still be retained:
+ * 1.If the source is required to return the exact number of limit number, the implementation
+ * of the source is highly required. The source is required to accurately control the record
+ * number of split, and the parallelism setting also need to be adjusted accordingly.
+ * 2.When remove the limit, maybe filter will be pushed down to the source after limit pushed
+ * down. The source need know it should do limit first and do the filter later, it is hard to
+ * implement.
+ * 3.We can support limit with offset, we can push down offset + fetch to table source.
+ */
+public class PushLimitIntoTableSourceScanRule extends RelOptRule {

Review comment:
       please add a rule test to verify this rule, just like `PushFilterIntoTableSourceScanRuleTest`




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

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



[GitHub] [flink] godfreyhe commented on a change in pull request #12964: [FLINK-17426][blink plannger] Dynamic Source supportsLimit pushdown

Posted by GitBox <gi...@apache.org>.
godfreyhe commented on a change in pull request #12964:
URL: https://github.com/apache/flink/pull/12964#discussion_r459961065



##########
File path: flink-table/flink-table-planner-blink/src/main/java/org/apache/flink/table/planner/plan/rules/logical/PushLimitIntoTableSourceScanRule.java
##########
@@ -0,0 +1,121 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.table.planner.plan.rules.logical;
+
+import org.apache.flink.table.connector.source.DynamicTableSource;
+import org.apache.flink.table.connector.source.abilities.SupportsLimitPushDown;
+import org.apache.flink.table.plan.stats.TableStats;
+import org.apache.flink.table.planner.plan.nodes.logical.FlinkLogicalSort;
+import org.apache.flink.table.planner.plan.nodes.logical.FlinkLogicalTableSourceScan;
+import org.apache.flink.table.planner.plan.schema.FlinkPreparingTableBase;
+import org.apache.flink.table.planner.plan.schema.TableSourceTable;
+import org.apache.flink.table.planner.plan.stats.FlinkStatistic;
+
+import org.apache.calcite.plan.RelOptRule;
+import org.apache.calcite.plan.RelOptRuleCall;
+import org.apache.calcite.rel.core.Sort;
+import org.apache.calcite.rex.RexLiteral;
+
+import java.util.Arrays;
+import java.util.Collections;
+
+/**
+ * Planner rule that tries to push limit into a {@link FlinkLogicalTableSourceScan},
+ * which table is a {@link TableSourceTable}. And the table source in the table is a {@link SupportsLimitPushDown}.
+ * The original limit will still be retained.
+ * The reasons why the limit still be retained:
+ * 1.If the source is required to return the exact number of limit number, the implementation
+ * of the source is highly required. The source is required to accurately control the record
+ * number of split, and the parallelism setting also need to be adjusted accordingly.
+ * 2.When remove the limit, maybe filter will be pushed down to the source after limit pushed
+ * down. The source need know it should do limit first and do the filter later, it is hard to
+ * implement.
+ * 3.We can support limit with offset, we can push down offset + fetch to table source.
+ */
+public class PushLimitIntoTableSourceScanRule extends RelOptRule {

Review comment:
       Rule test is different from plan test. Rule test focuses on the added rule and only a few must-involved rules can be added to the rule set to help the test. Plan test will verify the plan based on whole rule sets.




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

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