risingwave_frontend/optimizer/rule/batch/batch_push_limit_to_scan_rule.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// Copyright (c) 2011-present, Facebook, Inc. All rights reserved.
16// This source code is licensed under both the GPLv2 (found in the
17// COPYING file in the root directory) and Apache 2.0 License
18// (found in the LICENSE.Apache file in the root directory).
19
20use itertools::Itertools;
21
22use super::prelude::*;
23use crate::optimizer::plan_node::generic::PhysicalPlanRef;
24use crate::optimizer::plan_node::{BatchLimit, BatchSeqScan, PlanTreeNodeUnary};
25
26pub struct BatchPushLimitToScanRule {}
27
28impl Rule<Batch> for BatchPushLimitToScanRule {
29 fn apply(&self, plan: PlanRef) -> Option<PlanRef> {
30 let limit: &BatchLimit = plan.as_batch_limit()?;
31 let limit_input = limit.input();
32 let scan: &BatchSeqScan = limit_input.as_batch_seq_scan()?;
33 if scan.limit().is_some() {
34 return None;
35 }
36 let pushed_limit = limit.limit() + limit.offset();
37 let new_scan = BatchSeqScan::new_with_dist(
38 scan.core().clone(),
39 scan.base.distribution().clone(),
40 scan.scan_ranges().iter().cloned().collect_vec(),
41 Some(pushed_limit),
42 );
43 Some(limit.clone_with_input(new_scan.into()).into())
44 }
45}
46
47impl BatchPushLimitToScanRule {
48 pub fn create() -> BoxedRule {
49 Box::new(BatchPushLimitToScanRule {})
50 }
51}