use arrow::array::{ArrayRef, BooleanArray};
use datafusion_common::{Result, exec_err, not_impl_err, utils::split_vec_min_alloc};
use std::sync::Arc;
use crate::accumulator::AggregateMetrics;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EmitTo {
All,
First(usize),
}
impl EmitTo {
pub fn take_needed<T>(&self, v: &mut Vec<T>) -> Vec<T> {
match self {
Self::All => {
std::mem::take(v)
}
Self::First(n) => split_vec_min_alloc(v, *n),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct GroupSelection<'a> {
total_num_groups: usize,
indices: Option<&'a [usize]>,
}
impl<'a> GroupSelection<'a> {
pub fn all(total_num_groups: usize) -> Self {
Self {
total_num_groups,
indices: None,
}
}
pub fn try_from_indices(
indices: &'a [usize],
total_num_groups: usize,
) -> Result<Self> {
if let Some(index) = indices.iter().find(|&&index| index >= total_num_groups) {
return exec_err!(
"Group index {index} is out of bounds for {total_num_groups} groups"
);
}
Ok(Self {
total_num_groups,
indices: Some(indices),
})
}
pub fn total_num_groups(self) -> usize {
self.total_num_groups
}
pub fn validate_num_groups(self, actual_num_groups: usize) -> Result<()> {
if actual_num_groups != self.total_num_groups {
return exec_err!(
"Group selection was constructed for {} groups but applied to {actual_num_groups} groups",
self.total_num_groups
);
}
Ok(())
}
pub fn len(self) -> usize {
self.indices
.map_or(self.total_num_groups, |indices| indices.len())
}
pub fn is_empty(self) -> bool {
self.len() == 0
}
pub fn iter(self) -> impl Iterator<Item = usize> + 'a {
let (all, indices): (_, &'a [usize]) = match self.indices {
None => (0..self.total_num_groups, &[]),
Some(indices) => (0..0, indices),
};
all.chain(indices.iter().copied())
}
}
pub trait GroupsAccumulator: Send + std::any::Any {
fn set_metrics(&mut self, _metrics: Arc<dyn AggregateMetrics>) {}
fn update_batch(
&mut self,
values: &[ArrayRef],
group_indices: &[usize],
opt_filter: Option<&BooleanArray>,
total_num_groups: usize,
) -> Result<()>;
fn evaluate(&mut self, emit_to: EmitTo) -> Result<ArrayRef>;
fn evaluate_preserving(
&mut self,
_selection: GroupSelection<'_>,
) -> Result<ArrayRef> {
not_impl_err!("Preserving grouped evaluation is not implemented")
}
fn supports_evaluate_preserving(&self) -> bool {
false
}
fn state(&mut self, emit_to: EmitTo) -> Result<Vec<ArrayRef>>;
fn state_preserving(
&mut self,
_selection: GroupSelection<'_>,
) -> Result<Vec<ArrayRef>> {
not_impl_err!("Preserving grouped state is not implemented")
}
fn supports_state_preserving(&self) -> bool {
false
}
fn merge_batch(
&mut self,
values: &[ArrayRef],
group_indices: &[usize],
total_num_groups: usize,
) -> Result<()>;
fn convert_to_state(
&self,
values: &[ArrayRef],
opt_filter: Option<&BooleanArray>,
) -> Result<Vec<ArrayRef>>;
fn size(&self) -> usize;
fn shrink_to_fit(&mut self) {}
}
#[cfg(test)]
mod tests {
use super::{EmitTo, GroupSelection};
#[test]
fn take_needed_first_small_n_allocates_minimally() {
let mut v: Vec<i32> = Vec::with_capacity(128);
v.extend(0..20i32);
let original_capacity = v.capacity();
let emitted = EmitTo::First(4).take_needed(&mut v);
assert_eq!(emitted, vec![0, 1, 2, 3]);
assert_eq!(v, (4..20i32).collect::<Vec<_>>());
assert!(
emitted.capacity() <= 4,
"emitted prefix capacity {} should be ~n=4, not the original {}",
emitted.capacity(),
original_capacity,
);
assert_eq!(
v.capacity(),
original_capacity,
"remaining vec capacity {} should equal original {}",
v.capacity(),
original_capacity,
);
}
#[test]
fn group_selection_is_validated_once_and_reusable() {
let values = [10, 20, 30, 40];
let selected =
GroupSelection::try_from_indices(&[3, 1, 3], values.len()).unwrap();
assert_eq!(selected.total_num_groups(), values.len());
assert_eq!(selected.len(), 3);
assert_eq!(
selected
.iter()
.map(|index| values[index])
.collect::<Vec<_>>(),
vec![40, 20, 40]
);
selected.validate_num_groups(values.len()).unwrap();
let error = selected.validate_num_groups(values.len() - 1).unwrap_err();
assert!(error.to_string().contains("constructed for 4 groups"));
let all = GroupSelection::all(values.len());
assert_eq!(
all.iter().map(|index| values[index]).collect::<Vec<_>>(),
values
);
let empty = GroupSelection::try_from_indices(&[], values.len()).unwrap();
assert!(empty.is_empty());
assert!(empty.iter().next().is_none());
let error = GroupSelection::try_from_indices(&[4], values.len()).unwrap_err();
assert!(error.to_string().contains("out of bounds"));
}
}