risingwave_frontend/optimizer/rule/
intersect_to_semi_join_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_common::types::DataType::Boolean;
16use risingwave_common::util::iter_util::ZipEqDebug;
17use risingwave_pb::plan_common::JoinType;
18
19use super::prelude::{PlanRef, *};
20use crate::expr::{ExprImpl, ExprType, FunctionCall, InputRef};
21use crate::optimizer::plan_node::generic::Agg;
22use crate::optimizer::plan_node::{LogicalIntersect, LogicalJoin, PlanTreeNode};
23
24pub struct IntersectToSemiJoinRule {}
25impl Rule<Logical> for IntersectToSemiJoinRule {
26    fn apply(&self, plan: PlanRef) -> Option<PlanRef> {
27        let logical_intersect: &LogicalIntersect = plan.as_logical_intersect()?;
28        let all = logical_intersect.all();
29        if all {
30            return None;
31        }
32
33        let inputs = logical_intersect.inputs();
34        let join = inputs
35            .into_iter()
36            .fold(None, |left, right| match left {
37                None => Some(right),
38                Some(left) => {
39                    let on =
40                        IntersectToSemiJoinRule::gen_null_safe_equal(left.clone(), right.clone());
41                    Some(LogicalJoin::create(left, right, JoinType::LeftSemi, on))
42                }
43            })
44            .unwrap();
45
46        Some(Agg::new(vec![], (0..join.schema().len()).collect(), join).into())
47    }
48}
49
50impl IntersectToSemiJoinRule {
51    pub(crate) fn gen_null_safe_equal(left: PlanRef, right: PlanRef) -> ExprImpl {
52        let arms = (left
53            .schema()
54            .fields()
55            .iter()
56            .zip_eq_debug(right.schema().fields())
57            .enumerate())
58        .map(|(i, (left_field, right_field))| {
59            ExprImpl::FunctionCall(Box::new(FunctionCall::new_unchecked(
60                ExprType::IsNotDistinctFrom,
61                vec![
62                    ExprImpl::InputRef(Box::new(InputRef::new(i, left_field.data_type()))),
63                    ExprImpl::InputRef(Box::new(InputRef::new(
64                        i + left.schema().len(),
65                        right_field.data_type(),
66                    ))),
67                ],
68                Boolean,
69            )))
70        });
71        ExprImpl::and(arms)
72    }
73}
74
75impl IntersectToSemiJoinRule {
76    pub fn create() -> BoxedRule {
77        Box::new(IntersectToSemiJoinRule {})
78    }
79}