risingwave_frontend/optimizer/rule/
mod.rs

1// Copyright 2022 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 project_top_n_transpose_rule;
128pub use project_top_n_transpose_rule::*;
129mod top_n_project_transpose_rule;
130pub use top_n_project_transpose_rule::*;
131mod pull_up_correlated_predicate_rule;
132pub use pull_up_correlated_predicate_rule::*;
133mod pull_up_correlated_project_value_rule;
134pub use pull_up_correlated_project_value_rule::*;
135mod index_delta_join_rule;
136pub use index_delta_join_rule::*;
137mod left_deep_tree_join_ordering_rule;
138pub use left_deep_tree_join_ordering_rule::*;
139mod apply_agg_transpose_rule;
140pub use apply_agg_transpose_rule::*;
141mod apply_filter_transpose_rule;
142pub use apply_filter_transpose_rule::*;
143mod apply_project_transpose_rule;
144pub use apply_project_transpose_rule::*;
145mod apply_eliminate_rule;
146pub use apply_eliminate_rule::*;
147mod translate_apply_rule;
148pub use translate_apply_rule::*;
149mod merge_multijoin_rule;
150pub use merge_multijoin_rule::*;
151mod max_one_row_eliminate_rule;
152pub use max_one_row_eliminate_rule::*;
153mod apply_join_transpose_rule;
154pub use apply_join_transpose_rule::*;
155mod apply_to_join_rule;
156pub use apply_to_join_rule::*;
157mod distinct_agg_rule;
158pub use distinct_agg_rule::*;
159mod index_selection_rule;
160pub use index_selection_rule::*;
161mod push_calculation_of_join_rule;
162pub use push_calculation_of_join_rule::*;
163mod join_commute_rule;
164mod over_window_to_agg_and_join_rule;
165pub use over_window_to_agg_and_join_rule::*;
166mod over_window_split_rule;
167pub use over_window_split_rule::*;
168mod over_window_to_topn_rule;
169pub use join_commute_rule::*;
170pub use over_window_to_topn_rule::*;
171mod union_to_distinct_rule;
172pub use union_to_distinct_rule::*;
173mod agg_project_merge_rule;
174pub use agg_project_merge_rule::*;
175mod union_merge_rule;
176pub use union_merge_rule::*;
177mod dag_to_tree_rule;
178pub use dag_to_tree_rule::*;
179mod apply_share_eliminate_rule;
180pub use apply_share_eliminate_rule::*;
181mod top_n_on_index_rule;
182pub use top_n_on_index_rule::*;
183mod stream;
184pub use stream::bushy_tree_join_ordering_rule::*;
185pub use stream::filter_with_now_to_join_rule::*;
186pub use stream::generate_series_with_now_rule::*;
187pub use stream::separate_consecutive_join_rule::*;
188pub use stream::split_now_and_rule::*;
189pub use stream::split_now_or_rule::*;
190pub use stream::stream_project_merge_rule::*;
191mod trivial_project_to_values_rule;
192pub use trivial_project_to_values_rule::*;
193mod union_input_values_merge_rule;
194pub use union_input_values_merge_rule::*;
195mod rewrite_like_expr_rule;
196pub use rewrite_like_expr_rule::*;
197mod min_max_on_index_rule;
198pub use min_max_on_index_rule::*;
199mod always_false_filter_rule;
200pub use always_false_filter_rule::*;
201mod join_project_transpose_rule;
202pub use join_project_transpose_rule::*;
203mod limit_push_down_rule;
204pub use limit_push_down_rule::*;
205mod pull_up_hop_rule;
206pub use pull_up_hop_rule::*;
207mod apply_offset_rewriter;
208use apply_offset_rewriter::ApplyOffsetRewriter;
209mod intersect_to_semi_join_rule;
210pub use intersect_to_semi_join_rule::*;
211mod except_to_anti_join_rule;
212pub use except_to_anti_join_rule::*;
213mod intersect_merge_rule;
214pub use intersect_merge_rule::*;
215mod except_merge_rule;
216pub use except_merge_rule::*;
217mod apply_union_transpose_rule;
218pub use apply_union_transpose_rule::*;
219mod apply_dedup_transpose_rule;
220pub use apply_dedup_transpose_rule::*;
221mod project_join_separate_rule;
222pub use project_join_separate_rule::*;
223mod grouping_sets_to_expand_rule;
224pub use grouping_sets_to_expand_rule::*;
225mod apply_project_set_transpose_rule;
226pub use apply_project_set_transpose_rule::*;
227mod apply_table_function_to_project_set_rule;
228pub use apply_table_function_to_project_set_rule::*;
229mod cross_join_eliminate_rule;
230pub use cross_join_eliminate_rule::*;
231mod table_function_to_project_set_rule;
232
233pub use table_function_to_project_set_rule::*;
234mod apply_topn_transpose_rule;
235pub use apply_topn_transpose_rule::*;
236mod apply_limit_transpose_rule;
237pub use apply_limit_transpose_rule::*;
238mod batch;
239pub use batch::batch_project_merge_rule::*;
240mod common_sub_expr_extract_rule;
241pub use common_sub_expr_extract_rule::*;
242mod apply_over_window_transpose_rule;
243pub use apply_over_window_transpose_rule::*;
244mod apply_expand_transpose_rule;
245pub use apply_expand_transpose_rule::*;
246mod expand_to_project_rule;
247pub use expand_to_project_rule::*;
248mod agg_group_by_simplify_rule;
249pub use agg_group_by_simplify_rule::*;
250mod apply_hop_window_transpose_rule;
251pub use apply_hop_window_transpose_rule::*;
252mod agg_call_merge_rule;
253pub use agg_call_merge_rule::*;
254mod unify_first_last_value_rule;
255pub use unify_first_last_value_rule::*;
256mod empty_agg_remove_rule;
257pub use empty_agg_remove_rule::*;
258mod add_logstore_rule;
259mod correlated_topn_to_vector_search;
260mod iceberg_count_star_rule;
261mod iceberg_intermediate_scan_rule;
262mod pull_up_correlated_predicate_agg_rule;
263mod source_to_iceberg_intermediate_scan_rule;
264mod source_to_kafka_scan_rule;
265mod table_function_to_file_scan_rule;
266mod table_function_to_internal_backfill_progress;
267mod table_function_to_internal_get_channel_delta_stats;
268mod table_function_to_internal_source_backfill_progress;
269mod table_function_to_mysql_query_rule;
270mod table_function_to_postgres_query_rule;
271mod top_n_to_vector_search_rule;
272mod values_extract_project_rule;
273pub use add_logstore_rule::*;
274pub use batch::batch_push_limit_to_scan_rule::*;
275pub use correlated_topn_to_vector_search::*;
276pub use iceberg_count_star_rule::IcebergCountStarRule;
277pub use iceberg_intermediate_scan_rule::*;
278pub use pull_up_correlated_predicate_agg_rule::*;
279pub use source_to_iceberg_intermediate_scan_rule::*;
280pub use source_to_kafka_scan_rule::*;
281pub use table_function_to_file_scan_rule::*;
282pub use table_function_to_internal_backfill_progress::*;
283pub use table_function_to_internal_get_channel_delta_stats::*;
284pub use table_function_to_internal_source_backfill_progress::*;
285pub use table_function_to_mysql_query_rule::*;
286pub use table_function_to_postgres_query_rule::*;
287pub use top_n_to_vector_search_rule::*;
288pub use values_extract_project_rule::*;
289
290use crate::optimizer::plan_node::ConventionMarker;
291
292#[macro_export]
293macro_rules! for_all_rules {
294    ($macro:ident) => {
295        $macro! {
296              { ApplyAggTransposeRule }
297            , { ApplyFilterTransposeRule }
298            , { ApplyProjectTransposeRule }
299            , { ApplyProjectSetTransposeRule }
300            , { ApplyTableFunctionToProjectSetRule }
301            , { ApplyEliminateRule }
302            , { ApplyJoinTransposeRule }
303            , { ApplyShareEliminateRule }
304            , { ApplyToJoinRule }
305            , { MaxOneRowEliminateRule }
306            , { DistinctAggRule }
307            , { IndexDeltaJoinRule }
308            , { MergeMultiJoinRule }
309            , { ProjectEliminateRule }
310            , { ProjectJoinMergeRule }
311            , { ProjectMergeRule }
312            , { PullUpCorrelatedPredicateRule }
313            , { PullUpCorrelatedProjectValueRule }
314            , { LeftDeepTreeJoinOrderingRule }
315            , { TranslateApplyRule }
316            , { PushCalculationOfJoinRule }
317            , { IndexSelectionRule }
318            , { OverWindowToTopNRule }
319            , { OverWindowToAggAndJoinRule }
320            , { OverWindowSplitRule }
321            , { OverWindowMergeRule }
322            , { JoinCommuteRule }
323            , { UnionToDistinctRule }
324            , { AggProjectMergeRule }
325            , { UnionMergeRule }
326            , { DagToTreeRule }
327            , { SplitNowAndRule }
328            , { SplitNowOrRule }
329            , { FilterWithNowToJoinRule }
330            , { GenerateSeriesWithNowRule }
331            , { ProjectTopNTransposeRule }
332            , { TopNProjectTransposeRule }
333            , { TopNOnIndexRule }
334            , { TrivialProjectToValuesRule }
335            , { UnionInputValuesMergeRule }
336            , { RewriteLikeExprRule }
337            , { MinMaxOnIndexRule }
338            , { AlwaysFalseFilterRule }
339            , { BushyTreeJoinOrderingRule }
340            , { StreamProjectMergeRule }
341            , { SeparateConsecutiveJoinRule }
342            , { LogicalFilterExpressionSimplifyRule }
343            , { JoinProjectTransposeRule }
344            , { LimitPushDownRule }
345            , { PullUpHopRule }
346            , { IntersectToSemiJoinRule }
347            , { ExceptToAntiJoinRule }
348            , { IntersectMergeRule }
349            , { ExceptMergeRule }
350            , { ApplyUnionTransposeRule }
351            , { ApplyDedupTransposeRule }
352            , { ProjectJoinSeparateRule }
353            , { GroupingSetsToExpandRule }
354            , { CrossJoinEliminateRule }
355            , { ApplyTopNTransposeRule }
356            , { TableFunctionToProjectSetRule }
357            , { TableFunctionToFileScanRule }
358            , { TableFunctionToPostgresQueryRule }
359            , { TableFunctionToMySqlQueryRule }
360            , { TableFunctionToInternalBackfillProgressRule }
361            , { TableFunctionToInternalGetChannelDeltaStatsRule }
362            , { TableFunctionToInternalSourceBackfillProgressRule }
363            , { ApplyLimitTransposeRule }
364            , { CommonSubExprExtractRule }
365            , { BatchProjectMergeRule }
366            , { ApplyOverWindowTransposeRule }
367            , { ApplyExpandTransposeRule }
368            , { ExpandToProjectRule }
369            , { AggGroupBySimplifyRule }
370            , { ApplyHopWindowTransposeRule }
371            , { AggCallMergeRule }
372            , { UnifyFirstLastValueRule }
373            , { ValuesExtractProjectRule }
374            , { BatchPushLimitToScanRule }
375            , { PullUpCorrelatedPredicateAggRule }
376            , { SourceToKafkaScanRule }
377            , { SourceToIcebergIntermediateScanRule }
378            , { IcebergCountStarRule}
379            , { IcebergIntermediateScanRule }
380            , { AddLogstoreRule }
381            , { EmptyAggRemoveRule }
382            , { TopNToVectorSearchRule }
383            , { CorrelatedTopNToVectorSearchRule }
384        }
385    };
386}
387
388macro_rules! impl_description {
389    ($( { $name:ident }),*) => {
390        paste::paste!{
391            $(impl Description for [<$name>] {
392                fn description(&self) -> &str {
393                    stringify!([<$name>])
394                }
395            })*
396        }
397    }
398}
399
400for_all_rules! {impl_description}
401
402mod prelude {
403    pub(super) use crate::optimizer::plan_node::{Logical, LogicalPlanRef as PlanRef};
404    pub(super) use crate::optimizer::rule::Rule;
405
406    pub(super) type BoxedRule = crate::optimizer::rule::BoxedRule<Logical>;
407}