risingwave_frontend/optimizer/rule/union_to_distinct_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 super::prelude::{PlanRef, *};
16use crate::optimizer::plan_node::generic::{Agg, GenericPlanRef};
17use crate::optimizer::plan_node::{LogicalUnion, PlanTreeNode};
18
19/// Convert union to distinct + union all
20pub struct UnionToDistinctRule {}
21impl Rule<Logical> for UnionToDistinctRule {
22 fn apply(&self, plan: PlanRef) -> Option<PlanRef> {
23 let union: &LogicalUnion = plan.as_logical_union()?;
24 if !union.all() {
25 let union_all = LogicalUnion::create(true, union.inputs().into_iter().collect());
26 let distinct = Agg::new(vec![], (0..union.base.schema().len()).collect(), union_all)
27 .with_enable_two_phase(false);
28 Some(distinct.into())
29 } else {
30 None
31 }
32 }
33}
34
35impl UnionToDistinctRule {
36 pub fn create() -> BoxedRule {
37 Box::new(UnionToDistinctRule {})
38 }
39}