morrySnow commented on code in PR #11964:
URL: https://github.com/apache/doris/pull/11964#discussion_r953872284


##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/logical/PruneOlapScanPartition.java:
##########
@@ -0,0 +1,166 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package org.apache.doris.nereids.rules.rewrite.logical;
+
+import org.apache.doris.analysis.LiteralExpr;
+import org.apache.doris.catalog.OlapTable;
+import org.apache.doris.catalog.PartitionInfo;
+import org.apache.doris.catalog.PartitionItem;
+import org.apache.doris.catalog.PartitionType;
+import org.apache.doris.nereids.rules.Rule;
+import org.apache.doris.nereids.rules.RuleType;
+import org.apache.doris.nereids.rules.rewrite.OneRewriteRuleFactory;
+import org.apache.doris.nereids.trees.expressions.ComparisonPredicate;
+import org.apache.doris.nereids.trees.expressions.EqualTo;
+import org.apache.doris.nereids.trees.expressions.Expression;
+import org.apache.doris.nereids.trees.expressions.GreaterThan;
+import org.apache.doris.nereids.trees.expressions.GreaterThanEqual;
+import org.apache.doris.nereids.trees.expressions.LessThan;
+import org.apache.doris.nereids.trees.expressions.LessThanEqual;
+import org.apache.doris.nereids.trees.expressions.Or;
+import org.apache.doris.nereids.trees.expressions.SlotReference;
+import org.apache.doris.nereids.trees.expressions.literal.Literal;
+import org.apache.doris.nereids.trees.plans.logical.LogicalFilter;
+import org.apache.doris.nereids.trees.plans.logical.LogicalOlapScan;
+import org.apache.doris.nereids.util.ExpressionUtils;
+import org.apache.doris.nereids.util.Utils;
+import org.apache.doris.planner.ColumnBound;
+import org.apache.doris.planner.ColumnRange;
+import org.apache.doris.planner.PartitionPruner;
+import org.apache.doris.planner.RangePartitionPrunerV2;
+import org.apache.doris.planner.ScanNode.ColumnRanges;
+
+import com.google.common.collect.Lists;
+import com.google.common.collect.Maps;
+import com.google.common.collect.Range;
+
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * Used to prune partition of olap scan, should execute after 
SwapProjectAndFilter, MergeConsecutiveFilters,
+ * MergeConsecutiveProjects and all predicate push down related rules.
+ */
+public class PruneOlapScanPartition extends OneRewriteRuleFactory {
+
+    @Override
+    public Rule build() {
+        return logicalFilter(logicalOlapScan()).thenApply(ctx -> {
+            LogicalFilter<LogicalOlapScan> filter = ctx.root;
+            LogicalOlapScan scan = filter.child();
+            Expression predicate = filter.getPredicates();
+            List<Expression> expressionList = 
ExpressionUtils.extractConjunction(predicate);
+            OlapTable table = scan.getTable();
+            Set<String> partitionColumnNameSet = 
Utils.execWithReturnVal(table::getPartitionColumnNames);
+            PartitionInfo partitionInfo = table.getPartitionInfo();
+            // TODO: 1. support grammar: SELECT * FROM tbl PARTITION(p1,p2)
+            //       2. support list partition
+            if (partitionColumnNameSet.isEmpty() || 
!partitionInfo.getType().equals(PartitionType.RANGE)) {
+                return ctx.root;
+            }
+            // TODO: Process all partition column for now, better to process 
required column only.
+            Map<String, ColumnRange> columnNameToRange = Maps.newHashMap();
+            for (String colName : partitionColumnNameSet) {
+                ColumnRange columnRange = createColumnRange(colName, 
expressionList);
+                columnNameToRange.put(colName, columnRange);
+            }
+
+            Map<Long, PartitionItem> keyItemMap = 
partitionInfo.getIdToItem(false);
+            PartitionPruner partitionPruner = new 
RangePartitionPrunerV2(keyItemMap,
+                    partitionInfo.getPartitionColumns(), columnNameToRange);
+            Collection<Long> selectedPartitionId =  
Utils.execWithReturnVal(partitionPruner::prune);
+            scan.getSelectedPartitionIds().retainAll(selectedPartitionId);

Review Comment:
   REMEMBER THAT: `Plan` and `Expression` in Nereids is **_IMMUTABLE_**.
   we should not mod scan's attribute. Instead, we need to generate a new 
`LogicalOlapScan` with pruned partitionIds.



##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/logical/PruneOlapScanPartition.java:
##########
@@ -0,0 +1,166 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package org.apache.doris.nereids.rules.rewrite.logical;
+
+import org.apache.doris.analysis.LiteralExpr;
+import org.apache.doris.catalog.OlapTable;
+import org.apache.doris.catalog.PartitionInfo;
+import org.apache.doris.catalog.PartitionItem;
+import org.apache.doris.catalog.PartitionType;
+import org.apache.doris.nereids.rules.Rule;
+import org.apache.doris.nereids.rules.RuleType;
+import org.apache.doris.nereids.rules.rewrite.OneRewriteRuleFactory;
+import org.apache.doris.nereids.trees.expressions.ComparisonPredicate;
+import org.apache.doris.nereids.trees.expressions.EqualTo;
+import org.apache.doris.nereids.trees.expressions.Expression;
+import org.apache.doris.nereids.trees.expressions.GreaterThan;
+import org.apache.doris.nereids.trees.expressions.GreaterThanEqual;
+import org.apache.doris.nereids.trees.expressions.LessThan;
+import org.apache.doris.nereids.trees.expressions.LessThanEqual;
+import org.apache.doris.nereids.trees.expressions.Or;
+import org.apache.doris.nereids.trees.expressions.SlotReference;
+import org.apache.doris.nereids.trees.expressions.literal.Literal;
+import org.apache.doris.nereids.trees.plans.logical.LogicalFilter;
+import org.apache.doris.nereids.trees.plans.logical.LogicalOlapScan;
+import org.apache.doris.nereids.util.ExpressionUtils;
+import org.apache.doris.nereids.util.Utils;
+import org.apache.doris.planner.ColumnBound;
+import org.apache.doris.planner.ColumnRange;
+import org.apache.doris.planner.PartitionPruner;
+import org.apache.doris.planner.RangePartitionPrunerV2;
+import org.apache.doris.planner.ScanNode.ColumnRanges;
+
+import com.google.common.collect.Lists;
+import com.google.common.collect.Maps;
+import com.google.common.collect.Range;
+
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * Used to prune partition of olap scan, should execute after 
SwapProjectAndFilter, MergeConsecutiveFilters,
+ * MergeConsecutiveProjects and all predicate push down related rules.
+ */
+public class PruneOlapScanPartition extends OneRewriteRuleFactory {
+
+    @Override
+    public Rule build() {
+        return logicalFilter(logicalOlapScan()).thenApply(ctx -> {
+            LogicalFilter<LogicalOlapScan> filter = ctx.root;
+            LogicalOlapScan scan = filter.child();
+            Expression predicate = filter.getPredicates();
+            List<Expression> expressionList = 
ExpressionUtils.extractConjunction(predicate);
+            OlapTable table = scan.getTable();
+            Set<String> partitionColumnNameSet = 
Utils.execWithReturnVal(table::getPartitionColumnNames);
+            PartitionInfo partitionInfo = table.getPartitionInfo();
+            // TODO: 1. support grammar: SELECT * FROM tbl PARTITION(p1,p2)
+            //       2. support list partition
+            if (partitionColumnNameSet.isEmpty() || 
!partitionInfo.getType().equals(PartitionType.RANGE)) {
+                return ctx.root;
+            }
+            // TODO: Process all partition column for now, better to process 
required column only.
+            Map<String, ColumnRange> columnNameToRange = Maps.newHashMap();
+            for (String colName : partitionColumnNameSet) {
+                ColumnRange columnRange = createColumnRange(colName, 
expressionList);
+                columnNameToRange.put(colName, columnRange);
+            }
+
+            Map<Long, PartitionItem> keyItemMap = 
partitionInfo.getIdToItem(false);
+            PartitionPruner partitionPruner = new 
RangePartitionPrunerV2(keyItemMap,
+                    partitionInfo.getPartitionColumns(), columnNameToRange);
+            Collection<Long> selectedPartitionId =  
Utils.execWithReturnVal(partitionPruner::prune);
+            scan.getSelectedPartitionIds().retainAll(selectedPartitionId);
+            return ctx.root;
+        }).toRule(RuleType.PARTITION_PRUNE);
+    }
+
+    private ColumnRange createColumnRange(String colName, List<Expression> 
expressionList) {
+        ColumnRange result = ColumnRange.create();
+        for (Expression expression : expressionList) {
+            Expression leftMostChild = expression.leftMostNode();
+            if (!(leftMostChild instanceof SlotReference)) {
+                continue;
+            }
+            SlotReference slotRef = (SlotReference) leftMostChild;
+            if (!slotRef.boundToColumn(colName)) {
+                continue;
+            }
+            if (expression instanceof Or) {
+                ColumnRanges ranges = exprToRanges(expression, colName);
+                switch (ranges.type) {
+                    case IS_NULL:
+                        result.setHasConjunctiveIsNull(true);
+                        break;
+                    case CONVERT_SUCCESS:
+                        result.intersect(ranges.ranges);
+                        break;
+                    case CONVERT_FAILURE:
+                    default:
+                        break;
+                }
+            } else {
+                ColumnRanges ranges = exprToRanges(expression, colName);
+                switch (ranges.type) {
+                    case IS_NULL:
+                        result.setHasConjunctiveIsNull(true);
+                        break;
+                    case CONVERT_SUCCESS:
+                        result.intersect(ranges.ranges);
+                        break;
+                    case CONVERT_FAILURE:
+                    default:
+                        break;
+                }
+            }
+        }
+        return result;
+    }
+
+    private ColumnRanges exprToRanges(Expression expression, String colName) {
+        // TODO: process in/is null expression

Review Comment:
   is these needed by TPC-H?



##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/logical/PruneOlapScanPartition.java:
##########
@@ -0,0 +1,166 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package org.apache.doris.nereids.rules.rewrite.logical;
+
+import org.apache.doris.analysis.LiteralExpr;
+import org.apache.doris.catalog.OlapTable;
+import org.apache.doris.catalog.PartitionInfo;
+import org.apache.doris.catalog.PartitionItem;
+import org.apache.doris.catalog.PartitionType;
+import org.apache.doris.nereids.rules.Rule;
+import org.apache.doris.nereids.rules.RuleType;
+import org.apache.doris.nereids.rules.rewrite.OneRewriteRuleFactory;
+import org.apache.doris.nereids.trees.expressions.ComparisonPredicate;
+import org.apache.doris.nereids.trees.expressions.EqualTo;
+import org.apache.doris.nereids.trees.expressions.Expression;
+import org.apache.doris.nereids.trees.expressions.GreaterThan;
+import org.apache.doris.nereids.trees.expressions.GreaterThanEqual;
+import org.apache.doris.nereids.trees.expressions.LessThan;
+import org.apache.doris.nereids.trees.expressions.LessThanEqual;
+import org.apache.doris.nereids.trees.expressions.Or;
+import org.apache.doris.nereids.trees.expressions.SlotReference;
+import org.apache.doris.nereids.trees.expressions.literal.Literal;
+import org.apache.doris.nereids.trees.plans.logical.LogicalFilter;
+import org.apache.doris.nereids.trees.plans.logical.LogicalOlapScan;
+import org.apache.doris.nereids.util.ExpressionUtils;
+import org.apache.doris.nereids.util.Utils;
+import org.apache.doris.planner.ColumnBound;
+import org.apache.doris.planner.ColumnRange;
+import org.apache.doris.planner.PartitionPruner;
+import org.apache.doris.planner.RangePartitionPrunerV2;
+import org.apache.doris.planner.ScanNode.ColumnRanges;
+
+import com.google.common.collect.Lists;
+import com.google.common.collect.Maps;
+import com.google.common.collect.Range;
+
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * Used to prune partition of olap scan, should execute after 
SwapProjectAndFilter, MergeConsecutiveFilters,
+ * MergeConsecutiveProjects and all predicate push down related rules.
+ */
+public class PruneOlapScanPartition extends OneRewriteRuleFactory {
+
+    @Override
+    public Rule build() {
+        return logicalFilter(logicalOlapScan()).thenApply(ctx -> {

Review Comment:
   if u do not use other attributes in `ctx`, u could use `then()`



##########
fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/physical/PhysicalOlapScan.java:
##########
@@ -117,11 +121,15 @@ public <R, C> R accept(PlanVisitor<R, C> visitor, C 
context) {
 
     @Override
     public Plan withGroupExpression(Optional<GroupExpression> groupExpression) 
{
-        return new PhysicalOlapScan(olapTable, qualifier, distributionSpec, 
groupExpression, logicalProperties);
+        return new PhysicalOlapScan(olapTable,
+                selectedPartitionId, qualifier, distributionSpec, 
groupExpression, logicalProperties);
     }
 
     @Override
     public Plan withLogicalProperties(Optional<LogicalProperties> 
logicalProperties) {
-        return new PhysicalOlapScan(olapTable, qualifier, distributionSpec, 
Optional.empty(), logicalProperties.get());
+        return new PhysicalOlapScan(olapTable,
+                selectedPartitionId,
+                qualifier,
+                distributionSpec, Optional.empty(), logicalProperties.get());

Review Comment:
   ```suggestion
           return new PhysicalOlapScan(olapTable, selectedPartitionId, 
qualifier,
                   distributionSpec, Optional.empty(), logicalProperties.get());
   ```



##########
fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/logical/LogicalOlapScan.java:
##########
@@ -55,6 +55,7 @@ public LogicalOlapScan(Table table, List<String> qualifier) {
     public LogicalOlapScan(Table table, List<String> qualifier,
                            Optional<GroupExpression> groupExpression, 
Optional<LogicalProperties> logicalProperties) {
         super(PlanType.LOGICAL_OLAP_SCAN, table, qualifier, groupExpression, 
logicalProperties);
+        super.selectedPartitionIds = ((OlapTable) table).getPartitionIds();

Review Comment:
   why not add a new parameter to super constructor directly



##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/logical/SwapFilterAndProject.java:
##########
@@ -0,0 +1,58 @@
+// 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.doris.nereids.rules.rewrite.logical;
+
+import org.apache.doris.nereids.rules.Rule;
+import org.apache.doris.nereids.rules.RuleType;
+import org.apache.doris.nereids.rules.rewrite.OneRewriteRuleFactory;
+import org.apache.doris.nereids.trees.expressions.Alias;
+import org.apache.doris.nereids.trees.expressions.Expression;
+import org.apache.doris.nereids.trees.expressions.NamedExpression;
+import org.apache.doris.nereids.trees.expressions.Slot;
+import 
org.apache.doris.nereids.trees.expressions.visitor.RewriteAliasToChildExpr;
+import org.apache.doris.nereids.trees.plans.GroupPlan;
+import org.apache.doris.nereids.trees.plans.logical.LogicalFilter;
+import org.apache.doris.nereids.trees.plans.logical.LogicalPlan;
+import org.apache.doris.nereids.trees.plans.logical.LogicalProject;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Rewrite filter -> project to project -> filter.
+ */
+public class SwapFilterAndProject extends OneRewriteRuleFactory {
+    @Override
+    public Rule build() {
+        return logicalFilter(logicalProject()).thenApply(ctx -> {
+            LogicalFilter<LogicalProject<GroupPlan>> filter = ctx.root;
+            LogicalProject<GroupPlan> project = filter.child();
+            List<NamedExpression> namedExpressionList = project.getProjects();
+            Map<Slot, Alias> slotToAlias = new HashMap<>();

Review Comment:
   ```suggestion
               Map<Slot, Alias> slotToAlias = Maps.newHashMap();
   ```



##########
fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/visitor/RewriteAliasToChildExpr.java:
##########
@@ -0,0 +1,37 @@
+// 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.doris.nereids.trees.expressions.visitor;
+
+import org.apache.doris.nereids.trees.expressions.Alias;
+import org.apache.doris.nereids.trees.expressions.Expression;
+import org.apache.doris.nereids.trees.expressions.Slot;
+import org.apache.doris.nereids.trees.expressions.SlotReference;
+
+import java.util.Map;
+
+/**
+ * UpdateAliasVisitor

Review Comment:
   detailing it



##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/logical/PruneOlapScanPartition.java:
##########
@@ -0,0 +1,166 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package org.apache.doris.nereids.rules.rewrite.logical;
+
+import org.apache.doris.analysis.LiteralExpr;
+import org.apache.doris.catalog.OlapTable;
+import org.apache.doris.catalog.PartitionInfo;
+import org.apache.doris.catalog.PartitionItem;
+import org.apache.doris.catalog.PartitionType;
+import org.apache.doris.nereids.rules.Rule;
+import org.apache.doris.nereids.rules.RuleType;
+import org.apache.doris.nereids.rules.rewrite.OneRewriteRuleFactory;
+import org.apache.doris.nereids.trees.expressions.ComparisonPredicate;
+import org.apache.doris.nereids.trees.expressions.EqualTo;
+import org.apache.doris.nereids.trees.expressions.Expression;
+import org.apache.doris.nereids.trees.expressions.GreaterThan;
+import org.apache.doris.nereids.trees.expressions.GreaterThanEqual;
+import org.apache.doris.nereids.trees.expressions.LessThan;
+import org.apache.doris.nereids.trees.expressions.LessThanEqual;
+import org.apache.doris.nereids.trees.expressions.Or;
+import org.apache.doris.nereids.trees.expressions.SlotReference;
+import org.apache.doris.nereids.trees.expressions.literal.Literal;
+import org.apache.doris.nereids.trees.plans.logical.LogicalFilter;
+import org.apache.doris.nereids.trees.plans.logical.LogicalOlapScan;
+import org.apache.doris.nereids.util.ExpressionUtils;
+import org.apache.doris.nereids.util.Utils;
+import org.apache.doris.planner.ColumnBound;
+import org.apache.doris.planner.ColumnRange;
+import org.apache.doris.planner.PartitionPruner;
+import org.apache.doris.planner.RangePartitionPrunerV2;
+import org.apache.doris.planner.ScanNode.ColumnRanges;
+
+import com.google.common.collect.Lists;
+import com.google.common.collect.Maps;
+import com.google.common.collect.Range;
+
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * Used to prune partition of olap scan, should execute after 
SwapProjectAndFilter, MergeConsecutiveFilters,
+ * MergeConsecutiveProjects and all predicate push down related rules.
+ */
+public class PruneOlapScanPartition extends OneRewriteRuleFactory {
+
+    @Override
+    public Rule build() {
+        return logicalFilter(logicalOlapScan()).thenApply(ctx -> {
+            LogicalFilter<LogicalOlapScan> filter = ctx.root;
+            LogicalOlapScan scan = filter.child();
+            Expression predicate = filter.getPredicates();
+            List<Expression> expressionList = 
ExpressionUtils.extractConjunction(predicate);

Review Comment:
   move these after L79 for ease reading



##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/RuleType.java:
##########
@@ -72,6 +72,8 @@ public enum RuleType {
     MERGE_CONSECUTIVE_FILTERS(RuleTypeClass.REWRITE),
     MERGE_CONSECUTIVE_PROJECTS(RuleTypeClass.REWRITE),
     REWRITE_SENTINEL(RuleTypeClass.REWRITE),
+    PARTITION_PRUNE(RuleTypeClass.REWRITE),

Review Comment:
   ```suggestion
       OLAP_SCAN_PARTITION_PRUNE(RuleTypeClass.REWRITE),
   ```



##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/logical/SwapFilterAndProject.java:
##########
@@ -0,0 +1,58 @@
+// 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.doris.nereids.rules.rewrite.logical;
+
+import org.apache.doris.nereids.rules.Rule;
+import org.apache.doris.nereids.rules.RuleType;
+import org.apache.doris.nereids.rules.rewrite.OneRewriteRuleFactory;
+import org.apache.doris.nereids.trees.expressions.Alias;
+import org.apache.doris.nereids.trees.expressions.Expression;
+import org.apache.doris.nereids.trees.expressions.NamedExpression;
+import org.apache.doris.nereids.trees.expressions.Slot;
+import 
org.apache.doris.nereids.trees.expressions.visitor.RewriteAliasToChildExpr;
+import org.apache.doris.nereids.trees.plans.GroupPlan;
+import org.apache.doris.nereids.trees.plans.logical.LogicalFilter;
+import org.apache.doris.nereids.trees.plans.logical.LogicalPlan;
+import org.apache.doris.nereids.trees.plans.logical.LogicalProject;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Rewrite filter -> project to project -> filter.
+ */
+public class SwapFilterAndProject extends OneRewriteRuleFactory {
+    @Override
+    public Rule build() {
+        return logicalFilter(logicalProject()).thenApply(ctx -> {
+            LogicalFilter<LogicalProject<GroupPlan>> filter = ctx.root;
+            LogicalProject<GroupPlan> project = filter.child();
+            List<NamedExpression> namedExpressionList = project.getProjects();
+            Map<Slot, Alias> slotToAlias = new HashMap<>();
+            
namedExpressionList.stream().filter(Alias.class::isInstance).forEach(s -> {
+                slotToAlias.put(s.toSlot(), (Alias) s);

Review Comment:
   maybe u could generate a `Map<Expression, Expression>` like `(s.toSlot, 
s.child())`, and use `ExpressionReplacer.INSTANCE` to replace slot reference in 
expression



##########
fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/logical/LogicalRelation.java:
##########
@@ -42,6 +44,8 @@ public abstract class LogicalRelation extends LogicalLeaf 
implements Scan {
     protected final Table table;
     protected final List<String> qualifier;
 
+    protected Collection<Long> selectedPartitionIds = Lists.newArrayList();

Review Comment:
   why need collection?



##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/logical/PruneOlapScanPartition.java:
##########
@@ -0,0 +1,166 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package org.apache.doris.nereids.rules.rewrite.logical;
+
+import org.apache.doris.analysis.LiteralExpr;
+import org.apache.doris.catalog.OlapTable;
+import org.apache.doris.catalog.PartitionInfo;
+import org.apache.doris.catalog.PartitionItem;
+import org.apache.doris.catalog.PartitionType;
+import org.apache.doris.nereids.rules.Rule;
+import org.apache.doris.nereids.rules.RuleType;
+import org.apache.doris.nereids.rules.rewrite.OneRewriteRuleFactory;
+import org.apache.doris.nereids.trees.expressions.ComparisonPredicate;
+import org.apache.doris.nereids.trees.expressions.EqualTo;
+import org.apache.doris.nereids.trees.expressions.Expression;
+import org.apache.doris.nereids.trees.expressions.GreaterThan;
+import org.apache.doris.nereids.trees.expressions.GreaterThanEqual;
+import org.apache.doris.nereids.trees.expressions.LessThan;
+import org.apache.doris.nereids.trees.expressions.LessThanEqual;
+import org.apache.doris.nereids.trees.expressions.Or;
+import org.apache.doris.nereids.trees.expressions.SlotReference;
+import org.apache.doris.nereids.trees.expressions.literal.Literal;
+import org.apache.doris.nereids.trees.plans.logical.LogicalFilter;
+import org.apache.doris.nereids.trees.plans.logical.LogicalOlapScan;
+import org.apache.doris.nereids.util.ExpressionUtils;
+import org.apache.doris.nereids.util.Utils;
+import org.apache.doris.planner.ColumnBound;
+import org.apache.doris.planner.ColumnRange;
+import org.apache.doris.planner.PartitionPruner;
+import org.apache.doris.planner.RangePartitionPrunerV2;
+import org.apache.doris.planner.ScanNode.ColumnRanges;
+
+import com.google.common.collect.Lists;
+import com.google.common.collect.Maps;
+import com.google.common.collect.Range;
+
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * Used to prune partition of olap scan, should execute after 
SwapProjectAndFilter, MergeConsecutiveFilters,
+ * MergeConsecutiveProjects and all predicate push down related rules.
+ */
+public class PruneOlapScanPartition extends OneRewriteRuleFactory {
+
+    @Override
+    public Rule build() {
+        return logicalFilter(logicalOlapScan()).thenApply(ctx -> {
+            LogicalFilter<LogicalOlapScan> filter = ctx.root;
+            LogicalOlapScan scan = filter.child();
+            Expression predicate = filter.getPredicates();
+            List<Expression> expressionList = 
ExpressionUtils.extractConjunction(predicate);
+            OlapTable table = scan.getTable();
+            Set<String> partitionColumnNameSet = 
Utils.execWithReturnVal(table::getPartitionColumnNames);
+            PartitionInfo partitionInfo = table.getPartitionInfo();
+            // TODO: 1. support grammar: SELECT * FROM tbl PARTITION(p1,p2)
+            //       2. support list partition
+            if (partitionColumnNameSet.isEmpty() || 
!partitionInfo.getType().equals(PartitionType.RANGE)) {
+                return ctx.root;
+            }
+            // TODO: Process all partition column for now, better to process 
required column only.
+            Map<String, ColumnRange> columnNameToRange = Maps.newHashMap();
+            for (String colName : partitionColumnNameSet) {
+                ColumnRange columnRange = createColumnRange(colName, 
expressionList);
+                columnNameToRange.put(colName, columnRange);
+            }
+
+            Map<Long, PartitionItem> keyItemMap = 
partitionInfo.getIdToItem(false);
+            PartitionPruner partitionPruner = new 
RangePartitionPrunerV2(keyItemMap,
+                    partitionInfo.getPartitionColumns(), columnNameToRange);
+            Collection<Long> selectedPartitionId =  
Utils.execWithReturnVal(partitionPruner::prune);
+            scan.getSelectedPartitionIds().retainAll(selectedPartitionId);
+            return ctx.root;
+        }).toRule(RuleType.PARTITION_PRUNE);
+    }
+
+    private ColumnRange createColumnRange(String colName, List<Expression> 
expressionList) {
+        ColumnRange result = ColumnRange.create();
+        for (Expression expression : expressionList) {
+            Expression leftMostChild = expression.leftMostNode();
+            if (!(leftMostChild instanceof SlotReference)) {
+                continue;
+            }
+            SlotReference slotRef = (SlotReference) leftMostChild;
+            if (!slotRef.boundToColumn(colName)) {
+                continue;
+            }
+            if (expression instanceof Or) {
+                ColumnRanges ranges = exprToRanges(expression, colName);

Review Comment:
   this is strange that `expression` is a `Or`, but `exprToRanges` need a 
`ComparisonPredicate `.
   furthermore, if and else branches are same.
   So, do u forget something?



##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/logical/PruneOlapScanPartition.java:
##########
@@ -0,0 +1,166 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package org.apache.doris.nereids.rules.rewrite.logical;
+
+import org.apache.doris.analysis.LiteralExpr;
+import org.apache.doris.catalog.OlapTable;
+import org.apache.doris.catalog.PartitionInfo;
+import org.apache.doris.catalog.PartitionItem;
+import org.apache.doris.catalog.PartitionType;
+import org.apache.doris.nereids.rules.Rule;
+import org.apache.doris.nereids.rules.RuleType;
+import org.apache.doris.nereids.rules.rewrite.OneRewriteRuleFactory;
+import org.apache.doris.nereids.trees.expressions.ComparisonPredicate;
+import org.apache.doris.nereids.trees.expressions.EqualTo;
+import org.apache.doris.nereids.trees.expressions.Expression;
+import org.apache.doris.nereids.trees.expressions.GreaterThan;
+import org.apache.doris.nereids.trees.expressions.GreaterThanEqual;
+import org.apache.doris.nereids.trees.expressions.LessThan;
+import org.apache.doris.nereids.trees.expressions.LessThanEqual;
+import org.apache.doris.nereids.trees.expressions.Or;
+import org.apache.doris.nereids.trees.expressions.SlotReference;
+import org.apache.doris.nereids.trees.expressions.literal.Literal;
+import org.apache.doris.nereids.trees.plans.logical.LogicalFilter;
+import org.apache.doris.nereids.trees.plans.logical.LogicalOlapScan;
+import org.apache.doris.nereids.util.ExpressionUtils;
+import org.apache.doris.nereids.util.Utils;
+import org.apache.doris.planner.ColumnBound;
+import org.apache.doris.planner.ColumnRange;
+import org.apache.doris.planner.PartitionPruner;
+import org.apache.doris.planner.RangePartitionPrunerV2;
+import org.apache.doris.planner.ScanNode.ColumnRanges;
+
+import com.google.common.collect.Lists;
+import com.google.common.collect.Maps;
+import com.google.common.collect.Range;
+
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * Used to prune partition of olap scan, should execute after 
SwapProjectAndFilter, MergeConsecutiveFilters,
+ * MergeConsecutiveProjects and all predicate push down related rules.
+ */
+public class PruneOlapScanPartition extends OneRewriteRuleFactory {
+
+    @Override
+    public Rule build() {
+        return logicalFilter(logicalOlapScan()).thenApply(ctx -> {
+            LogicalFilter<LogicalOlapScan> filter = ctx.root;
+            LogicalOlapScan scan = filter.child();
+            Expression predicate = filter.getPredicates();
+            List<Expression> expressionList = 
ExpressionUtils.extractConjunction(predicate);
+            OlapTable table = scan.getTable();
+            Set<String> partitionColumnNameSet = 
Utils.execWithReturnVal(table::getPartitionColumnNames);
+            PartitionInfo partitionInfo = table.getPartitionInfo();
+            // TODO: 1. support grammar: SELECT * FROM tbl PARTITION(p1,p2)
+            //       2. support list partition
+            if (partitionColumnNameSet.isEmpty() || 
!partitionInfo.getType().equals(PartitionType.RANGE)) {
+                return ctx.root;
+            }
+            // TODO: Process all partition column for now, better to process 
required column only.
+            Map<String, ColumnRange> columnNameToRange = Maps.newHashMap();
+            for (String colName : partitionColumnNameSet) {
+                ColumnRange columnRange = createColumnRange(colName, 
expressionList);
+                columnNameToRange.put(colName, columnRange);
+            }
+
+            Map<Long, PartitionItem> keyItemMap = 
partitionInfo.getIdToItem(false);
+            PartitionPruner partitionPruner = new 
RangePartitionPrunerV2(keyItemMap,
+                    partitionInfo.getPartitionColumns(), columnNameToRange);
+            Collection<Long> selectedPartitionId =  
Utils.execWithReturnVal(partitionPruner::prune);
+            scan.getSelectedPartitionIds().retainAll(selectedPartitionId);
+            return ctx.root;
+        }).toRule(RuleType.PARTITION_PRUNE);
+    }
+
+    private ColumnRange createColumnRange(String colName, List<Expression> 
expressionList) {
+        ColumnRange result = ColumnRange.create();
+        for (Expression expression : expressionList) {
+            Expression leftMostChild = expression.leftMostNode();

Review Comment:
   use `collect(SlotReference.class:isInstance)`



##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/logical/PruneOlapScanPartition.java:
##########
@@ -0,0 +1,166 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package org.apache.doris.nereids.rules.rewrite.logical;
+
+import org.apache.doris.analysis.LiteralExpr;
+import org.apache.doris.catalog.OlapTable;
+import org.apache.doris.catalog.PartitionInfo;
+import org.apache.doris.catalog.PartitionItem;
+import org.apache.doris.catalog.PartitionType;
+import org.apache.doris.nereids.rules.Rule;
+import org.apache.doris.nereids.rules.RuleType;
+import org.apache.doris.nereids.rules.rewrite.OneRewriteRuleFactory;
+import org.apache.doris.nereids.trees.expressions.ComparisonPredicate;
+import org.apache.doris.nereids.trees.expressions.EqualTo;
+import org.apache.doris.nereids.trees.expressions.Expression;
+import org.apache.doris.nereids.trees.expressions.GreaterThan;
+import org.apache.doris.nereids.trees.expressions.GreaterThanEqual;
+import org.apache.doris.nereids.trees.expressions.LessThan;
+import org.apache.doris.nereids.trees.expressions.LessThanEqual;
+import org.apache.doris.nereids.trees.expressions.Or;
+import org.apache.doris.nereids.trees.expressions.SlotReference;
+import org.apache.doris.nereids.trees.expressions.literal.Literal;
+import org.apache.doris.nereids.trees.plans.logical.LogicalFilter;
+import org.apache.doris.nereids.trees.plans.logical.LogicalOlapScan;
+import org.apache.doris.nereids.util.ExpressionUtils;
+import org.apache.doris.nereids.util.Utils;
+import org.apache.doris.planner.ColumnBound;
+import org.apache.doris.planner.ColumnRange;
+import org.apache.doris.planner.PartitionPruner;
+import org.apache.doris.planner.RangePartitionPrunerV2;
+import org.apache.doris.planner.ScanNode.ColumnRanges;
+
+import com.google.common.collect.Lists;
+import com.google.common.collect.Maps;
+import com.google.common.collect.Range;
+
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * Used to prune partition of olap scan, should execute after 
SwapProjectAndFilter, MergeConsecutiveFilters,
+ * MergeConsecutiveProjects and all predicate push down related rules.
+ */
+public class PruneOlapScanPartition extends OneRewriteRuleFactory {
+
+    @Override
+    public Rule build() {
+        return logicalFilter(logicalOlapScan()).thenApply(ctx -> {
+            LogicalFilter<LogicalOlapScan> filter = ctx.root;
+            LogicalOlapScan scan = filter.child();
+            Expression predicate = filter.getPredicates();
+            List<Expression> expressionList = 
ExpressionUtils.extractConjunction(predicate);
+            OlapTable table = scan.getTable();
+            Set<String> partitionColumnNameSet = 
Utils.execWithReturnVal(table::getPartitionColumnNames);
+            PartitionInfo partitionInfo = table.getPartitionInfo();
+            // TODO: 1. support grammar: SELECT * FROM tbl PARTITION(p1,p2)
+            //       2. support list partition
+            if (partitionColumnNameSet.isEmpty() || 
!partitionInfo.getType().equals(PartitionType.RANGE)) {
+                return ctx.root;
+            }
+            // TODO: Process all partition column for now, better to process 
required column only.
+            Map<String, ColumnRange> columnNameToRange = Maps.newHashMap();
+            for (String colName : partitionColumnNameSet) {
+                ColumnRange columnRange = createColumnRange(colName, 
expressionList);
+                columnNameToRange.put(colName, columnRange);
+            }
+
+            Map<Long, PartitionItem> keyItemMap = 
partitionInfo.getIdToItem(false);
+            PartitionPruner partitionPruner = new 
RangePartitionPrunerV2(keyItemMap,
+                    partitionInfo.getPartitionColumns(), columnNameToRange);
+            Collection<Long> selectedPartitionId =  
Utils.execWithReturnVal(partitionPruner::prune);
+            scan.getSelectedPartitionIds().retainAll(selectedPartitionId);
+            return ctx.root;
+        }).toRule(RuleType.PARTITION_PRUNE);
+    }
+
+    private ColumnRange createColumnRange(String colName, List<Expression> 
expressionList) {
+        ColumnRange result = ColumnRange.create();
+        for (Expression expression : expressionList) {
+            Expression leftMostChild = expression.leftMostNode();
+            if (!(leftMostChild instanceof SlotReference)) {
+                continue;
+            }
+            SlotReference slotRef = (SlotReference) leftMostChild;
+            if (!slotRef.boundToColumn(colName)) {
+                continue;
+            }
+            if (expression instanceof Or) {
+                ColumnRanges ranges = exprToRanges(expression, colName);
+                switch (ranges.type) {
+                    case IS_NULL:
+                        result.setHasConjunctiveIsNull(true);
+                        break;
+                    case CONVERT_SUCCESS:
+                        result.intersect(ranges.ranges);
+                        break;
+                    case CONVERT_FAILURE:
+                    default:
+                        break;
+                }
+            } else {
+                ColumnRanges ranges = exprToRanges(expression, colName);
+                switch (ranges.type) {
+                    case IS_NULL:
+                        result.setHasConjunctiveIsNull(true);
+                        break;
+                    case CONVERT_SUCCESS:
+                        result.intersect(ranges.ranges);
+                        break;
+                    case CONVERT_FAILURE:
+                    default:
+                        break;
+                }
+            }
+        }
+        return result;
+    }
+
+    private ColumnRanges exprToRanges(Expression expression, String colName) {
+        // TODO: process in/is null expression
+        if (!(expression instanceof ComparisonPredicate)) {
+            return ColumnRanges.createFailure();
+        }
+        List<Range<ColumnBound>> result = Lists.newArrayList();
+        ComparisonPredicate comparisonPredicate = (ComparisonPredicate) 
expression;
+        Expression rightChild = comparisonPredicate.child(1);
+        if (rightChild == null || !rightChild.isConstant() || !(rightChild 
instanceof Literal)) {
+            return ColumnRanges.createFailure();
+        }
+        LiteralExpr value = ((Literal) rightChild).toLegacyLiteral();
+        if (expression instanceof EqualTo) {
+            ColumnBound bound = ColumnBound.of(value);
+            result.add(Range.closed(bound, bound));
+        } else if (expression instanceof GreaterThanEqual) {
+            result.add(Range.atLeast(ColumnBound.of(value)));
+        } else if (expression instanceof GreaterThan) {
+            result.add(Range.greaterThan(ColumnBound.of(value)));
+        } else if (expression instanceof LessThan) {
+            result.add(Range.atMost(ColumnBound.of(value)));

Review Comment:
   ```suggestion
               result.add(Range.LessThan(ColumnBound.of(value)));
   ```
   
   add more test please



-- 
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.

To unsubscribe, e-mail: commits-unsubscr...@doris.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscr...@doris.apache.org
For additional commands, e-mail: commits-h...@doris.apache.org

Reply via email to