Apache DataFusion SQL Query Engine
feat: Support `FILTER` clause in aggregate window functions (#17378)
Geoffrey Claude3f422a1746a2
diff --git a/datafusion-examples/examples/advanced_udwf.rs b/datafusion-examples/examples/advanced_udwf.rsindex 5e7275af7d..50860535b7 100644--- a/datafusion-examples/examples/advanced_udwf.rs+++ b/datafusion-examples/examples/advanced_udwf.rs@@ -200,6 +200,7 @@ impl WindowUDFImpl for SimplifySmoothItUdf {window_frame: window_function.params.window_frame,null_treatment: window_function.params.null_treatment,distinct: window_function.params.distinct,+ filter: window_function.params.filter,},}))};diff --git a/datafusion/common/src/tree_node.rs b/datafusion/common/src/tree_node.rsindex 7af20faca2..ea0aa28c93 100644--- a/datafusion/common/src/tree_node.rs+++ b/datafusion/common/src/tree_node.rs@@ -990,6 +990,48 @@ impl<}}+impl<+ 'a,+ T: 'a,+ C0: TreeNodeContainer<'a, T>,+ C1: TreeNodeContainer<'a, T>,+ C2: TreeNodeContainer<'a, T>,+ C3: TreeNodeContainer<'a, T>,+ > TreeNodeContainer<'a, T> for (C0, C1, C2, C3)+{+ fn apply_elements<F: FnMut(&'a T) -> Result<TreeNodeRecursion>>(+ &'a self,+ mut f: F,+ ) -> Result<TreeNodeRecursion> {+ self.0+ .apply_elements(&mut f)?+ .visit_sibling(|| self.1.apply_elements(&mut f))?+ .visit_sibling(|| self.2.apply_elements(&mut f))?+ .visit_sibling(|| self.3.apply_elements(&mut f))+ }++ fn map_elements<F: FnMut(T) -> Result<Transformed<T>>>(+ self,+ mut f: F,+ ) -> Result<Transformed<Self>> {+ self.0+ .map_elements(&mut f)?+ .map_data(|new_c0| Ok((new_c0, self.1, self.2, self.3)))?+ .transform_sibling(|(new_c0, c1, c2, c3)| {+ c1.map_elements(&mut f)?+ .map_data(|new_c1| Ok((new_c0, new_c1, c2, c3)))+ })?+ .transform_sibling(|(new_c0, new_c1, c2, c3)| {+ c2.map_elements(&mut f)?+ .map_data(|new_c2| Ok((new_c0, new_c1, new_c2, c3)))+ })?+ .transform_sibling(|(new_c0, new_c1, new_c2, c3)| {+ c3.map_elements(&mut f)?+ .map_data(|new_c3| Ok((new_c0, new_c1, new_c2, new_c3)))+ })+ }+}+/// [`TreeNodeRefContainer`] contains references to elements that a function can be/// applied on. The elements of the container are siblings so the continuation rules are/// similar to [`TreeNodeRecursion::visit_sibling`].@@ -1065,6 +1107,27 @@ impl<}}+impl<+ 'a,+ T: 'a,+ C0: TreeNodeContainer<'a, T>,+ C1: TreeNodeContainer<'a, T>,+ C2: TreeNodeContainer<'a, T>,+ C3: TreeNodeContainer<'a, T>,+ > TreeNodeRefContainer<'a, T> for (&'a C0, &'a C1, &'a C2, &'a C3)+{+ fn apply_ref_elements<F: FnMut(&'a T) -> Result<TreeNodeRecursion>>(+ &self,+ mut f: F,+ ) -> Result<TreeNodeRecursion> {+ self.0+ .apply_elements(&mut f)?+ .visit_sibling(|| self.1.apply_elements(&mut f))?+ .visit_sibling(|| self.2.apply_elements(&mut f))?+ .visit_sibling(|| self.3.apply_elements(&mut f))+ }+}+/// Transformation helper to process a sequence of iterable tree nodes that are siblings.pub trait TreeNodeIterator: Iterator {/// Apples `f` to each item in this iteratordiff --git a/datafusion/core/src/physical_planner.rs b/datafusion/core/src/physical_planner.rsindex 413b809c4e..6618d9495d 100644--- a/datafusion/core/src/physical_planner.rs+++ b/datafusion/core/src/physical_planner.rs@@ -1650,6 +1650,7 @@ pub fn create_window_expr_with_name(window_frame,null_treatment,distinct,+ filter,},} = window_fun.as_ref();let physical_args =@@ -1669,6 +1670,11 @@ pub fn create_window_expr_with_name(let window_frame = Arc::new(window_frame.clone());let ignore_nulls = null_treatment.unwrap_or(NullTreatment::RespectNulls)== NullTreatment::IgnoreNulls;+ let physical_filter = filter+ .as_ref()+ .map(|f| create_physical_expr(f, logical_schema, execution_props))+ .transpose()?;+windows::create_window_expr(fun,name,@@ -1679,6 +1685,7 @@ pub fn create_window_expr_with_name(physical_schema,ignore_nulls,*distinct,+ physical_filter,)}other => plan_err!("Invalid window expression '{other:?}'"),diff --git a/datafusion/core/tests/dataframe/mod.rs b/datafusion/core/tests/dataframe/mod.rsindex 27afbd7246..a563459f42 100644--- a/datafusion/core/tests/dataframe/mod.rs+++ b/datafusion/core/tests/dataframe/mod.rs@@ -959,6 +959,83 @@ async fn window_using_aggregates() -> Result<()> {Ok(())}+#[tokio::test]+async fn window_aggregates_with_filter() -> Result<()> {+ // Define a small in-memory table to make expected values clear+ let ts: Int32Array = [1, 2, 3, 4, 5].into_iter().collect();+ let val: Int32Array = [-3, -2, 1, 4, -1].into_iter().collect();+ let batch = RecordBatch::try_from_iter(vec![+ ("ts", Arc::new(ts) as _),+ ("val", Arc::new(val) as _),+ ])?;++ let ctx = SessionContext::new();+ ctx.register_batch("t", batch)?;++ let df = ctx.table("t").await?;++ // Build filtered window aggregates over ORDER BY ts ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW+ let mut exprs = vec![+ (datafusion_functions_aggregate::sum::sum_udaf(), "sum_pos"),+ (+ datafusion_functions_aggregate::average::avg_udaf(),+ "avg_pos",+ ),+ (+ datafusion_functions_aggregate::min_max::min_udaf(),+ "min_pos",+ ),+ (+ datafusion_functions_aggregate::min_max::max_udaf(),+ "max_pos",+ ),+ (+ datafusion_functions_aggregate::count::count_udaf(),+ "cnt_pos",+ ),+ ]+ .into_iter()+ .map(|(func, alias)| {+ let w = WindowFunction::new(+ WindowFunctionDefinition::AggregateUDF(func),+ vec![col("val")],+ );++ Expr::from(w)+ .order_by(vec![col("ts").sort(true, true)])+ .window_frame(WindowFrame::new_bounds(+ WindowFrameUnits::Rows,+ WindowFrameBound::Preceding(ScalarValue::UInt64(None)),+ WindowFrameBound::CurrentRow,+ ))+ .filter(col("val").gt(lit(0)))+ .build()+ .unwrap()+ .alias(alias)+ })+ .collect::<Vec<_>>();+ exprs.extend_from_slice(&[col("ts"), col("val")]);++ let results = df.select(exprs)?.collect().await?;++ assert_snapshot!(+ batches_to_string(&results),+ @r###"+ +---------+---------+---------+---------+---------+----+-----++ | sum_pos | avg_pos | min_pos | max_pos | cnt_pos | ts | val |+ +---------+---------+---------+---------+---------+----+-----++ | | | | | 0 | 1 | -3 |+ | | | | | 0 | 2 | -2 |+ | 1 | 1.0 | 1 | 1 | 1 | 3 | 1 |+ | 5 | 2.5 | 1 | 4 | 2 | 4 | 4 |+ | 5 | 2.5 | 1 | 4 | 2 | 5 | -1 |+ +---------+---------+---------+---------+---------+----+-----++ "###+ );++ Ok(())+}+// Test issue: https://github.com/apache/datafusion/issues/10346#[tokio::test]async fn test_select_over_aggregate_schema() -> Result<()> {diff --git a/datafusion/core/tests/fuzz_cases/window_fuzz.rs b/datafusion/core/tests/fuzz_cases/window_fuzz.rsindex 23e3281cf3..a816afe3c3 100644--- a/datafusion/core/tests/fuzz_cases/window_fuzz.rs+++ b/datafusion/core/tests/fuzz_cases/window_fuzz.rs@@ -289,6 +289,7 @@ async fn bounded_window_causal_non_causal() -> Result<()> {&extended_schema,false,false,+ None,)?;let running_window_exec = Arc::new(BoundedWindowAggExec::try_new(vec![window_expr],@@ -662,6 +663,7 @@ async fn run_window_test(&extended_schema,false,false,+ None,)?],exec1,false,@@ -681,6 +683,7 @@ async fn run_window_test(&extended_schema,false,false,+ None,)?],exec2,search_mode.clone(),diff --git a/datafusion/core/tests/physical_optimizer/enforce_sorting.rs b/datafusion/core/tests/physical_optimizer/enforce_sorting.rsindex d10459ce86..a19dd7ace9 100644--- a/datafusion/core/tests/physical_optimizer/enforce_sorting.rs+++ b/datafusion/core/tests/physical_optimizer/enforce_sorting.rs@@ -3686,6 +3686,7 @@ async fn test_window_partial_constant_and_set_monotonicity() -> Result<()> {input_schema.as_ref(),false,false,+ None,)?;let window_exec = if window_expr.uses_bounded_memory() {Arc::new(BoundedWindowAggExec::try_new(diff --git a/datafusion/core/tests/physical_optimizer/test_utils.rs b/datafusion/core/tests/physical_optimizer/test_utils.rsindex 6ed886af7b..69dbe04927 100644--- a/datafusion/core/tests/physical_optimizer/test_utils.rs+++ b/datafusion/core/tests/physical_optimizer/test_utils.rs@@ -266,6 +266,7 @@ pub fn bounded_window_exec_with_partition(schema.as_ref(),false,false,+ None,).unwrap();diff --git a/datafusion/core/tests/physical_optimizer/window_optimize.rs b/datafusion/core/tests/physical_optimizer/window_optimize.rsindex d16b516d5c..fc1e6444d7 100644--- a/datafusion/core/tests/physical_optimizer/window_optimize.rs+++ b/datafusion/core/tests/physical_optimizer/window_optimize.rs@@ -49,6 +49,7 @@ mod test {&partition,&[],Arc::new(frame),+ None,);let bounded_agg_exec = BoundedWindowAggExec::try_new(diff --git a/datafusion/expr/src/expr.rs b/datafusion/expr/src/expr.rsindex 0eef8a00a9..f2493abbde 100644--- a/datafusion/expr/src/expr.rs+++ b/datafusion/expr/src/expr.rs@@ -1230,6 +1230,8 @@ pub struct WindowFunctionParams {pub order_by: Vec<Sort>,/// Window framepub window_frame: WindowFrame,+ /// Optional filter expression (FILTER (WHERE ...))+ pub filter: Option<Box<Expr>>,/// Specifies how NULL value is treated: ignore or respectpub null_treatment: Option<NullTreatment>,/// Distinct flag@@ -1247,6 +1249,7 @@ impl WindowFunction {partition_by: Vec::default(),order_by: Vec::default(),window_frame: WindowFrame::new(None),+ filter: None,null_treatment: None,distinct: false,},@@ -2388,6 +2391,7 @@ impl NormalizeEq for Expr {window_frame: self_window_frame,partition_by: self_partition_by,order_by: self_order_by,+ filter: self_filter,null_treatment: self_null_treatment,distinct: self_distinct,},@@ -2400,6 +2404,7 @@ impl NormalizeEq for Expr {window_frame: other_window_frame,partition_by: other_partition_by,order_by: other_order_by,+ filter: other_filter,null_treatment: other_null_treatment,distinct: other_distinct,},@@ -2407,6 +2412,11 @@ impl NormalizeEq for Expr {self_fun.name() == other_fun.name()&& self_window_frame == other_window_frame+ && match (self_filter, other_filter) {+ (Some(a), Some(b)) => a.normalize_eq(b),+ (None, None) => true,+ _ => false,+ }&& self_null_treatment == other_null_treatment&& self_args.len() == other_args.len()&& self_args@@ -2658,12 +2668,14 @@ impl HashNode for Expr {partition_by: _,order_by: _,window_frame,+ filter,null_treatment,distinct,},} = window_fun.as_ref();fun.hash(state);window_frame.hash(state);+ filter.hash(state);null_treatment.hash(state);distinct.hash(state);}@@ -2967,6 +2979,7 @@ impl Display for SchemaDisplay<'_> {partition_by,order_by,window_frame,+ filter,null_treatment,distinct,} = params;@@ -2993,6 +3006,10 @@ impl Display for SchemaDisplay<'_> {write!(f, " {null_treatment}")?;}+ if let Some(filter) = filter {+ write!(f, " FILTER (WHERE {filter})")?;+ }+if !partition_by.is_empty() {write!(f,@@ -3370,6 +3387,7 @@ impl Display for Expr {partition_by,order_by,window_frame,+ filter,null_treatment,distinct,} = params;@@ -3380,6 +3398,10 @@ impl Display for Expr {write!(f, "{nt}")?;}+ if let Some(fe) = filter {+ write!(f, " FILTER (WHERE {fe})")?;+ }+if !partition_by.is_empty() {write!(f, " PARTITION BY [{}]", expr_vec_fmt!(partition_by))?;}diff --git a/datafusion/expr/src/expr_fn.rs b/datafusion/expr/src/expr_fn.rsindex 48a16ab595..63b4333f21 100644--- a/datafusion/expr/src/expr_fn.rs+++ b/datafusion/expr/src/expr_fn.rs@@ -19,7 +19,7 @@use crate::expr::{AggregateFunction, BinaryExpr, Cast, Exists, GroupingSet, InList, InSubquery,- Placeholder, TryCast, Unnest, WildcardOptions, WindowFunction, WindowFunctionParams,+ Placeholder, TryCast, Unnest, WildcardOptions, WindowFunction,};use crate::function::{AccumulatorArgs, AccumulatorFactoryFunction, PartitionEvaluatorFactory,@@ -770,7 +770,7 @@ pub trait ExprFunctionExt {#[derive(Debug, Clone)]pub enum ExprFuncKind {Aggregate(AggregateFunction),- Window(WindowFunction),+ Window(Box<WindowFunction>),}/// Implementation of [`ExprFunctionExt`].@@ -832,23 +832,16 @@ impl ExprFuncBuilder {udaf.params.null_treatment = null_treatment;Expr::AggregateFunction(udaf)}- ExprFuncKind::Window(WindowFunction {- fun,- params: WindowFunctionParams { args, .. },- }) => {+ ExprFuncKind::Window(mut udwf) => {let has_order_by = order_by.as_ref().map(|o| !o.is_empty());- Expr::from(WindowFunction {- fun,- params: WindowFunctionParams {- args,- partition_by: partition_by.unwrap_or_default(),- order_by: order_by.unwrap_or_default(),- window_frame: window_frame- .unwrap_or_else(|| WindowFrame::new(has_order_by)),- null_treatment,- distinct,- },- })+ udwf.params.partition_by = partition_by.unwrap_or_default();+ udwf.params.order_by = order_by.unwrap_or_default();+ udwf.params.window_frame =+ window_frame.unwrap_or_else(|| WindowFrame::new(has_order_by));+ udwf.params.filter = filter.map(Box::new);+ udwf.params.null_treatment = null_treatment;+ udwf.params.distinct = distinct;+ Expr::WindowFunction(udwf)}};@@ -902,7 +895,7 @@ impl ExprFunctionExt for Expr {ExprFuncBuilder::new(Some(ExprFuncKind::Aggregate(udaf)))}Expr::WindowFunction(udwf) => {- ExprFuncBuilder::new(Some(ExprFuncKind::Window(*udwf)))+ ExprFuncBuilder::new(Some(ExprFuncKind::Window(udwf)))}_ => ExprFuncBuilder::new(None),};@@ -942,7 +935,7 @@ impl ExprFunctionExt for Expr {ExprFuncBuilder::new(Some(ExprFuncKind::Aggregate(udaf)))}Expr::WindowFunction(udwf) => {- ExprFuncBuilder::new(Some(ExprFuncKind::Window(*udwf)))+ ExprFuncBuilder::new(Some(ExprFuncKind::Window(udwf)))}_ => ExprFuncBuilder::new(None),};@@ -955,7 +948,7 @@ impl ExprFunctionExt for Expr {fn partition_by(self, partition_by: Vec<Expr>) -> ExprFuncBuilder {match self {Expr::WindowFunction(udwf) => {- let mut builder = ExprFuncBuilder::new(Some(ExprFuncKind::Window(*udwf)));+ let mut builder = ExprFuncBuilder::new(Some(ExprFuncKind::Window(udwf)));builder.partition_by = Some(partition_by);builder}@@ -966,7 +959,7 @@ impl ExprFunctionExt for Expr {fn window_frame(self, window_frame: WindowFrame) -> ExprFuncBuilder {match self {Expr::WindowFunction(udwf) => {- let mut builder = ExprFuncBuilder::new(Some(ExprFuncKind::Window(*udwf)));+ let mut builder = ExprFuncBuilder::new(Some(ExprFuncKind::Window(udwf)));builder.window_frame = Some(window_frame);builder}diff --git a/datafusion/expr/src/logical_plan/plan.rs b/datafusion/expr/src/logical_plan/plan.rsindex a354fb666f..b4f2902cc4 100644--- a/datafusion/expr/src/logical_plan/plan.rs+++ b/datafusion/expr/src/logical_plan/plan.rs@@ -2469,6 +2469,20 @@ impl Window {window_func_dependencies.extend(new_deps);}+ // Validate that FILTER clauses are only used with aggregate window functions+ if let Some(e) = window_expr.iter().find(|e| {+ matches!(+ e,+ Expr::WindowFunction(wf)+ if !matches!(wf.fun, WindowFunctionDefinition::AggregateUDF(_))+ && wf.params.filter.is_some()+ )+ }) {+ return plan_err!(+ "FILTER clause can only be used with aggregate window functions. Found in '{e}'"+ );+ }+Self::try_new_with_schema(window_expr,input,diff --git a/datafusion/expr/src/planner.rs b/datafusion/expr/src/planner.rsindex 24d1993956..669931d7ba 100644--- a/datafusion/expr/src/planner.rs+++ b/datafusion/expr/src/planner.rs@@ -307,6 +307,7 @@ pub struct RawWindowExpr {pub partition_by: Vec<Expr>,pub order_by: Vec<SortExpr>,pub window_frame: WindowFrame,+ pub filter: Option<Box<Expr>>,pub null_treatment: Option<NullTreatment>,pub distinct: bool,}diff --git a/datafusion/expr/src/tree_node.rs b/datafusion/expr/src/tree_node.rsindex b6f583ca4c..81846b4f80 100644--- a/datafusion/expr/src/tree_node.rs+++ b/datafusion/expr/src/tree_node.rs@@ -22,7 +22,7 @@ use crate::expr::{GroupingSet, InList, InSubquery, Like, Placeholder, ScalarFunction, TryCast, Unnest,WindowFunction, WindowFunctionParams,};-use crate::{Expr, ExprFunctionExt};+use crate::Expr;use datafusion_common::tree_node::{Transformed, TreeNode, TreeNodeContainer, TreeNodeRecursion, TreeNodeRefContainer,@@ -97,9 +97,10 @@ impl TreeNode for Expr {args,partition_by,order_by,+ filter,..} = &window_fun.as_ref().params;- (args, partition_by, order_by).apply_ref_elements(f)+ (args, partition_by, order_by, filter).apply_ref_elements(f)}Expr::InList(InList { expr, list, .. }) => {@@ -241,32 +242,30 @@ impl TreeNode for Expr {partition_by,order_by,window_frame,+ filter,null_treatment,distinct,},} = *window_fun;- (args, partition_by, order_by).map_elements(f)?.update_data(- |(new_args, new_partition_by, new_order_by)| {- if distinct {- return Expr::from(WindowFunction::new(fun, new_args))- .partition_by(new_partition_by)- .order_by(new_order_by)- .window_frame(window_frame)- .null_treatment(null_treatment)- .distinct()- .build()- .unwrap();- }- Expr::from(WindowFunction::new(fun, new_args))- .partition_by(new_partition_by)- .order_by(new_order_by)- .window_frame(window_frame)- .null_treatment(null_treatment)- .build()- .unwrap()- },- )+ (args, partition_by, order_by, filter)+ .map_elements(f)?+ .map_data(+ |(new_args, new_partition_by, new_order_by, new_filter)| {+ Ok(Expr::from(WindowFunction {+ fun,+ params: WindowFunctionParams {+ args: new_args,+ partition_by: new_partition_by,+ order_by: new_order_by,+ window_frame,+ filter: new_filter,+ null_treatment,+ distinct,+ },+ }))+ },+ )?}Expr::AggregateFunction(AggregateFunction {func,diff --git a/datafusion/expr/src/udaf.rs b/datafusion/expr/src/udaf.rsindex e1d36da9c4..9619d60a24 100644--- a/datafusion/expr/src/udaf.rs+++ b/datafusion/expr/src/udaf.rs@@ -552,6 +552,7 @@ pub trait AggregateUDFImpl: Debug + DynEq + DynHash + Send + Sync {partition_by,order_by,window_frame,+ filter,null_treatment,distinct,} = params;@@ -577,6 +578,10 @@ pub trait AggregateUDFImpl: Debug + DynEq + DynHash + Send + Sync {schema_name.write_fmt(format_args!(" {null_treatment}"))?;}+ if let Some(filter) = filter {+ schema_name.write_fmt(format_args!(" FILTER (WHERE {filter})"))?;+ }+if !partition_by.is_empty() {schema_name.write_fmt(format_args!(" PARTITION BY [{}]",@@ -657,6 +662,7 @@ pub trait AggregateUDFImpl: Debug + DynEq + DynHash + Send + Sync {partition_by,order_by,window_frame,+ filter,null_treatment,distinct,} = params;@@ -681,6 +687,10 @@ pub trait AggregateUDFImpl: Debug + DynEq + DynHash + Send + Sync {display_name.write_fmt(format_args!(" {null_treatment}"))?;}+ if let Some(fe) = filter {+ display_name.write_fmt(format_args!(" FILTER (WHERE {fe})"))?;+ }+if !partition_by.is_empty() {display_name.write_fmt(format_args!(" PARTITION BY [{}]",diff --git a/datafusion/functions-window/src/planner.rs b/datafusion/functions-window/src/planner.rsindex 5e3a6bc633..84836ad569 100644--- a/datafusion/functions-window/src/planner.rs+++ b/datafusion/functions-window/src/planner.rs@@ -23,7 +23,7 @@ use datafusion_expr::{expr_rewriter::NamePreserver,planner::{ExprPlanner, PlannerResult, RawWindowExpr},utils::COUNT_STAR_EXPANSION,- Expr, ExprFunctionExt,+ Expr,};#[derive(Debug)]@@ -40,6 +40,7 @@ impl ExprPlanner for WindowFunctionPlanner {partition_by,order_by,window_frame,+ filter,null_treatment,distinct,} = raw_expr;@@ -51,6 +52,7 @@ impl ExprPlanner for WindowFunctionPlanner {partition_by,order_by,window_frame,+ filter,null_treatment,distinct,},@@ -71,6 +73,7 @@ impl ExprPlanner for WindowFunctionPlanner {window_frame,null_treatment,distinct,+ filter,},} = *window_fun;let raw_expr = RawWindowExpr {@@ -79,6 +82,7 @@ impl ExprPlanner for WindowFunctionPlanner {partition_by,order_by,window_frame,+ filter,null_treatment,distinct,};@@ -96,24 +100,23 @@ impl ExprPlanner for WindowFunctionPlanner {partition_by,order_by,window_frame,+ filter,null_treatment,distinct,} = raw_expr;- let mut new_expr_before_build = Expr::from(WindowFunction::new(- func_def,- vec![Expr::Literal(COUNT_STAR_EXPANSION, None)],- ))- .partition_by(partition_by)- .order_by(order_by)- .window_frame(window_frame)- .null_treatment(null_treatment);-- if distinct {- new_expr_before_build = new_expr_before_build.distinct();- }-- let new_expr = new_expr_before_build.build()?;+ let new_expr = Expr::from(WindowFunction {+ fun: func_def,+ params: WindowFunctionParams {+ args: vec![Expr::Literal(COUNT_STAR_EXPANSION, None)],+ partition_by,+ order_by,+ window_frame,+ filter,+ null_treatment,+ distinct,+ },+ });let new_expr = saved_name.restore(new_expr);return Ok(PlannerResult::Planned(new_expr));diff --git a/datafusion/optimizer/src/analyzer/type_coercion.rs b/datafusion/optimizer/src/analyzer/type_coercion.rsindex 2d7db740da..e268053781 100644--- a/datafusion/optimizer/src/analyzer/type_coercion.rs+++ b/datafusion/optimizer/src/analyzer/type_coercion.rs@@ -50,9 +50,8 @@ use datafusion_expr::type_coercion::{is_datetime, is_utf8_or_utf8view_or_large_uuse datafusion_expr::utils::merge_schema;use datafusion_expr::{is_false, is_not_false, is_not_true, is_not_unknown, is_true, is_unknown, not,- AggregateUDF, Expr, ExprFunctionExt, ExprSchemable, Join, Limit, LogicalPlan,- Operator, Projection, ScalarUDF, Union, WindowFrame, WindowFrameBound,- WindowFrameUnits,+ AggregateUDF, Expr, ExprSchemable, Join, Limit, LogicalPlan, Operator, Projection,+ ScalarUDF, Union, WindowFrame, WindowFrameBound, WindowFrameUnits,};/// Performs type coercion by determining the schema@@ -548,6 +547,7 @@ impl TreeNodeRewriter for TypeCoercionRewriter<'_> {partition_by,order_by,window_frame,+ filter,null_treatment,distinct,},@@ -566,26 +566,19 @@ impl TreeNodeRewriter for TypeCoercionRewriter<'_> {_ => args,};- if distinct {- Ok(Transformed::yes(- Expr::from(WindowFunction::new(fun, args))- .partition_by(partition_by)- .order_by(order_by)- .window_frame(window_frame)- .null_treatment(null_treatment)- .distinct()- .build()?,- ))- } else {- Ok(Transformed::yes(- Expr::from(WindowFunction::new(fun, args))- .partition_by(partition_by)- .order_by(order_by)- .window_frame(window_frame)- .null_treatment(null_treatment)- .build()?,- ))- }+ let new_expr = Expr::from(WindowFunction {+ fun,+ params: expr::WindowFunctionParams {+ args,+ partition_by,+ order_by,+ window_frame,+ filter,+ null_treatment,+ distinct,+ },+ });+ Ok(Transformed::yes(new_expr))}// TODO: remove the next line after `Expr::Wildcard` is removed#[expect(deprecated)]diff --git a/datafusion/physical-expr/src/window/aggregate.rs b/datafusion/physical-expr/src/window/aggregate.rsindex d7287c27de..7b51300d30 100644--- a/datafusion/physical-expr/src/window/aggregate.rs+++ b/datafusion/physical-expr/src/window/aggregate.rs@@ -23,14 +23,14 @@ use std::sync::Arc;use crate::aggregate::AggregateFunctionExpr;use crate::window::standard::add_new_ordering_expr_with_partition_by;-use crate::window::window_expr::{AggregateWindowExpr, WindowFn};+use crate::window::window_expr::{filter_array, AggregateWindowExpr, WindowFn};use crate::window::{PartitionBatches, PartitionWindowAggStates, SlidingAggregateWindowExpr, WindowExpr,};use crate::{EquivalenceProperties, PhysicalExpr};-use arrow::array::Array;use arrow::array::ArrayRef;+use arrow::array::BooleanArray;use arrow::datatypes::FieldRef;use arrow::record_batch::RecordBatch;use datafusion_common::{DataFusionError, Result, ScalarValue};@@ -47,6 +47,7 @@ pub struct PlainAggregateWindowExpr {order_by: Vec<PhysicalSortExpr>,window_frame: Arc<WindowFrame>,is_constant_in_partition: bool,+ filter: Option<Arc<dyn PhysicalExpr>>,}impl PlainAggregateWindowExpr {@@ -56,6 +57,7 @@ impl PlainAggregateWindowExpr {partition_by: &[Arc<dyn PhysicalExpr>],order_by: &[PhysicalSortExpr],window_frame: Arc<WindowFrame>,+ filter: Option<Arc<dyn PhysicalExpr>>,) -> Self {let is_constant_in_partition =Self::is_window_constant_in_partition(order_by, &window_frame);@@ -65,6 +67,7 @@ impl PlainAggregateWindowExpr {order_by: order_by.to_vec(),window_frame,is_constant_in_partition,+ filter,}}@@ -192,6 +195,7 @@ impl WindowExpr for PlainAggregateWindowExpr {.map(|e| e.reverse()).collect::<Vec<_>>(),Arc::new(self.window_frame.reverse()),+ self.filter.clone(),)) as _} else {Arc::new(SlidingAggregateWindowExpr::new(@@ -203,6 +207,7 @@ impl WindowExpr for PlainAggregateWindowExpr {.map(|e| e.reverse()).collect::<Vec<_>>(),Arc::new(self.window_frame.reverse()),+ self.filter.clone(),)) as _}})@@ -222,6 +227,10 @@ impl AggregateWindowExpr for PlainAggregateWindowExpr {self.aggregate.create_accumulator()}+ fn filter_expr(&self) -> Option<&Arc<dyn PhysicalExpr>> {+ self.filter.as_ref()+ }+/// For a given range, calculate accumulation result inside the range on/// `value_slice` and update accumulator state.// We assume that `cur_range` contains `last_range` and their start points@@ -233,6 +242,7 @@ impl AggregateWindowExpr for PlainAggregateWindowExpr {cur_range: &Range<usize>,value_slice: &[ArrayRef],accumulator: &mut Box<dyn Accumulator>,+ filter_mask: Option<&BooleanArray>,) -> Result<ScalarValue> {if cur_range.start == cur_range.end {self.aggregate@@ -245,10 +255,16 @@ impl AggregateWindowExpr for PlainAggregateWindowExpr {// same point (i.e. the beginning of the table/frame). Hence, we// do not call `retract_batch`.if update_bound > 0 {+ let slice_mask =+ filter_mask.map(|m| m.slice(last_range.end, update_bound));let update: Vec<ArrayRef> = value_slice.iter().map(|v| v.slice(last_range.end, update_bound))- .collect();+ .map(|arr| match &slice_mask {+ Some(m) => filter_array(&arr, m),+ None => Ok(arr),+ })+ .collect::<Result<Vec<_>>>()?;accumulator.update_batch(&update)?}accumulator.evaluate()diff --git a/datafusion/physical-expr/src/window/sliding_aggregate.rs b/datafusion/physical-expr/src/window/sliding_aggregate.rsindex cb105e773d..f93b13fef4 100644--- a/datafusion/physical-expr/src/window/sliding_aggregate.rs+++ b/datafusion/physical-expr/src/window/sliding_aggregate.rs@@ -22,13 +22,13 @@ use std::ops::Range;use std::sync::Arc;use crate::aggregate::AggregateFunctionExpr;-use crate::window::window_expr::{AggregateWindowExpr, WindowFn};+use crate::window::window_expr::{filter_array, AggregateWindowExpr, WindowFn};use crate::window::{PartitionBatches, PartitionWindowAggStates, PlainAggregateWindowExpr, WindowExpr,};use crate::{expressions::PhysicalSortExpr, PhysicalExpr};-use arrow::array::{Array, ArrayRef};+use arrow::array::{ArrayRef, BooleanArray};use arrow::datatypes::FieldRef;use arrow::record_batch::RecordBatch;use datafusion_common::{Result, ScalarValue};@@ -44,6 +44,7 @@ pub struct SlidingAggregateWindowExpr {partition_by: Vec<Arc<dyn PhysicalExpr>>,order_by: Vec<PhysicalSortExpr>,window_frame: Arc<WindowFrame>,+ filter: Option<Arc<dyn PhysicalExpr>>,}impl SlidingAggregateWindowExpr {@@ -53,12 +54,14 @@ impl SlidingAggregateWindowExpr {partition_by: &[Arc<dyn PhysicalExpr>],order_by: &[PhysicalSortExpr],window_frame: Arc<WindowFrame>,+ filter: Option<Arc<dyn PhysicalExpr>>,) -> Self {Self {aggregate,partition_by: partition_by.to_vec(),order_by: order_by.to_vec(),window_frame,+ filter,}}@@ -128,6 +131,7 @@ impl WindowExpr for SlidingAggregateWindowExpr {.map(|e| e.reverse()).collect::<Vec<_>>(),Arc::new(self.window_frame.reverse()),+ self.filter.clone(),)) as _} else {Arc::new(SlidingAggregateWindowExpr::new(@@ -139,6 +143,7 @@ impl WindowExpr for SlidingAggregateWindowExpr {.map(|e| e.reverse()).collect::<Vec<_>>(),Arc::new(self.window_frame.reverse()),+ self.filter.clone(),)) as _}})@@ -173,6 +178,7 @@ impl WindowExpr for SlidingAggregateWindowExpr {partition_by: partition_bys,order_by: new_order_by,window_frame: Arc::clone(&self.window_frame),+ filter: self.filter.clone(),}))}@@ -186,6 +192,10 @@ impl AggregateWindowExpr for SlidingAggregateWindowExpr {self.aggregate.create_sliding_accumulator()}+ fn filter_expr(&self) -> Option<&Arc<dyn PhysicalExpr>> {+ self.filter.as_ref()+ }+/// Given current range and the last range, calculates the accumulator/// result for the range of interest.fn get_aggregate_result_inside_range(@@ -194,6 +204,7 @@ impl AggregateWindowExpr for SlidingAggregateWindowExpr {cur_range: &Range<usize>,value_slice: &[ArrayRef],accumulator: &mut Box<dyn Accumulator>,+ filter_mask: Option<&BooleanArray>,) -> Result<ScalarValue> {if cur_range.start == cur_range.end {self.aggregate@@ -202,20 +213,32 @@ impl AggregateWindowExpr for SlidingAggregateWindowExpr {// Accumulate any new rows that have entered the window:let update_bound = cur_range.end - last_range.end;if update_bound > 0 {+ let slice_mask =+ filter_mask.map(|m| m.slice(last_range.end, update_bound));let update: Vec<ArrayRef> = value_slice.iter().map(|v| v.slice(last_range.end, update_bound))- .collect();+ .map(|arr| match &slice_mask {+ Some(m) => filter_array(&arr, m),+ None => Ok(arr),+ })+ .collect::<Result<Vec<_>>>()?;accumulator.update_batch(&update)?}// Remove rows that have now left the window:let retract_bound = cur_range.start - last_range.start;if retract_bound > 0 {+ let slice_mask =+ filter_mask.map(|m| m.slice(last_range.start, retract_bound));let retract: Vec<ArrayRef> = value_slice.iter().map(|v| v.slice(last_range.start, retract_bound))- .collect();+ .map(|arr| match &slice_mask {+ Some(m) => filter_array(&arr, m),+ None => Ok(arr),+ })+ .collect::<Result<Vec<_>>>()?;accumulator.retract_batch(&retract)?}accumulator.evaluate()diff --git a/datafusion/physical-expr/src/window/window_expr.rs b/datafusion/physical-expr/src/window/window_expr.rsindex ee39b5b245..c783862d57 100644--- a/datafusion/physical-expr/src/window/window_expr.rs+++ b/datafusion/physical-expr/src/window/window_expr.rs@@ -22,13 +22,18 @@ use std::sync::Arc;use crate::PhysicalExpr;+use arrow::array::BooleanArray;use arrow::array::{new_empty_array, Array, ArrayRef};+use arrow::compute::filter as arrow_filter;use arrow::compute::kernels::sort::SortColumn;use arrow::compute::SortOptions;use arrow::datatypes::FieldRef;use arrow::record_batch::RecordBatch;+use datafusion_common::cast::as_boolean_array;use datafusion_common::utils::compare_rows;-use datafusion_common::{internal_err, DataFusionError, Result, ScalarValue};+use datafusion_common::{+ arrow_datafusion_err, internal_err, DataFusionError, Result, ScalarValue,+};use datafusion_expr::window_state::{PartitionBatchState, WindowAggState, WindowFrameContext, WindowFrameStateGroups,};@@ -183,6 +188,9 @@ pub trait AggregateWindowExpr: WindowExpr {/// (non-sliding) expressions will return sliding (normal) accumulators.fn get_accumulator(&self) -> Result<Box<dyn Accumulator>>;+ /// Optional FILTER (WHERE ...) predicate for this window aggregate.+ fn filter_expr(&self) -> Option<&Arc<dyn PhysicalExpr>>;+/// Given current range and the last range, calculates the accumulator/// result for the range of interest.fn get_aggregate_result_inside_range(@@ -191,6 +199,7 @@ pub trait AggregateWindowExpr: WindowExpr {cur_range: &Range<usize>,value_slice: &[ArrayRef],accumulator: &mut Box<dyn Accumulator>,+ filter_mask: Option<&BooleanArray>,) -> Result<ScalarValue>;/// Indicates whether this window function always produces the same result@@ -291,12 +300,33 @@ pub trait AggregateWindowExpr: WindowExpr {) -> Result<ArrayRef> {let values = self.evaluate_args(record_batch)?;+ // Evaluate filter mask once per record batch if present+ let filter_mask_arr: Option<ArrayRef> = match self.filter_expr() {+ Some(expr) => {+ let value = expr.evaluate(record_batch)?;+ Some(value.into_array(record_batch.num_rows())?)+ }+ None => None,+ };++ // Borrow boolean view from the owned array+ let filter_mask: Option<&BooleanArray> = match filter_mask_arr.as_deref() {+ Some(arr) => Some(as_boolean_array(arr)?),+ None => None,+ };+if self.is_constant_in_partition() {if not_end {let field = self.field()?;let out_type = field.data_type();return Ok(new_empty_array(out_type));}+ let values = if let Some(mask) = filter_mask {+ // Apply mask to all argument arrays before a single update+ filter_arrays(&values, mask)?+ } else {+ values+ };accumulator.update_batch(&values)?;let value = accumulator.evaluate()?;return value.to_array_of_size(record_batch.num_rows());@@ -334,6 +364,7 @@ pub trait AggregateWindowExpr: WindowExpr {&cur_range,&values,accumulator,+ filter_mask,)?;// Update last range*last_range = cur_range;@@ -351,6 +382,21 @@ pub trait AggregateWindowExpr: WindowExpr {}}+/// Filters a single array with the provided boolean mask.+pub(crate) fn filter_array(array: &ArrayRef, mask: &BooleanArray) -> Result<ArrayRef> {+ arrow_filter(array.as_ref(), mask)+ .map(|a| a as ArrayRef)+ .map_err(|e| arrow_datafusion_err!(e))+}++/// Filters a list of arrays with the provided boolean mask.+pub(crate) fn filter_arrays(+ arrays: &[ArrayRef],+ mask: &BooleanArray,+) -> Result<Vec<ArrayRef>> {+ arrays.iter().map(|arr| filter_array(arr, mask)).collect()+}+/// Determines whether the end bound calculation for a window frame context is/// safe, meaning that the end bound stays the same, regardless of future data,/// based on the current sort expressions and ORDER BY columns. This functiondiff --git a/datafusion/physical-plan/src/windows/bounded_window_agg_exec.rs b/datafusion/physical-plan/src/windows/bounded_window_agg_exec.rsindex 1bb19654f8..e51b2d3f56 100644--- a/datafusion/physical-plan/src/windows/bounded_window_agg_exec.rs+++ b/datafusion/physical-plan/src/windows/bounded_window_agg_exec.rs@@ -1378,6 +1378,7 @@ mod tests {&input.schema(),false,false,+ None,)?],input,input_order_mode,diff --git a/datafusion/physical-plan/src/windows/mod.rs b/datafusion/physical-plan/src/windows/mod.rsindex 721432ce25..dccd9200fc 100644--- a/datafusion/physical-plan/src/windows/mod.rs+++ b/datafusion/physical-plan/src/windows/mod.rs@@ -99,6 +99,7 @@ pub fn create_window_expr(input_schema: &Schema,ignore_nulls: bool,distinct: bool,+ filter: Option<Arc<dyn PhysicalExpr>>,) -> Result<Arc<dyn WindowExpr>> {Ok(match fun {WindowFunctionDefinition::AggregateUDF(fun) => {@@ -123,6 +124,7 @@ pub fn create_window_expr(order_by,window_frame,aggregate,+ filter,)}WindowFunctionDefinition::WindowUDF(fun) => Arc::new(StandardWindowExpr::new(@@ -140,6 +142,7 @@ fn window_expr_from_aggregate_expr(order_by: &[PhysicalSortExpr],window_frame: Arc<WindowFrame>,aggregate: Arc<AggregateFunctionExpr>,+ filter: Option<Arc<dyn PhysicalExpr>>,) -> Arc<dyn WindowExpr> {// Is there a potentially unlimited sized window frame?let unbounded_window = window_frame.is_ever_expanding();@@ -150,6 +153,7 @@ fn window_expr_from_aggregate_expr(partition_by,order_by,window_frame,+ filter,))} else {Arc::new(PlainAggregateWindowExpr::new(@@ -157,6 +161,7 @@ fn window_expr_from_aggregate_expr(partition_by,order_by,window_frame,+ filter,))}}@@ -812,6 +817,7 @@ mod tests {schema.as_ref(),false,false,+ None,)?],blocking_exec,false,diff --git a/datafusion/proto/src/logical_plan/from_proto.rs b/datafusion/proto/src/logical_plan/from_proto.rsindex 6c5b348698..cbfa15183b 100644--- a/datafusion/proto/src/logical_plan/from_proto.rs+++ b/datafusion/proto/src/logical_plan/from_proto.rs@@ -301,7 +301,8 @@ pub fn parse_expr(exec_datafusion_err!("missing window frame during deserialization")})?;- // TODO: support proto for null treatment+ // TODO: support null treatment, distinct, and filter in proto.+ // See https://github.com/apache/datafusion/issues/17417match window_function {window_expr_node::WindowFunction::Udaf(udaf_name) => {let udaf_function = match &expr.fun_definition {diff --git a/datafusion/proto/src/logical_plan/to_proto.rs b/datafusion/proto/src/logical_plan/to_proto.rsindex f59e97df0d..1be3300008 100644--- a/datafusion/proto/src/logical_plan/to_proto.rs+++ b/datafusion/proto/src/logical_plan/to_proto.rs@@ -314,9 +314,11 @@ pub fn serialize_expr(ref partition_by,ref order_by,ref window_frame,- // TODO: support null treatment in proto+ // TODO: support null treatment, distinct, and filter in proto.+ // See https://github.com/apache/datafusion/issues/17417null_treatment: _,distinct: _,+ filter: _,},} = window_fun.as_ref();let mut buf = Vec::new();diff --git a/datafusion/proto/src/physical_plan/from_proto.rs b/datafusion/proto/src/physical_plan/from_proto.rsindex dec227d168..85de56e972 100644--- a/datafusion/proto/src/physical_plan/from_proto.rs+++ b/datafusion/proto/src/physical_plan/from_proto.rs@@ -180,6 +180,7 @@ pub fn parse_physical_window_expr(&extended_schema,proto.ignore_nulls,proto.distinct,+ None,)}diff --git a/datafusion/proto/tests/cases/roundtrip_physical_plan.rs b/datafusion/proto/tests/cases/roundtrip_physical_plan.rsindex a1112f8f94..a5357a132e 100644--- a/datafusion/proto/tests/cases/roundtrip_physical_plan.rs+++ b/datafusion/proto/tests/cases/roundtrip_physical_plan.rs@@ -391,6 +391,7 @@ fn roundtrip_window() -> Result<()> {&[],&[],Arc::new(WindowFrame::new(None)),+ None,));let window_frame = WindowFrame::new_bounds(@@ -411,6 +412,7 @@ fn roundtrip_window() -> Result<()> {&[],&[],Arc::new(window_frame),+ None,));let input = Arc::new(EmptyExec::new(schema.clone()));@@ -439,6 +441,7 @@ fn roundtrip_window_distinct() -> Result<()> {&[col("b", &schema)?], // partition by b&[], // no order byArc::new(WindowFrame::new(None)), // unbounded frame+ None,));// Create a distinct sum window expression with bounded frame (becomes SlidingAggregateWindowExpr)@@ -462,6 +465,7 @@ fn roundtrip_window_distinct() -> Result<()> {&[], // no partition by&[], // no order byArc::new(bounded_frame), // bounded frame+ None,));let input = Arc::new(EmptyExec::new(schema.clone()));@@ -493,6 +497,7 @@ fn test_distinct_window_serialization_end_to_end() -> Result<()> {&[col("b", &schema)?],&[],Arc::new(WindowFrame::new(None)),+ None,));// Test 2: DISTINCT SUM (without ignore nulls)@@ -515,6 +520,7 @@ fn test_distinct_window_serialization_end_to_end() -> Result<()> {&[],&[],Arc::new(bounded_frame),+ None,));let input = Arc::new(EmptyExec::new(schema.clone()));@@ -1258,6 +1264,7 @@ fn roundtrip_scalar_udf_extension_codec() -> Result<()> {&[col("author", &schema)?],&[],Arc::new(WindowFrame::new(None)),+ None,))],filter,true,@@ -1367,6 +1374,7 @@ fn roundtrip_aggregate_udf_extension_codec() -> Result<()> {&[col("author", &schema)?],&[],Arc::new(WindowFrame::new(None)),+ None,))],filter,true,diff --git a/datafusion/sql/src/expr/function.rs b/datafusion/sql/src/expr/function.rsindex 7f8bfa4659..5a47c56f34 100644--- a/datafusion/sql/src/expr/function.rs+++ b/datafusion/sql/src/expr/function.rs@@ -22,11 +22,9 @@ use datafusion_common::{internal_datafusion_err, internal_err, not_impl_err, plan_datafusion_err, plan_err,DFSchema, Dependency, Diagnostic, Result, Span,};-use datafusion_expr::expr::{ScalarFunction, Unnest, WildcardOptions};+use datafusion_expr::expr::{ScalarFunction, Unnest, WildcardOptions, WindowFunction};use datafusion_expr::planner::{PlannerResult, RawAggregateExpr, RawWindowExpr};-use datafusion_expr::{- expr, Expr, ExprFunctionExt, ExprSchemable, WindowFrame, WindowFunctionDefinition,-};+use datafusion_expr::{expr, Expr, ExprSchemable, WindowFrame, WindowFunctionDefinition};use sqlparser::ast::{DuplicateTreatment, Expr as SQLExpr, Function as SQLFunction, FunctionArg,FunctionArgExpr, FunctionArgumentClause, FunctionArgumentList, FunctionArguments,@@ -345,12 +343,20 @@ impl<S: ContextProvider> SqlToRel<'_, S> {if let Ok(fun) = self.find_window_func(&name) {let args = self.function_args_to_expr(args, schema, planner_context)?;++ // Plan FILTER clause if present+ let filter = filter+ .map(|e| self.sql_expr_to_logical_expr(*e, schema, planner_context))+ .transpose()?+ .map(Box::new);+let mut window_expr = RawWindowExpr {func_def: fun,args,partition_by,order_by,window_frame,+ filter,null_treatment,distinct: function_args.distinct,};@@ -368,26 +374,25 @@ impl<S: ContextProvider> SqlToRel<'_, S> {partition_by,order_by,window_frame,+ filter,null_treatment,distinct,} = window_expr;- if distinct {- return Expr::from(expr::WindowFunction::new(func_def, args))- .partition_by(partition_by)- .order_by(order_by)- .window_frame(window_frame)- .null_treatment(null_treatment)- .distinct()- .build();- }-- return Expr::from(expr::WindowFunction::new(func_def, args))- .partition_by(partition_by)- .order_by(order_by)- .window_frame(window_frame)- .null_treatment(null_treatment)- .build();+ let expr = Expr::from(WindowFunction {+ fun: func_def,+ params: expr::WindowFunctionParams {+ args,+ partition_by,+ order_by,+ window_frame,+ filter,+ null_treatment,+ distinct,+ },+ });++ return Ok(expr);}} else {// User defined aggregate functions (UDAF) have precedence in case it has the same name as a scalar built-in functiondiff --git a/datafusion/sql/src/unparser/expr.rs b/datafusion/sql/src/unparser/expr.rsindex 0501a4e049..d4e911a62c 100644--- a/datafusion/sql/src/unparser/expr.rs+++ b/datafusion/sql/src/unparser/expr.rs@@ -201,6 +201,7 @@ impl Unparser<'_> {partition_by,order_by,window_frame,+ filter,distinct,..},@@ -265,7 +266,10 @@ impl Unparser<'_> {args,clauses: vec![],}),- filter: None,+ filter: filter+ .as_ref()+ .map(|f| self.expr_to_sql_inner(f).map(Box::new))+ .transpose()?,null_treatment: None,over,within_group: vec![],@@ -2065,6 +2069,7 @@ mod tests {window_frame: WindowFrame::new(None),null_treatment: None,distinct: false,+ filter: None,},}),r#"row_number(col) OVER (ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)"#,@@ -2091,9 +2096,10 @@ mod tests {),null_treatment: None,distinct: false,+ filter: Some(Box::new(col("a").gt(lit(100)))),},}),- r#"count(*) OVER (ORDER BY a DESC NULLS FIRST RANGE BETWEEN 6 PRECEDING AND 2 FOLLOWING)"#,+ r#"count(*) FILTER (WHERE (a > 100)) OVER (ORDER BY a DESC NULLS FIRST RANGE BETWEEN 6 PRECEDING AND 2 FOLLOWING)"#,),(col("a").is_not_null(), r#"a IS NOT NULL"#),(col("a").is_null(), r#"a IS NULL"#),diff --git a/datafusion/sql/tests/cases/plan_to_sql.rs b/datafusion/sql/tests/cases/plan_to_sql.rsindex 349933b8ec..02a4da4267 100644--- a/datafusion/sql/tests/cases/plan_to_sql.rs+++ b/datafusion/sql/tests/cases/plan_to_sql.rs@@ -1919,6 +1919,7 @@ fn test_aggregation_to_sql() {let sql = r#"SELECT id, first_name,SUM(id) AS total_sum,SUM(id) OVER (PARTITION BY first_name ROWS BETWEEN 5 PRECEDING AND 2 FOLLOWING) AS moving_sum,+ SUM(id) FILTER (WHERE id > 50 AND first_name = 'John') OVER (PARTITION BY first_name ROWS BETWEEN 5 PRECEDING AND 2 FOLLOWING) AS filtered_sum,MAX(SUM(id)) OVER (PARTITION BY first_name ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS max_total,rank() OVER (PARTITION BY grouping(id) + grouping(age), CASE WHEN grouping(age) = 0 THEN id END ORDER BY sum(id) DESC) AS rank_within_parent_1,rank() OVER (PARTITION BY grouping(age) + grouping(id), CASE WHEN (CAST(grouping(age) AS BIGINT) = 0) THEN id END ORDER BY sum(id) DESC) AS rank_within_parent_2@@ -1927,7 +1928,7 @@ fn test_aggregation_to_sql() {let statement = generate_round_trip_statement(GenericDialect {}, sql);assert_snapshot!(statement,- @"SELECT person.id, person.first_name, sum(person.id) AS total_sum, sum(person.id) OVER (PARTITION BY person.first_name ROWS BETWEEN 5 PRECEDING AND 2 FOLLOWING) AS moving_sum, max(sum(person.id)) OVER (PARTITION BY person.first_name ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS max_total, rank() OVER (PARTITION BY (grouping(person.id) + grouping(person.age)), CASE WHEN (grouping(person.age) = 0) THEN person.id END ORDER BY sum(person.id) DESC NULLS FIRST RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS rank_within_parent_1, rank() OVER (PARTITION BY (grouping(person.age) + grouping(person.id)), CASE WHEN (CAST(grouping(person.age) AS BIGINT) = 0) THEN person.id END ORDER BY sum(person.id) DESC NULLS FIRST RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS rank_within_parent_2 FROM person GROUP BY person.id, person.first_name",+ @"SELECT person.id, person.first_name, sum(person.id) AS total_sum, sum(person.id) OVER (PARTITION BY person.first_name ROWS BETWEEN 5 PRECEDING AND 2 FOLLOWING) AS moving_sum, sum(person.id) FILTER (WHERE ((person.id > 50) AND (person.first_name = 'John'))) OVER (PARTITION BY person.first_name ROWS BETWEEN 5 PRECEDING AND 2 FOLLOWING) AS filtered_sum, max(sum(person.id)) OVER (PARTITION BY person.first_name ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS max_total, rank() OVER (PARTITION BY (grouping(person.id) + grouping(person.age)), CASE WHEN (grouping(person.age) = 0) THEN person.id END ORDER BY sum(person.id) DESC NULLS FIRST RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS rank_within_parent_1, rank() OVER (PARTITION BY (grouping(person.age) + grouping(person.id)), CASE WHEN (CAST(grouping(person.age) AS BIGINT) = 0) THEN person.id END ORDER BY sum(person.id) DESC NULLS FIRST RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS rank_within_parent_2 FROM person GROUP BY person.id, person.first_name",);}diff --git a/datafusion/sqllogictest/test_files/window.slt b/datafusion/sqllogictest/test_files/window.sltindex 5475fd923b..c302582344 100644--- a/datafusion/sqllogictest/test_files/window.slt+++ b/datafusion/sqllogictest/test_files/window.slt@@ -5898,3 +5898,139 @@ physical_plan06)----------RepartitionExec: partitioning=Hash([k@1], 2), input_partitions=207)------------ProjectionExec: expr=[CAST(v@1 AS Int64) as __common_expr_1, k@0 as k, time@2 as time]08)--------------DataSourceExec: partitions=2, partition_sizes=[5, 4]+++# FILTER clause with window functions++# Verify FILTER clause with non-aggregate window functions fails with a clear message+query error DataFusion error: Error during planning: FILTER clause can only be used with aggregate window functions\. Found in 'row_number\(\) FILTER \(WHERE test\.c1 > Int64\(0\)\) ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING'+SELECT+c1,+ROW_NUMBER() FILTER(WHERE c1 > 0) OVER () as rn1+FROM test+LIMIT 5+++query error DataFusion error: Error during planning: FILTER clause can only be used with aggregate window functions\. Found in 'first_value\(test\.c1\) FILTER \(WHERE test\.c1 > Int64\(0\)\) ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING'+SELECT+c1,+FIRST_VALUE(c1) FILTER(WHERE c1 > 0) OVER () as rn1+FROM test+LIMIT 5+++query error DataFusion error: Error during planning: FILTER clause can only be used with aggregate window functions\. Found in 'lag\(test\.c1\) FILTER \(WHERE test\.c1 > Int64\(0\)\) ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING'+SELECT+c1,+LAG(c1) FILTER(WHERE c1 > 0) OVER () as rn1+FROM test+LIMIT 5+++# Check error propagation from filter to window function+query error+SELECT+c1,+SUM(c2) FILTER (WHERE c2 >= []) OVER (ORDER BY c1, c2 ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as sum1,+FROM test+LIMIT 5+----+DataFusion error: type_coercion+caused by+Error during planning: Cannot infer common argument type for comparison operation Int64 >= List(Field { name: "item", data_type: Null, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} })++++# EXPLAIN should display the filters+query TT+EXPLAIN SELECT+c1,+c2,+SUM(c2) FILTER (WHERE c2 >= 2) OVER (ORDER BY c1, c2 ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as sum1,+SUM(c2) FILTER (WHERE c2 >= 2 AND c2 < 4 AND c1 > 0) OVER (ORDER BY c1, c2 ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as sum2,+COUNT(c2) FILTER (WHERE c2 >= 2) OVER (ORDER BY c1, c2 ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as count1,+ARRAY_AGG(c2) FILTER (WHERE c2 >= 2) OVER (ORDER BY c1, c2 ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as array_agg1,+ARRAY_AGG(c2) FILTER (WHERE c2 >= 2 AND c2 < 4 AND c1 > 0) OVER (ORDER BY c1, c2 ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as array_agg2,+FROM test+ORDER BY c1, c2+LIMIT 5+----+logical_plan+01)Sort: test.c1 ASC NULLS LAST, test.c2 ASC NULLS LAST, fetch=5+02)--Projection: test.c1, test.c2, sum(test.c2) FILTER (WHERE test.c2 >= Int64(2)) ORDER BY [test.c1 ASC NULLS LAST, test.c2 ASC NULLS LAST] ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW AS sum1, sum(test.c2) FILTER (WHERE test.c2 >= Int64(2) AND test.c2 < Int64(4) AND test.c1 > Int64(0)) ORDER BY [test.c1 ASC NULLS LAST, test.c2 ASC NULLS LAST] ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW AS sum2, count(test.c2) FILTER (WHERE test.c2 >= Int64(2)) ORDER BY [test.c1 ASC NULLS LAST, test.c2 ASC NULLS LAST] ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW AS count1, array_agg(test.c2) FILTER (WHERE test.c2 >= Int64(2)) ORDER BY [test.c1 ASC NULLS LAST, test.c2 ASC NULLS LAST] ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW AS array_agg1, array_agg(test.c2) FILTER (WHERE test.c2 >= Int64(2) AND test.c2 < Int64(4) AND test.c1 > Int64(0)) ORDER BY [test.c1 ASC NULLS LAST, test.c2 ASC NULLS LAST] ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW AS array_agg2+03)----WindowAggr: windowExpr=[[sum(test.c2) FILTER (WHERE __common_expr_1 AS test.c2 >= Int64(2)) ORDER BY [test.c1 ASC NULLS LAST, test.c2 ASC NULLS LAST] ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW AS sum(test.c2) FILTER (WHERE test.c2 >= Int64(2)) ORDER BY [test.c1 ASC NULLS LAST, test.c2 ASC NULLS LAST] ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, sum(test.c2) FILTER (WHERE __common_expr_2) ORDER BY [test.c1 ASC NULLS LAST, test.c2 ASC NULLS LAST] ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW AS sum(test.c2) FILTER (WHERE test.c2 >= Int64(2) AND test.c2 < Int64(4) AND test.c1 > Int64(0)) ORDER BY [test.c1 ASC NULLS LAST, test.c2 ASC NULLS LAST] ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, count(test.c2) FILTER (WHERE __common_expr_1 AS test.c2 >= Int64(2)) ORDER BY [test.c1 ASC NULLS LAST, test.c2 ASC NULLS LAST] ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW AS count(test.c2) FILTER (WHERE test.c2 >= Int64(2)) ORDER BY [test.c1 ASC NULLS LAST, test.c2 ASC NULLS LAST] ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, array_agg(test.c2) FILTER (WHERE __common_expr_1 AS test.c2 >= Int64(2)) ORDER BY [test.c1 ASC NULLS LAST, test.c2 ASC NULLS LAST] ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW AS array_agg(test.c2) FILTER (WHERE test.c2 >= Int64(2)) ORDER BY [test.c1 ASC NULLS LAST, test.c2 ASC NULLS LAST] ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, array_agg(test.c2) FILTER (WHERE __common_expr_2) ORDER BY [test.c1 ASC NULLS LAST, test.c2 ASC NULLS LAST] ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW AS array_agg(test.c2) FILTER (WHERE test.c2 >= Int64(2) AND test.c2 < Int64(4) AND test.c1 > Int64(0)) ORDER BY [test.c1 ASC NULLS LAST, test.c2 ASC NULLS LAST] ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW]]+04)------Projection: __common_expr_3 AS __common_expr_1, __common_expr_3 AND test.c2 < Int64(4) AND test.c1 > Int32(0) AS __common_expr_2, test.c1, test.c2+05)--------Projection: test.c2 >= Int64(2) AS __common_expr_3, test.c1, test.c2+06)----------TableScan: test projection=[c1, c2]+physical_plan+01)ProjectionExec: expr=[c1@2 as c1, c2@3 as c2, sum(test.c2) FILTER (WHERE test.c2 >= Int64(2)) ORDER BY [test.c1 ASC NULLS LAST, test.c2 ASC NULLS LAST] ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW@4 as sum1, sum(test.c2) FILTER (WHERE test.c2 >= Int64(2) AND test.c2 < Int64(4) AND test.c1 > Int64(0)) ORDER BY [test.c1 ASC NULLS LAST, test.c2 ASC NULLS LAST] ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW@5 as sum2, count(test.c2) FILTER (WHERE test.c2 >= Int64(2)) ORDER BY [test.c1 ASC NULLS LAST, test.c2 ASC NULLS LAST] ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW@6 as count1, array_agg(test.c2) FILTER (WHERE test.c2 >= Int64(2)) ORDER BY [test.c1 ASC NULLS LAST, test.c2 ASC NULLS LAST] ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW@7 as array_agg1, array_agg(test.c2) FILTER (WHERE test.c2 >= Int64(2) AND test.c2 < Int64(4) AND test.c1 > Int64(0)) ORDER BY [test.c1 ASC NULLS LAST, test.c2 ASC NULLS LAST] ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW@8 as array_agg2]+02)--GlobalLimitExec: skip=0, fetch=5+03)----BoundedWindowAggExec: wdw=[sum(test.c2) FILTER (WHERE test.c2 >= Int64(2)) ORDER BY [test.c1 ASC NULLS LAST, test.c2 ASC NULLS LAST] ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW: Field { name: "sum(test.c2) FILTER (WHERE test.c2 >= Int64(2)) ORDER BY [test.c1 ASC NULLS LAST, test.c2 ASC NULLS LAST] ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }, frame: ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, sum(test.c2) FILTER (WHERE test.c2 >= Int64(2) AND test.c2 < Int64(4) AND test.c1 > Int64(0)) ORDER BY [test.c1 ASC NULLS LAST, test.c2 ASC NULLS LAST] ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW: Field { name: "sum(test.c2) FILTER (WHERE test.c2 >= Int64(2) AND test.c2 < Int64(4) AND test.c1 > Int64(0)) ORDER BY [test.c1 ASC NULLS LAST, test.c2 ASC NULLS LAST] ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }, frame: ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, count(test.c2) FILTER (WHERE test.c2 >= Int64(2)) ORDER BY [test.c1 ASC NULLS LAST, test.c2 ASC NULLS LAST] ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW: Field { name: "count(test.c2) FILTER (WHERE test.c2 >= Int64(2)) ORDER BY [test.c1 ASC NULLS LAST, test.c2 ASC NULLS LAST] ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW", data_type: Int64, nullable: false, dict_id: 0, dict_is_ordered: false, metadata: {} }, frame: ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, array_agg(test.c2) FILTER (WHERE test.c2 >= Int64(2)) ORDER BY [test.c1 ASC NULLS LAST, test.c2 ASC NULLS LAST] ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW: Field { name: "array_agg(test.c2) FILTER (WHERE test.c2 >= Int64(2)) ORDER BY [test.c1 ASC NULLS LAST, test.c2 ASC NULLS LAST] ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW", data_type: List(Field { name: "item", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }, frame: ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, array_agg(test.c2) FILTER (WHERE test.c2 >= Int64(2) AND test.c2 < Int64(4) AND test.c1 > Int64(0)) ORDER BY [test.c1 ASC NULLS LAST, test.c2 ASC NULLS LAST] ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW: Field { name: "array_agg(test.c2) FILTER (WHERE test.c2 >= Int64(2) AND test.c2 < Int64(4) AND test.c1 > Int64(0)) ORDER BY [test.c1 ASC NULLS LAST, test.c2 ASC NULLS LAST] ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW", data_type: List(Field { name: "item", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }, frame: ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW], mode=[Sorted]+04)------SortPreservingMergeExec: [c1@2 ASC NULLS LAST, c2@3 ASC NULLS LAST]+05)--------SortExec: expr=[c1@2 ASC NULLS LAST, c2@3 ASC NULLS LAST], preserve_partitioning=[true]+06)----------ProjectionExec: expr=[__common_expr_3@0 as __common_expr_1, __common_expr_3@0 AND c2@2 < 4 AND c1@1 > 0 as __common_expr_2, c1@1 as c1, c2@2 as c2]+07)------------ProjectionExec: expr=[c2@1 >= 2 as __common_expr_3, c1@0 as c1, c2@1 as c2]+08)--------------DataSourceExec: file_groups={4 groups: [[WORKSPACE_ROOT/datafusion/core/tests/data/partitioned_csv/partition-0.csv], [WORKSPACE_ROOT/datafusion/core/tests/data/partitioned_csv/partition-1.csv], [WORKSPACE_ROOT/datafusion/core/tests/data/partitioned_csv/partition-2.csv], [WORKSPACE_ROOT/datafusion/core/tests/data/partitioned_csv/partition-3.csv]]}, projection=[c1, c2], file_type=csv, has_header=false+++# FILTER filters out some rows+query IIIII??+SELECT+c1,+c2,+SUM(c2) FILTER (WHERE c2 >= 2) OVER (ORDER BY c1, c2 ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as sum1,+SUM(c2) FILTER (WHERE c2 >= 2 AND c2 < 4 AND c1 >= 0) OVER (ORDER BY c1, c2 ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as sum2,+COUNT(c2) FILTER (WHERE c2 >= 2) OVER (ORDER BY c1, c2 ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as count1,+ARRAY_AGG(c2) FILTER (WHERE c2 >= 2) OVER (ORDER BY c1, c2 ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as array_agg1,+ARRAY_AGG(c2) FILTER (WHERE c2 >= 2 AND c2 < 4 AND c1 >= 0) OVER (ORDER BY c1, c2 ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as array_agg2,+FROM test+ORDER BY c1, c2+LIMIT 5+----+0 0 NULL NULL 0 NULL NULL+0 1 NULL NULL 0 NULL NULL+0 2 2 2 1 [2] [2]+0 3 5 5 2 [2, 3] [2, 3]+0 4 9 5 3 [2, 3, 4] [2, 3]+++# FILTER filters out no rows+query IIIII??+SELECT+c1,+c2,+SUM(c2) FILTER (WHERE c2 >= 0) OVER (ORDER BY c1, c2 ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as sum1,+SUM(c2) FILTER (WHERE c2 >= 0 AND c2 < 1000 AND c1 >= 0) OVER (ORDER BY c1, c2 ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as sum2,+COUNT(c2) FILTER (WHERE c2 >= 0) OVER (ORDER BY c1, c2 ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as count1,+ARRAY_AGG(c2) FILTER (WHERE c2 >= 0) OVER (ORDER BY c1, c2 ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as array_agg1,+ARRAY_AGG(c2) FILTER (WHERE c2 >= 0 AND c2 < 1000 AND c1 >= 0) OVER (ORDER BY c1, c2 ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as array_agg2,+FROM test+ORDER BY c1, c2+LIMIT 5+----+0 0 0 0 1 [0] [0]+0 1 1 1 2 [0, 1] [0, 1]+0 2 3 3 3 [0, 1, 2] [0, 1, 2]+0 3 6 6 4 [0, 1, 2, 3] [0, 1, 2, 3]+0 4 10 10 5 [0, 1, 2, 3, 4] [0, 1, 2, 3, 4]+++# FILTER filters out every row+query IIIII??+SELECT+c1,+c2,+SUM(c2) FILTER (WHERE c2 == -1) OVER (ORDER BY c1, c2 ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as sum1,+SUM(c2) FILTER (WHERE c2 >= 0 AND c2 < 0 AND c1 >= 0) OVER (ORDER BY c1, c2 ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as sum2,+COUNT(c2) FILTER (WHERE c2 == -1) OVER (ORDER BY c1, c2 ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as count1,+ARRAY_AGG(c2) FILTER (WHERE c2 >= 1000) OVER (ORDER BY c1, c2 ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as array_agg1,+ARRAY_AGG(c2) FILTER (WHERE c2 >= 0 AND c2 < 1000 AND c1 >= 1000) OVER (ORDER BY c1, c2 ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as array_agg2,+FROM test+ORDER BY c1, c2+LIMIT 5+----+0 0 NULL NULL 0 NULL NULL+0 1 NULL NULL 0 NULL NULL+0 2 NULL NULL 0 NULL NULL+0 3 NULL NULL 0 NULL NULL+0 4 NULL NULL 0 NULL NULLdiff --git a/datafusion/substrait/src/logical_plan/consumer/expr/window_function.rs b/datafusion/substrait/src/logical_plan/consumer/expr/window_function.rsindex 27f0de84b7..3399d660df 100644--- a/datafusion/substrait/src/logical_plan/consumer/expr/window_function.rs+++ b/datafusion/substrait/src/logical_plan/consumer/expr/window_function.rs@@ -111,6 +111,7 @@ pub async fn from_window_function(.await?,order_by,window_frame,+ filter: None,null_treatment: None,distinct: false,},diff --git a/datafusion/substrait/src/logical_plan/producer/expr/window_function.rs b/datafusion/substrait/src/logical_plan/producer/expr/window_function.rsindex 94a39e930f..465479e1e0 100644--- a/datafusion/substrait/src/logical_plan/producer/expr/window_function.rs+++ b/datafusion/substrait/src/logical_plan/producer/expr/window_function.rs@@ -43,6 +43,7 @@ pub fn from_window_function(window_frame,null_treatment: _,distinct: _,+ filter: _,},} = window_fn;// function referencediff --git a/dev/update_function_docs.sh b/dev/update_function_docs.shindex a9e87aacf5..6ed760bd22 100755--- a/dev/update_function_docs.sh+++ b/dev/update_function_docs.sh@@ -59,6 +59,25 @@ dev/update_function_docs.sh file for updating surrounding text.# Aggregate FunctionsAggregate functions operate on a set of values to compute a single result.++## Filter clause++Aggregate functions support the SQL `FILTER (WHERE ...)` clause to restrict which input rows contribute to the aggregate result.++```sql+function([exprs]) FILTER (WHERE condition)+```++Example:++```sql+SELECT+ sum(salary) FILTER (WHERE salary > 0) AS sum_positive_salaries,+ count(*) FILTER (WHERE active) AS active_count+FROM employees;+```++Note: When no rows pass the filter, `COUNT` returns `0` while `SUM`/`AVG`/`MIN`/`MAX` return `NULL`.EOFecho "Running CLI and inserting aggregate function docs table"@@ -266,6 +285,17 @@ where **offset** is an non-negative integer.RANGE and GROUPS modes require an ORDER BY clause (with RANGE the ORDER BY must specify exactly one column).+## Filter clause for aggregate window functions++Aggregate window functions support the SQL `FILTER (WHERE ...)` clause to include only rows that satisfy the predicate from the window frame in the aggregation.++```sql+sum(salary) FILTER (WHERE salary > 0)+ OVER (PARTITION BY depname ORDER BY salary ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)+```++If no rows in the frame satisfy the filter for a given output row, `COUNT` yields `0` while `SUM`/`AVG`/`MIN`/`MAX` yield `NULL`.+## Aggregate functionsAll [aggregate functions](aggregate_functions.md) can be used as window functions.diff --git a/docs/source/user-guide/sql/aggregate_functions.md b/docs/source/user-guide/sql/aggregate_functions.mdindex cdb51c64fc..205962031b 100644--- a/docs/source/user-guide/sql/aggregate_functions.md+++ b/docs/source/user-guide/sql/aggregate_functions.md@@ -29,6 +29,25 @@ dev/update_function_docs.sh file for updating surrounding text.Aggregate functions operate on a set of values to compute a single result.+## Filter clause++Aggregate functions support the SQL `FILTER (WHERE ...)` clause to restrict which input rows contribute to the aggregate result.++```sql+function([exprs]) FILTER (WHERE condition)+```++Example:++```sql+SELECT+ sum(salary) FILTER (WHERE salary > 0) AS sum_positive_salaries,+ count(*) FILTER (WHERE active) AS active_count+FROM employees;+```++Note: When no rows pass the filter, `COUNT` returns `0` while `SUM`/`AVG`/`MIN`/`MAX` return `NULL`.+## General Functions- [array_agg](#array_agg)diff --git a/docs/source/user-guide/sql/window_functions.md b/docs/source/user-guide/sql/window_functions.mdindex 73e9731cdb..2c8050ce1f 100644--- a/docs/source/user-guide/sql/window_functions.md+++ b/docs/source/user-guide/sql/window_functions.md@@ -145,6 +145,17 @@ where **offset** is an non-negative integer.RANGE and GROUPS modes require an ORDER BY clause (with RANGE the ORDER BY must specify exactly one column).+## Filter clause for aggregate window functions++Aggregate window functions support the SQL `FILTER (WHERE ...)` clause to include only rows that satisfy the predicate from the window frame in the aggregation.++```sql+sum(salary) FILTER (WHERE salary > 0)+ OVER (PARTITION BY depname ORDER BY salary ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)+```++If no rows in the frame satisfy the filter for a given output row, `COUNT` yields `0` while `SUM`/`AVG`/`MIN`/`MAX` yield `NULL`.+## Aggregate functionsAll [aggregate functions](aggregate_functions.md) can be used as window functions.