risingwave_frontend/optimizer/rule/
common_sub_expr_extract_rule.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// Copyright 2024 RisingWave Labs
//
// Licensed 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.

use itertools::Itertools;

use super::super::plan_node::*;
use super::{BoxedRule, Rule};
use crate::expr::{ExprImpl, ExprRewriter, ExprVisitor, InputRef};
use crate::optimizer::plan_expr_rewriter::CseRewriter;
use crate::optimizer::plan_expr_visitor::CseExprCounter;
use crate::optimizer::plan_node::generic::GenericPlanRef;

pub struct CommonSubExprExtractRule {}
impl Rule for CommonSubExprExtractRule {
    fn apply(&self, plan: PlanRef) -> Option<PlanRef> {
        let project: &LogicalProject = plan.as_logical_project()?;

        let mut expr_counter = CseExprCounter::default();
        for expr in project.exprs() {
            expr_counter.visit_expr(expr);
        }

        if expr_counter.counter.values().all(|counter| *counter <= 1) {
            return None;
        }

        let (exprs, input) = project.clone().decompose();
        let input_schema_len = input.schema().len();
        let mut cse_rewriter = CseRewriter::new(expr_counter, input_schema_len);
        let top_project_exprs = exprs
            .into_iter()
            .map(|expr| cse_rewriter.rewrite_expr(expr))
            .collect_vec();
        let bottom_project_exprs = {
            let mut exprs = Vec::with_capacity(input_schema_len + cse_rewriter.cse_mapping.len());
            for (i, field) in input.schema().fields.iter().enumerate() {
                let expr = ExprImpl::InputRef(InputRef::new(i, field.data_type.clone()).into());
                exprs.push(expr);
            }
            exprs.extend(
                cse_rewriter
                    .cse_mapping
                    .into_iter()
                    .sorted_by(|(_, v1), (_, v2)| Ord::cmp(&v1.index, &v2.index))
                    .map(|(k, _)| ExprImpl::FunctionCall(k.into())),
            );
            exprs
        };
        let bottom_project = LogicalProject::new(input, bottom_project_exprs);
        let top_project = LogicalProject::new(bottom_project.into(), top_project_exprs);
        Some(top_project.into())
    }
}

impl CommonSubExprExtractRule {
    pub fn create() -> BoxedRule {
        Box::new(CommonSubExprExtractRule {})
    }
}