risingwave_frontend/optimizer/rule/
mv_selection_rule.rs

1// Copyright 2026 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 crate::optimizer::PlanRef;
16use crate::optimizer::plan_node::{Logical, LogicalPlanRef, LogicalScan};
17use crate::optimizer::rule::{BoxedRule, Rule};
18
19pub struct MvSelectionRule;
20
21impl MvSelectionRule {
22    pub fn create() -> BoxedRule<Logical> {
23        Box::new(Self)
24    }
25}
26
27impl Rule<Logical> for MvSelectionRule {
28    fn apply(&self, plan: PlanRef<Logical>) -> Option<PlanRef<Logical>> {
29        let ctx = plan.ctx();
30        for candidate in ctx.batch_mview_candidates().iter() {
31            if plan == candidate.plan {
32                let output_len = plan.schema().len();
33                if output_len > candidate.table.columns().len() {
34                    continue;
35                }
36                let output_col_idx = (0..output_len).collect();
37                let scan = LogicalScan::create(candidate.table.clone(), ctx.clone(), None)
38                    .clone_with_output_indices(output_col_idx);
39                let rewritten: LogicalPlanRef = scan.into();
40                return Some(rewritten);
41            }
42        }
43        None
44    }
45}