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 top_n_to_vector_search_rule;
260mod values_extract_project_rule;
261
262pub use add_logstore_rule::*;
263pub use batch::batch_iceberg_count_star::*;
264pub use batch::batch_iceberg_predicate_pushdown::*;
265pub use batch::batch_push_limit_to_scan_rule::*;
266pub use pull_up_correlated_predicate_agg_rule::*;
267pub use source_to_iceberg_scan_rule::*;
268pub use source_to_kafka_scan_rule::*;
269pub use table_function_to_file_scan_rule::*;
270pub use table_function_to_internal_backfill_progress::*;
271pub use table_function_to_internal_source_backfill_progress::*;
272pub use table_function_to_mysql_query_rule::*;
273pub use table_function_to_postgres_query_rule::*;
274pub use top_n_to_vector_search_rule::*;
275pub use values_extract_project_rule::*;
276
277use crate::optimizer::plan_node::ConventionMarker;
278
279#[macro_export]
280macro_rules! for_all_rules {
281    ($macro:ident) => {
282        $macro! {
283              { ApplyAggTransposeRule }
284            , { ApplyFilterTransposeRule }
285            , { ApplyProjectTransposeRule }
286            , { ApplyProjectSetTransposeRule }
287            , { ApplyEliminateRule }
288            , { ApplyJoinTransposeRule }
289            , { ApplyShareEliminateRule }
290            , { ApplyToJoinRule }
291            , { MaxOneRowEliminateRule }
292            , { DistinctAggRule }
293            , { IndexDeltaJoinRule }
294            , { MergeMultiJoinRule }
295            , { ProjectEliminateRule }
296            , { ProjectJoinMergeRule }
297            , { ProjectMergeRule }
298            , { PullUpCorrelatedPredicateRule }
299            , { PullUpCorrelatedProjectValueRule }
300            , { LeftDeepTreeJoinOrderingRule }
301            , { TranslateApplyRule }
302            , { PushCalculationOfJoinRule }
303            , { IndexSelectionRule }
304            , { OverWindowToTopNRule }
305            , { OverWindowToAggAndJoinRule }
306            , { OverWindowSplitRule }
307            , { OverWindowMergeRule }
308            , { JoinCommuteRule }
309            , { UnionToDistinctRule }
310            , { AggProjectMergeRule }
311            , { UnionMergeRule }
312            , { DagToTreeRule }
313            , { SplitNowAndRule }
314            , { SplitNowOrRule }
315            , { FilterWithNowToJoinRule }
316            , { GenerateSeriesWithNowRule }
317            , { TopNOnIndexRule }
318            , { TrivialProjectToValuesRule }
319            , { UnionInputValuesMergeRule }
320            , { RewriteLikeExprRule }
321            , { MinMaxOnIndexRule }
322            , { AlwaysFalseFilterRule }
323            , { BushyTreeJoinOrderingRule }
324            , { StreamProjectMergeRule }
325            , { SeparateConsecutiveJoinRule }
326            , { LogicalFilterExpressionSimplifyRule }
327            , { JoinProjectTransposeRule }
328            , { LimitPushDownRule }
329            , { PullUpHopRule }
330            , { IntersectToSemiJoinRule }
331            , { ExceptToAntiJoinRule }
332            , { IntersectMergeRule }
333            , { ExceptMergeRule }
334            , { ApplyUnionTransposeRule }
335            , { ApplyDedupTransposeRule }
336            , { ProjectJoinSeparateRule }
337            , { GroupingSetsToExpandRule }
338            , { CrossJoinEliminateRule }
339            , { ApplyTopNTransposeRule }
340            , { TableFunctionToProjectSetRule }
341            , { TableFunctionToFileScanRule }
342            , { TableFunctionToPostgresQueryRule }
343            , { TableFunctionToMySqlQueryRule }
344            , { TableFunctionToInternalBackfillProgressRule }
345            , { TableFunctionToInternalSourceBackfillProgressRule }
346            , { ApplyLimitTransposeRule }
347            , { CommonSubExprExtractRule }
348            , { BatchProjectMergeRule }
349            , { ApplyOverWindowTransposeRule }
350            , { ApplyExpandTransposeRule }
351            , { ExpandToProjectRule }
352            , { AggGroupBySimplifyRule }
353            , { ApplyHopWindowTransposeRule }
354            , { AggCallMergeRule }
355            , { ValuesExtractProjectRule }
356            , { BatchPushLimitToScanRule }
357            , { BatchIcebergPredicatePushDownRule }
358            , { BatchIcebergCountStar }
359            , { PullUpCorrelatedPredicateAggRule }
360            , { SourceToKafkaScanRule }
361            , { SourceToIcebergScanRule }
362            , { AddLogstoreRule }
363            , { EmptyAggRemoveRule }
364            , { TopNToVectorSearchRule }
365        }
366    };
367}
368
369macro_rules! impl_description {
370    ($( { $name:ident }),*) => {
371        paste::paste!{
372            $(impl Description for [<$name>] {
373                fn description(&self) -> &str {
374                    stringify!([<$name>])
375                }
376            })*
377        }
378    }
379}
380
381for_all_rules! {impl_description}
382
383mod prelude {
384    pub(super) use crate::optimizer::plan_node::{Logical, LogicalPlanRef as PlanRef};
385    pub(super) use crate::optimizer::rule::Rule;
386
387    pub(super) type BoxedRule = crate::optimizer::rule::BoxedRule<Logical>;
388}