risingwave_frontend/optimizer/rule/
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
15//! Define all [`Rule`]
16
17use std::convert::Infallible;
18use std::ops::FromResidual;
19
20use thiserror_ext::AsReport;
21
22use super::PlanRef;
23use crate::error::RwError;
24
25/// Result when applying a [`Rule`] to a `PlanNode`
26pub enum ApplyResult<T> {
27    /// Successfully applied the rule and returned a new plan.
28    Ok(T),
29    /// The current rule is not applicable to the input.
30    /// The optimizer may try another rule.
31    NotApplicable,
32    /// An unrecoverable error occurred while applying the rule.
33    /// The optimizer should stop applying other rules and report the error to the user.
34    Err(RwError),
35}
36
37impl<T> ApplyResult<T> {
38    /// Unwrap the result, panicking if it's not `Ok`.
39    pub fn unwrap(self) -> T {
40        match self {
41            ApplyResult::Ok(plan) => plan,
42            ApplyResult::NotApplicable => panic!("unwrap ApplyResult::NotApplicable"),
43            ApplyResult::Err(e) => panic!("unwrap ApplyResult::Err, error: {:?}", e.as_report()),
44        }
45    }
46}
47
48/// Allow calling `?` on an `Option` in a function returning `ApplyResult`.
49impl<T> FromResidual<Option<Infallible>> for ApplyResult<T> {
50    fn from_residual(residual: Option<Infallible>) -> Self {
51        match residual {
52            Some(i) => match i {},
53            None => Self::NotApplicable,
54        }
55    }
56}
57
58/// Allow calling `?` on a `Result` in a function returning `ApplyResult`.
59impl<T, E> FromResidual<Result<Infallible, E>> for ApplyResult<T>
60where
61    E: Into<RwError>,
62{
63    fn from_residual(residual: Result<Infallible, E>) -> Self {
64        match residual {
65            Ok(i) => match i {},
66            Err(e) => Self::Err(e.into()),
67        }
68    }
69}
70
71/// An one-to-one transform for the `PlanNode`.
72///
73/// It's a convenient trait to implement [`FallibleRule`], thus made available only within this module.
74trait InfallibleRule<C: ConventionMarker>: Send + Sync + Description {
75    /// Apply the rule to the plan node.
76    ///
77    /// - Returns `Some` if the apply is successful.
78    /// - Returns `None` if it's not applicable. The optimizer may try other rules.
79    fn apply(&self, plan: PlanRef<C>) -> Option<PlanRef<C>>;
80}
81
82use InfallibleRule as Rule;
83
84/// An one-to-one transform for the `PlanNode` that may return an
85/// unrecoverable error that stops further optimization.
86///
87/// An [`InfallibleRule`] is always a [`FallibleRule`].
88pub trait FallibleRule<C: ConventionMarker>: Send + Sync + Description {
89    /// Apply the rule to the plan node, which may return an unrecoverable error.
90    ///
91    /// - Returns `ApplyResult::Ok` if the apply is successful.
92    /// - Returns `ApplyResult::NotApplicable` if it's not applicable. The optimizer may try other rules.
93    /// - Returns `ApplyResult::Err` if an unrecoverable error occurred. The optimizer should stop applying
94    ///   other rules and report the error to the user.
95    fn apply(&self, plan: PlanRef<C>) -> ApplyResult<PlanRef<C>>;
96}
97
98impl<C: ConventionMarker, R> FallibleRule<C> for R
99where
100    R: InfallibleRule<C>,
101{
102    fn apply(&self, plan: PlanRef<C>) -> ApplyResult<PlanRef<C>> {
103        match InfallibleRule::apply(self, plan) {
104            Some(plan) => ApplyResult::Ok(plan),
105            None => ApplyResult::NotApplicable,
106        }
107    }
108}
109
110pub trait Description {
111    fn description(&self) -> &str;
112}
113
114pub(super) type BoxedRule<C> = Box<dyn FallibleRule<C>>;
115
116mod correlated_expr_rewriter;
117mod logical_filter_expression_simplify_rule;
118pub use logical_filter_expression_simplify_rule::*;
119mod over_window_merge_rule;
120pub use over_window_merge_rule::*;
121mod project_join_merge_rule;
122pub use project_join_merge_rule::*;
123mod project_eliminate_rule;
124pub use project_eliminate_rule::*;
125mod project_merge_rule;
126pub use project_merge_rule::*;
127mod pull_up_correlated_predicate_rule;
128pub use pull_up_correlated_predicate_rule::*;
129mod pull_up_correlated_project_value_rule;
130pub use pull_up_correlated_project_value_rule::*;
131mod index_delta_join_rule;
132pub use index_delta_join_rule::*;
133mod left_deep_tree_join_ordering_rule;
134pub use left_deep_tree_join_ordering_rule::*;
135mod apply_agg_transpose_rule;
136pub use apply_agg_transpose_rule::*;
137mod apply_filter_transpose_rule;
138pub use apply_filter_transpose_rule::*;
139mod apply_project_transpose_rule;
140pub use apply_project_transpose_rule::*;
141mod apply_eliminate_rule;
142pub use apply_eliminate_rule::*;
143mod translate_apply_rule;
144pub use translate_apply_rule::*;
145mod merge_multijoin_rule;
146pub use merge_multijoin_rule::*;
147mod max_one_row_eliminate_rule;
148pub use max_one_row_eliminate_rule::*;
149mod apply_join_transpose_rule;
150pub use apply_join_transpose_rule::*;
151mod apply_to_join_rule;
152pub use apply_to_join_rule::*;
153mod distinct_agg_rule;
154pub use distinct_agg_rule::*;
155mod index_selection_rule;
156pub use index_selection_rule::*;
157mod push_calculation_of_join_rule;
158pub use push_calculation_of_join_rule::*;
159mod join_commute_rule;
160mod over_window_to_agg_and_join_rule;
161pub use over_window_to_agg_and_join_rule::*;
162mod over_window_split_rule;
163pub use over_window_split_rule::*;
164mod over_window_to_topn_rule;
165pub use join_commute_rule::*;
166pub use over_window_to_topn_rule::*;
167mod union_to_distinct_rule;
168pub use union_to_distinct_rule::*;
169mod agg_project_merge_rule;
170pub use agg_project_merge_rule::*;
171mod union_merge_rule;
172pub use union_merge_rule::*;
173mod dag_to_tree_rule;
174pub use dag_to_tree_rule::*;
175mod apply_share_eliminate_rule;
176pub use apply_share_eliminate_rule::*;
177mod top_n_on_index_rule;
178pub use top_n_on_index_rule::*;
179mod stream;
180pub use stream::bushy_tree_join_ordering_rule::*;
181pub use stream::filter_with_now_to_join_rule::*;
182pub use stream::generate_series_with_now_rule::*;
183pub use stream::separate_consecutive_join_rule::*;
184pub use stream::split_now_and_rule::*;
185pub use stream::split_now_or_rule::*;
186pub use stream::stream_project_merge_rule::*;
187mod trivial_project_to_values_rule;
188pub use trivial_project_to_values_rule::*;
189mod union_input_values_merge_rule;
190pub use union_input_values_merge_rule::*;
191mod rewrite_like_expr_rule;
192pub use rewrite_like_expr_rule::*;
193mod min_max_on_index_rule;
194pub use min_max_on_index_rule::*;
195mod always_false_filter_rule;
196pub use always_false_filter_rule::*;
197mod join_project_transpose_rule;
198pub use join_project_transpose_rule::*;
199mod limit_push_down_rule;
200pub use limit_push_down_rule::*;
201mod pull_up_hop_rule;
202pub use pull_up_hop_rule::*;
203mod apply_offset_rewriter;
204use apply_offset_rewriter::ApplyOffsetRewriter;
205mod intersect_to_semi_join_rule;
206pub use intersect_to_semi_join_rule::*;
207mod except_to_anti_join_rule;
208pub use except_to_anti_join_rule::*;
209mod intersect_merge_rule;
210pub use intersect_merge_rule::*;
211mod except_merge_rule;
212pub use except_merge_rule::*;
213mod apply_union_transpose_rule;
214pub use apply_union_transpose_rule::*;
215mod apply_dedup_transpose_rule;
216pub use apply_dedup_transpose_rule::*;
217mod project_join_separate_rule;
218pub use project_join_separate_rule::*;
219mod grouping_sets_to_expand_rule;
220pub use grouping_sets_to_expand_rule::*;
221mod apply_project_set_transpose_rule;
222pub use apply_project_set_transpose_rule::*;
223mod cross_join_eliminate_rule;
224pub use cross_join_eliminate_rule::*;
225mod table_function_to_project_set_rule;
226
227pub use table_function_to_project_set_rule::*;
228mod apply_topn_transpose_rule;
229pub use apply_topn_transpose_rule::*;
230mod apply_limit_transpose_rule;
231pub use apply_limit_transpose_rule::*;
232mod batch;
233pub use batch::batch_project_merge_rule::*;
234mod common_sub_expr_extract_rule;
235pub use common_sub_expr_extract_rule::*;
236mod apply_over_window_transpose_rule;
237pub use apply_over_window_transpose_rule::*;
238mod apply_expand_transpose_rule;
239pub use apply_expand_transpose_rule::*;
240mod expand_to_project_rule;
241pub use expand_to_project_rule::*;
242mod agg_group_by_simplify_rule;
243pub use agg_group_by_simplify_rule::*;
244mod apply_hop_window_transpose_rule;
245pub use apply_hop_window_transpose_rule::*;
246mod agg_call_merge_rule;
247pub use agg_call_merge_rule::*;
248mod empty_agg_remove_rule;
249pub use empty_agg_remove_rule::*;
250mod add_logstore_rule;
251mod pull_up_correlated_predicate_agg_rule;
252mod source_to_iceberg_scan_rule;
253mod source_to_kafka_scan_rule;
254mod table_function_to_file_scan_rule;
255mod table_function_to_internal_backfill_progress;
256mod table_function_to_internal_source_backfill_progress;
257mod table_function_to_mysql_query_rule;
258mod table_function_to_postgres_query_rule;
259mod values_extract_project_rule;
260
261pub use add_logstore_rule::*;
262pub use batch::batch_iceberg_count_star::*;
263pub use batch::batch_iceberg_predicate_pushdown::*;
264pub use batch::batch_push_limit_to_scan_rule::*;
265pub use pull_up_correlated_predicate_agg_rule::*;
266pub use source_to_iceberg_scan_rule::*;
267pub use source_to_kafka_scan_rule::*;
268pub use table_function_to_file_scan_rule::*;
269pub use table_function_to_internal_backfill_progress::*;
270pub use table_function_to_internal_source_backfill_progress::*;
271pub use table_function_to_mysql_query_rule::*;
272pub use table_function_to_postgres_query_rule::*;
273pub use values_extract_project_rule::*;
274
275use crate::optimizer::plan_node::ConventionMarker;
276
277#[macro_export]
278macro_rules! for_all_rules {
279    ($macro:ident) => {
280        $macro! {
281              { ApplyAggTransposeRule }
282            , { ApplyFilterTransposeRule }
283            , { ApplyProjectTransposeRule }
284            , { ApplyProjectSetTransposeRule }
285            , { ApplyEliminateRule }
286            , { ApplyJoinTransposeRule }
287            , { ApplyShareEliminateRule }
288            , { ApplyToJoinRule }
289            , { MaxOneRowEliminateRule }
290            , { DistinctAggRule }
291            , { IndexDeltaJoinRule }
292            , { MergeMultiJoinRule }
293            , { ProjectEliminateRule }
294            , { ProjectJoinMergeRule }
295            , { ProjectMergeRule }
296            , { PullUpCorrelatedPredicateRule }
297            , { PullUpCorrelatedProjectValueRule }
298            , { LeftDeepTreeJoinOrderingRule }
299            , { TranslateApplyRule }
300            , { PushCalculationOfJoinRule }
301            , { IndexSelectionRule }
302            , { OverWindowToTopNRule }
303            , { OverWindowToAggAndJoinRule }
304            , { OverWindowSplitRule }
305            , { OverWindowMergeRule }
306            , { JoinCommuteRule }
307            , { UnionToDistinctRule }
308            , { AggProjectMergeRule }
309            , { UnionMergeRule }
310            , { DagToTreeRule }
311            , { SplitNowAndRule }
312            , { SplitNowOrRule }
313            , { FilterWithNowToJoinRule }
314            , { GenerateSeriesWithNowRule }
315            , { TopNOnIndexRule }
316            , { TrivialProjectToValuesRule }
317            , { UnionInputValuesMergeRule }
318            , { RewriteLikeExprRule }
319            , { MinMaxOnIndexRule }
320            , { AlwaysFalseFilterRule }
321            , { BushyTreeJoinOrderingRule }
322            , { StreamProjectMergeRule }
323            , { SeparateConsecutiveJoinRule }
324            , { LogicalFilterExpressionSimplifyRule }
325            , { JoinProjectTransposeRule }
326            , { LimitPushDownRule }
327            , { PullUpHopRule }
328            , { IntersectToSemiJoinRule }
329            , { ExceptToAntiJoinRule }
330            , { IntersectMergeRule }
331            , { ExceptMergeRule }
332            , { ApplyUnionTransposeRule }
333            , { ApplyDedupTransposeRule }
334            , { ProjectJoinSeparateRule }
335            , { GroupingSetsToExpandRule }
336            , { CrossJoinEliminateRule }
337            , { ApplyTopNTransposeRule }
338            , { TableFunctionToProjectSetRule }
339            , { TableFunctionToFileScanRule }
340            , { TableFunctionToPostgresQueryRule }
341            , { TableFunctionToMySqlQueryRule }
342            , { TableFunctionToInternalBackfillProgressRule }
343            , { TableFunctionToInternalSourceBackfillProgressRule }
344            , { ApplyLimitTransposeRule }
345            , { CommonSubExprExtractRule }
346            , { BatchProjectMergeRule }
347            , { ApplyOverWindowTransposeRule }
348            , { ApplyExpandTransposeRule }
349            , { ExpandToProjectRule }
350            , { AggGroupBySimplifyRule }
351            , { ApplyHopWindowTransposeRule }
352            , { AggCallMergeRule }
353            , { ValuesExtractProjectRule }
354            , { BatchPushLimitToScanRule }
355            , { BatchIcebergPredicatePushDownRule }
356            , { BatchIcebergCountStar }
357            , { PullUpCorrelatedPredicateAggRule }
358            , { SourceToKafkaScanRule }
359            , { SourceToIcebergScanRule }
360            , { AddLogstoreRule }
361            , { EmptyAggRemoveRule }
362        }
363    };
364}
365
366macro_rules! impl_description {
367    ($( { $name:ident }),*) => {
368        paste::paste!{
369            $(impl Description for [<$name>] {
370                fn description(&self) -> &str {
371                    stringify!([<$name>])
372                }
373            })*
374        }
375    }
376}
377
378for_all_rules! {impl_description}
379
380mod prelude {
381    pub(super) use crate::optimizer::plan_node::{Logical, LogicalPlanRef as PlanRef};
382    pub(super) use crate::optimizer::rule::Rule;
383
384    pub(super) type BoxedRule = crate::optimizer::rule::BoxedRule<Logical>;
385}