risingwave_frontend/optimizer/plan_visitor/
mod.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 paste::paste;
16mod apply_visitor;
17pub use apply_visitor::*;
18mod plan_correlated_id_finder;
19pub use plan_correlated_id_finder::*;
20mod share_parent_counter;
21pub use share_parent_counter::*;
22
23#[cfg(debug_assertions)]
24mod input_ref_validator;
25#[cfg(debug_assertions)]
26pub use input_ref_validator::*;
27
28mod execution_mode_decider;
29pub use execution_mode_decider::*;
30mod temporal_join_validator;
31pub use temporal_join_validator::*;
32mod relation_collector_visitor;
33mod sys_table_visitor;
34pub use relation_collector_visitor::*;
35pub use sys_table_visitor::*;
36mod side_effect_visitor;
37pub use side_effect_visitor::*;
38mod cardinality_visitor;
39pub use cardinality_visitor::*;
40mod jsonb_stream_key_checker;
41pub use jsonb_stream_key_checker::*;
42mod distributed_dml_visitor;
43mod locality_provider_counter;
44mod rw_timestamp_validator;
45mod sole_sys_table_visitor;
46pub use distributed_dml_visitor::*;
47pub use locality_provider_counter::*;
48pub use rw_timestamp_validator::*;
49pub use sole_sys_table_visitor::*;
50
51use crate::for_each_convention_all_plan_nodes;
52use crate::optimizer::plan_node::*;
53
54/// The behavior for the default implementations of `visit_xxx`.
55pub trait DefaultBehavior<R> {
56    /// Apply this behavior to the plan node with the given results.
57    fn apply(&self, results: impl IntoIterator<Item = R>) -> R;
58}
59
60/// Visit all input nodes, merge the results with a function.
61/// - If there's no input node, return the default value of the result type.
62/// - If there's only a single input node, directly return its result.
63pub struct Merge<F>(F);
64
65impl<F, R> DefaultBehavior<R> for Merge<F>
66where
67    F: Fn(R, R) -> R,
68    R: Default,
69{
70    fn apply(&self, results: impl IntoIterator<Item = R>) -> R {
71        results.into_iter().reduce(&self.0).unwrap_or_default()
72    }
73}
74
75/// Visit all input nodes, return the default value of the result type.
76pub struct DefaultValue;
77
78impl<R> DefaultBehavior<R> for DefaultValue
79where
80    R: Default,
81{
82    fn apply(&self, results: impl IntoIterator<Item = R>) -> R {
83        let _ = results.into_iter().count(); // consume the iterator
84        R::default()
85    }
86}
87
88pub trait PlanVisitor<C: ConventionMarker> {
89    type Result;
90    fn visit(&mut self, plan: PlanRef<C>) -> Self::Result;
91}
92
93/// Define `PlanVisitor` trait.
94macro_rules! def_visitor {
95    ({
96        $( $convention:ident, { $( $name:ident ),* }),*
97    }) => {
98        paste! {
99            $(
100                /// The visitor for plan nodes. visit all inputs and return the ret value of the left most input,
101                /// and leaf node returns `R::default()`
102                pub trait [<$convention  PlanVisitor>] {
103                    type Result: Default;
104                    type DefaultBehavior: DefaultBehavior<Self::Result>;
105
106                    /// The behavior for the default implementations of `visit_xxx`.
107                    fn default_behavior() -> Self::DefaultBehavior;
108
109                    fn [<visit_ $convention:snake>](&mut self, plan: PlanRef<$convention>) -> Self::Result {
110                        use risingwave_common::util::recursive::{tracker, Recurse};
111                        use crate::session::current::notice_to_user;
112
113                        tracker!().recurse(|t| {
114                            if t.depth_reaches(PLAN_DEPTH_THRESHOLD) {
115                                notice_to_user(PLAN_TOO_DEEP_NOTICE);
116                            }
117
118                            match plan.node_type() {
119                                $(
120                                    [<$convention PlanNodeType>]::[<$convention $name>] => self.[<visit_ $convention:snake _ $name:snake>](plan.downcast_ref::<[<$convention $name>]>().unwrap()),
121                                )*
122                            }
123                        })
124                    }
125
126                    $(
127                        #[doc = "Visit [`" [<$convention $name>] "`] , the function should visit the inputs."]
128                        fn [<visit_ $convention:snake _ $name:snake>](&mut self, plan: &[<$convention $name>]) -> Self::Result {
129                            let results = plan.inputs().into_iter().map(|input| self.[<visit_ $convention:snake>](input));
130                            Self::default_behavior().apply(results)
131                        }
132                    )*
133
134                }
135
136                impl<V: [<$convention  PlanVisitor>]> PlanVisitor<$convention> for V {
137                    type Result = V::Result;
138                    fn visit(&mut self, plan: PlanRef<$convention>) -> Self::Result {
139                        self.[<visit_ $convention:snake>](plan)
140                    }
141                }
142            )*
143        }
144    }
145}
146
147for_each_convention_all_plan_nodes! { def_visitor }
148
149macro_rules! impl_has_variant {
150    ( $({$convention:ident $variant_name:ident}),* ) => {
151        paste! {
152            $(
153                pub fn [<has_ $convention:snake _ $variant_name:snake _where>]<P>(plan: PlanRef<$convention>, pred: P) -> bool
154                where
155                    P: FnMut(&[<$convention $variant_name>]) -> bool,
156                {
157                    struct HasWhere<P> {
158                        pred: P,
159                    }
160
161                    impl<P> [<$convention PlanVisitor>] for HasWhere<P>
162                    where
163                        P: FnMut(&[<$convention $variant_name>]) -> bool,
164                    {
165                        type Result = bool;
166                        type DefaultBehavior = impl DefaultBehavior<Self::Result>;
167
168                        fn default_behavior() -> Self::DefaultBehavior {
169                            Merge(|a, b| a | b)
170                        }
171
172                        fn [<visit_ $convention:snake _ $variant_name:snake>](&mut self, node: &[<$convention $variant_name>]) -> Self::Result {
173                            (self.pred)(node)
174                        }
175                    }
176
177                    let mut visitor = HasWhere { pred };
178                    visitor.visit(plan)
179                }
180
181                #[allow(dead_code)]
182                pub fn [<has_ $convention:snake _ $variant_name:snake>](plan: PlanRef<$convention>) -> bool {
183                    [<has_ $convention:snake _$variant_name:snake _where>](plan, |_| true)
184                }
185            )*
186        }
187    };
188}
189
190impl_has_variant! {
191    {Logical Apply},
192    {Logical MaxOneRow},
193    {Logical OverWindow},
194    {Logical Scan},
195    {Logical Source},
196    {Batch Exchange},
197    {Batch SeqScan},
198    {Batch Source},
199    {Batch Insert},
200    {Batch Delete},
201    {Batch Update}
202}