Skip to main content

datafusion_physical_expr/window/
standard.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//! Physical exec for standard window function expressions.
6
7use std::any::Any;
8use std::sync::Arc;
9
10use super::{StandardWindowFunctionExpr, WindowExpr};
11use crate::window::window_expr::{WindowEvalContext, WindowFn, get_orderby_values};
12use crate::window::{PartitionBatches, PartitionWindowAggStates, WindowState};
13use crate::{EquivalenceProperties, PhysicalExpr};
14
15use arrow::array::{ArrayRef, new_empty_array};
16use arrow::datatypes::FieldRef;
17use arrow::record_batch::RecordBatch;
18use datafusion_common::utils::evaluate_partition_ranges;
19use datafusion_common::{Result, ScalarValue};
20use datafusion_expr::WindowFrame;
21use datafusion_expr::window_state::{WindowAggState, WindowFrameContext};
22use datafusion_physical_expr_common::sort_expr::PhysicalSortExpr;
23
24/// A window expr that takes the form of a [`StandardWindowFunctionExpr`].
25#[derive(Debug)]
26pub struct StandardWindowExpr {
27    expr: Arc<dyn StandardWindowFunctionExpr>,
28    partition_by: Vec<Arc<dyn PhysicalExpr>>,
29    order_by: Vec<PhysicalSortExpr>,
30    window_frame: Arc<WindowFrame>,
31}
32
33impl StandardWindowExpr {
34    /// create a new standard window function expression
35    pub fn new(
36        expr: Arc<dyn StandardWindowFunctionExpr>,
37        partition_by: &[Arc<dyn PhysicalExpr>],
38        order_by: &[PhysicalSortExpr],
39        window_frame: Arc<WindowFrame>,
40    ) -> Self {
41        Self {
42            expr,
43            partition_by: partition_by.to_vec(),
44            order_by: order_by.to_vec(),
45            window_frame,
46        }
47    }
48
49    /// Get StandardWindowFunction expr of StandardWindowExpr
50    pub fn get_standard_func_expr(&self) -> &Arc<dyn StandardWindowFunctionExpr> {
51        &self.expr
52    }
53
54    /// Adds any equivalent orderings generated by `self.expr` to `builder`.
55    ///
56    /// If `self.expr` doesn't have an ordering, ordering equivalence properties
57    /// are not updated. Otherwise, ordering equivalence properties are updated
58    /// by the ordering of `self.expr`.
59    pub fn add_equal_orderings(
60        &self,
61        eq_properties: &mut EquivalenceProperties,
62    ) -> Result<()> {
63        let schema = eq_properties.schema();
64        if let Some(fn_res_ordering) = self.expr.get_result_ordering(schema) {
65            add_new_ordering_expr_with_partition_by(
66                eq_properties,
67                fn_res_ordering,
68                &self.partition_by,
69            )?;
70        }
71        Ok(())
72    }
73}
74
75impl WindowExpr for StandardWindowExpr {
76    /// Return a reference to Any that can be used for downcasting
77    fn as_any(&self) -> &dyn Any {
78        self
79    }
80
81    fn name(&self) -> &str {
82        self.expr.name()
83    }
84
85    fn field(&self) -> Result<FieldRef> {
86        self.expr.field()
87    }
88
89    fn expressions(&self) -> Vec<Arc<dyn PhysicalExpr>> {
90        self.expr.expressions()
91    }
92
93    fn partition_by(&self) -> &[Arc<dyn PhysicalExpr>] {
94        &self.partition_by
95    }
96
97    fn order_by(&self) -> &[PhysicalSortExpr] {
98        &self.order_by
99    }
100
101    fn evaluate(&self, batch: &RecordBatch) -> Result<ArrayRef> {
102        let mut evaluator = self.expr.create_evaluator()?;
103        let num_rows = batch.num_rows();
104        if evaluator.uses_window_frame() {
105            let sort_options = self.order_by.iter().map(|o| o.options).collect();
106            let mut ranges = Vec::with_capacity(num_rows);
107
108            let mut values = self.evaluate_args(batch)?;
109            let order_bys = get_orderby_values(self.order_by_columns(batch)?);
110            let n_args = values.len();
111            values.extend(order_bys);
112            let order_bys_ref = &values[n_args..];
113
114            let mut window_frame_ctx =
115                WindowFrameContext::new(Arc::clone(&self.window_frame), sort_options);
116            // We iterate on each row to calculate its window frame range
117            for idx in 0..num_rows {
118                let range = window_frame_ctx.calculate_range(
119                    order_bys_ref,
120                    ranges.last().unwrap_or(&(0..0)),
121                    num_rows,
122                    idx,
123                )?;
124                ranges.push(range);
125            }
126            evaluator.evaluate_ranges(&values, &ranges)
127        } else if evaluator.include_rank() {
128            let columns = self.order_by_columns(batch)?;
129            let sort_partition_points = evaluate_partition_ranges(num_rows, &columns)?;
130            evaluator.evaluate_all_with_rank(num_rows, &sort_partition_points)
131        } else {
132            let values = self.evaluate_args(batch)?;
133            evaluator.evaluate_all(&values, num_rows)
134        }
135    }
136
137    /// Evaluate the window function against the batch. This function facilitates
138    /// stateful, bounded-memory implementations.
139    fn evaluate_stateful(
140        &self,
141        partition_batches: &PartitionBatches,
142        window_agg_state: &mut PartitionWindowAggStates,
143        _eval_ctx: &WindowEvalContext<'_>,
144    ) -> Result<()> {
145        let field = self.expr.field()?;
146        let out_type = field.data_type();
147        let sort_options = self.order_by.iter().map(|o| o.options).collect::<Vec<_>>();
148        // create a WindowAggState to clone when `window_agg_state` does not contain the respective
149        // group, which is faster than potentially creating a new one at every iteration
150        let new_state = WindowAggState::new(out_type)?;
151        for (partition_row, partition_batch_state) in partition_batches.iter() {
152            let window_state =
153                if let Some(window_state) = window_agg_state.get_mut(partition_row) {
154                    window_state
155                } else {
156                    let evaluator = self.expr.create_evaluator()?;
157                    window_agg_state
158                        .entry(partition_row.clone())
159                        .or_insert(WindowState {
160                            state: new_state.clone(),
161                            window_fn: WindowFn::Builtin(evaluator),
162                            published: false,
163                        })
164                };
165            // Skip partitions whose input is unchanged since the last
166            // evaluation pass.
167            if window_state.state.is_input_unchanged(partition_batch_state) {
168                continue;
169            }
170            let WindowFn::Builtin(evaluator) = &mut window_state.window_fn else {
171                unreachable!()
172            };
173            let state = &mut window_state.state;
174
175            let batch_ref = &partition_batch_state.record_batch;
176            let mut values = self.evaluate_args(batch_ref)?;
177            let uses_window_frame = evaluator.uses_window_frame();
178            let order_bys = if uses_window_frame || evaluator.include_rank() {
179                get_orderby_values(self.order_by_columns(batch_ref)?)
180            } else {
181                vec![]
182            };
183            let n_args = values.len();
184            values.extend(order_bys);
185            let order_bys_ref = &values[n_args..];
186
187            // We iterate on each row to perform a running calculation.
188            let record_batch = &partition_batch_state.record_batch;
189            let num_rows = record_batch.num_rows();
190            let n_new_rows = num_rows.saturating_sub(state.last_calculated_index);
191            // Functions that use the window frame are evaluated on all frames after
192            // the loop. Other functions are evaluated row by row, because their
193            // `get_range` can depend on state that `evaluate` updates.
194            let (mut frame_ranges, mut row_wise_results) = if uses_window_frame {
195                (Vec::with_capacity(n_new_rows), Vec::new())
196            } else {
197                (Vec::new(), Vec::with_capacity(n_new_rows))
198            };
199            let is_causal = if uses_window_frame {
200                self.window_frame.is_causal()
201            } else {
202                evaluator.is_causal()
203            };
204            for idx in state.last_calculated_index..num_rows {
205                let frame_range = if uses_window_frame {
206                    state
207                        .window_frame_ctx
208                        .get_or_insert_with(|| {
209                            WindowFrameContext::new(
210                                Arc::clone(&self.window_frame),
211                                sort_options.clone(),
212                            )
213                        })
214                        .calculate_range(
215                            order_bys_ref,
216                            // Start search from the last range
217                            &state.window_frame_range,
218                            num_rows,
219                            idx,
220                        )
221                } else {
222                    evaluator.get_range(idx, num_rows)
223                }?;
224
225                // Exit if the range is non-causal and extends all the way:
226                if frame_range.end == num_rows
227                    && !is_causal
228                    && !partition_batch_state.is_end
229                {
230                    break;
231                }
232                // Update last range
233                state.window_frame_range = frame_range;
234                if uses_window_frame {
235                    frame_ranges.push(state.window_frame_range.clone());
236                } else {
237                    row_wise_results
238                        .push(evaluator.evaluate(&values, &state.window_frame_range)?);
239                }
240            }
241            let out_col = if !frame_ranges.is_empty() {
242                evaluator.evaluate_ranges(&values, &frame_ranges)?
243            } else if row_wise_results.is_empty() {
244                new_empty_array(out_type)
245            } else if row_wise_results.len() == 1 {
246                // fast path when the result only has a single row
247                row_wise_results[0].to_array()?
248            } else {
249                ScalarValue::iter_to_array(row_wise_results)?
250            };
251
252            state.update(&out_col, partition_batch_state)?;
253            if self.window_frame.start_bound.is_unbounded() {
254                evaluator.memoize(state)?;
255            }
256        }
257        Ok(())
258    }
259
260    fn get_window_frame(&self) -> &Arc<WindowFrame> {
261        &self.window_frame
262    }
263
264    fn get_reverse_expr(&self) -> Option<Arc<dyn WindowExpr>> {
265        self.expr.reverse_expr().map(|reverse_expr| {
266            Arc::new(StandardWindowExpr::new(
267                reverse_expr,
268                &self.partition_by.clone(),
269                &self
270                    .order_by
271                    .iter()
272                    .map(|e| e.reverse())
273                    .collect::<Vec<_>>(),
274                Arc::new(self.window_frame.reverse()),
275            )) as _
276        })
277    }
278
279    fn uses_bounded_memory(&self) -> bool {
280        if let Ok(evaluator) = self.expr.create_evaluator() {
281            evaluator.supports_bounded_execution()
282                && (!evaluator.uses_window_frame()
283                    || !self.window_frame.end_bound.is_unbounded())
284        } else {
285            false
286        }
287    }
288
289    fn create_window_fn(&self) -> Result<WindowFn> {
290        Ok(WindowFn::Builtin(self.expr.create_evaluator()?))
291    }
292}
293
294/// Adds a new ordering expression into existing ordering equivalence class(es) based on
295/// PARTITION BY information (if it exists).
296pub(crate) fn add_new_ordering_expr_with_partition_by(
297    eqp: &mut EquivalenceProperties,
298    expr: PhysicalSortExpr,
299    partition_by: &[Arc<dyn PhysicalExpr>],
300) -> Result<()> {
301    if partition_by.is_empty() {
302        // In the absence of a PARTITION BY, ordering of `self.expr` is global:
303        eqp.add_ordering([expr]);
304    } else {
305        // If we have a PARTITION BY, standard functions can not introduce
306        // a global ordering unless the existing ordering is compatible
307        // with PARTITION BY expressions. To elaborate, when PARTITION BY
308        // expressions and existing ordering expressions are equal (w.r.t.
309        // set equality), we can prefix the ordering of `self.expr` with
310        // the existing ordering.
311        let (mut ordering, _) = eqp.find_longest_permutation(partition_by)?;
312        if ordering.len() == partition_by.len() {
313            ordering.push(expr);
314            eqp.add_ordering(ordering);
315        }
316    }
317    Ok(())
318}