use std::any::Any;
use std::fmt::Debug;
use std::mem::size_of_val;
use std::sync::{Arc, OnceLock};
use arrow::array::{ArrayRef, AsArray, BooleanArray};
use arrow::compute::{self, lexsort_to_indices, take_arrays, SortColumn};
use arrow::datatypes::{DataType, Field};
use datafusion_common::utils::{compare_rows, get_row_at_idx};
use datafusion_common::{
arrow_datafusion_err, internal_err, DataFusionError, Result, ScalarValue,
};
use datafusion_expr::aggregate_doc_sections::DOC_SECTION_GENERAL;
use datafusion_expr::function::{AccumulatorArgs, StateFieldsArgs};
use datafusion_expr::utils::{format_state_name, AggregateOrderSensitivity};
use datafusion_expr::{
Accumulator, AggregateUDFImpl, ArrayFunctionSignature, Documentation, Expr,
ExprFunctionExt, Signature, SortExpr, TypeSignature, Volatility,
};
use datafusion_functions_aggregate_common::utils::get_sort_options;
use datafusion_physical_expr_common::sort_expr::{LexOrdering, LexOrderingRef};
create_func!(FirstValue, first_value_udaf);
pub fn first_value(expression: Expr, order_by: Option<Vec<SortExpr>>) -> Expr {
if let Some(order_by) = order_by {
first_value_udaf()
.call(vec![expression])
.order_by(order_by)
.build()
.unwrap()
} else {
first_value_udaf().call(vec![expression])
}
}
pub struct FirstValue {
signature: Signature,
requirement_satisfied: bool,
}
impl Debug for FirstValue {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.debug_struct("FirstValue")
.field("name", &self.name())
.field("signature", &self.signature)
.field("accumulator", &"<FUNC>")
.finish()
}
}
impl Default for FirstValue {
fn default() -> Self {
Self::new()
}
}
impl FirstValue {
pub fn new() -> Self {
Self {
signature: Signature::one_of(
vec![
TypeSignature::ArraySignature(ArrayFunctionSignature::Array),
TypeSignature::Numeric(1),
TypeSignature::Uniform(1, vec![DataType::Utf8]),
],
Volatility::Immutable,
),
requirement_satisfied: false,
}
}
fn with_requirement_satisfied(mut self, requirement_satisfied: bool) -> Self {
self.requirement_satisfied = requirement_satisfied;
self
}
}
impl AggregateUDFImpl for FirstValue {
fn as_any(&self) -> &dyn Any {
self
}
fn name(&self) -> &str {
"first_value"
}
fn signature(&self) -> &Signature {
&self.signature
}
fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
Ok(arg_types[0].clone())
}
fn accumulator(&self, acc_args: AccumulatorArgs) -> Result<Box<dyn Accumulator>> {
let ordering_dtypes = acc_args
.ordering_req
.iter()
.map(|e| e.expr.data_type(acc_args.schema))
.collect::<Result<Vec<_>>>()?;
let requirement_satisfied =
acc_args.ordering_req.is_empty() || self.requirement_satisfied;
FirstValueAccumulator::try_new(
acc_args.return_type,
&ordering_dtypes,
LexOrdering::from_ref(acc_args.ordering_req),
acc_args.ignore_nulls,
)
.map(|acc| Box::new(acc.with_requirement_satisfied(requirement_satisfied)) as _)
}
fn state_fields(&self, args: StateFieldsArgs) -> Result<Vec<Field>> {
let mut fields = vec![Field::new(
format_state_name(args.name, "first_value"),
args.return_type.clone(),
true,
)];
fields.extend(args.ordering_fields.to_vec());
fields.push(Field::new("is_set", DataType::Boolean, true));
Ok(fields)
}
fn aliases(&self) -> &[String] {
&[]
}
fn with_beneficial_ordering(
self: Arc<Self>,
beneficial_ordering: bool,
) -> Result<Option<Arc<dyn AggregateUDFImpl>>> {
Ok(Some(Arc::new(
FirstValue::new().with_requirement_satisfied(beneficial_ordering),
)))
}
fn order_sensitivity(&self) -> AggregateOrderSensitivity {
AggregateOrderSensitivity::Beneficial
}
fn reverse_expr(&self) -> datafusion_expr::ReversedUDAF {
datafusion_expr::ReversedUDAF::Reversed(last_value_udaf())
}
fn documentation(&self) -> Option<&Documentation> {
Some(get_first_value_doc())
}
}
static DOCUMENTATION: OnceLock<Documentation> = OnceLock::new();
fn get_first_value_doc() -> &'static Documentation {
DOCUMENTATION.get_or_init(|| {
Documentation::builder()
.with_doc_section(DOC_SECTION_GENERAL)
.with_description(
"Returns the first element in an aggregation group according to the requested ordering. If no ordering is given, returns an arbitrary element from the group.",
)
.with_syntax_example("first_value(expression [ORDER BY expression])")
.with_sql_example(r#"```sql
> SELECT first_value(column_name ORDER BY other_column) FROM table_name;
+-----------------------------------------------+
| first_value(column_name ORDER BY other_column)|
+-----------------------------------------------+
| first_element |
+-----------------------------------------------+
```"#,
)
.with_standard_argument("expression", None)
.build()
.unwrap()
})
}
#[derive(Debug)]
pub struct FirstValueAccumulator {
first: ScalarValue,
is_set: bool,
orderings: Vec<ScalarValue>,
ordering_req: LexOrdering,
requirement_satisfied: bool,
ignore_nulls: bool,
}
impl FirstValueAccumulator {
pub fn try_new(
data_type: &DataType,
ordering_dtypes: &[DataType],
ordering_req: LexOrdering,
ignore_nulls: bool,
) -> Result<Self> {
let orderings = ordering_dtypes
.iter()
.map(ScalarValue::try_from)
.collect::<Result<Vec<_>>>()?;
let requirement_satisfied = ordering_req.is_empty();
ScalarValue::try_from(data_type).map(|first| Self {
first,
is_set: false,
orderings,
ordering_req,
requirement_satisfied,
ignore_nulls,
})
}
pub fn with_requirement_satisfied(mut self, requirement_satisfied: bool) -> Self {
self.requirement_satisfied = requirement_satisfied;
self
}
fn update_with_new_row(&mut self, row: &[ScalarValue]) {
self.first = row[0].clone();
self.orderings = row[1..].to_vec();
self.is_set = true;
}
fn get_first_idx(&self, values: &[ArrayRef]) -> Result<Option<usize>> {
let [value, ordering_values @ ..] = values else {
return internal_err!("Empty row in FIRST_VALUE");
};
if self.requirement_satisfied {
if self.ignore_nulls {
for i in 0..value.len() {
if !value.is_null(i) {
return Ok(Some(i));
}
}
return Ok(None);
} else {
return Ok((!value.is_empty()).then_some(0));
}
}
let sort_columns = ordering_values
.iter()
.zip(self.ordering_req.iter())
.map(|(values, req)| SortColumn {
values: Arc::clone(values),
options: Some(req.options),
})
.collect::<Vec<_>>();
if self.ignore_nulls {
let indices = lexsort_to_indices(&sort_columns, None)?;
for index in indices.iter().flatten() {
if !value.is_null(index as usize) {
return Ok(Some(index as usize));
}
}
Ok(None)
} else {
let indices = lexsort_to_indices(&sort_columns, Some(1))?;
Ok((!indices.is_empty()).then_some(indices.value(0) as _))
}
}
}
impl Accumulator for FirstValueAccumulator {
fn state(&mut self) -> Result<Vec<ScalarValue>> {
let mut result = vec![self.first.clone()];
result.extend(self.orderings.iter().cloned());
result.push(ScalarValue::Boolean(Some(self.is_set)));
Ok(result)
}
fn update_batch(&mut self, values: &[ArrayRef]) -> Result<()> {
if !self.is_set {
if let Some(first_idx) = self.get_first_idx(values)? {
let row = get_row_at_idx(values, first_idx)?;
self.update_with_new_row(&row);
}
} else if !self.requirement_satisfied {
if let Some(first_idx) = self.get_first_idx(values)? {
let row = get_row_at_idx(values, first_idx)?;
let orderings = &row[1..];
if compare_rows(
&self.orderings,
orderings,
&get_sort_options(self.ordering_req.as_ref()),
)?
.is_gt()
{
self.update_with_new_row(&row);
}
}
}
Ok(())
}
fn merge_batch(&mut self, states: &[ArrayRef]) -> Result<()> {
let is_set_idx = states.len() - 1;
let flags = states[is_set_idx].as_boolean();
let filtered_states = filter_states_according_to_is_set(states, flags)?;
let sort_cols = convert_to_sort_cols(
&filtered_states[1..is_set_idx],
self.ordering_req.as_ref(),
);
let ordered_states = if sort_cols.is_empty() {
filtered_states
} else {
let indices = lexsort_to_indices(&sort_cols, None)?;
take_arrays(&filtered_states, &indices, None)?
};
if !ordered_states[0].is_empty() {
let first_row = get_row_at_idx(&ordered_states, 0)?;
let first_ordering = &first_row[1..is_set_idx];
let sort_options = get_sort_options(self.ordering_req.as_ref());
if !self.is_set
|| compare_rows(&self.orderings, first_ordering, &sort_options)?.is_gt()
{
self.update_with_new_row(&first_row[0..is_set_idx]);
}
}
Ok(())
}
fn evaluate(&mut self) -> Result<ScalarValue> {
Ok(self.first.clone())
}
fn size(&self) -> usize {
size_of_val(self) - size_of_val(&self.first)
+ self.first.size()
+ ScalarValue::size_of_vec(&self.orderings)
- size_of_val(&self.orderings)
}
}
make_udaf_expr_and_func!(
LastValue,
last_value,
"Returns the last value in a group of values.",
last_value_udaf
);
pub struct LastValue {
signature: Signature,
requirement_satisfied: bool,
}
impl Debug for LastValue {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.debug_struct("LastValue")
.field("name", &self.name())
.field("signature", &self.signature)
.field("accumulator", &"<FUNC>")
.finish()
}
}
impl Default for LastValue {
fn default() -> Self {
Self::new()
}
}
impl LastValue {
pub fn new() -> Self {
Self {
signature: Signature::one_of(
vec![
TypeSignature::ArraySignature(ArrayFunctionSignature::Array),
TypeSignature::Numeric(1),
TypeSignature::Uniform(1, vec![DataType::Utf8]),
],
Volatility::Immutable,
),
requirement_satisfied: false,
}
}
fn with_requirement_satisfied(mut self, requirement_satisfied: bool) -> Self {
self.requirement_satisfied = requirement_satisfied;
self
}
}
impl AggregateUDFImpl for LastValue {
fn as_any(&self) -> &dyn Any {
self
}
fn name(&self) -> &str {
"last_value"
}
fn signature(&self) -> &Signature {
&self.signature
}
fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
Ok(arg_types[0].clone())
}
fn accumulator(&self, acc_args: AccumulatorArgs) -> Result<Box<dyn Accumulator>> {
let ordering_dtypes = acc_args
.ordering_req
.iter()
.map(|e| e.expr.data_type(acc_args.schema))
.collect::<Result<Vec<_>>>()?;
let requirement_satisfied =
acc_args.ordering_req.is_empty() || self.requirement_satisfied;
LastValueAccumulator::try_new(
acc_args.return_type,
&ordering_dtypes,
LexOrdering::from_ref(acc_args.ordering_req),
acc_args.ignore_nulls,
)
.map(|acc| Box::new(acc.with_requirement_satisfied(requirement_satisfied)) as _)
}
fn state_fields(&self, args: StateFieldsArgs) -> Result<Vec<Field>> {
let StateFieldsArgs {
name,
input_types,
return_type: _,
ordering_fields,
is_distinct: _,
} = args;
let mut fields = vec![Field::new(
format_state_name(name, "last_value"),
input_types[0].clone(),
true,
)];
fields.extend(ordering_fields.to_vec());
fields.push(Field::new("is_set", DataType::Boolean, true));
Ok(fields)
}
fn aliases(&self) -> &[String] {
&[]
}
fn with_beneficial_ordering(
self: Arc<Self>,
beneficial_ordering: bool,
) -> Result<Option<Arc<dyn AggregateUDFImpl>>> {
Ok(Some(Arc::new(
LastValue::new().with_requirement_satisfied(beneficial_ordering),
)))
}
fn order_sensitivity(&self) -> AggregateOrderSensitivity {
AggregateOrderSensitivity::Beneficial
}
fn reverse_expr(&self) -> datafusion_expr::ReversedUDAF {
datafusion_expr::ReversedUDAF::Reversed(first_value_udaf())
}
fn documentation(&self) -> Option<&Documentation> {
Some(get_last_value_doc())
}
}
fn get_last_value_doc() -> &'static Documentation {
DOCUMENTATION.get_or_init(|| {
Documentation::builder()
.with_doc_section(DOC_SECTION_GENERAL)
.with_description(
"Returns the last element in an aggregation group according to the requested ordering. If no ordering is given, returns an arbitrary element from the group.",
)
.with_syntax_example("last_value(expression [ORDER BY expression])")
.with_sql_example(r#"```sql
> SELECT last_value(column_name ORDER BY other_column) FROM table_name;
+-----------------------------------------------+
| last_value(column_name ORDER BY other_column) |
+-----------------------------------------------+
| last_element |
+-----------------------------------------------+
```"#,
)
.with_standard_argument("expression", None)
.build()
.unwrap()
})
}
#[derive(Debug)]
struct LastValueAccumulator {
last: ScalarValue,
is_set: bool,
orderings: Vec<ScalarValue>,
ordering_req: LexOrdering,
requirement_satisfied: bool,
ignore_nulls: bool,
}
impl LastValueAccumulator {
pub fn try_new(
data_type: &DataType,
ordering_dtypes: &[DataType],
ordering_req: LexOrdering,
ignore_nulls: bool,
) -> Result<Self> {
let orderings = ordering_dtypes
.iter()
.map(ScalarValue::try_from)
.collect::<Result<Vec<_>>>()?;
let requirement_satisfied = ordering_req.is_empty();
ScalarValue::try_from(data_type).map(|last| Self {
last,
is_set: false,
orderings,
ordering_req,
requirement_satisfied,
ignore_nulls,
})
}
fn update_with_new_row(&mut self, row: &[ScalarValue]) {
self.last = row[0].clone();
self.orderings = row[1..].to_vec();
self.is_set = true;
}
fn get_last_idx(&self, values: &[ArrayRef]) -> Result<Option<usize>> {
let [value, ordering_values @ ..] = values else {
return internal_err!("Empty row in LAST_VALUE");
};
if self.requirement_satisfied {
if self.ignore_nulls {
for i in (0..value.len()).rev() {
if !value.is_null(i) {
return Ok(Some(i));
}
}
return Ok(None);
} else {
return Ok((!value.is_empty()).then_some(value.len() - 1));
}
}
let sort_columns = ordering_values
.iter()
.zip(self.ordering_req.iter())
.map(|(values, req)| {
SortColumn {
values: Arc::clone(values),
options: Some(!req.options),
}
})
.collect::<Vec<_>>();
if self.ignore_nulls {
let indices = lexsort_to_indices(&sort_columns, None)?;
for index in indices.iter().flatten() {
if !value.is_null(index as usize) {
return Ok(Some(index as usize));
}
}
Ok(None)
} else {
let indices = lexsort_to_indices(&sort_columns, Some(1))?;
Ok((!indices.is_empty()).then_some(indices.value(0) as _))
}
}
fn with_requirement_satisfied(mut self, requirement_satisfied: bool) -> Self {
self.requirement_satisfied = requirement_satisfied;
self
}
}
impl Accumulator for LastValueAccumulator {
fn state(&mut self) -> Result<Vec<ScalarValue>> {
let mut result = vec![self.last.clone()];
result.extend(self.orderings.clone());
result.push(ScalarValue::Boolean(Some(self.is_set)));
Ok(result)
}
fn update_batch(&mut self, values: &[ArrayRef]) -> Result<()> {
if !self.is_set || self.requirement_satisfied {
if let Some(last_idx) = self.get_last_idx(values)? {
let row = get_row_at_idx(values, last_idx)?;
self.update_with_new_row(&row);
}
} else if let Some(last_idx) = self.get_last_idx(values)? {
let row = get_row_at_idx(values, last_idx)?;
let orderings = &row[1..];
if compare_rows(
&self.orderings,
orderings,
&get_sort_options(self.ordering_req.as_ref()),
)?
.is_lt()
{
self.update_with_new_row(&row);
}
}
Ok(())
}
fn merge_batch(&mut self, states: &[ArrayRef]) -> Result<()> {
let is_set_idx = states.len() - 1;
let flags = states[is_set_idx].as_boolean();
let filtered_states = filter_states_according_to_is_set(states, flags)?;
let sort_cols = convert_to_sort_cols(
&filtered_states[1..is_set_idx],
self.ordering_req.as_ref(),
);
let ordered_states = if sort_cols.is_empty() {
filtered_states
} else {
let indices = lexsort_to_indices(&sort_cols, None)?;
take_arrays(&filtered_states, &indices, None)?
};
if !ordered_states[0].is_empty() {
let last_idx = ordered_states[0].len() - 1;
let last_row = get_row_at_idx(&ordered_states, last_idx)?;
let last_ordering = &last_row[1..is_set_idx];
let sort_options = get_sort_options(self.ordering_req.as_ref());
if !self.is_set
|| compare_rows(&self.orderings, last_ordering, &sort_options)?.is_lt()
{
self.update_with_new_row(&last_row[0..is_set_idx]);
}
}
Ok(())
}
fn evaluate(&mut self) -> Result<ScalarValue> {
Ok(self.last.clone())
}
fn size(&self) -> usize {
size_of_val(self) - size_of_val(&self.last)
+ self.last.size()
+ ScalarValue::size_of_vec(&self.orderings)
- size_of_val(&self.orderings)
}
}
fn filter_states_according_to_is_set(
states: &[ArrayRef],
flags: &BooleanArray,
) -> Result<Vec<ArrayRef>> {
states
.iter()
.map(|state| compute::filter(state, flags).map_err(|e| arrow_datafusion_err!(e)))
.collect::<Result<Vec<_>>>()
}
fn convert_to_sort_cols(
arrs: &[ArrayRef],
sort_exprs: LexOrderingRef,
) -> Vec<SortColumn> {
arrs.iter()
.zip(sort_exprs.iter())
.map(|(item, sort_expr)| SortColumn {
values: Arc::clone(item),
options: Some(sort_expr.options),
})
.collect::<Vec<_>>()
}
#[cfg(test)]
mod tests {
use arrow::array::Int64Array;
use super::*;
#[test]
fn test_first_last_value_value() -> Result<()> {
let mut first_accumulator = FirstValueAccumulator::try_new(
&DataType::Int64,
&[],
LexOrdering::default(),
false,
)?;
let mut last_accumulator = LastValueAccumulator::try_new(
&DataType::Int64,
&[],
LexOrdering::default(),
false,
)?;
let ranges: Vec<(i64, i64)> = vec![(0, 10), (1, 11), (2, 13)];
let arrs = ranges
.into_iter()
.map(|(start, end)| {
Arc::new(Int64Array::from((start..end).collect::<Vec<_>>())) as ArrayRef
})
.collect::<Vec<_>>();
for arr in arrs {
first_accumulator.update_batch(&[Arc::clone(&arr)])?;
last_accumulator.update_batch(&[arr])?;
}
assert_eq!(first_accumulator.evaluate()?, ScalarValue::Int64(Some(0)));
assert_eq!(last_accumulator.evaluate()?, ScalarValue::Int64(Some(12)));
Ok(())
}
#[test]
fn test_first_last_state_after_merge() -> Result<()> {
let ranges: Vec<(i64, i64)> = vec![(0, 10), (1, 11), (2, 13)];
let arrs = ranges
.into_iter()
.map(|(start, end)| {
Arc::new((start..end).collect::<Int64Array>()) as ArrayRef
})
.collect::<Vec<_>>();
let mut first_accumulator = FirstValueAccumulator::try_new(
&DataType::Int64,
&[],
LexOrdering::default(),
false,
)?;
first_accumulator.update_batch(&[Arc::clone(&arrs[0])])?;
let state1 = first_accumulator.state()?;
let mut first_accumulator = FirstValueAccumulator::try_new(
&DataType::Int64,
&[],
LexOrdering::default(),
false,
)?;
first_accumulator.update_batch(&[Arc::clone(&arrs[1])])?;
let state2 = first_accumulator.state()?;
assert_eq!(state1.len(), state2.len());
let mut states = vec![];
for idx in 0..state1.len() {
states.push(compute::concat(&[
&state1[idx].to_array()?,
&state2[idx].to_array()?,
])?);
}
let mut first_accumulator = FirstValueAccumulator::try_new(
&DataType::Int64,
&[],
LexOrdering::default(),
false,
)?;
first_accumulator.merge_batch(&states)?;
let merged_state = first_accumulator.state()?;
assert_eq!(merged_state.len(), state1.len());
let mut last_accumulator = LastValueAccumulator::try_new(
&DataType::Int64,
&[],
LexOrdering::default(),
false,
)?;
last_accumulator.update_batch(&[Arc::clone(&arrs[0])])?;
let state1 = last_accumulator.state()?;
let mut last_accumulator = LastValueAccumulator::try_new(
&DataType::Int64,
&[],
LexOrdering::default(),
false,
)?;
last_accumulator.update_batch(&[Arc::clone(&arrs[1])])?;
let state2 = last_accumulator.state()?;
assert_eq!(state1.len(), state2.len());
let mut states = vec![];
for idx in 0..state1.len() {
states.push(compute::concat(&[
&state1[idx].to_array()?,
&state2[idx].to_array()?,
])?);
}
let mut last_accumulator = LastValueAccumulator::try_new(
&DataType::Int64,
&[],
LexOrdering::default(),
false,
)?;
last_accumulator.merge_batch(&states)?;
let merged_state = last_accumulator.state()?;
assert_eq!(merged_state.len(), state1.len());
Ok(())
}
}