risingwave_frontend/optimizer/rule/
cross_join_eliminate_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 risingwave_pb::plan_common::JoinType;
16
17use super::prelude::{PlanRef, *};
18use crate::optimizer::plan_node::{LogicalJoin, LogicalValues};
19
20/// Eliminate trivial cross join generated by subquery unnesting.
21///
22/// Before:
23///
24/// ```text
25///             LogicalJoin (join type: inner, on condition: true)
26///             /      \
27///          Input    Value (with one row but no columns)
28/// ```
29///
30/// After:
31///
32///
33/// ```text
34///              Input
35/// ```
36pub struct CrossJoinEliminateRule {}
37impl Rule<Logical> for CrossJoinEliminateRule {
38    fn apply(&self, plan: PlanRef) -> Option<PlanRef> {
39        let join: &LogicalJoin = plan.as_logical_join()?;
40        let (left, right, on, join_type, _output_indices) = join.clone().decompose();
41        let values: &LogicalValues = right.as_logical_values()?;
42        if on.always_true() // cross join
43            && join_type == JoinType::Inner
44            && values.rows().len() == 1 // one row
45            && values.rows()[0].is_empty() // no columns
46            && join.output_indices_are_trivial()
47        {
48            Some(left)
49        } else {
50            None
51        }
52    }
53}
54
55impl CrossJoinEliminateRule {
56    pub fn create() -> BoxedRule {
57        Box::new(CrossJoinEliminateRule {})
58    }
59}