Skip to main content

risingwave_frontend/optimizer/rule/stream/
stream_project_merge_rule.rs

1// Copyright 2023 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::*;
16use super::stream_project_split_rule::{has_mixed_computations, is_trivial_expr};
17use crate::expr::ExprImpl;
18use crate::optimizer::plan_node::{PlanTreeNodeUnary, StreamProject};
19use crate::optimizer::rule::ProjectMergeRule;
20
21/// Merge contiguous [`StreamProject`] nodes.
22pub struct StreamProjectMergeRule {}
23impl Rule<Stream> for StreamProjectMergeRule {
24    fn apply(&self, plan: PlanRef) -> Option<PlanRef> {
25        let outer_project = plan.as_stream_project()?;
26        let input = outer_project.input();
27        let inner_project = input.as_stream_project()?;
28
29        // Keep evaluated async results as column references. Inlining them into a conditional
30        // or lambda can change which rows evaluate the call, even without duplicating its tree.
31        if inner_project.exprs().iter().any(ExprImpl::is_async)
32            && outer_project
33                .exprs()
34                .iter()
35                .any(|expr| !is_trivial_expr(expr))
36        {
37            return None;
38        }
39
40        let mut core = outer_project.core().clone();
41        core.exprs = ProjectMergeRule::merge_project_exprs(
42            outer_project.exprs(),
43            inner_project.exprs(),
44            true,
45        )?;
46        if has_mixed_computations(&core.exprs) {
47            return None;
48        }
49        core.input = inner_project.input();
50
51        // If either of the projects has the hint, we should keep it.
52        let noop_update_hint = outer_project.noop_update_hint() || inner_project.noop_update_hint();
53
54        Some(
55            StreamProject::new(core)
56                .with_noop_update_hint(noop_update_hint)
57                .into(),
58        )
59    }
60}
61
62impl StreamProjectMergeRule {
63    pub fn create() -> BoxedRule {
64        Box::new(StreamProjectMergeRule {})
65    }
66}