use crate::logical_plan::producer::SubstraitProducer;
use crate::logical_plan::producer::to_substrait_type_from_field;
use crate::logical_plan::producer::utils::substrait_sort_field;
use datafusion::common::{DFSchemaRef, ScalarValue, not_impl_err};
use datafusion::logical_expr::expr::{WindowFunction, WindowFunctionParams};
use datafusion::logical_expr::{Expr, ExprSchemable};
use datafusion::logical_expr::{WindowFrame, WindowFrameBound, WindowFrameUnits};
use substrait::proto::aggregate_function::AggregationInvocation;
use substrait::proto::expression::RexType;
use substrait::proto::expression::WindowFunction as SubstraitWindowFunction;
use substrait::proto::expression::window_function::bound as SubstraitBound;
use substrait::proto::expression::window_function::bound::Kind as BoundKind;
use substrait::proto::expression::window_function::{Bound, BoundsType};
use substrait::proto::function_argument::ArgType;
use substrait::proto::{Expression, FunctionArgument};
pub fn from_window_function(
producer: &mut impl SubstraitProducer,
window_fn: &WindowFunction,
schema: &DFSchemaRef,
) -> datafusion::common::Result<Expression> {
let WindowFunction {
fun,
params:
WindowFunctionParams {
args,
partition_by,
order_by,
window_frame,
null_treatment,
distinct,
filter,
},
} = window_fn;
if let Some(null_treatment) = null_treatment {
return not_impl_err!(
"Window functions with {null_treatment} are not supported in Substrait"
);
}
if filter.is_some() {
return not_impl_err!(
"Window functions with FILTER are not supported in Substrait"
);
}
let function_anchor = producer.register_function(fun.to_string());
let mut arguments: Vec<FunctionArgument> = Vec::with_capacity(args.len());
for arg in args {
arguments.push(FunctionArgument {
arg_type: Some(ArgType::Value(producer.handle_expr(arg, schema)?)),
});
}
let partition_by = partition_by
.iter()
.map(|e| producer.handle_expr(e, schema))
.collect::<datafusion::common::Result<Vec<_>>>()?;
let order_by = order_by
.iter()
.map(|e| substrait_sort_field(producer, e, schema))
.collect::<datafusion::common::Result<Vec<_>>>()?;
let bounds = to_substrait_bounds(window_frame)?;
let bound_type = to_substrait_bound_type(window_frame)?;
let (_, output_field) =
Expr::WindowFunction(Box::new(window_fn.clone())).to_field(schema)?;
let output_type = to_substrait_type_from_field(producer, &output_field)?;
#[expect(deprecated)]
Ok(Expression {
rex_type: Some(RexType::WindowFunction(SubstraitWindowFunction {
function_reference: function_anchor,
arguments,
partitions: partition_by,
sorts: order_by,
options: vec![],
output_type: Some(output_type),
phase: 0, invocation: if *distinct {
AggregationInvocation::Distinct as i32
} else {
AggregationInvocation::All as i32
},
lower_bound: Some(bounds.0),
upper_bound: Some(bounds.1),
args: vec![],
bounds_type: bound_type as i32,
})),
})
}
fn to_substrait_bound_type(
window_frame: &WindowFrame,
) -> datafusion::common::Result<BoundsType> {
match window_frame.units {
WindowFrameUnits::Rows => Ok(BoundsType::Rows), WindowFrameUnits::Range => Ok(BoundsType::Range), unit => not_impl_err!("Unsupported window frame unit: {unit:?}"),
}
}
fn to_substrait_bounds(
window_frame: &WindowFrame,
) -> datafusion::common::Result<(Bound, Bound)> {
Ok((
to_substrait_bound(&window_frame.start_bound)?,
to_substrait_bound(&window_frame.end_bound)?,
))
}
fn to_substrait_bound(bound: &WindowFrameBound) -> datafusion::common::Result<Bound> {
if bound.is_unbounded() {
return Ok(Bound {
kind: Some(BoundKind::Unbounded(SubstraitBound::Unbounded {})),
});
}
match bound {
WindowFrameBound::CurrentRow => Ok(Bound {
kind: Some(BoundKind::CurrentRow(SubstraitBound::CurrentRow {})),
}),
WindowFrameBound::Preceding(s) => Ok(Bound {
kind: Some(BoundKind::Preceding(SubstraitBound::Preceding {
offset: to_substrait_bound_offset(s)?,
})),
}),
WindowFrameBound::Following(s) => Ok(Bound {
kind: Some(BoundKind::Following(SubstraitBound::Following {
offset: to_substrait_bound_offset(s)?,
})),
}),
}
}
fn to_substrait_bound_offset(value: &ScalarValue) -> datafusion::common::Result<i64> {
match value {
ScalarValue::UInt8(Some(v)) => Ok((*v).into()),
ScalarValue::UInt16(Some(v)) => Ok((*v).into()),
ScalarValue::UInt32(Some(v)) => Ok((*v).into()),
ScalarValue::UInt64(Some(v)) => match i64::try_from(*v) {
Ok(v) => Ok(v),
Err(_) => not_impl_err!("Unsupported Substrait window frame offset: {value}"),
},
ScalarValue::Int8(Some(v)) => Ok((*v).into()),
ScalarValue::Int16(Some(v)) => Ok((*v).into()),
ScalarValue::Int32(Some(v)) => Ok((*v).into()),
ScalarValue::Int64(Some(v)) => Ok(*v),
_ => not_impl_err!("Unsupported Substrait window frame offset: {value}"),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::logical_plan::producer::{DefaultSubstraitProducer, to_substrait_type};
use datafusion::arrow::datatypes::{DataType, Field, Schema};
use datafusion::common::{DFSchema, assert_contains};
use datafusion::execution::SessionStateBuilder;
use datafusion::functions_aggregate::count::count_all_window;
use datafusion::functions_aggregate::sum::sum_udaf;
use datafusion::logical_expr::expr::WindowFunction;
use datafusion::prelude::col;
use substrait::proto::expression::RexType;
#[test]
fn window_function_output_type() -> datafusion::common::Result<()> {
let state = SessionStateBuilder::default().build();
let schema =
DFSchemaRef::new(DFSchema::try_from(Schema::new(vec![Field::new(
"i",
DataType::Int64,
true,
)]))?);
let mut producer = DefaultSubstraitProducer::new(&state);
let window_fn = WindowFunction::new(sum_udaf(), vec![col("i")]);
let expr = Expr::WindowFunction(Box::new(window_fn));
let substrait_expr = producer.handle_expr(&expr, &schema)?;
let Some(RexType::WindowFunction(window)) = substrait_expr.rex_type else {
panic!("Substrait WindowFunction expected")
};
let expected = to_substrait_type(&mut producer, &DataType::Int64, true)?;
assert_eq!(window.output_type, Some(expected));
Ok(())
}
#[test]
fn count_window_function_output_type_is_non_nullable()
-> datafusion::common::Result<()> {
let state = SessionStateBuilder::default().build();
let schema =
DFSchemaRef::new(DFSchema::try_from(Schema::new(vec![Field::new(
"i",
DataType::Int64,
true,
)]))?);
let mut producer = DefaultSubstraitProducer::new(&state);
let substrait_expr = producer.handle_expr(&count_all_window(), &schema)?;
let Some(RexType::WindowFunction(window)) = substrait_expr.rex_type else {
panic!("Substrait WindowFunction expected")
};
let expected = to_substrait_type(&mut producer, &DataType::Int64, false)?;
assert_eq!(window.output_type, Some(expected));
Ok(())
}
#[test]
fn window_frame_offsets() {
for value in [
ScalarValue::UInt8(Some(1)),
ScalarValue::UInt16(Some(1)),
ScalarValue::UInt32(Some(1)),
ScalarValue::UInt64(Some(1)),
ScalarValue::Int8(Some(1)),
ScalarValue::Int16(Some(1)),
ScalarValue::Int32(Some(1)),
ScalarValue::Int64(Some(1)),
] {
let frame = WindowFrame::new_bounds(
WindowFrameUnits::Rows,
WindowFrameBound::CurrentRow,
WindowFrameBound::Following(value),
);
let (_, bound) = to_substrait_bounds(&frame).unwrap();
assert_eq!(
bound.kind,
Some(BoundKind::Following(SubstraitBound::Following {
offset: 1
}))
);
}
let frame = WindowFrame::new_bounds(
WindowFrameUnits::Rows,
WindowFrameBound::CurrentRow,
WindowFrameBound::Following(ScalarValue::UInt64(Some(u64::MAX))),
);
let err = to_substrait_bounds(&frame).unwrap_err();
assert_contains!(err.to_string(), "Unsupported Substrait window frame offset");
}
}