|
| 1 | +// Licensed to the Apache Software Foundation (ASF) under one |
| 2 | +// or more contributor license agreements. See the NOTICE file |
| 3 | +// distributed with this work for additional information |
| 4 | +// regarding copyright ownership. The ASF licenses this file |
| 5 | +// to you under the Apache License, Version 2.0 (the |
| 6 | +// "License"); you may not use this file except in compliance |
| 7 | +// with the License. You may obtain a copy of the License at |
| 8 | +// |
| 9 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +// |
| 11 | +// Unless required by applicable law or agreed to in writing, |
| 12 | +// software distributed under the License is distributed on an |
| 13 | +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 14 | +// KIND, either express or implied. See the License for the |
| 15 | +// specific language governing permissions and limitations |
| 16 | +// under the License. |
| 17 | + |
| 18 | +use crate::PhysicalOptimizerRule; |
| 19 | +use datafusion_common::config::ConfigOptions; |
| 20 | +use datafusion_common::tree_node::{Transformed, TreeNode}; |
| 21 | +use datafusion_common::ScalarValue; |
| 22 | +use datafusion_expr::{WindowFrameBound, WindowFrameUnits}; |
| 23 | +use datafusion_physical_plan::execution_plan::CardinalityEffect; |
| 24 | +use datafusion_physical_plan::limit::GlobalLimitExec; |
| 25 | +use datafusion_physical_plan::sorts::sort::SortExec; |
| 26 | +use datafusion_physical_plan::windows::BoundedWindowAggExec; |
| 27 | +use datafusion_physical_plan::ExecutionPlan; |
| 28 | +use std::cmp; |
| 29 | +use std::sync::Arc; |
| 30 | + |
| 31 | +/// This rule inspects [`ExecutionPlan`]'s attempting to find fetch limits that were not pushed |
| 32 | +/// down by `LimitPushdown` because [BoundedWindowAggExec]s were "in the way". If the window is |
| 33 | +/// bounded by [WindowFrameUnits::Rows] then we calculate the adjustment needed to grow the limit |
| 34 | +/// and continue pushdown. |
| 35 | +#[derive(Default, Clone, Debug)] |
| 36 | +pub struct LimitPushPastWindows; |
| 37 | + |
| 38 | +impl LimitPushPastWindows { |
| 39 | + pub fn new() -> Self { |
| 40 | + Self |
| 41 | + } |
| 42 | +} |
| 43 | + |
| 44 | +impl PhysicalOptimizerRule for LimitPushPastWindows { |
| 45 | + fn optimize( |
| 46 | + &self, |
| 47 | + original: Arc<dyn ExecutionPlan>, |
| 48 | + config: &ConfigOptions, |
| 49 | + ) -> datafusion_common::Result<Arc<dyn ExecutionPlan>> { |
| 50 | + if !config.optimizer.enable_window_limits { |
| 51 | + return Ok(original); |
| 52 | + } |
| 53 | + let mut latest_limit: Option<usize> = None; |
| 54 | + let mut latest_max = 0; |
| 55 | + let result = original.transform_down(|node| { |
| 56 | + // helper closure to DRY out most the early return cases |
| 57 | + let mut reset = |node, |
| 58 | + max: &mut usize| |
| 59 | + -> datafusion_common::Result< |
| 60 | + Transformed<Arc<dyn ExecutionPlan>>, |
| 61 | + > { |
| 62 | + latest_limit = None; |
| 63 | + *max = 0; |
| 64 | + Ok(Transformed::no(node)) |
| 65 | + }; |
| 66 | + |
| 67 | + // traversing sides of joins will require more thought |
| 68 | + if node.children().len() > 1 { |
| 69 | + return reset(node, &mut latest_max); |
| 70 | + } |
| 71 | + |
| 72 | + // grab the latest limit we see |
| 73 | + if let Some(limit) = node.as_any().downcast_ref::<GlobalLimitExec>() { |
| 74 | + latest_limit = limit.fetch().map(|fetch| fetch + limit.skip()); |
| 75 | + latest_max = 0; |
| 76 | + return Ok(Transformed::no(node)); |
| 77 | + } |
| 78 | + |
| 79 | + // grow the limit if we hit a window function |
| 80 | + if let Some(window) = node.as_any().downcast_ref::<BoundedWindowAggExec>() { |
| 81 | + for expr in window.window_expr().iter() { |
| 82 | + let frame = expr.get_window_frame(); |
| 83 | + if frame.units != WindowFrameUnits::Rows { |
| 84 | + return reset(node, &mut latest_max); // expression-based limits? |
| 85 | + } |
| 86 | + let Some(end_bound) = bound_to_usize(&frame.end_bound) else { |
| 87 | + return reset(node, &mut latest_max); |
| 88 | + }; |
| 89 | + latest_max = cmp::max(end_bound, latest_max); |
| 90 | + } |
| 91 | + return Ok(Transformed::no(node)); |
| 92 | + } |
| 93 | + |
| 94 | + // Apply the limit if we hit a sort node |
| 95 | + if let Some(sort) = node.as_any().downcast_ref::<SortExec>() { |
| 96 | + let latest = latest_limit.take(); |
| 97 | + let Some(fetch) = latest else { |
| 98 | + latest_max = 0; |
| 99 | + return Ok(Transformed::no(node)); |
| 100 | + }; |
| 101 | + let fetch = match sort.fetch() { |
| 102 | + None => fetch + latest_max, |
| 103 | + Some(existing) => cmp::min(existing, fetch + latest_max), |
| 104 | + }; |
| 105 | + let sort: Arc<dyn ExecutionPlan> = Arc::new(sort.with_fetch(Some(fetch))); |
| 106 | + latest_max = 0; |
| 107 | + return Ok(Transformed::complete(sort)); |
| 108 | + } |
| 109 | + |
| 110 | + // we can't push the limit past nodes that decrease row count |
| 111 | + match node.cardinality_effect() { |
| 112 | + CardinalityEffect::Equal => {} |
| 113 | + _ => return reset(node, &mut latest_max), |
| 114 | + } |
| 115 | + |
| 116 | + Ok(Transformed::no(node)) |
| 117 | + })?; |
| 118 | + Ok(result.data) |
| 119 | + } |
| 120 | + |
| 121 | + fn name(&self) -> &str { |
| 122 | + "LimitPushPastWindows" |
| 123 | + } |
| 124 | + |
| 125 | + fn schema_check(&self) -> bool { |
| 126 | + false // we don't change the schema |
| 127 | + } |
| 128 | +} |
| 129 | + |
| 130 | +fn bound_to_usize(bound: &WindowFrameBound) -> Option<usize> { |
| 131 | + match bound { |
| 132 | + WindowFrameBound::Preceding(_) => Some(0), |
| 133 | + WindowFrameBound::CurrentRow => Some(0), |
| 134 | + WindowFrameBound::Following(ScalarValue::UInt64(Some(scalar))) => { |
| 135 | + Some(*scalar as usize) |
| 136 | + } |
| 137 | + _ => None, |
| 138 | + } |
| 139 | +} |
| 140 | + |
| 141 | +// tests: all branches are covered by sqllogictests |
0 commit comments