risingwave_frontend/optimizer/rule/
project_merge_rule.rs

1// Copyright 2025 RisingWave Labs
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use super::prelude::{PlanRef, *};
16use crate::expr::{ExprImpl, ExprRewriter, ExprVisitor};
17use crate::optimizer::plan_expr_visitor::InputRefCounter;
18use crate::optimizer::plan_node::*;
19use crate::utils::Substitute;
20
21/// Merge contiguous [`LogicalProject`] nodes.
22pub struct ProjectMergeRule {}
23impl ProjectMergeRule {
24    pub fn merge_project_exprs(
25        outer_project_exprs: &[ExprImpl],
26        inner_project_exprs: &[ExprImpl],
27        keep_common_sub_func: bool,
28    ) -> Option<Vec<ExprImpl>> {
29        let mut input_ref_counter = InputRefCounter::default();
30        if keep_common_sub_func {
31            for expr in outer_project_exprs {
32                input_ref_counter.visit_expr(expr);
33            }
34            // bail out if it is a project generated by `CommonSubExprExtractRule`.
35            for (index, count) in &input_ref_counter.counter {
36                if *count > 1 && matches!(inner_project_exprs[*index], ExprImpl::FunctionCall(_)) {
37                    return None;
38                }
39            }
40        }
41
42        let mut subst = Substitute {
43            mapping: inner_project_exprs.to_vec(),
44        };
45        let exprs = outer_project_exprs
46            .iter()
47            .cloned()
48            .map(|expr| subst.rewrite_expr(expr))
49            .collect();
50        Some(exprs)
51    }
52}
53
54impl ProjectMergeRule {
55    pub fn create() -> BoxedRule {
56        Box::new(ProjectMergeRule {})
57    }
58}
59
60impl Rule<Logical> for ProjectMergeRule {
61    fn apply(&self, plan: PlanRef) -> Option<PlanRef> {
62        let outer_project: &LogicalProject = plan.as_logical_project()?;
63        let input = outer_project.input();
64        let inner_project: &LogicalProject = input.as_logical_project()?;
65
66        let exprs = Self::merge_project_exprs(outer_project.exprs(), inner_project.exprs(), true)?;
67        Some(LogicalProject::new(inner_project.input(), exprs).into())
68    }
69}