Skip to main content

datafusion_optimizer/
push_down_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//! [`PushDownLimit`] pushes `LIMIT` earlier in the query plan, and pushes a
6//! `Sort` with a fetch limit (TopK) onto a join's preserved-side child (see
7//! the `topk_through_join` submodule).
8
9use std::cmp::min;
10use std::sync::Arc;
11
12use crate::optimizer::ApplyOrder;
13use crate::{OptimizerConfig, OptimizerRule};
14
15use datafusion_common::Result;
16use datafusion_common::tree_node::Transformed;
17use datafusion_common::utils::combine_limit;
18use datafusion_expr::logical_plan::{Join, JoinType, Limit, LogicalPlan};
19use datafusion_expr::{FetchType, SkipType, lit};
20
21mod topk_through_join;
22use topk_through_join::push_topk_through_join;
23
24/// Optimization rule that tries to push down `LIMIT`.
25///
26/// It pushes `LIMIT` through projections, unions, joins and into scans
27/// (taking the smaller limit when one is already present), merges adjacent
28/// limits, and pushes a `Sort` carrying a fetch limit (a TopK) onto a join's
29/// preserved-side child so fewer rows enter the join. See
30/// `topk_through_join` for the latter.
31///
32/// The TopK-through-join rewrite has an implicit ordering dependency on
33/// `push_down_filter` and `eliminate_outer_join`: a `Filter` sitting between
34/// the `Sort` and the `Join` blocks this rule (a `Filter` can't sink below a
35/// fetch-bearing node without changing which rows survive), and an outer
36/// join only has a "preserved side" once `eliminate_outer_join` has already
37/// dropped joins it can prove are equivalent to an inner join. Both of those
38/// rules need a prior or concurrent pass to unblock this one; with
39/// `max_passes >= 2` this resolves on a later pass.
40#[derive(Default, Debug)]
41pub struct PushDownLimit {}
42
43impl PushDownLimit {
44    #[expect(missing_docs)]
45    pub fn new() -> Self {
46        Self {}
47    }
48}
49
50/// Push down Limit.
51impl OptimizerRule for PushDownLimit {
52    fn rewrite(
53        &self,
54        plan: LogicalPlan,
55        _config: &dyn OptimizerConfig,
56    ) -> Result<Transformed<LogicalPlan>> {
57        match plan {
58            LogicalPlan::Limit(limit) => rewrite_limit(limit),
59            LogicalPlan::Sort(s) if s.fetch.is_some() => push_topk_through_join(s),
60            other => Ok(Transformed::no(other)),
61        }
62    }
63
64    fn name(&self) -> &str {
65        "push_down_limit"
66    }
67
68    fn apply_order(&self) -> Option<ApplyOrder> {
69        Some(ApplyOrder::TopDown)
70    }
71}
72
73/// Limit-side dispatch (split out from `rewrite` so that the top-level
74/// match in `OptimizerRule::rewrite` reads as a parallel branch alongside
75/// the Sort-with-fetch handler).
76fn rewrite_limit(mut limit: Limit) -> Result<Transformed<LogicalPlan>> {
77    // Currently only rewrite if skip and fetch are both literals
78    let SkipType::Literal(skip) = limit.get_skip_type()? else {
79        return Ok(Transformed::no(LogicalPlan::Limit(limit)));
80    };
81    let FetchType::Literal(fetch) = limit.get_fetch_type()? else {
82        return Ok(Transformed::no(LogicalPlan::Limit(limit)));
83    };
84
85    // Merge the Parent Limit and the Child Limit.
86    if let LogicalPlan::Limit(child) = limit.input.as_ref() {
87        let SkipType::Literal(child_skip) = child.get_skip_type()? else {
88            return Ok(Transformed::no(LogicalPlan::Limit(limit)));
89        };
90        let FetchType::Literal(child_fetch) = child.get_fetch_type()? else {
91            return Ok(Transformed::no(LogicalPlan::Limit(limit)));
92        };
93
94        let (skip, fetch) = combine_limit(skip, fetch, child_skip, child_fetch);
95        let new_limit = Limit {
96            skip: Some(Box::new(lit(skip as i64))),
97            fetch: fetch.map(|f| Box::new(lit(f as i64))),
98            input: Arc::clone(&child.input),
99        };
100
101        // recursively reapply the rule on the new limit
102        return rewrite_limit(new_limit);
103    }
104
105    // no fetch to push, so return the original plan
106    let Some(fetch) = fetch else {
107        return Ok(Transformed::no(LogicalPlan::Limit(limit)));
108    };
109
110    match Arc::unwrap_or_clone(limit.input) {
111        LogicalPlan::TableScan(mut scan)
112            if skip > 0 && scan.source.supports_skip_pushdown() =>
113        {
114            // The source guarantees it will omit exactly the first `skip`
115            // rows itself, so the remaining `Limit` only needs to trim to
116            // `fetch` — its skip becomes 0.
117            scan.skip = Some(scan.skip.unwrap_or(0).saturating_add(skip));
118            let new_fetch = if fetch != 0 {
119                scan.fetch
120                    .map(|existing_fetch| min(existing_fetch.saturating_sub(skip), fetch))
121                    .or(Some(fetch))
122            } else {
123                Some(0)
124            };
125            scan.fetch = new_fetch;
126            transformed_limit(0, fetch, LogicalPlan::TableScan(scan))
127        }
128        LogicalPlan::TableScan(mut scan) => {
129            let rows_needed = if fetch != 0 { fetch + skip } else { 0 };
130            let new_fetch = scan
131                .fetch
132                .map(|x| min(x, rows_needed))
133                .or(Some(rows_needed));
134            if new_fetch == scan.fetch {
135                original_limit(skip, fetch, LogicalPlan::TableScan(scan))
136            } else {
137                // push limit into the table scan itself
138                scan.fetch = scan
139                    .fetch
140                    .map(|x| min(x, rows_needed))
141                    .or(Some(rows_needed));
142                transformed_limit(skip, fetch, LogicalPlan::TableScan(scan))
143            }
144        }
145        LogicalPlan::Union(mut union) => {
146            // push limits to each input of the union
147            union.inputs = union
148                .inputs
149                .into_iter()
150                .map(|input| make_arc_limit(0, fetch + skip, input))
151                .collect();
152            transformed_limit(skip, fetch, LogicalPlan::Union(union))
153        }
154
155        LogicalPlan::Join(join) => {
156            Ok(push_down_join(join, fetch + skip).update_data(|join| {
157                make_limit(skip, fetch, Arc::new(LogicalPlan::Join(join)))
158            }))
159        }
160
161        LogicalPlan::Sort(mut sort) => {
162            let new_fetch = {
163                let sort_fetch = skip + fetch;
164                Some(sort.fetch.map(|f| f.min(sort_fetch)).unwrap_or(sort_fetch))
165            };
166            let fetch_changed = new_fetch != sort.fetch;
167            sort.fetch = new_fetch;
168            if skip > 0 {
169                if fetch_changed {
170                    limit.input = Arc::new(LogicalPlan::Sort(sort));
171                    Ok(Transformed::yes(LogicalPlan::Limit(limit)))
172                } else {
173                    original_limit(skip, fetch, LogicalPlan::Sort(sort))
174                }
175            } else {
176                // With `skip = 0` the Sort's fetch already caps the output, so
177                // drop the Limit now instead of on the next pass. The Sort then
178                // replaces the Limit as the visited node and its own visit is
179                // skipped, so apply the TopK pushdown here. The plan changed
180                // (the Limit is gone) even if the TopK does not move.
181                let mut result = push_topk_through_join(sort)?;
182                result.transformed = true;
183                Ok(result)
184            }
185        }
186        LogicalPlan::Projection(mut proj) => {
187            // commute
188            limit.input = Arc::clone(&proj.input);
189            let new_limit = LogicalPlan::Limit(limit);
190            proj.input = Arc::new(new_limit);
191            Ok(Transformed::yes(LogicalPlan::Projection(proj)))
192        }
193        LogicalPlan::SubqueryAlias(mut subquery_alias) => {
194            // commute
195            limit.input = Arc::clone(&subquery_alias.input);
196            let new_limit = LogicalPlan::Limit(limit);
197            subquery_alias.input = Arc::new(new_limit);
198            Ok(Transformed::yes(LogicalPlan::SubqueryAlias(subquery_alias)))
199        }
200        LogicalPlan::Extension(extension_plan)
201            if extension_plan.node.supports_limit_pushdown() =>
202        {
203            let new_children = extension_plan
204                .node
205                .inputs()
206                .into_iter()
207                .map(|child| {
208                    LogicalPlan::Limit(Limit {
209                        skip: None,
210                        fetch: Some(Box::new(lit((fetch + skip) as i64))),
211                        input: Arc::new(child.clone()),
212                    })
213                })
214                .collect::<Vec<_>>();
215
216            // Create a new extension node with updated inputs
217            let child_plan = LogicalPlan::Extension(extension_plan);
218            let new_extension =
219                child_plan.with_new_exprs(child_plan.expressions(), new_children)?;
220
221            transformed_limit(skip, fetch, new_extension)
222        }
223        input => original_limit(skip, fetch, input),
224    }
225}
226
227/// Wrap the input plan with a limit node
228///
229/// Original:
230/// ```text
231/// input
232/// ```
233///
234/// Return
235/// ```text
236/// Limit: skip=skip, fetch=fetch
237///  input
238/// ```
239fn make_limit(skip: usize, fetch: usize, input: Arc<LogicalPlan>) -> LogicalPlan {
240    LogicalPlan::Limit(Limit {
241        skip: Some(Box::new(lit(skip as i64))),
242        fetch: Some(Box::new(lit(fetch as i64))),
243        input,
244    })
245}
246
247/// Wrap the input plan with a limit node
248fn make_arc_limit(
249    skip: usize,
250    fetch: usize,
251    input: Arc<LogicalPlan>,
252) -> Arc<LogicalPlan> {
253    Arc::new(make_limit(skip, fetch, input))
254}
255
256/// Returns the original limit (non transformed)
257fn original_limit(
258    skip: usize,
259    fetch: usize,
260    input: LogicalPlan,
261) -> Result<Transformed<LogicalPlan>> {
262    Ok(Transformed::no(make_limit(skip, fetch, Arc::new(input))))
263}
264
265/// Returns the a transformed limit
266fn transformed_limit(
267    skip: usize,
268    fetch: usize,
269    input: LogicalPlan,
270) -> Result<Transformed<LogicalPlan>> {
271    Ok(Transformed::yes(make_limit(skip, fetch, Arc::new(input))))
272}
273
274/// Adds a limit to the inputs of a join, if possible
275fn push_down_join(mut join: Join, limit: usize) -> Transformed<Join> {
276    use JoinType::*;
277
278    // Cross join is the special case of inner join where there is no join condition. see [LogicalPlanBuilder::cross_join]
279    fn is_cross_join(join: &Join) -> bool {
280        join.join_type == Inner && join.on.is_empty() && join.filter.is_none()
281    }
282
283    let (left_limit, right_limit) = if is_cross_join(&join) {
284        (Some(limit), Some(limit))
285    } else {
286        match join.join_type {
287            Left => (Some(limit), None),
288            Right => (None, Some(limit)),
289            _ => (None, None),
290        }
291    };
292
293    if left_limit.is_none() && right_limit.is_none() {
294        return Transformed::no(join);
295    }
296    if let Some(limit) = left_limit {
297        join.left = make_arc_limit(0, limit, join.left);
298    }
299    if let Some(limit) = right_limit {
300        join.right = make_arc_limit(0, limit, join.right);
301    }
302    Transformed::yes(join)
303}
304
305#[cfg(test)]
306mod test {
307    use std::cmp::Ordering;
308    use std::fmt::{Debug, Formatter};
309    use std::vec;
310
311    use super::*;
312    use crate::assert_optimized_plan_eq_snapshot;
313    use crate::test::*;
314
315    use crate::OptimizerContext;
316    use arrow::datatypes::{Schema, SchemaRef};
317    use datafusion_common::DFSchemaRef;
318    use datafusion_expr::{
319        Expr, Extension, TableScanBuilder, TableSource, UserDefinedLogicalNodeCore, col,
320        exists, logical_plan::builder::LogicalPlanBuilder,
321    };
322    use datafusion_functions_aggregate::expr_fn::max;
323
324    macro_rules! assert_optimized_plan_equal {
325        (
326            $plan:expr,
327            @ $expected:literal $(,)?
328        ) => {{
329            let optimizer_ctx = OptimizerContext::new().with_max_passes(1);
330            let rules: Vec<Arc<dyn crate::OptimizerRule + Send + Sync>> = vec![Arc::new(PushDownLimit::new())];
331            assert_optimized_plan_eq_snapshot!(
332                optimizer_ctx,
333                rules,
334                $plan,
335                @ $expected,
336            )
337        }};
338    }
339
340    #[derive(Debug, PartialEq, Eq, Hash)]
341    pub struct NoopPlan {
342        input: Vec<LogicalPlan>,
343        schema: DFSchemaRef,
344    }
345
346    // Manual implementation needed because of `schema` field. Comparison excludes this field.
347    impl PartialOrd for NoopPlan {
348        fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
349            self.input
350                .partial_cmp(&other.input)
351                // TODO (https://github.com/apache/datafusion/issues/17477) avoid recomparing all fields
352                .filter(|cmp| *cmp != Ordering::Equal || self == other)
353        }
354    }
355
356    impl UserDefinedLogicalNodeCore for NoopPlan {
357        fn name(&self) -> &str {
358            "NoopPlan"
359        }
360
361        fn inputs(&self) -> Vec<&LogicalPlan> {
362            self.input.iter().collect()
363        }
364
365        fn schema(&self) -> &DFSchemaRef {
366            &self.schema
367        }
368
369        fn expressions(&self) -> Vec<Expr> {
370            self.input
371                .iter()
372                .flat_map(|child| child.expressions())
373                .collect()
374        }
375
376        fn fmt_for_explain(&self, f: &mut Formatter) -> std::fmt::Result {
377            write!(f, "NoopPlan")
378        }
379
380        fn with_exprs_and_inputs(
381            &self,
382            _exprs: Vec<Expr>,
383            inputs: Vec<LogicalPlan>,
384        ) -> Result<Self> {
385            Ok(Self {
386                input: inputs,
387                schema: Arc::clone(&self.schema),
388            })
389        }
390
391        fn supports_limit_pushdown(&self) -> bool {
392            true // Allow limit push-down
393        }
394    }
395
396    #[derive(Debug, PartialEq, Eq, Hash)]
397    struct NoLimitNoopPlan {
398        input: Vec<LogicalPlan>,
399        schema: DFSchemaRef,
400    }
401
402    // Manual implementation needed because of `schema` field. Comparison excludes this field.
403    impl PartialOrd for NoLimitNoopPlan {
404        fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
405            self.input
406                .partial_cmp(&other.input)
407                // TODO (https://github.com/apache/datafusion/issues/17477) avoid recomparing all fields
408                .filter(|cmp| *cmp != Ordering::Equal || self == other)
409        }
410    }
411
412    impl UserDefinedLogicalNodeCore for NoLimitNoopPlan {
413        fn name(&self) -> &str {
414            "NoLimitNoopPlan"
415        }
416
417        fn inputs(&self) -> Vec<&LogicalPlan> {
418            self.input.iter().collect()
419        }
420
421        fn schema(&self) -> &DFSchemaRef {
422            &self.schema
423        }
424
425        fn expressions(&self) -> Vec<Expr> {
426            self.input
427                .iter()
428                .flat_map(|child| child.expressions())
429                .collect()
430        }
431
432        fn fmt_for_explain(&self, f: &mut Formatter) -> std::fmt::Result {
433            write!(f, "NoLimitNoopPlan")
434        }
435
436        fn with_exprs_and_inputs(
437            &self,
438            _exprs: Vec<Expr>,
439            inputs: Vec<LogicalPlan>,
440        ) -> Result<Self> {
441            Ok(Self {
442                input: inputs,
443                schema: Arc::clone(&self.schema),
444            })
445        }
446
447        fn supports_limit_pushdown(&self) -> bool {
448            false // Disallow limit push-down by default
449        }
450    }
451    #[test]
452    fn limit_pushdown_basic() -> Result<()> {
453        let table_scan = test_table_scan()?;
454        let noop_plan = LogicalPlan::Extension(Extension {
455            node: Arc::new(NoopPlan {
456                input: vec![table_scan.clone()],
457                schema: Arc::clone(table_scan.schema()),
458            }),
459        });
460
461        let plan = LogicalPlanBuilder::from(noop_plan)
462            .limit(0, Some(1000))?
463            .build()?;
464
465        assert_optimized_plan_equal!(
466            plan,
467            @r"
468        Limit: skip=0, fetch=1000
469          NoopPlan
470            Limit: skip=0, fetch=1000
471              TableScan: test, fetch=1000
472        "
473        )
474    }
475
476    #[test]
477    fn limit_pushdown_with_skip() -> Result<()> {
478        let table_scan = test_table_scan()?;
479        let noop_plan = LogicalPlan::Extension(Extension {
480            node: Arc::new(NoopPlan {
481                input: vec![table_scan.clone()],
482                schema: Arc::clone(table_scan.schema()),
483            }),
484        });
485
486        let plan = LogicalPlanBuilder::from(noop_plan)
487            .limit(10, Some(1000))?
488            .build()?;
489
490        assert_optimized_plan_equal!(
491            plan,
492            @r"
493        Limit: skip=10, fetch=1000
494          NoopPlan
495            Limit: skip=0, fetch=1010
496              TableScan: test, fetch=1010
497        "
498        )
499    }
500
501    /// A `TableSource` that declares it will honor `skip` exactly, so
502    /// `push_down_limit` is allowed to push `skip` into `TableScan::skip`
503    /// and elide the outer `Limit`'s skip.
504    #[derive(Debug)]
505    struct SkipPushdownTableSource {
506        schema: SchemaRef,
507    }
508
509    impl TableSource for SkipPushdownTableSource {
510        fn schema(&self) -> SchemaRef {
511            Arc::clone(&self.schema)
512        }
513
514        fn supports_skip_pushdown(&self) -> bool {
515            true
516        }
517    }
518
519    fn skip_pushdown_table_scan() -> Result<LogicalPlan> {
520        let schema = Arc::new(Schema::new(test_table_scan_fields()));
521        let source = Arc::new(SkipPushdownTableSource { schema });
522        Ok(LogicalPlan::TableScan(
523            TableScanBuilder::new("test", source).build()?,
524        ))
525    }
526
527    #[test]
528    fn limit_pushdown_skip_supported() -> Result<()> {
529        let table_scan = skip_pushdown_table_scan()?;
530
531        let plan = LogicalPlanBuilder::from(table_scan)
532            .limit(10, Some(1000))?
533            .build()?;
534
535        assert_optimized_plan_equal!(
536            plan,
537            @r"
538        Limit: skip=0, fetch=1000
539          TableScan: test, fetch=1000, skip=10
540        "
541        )
542    }
543
544    fn skip_pushdown_table_scan_with(
545        fetch: Option<usize>,
546        skip: Option<usize>,
547    ) -> Result<LogicalPlan> {
548        let LogicalPlan::TableScan(scan) = skip_pushdown_table_scan()? else {
549            unreachable!()
550        };
551        Ok(LogicalPlan::TableScan(
552            TableScanBuilder::from(scan)
553                .with_fetch(fetch)
554                .with_skip(skip)
555                .build()?,
556        ))
557    }
558
559    /// A scan that already skips/fetches: the new skip is added on top of
560    /// the existing one and the existing fetch shrinks by the new skip.
561    #[test]
562    fn limit_pushdown_skip_into_scan_with_skip_and_fetch() -> Result<()> {
563        let table_scan = skip_pushdown_table_scan_with(Some(15), Some(3))?;
564
565        let plan = LogicalPlanBuilder::from(table_scan)
566            .limit(10, Some(1000))?
567            .build()?;
568
569        assert_optimized_plan_equal!(
570            plan,
571            @r"
572        Limit: skip=0, fetch=1000
573          TableScan: test, fetch=5, skip=13
574        "
575        )
576    }
577
578    /// Skipping past the scan's existing fetch leaves nothing to read
579    #[test]
580    fn limit_pushdown_skip_beyond_scan_fetch() -> Result<()> {
581        let table_scan = skip_pushdown_table_scan_with(Some(5), None)?;
582
583        let plan = LogicalPlanBuilder::from(table_scan)
584            .limit(10, Some(3))?
585            .build()?;
586
587        assert_optimized_plan_equal!(
588            plan,
589            @r"
590        Limit: skip=0, fetch=3
591          TableScan: test, fetch=0, skip=10
592        "
593        )
594    }
595
596    #[test]
597    fn limit_pushdown_skip_with_fetch_zero() -> Result<()> {
598        let table_scan = skip_pushdown_table_scan()?;
599
600        let plan = LogicalPlanBuilder::from(table_scan)
601            .limit(10, Some(0))?
602            .build()?;
603
604        assert_optimized_plan_equal!(
605            plan,
606            @r"
607        Limit: skip=0, fetch=0
608          TableScan: test, fetch=0, skip=10
609        "
610        )
611    }
612
613    /// Adding to an existing skip must saturate instead of overflowing
614    #[test]
615    fn limit_pushdown_skip_saturates() -> Result<()> {
616        let table_scan = skip_pushdown_table_scan_with(None, Some(usize::MAX - 1))?;
617
618        let plan = LogicalPlanBuilder::from(table_scan)
619            .limit(10, Some(3))?
620            .build()?;
621
622        assert_optimized_plan_equal!(
623            plan,
624            @r"
625        Limit: skip=0, fetch=3
626          TableScan: test, fetch=3, skip=18446744073709551615
627        "
628        )
629    }
630
631    #[test]
632    fn limit_pushdown_multiple_limits() -> Result<()> {
633        let table_scan = test_table_scan()?;
634        let noop_plan = LogicalPlan::Extension(Extension {
635            node: Arc::new(NoopPlan {
636                input: vec![table_scan.clone()],
637                schema: Arc::clone(table_scan.schema()),
638            }),
639        });
640
641        let plan = LogicalPlanBuilder::from(noop_plan)
642            .limit(10, Some(1000))?
643            .limit(20, Some(500))?
644            .build()?;
645
646        assert_optimized_plan_equal!(
647            plan,
648            @r"
649        Limit: skip=30, fetch=500
650          NoopPlan
651            Limit: skip=0, fetch=530
652              TableScan: test, fetch=530
653        "
654        )
655    }
656
657    #[test]
658    fn limit_pushdown_multiple_inputs() -> Result<()> {
659        let table_scan = test_table_scan()?;
660        let noop_plan = LogicalPlan::Extension(Extension {
661            node: Arc::new(NoopPlan {
662                input: vec![table_scan.clone(), table_scan.clone()],
663                schema: Arc::clone(table_scan.schema()),
664            }),
665        });
666
667        let plan = LogicalPlanBuilder::from(noop_plan)
668            .limit(0, Some(1000))?
669            .build()?;
670
671        assert_optimized_plan_equal!(
672            plan,
673            @r"
674        Limit: skip=0, fetch=1000
675          NoopPlan
676            Limit: skip=0, fetch=1000
677              TableScan: test, fetch=1000
678            Limit: skip=0, fetch=1000
679              TableScan: test, fetch=1000
680        "
681        )
682    }
683
684    #[test]
685    fn limit_pushdown_disallowed_noop_plan() -> Result<()> {
686        let table_scan = test_table_scan()?;
687        let no_limit_noop_plan = LogicalPlan::Extension(Extension {
688            node: Arc::new(NoLimitNoopPlan {
689                input: vec![table_scan.clone()],
690                schema: Arc::clone(table_scan.schema()),
691            }),
692        });
693
694        let plan = LogicalPlanBuilder::from(no_limit_noop_plan)
695            .limit(0, Some(1000))?
696            .build()?;
697
698        assert_optimized_plan_equal!(
699            plan,
700            @r"
701        Limit: skip=0, fetch=1000
702          NoLimitNoopPlan
703            TableScan: test
704        "
705        )
706    }
707
708    #[test]
709    fn limit_pushdown_projection_table_provider() -> Result<()> {
710        let table_scan = test_table_scan()?;
711
712        let plan = LogicalPlanBuilder::from(table_scan)
713            .project(vec![col("a")])?
714            .limit(0, Some(1000))?
715            .build()?;
716
717        // Should push the limit down to table provider
718        // When it has a select
719        assert_optimized_plan_equal!(
720            plan,
721            @r"
722        Projection: test.a
723          Limit: skip=0, fetch=1000
724            TableScan: test, fetch=1000
725        "
726        )
727    }
728
729    #[test]
730    fn limit_push_down_take_smaller_limit() -> Result<()> {
731        let table_scan = test_table_scan()?;
732
733        let plan = LogicalPlanBuilder::from(table_scan)
734            .limit(0, Some(1000))?
735            .limit(0, Some(10))?
736            .build()?;
737
738        // Should push down the smallest limit
739        // Towards table scan
740        // This rule doesn't replace multiple limits
741        assert_optimized_plan_equal!(
742            plan,
743            @r"
744        Limit: skip=0, fetch=10
745          TableScan: test, fetch=10
746        "
747        )
748    }
749
750    #[test]
751    fn limit_doesnt_push_down_aggregation() -> Result<()> {
752        let table_scan = test_table_scan()?;
753
754        let plan = LogicalPlanBuilder::from(table_scan)
755            .aggregate(vec![col("a")], vec![max(col("b"))])?
756            .limit(0, Some(1000))?
757            .build()?;
758
759        // Limit should *not* push down aggregate node
760        assert_optimized_plan_equal!(
761            plan,
762            @r"
763        Limit: skip=0, fetch=1000
764          Aggregate: groupBy=[[test.a]], aggr=[[max(test.b)]]
765            TableScan: test
766        "
767        )
768    }
769
770    #[test]
771    fn limit_should_push_down_union() -> Result<()> {
772        let table_scan = test_table_scan()?;
773
774        let plan = LogicalPlanBuilder::from(table_scan.clone())
775            .union(LogicalPlanBuilder::from(table_scan).build()?)?
776            .limit(0, Some(1000))?
777            .build()?;
778
779        // Limit should push down through union
780        assert_optimized_plan_equal!(
781            plan,
782            @r"
783        Limit: skip=0, fetch=1000
784          Union
785            Limit: skip=0, fetch=1000
786              TableScan: test, fetch=1000
787            Limit: skip=0, fetch=1000
788              TableScan: test, fetch=1000
789        "
790        )
791    }
792
793    #[test]
794    fn limit_push_down_sort() -> Result<()> {
795        let table_scan = test_table_scan()?;
796
797        let plan = LogicalPlanBuilder::from(table_scan)
798            .sort_by(vec![col("a")])?
799            .limit(0, Some(10))?
800            .build()?;
801
802        // Should push down limit to sort, and drop the now redundant limit
803        assert_optimized_plan_equal!(
804            plan,
805            @r"
806        Sort: test.a ASC NULLS LAST, fetch=10
807          TableScan: test
808        "
809        )
810    }
811
812    /// `Limit(skip=0) -> Sort` settles in the first pass: the second pass
813    /// leaves the plan unchanged, so the optimizer stops after 2 passes.
814    #[test]
815    fn limit_push_down_sort_settles_in_first_pass() -> Result<()> {
816        let table_scan = test_table_scan()?;
817
818        let plan = LogicalPlanBuilder::from(table_scan)
819            .sort_by(vec![col("a")])?
820            .limit(0, Some(10))?
821            .build()?;
822
823        let optimizer_ctx = OptimizerContext::new().with_max_passes(3);
824        let optimizer =
825            crate::Optimizer::with_rules(vec![Arc::new(PushDownLimit::new())]);
826        let mut passes = 0;
827        optimizer.optimize(plan, &optimizer_ctx, |_, _| passes += 1)?;
828        assert_eq!(passes, 2);
829        Ok(())
830    }
831
832    /// Dropping the `Limit` above a `Sort` changes the plan even when the
833    /// TopK has no join to move through, so the rule must report it.
834    #[test]
835    fn limit_push_down_sort_reports_transformed() -> Result<()> {
836        for sort_fetch in [None, Some(10), Some(5)] {
837            let plan = LogicalPlanBuilder::from(test_table_scan()?)
838                .sort_with_limit(vec![col("a").sort(true, false)], sort_fetch)?
839                .limit(0, Some(10))?
840                .build()?;
841
842            let result = PushDownLimit::new().rewrite(plan, &OptimizerContext::new())?;
843            assert!(result.transformed, "sort fetch {sort_fetch:?}");
844            assert!(matches!(result.data, LogicalPlan::Sort(_)));
845        }
846        Ok(())
847    }
848
849    #[test]
850    fn limit_push_down_sort_skip() -> Result<()> {
851        let table_scan = test_table_scan()?;
852
853        let plan = LogicalPlanBuilder::from(table_scan)
854            .sort_by(vec![col("a")])?
855            .limit(5, Some(10))?
856            .build()?;
857
858        // Should push down limit to sort
859        assert_optimized_plan_equal!(
860            plan,
861            @r"
862        Limit: skip=5, fetch=10
863          Sort: test.a ASC NULLS LAST, fetch=15
864            TableScan: test
865        "
866        )
867    }
868
869    #[test]
870    fn multi_stage_limit_recursive_to_deeper_limit() -> Result<()> {
871        let table_scan = test_table_scan()?;
872
873        let plan = LogicalPlanBuilder::from(table_scan)
874            .limit(0, Some(1000))?
875            .aggregate(vec![col("a")], vec![max(col("b"))])?
876            .limit(0, Some(10))?
877            .build()?;
878
879        // Limit should use deeper LIMIT 1000, but Limit 10 shouldn't push down aggregation
880        assert_optimized_plan_equal!(
881            plan,
882            @r"
883        Limit: skip=0, fetch=10
884          Aggregate: groupBy=[[test.a]], aggr=[[max(test.b)]]
885            Limit: skip=0, fetch=1000
886              TableScan: test, fetch=1000
887        "
888        )
889    }
890
891    #[test]
892    fn limit_pushdown_should_not_pushdown_limit_with_offset_only() -> Result<()> {
893        let table_scan = test_table_scan()?;
894        let plan = LogicalPlanBuilder::from(table_scan)
895            .limit(10, None)?
896            .build()?;
897
898        // Should not push any limit down to table provider
899        // When it has a select
900        assert_optimized_plan_equal!(
901            plan,
902            @r"
903        Limit: skip=10, fetch=None
904          TableScan: test
905        "
906        )
907    }
908
909    #[test]
910    fn limit_pushdown_with_offset_projection_table_provider() -> Result<()> {
911        let table_scan = test_table_scan()?;
912
913        let plan = LogicalPlanBuilder::from(table_scan)
914            .project(vec![col("a")])?
915            .limit(10, Some(1000))?
916            .build()?;
917
918        // Should push the limit down to table provider
919        // When it has a select
920        assert_optimized_plan_equal!(
921            plan,
922            @r"
923        Projection: test.a
924          Limit: skip=10, fetch=1000
925            TableScan: test, fetch=1010
926        "
927        )
928    }
929
930    #[test]
931    fn limit_pushdown_with_offset_after_limit() -> Result<()> {
932        let table_scan = test_table_scan()?;
933
934        let plan = LogicalPlanBuilder::from(table_scan)
935            .project(vec![col("a")])?
936            .limit(0, Some(1000))?
937            .limit(10, None)?
938            .build()?;
939
940        assert_optimized_plan_equal!(
941            plan,
942            @r"
943        Projection: test.a
944          Limit: skip=10, fetch=990
945            TableScan: test, fetch=1000
946        "
947        )
948    }
949
950    #[test]
951    fn limit_pushdown_with_limit_after_offset() -> Result<()> {
952        let table_scan = test_table_scan()?;
953
954        let plan = LogicalPlanBuilder::from(table_scan)
955            .project(vec![col("a")])?
956            .limit(10, None)?
957            .limit(0, Some(1000))?
958            .build()?;
959
960        assert_optimized_plan_equal!(
961            plan,
962            @r"
963        Projection: test.a
964          Limit: skip=10, fetch=1000
965            TableScan: test, fetch=1010
966        "
967        )
968    }
969
970    #[test]
971    fn limit_push_down_with_offset_take_smaller_limit() -> Result<()> {
972        let table_scan = test_table_scan()?;
973
974        let plan = LogicalPlanBuilder::from(table_scan)
975            .limit(10, None)?
976            .limit(0, Some(1000))?
977            .limit(0, Some(10))?
978            .build()?;
979
980        assert_optimized_plan_equal!(
981            plan,
982            @r"
983        Limit: skip=10, fetch=10
984          TableScan: test, fetch=20
985        "
986        )
987    }
988
989    #[test]
990    fn limit_doesnt_push_down_with_offset_aggregation() -> Result<()> {
991        let table_scan = test_table_scan()?;
992
993        let plan = LogicalPlanBuilder::from(table_scan)
994            .aggregate(vec![col("a")], vec![max(col("b"))])?
995            .limit(10, Some(1000))?
996            .build()?;
997
998        // Limit should *not* push down aggregate node
999        assert_optimized_plan_equal!(
1000            plan,
1001            @r"
1002        Limit: skip=10, fetch=1000
1003          Aggregate: groupBy=[[test.a]], aggr=[[max(test.b)]]
1004            TableScan: test
1005        "
1006        )
1007    }
1008
1009    #[test]
1010    fn limit_should_push_down_with_offset_union() -> Result<()> {
1011        let table_scan = test_table_scan()?;
1012
1013        let plan = LogicalPlanBuilder::from(table_scan.clone())
1014            .union(LogicalPlanBuilder::from(table_scan).build()?)?
1015            .limit(10, Some(1000))?
1016            .build()?;
1017
1018        // Limit should push down through union
1019        assert_optimized_plan_equal!(
1020            plan,
1021            @r"
1022        Limit: skip=10, fetch=1000
1023          Union
1024            Limit: skip=0, fetch=1010
1025              TableScan: test, fetch=1010
1026            Limit: skip=0, fetch=1010
1027              TableScan: test, fetch=1010
1028        "
1029        )
1030    }
1031
1032    #[test]
1033    fn limit_offset_should_not_push_down_with_offset_join() -> Result<()> {
1034        let table_scan_1 = test_table_scan()?;
1035        let table_scan_2 = test_table_scan_with_name("test2")?;
1036
1037        let plan = LogicalPlanBuilder::from(table_scan_1)
1038            .join(
1039                LogicalPlanBuilder::from(table_scan_2).build()?,
1040                JoinType::Inner,
1041                (vec!["a"], vec!["a"]),
1042                None,
1043            )?
1044            .limit(10, Some(1000))?
1045            .build()?;
1046
1047        // Limit pushdown Not supported in Join
1048        assert_optimized_plan_equal!(
1049            plan,
1050            @r"
1051        Limit: skip=10, fetch=1000
1052          Inner Join: test.a = test2.a
1053            TableScan: test
1054            TableScan: test2
1055        "
1056        )
1057    }
1058
1059    #[test]
1060    fn offset_limit_should_not_push_down_with_offset_join() -> Result<()> {
1061        let table_scan_1 = test_table_scan()?;
1062        let table_scan_2 = test_table_scan_with_name("test2")?;
1063
1064        let plan = LogicalPlanBuilder::from(table_scan_1)
1065            .join(
1066                LogicalPlanBuilder::from(table_scan_2).build()?,
1067                JoinType::Inner,
1068                (vec!["a"], vec!["a"]),
1069                None,
1070            )?
1071            .limit(10, Some(1000))?
1072            .build()?;
1073
1074        // Limit pushdown Not supported in Join
1075        assert_optimized_plan_equal!(
1076            plan,
1077            @r"
1078        Limit: skip=10, fetch=1000
1079          Inner Join: test.a = test2.a
1080            TableScan: test
1081            TableScan: test2
1082        "
1083        )
1084    }
1085
1086    #[test]
1087    fn limit_offset_should_not_push_down_with_offset_sub_query() -> Result<()> {
1088        let table_scan_1 = test_table_scan_with_name("test1")?;
1089        let table_scan_2 = test_table_scan_with_name("test2")?;
1090
1091        let subquery = LogicalPlanBuilder::from(table_scan_1)
1092            .project(vec![col("a")])?
1093            .filter(col("a").eq(col("test1.a")))?
1094            .build()?;
1095
1096        let outer_query = LogicalPlanBuilder::from(table_scan_2)
1097            .project(vec![col("a")])?
1098            .filter(exists(Arc::new(subquery)))?
1099            .limit(10, Some(100))?
1100            .build()?;
1101
1102        // Limit pushdown Not supported in sub_query
1103        assert_optimized_plan_equal!(
1104            outer_query,
1105            @r"
1106        Limit: skip=10, fetch=100
1107          Filter: EXISTS (<subquery>)
1108            Subquery:
1109              Filter: test1.a = test1.a
1110                Projection: test1.a
1111                  TableScan: test1
1112            Projection: test2.a
1113              TableScan: test2
1114        "
1115        )
1116    }
1117
1118    #[test]
1119    fn offset_limit_should_not_push_down_with_offset_sub_query() -> Result<()> {
1120        let table_scan_1 = test_table_scan_with_name("test1")?;
1121        let table_scan_2 = test_table_scan_with_name("test2")?;
1122
1123        let subquery = LogicalPlanBuilder::from(table_scan_1)
1124            .project(vec![col("a")])?
1125            .filter(col("a").eq(col("test1.a")))?
1126            .build()?;
1127
1128        let outer_query = LogicalPlanBuilder::from(table_scan_2)
1129            .project(vec![col("a")])?
1130            .filter(exists(Arc::new(subquery)))?
1131            .limit(10, Some(100))?
1132            .build()?;
1133
1134        // Limit pushdown Not supported in sub_query
1135        assert_optimized_plan_equal!(
1136            outer_query,
1137            @r"
1138        Limit: skip=10, fetch=100
1139          Filter: EXISTS (<subquery>)
1140            Subquery:
1141              Filter: test1.a = test1.a
1142                Projection: test1.a
1143                  TableScan: test1
1144            Projection: test2.a
1145              TableScan: test2
1146        "
1147        )
1148    }
1149
1150    #[test]
1151    fn limit_should_push_down_left_outer_join_with_offset() -> Result<()> {
1152        let table_scan_1 = test_table_scan()?;
1153        let table_scan_2 = test_table_scan_with_name("test2")?;
1154
1155        let plan = LogicalPlanBuilder::from(table_scan_1)
1156            .join(
1157                LogicalPlanBuilder::from(table_scan_2).build()?,
1158                JoinType::Left,
1159                (vec!["a"], vec!["a"]),
1160                None,
1161            )?
1162            .limit(10, Some(1000))?
1163            .build()?;
1164
1165        // Limit pushdown Not supported in Join
1166        assert_optimized_plan_equal!(
1167            plan,
1168            @r"
1169        Limit: skip=10, fetch=1000
1170          Left Join: test.a = test2.a
1171            Limit: skip=0, fetch=1010
1172              TableScan: test, fetch=1010
1173            TableScan: test2
1174        "
1175        )
1176    }
1177
1178    #[test]
1179    fn limit_should_push_down_right_outer_join() -> Result<()> {
1180        let table_scan_1 = test_table_scan()?;
1181        let table_scan_2 = test_table_scan_with_name("test2")?;
1182
1183        let plan = LogicalPlanBuilder::from(table_scan_1)
1184            .join(
1185                LogicalPlanBuilder::from(table_scan_2).build()?,
1186                JoinType::Right,
1187                (vec!["a"], vec!["a"]),
1188                None,
1189            )?
1190            .limit(0, Some(1000))?
1191            .build()?;
1192
1193        // Limit pushdown Not supported in Join
1194        assert_optimized_plan_equal!(
1195            plan,
1196            @r"
1197        Limit: skip=0, fetch=1000
1198          Right Join: test.a = test2.a
1199            TableScan: test
1200            Limit: skip=0, fetch=1000
1201              TableScan: test2, fetch=1000
1202        "
1203        )
1204    }
1205
1206    #[test]
1207    fn limit_should_push_down_right_outer_join_with_offset() -> Result<()> {
1208        let table_scan_1 = test_table_scan()?;
1209        let table_scan_2 = test_table_scan_with_name("test2")?;
1210
1211        let plan = LogicalPlanBuilder::from(table_scan_1)
1212            .join(
1213                LogicalPlanBuilder::from(table_scan_2).build()?,
1214                JoinType::Right,
1215                (vec!["a"], vec!["a"]),
1216                None,
1217            )?
1218            .limit(10, Some(1000))?
1219            .build()?;
1220
1221        // Limit pushdown with offset supported in right outer join
1222        assert_optimized_plan_equal!(
1223            plan,
1224            @r"
1225        Limit: skip=10, fetch=1000
1226          Right Join: test.a = test2.a
1227            TableScan: test
1228            Limit: skip=0, fetch=1010
1229              TableScan: test2, fetch=1010
1230        "
1231        )
1232    }
1233
1234    #[test]
1235    fn limit_push_down_cross_join() -> Result<()> {
1236        let table_scan_1 = test_table_scan()?;
1237        let table_scan_2 = test_table_scan_with_name("test2")?;
1238
1239        let plan = LogicalPlanBuilder::from(table_scan_1)
1240            .cross_join(LogicalPlanBuilder::from(table_scan_2).build()?)?
1241            .limit(0, Some(1000))?
1242            .build()?;
1243
1244        assert_optimized_plan_equal!(
1245            plan,
1246            @r"
1247        Limit: skip=0, fetch=1000
1248          Cross Join:
1249            Limit: skip=0, fetch=1000
1250              TableScan: test, fetch=1000
1251            Limit: skip=0, fetch=1000
1252              TableScan: test2, fetch=1000
1253        "
1254        )
1255    }
1256
1257    #[test]
1258    fn skip_limit_push_down_cross_join() -> Result<()> {
1259        let table_scan_1 = test_table_scan()?;
1260        let table_scan_2 = test_table_scan_with_name("test2")?;
1261
1262        let plan = LogicalPlanBuilder::from(table_scan_1)
1263            .cross_join(LogicalPlanBuilder::from(table_scan_2).build()?)?
1264            .limit(1000, Some(1000))?
1265            .build()?;
1266
1267        assert_optimized_plan_equal!(
1268            plan,
1269            @r"
1270        Limit: skip=1000, fetch=1000
1271          Cross Join:
1272            Limit: skip=0, fetch=2000
1273              TableScan: test, fetch=2000
1274            Limit: skip=0, fetch=2000
1275              TableScan: test2, fetch=2000
1276        "
1277        )
1278    }
1279
1280    #[test]
1281    fn merge_limit_result_empty() -> Result<()> {
1282        let scan = test_table_scan()?;
1283
1284        let plan = LogicalPlanBuilder::from(scan)
1285            .limit(0, Some(1000))?
1286            .limit(1000, None)?
1287            .build()?;
1288
1289        assert_optimized_plan_equal!(
1290            plan,
1291            @r"
1292        Limit: skip=1000, fetch=0
1293          TableScan: test, fetch=0
1294        "
1295        )
1296    }
1297
1298    #[test]
1299    fn skip_great_than_fetch() -> Result<()> {
1300        let scan = test_table_scan()?;
1301
1302        let plan = LogicalPlanBuilder::from(scan)
1303            .limit(0, Some(1))?
1304            .limit(1000, None)?
1305            .build()?;
1306
1307        assert_optimized_plan_equal!(
1308            plan,
1309            @r"
1310        Limit: skip=1000, fetch=0
1311          TableScan: test, fetch=0
1312        "
1313        )
1314    }
1315
1316    #[test]
1317    fn push_down_subquery_alias() -> Result<()> {
1318        let scan = test_table_scan()?;
1319
1320        let plan = LogicalPlanBuilder::from(scan)
1321            .alias("a")?
1322            .limit(0, Some(1))?
1323            .limit(1000, None)?
1324            .build()?;
1325
1326        assert_optimized_plan_equal!(
1327            plan,
1328            @r"
1329        SubqueryAlias: a
1330          Limit: skip=1000, fetch=0
1331            TableScan: test, fetch=0
1332        "
1333        )
1334    }
1335}