Skip to main content

datafusion_optimizer/
eliminate_limit.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! [`EliminateLimit`] eliminates `LIMIT` when possible
6use crate::optimizer::ApplyOrder;
7use crate::{OptimizerConfig, OptimizerRule};
8use datafusion_common::Result;
9use datafusion_common::tree_node::Transformed;
10use datafusion_expr::logical_plan::{EmptyRelation, FetchType, LogicalPlan, SkipType};
11use std::sync::Arc;
12
13/// Optimizer rule to replace `LIMIT 0` or `LIMIT` whose ancestor LIMIT's skip is
14/// greater than or equal to current's fetch
15///
16/// It can cooperate with `propagate_empty_relation` and `limit_push_down`. on a
17/// plan with an empty relation.
18///
19/// This rule also removes OFFSET 0 from the [LogicalPlan]
20#[derive(Default, Debug)]
21pub struct EliminateLimit;
22
23impl EliminateLimit {
24    /// Create a new `EliminateLimit`
25    pub fn new() -> Self {
26        Self {}
27    }
28}
29
30impl OptimizerRule for EliminateLimit {
31    fn name(&self) -> &str {
32        "eliminate_limit"
33    }
34
35    fn apply_order(&self) -> Option<ApplyOrder> {
36        Some(ApplyOrder::BottomUp)
37    }
38
39    fn rewrite(
40        &self,
41        plan: LogicalPlan,
42        _config: &dyn OptimizerConfig,
43    ) -> Result<Transformed<LogicalPlan>, datafusion_common::DataFusionError> {
44        match plan {
45            LogicalPlan::Limit(limit) => {
46                // Only supports rewriting for literal fetch
47                let FetchType::Literal(fetch) = limit.get_fetch_type()? else {
48                    return Ok(Transformed::no(LogicalPlan::Limit(limit)));
49                };
50
51                if let Some(v) = fetch {
52                    if v == 0 {
53                        return Ok(Transformed::yes(LogicalPlan::EmptyRelation(
54                            EmptyRelation {
55                                produce_one_row: false,
56                                schema: Arc::clone(limit.input.schema()),
57                            },
58                        )));
59                    }
60                } else if matches!(limit.get_skip_type()?, SkipType::Literal(0)) {
61                    // If fetch is `None` and skip is 0, then Limit takes no effect and
62                    // we can remove it.
63                    return Ok(Transformed::yes(Arc::unwrap_or_clone(limit.input)));
64                }
65                Ok(Transformed::no(LogicalPlan::Limit(limit)))
66            }
67            _ => Ok(Transformed::no(plan)),
68        }
69    }
70}
71
72#[cfg(test)]
73mod tests {
74    use super::*;
75    use crate::OptimizerContext;
76    use crate::test::*;
77    use datafusion_common::Column;
78    use datafusion_expr::{
79        col,
80        logical_plan::{JoinType, builder::LogicalPlanBuilder},
81    };
82
83    use crate::assert_optimized_plan_eq_snapshot;
84    use crate::push_down_limit::PushDownLimit;
85    use datafusion_expr::test::function_stub::sum;
86
87    macro_rules! assert_optimized_plan_equal {
88        (
89            $plan:expr,
90            @ $expected:literal $(,)?
91        ) => {{
92            let rules: Vec<Arc<dyn crate::OptimizerRule + Send + Sync>> = vec![Arc::new(EliminateLimit::new())];
93            let optimizer_ctx = OptimizerContext::new();
94            assert_optimized_plan_eq_snapshot!(
95                optimizer_ctx,
96                rules,
97                $plan,
98                @ $expected,
99            )
100        }};
101    }
102
103    macro_rules! assert_optimized_plan_eq_with_pushdown {
104        (
105            $plan:expr,
106            @ $expected:literal $(,)?
107        ) => {{
108            let optimizer_ctx = OptimizerContext::new().with_max_passes(1);
109            let rules: Vec<Arc<dyn crate::OptimizerRule + Send + Sync>> = vec![
110                Arc::new(PushDownLimit::new()),
111                Arc::new(EliminateLimit::new())
112                ];
113            assert_optimized_plan_eq_snapshot!(
114                optimizer_ctx,
115                rules,
116                $plan,
117                @ $expected,
118            )
119        }};
120    }
121
122    #[test]
123    fn limit_0_root() -> Result<()> {
124        let table_scan = test_table_scan().unwrap();
125        let plan = LogicalPlanBuilder::from(table_scan)
126            .aggregate(vec![col("a")], vec![sum(col("b"))])?
127            .limit(0, Some(0))?
128            .build()?;
129        // No aggregate / scan / limit
130        assert_optimized_plan_equal!(
131            plan,
132            @ "EmptyRelation: rows=0"
133        )
134    }
135
136    #[test]
137    fn limit_0_nested() -> Result<()> {
138        let table_scan = test_table_scan()?;
139        let plan1 = LogicalPlanBuilder::from(table_scan.clone())
140            .aggregate(vec![col("a")], vec![sum(col("b"))])?
141            .build()?;
142        let plan = LogicalPlanBuilder::from(table_scan)
143            .aggregate(vec![col("a")], vec![sum(col("b"))])?
144            .limit(0, Some(0))?
145            .union(plan1)?
146            .build()?;
147
148        // Left side is removed
149        assert_optimized_plan_equal!(
150            plan,
151            @ r"
152        Union
153          EmptyRelation: rows=0
154          Aggregate: groupBy=[[test.a]], aggr=[[sum(test.b)]]
155            TableScan: test
156        "
157        )
158    }
159
160    #[test]
161    fn limit_fetch_with_ancestor_limit_skip() -> Result<()> {
162        let table_scan = test_table_scan()?;
163        let plan = LogicalPlanBuilder::from(table_scan)
164            .aggregate(vec![col("a")], vec![sum(col("b"))])?
165            .limit(0, Some(2))?
166            .limit(2, None)?
167            .build()?;
168
169        // No aggregate / scan / limit
170        assert_optimized_plan_eq_with_pushdown!(
171            plan,
172            @ "EmptyRelation: rows=0"
173        )
174    }
175
176    #[test]
177    fn multi_limit_offset_sort_eliminate() -> Result<()> {
178        let table_scan = test_table_scan()?;
179        let plan = LogicalPlanBuilder::from(table_scan)
180            .aggregate(vec![col("a")], vec![sum(col("b"))])?
181            .limit(0, Some(2))?
182            .sort_by(vec![col("a")])?
183            .limit(2, Some(1))?
184            .build()?;
185
186        // After remove global-state, we don't record the parent <skip, fetch>
187        // So, bottom don't know parent info, so can't eliminate.
188        assert_optimized_plan_eq_with_pushdown!(
189            plan,
190            @ r"
191        Limit: skip=2, fetch=1
192          Sort: test.a ASC NULLS LAST, fetch=3
193            Limit: skip=0, fetch=2
194              Aggregate: groupBy=[[test.a]], aggr=[[sum(test.b)]]
195                TableScan: test
196        "
197        )
198    }
199
200    #[test]
201    fn limit_fetch_with_ancestor_limit_fetch() -> Result<()> {
202        let table_scan = test_table_scan()?;
203        let plan = LogicalPlanBuilder::from(table_scan)
204            .aggregate(vec![col("a")], vec![sum(col("b"))])?
205            .limit(0, Some(2))?
206            .sort_by(vec![col("a")])?
207            .limit(0, Some(1))?
208            .build()?;
209
210        assert_optimized_plan_equal!(
211            plan,
212            @ r"
213        Limit: skip=0, fetch=1
214          Sort: test.a ASC NULLS LAST
215            Limit: skip=0, fetch=2
216              Aggregate: groupBy=[[test.a]], aggr=[[sum(test.b)]]
217                TableScan: test
218        "
219        )
220    }
221
222    #[test]
223    fn limit_with_ancestor_limit() -> Result<()> {
224        let table_scan = test_table_scan().unwrap();
225        let plan = LogicalPlanBuilder::from(table_scan)
226            .aggregate(vec![col("a")], vec![sum(col("b"))])?
227            .limit(2, Some(1))?
228            .sort_by(vec![col("a")])?
229            .limit(3, Some(1))?
230            .build()?;
231
232        assert_optimized_plan_equal!(
233            plan,
234            @ r"
235        Limit: skip=3, fetch=1
236          Sort: test.a ASC NULLS LAST
237            Limit: skip=2, fetch=1
238              Aggregate: groupBy=[[test.a]], aggr=[[sum(test.b)]]
239                TableScan: test
240        "
241        )
242    }
243
244    #[test]
245    fn limit_join_with_ancestor_limit() -> Result<()> {
246        let table_scan = test_table_scan()?;
247        let table_scan_inner = test_table_scan_with_name("test1")?;
248        let plan = LogicalPlanBuilder::from(table_scan)
249            .limit(2, Some(1))?
250            .join_using(
251                table_scan_inner,
252                JoinType::Inner,
253                vec![Column::from_name("a".to_string())],
254            )?
255            .limit(3, Some(1))?
256            .build()?;
257
258        assert_optimized_plan_equal!(
259            plan,
260            @ r"
261        Limit: skip=3, fetch=1
262          Inner Join: Using test.a = test1.a
263            Limit: skip=2, fetch=1
264              TableScan: test
265            TableScan: test1
266        "
267        )
268    }
269
270    #[test]
271    fn remove_zero_offset() -> Result<()> {
272        let table_scan = test_table_scan()?;
273        let plan = LogicalPlanBuilder::from(table_scan)
274            .aggregate(vec![col("a")], vec![sum(col("b"))])?
275            .limit(0, None)?
276            .build()?;
277
278        assert_optimized_plan_equal!(
279            plan,
280            @ r"
281        Aggregate: groupBy=[[test.a]], aggr=[[sum(test.b)]]
282          TableScan: test
283        "
284        )
285    }
286
287    #[test]
288    fn remove_noop_limit_under_extension() -> Result<()> {
289        let table_scan = test_table_scan()?;
290        let plan = LogicalPlanBuilder::from(table_scan)
291            .limit(0, None)?
292            .build()?;
293        let plan = user_defined::new(plan);
294
295        assert_optimized_plan_equal!(
296            plan,
297            @ r"
298        TestUserDefined
299          TableScan: test
300        "
301        )
302    }
303}