datafusion_physical_expr/window/
aggregate.rs1use std::any::Any;
8use std::ops::Range;
9use std::sync::Arc;
10
11use crate::aggregate::AggregateFunctionExpr;
12use crate::window::standard::add_new_ordering_expr_with_partition_by;
13use crate::window::window_expr::{
14 AggregateWindowExpr, WindowEvalContext, WindowFn, filter_array,
15};
16use crate::window::{
17 PartitionBatches, PartitionWindowAggStates, SlidingAggregateWindowExpr, WindowExpr,
18};
19use crate::{EquivalenceProperties, PhysicalExpr};
20
21use arrow::array::ArrayRef;
22use arrow::array::BooleanArray;
23use arrow::datatypes::FieldRef;
24use arrow::record_batch::RecordBatch;
25use datafusion_common::{Result, ScalarValue, exec_datafusion_err};
26use datafusion_expr::{Accumulator, WindowFrame, WindowFrameBound, WindowFrameUnits};
27use datafusion_physical_expr_common::sort_expr::PhysicalSortExpr;
28
29pub(crate) fn reverse_aggregate_window_expr(
42 aggregate: &AggregateFunctionExpr,
43 partition_by: &[Arc<dyn PhysicalExpr>],
44 order_by: &[PhysicalSortExpr],
45 window_frame: &WindowFrame,
46 filter: Option<&Arc<dyn PhysicalExpr>>,
47) -> Option<Arc<dyn WindowExpr>> {
48 aggregate
49 .reverse_expr_preserving_name()
50 .map(|reverse_expr| {
51 let reverse_expr = Arc::new(reverse_expr);
52 let reverse_order_by =
53 order_by.iter().map(|e| e.reverse()).collect::<Vec<_>>();
54 let reverse_window_frame = Arc::new(window_frame.reverse());
55 let filter = filter.cloned();
56 if reverse_window_frame.is_ever_expanding() {
57 Arc::new(PlainAggregateWindowExpr::new(
58 reverse_expr,
59 partition_by,
60 &reverse_order_by,
61 reverse_window_frame,
62 filter,
63 )) as _
64 } else {
65 Arc::new(SlidingAggregateWindowExpr::new(
66 reverse_expr,
67 partition_by,
68 &reverse_order_by,
69 reverse_window_frame,
70 filter,
71 )) as _
72 }
73 })
74}
75
76#[derive(Debug)]
80pub struct PlainAggregateWindowExpr {
81 aggregate: Arc<AggregateFunctionExpr>,
82 partition_by: Vec<Arc<dyn PhysicalExpr>>,
83 order_by: Vec<PhysicalSortExpr>,
84 window_frame: Arc<WindowFrame>,
85 is_constant_in_partition: bool,
86 filter: Option<Arc<dyn PhysicalExpr>>,
87}
88
89impl PlainAggregateWindowExpr {
90 pub fn new(
92 aggregate: Arc<AggregateFunctionExpr>,
93 partition_by: &[Arc<dyn PhysicalExpr>],
94 order_by: &[PhysicalSortExpr],
95 window_frame: Arc<WindowFrame>,
96 filter: Option<Arc<dyn PhysicalExpr>>,
97 ) -> Self {
98 let is_constant_in_partition =
99 Self::is_window_constant_in_partition(order_by, &window_frame);
100 Self {
101 aggregate,
102 partition_by: partition_by.to_vec(),
103 order_by: order_by.to_vec(),
104 window_frame,
105 is_constant_in_partition,
106 filter,
107 }
108 }
109
110 pub fn get_aggregate_expr(&self) -> &AggregateFunctionExpr {
112 &self.aggregate
113 }
114
115 pub fn add_equal_orderings(
116 &self,
117 eq_properties: &mut EquivalenceProperties,
118 window_expr_index: usize,
119 ) -> Result<()> {
120 if let Some(expr) = self
121 .get_aggregate_expr()
122 .get_result_ordering(window_expr_index)
123 {
124 add_new_ordering_expr_with_partition_by(
125 eq_properties,
126 expr,
127 &self.partition_by,
128 )?;
129 }
130 Ok(())
131 }
132
133 fn is_window_constant_in_partition(
143 order_by: &[PhysicalSortExpr],
144 window_frame: &WindowFrame,
145 ) -> bool {
146 let is_constant_bound = |bound: &WindowFrameBound| match bound {
147 WindowFrameBound::CurrentRow => {
148 window_frame.units == WindowFrameUnits::Range && order_by.is_empty()
149 }
150 _ => bound.is_unbounded(),
151 };
152
153 is_constant_bound(&window_frame.start_bound)
154 && is_constant_bound(&window_frame.end_bound)
155 }
156}
157
158impl WindowExpr for PlainAggregateWindowExpr {
162 fn as_any(&self) -> &dyn Any {
164 self
165 }
166
167 fn field(&self) -> Result<FieldRef> {
168 Ok(self.aggregate.field())
169 }
170
171 fn name(&self) -> &str {
172 self.aggregate.name()
173 }
174
175 fn expressions(&self) -> Vec<Arc<dyn PhysicalExpr>> {
176 self.aggregate.expressions()
177 }
178
179 fn evaluate(&self, batch: &RecordBatch) -> Result<ArrayRef> {
180 self.aggregate_evaluate(batch)
181 }
182
183 fn evaluate_stateful(
184 &self,
185 partition_batches: &PartitionBatches,
186 window_agg_state: &mut PartitionWindowAggStates,
187 eval_ctx: &WindowEvalContext<'_>,
188 ) -> Result<()> {
189 self.aggregate_evaluate_stateful(partition_batches, window_agg_state, eval_ctx)?;
190
191 for partition_row in partition_batches.keys() {
197 let window_state = window_agg_state
198 .get_mut(partition_row)
199 .ok_or_else(|| exec_datafusion_err!("Cannot find state"))?;
200 let state = &mut window_state.state;
201 if self.window_frame.start_bound.is_unbounded() {
202 state.window_frame_range.start =
203 state.window_frame_range.end.saturating_sub(1);
204 }
205 }
206 Ok(())
207 }
208
209 fn partition_by(&self) -> &[Arc<dyn PhysicalExpr>] {
210 &self.partition_by
211 }
212
213 fn order_by(&self) -> &[PhysicalSortExpr] {
214 &self.order_by
215 }
216
217 fn get_window_frame(&self) -> &Arc<WindowFrame> {
218 &self.window_frame
219 }
220
221 fn get_reverse_expr(&self) -> Option<Arc<dyn WindowExpr>> {
222 reverse_aggregate_window_expr(
223 &self.aggregate,
224 &self.partition_by,
225 &self.order_by,
226 &self.window_frame,
227 self.filter.as_ref(),
228 )
229 }
230
231 fn uses_bounded_memory(&self) -> bool {
232 !self.window_frame.end_bound.is_unbounded()
233 }
234
235 fn create_window_fn(&self) -> Result<WindowFn> {
236 Ok(WindowFn::Aggregate(self.get_accumulator()?))
237 }
238}
239
240impl AggregateWindowExpr for PlainAggregateWindowExpr {
241 fn get_accumulator(&self) -> Result<Box<dyn Accumulator>> {
242 self.aggregate.create_accumulator()
243 }
244
245 fn filter_expr(&self) -> Option<&Arc<dyn PhysicalExpr>> {
246 self.filter.as_ref()
247 }
248
249 fn get_aggregate_result_inside_range(
255 &self,
256 last_range: &Range<usize>,
257 cur_range: &Range<usize>,
258 value_slice: &[ArrayRef],
259 accumulator: &mut Box<dyn Accumulator>,
260 filter_mask: Option<&BooleanArray>,
261 ) -> Result<ScalarValue> {
262 if cur_range.start == cur_range.end {
263 self.aggregate
264 .default_value(self.aggregate.field().data_type())
265 } else {
266 let update_bound = cur_range.end - last_range.end;
268 if update_bound > 0 {
273 let slice_mask =
274 filter_mask.map(|m| m.slice(last_range.end, update_bound));
275 let update: Vec<ArrayRef> = value_slice
276 .iter()
277 .map(|v| v.slice(last_range.end, update_bound))
278 .map(|arr| match &slice_mask {
279 Some(m) => filter_array(&arr, m),
280 None => Ok(arr),
281 })
282 .collect::<Result<Vec<_>>>()?;
283 accumulator.update_batch(&update)?
284 }
285 accumulator.evaluate()
286 }
287 }
288
289 fn is_constant_in_partition(&self) -> bool {
290 self.is_constant_in_partition
291 }
292}