alamb commented on code in PR #10354: URL: https://github.com/apache/datafusion/pull/10354#discussion_r1591437235
########## datafusion/optimizer/src/simplify_expressions/expr_simplifier.rs: ########## @@ -1307,6 +1309,39 @@ impl<'a, S: SimplifyInfo> TreeNodeRewriter for Simplifier<'a, S> { ExprSimplifyResult::Simplified(expr) => Transformed::yes(expr), }, + Expr::AggregateFunction(AggregateFunction { Review Comment: It seems like in order to be able to make this API avoid copying, it would need to pass the `distinct`, `filter`, etc fields in and then get them back Another thing we could do is to use `Transformed` directly What if we made something like ```rust struct AggregateFunctionsArgs { args: Vec<Expr>, distinct: bool, filter: Option<Expr>, order_by: ... } ``` And then the call to simplify to be ```rust trait AggreagateUDFImpl { ... fn simplify( &self, agg_args: AggregateFunctionsArgs, ) -> Result<Transformed<AggregateFunctionsArgs> { Ok(Transformed::no(agg_args)) } ``` ########## datafusion/expr/src/udaf.rs: ########## @@ -195,6 +197,21 @@ impl AggregateUDF { pub fn create_groups_accumulator(&self) -> Result<Box<dyn GroupsAccumulator>> { self.inner.create_groups_accumulator() } + /// Do the function rewrite + /// + /// See [`AggregateUDFImpl::simplify`] for more details. + pub fn simplify( + &self, + args: Vec<Expr>, Review Comment: One benefit is that we could potentially add new fields without causing an API change 🤔 Another benefit could be that we could add a default method that recreated the expression. For example ```rust impl AggegateArgs { // recreate the original aggregate fucntions fn into_expr(self) -> Expr { ... } ... } ``` Another benefit is, as @jayzhan211 says, that it would be more consistent with the other APIs ########## datafusion-examples/examples/simplify_udaf_expression.rs: ########## @@ -0,0 +1,185 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +use arrow_schema::{Field, Schema}; +use datafusion::{arrow::datatypes::DataType, logical_expr::Volatility}; +use datafusion_expr::simplify::SimplifyInfo; + +use std::{any::Any, sync::Arc}; + +use datafusion::arrow::{array::Float32Array, record_batch::RecordBatch}; +use datafusion::error::Result; +use datafusion::{assert_batches_eq, prelude::*}; +use datafusion_common::cast::as_float64_array; +use datafusion_expr::{ + expr::{AggregateFunction, AggregateFunctionDefinition}, + function::AccumulatorArgs, + simplify::ExprSimplifyResult, + Accumulator, AggregateUDF, AggregateUDFImpl, GroupsAccumulator, Signature, +}; + +/// This example shows how to use the AggregateUDFImpl::simplify API to simplify/replace user +/// defined aggregate function with a different expression which is defined in the `simplify` method. + +#[derive(Debug, Clone)] +struct BetterAvgUdaf { + signature: Signature, +} + +impl BetterAvgUdaf { + /// Create a new instance of the GeoMeanUdaf struct + fn new() -> Self { + Self { + signature: Signature::exact(vec![DataType::Float64], Volatility::Immutable), + } + } +} + +impl AggregateUDFImpl for BetterAvgUdaf { + fn as_any(&self) -> &dyn Any { + self + } + + fn name(&self) -> &str { + "better_avg" + } + + fn signature(&self) -> &Signature { + &self.signature + } + + fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> { + Ok(DataType::Float64) + } + + fn accumulator(&self, _acc_args: AccumulatorArgs) -> Result<Box<dyn Accumulator>> { + unimplemented!("should not be invoked") + } + + fn state_fields( + &self, + _name: &str, + _value_type: DataType, + _ordering_fields: Vec<arrow_schema::Field>, + ) -> Result<Vec<arrow_schema::Field>> { + unimplemented!("should not be invoked") + } + + fn groups_accumulator_supported(&self) -> bool { + true + } + + fn create_groups_accumulator(&self) -> Result<Box<dyn GroupsAccumulator>> { + unimplemented!("should not get here"); + } + // we override method, to return new expression which would substitute + // user defined function call + fn simplify( + &self, + args: Vec<Expr>, + distinct: &bool, Review Comment: Given the work we have been doing on https://github.com/apache/datafusion/issues/9637 let's not add an API that forces cloning Another potential thing is to use [`Transformed`](https://github.com/apache/datafusion/blob/89443bff20015ef6c7646ca32754ece8c4093910/datafusion/common/src/tree_node.rs#L583-L606) directlt -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: github-unsubscr...@datafusion.apache.org For queries about this service, please contact Infrastructure at: us...@infra.apache.org --------------------------------------------------------------------- To unsubscribe, e-mail: github-unsubscr...@datafusion.apache.org For additional commands, e-mail: github-h...@datafusion.apache.org