Skip to content

Commit 3b390d7

Browse files
authored
Refactor avg & sum signatures away from user defined (#18769)
## Which issue does this PR close? <!-- We generally require a GitHub issue to be filed for all bug fixes and enhancements and this helps us generate change logs for our releases. You can link an issue to this PR using the GitHub syntax. For example `Closes #123` indicates that this PR will close issue #123. --> Part of #12725 ## Rationale for this change <!-- Why are you proposing this change? If this is already explained clearly in the issue then this section is not needed. Explaining clearly why changes are proposed helps reviewers understand your changes and offer better suggestions for fixes. --> Prefer to avoid user_defined for consistency in function definitions. ## What changes are included in this PR? <!-- There is no need to duplicate the description in the issue here but it is sometimes worth providing a summary of the individual changes in this PR. --> Refactor signature of avg & sum away from user_defined. ## Are these changes tested? <!-- We typically require tests for all PRs in order to: 1. Prevent the code from being accidentally broken by subsequent changes 2. Serve as another way to document the expected behavior of the code If tests are not included in your PR, please explain why (for example, are they covered by existing tests)? --> Existing tests. ## Are there any user-facing changes? <!-- If there are user-facing changes then we may require documentation to be updated before approving the PR. --> No. <!-- If there are any breaking changes to public APIs, please add the `api change` label. -->
1 parent 5b0aa37 commit 3b390d7

File tree

3 files changed

+91
-109
lines changed

3 files changed

+91
-109
lines changed

datafusion/functions-aggregate/src/average.rs

Lines changed: 23 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -31,26 +31,22 @@ use arrow::datatypes::{
3131
DECIMAL256_MAX_SCALE, DECIMAL32_MAX_PRECISION, DECIMAL32_MAX_SCALE,
3232
DECIMAL64_MAX_PRECISION, DECIMAL64_MAX_SCALE,
3333
};
34-
use datafusion_common::plan_err;
35-
use datafusion_common::{
36-
exec_err, not_impl_err, utils::take_function_args, Result, ScalarValue,
37-
};
34+
use datafusion_common::types::{logical_float64, NativeType};
35+
use datafusion_common::{exec_err, not_impl_err, Result, ScalarValue};
3836
use datafusion_expr::function::{AccumulatorArgs, StateFieldsArgs};
3937
use datafusion_expr::utils::format_state_name;
40-
use datafusion_expr::Volatility::Immutable;
4138
use datafusion_expr::{
42-
Accumulator, AggregateUDFImpl, Documentation, EmitTo, Expr, GroupsAccumulator,
43-
ReversedUDAF, Signature,
39+
Accumulator, AggregateUDFImpl, Coercion, Documentation, EmitTo, Expr,
40+
GroupsAccumulator, ReversedUDAF, Signature, TypeSignature, TypeSignatureClass,
41+
Volatility,
4442
};
45-
4643
use datafusion_functions_aggregate_common::aggregate::avg_distinct::{
4744
DecimalDistinctAvgAccumulator, Float64DistinctAvgAccumulator,
4845
};
4946
use datafusion_functions_aggregate_common::aggregate::groups_accumulator::accumulate::NullState;
5047
use datafusion_functions_aggregate_common::aggregate::groups_accumulator::nulls::{
5148
filtered_null_mask, set_nulls,
5249
};
53-
5450
use datafusion_functions_aggregate_common::utils::DecimalAverager;
5551
use datafusion_macros::user_doc;
5652
use log::debug;
@@ -101,7 +97,24 @@ pub struct Avg {
10197
impl Avg {
10298
pub fn new() -> Self {
10399
Self {
104-
signature: Signature::user_defined(Immutable),
100+
// Supported types smallint, int, bigint, real, double precision, decimal, or interval
101+
// Refer to https://www.postgresql.org/docs/8.2/functions-aggregate.html doc
102+
signature: Signature::one_of(
103+
vec![
104+
TypeSignature::Coercible(vec![Coercion::new_exact(
105+
TypeSignatureClass::Decimal,
106+
)]),
107+
TypeSignature::Coercible(vec![Coercion::new_exact(
108+
TypeSignatureClass::Duration,
109+
)]),
110+
TypeSignature::Coercible(vec![Coercion::new_implicit(
111+
TypeSignatureClass::Native(logical_float64()),
112+
vec![TypeSignatureClass::Integer, TypeSignatureClass::Float],
113+
NativeType::Float64,
114+
)]),
115+
],
116+
Volatility::Immutable,
117+
),
105118
aliases: vec![String::from("mean")],
106119
}
107120
}
@@ -126,28 +139,6 @@ impl AggregateUDFImpl for Avg {
126139
&self.signature
127140
}
128141

129-
fn coerce_types(&self, arg_types: &[DataType]) -> Result<Vec<DataType>> {
130-
let [args] = take_function_args(self.name(), arg_types)?;
131-
132-
// Supported types smallint, int, bigint, real, double precision, decimal, or interval
133-
// Refer to https://www.postgresql.org/docs/8.2/functions-aggregate.html doc
134-
fn coerced_type(data_type: &DataType) -> Result<DataType> {
135-
match &data_type {
136-
DataType::Decimal32(p, s) => Ok(DataType::Decimal32(*p, *s)),
137-
DataType::Decimal64(p, s) => Ok(DataType::Decimal64(*p, *s)),
138-
DataType::Decimal128(p, s) => Ok(DataType::Decimal128(*p, *s)),
139-
DataType::Decimal256(p, s) => Ok(DataType::Decimal256(*p, *s)),
140-
d if d.is_numeric() => Ok(DataType::Float64),
141-
DataType::Duration(time_unit) => Ok(DataType::Duration(*time_unit)),
142-
DataType::Dictionary(_, v) => coerced_type(v.as_ref()),
143-
_ => {
144-
plan_err!("Avg does not support inputs of type {data_type}.")
145-
}
146-
}
147-
}
148-
Ok(vec![coerced_type(args)?])
149-
}
150-
151142
fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
152143
match &arg_types[0] {
153144
DataType::Decimal32(precision, scale) => {

datafusion/functions-aggregate/src/sum.rs

Lines changed: 55 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -18,35 +18,31 @@
1818
//! Defines `SUM` and `SUM DISTINCT` aggregate accumulators
1919
2020
use ahash::RandomState;
21-
use arrow::datatypes::DECIMAL32_MAX_PRECISION;
22-
use arrow::datatypes::DECIMAL64_MAX_PRECISION;
23-
use datafusion_expr::utils::AggregateOrderSensitivity;
24-
use datafusion_expr::Expr;
25-
use std::any::Any;
26-
use std::mem::size_of_val;
27-
28-
use arrow::array::Array;
29-
use arrow::array::ArrowNativeTypeOp;
30-
use arrow::array::{ArrowNumericType, AsArray};
31-
use arrow::datatypes::{ArrowNativeType, FieldRef};
21+
use arrow::array::{Array, ArrayRef, ArrowNativeTypeOp, ArrowNumericType, AsArray};
22+
use arrow::datatypes::Field;
3223
use arrow::datatypes::{
33-
DataType, Decimal128Type, Decimal256Type, Decimal32Type, Decimal64Type, Float64Type,
34-
Int64Type, UInt64Type, DECIMAL128_MAX_PRECISION, DECIMAL256_MAX_PRECISION,
24+
ArrowNativeType, DataType, Decimal128Type, Decimal256Type, Decimal32Type,
25+
Decimal64Type, FieldRef, Float64Type, Int64Type, UInt64Type,
26+
DECIMAL128_MAX_PRECISION, DECIMAL256_MAX_PRECISION, DECIMAL32_MAX_PRECISION,
27+
DECIMAL64_MAX_PRECISION,
3528
};
36-
use arrow::{array::ArrayRef, datatypes::Field};
37-
use datafusion_common::{
38-
exec_err, not_impl_err, utils::take_function_args, HashMap, Result, ScalarValue,
29+
use datafusion_common::types::{
30+
logical_float64, logical_int16, logical_int32, logical_int64, logical_int8,
31+
logical_uint16, logical_uint32, logical_uint64, logical_uint8, NativeType,
3932
};
40-
use datafusion_expr::function::AccumulatorArgs;
41-
use datafusion_expr::function::StateFieldsArgs;
42-
use datafusion_expr::utils::format_state_name;
33+
use datafusion_common::{exec_err, not_impl_err, HashMap, Result, ScalarValue};
34+
use datafusion_expr::function::{AccumulatorArgs, StateFieldsArgs};
35+
use datafusion_expr::utils::{format_state_name, AggregateOrderSensitivity};
4336
use datafusion_expr::{
44-
Accumulator, AggregateUDFImpl, Documentation, GroupsAccumulator, ReversedUDAF,
45-
SetMonotonicity, Signature, Volatility,
37+
Accumulator, AggregateUDFImpl, Coercion, Documentation, Expr, GroupsAccumulator,
38+
ReversedUDAF, SetMonotonicity, Signature, TypeSignature, TypeSignatureClass,
39+
Volatility,
4640
};
4741
use datafusion_functions_aggregate_common::aggregate::groups_accumulator::prim_op::PrimitiveGroupsAccumulator;
4842
use datafusion_functions_aggregate_common::aggregate::sum_distinct::DistinctSumAccumulator;
4943
use datafusion_macros::user_doc;
44+
use std::any::Any;
45+
use std::mem::size_of_val;
5046

5147
make_udaf_expr_and_func!(
5248
Sum,
@@ -130,7 +126,42 @@ pub struct Sum {
130126
impl Sum {
131127
pub fn new() -> Self {
132128
Self {
133-
signature: Signature::user_defined(Volatility::Immutable),
129+
// Refer to https://www.postgresql.org/docs/8.2/functions-aggregate.html doc
130+
// smallint, int, bigint, real, double precision, decimal, or interval.
131+
signature: Signature::one_of(
132+
vec![
133+
TypeSignature::Coercible(vec![Coercion::new_exact(
134+
TypeSignatureClass::Decimal,
135+
)]),
136+
// Unsigned to u64
137+
TypeSignature::Coercible(vec![Coercion::new_implicit(
138+
TypeSignatureClass::Native(logical_uint64()),
139+
vec![
140+
TypeSignatureClass::Native(logical_uint8()),
141+
TypeSignatureClass::Native(logical_uint16()),
142+
TypeSignatureClass::Native(logical_uint32()),
143+
],
144+
NativeType::UInt64,
145+
)]),
146+
// Signed to i64
147+
TypeSignature::Coercible(vec![Coercion::new_implicit(
148+
TypeSignatureClass::Native(logical_int64()),
149+
vec![
150+
TypeSignatureClass::Native(logical_int8()),
151+
TypeSignatureClass::Native(logical_int16()),
152+
TypeSignatureClass::Native(logical_int32()),
153+
],
154+
NativeType::Int64,
155+
)]),
156+
// Floats to f64
157+
TypeSignature::Coercible(vec![Coercion::new_implicit(
158+
TypeSignatureClass::Native(logical_float64()),
159+
vec![TypeSignatureClass::Float],
160+
NativeType::Float64,
161+
)]),
162+
],
163+
Volatility::Immutable,
164+
),
134165
}
135166
}
136167
}
@@ -154,57 +185,26 @@ impl AggregateUDFImpl for Sum {
154185
&self.signature
155186
}
156187

157-
fn coerce_types(&self, arg_types: &[DataType]) -> Result<Vec<DataType>> {
158-
let [args] = take_function_args(self.name(), arg_types)?;
159-
160-
// Refer to https://www.postgresql.org/docs/8.2/functions-aggregate.html doc
161-
// smallint, int, bigint, real, double precision, decimal, or interval.
162-
163-
fn coerced_type(data_type: &DataType) -> Result<DataType> {
164-
match data_type {
165-
DataType::Dictionary(_, v) => coerced_type(v),
166-
// in the spark, the result type is DECIMAL(min(38,precision+10), s)
167-
// ref: https://github.com/apache/spark/blob/fcf636d9eb8d645c24be3db2d599aba2d7e2955a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/aggregate/Sum.scala#L66
168-
DataType::Decimal32(_, _)
169-
| DataType::Decimal64(_, _)
170-
| DataType::Decimal128(_, _)
171-
| DataType::Decimal256(_, _) => Ok(data_type.clone()),
172-
dt if dt.is_signed_integer() => Ok(DataType::Int64),
173-
dt if dt.is_unsigned_integer() => Ok(DataType::UInt64),
174-
dt if dt.is_floating() => Ok(DataType::Float64),
175-
_ => exec_err!("Sum not supported for {data_type}"),
176-
}
177-
}
178-
179-
Ok(vec![coerced_type(args)?])
180-
}
181-
182188
fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
183189
match &arg_types[0] {
184190
DataType::Int64 => Ok(DataType::Int64),
185191
DataType::UInt64 => Ok(DataType::UInt64),
186192
DataType::Float64 => Ok(DataType::Float64),
193+
// In the spark, the result type is DECIMAL(min(38,precision+10), s)
194+
// ref: https://github.com/apache/spark/blob/fcf636d9eb8d645c24be3db2d599aba2d7e2955a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/aggregate/Sum.scala#L66
187195
DataType::Decimal32(precision, scale) => {
188-
// in the spark, the result type is DECIMAL(min(38,precision+10), s)
189-
// ref: https://github.com/apache/spark/blob/fcf636d9eb8d645c24be3db2d599aba2d7e2955a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/aggregate/Sum.scala#L66
190196
let new_precision = DECIMAL32_MAX_PRECISION.min(*precision + 10);
191197
Ok(DataType::Decimal32(new_precision, *scale))
192198
}
193199
DataType::Decimal64(precision, scale) => {
194-
// in the spark, the result type is DECIMAL(min(38,precision+10), s)
195-
// ref: https://github.com/apache/spark/blob/fcf636d9eb8d645c24be3db2d599aba2d7e2955a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/aggregate/Sum.scala#L66
196200
let new_precision = DECIMAL64_MAX_PRECISION.min(*precision + 10);
197201
Ok(DataType::Decimal64(new_precision, *scale))
198202
}
199203
DataType::Decimal128(precision, scale) => {
200-
// in the spark, the result type is DECIMAL(min(38,precision+10), s)
201-
// ref: https://github.com/apache/spark/blob/fcf636d9eb8d645c24be3db2d599aba2d7e2955a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/aggregate/Sum.scala#L66
202204
let new_precision = DECIMAL128_MAX_PRECISION.min(*precision + 10);
203205
Ok(DataType::Decimal128(new_precision, *scale))
204206
}
205207
DataType::Decimal256(precision, scale) => {
206-
// in the spark, the result type is DECIMAL(min(38,precision+10), s)
207-
// ref: https://github.com/apache/spark/blob/fcf636d9eb8d645c24be3db2d599aba2d7e2955a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/aggregate/Sum.scala#L66
208208
let new_precision = DECIMAL256_MAX_PRECISION.min(*precision + 10);
209209
Ok(DataType::Decimal256(new_precision, *scale))
210210
}

datafusion/spark/src/function/aggregate/avg.rs

Lines changed: 13 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -15,22 +15,21 @@
1515
// specific language governing permissions and limitations
1616
// under the License.
1717

18-
use arrow::array::ArrowNativeTypeOp;
1918
use arrow::array::{
2019
builder::PrimitiveBuilder,
2120
cast::AsArray,
2221
types::{Float64Type, Int64Type},
23-
Array, ArrayRef, ArrowNumericType, Int64Array, PrimitiveArray,
22+
Array, ArrayRef, ArrowNativeTypeOp, ArrowNumericType, Int64Array, PrimitiveArray,
2423
};
2524
use arrow::compute::sum;
2625
use arrow::datatypes::{DataType, Field, FieldRef};
27-
use datafusion_common::utils::take_function_args;
28-
use datafusion_common::{not_impl_err, plan_err, Result, ScalarValue};
26+
use datafusion_common::types::{logical_float64, NativeType};
27+
use datafusion_common::{not_impl_err, Result, ScalarValue};
2928
use datafusion_expr::function::{AccumulatorArgs, StateFieldsArgs};
3029
use datafusion_expr::utils::format_state_name;
31-
use datafusion_expr::Volatility::Immutable;
3230
use datafusion_expr::{
33-
Accumulator, AggregateUDFImpl, EmitTo, GroupsAccumulator, ReversedUDAF, Signature,
31+
Accumulator, AggregateUDFImpl, Coercion, EmitTo, GroupsAccumulator, ReversedUDAF,
32+
Signature, TypeSignatureClass, Volatility,
3433
};
3534
use std::{any::Any, sync::Arc};
3635

@@ -56,7 +55,14 @@ impl SparkAvg {
5655
/// Implement AVG aggregate function
5756
pub fn new() -> Self {
5857
Self {
59-
signature: Signature::user_defined(Immutable),
58+
signature: Signature::coercible(
59+
vec![Coercion::new_implicit(
60+
TypeSignatureClass::Native(logical_float64()),
61+
vec![TypeSignatureClass::Numeric],
62+
NativeType::Float64,
63+
)],
64+
Volatility::Immutable,
65+
),
6066
}
6167
}
6268
}
@@ -66,21 +72,6 @@ impl AggregateUDFImpl for SparkAvg {
6672
self
6773
}
6874

69-
fn coerce_types(&self, arg_types: &[DataType]) -> Result<Vec<DataType>> {
70-
let [args] = take_function_args(self.name(), arg_types)?;
71-
72-
fn coerced_type(data_type: &DataType) -> Result<DataType> {
73-
match &data_type {
74-
d if d.is_numeric() => Ok(DataType::Float64),
75-
DataType::Dictionary(_, v) => coerced_type(v.as_ref()),
76-
_ => {
77-
plan_err!("Avg does not support inputs of type {data_type}.")
78-
}
79-
}
80-
}
81-
Ok(vec![coerced_type(args)?])
82-
}
83-
8475
fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
8576
Ok(DataType::Float64)
8677
}

0 commit comments

Comments
 (0)