Skip to main content

datafusion_expr/
partition_evaluator.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//! Partition evaluation module
6
7use arrow::array::ArrayRef;
8use datafusion_common::{Result, ScalarValue, exec_err, not_impl_err};
9use std::fmt::Debug;
10use std::ops::Range;
11
12use crate::window_state::WindowAggState;
13
14/// Partition evaluator for Window Functions
15///
16/// # Background
17///
18/// An implementation of this trait is created and used for each
19/// partition defined by an `OVER` clause and is instantiated by
20/// the DataFusion runtime.
21///
22/// For example, evaluating `window_func(val) OVER (PARTITION BY col)`
23/// on the following data:
24///
25/// ```text
26/// col | val
27/// --- + ----
28///  A  | 10
29///  A  | 10
30///  C  | 20
31///  D  | 30
32///  D  | 30
33/// ```
34///
35/// Will instantiate three `PartitionEvaluator`s, one each for the
36/// partitions defined by `col=A`, `col=B`, and `col=C`.
37///
38/// ```text
39/// col | val
40/// --- + ----
41///  A  | 10     <--- partition 1
42///  A  | 10
43///
44/// col | val
45/// --- + ----
46///  C  | 20     <--- partition 2
47///
48/// col | val
49/// --- + ----
50///  D  | 30     <--- partition 3
51///  D  | 30
52/// ```
53///
54/// Different methods on this trait will be called depending on the
55/// capabilities described by [`supports_bounded_execution`],
56/// [`uses_window_frame`], and [`include_rank`],
57///
58/// When implementing a new `PartitionEvaluator`, implement
59/// corresponding evaluator according to table below.
60///
61/// # Implementation Table
62///
63/// |[`uses_window_frame`]|[`supports_bounded_execution`]|[`include_rank`]|function_to_implement|
64/// |---|---|----|----|
65/// |false (default)      |false (default)               |false (default)   | [`evaluate_all`]           |
66/// |false                |true                          |false             | [`evaluate`]               |
67/// |false                |true/false                    |true              | [`evaluate_all_with_rank`] |
68/// |true                 |true/false                    |true/false        | [`evaluate`]               |
69///
70/// [`evaluate`]: Self::evaluate
71/// [`evaluate_all`]: Self::evaluate_all
72/// [`evaluate_all_with_rank`]: Self::evaluate_all_with_rank
73/// [`uses_window_frame`]: Self::uses_window_frame
74/// [`include_rank`]: Self::include_rank
75/// [`supports_bounded_execution`]: Self::supports_bounded_execution
76///
77/// For more background, please also see the [User defined Window Functions in DataFusion blog]
78///
79/// [User defined Window Functions in DataFusion blog]: https://datafusion.apache.org/blog/2025/04/19/user-defined-window-functions
80pub trait PartitionEvaluator: Debug + Send + std::any::Any {
81    /// When the window frame has a fixed beginning (e.g UNBOUNDED
82    /// PRECEDING), some functions such as FIRST_VALUE, LAST_VALUE and
83    /// NTH_VALUE do not need the (unbounded) input once they have
84    /// seen a certain amount of input.
85    ///
86    /// `memoize` is called after each input batch is processed, and
87    /// such functions can save whatever they need and modify
88    /// [`WindowAggState`] appropriately to allow rows to be pruned
89    fn memoize(&mut self, _state: &mut WindowAggState) -> Result<()> {
90        Ok(())
91    }
92
93    /// If `uses_window_frame` flag is `false`. This method is used to
94    /// calculate required range for the window function during
95    /// stateful execution.
96    ///
97    /// Generally there is no required range, hence by default this
98    /// returns smallest range(current row). e.g seeing current row is
99    /// enough to calculate window result (such as row_number, rank,
100    /// etc)
101    fn get_range(&self, idx: usize, _n_rows: usize) -> Result<Range<usize>> {
102        if self.uses_window_frame() {
103            exec_err!("Range should be calculated from window frame")
104        } else {
105            Ok(Range {
106                start: idx,
107                end: idx + 1,
108            })
109        }
110    }
111
112    /// Get whether evaluator needs future data for its result (if so returns `false`) or not
113    fn is_causal(&self) -> bool {
114        false
115    }
116
117    /// Evaluate a window function on an entire input partition.
118    ///
119    /// This function is called once per input *partition* for window
120    /// functions that *do not use* values from the window frame,
121    /// such as `ROW_NUMBER`, `RANK`, `DENSE_RANK`, `PERCENT_RANK`,
122    /// `CUME_DIST`, `LEAD`, `LAG`).
123    ///
124    /// It produces the result of all rows in a single pass. It
125    /// expects to receive the entire partition as the `value` and
126    /// must produce an output column with one output row for every
127    /// input row.
128    ///
129    /// `num_rows` is required to correctly compute the output in case
130    /// `values.len() == 0`
131    ///
132    /// Implementing this function is an optimization: certain window
133    /// functions are not affected by the window frame definition or
134    /// the query doesn't have a frame, and `evaluate` skips the
135    /// (costly) window frame boundary calculation and the overhead of
136    /// calling `evaluate` for each output row.
137    ///
138    /// For example, the `LAG` built in window function does not use
139    /// the values of its window frame (it can be computed in one shot
140    /// on the entire partition with `Self::evaluate_all` regardless of the
141    /// window defined in the `OVER` clause)
142    ///
143    /// ```sql
144    /// lag(x, 1) OVER (ORDER BY z ROWS BETWEEN 2 PRECEDING AND 3 FOLLOWING)
145    /// ```
146    ///
147    /// However, `avg()` computes the average in the window and thus
148    /// does use its window frame
149    ///
150    /// ```sql
151    /// avg(x) OVER (PARTITION BY y ORDER BY z ROWS BETWEEN 2 PRECEDING AND 3 FOLLOWING)
152    /// ```
153    fn evaluate_all(&mut self, values: &[ArrayRef], num_rows: usize) -> Result<ArrayRef> {
154        // When window frame boundaries are not used and evaluator supports bounded execution
155        // We can calculate evaluate result by repeatedly calling `self.evaluate` `num_rows` times
156        // If user wants to implement more efficient version, this method should be overwritten
157        // Default implementation may behave suboptimally (For instance `NumRowEvaluator` overwrites it)
158        if !self.uses_window_frame() && self.supports_bounded_execution() {
159            let res = (0..num_rows)
160                .map(|idx| self.evaluate(values, &self.get_range(idx, num_rows)?))
161                .collect::<Result<Vec<_>>>()?;
162            ScalarValue::iter_to_array(res)
163        } else {
164            not_impl_err!("evaluate_all is not implemented by default")
165        }
166    }
167
168    /// Evaluate window function on a range of rows in an input
169    /// partition.
170    ///
171    /// This is the simplest and most general function to implement
172    /// but also the least performant as it creates output one row at
173    /// a time. It is typically much faster to implement stateful
174    /// evaluation using one of the other specialized methods on this
175    /// trait.
176    ///
177    /// Returns a [`ScalarValue`] that is the value of the window
178    /// function within `range` for the entire partition. Argument
179    /// `values` contains the evaluation result of function arguments
180    /// and evaluation results of ORDER BY expressions. If function has a
181    /// single argument, `values[1..]` will contain ORDER BY expression results.
182    fn evaluate(
183        &mut self,
184        _values: &[ArrayRef],
185        _range: &Range<usize>,
186    ) -> Result<ScalarValue> {
187        not_impl_err!("evaluate is not implemented by default")
188    }
189
190    /// Evaluate window function on the window frames of consecutive rows
191    /// in an input partition, returning one result per range.
192    ///
193    /// This is called instead of [`Self::evaluate`] for window functions
194    /// that [use the window frame](Self::uses_window_frame), with the same
195    /// `values`.
196    ///
197    /// The default implementation calls [`Self::evaluate`] for each range.
198    /// Implementing this function is an optimization: a function such as
199    /// `FIRST_VALUE`, whose result is one of the input rows, can gather
200    /// all results with a single `take` instead of creating a
201    /// [`ScalarValue`] for every row.
202    fn evaluate_ranges(
203        &mut self,
204        values: &[ArrayRef],
205        ranges: &[Range<usize>],
206    ) -> Result<ArrayRef> {
207        if let [range] = ranges {
208            return self.evaluate(values, range)?.to_array();
209        }
210        let mut results = Vec::with_capacity(ranges.len());
211        for range in ranges {
212            results.push(self.evaluate(values, range)?);
213        }
214        ScalarValue::iter_to_array(results)
215    }
216
217    /// [`PartitionEvaluator::evaluate_all_with_rank`] is called for window
218    /// functions that only need the rank of a row within its window
219    /// frame.
220    ///
221    /// Evaluate the partition evaluator against the partition using
222    /// the row ranks. For example, `RANK(col)` produces
223    ///
224    /// ```text
225    /// col | rank
226    /// --- + ----
227    ///  A  | 1
228    ///  A  | 1
229    ///  C  | 3
230    ///  D  | 4
231    ///  D  | 4
232    /// ```
233    ///
234    /// For this case, `num_rows` would be `5` and the
235    /// `ranks_in_partition` would be called with
236    ///
237    /// ```text
238    /// [
239    ///   (0,1),
240    ///   (2,2),
241    ///   (3,4),
242    /// ]
243    /// ```
244    fn evaluate_all_with_rank(
245        &self,
246        _num_rows: usize,
247        _ranks_in_partition: &[Range<usize>],
248    ) -> Result<ArrayRef> {
249        not_impl_err!("evaluate_partition_with_rank is not implemented by default")
250    }
251
252    /// Can the window function be incrementally computed using
253    /// bounded memory?
254    ///
255    /// See the table on [`Self`] for what functions to implement
256    fn supports_bounded_execution(&self) -> bool {
257        false
258    }
259
260    /// Does the window function use the values from the window frame,
261    /// if one is specified?
262    ///
263    /// See the table on [`Self`] for what functions to implement
264    fn uses_window_frame(&self) -> bool {
265        false
266    }
267
268    /// Can this function be evaluated with (only) rank
269    ///
270    /// See the table on [`Self`] for what functions to implement
271    fn include_rank(&self) -> bool {
272        false
273    }
274}