Skip to content

Apache DataFusion SQL Query Engine

refactor: use a common macro to define math UDFs (#9598)

Jonah Gao60f65149b0d1
diff --git a/datafusion/functions/src/macros.rs b/datafusion/functions/src/macros.rs
index 859964b5b8..e735523df6 100644
--- a/datafusion/functions/src/macros.rs
+++ b/datafusion/functions/src/macros.rs
@@ -146,3 +146,100 @@ macro_rules! downcast_arg {
})?
}};
}
+
+/// Macro to create a unary math UDF.
+///
+/// A unary math function takes an argument of type Float32 or Float64,
+/// applies a unary floating function to the argument, and returns a value of the same type.
+///
+/// $UDF: the name of the UDF struct that implements `ScalarUDFImpl`
+/// $GNAME: a singleton instance of the UDF
+/// $NAME: the name of the function
+/// $UNARY_FUNC: the unary function to apply to the argument
+macro_rules! make_math_unary_udf {
+ ($UDF:ident, $GNAME:ident, $NAME:ident, $UNARY_FUNC:ident) => {
+ make_udf_function!($NAME::$UDF, $GNAME, $NAME);
+
+ mod $NAME {
+ use arrow::array::{ArrayRef, Float32Array, Float64Array};
+ use arrow::datatypes::DataType;
+ use datafusion_common::{exec_err, DataFusionError, Result};
+ use datafusion_expr::{ColumnarValue, ScalarUDFImpl, Signature, Volatility};
+ use std::any::Any;
+ use std::sync::Arc;
+
+ #[derive(Debug)]
+ pub struct $UDF {
+ signature: Signature,
+ }
+
+ impl $UDF {
+ pub fn new() -> Self {
+ use DataType::*;
+ Self {
+ signature: Signature::uniform(
+ 1,
+ vec![Float64, Float32],
+ Volatility::Immutable,
+ ),
+ }
+ }
+ }
+
+ impl ScalarUDFImpl for $UDF {
+ fn as_any(&self) -> &dyn Any {
+ self
+ }
+ fn name(&self) -> &str {
+ stringify!($NAME)
+ }
+
+ fn signature(&self) -> &Signature {
+ &self.signature
+ }
+
+ fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
+ let arg_type = &arg_types[0];
+
+ match arg_type {
+ DataType::Float32 => Ok(DataType::Float32),
+ // For other types (possible values float64/null/int), use Float64
+ _ => Ok(DataType::Float64),
+ }
+ }
+
+ fn invoke(&self, args: &[ColumnarValue]) -> Result<ColumnarValue> {
+ let args = ColumnarValue::values_to_arrays(args)?;
+
+ let arr: ArrayRef = match args[0].data_type() {
+ DataType::Float64 => {
+ Arc::new(make_function_scalar_inputs_return_type!(
+ &args[0],
+ self.name(),
+ Float64Array,
+ Float64Array,
+ { f64::$UNARY_FUNC }
+ ))
+ }
+ DataType::Float32 => {
+ Arc::new(make_function_scalar_inputs_return_type!(
+ &args[0],
+ self.name(),
+ Float32Array,
+ Float32Array,
+ { f32::$UNARY_FUNC }
+ ))
+ }
+ other => {
+ return exec_err!(
+ "Unsupported data type {other:?} for function {}",
+ self.name()
+ )
+ }
+ };
+ Ok(ColumnarValue::Array(arr))
+ }
+ }
+ }
+ };
+}
diff --git a/datafusion/functions/src/math/acos.rs b/datafusion/functions/src/math/acos.rs
deleted file mode 100644
index f6a440beec..0000000000
--- a/datafusion/functions/src/math/acos.rs
+++ /dev/null
@@ -1,97 +0,0 @@
-// 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.
-
-//! Math function: `acos()`.
-
-use arrow::array::{ArrayRef, Float32Array, Float64Array};
-use arrow::datatypes::DataType;
-use datafusion_common::{exec_err, DataFusionError, Result};
-use datafusion_expr::ColumnarValue;
-use datafusion_expr::{ScalarUDFImpl, Signature, Volatility};
-use std::any::Any;
-use std::sync::Arc;
-
-#[derive(Debug)]
-pub struct AcosFunc {
- signature: Signature,
-}
-
-impl AcosFunc {
- pub fn new() -> Self {
- use DataType::*;
- Self {
- signature: Signature::uniform(
- 1,
- vec![Float64, Float32],
- Volatility::Immutable,
- ),
- }
- }
-}
-
-impl ScalarUDFImpl for AcosFunc {
- fn as_any(&self) -> &dyn Any {
- self
- }
- fn name(&self) -> &str {
- "acos"
- }
-
- fn signature(&self) -> &Signature {
- &self.signature
- }
-
- fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
- let arg_type = &arg_types[0];
-
- match arg_type {
- DataType::Float64 => Ok(DataType::Float64),
- DataType::Float32 => Ok(DataType::Float32),
-
- // For other types (possible values null/int), use Float 64
- _ => Ok(DataType::Float64),
- }
- }
-
- fn invoke(&self, args: &[ColumnarValue]) -> Result<ColumnarValue> {
- let args = ColumnarValue::values_to_arrays(args)?;
-
- let arr: ArrayRef = match args[0].data_type() {
- DataType::Float64 => Arc::new(make_function_scalar_inputs_return_type!(
- &args[0],
- self.name(),
- Float64Array,
- Float64Array,
- { f64::acos }
- )),
- DataType::Float32 => Arc::new(make_function_scalar_inputs_return_type!(
- &args[0],
- self.name(),
- Float32Array,
- Float32Array,
- { f32::acos }
- )),
- other => {
- return exec_err!(
- "Unsupported data type {other:?} for function {}",
- self.name()
- )
- }
- };
- Ok(ColumnarValue::Array(arr))
- }
-}
diff --git a/datafusion/functions/src/math/asin.rs b/datafusion/functions/src/math/asin.rs
deleted file mode 100644
index f34bf56840..0000000000
--- a/datafusion/functions/src/math/asin.rs
+++ /dev/null
@@ -1,110 +0,0 @@
-// 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.
-
-//! Math function: `asin()`.
-
-use arrow::array::{ArrayRef, Float32Array, Float64Array};
-use arrow::datatypes::DataType;
-use datafusion_common::{exec_err, plan_datafusion_err, DataFusionError, Result};
-use datafusion_expr::ColumnarValue;
-use datafusion_expr::{
- utils::generate_signature_error_msg, ScalarUDFImpl, Signature, Volatility,
-};
-use std::any::Any;
-use std::sync::Arc;
-
-#[derive(Debug)]
-pub struct AsinFunc {
- signature: Signature,
-}
-
-impl AsinFunc {
- pub fn new() -> Self {
- use DataType::*;
- Self {
- signature: Signature::uniform(
- 1,
- vec![Float64, Float32],
- Volatility::Immutable,
- ),
- }
- }
-}
-
-impl ScalarUDFImpl for AsinFunc {
- fn as_any(&self) -> &dyn Any {
- self
- }
- fn name(&self) -> &str {
- "asin"
- }
-
- fn signature(&self) -> &Signature {
- &self.signature
- }
-
- fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
- if arg_types.len() != 1 {
- return Err(plan_datafusion_err!(
- "{}",
- generate_signature_error_msg(
- self.name(),
- self.signature().clone(),
- arg_types,
- )
- ));
- }
-
- let arg_type = &arg_types[0];
-
- match arg_type {
- DataType::Float64 => Ok(DataType::Float64),
- DataType::Float32 => Ok(DataType::Float32),
-
- // For other types (possible values null/int), use Float 64
- _ => Ok(DataType::Float64),
- }
- }
-
- fn invoke(&self, args: &[ColumnarValue]) -> Result<ColumnarValue> {
- let args = ColumnarValue::values_to_arrays(args)?;
-
- let arr: ArrayRef = match args[0].data_type() {
- DataType::Float64 => Arc::new(make_function_scalar_inputs_return_type!(
- &args[0],
- self.name(),
- Float64Array,
- Float64Array,
- { f64::asin }
- )),
- DataType::Float32 => Arc::new(make_function_scalar_inputs_return_type!(
- &args[0],
- self.name(),
- Float32Array,
- Float32Array,
- { f32::asin }
- )),
- other => {
- return exec_err!(
- "Unsupported data type {other:?} for function {}",
- self.name()
- )
- }
- };
- Ok(ColumnarValue::Array(arr))
- }
-}
diff --git a/datafusion/functions/src/math/mod.rs b/datafusion/functions/src/math/mod.rs
index e7ede6043a..27deb7d684 100644
--- a/datafusion/functions/src/math/mod.rs
+++ b/datafusion/functions/src/math/mod.rs
@@ -18,19 +18,16 @@
//! "math" DataFusion functions
mod abs;
-mod acos;
-mod asin;
mod nans;
-mod tan;
-mod tanh;
-// create UDFs
+// Create UDFs
make_udf_function!(nans::IsNanFunc, ISNAN, isnan);
make_udf_function!(abs::AbsFunc, ABS, abs);
-make_udf_function!(acos::AcosFunc, ACOS, acos);
-make_udf_function!(asin::AsinFunc, ASIN, asin);
-make_udf_function!(tan::TanFunc, TAN, tan);
-make_udf_function!(tanh::TanhFunc, TANH, tanh);
+
+make_math_unary_udf!(TanhFunc, TANH, tanh, tanh);
+make_math_unary_udf!(AcosFunc, ACOS, acos, acos);
+make_math_unary_udf!(AsinFunc, ASIN, asin, asin);
+make_math_unary_udf!(TanFunc, TAN, tan, tan);
// Export the functions out of this package, both as expr_fn as well as a list of functions
export_functions!(
diff --git a/datafusion/functions/src/math/tan.rs b/datafusion/functions/src/math/tan.rs
deleted file mode 100644
index ea3e002f84..0000000000
--- a/datafusion/functions/src/math/tan.rs
+++ /dev/null
@@ -1,98 +0,0 @@
-// 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.
-
-//! Math function: `tan()`.
-
-use std::any::Any;
-use std::sync::Arc;
-
-use arrow::datatypes::DataType;
-use arrow_array::{ArrayRef, Float32Array, Float64Array};
-use datafusion_common::{exec_err, DataFusionError, Result};
-use datafusion_expr::Volatility;
-use datafusion_expr::{ColumnarValue, ScalarUDFImpl, Signature};
-
-#[derive(Debug)]
-pub struct TanFunc {
- signature: Signature,
-}
-
-impl TanFunc {
- pub fn new() -> Self {
- Self {
- signature: Signature::uniform(
- 1,
- vec![DataType::Float64, DataType::Float32],
- Volatility::Immutable,
- ),
- }
- }
-}
-
-impl ScalarUDFImpl for TanFunc {
- fn as_any(&self) -> &dyn Any {
- self
- }
-
- fn name(&self) -> &str {
- "tan"
- }
-
- fn signature(&self) -> &Signature {
- &self.signature
- }
-
- fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
- let arg_type = &arg_types[0];
-
- match arg_type {
- DataType::Float64 => Ok(DataType::Float64),
- DataType::Float32 => Ok(DataType::Float32),
-
- // For other types (possible values null/int), use Float 64
- _ => Ok(DataType::Float64),
- }
- }
-
- fn invoke(&self, args: &[ColumnarValue]) -> Result<ColumnarValue> {
- let args = ColumnarValue::values_to_arrays(args)?;
-
- let arr: ArrayRef = match args[0].data_type() {
- DataType::Float64 => Arc::new(make_function_scalar_inputs_return_type!(
- &args[0],
- self.name(),
- Float64Array,
- Float64Array,
- { f64::tan }
- )),
- DataType::Float32 => Arc::new(make_function_scalar_inputs_return_type!(
- &args[0],
- self.name(),
- Float32Array,
- Float32Array,
- { f32::tan }
- )),
- other => {
- return exec_err!(
- "Unsupported data type {other:?} for function {}",
- self.name()
- )
- }
- };
- Ok(ColumnarValue::Array(arr))
- }
-}
diff --git a/datafusion/functions/src/math/tanh.rs b/datafusion/functions/src/math/tanh.rs
deleted file mode 100644
index af34681919..0000000000
--- a/datafusion/functions/src/math/tanh.rs
+++ /dev/null
@@ -1,98 +0,0 @@
-// 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.
-
-//! Math function: `tanh()`.
-
-use std::any::Any;
-use std::sync::Arc;
-
-use arrow::datatypes::DataType;
-use arrow_array::{ArrayRef, Float32Array, Float64Array};
-use datafusion_common::{exec_err, DataFusionError, Result};
-use datafusion_expr::Volatility;
-use datafusion_expr::{ColumnarValue, ScalarUDFImpl, Signature};
-
-#[derive(Debug)]
-pub struct TanhFunc {
- signature: Signature,
-}
-
-impl TanhFunc {
- pub fn new() -> Self {
- Self {
- signature: Signature::uniform(
- 1,
- vec![DataType::Float64, DataType::Float32],
- Volatility::Immutable,
- ),
- }
- }
-}
-
-impl ScalarUDFImpl for TanhFunc {
- fn as_any(&self) -> &dyn Any {
- self
- }
-
- fn name(&self) -> &str {
- "tanh"
- }
-
- fn signature(&self) -> &Signature {
- &self.signature
- }
-
- fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
- let arg_type = &arg_types[0];
-
- match arg_type {
- DataType::Float64 => Ok(DataType::Float64),
- DataType::Float32 => Ok(DataType::Float32),
-
- // For other types (possible values null/int), use Float 64
- _ => Ok(DataType::Float64),
- }
- }
-
- fn invoke(&self, args: &[ColumnarValue]) -> Result<ColumnarValue> {
- let args = ColumnarValue::values_to_arrays(args)?;
-
- let arr: ArrayRef = match args[0].data_type() {
- DataType::Float64 => Arc::new(make_function_scalar_inputs_return_type!(
- &args[0],
- self.name(),
- Float64Array,
- Float64Array,
- { f64::tanh }
- )),
- DataType::Float32 => Arc::new(make_function_scalar_inputs_return_type!(
- &args[0],
- self.name(),
- Float32Array,
- Float32Array,
- { f32::tanh }
- )),
- other => {
- return exec_err!(
- "Unsupported data type {other:?} for function {}",
- self.name()
- )
- }
- };
- Ok(ColumnarValue::Array(arr))
- }
-}