Skip to main content

risingwave_frontend/optimizer/rule/
project_merge_rule.rs

1// Copyright 2022 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    /// With `keep_common_sub_func`, returns `None` if an inner expression other than a column
25    /// reference or a literal is referenced more than once: substituting it would evaluate it
26    /// once per reference, which repeats its cost and can give different values if it is impure.
27    pub fn merge_project_exprs(
28        outer_project_exprs: &[ExprImpl],
29        inner_project_exprs: &[ExprImpl],
30        keep_common_sub_func: bool,
31    ) -> Option<Vec<ExprImpl>> {
32        if keep_common_sub_func {
33            let mut input_ref_counter = InputRefCounter::default();
34            for expr in outer_project_exprs {
35                input_ref_counter.visit_expr(expr);
36            }
37            for (index, count) in &input_ref_counter.counter {
38                if *count > 1
39                    && !matches!(
40                        inner_project_exprs[*index],
41                        ExprImpl::InputRef(_)
42                            | ExprImpl::CorrelatedInputRef(_)
43                            | ExprImpl::Literal(_)
44                    )
45                {
46                    return None;
47                }
48            }
49        }
50
51        let mut subst = Substitute {
52            mapping: inner_project_exprs.to_vec(),
53        };
54        let exprs = outer_project_exprs
55            .iter()
56            .cloned()
57            .map(|expr| subst.rewrite_expr(expr))
58            .collect();
59        Some(exprs)
60    }
61}
62
63impl ProjectMergeRule {
64    pub fn create() -> BoxedRule {
65        Box::new(ProjectMergeRule {})
66    }
67}
68
69impl Rule<Logical> for ProjectMergeRule {
70    fn apply(&self, plan: PlanRef) -> Option<PlanRef> {
71        let outer_project: &LogicalProject = plan.as_logical_project()?;
72        let input = outer_project.input();
73        let inner_project: &LogicalProject = input.as_logical_project()?;
74
75        let exprs = Self::merge_project_exprs(outer_project.exprs(), inner_project.exprs(), true)?;
76        Some(LogicalProject::new(inner_project.input(), exprs).into())
77    }
78}