Apache DataFusion SQL Query Engine
Convert Option<Vec<sort expression>> to Vec<sort expression> (#16615)
ViggoC50dc83a1a19f
diff --git a/datafusion/core/src/physical_planner.rs b/datafusion/core/src/physical_planner.rsindex 90cc0b572f..e4bf2f5985 100644--- a/datafusion/core/src/physical_planner.rs+++ b/datafusion/core/src/physical_planner.rs@@ -1651,14 +1651,11 @@ pub fn create_aggregate_expr_with_name_and_maybe_filter(== NullTreatment::IgnoreNulls;let (agg_expr, filter, order_bys) = {- let order_bys = match order_by {- Some(exprs) => create_physical_sort_exprs(- exprs,- logical_input_schema,- execution_props,- )?,- None => vec![],- };+ let order_bys = create_physical_sort_exprs(+ order_by,+ logical_input_schema,+ execution_props,+ )?;let agg_expr =AggregateExprBuilder::new(func.to_owned(), physical_args.to_vec())diff --git a/datafusion/core/tests/execution/logical_plan.rs b/datafusion/core/tests/execution/logical_plan.rsindex f5a8a30e01..da8f980722 100644--- a/datafusion/core/tests/execution/logical_plan.rs+++ b/datafusion/core/tests/execution/logical_plan.rs@@ -68,7 +68,7 @@ async fn count_only_nulls() -> Result<()> {args: vec![input_col_ref],distinct: false,filter: None,- order_by: None,+ order_by: vec![],null_treatment: None,},})],diff --git a/datafusion/expr/src/expr.rs b/datafusion/expr/src/expr.rsindex c50268d996..a5e1f1c0e2 100644--- a/datafusion/expr/src/expr.rs+++ b/datafusion/expr/src/expr.rs@@ -28,7 +28,7 @@ use crate::expr_fn::binary_expr;use crate::function::WindowFunctionSimplification;use crate::logical_plan::Subquery;use crate::Volatility;-use crate::{udaf, ExprSchemable, Operator, Signature, WindowFrame, WindowUDF};+use crate::{ExprSchemable, Operator, Signature, WindowFrame, WindowUDF};use arrow::datatypes::{DataType, Field, FieldRef};use datafusion_common::cse::{HashNode, NormalizeEq, Normalizeable};@@ -994,7 +994,7 @@ pub struct AggregateFunctionParams {/// Optional filterpub filter: Option<Box<Expr>>,/// Optional ordering- pub order_by: Option<Vec<Sort>>,+ pub order_by: Vec<Sort>,pub null_treatment: Option<NullTreatment>,}@@ -1005,7 +1005,7 @@ impl AggregateFunction {args: Vec<Expr>,distinct: bool,filter: Option<Box<Expr>>,- order_by: Option<Vec<Sort>>,+ order_by: Vec<Sort>,null_treatment: Option<NullTreatment>,) -> Self {Self {@@ -1175,26 +1175,26 @@ impl Exists {/// User Defined Aggregate Function///-/// See [`udaf::AggregateUDF`] for more information.+/// See [`crate::udaf::AggregateUDF`] for more information.#[derive(Clone, PartialEq, Eq, Hash, Debug)]pub struct AggregateUDF {/// The function- pub fun: Arc<udaf::AggregateUDF>,+ pub fun: Arc<crate::AggregateUDF>,/// List of expressions to feed to the functions as argumentspub args: Vec<Expr>,/// Optional filterpub filter: Option<Box<Expr>>,/// Optional ORDER BY applied prior to aggregating- pub order_by: Option<Vec<Expr>>,+ pub order_by: Vec<Expr>,}impl AggregateUDF {/// Create a new AggregateUDF expressionpub fn new(- fun: Arc<udaf::AggregateUDF>,+ fun: Arc<crate::AggregateUDF>,args: Vec<Expr>,filter: Option<Box<Expr>>,- order_by: Option<Vec<Expr>>,+ order_by: Vec<Expr>,) -> Self {Self {fun,@@ -2303,18 +2303,15 @@ impl NormalizeEq for Expr {(None, None) => true,_ => false,}- && match (self_order_by, other_order_by) {- (Some(self_order_by), Some(other_order_by)) => self_order_by- .iter()- .zip(other_order_by.iter())- .all(|(a, b)| {- a.asc == b.asc- && a.nulls_first == b.nulls_first- && a.expr.normalize_eq(&b.expr)- }),- (None, None) => true,- _ => false,- }+ && self_order_by+ .iter()+ .zip(other_order_by.iter())+ .all(|(a, b)| {+ a.asc == b.asc+ && a.nulls_first == b.nulls_first+ && a.expr.normalize_eq(&b.expr)+ })+ && self_order_by.len() == other_order_by.len()}(Expr::WindowFunction(left), Expr::WindowFunction(other)) => {let WindowFunction {diff --git a/datafusion/expr/src/expr_fn.rs b/datafusion/expr/src/expr_fn.rsindex e8885ed6b7..001dfce59c 100644--- a/datafusion/expr/src/expr_fn.rs+++ b/datafusion/expr/src/expr_fn.rs@@ -821,7 +821,7 @@ impl ExprFuncBuilder {let fun_expr = match fun {ExprFuncKind::Aggregate(mut udaf) => {- udaf.params.order_by = order_by;+ udaf.params.order_by = order_by.unwrap_or_default();udaf.params.filter = filter.map(Box::new);udaf.params.distinct = distinct;udaf.params.null_treatment = null_treatment;diff --git a/datafusion/expr/src/planner.rs b/datafusion/expr/src/planner.rsindex 4c03f91931..067c7a9427 100644--- a/datafusion/expr/src/planner.rs+++ b/datafusion/expr/src/planner.rs@@ -294,7 +294,7 @@ pub struct RawAggregateExpr {pub args: Vec<Expr>,pub distinct: bool,pub filter: Option<Box<Expr>>,- pub order_by: Option<Vec<SortExpr>>,+ pub order_by: Vec<SortExpr>,pub null_treatment: Option<NullTreatment>,}diff --git a/datafusion/expr/src/test/function_stub.rs b/datafusion/expr/src/test/function_stub.rsindex f310f31be3..8f8e84c0d1 100644--- a/datafusion/expr/src/test/function_stub.rs+++ b/datafusion/expr/src/test/function_stub.rs@@ -60,7 +60,7 @@ pub fn sum(expr: Expr) -> Expr {vec![expr],false,None,- None,+ vec![],None,))}@@ -73,7 +73,7 @@ pub fn count(expr: Expr) -> Expr {vec![expr],false,None,- None,+ vec![],None,))}@@ -86,7 +86,7 @@ pub fn avg(expr: Expr) -> Expr {vec![expr],false,None,- None,+ vec![],None,))}@@ -282,7 +282,7 @@ pub fn min(expr: Expr) -> Expr {vec![expr],false,None,- None,+ vec![],None,))}@@ -363,7 +363,7 @@ pub fn max(expr: Expr) -> Expr {vec![expr],false,None,- None,+ vec![],None,))}diff --git a/datafusion/expr/src/udaf.rs b/datafusion/expr/src/udaf.rsindex bc617097f0..c6ccddc70c 100644--- a/datafusion/expr/src/udaf.rs+++ b/datafusion/expr/src/udaf.rs@@ -158,7 +158,7 @@ impl AggregateUDF {args,false,None,- None,+ vec![],None,))}@@ -394,7 +394,7 @@ where/// fn get_doc() -> &'static Documentation {/// &DOCUMENTATION/// }-///+////// /// Implement the AggregateUDFImpl trait for GeoMeanUdf/// impl AggregateUDFImpl for GeoMeanUdf {/// fn as_any(&self) -> &dyn Any { self }@@ -415,7 +415,7 @@ where/// ])/// }/// fn documentation(&self) -> Option<&Documentation> {-/// Some(get_doc())+/// Some(get_doc())/// }/// }///@@ -482,7 +482,7 @@ pub trait AggregateUDFImpl: Debug + Send + Sync {schema_name.write_fmt(format_args!(" FILTER (WHERE {filter})"))?;};- if let Some(order_by) = order_by {+ if !order_by.is_empty() {let clause = match self.is_ordered_set_aggregate() {true => "WITHIN GROUP",false => "ORDER BY",@@ -527,7 +527,7 @@ pub trait AggregateUDFImpl: Debug + Send + Sync {schema_name.write_fmt(format_args!(" FILTER (WHERE {filter})"))?;};- if let Some(order_by) = order_by {+ if !order_by.is_empty() {schema_name.write_fmt(format_args!(" ORDER BY [{}]",schema_name_from_sorts(order_by)?@@ -616,10 +616,11 @@ pub trait AggregateUDFImpl: Debug + Send + Sync {if let Some(fe) = filter {display_name.write_fmt(format_args!(" FILTER (WHERE {fe})"))?;}- if let Some(ob) = order_by {+ if !order_by.is_empty() {display_name.write_fmt(format_args!(" ORDER BY [{}]",- ob.iter()+ order_by+ .iter().map(|o| format!("{o}")).collect::<Vec<String>>().join(", ")diff --git a/datafusion/functions-aggregate/src/approx_percentile_cont.rs b/datafusion/functions-aggregate/src/approx_percentile_cont.rsindex 9b0d62e936..55c8c847ad 100644--- a/datafusion/functions-aggregate/src/approx_percentile_cont.rs+++ b/datafusion/functions-aggregate/src/approx_percentile_cont.rs@@ -69,7 +69,7 @@ pub fn approx_percentile_cont(args,false,None,- Some(vec![order_by]),+ vec![order_by],None,))}diff --git a/datafusion/functions-aggregate/src/count.rs b/datafusion/functions-aggregate/src/count.rsindex d1fe410321..09904bbad6 100644--- a/datafusion/functions-aggregate/src/count.rs+++ b/datafusion/functions-aggregate/src/count.rs@@ -73,7 +73,7 @@ pub fn count_distinct(expr: Expr) -> Expr {vec![expr],true,None,- None,+ vec![],None,))}diff --git a/datafusion/functions-aggregate/src/first_last.rs b/datafusion/functions-aggregate/src/first_last.rsindex 790eaada6a..9b5b821317 100644--- a/datafusion/functions-aggregate/src/first_last.rs+++ b/datafusion/functions-aggregate/src/first_last.rs@@ -55,31 +55,23 @@ create_func!(FirstValue, first_value_udaf);create_func!(LastValue, last_value_udaf);/// Returns the first value in a group of values.-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()- // guaranteed to be `Expr::AggregateFunction`- .unwrap()- } else {- first_value_udaf().call(vec![expression])- }+pub fn first_value(expression: Expr, order_by: Vec<SortExpr>) -> Expr {+ first_value_udaf()+ .call(vec![expression])+ .order_by(order_by)+ .build()+ // guaranteed to be `Expr::AggregateFunction`+ .unwrap()}/// Returns the last value in a group of values.-pub fn last_value(expression: Expr, order_by: Option<Vec<SortExpr>>) -> Expr {- if let Some(order_by) = order_by {- last_value_udaf()- .call(vec![expression])- .order_by(order_by)- .build()- // guaranteed to be `Expr::AggregateFunction`- .unwrap()- } else {- last_value_udaf().call(vec![expression])- }+pub fn last_value(expression: Expr, order_by: Vec<SortExpr>) -> Expr {+ last_value_udaf()+ .call(vec![expression])+ .order_by(order_by)+ .build()+ // guaranteed to be `Expr::AggregateFunction`+ .unwrap()}#[user_doc(diff --git a/datafusion/functions-aggregate/src/macros.rs b/datafusion/functions-aggregate/src/macros.rsindex 18f27c3c4a..6c6bf72838 100644--- a/datafusion/functions-aggregate/src/macros.rs+++ b/datafusion/functions-aggregate/src/macros.rs@@ -28,7 +28,7 @@ macro_rules! make_udaf_expr {vec![$($arg),*],false,None,- None,+ vec![],None,))}@@ -52,7 +52,7 @@ macro_rules! make_udaf_expr_and_func {args,false,None,- None,+ vec![],None,))}diff --git a/datafusion/optimizer/src/analyzer/type_coercion.rs b/datafusion/optimizer/src/analyzer/type_coercion.rsindex b5a3e9a2d5..a98b0fdcc3 100644--- a/datafusion/optimizer/src/analyzer/type_coercion.rs+++ b/datafusion/optimizer/src/analyzer/type_coercion.rs@@ -1597,7 +1597,7 @@ mod test {vec![lit(10i64)],false,None,- None,+ vec![],None,));let plan = LogicalPlan::Projection(Projection::try_new(vec![udaf], empty)?);@@ -1632,7 +1632,7 @@ mod test {vec![lit("10")],false,None,- None,+ vec![],None,));@@ -1651,7 +1651,7 @@ mod test {vec![lit(12f64)],false,None,- None,+ vec![],None,));let plan = LogicalPlan::Projection(Projection::try_new(vec![agg_expr], empty)?);@@ -1670,7 +1670,7 @@ mod test {vec![cast(col("a"), DataType::Float64)],false,None,- None,+ vec![],None,));let plan = LogicalPlan::Projection(Projection::try_new(vec![agg_expr], empty)?);@@ -1692,7 +1692,7 @@ mod test {vec![lit("1")],false,None,- None,+ vec![],None,));let err = Projection::try_new(vec![agg_expr], empty)@@ -1727,7 +1727,7 @@ mod test {let empty = empty_with_type(DataType::Int64);let plan = LogicalPlan::Projection(Projection::try_new(vec![expr], empty)?);assert_analyzed_plan_eq!(- plan,+ plan,@r"Projection: a IN ([CAST(Int32(1) AS Int64), CAST(Int8(4) AS Int64), Int64(8)])EmptyRelation@@ -1744,7 +1744,7 @@ mod test {}));let plan = LogicalPlan::Projection(Projection::try_new(vec![expr], empty)?);assert_analyzed_plan_eq!(- plan,+ plan,@r"Projection: CAST(a AS Decimal128(24, 4)) IN ([CAST(Int32(1) AS Decimal128(24, 4)), CAST(Int8(4) AS Decimal128(24, 4)), CAST(Int64(8) AS Decimal128(24, 4))])EmptyRelationdiff --git a/datafusion/optimizer/src/common_subexpr_eliminate.rs b/datafusion/optimizer/src/common_subexpr_eliminate.rsindex 6a49e5d220..88d51e1ade 100644--- a/datafusion/optimizer/src/common_subexpr_eliminate.rs+++ b/datafusion/optimizer/src/common_subexpr_eliminate.rs@@ -909,7 +909,7 @@ mod test {vec![inner],false,None,- None,+ vec![],None,))};diff --git a/datafusion/optimizer/src/simplify_expressions/expr_simplifier.rs b/datafusion/optimizer/src/simplify_expressions/expr_simplifier.rsindex 26ac4a30b7..ac58bc8db3 100644--- a/datafusion/optimizer/src/simplify_expressions/expr_simplifier.rs+++ b/datafusion/optimizer/src/simplify_expressions/expr_simplifier.rs@@ -4322,7 +4322,7 @@ mod tests {vec![],false,None,- None,+ vec![],None,));@@ -4336,7 +4336,7 @@ mod tests {vec![],false,None,- None,+ vec![],None,));diff --git a/datafusion/optimizer/src/single_distinct_to_groupby.rs b/datafusion/optimizer/src/single_distinct_to_groupby.rsindex 50783a2143..e9a23c7c4d 100644--- a/datafusion/optimizer/src/single_distinct_to_groupby.rs+++ b/datafusion/optimizer/src/single_distinct_to_groupby.rs@@ -79,7 +79,7 @@ fn is_single_distinct_agg(aggr_expr: &[Expr]) -> Result<bool> {},}) = expr{- if filter.is_some() || order_by.is_some() {+ if filter.is_some() || !order_by.is_empty() {return Ok(false);}aggregate_count += 1;@@ -200,7 +200,7 @@ impl OptimizerRule for SingleDistinctToGroupBy {vec![col(SINGLE_DISTINCT_ALIAS)],false, // intentional to remove distinct hereNone,- None,+ vec![],None,)))// if the aggregate function is not distinct, we need to rewrite it like two phase aggregation@@ -213,7 +213,7 @@ impl OptimizerRule for SingleDistinctToGroupBy {args,false,None,- None,+ vec![],None,)).alias(&alias_str),@@ -223,7 +223,7 @@ impl OptimizerRule for SingleDistinctToGroupBy {vec![col(&alias_str)],false,None,- None,+ vec![],None,)))}@@ -296,7 +296,7 @@ mod tests {vec![expr],true,None,- None,+ vec![],None,))}@@ -627,7 +627,7 @@ mod tests {vec![col("a")],false,Some(Box::new(col("a").gt(lit(5)))),- None,+ vec![],None,));let plan = LogicalPlanBuilder::from(table_scan)@@ -678,7 +678,7 @@ mod tests {vec![col("a")],false,None,- Some(vec![col("a").sort(true, false)]),+ vec![col("a").sort(true, false)],None,));let plan = LogicalPlanBuilder::from(table_scan)diff --git a/datafusion/proto/src/logical_plan/from_proto.rs b/datafusion/proto/src/logical_plan/from_proto.rsindex 66ef0ebfe3..6c5b348698 100644--- a/datafusion/proto/src/logical_plan/from_proto.rs+++ b/datafusion/proto/src/logical_plan/from_proto.rs@@ -576,10 +576,7 @@ pub fn parse_expr(parse_exprs(&pb.args, registry, codec)?,pb.distinct,parse_optional_expr(pb.filter.as_deref(), registry, codec)?.map(Box::new),- match pb.order_by.len() {- 0 => None,- _ => Some(parse_sorts(&pb.order_by, registry, codec)?),- },+ parse_sorts(&pb.order_by, registry, codec)?,None,)))}diff --git a/datafusion/proto/src/logical_plan/to_proto.rs b/datafusion/proto/src/logical_plan/to_proto.rsindex b14ad7aadf..43afaa0fbe 100644--- a/datafusion/proto/src/logical_plan/to_proto.rs+++ b/datafusion/proto/src/logical_plan/to_proto.rs@@ -374,10 +374,7 @@ pub fn serialize_expr(Some(e) => Some(Box::new(serialize_expr(e.as_ref(), codec)?)),None => None,},- order_by: match order_by {- Some(e) => serialize_sorts(e, codec)?,- None => vec![],- },+ order_by: serialize_sorts(order_by, codec)?,fun_definition: (!buf.is_empty()).then_some(buf),},))),diff --git a/datafusion/proto/tests/cases/roundtrip_logical_plan.rs b/datafusion/proto/tests/cases/roundtrip_logical_plan.rsindex 993cc6f87c..12c05cfcb5 100644--- a/datafusion/proto/tests/cases/roundtrip_logical_plan.rs+++ b/datafusion/proto/tests/cases/roundtrip_logical_plan.rs@@ -960,8 +960,8 @@ async fn roundtrip_expr_api() -> Result<()> {array_replace_all(make_array(vec![lit(1), lit(2), lit(3)]), lit(2), lit(4)),count(lit(1)),count_distinct(lit(1)),- first_value(lit(1), None),- first_value(lit(1), Some(vec![lit(2).sort(true, true)])),+ first_value(lit(1), vec![]),+ first_value(lit(1), vec![lit(2).sort(true, true)]),functions_window::nth_value::first_value(lit(1)),functions_window::nth_value::last_value(lit(1)),functions_window::nth_value::nth_value(lit(1), 1),@@ -2181,7 +2181,7 @@ fn roundtrip_aggregate_udf() {vec![lit(1.0_f64)],false,Some(Box::new(lit(true))),- None,+ vec![],None,));diff --git a/datafusion/sql/src/expr/function.rs b/datafusion/sql/src/expr/function.rsindex d0cb4263db..91587bda52 100644--- a/datafusion/sql/src/expr/function.rs+++ b/datafusion/sql/src/expr/function.rs@@ -406,21 +406,20 @@ impl<S: ContextProvider> SqlToRel<'_, S> {.chain(args).collect::<Vec<_>>();}- (!within_group.is_empty()).then_some(within_group)+ within_group} else {let order_by = if !order_by.is_empty() {order_by} else {within_group};- let order_by = self.order_by_to_sort_expr(+ self.order_by_to_sort_expr(order_by,schema,planner_context,true,None,- )?;- (!order_by.is_empty()).then_some(order_by)+ )?};let filter: Option<Box<Expr>> = filterdiff --git a/datafusion/sql/src/unparser/expr.rs b/datafusion/sql/src/unparser/expr.rsindex 729c6f235b..4ddd5ccccb 100644--- a/datafusion/sql/src/unparser/expr.rs+++ b/datafusion/sql/src/unparser/expr.rs@@ -322,16 +322,15 @@ impl Unparser<'_> {Some(filter) => Some(Box::new(self.expr_to_sql_inner(filter)?)),None => None,};- let within_group = if agg.func.is_ordered_set_aggregate() {- order_by- .as_ref()- .unwrap_or(&Vec::new())- .iter()- .map(|sort_expr| self.sort_to_sql(sort_expr))- .collect::<Result<Vec<_>>>()?- } else {- Vec::new()- };+ let within_group: Vec<ast::OrderByExpr> =+ if agg.func.is_ordered_set_aggregate() {+ order_by+ .iter()+ .map(|sort_expr| self.sort_to_sql(sort_expr))+ .collect::<Result<Vec<ast::OrderByExpr>>>()?+ } else {+ Vec::new()+ };Ok(ast::Expr::Function(Function {name: ObjectName::from(vec![Ident {value: func_name.to_string(),diff --git a/datafusion/substrait/src/logical_plan/consumer/expr/aggregate_function.rs b/datafusion/substrait/src/logical_plan/consumer/expr/aggregate_function.rsindex 114fe1e7ae..62e140acc2 100644--- a/datafusion/substrait/src/logical_plan/consumer/expr/aggregate_function.rs+++ b/datafusion/substrait/src/logical_plan/consumer/expr/aggregate_function.rs@@ -30,7 +30,7 @@ pub async fn from_substrait_agg_func(f: &AggregateFunction,input_schema: &DFSchema,filter: Option<Box<Expr>>,- order_by: Option<Vec<SortExpr>>,+ order_by: Vec<SortExpr>,distinct: bool,) -> datafusion::common::Result<Arc<Expr>> {let Some(fn_signature) = consumerdiff --git a/datafusion/substrait/src/logical_plan/consumer/rel/aggregate_rel.rs b/datafusion/substrait/src/logical_plan/consumer/rel/aggregate_rel.rsindex 9421bb17c1..c919bd0389 100644--- a/datafusion/substrait/src/logical_plan/consumer/rel/aggregate_rel.rs+++ b/datafusion/substrait/src/logical_plan/consumer/rel/aggregate_rel.rs@@ -88,14 +88,8 @@ pub async fn from_aggregate_rel(_ if f.invocation == AggregationInvocation::All as i32 => false,_ => false,};- let order_by = if !f.sorts.is_empty() {- Some(- from_substrait_sorts(consumer, &f.sorts, input.schema())- .await?,- )- } else {- None- };+ let order_by =+ from_substrait_sorts(consumer, &f.sorts, input.schema()).await?;from_substrait_agg_func(consumer,diff --git a/datafusion/substrait/src/logical_plan/producer/expr/aggregate_function.rs b/datafusion/substrait/src/logical_plan/producer/expr/aggregate_function.rsindex 0619b49753..1e79897a1b 100644--- a/datafusion/substrait/src/logical_plan/producer/expr/aggregate_function.rs+++ b/datafusion/substrait/src/logical_plan/producer/expr/aggregate_function.rs@@ -43,14 +43,10 @@ pub fn from_aggregate_function(null_treatment: _null_treatment,},} = agg_fn;- let sorts = if let Some(order_by) = order_by {- order_by- .iter()- .map(|expr| to_substrait_sort_field(producer, expr, schema))- .collect::<datafusion::common::Result<Vec<_>>>()?- } else {- vec![]- };+ let sorts = order_by+ .iter()+ .map(|expr| to_substrait_sort_field(producer, expr, schema))+ .collect::<datafusion::common::Result<Vec<_>>>()?;let mut arguments: Vec<FunctionArgument> = vec![];for arg in args {arguments.push(FunctionArgument {