Skip to content

Commit b75f1cf

Browse files
committed
refactor: move acos() to function crate
1 parent 544b3d9 commit b75f1cf

File tree

14 files changed

+240
-145
lines changed

14 files changed

+240
-145
lines changed

datafusion-cli/Cargo.lock

Lines changed: 92 additions & 101 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

datafusion/expr/src/built_in_function.rs

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -42,8 +42,6 @@ use strum_macros::EnumIter;
4242
#[derive(Debug, Clone, PartialEq, Eq, Hash, EnumIter, Copy)]
4343
pub enum BuiltinScalarFunction {
4444
// math functions
45-
/// acos
46-
Acos,
4745
/// asin
4846
Asin,
4947
/// atan
@@ -362,7 +360,6 @@ impl BuiltinScalarFunction {
362360
pub fn volatility(&self) -> Volatility {
363361
match self {
364362
// Immutable scalar builtins
365-
BuiltinScalarFunction::Acos => Volatility::Immutable,
366363
BuiltinScalarFunction::Asin => Volatility::Immutable,
367364
BuiltinScalarFunction::Atan => Volatility::Immutable,
368365
BuiltinScalarFunction::Atan2 => Volatility::Immutable,
@@ -873,8 +870,7 @@ impl BuiltinScalarFunction {
873870
utf8_to_int_type(&input_expr_types[0], "levenshtein")
874871
}
875872

876-
BuiltinScalarFunction::Acos
877-
| BuiltinScalarFunction::Asin
873+
BuiltinScalarFunction::Asin
878874
| BuiltinScalarFunction::Atan
879875
| BuiltinScalarFunction::Acosh
880876
| BuiltinScalarFunction::Asinh
@@ -1346,8 +1342,7 @@ impl BuiltinScalarFunction {
13461342
vec![Exact(vec![Utf8, Utf8]), Exact(vec![LargeUtf8, LargeUtf8])],
13471343
self.volatility(),
13481344
),
1349-
BuiltinScalarFunction::Acos
1350-
| BuiltinScalarFunction::Asin
1345+
BuiltinScalarFunction::Asin
13511346
| BuiltinScalarFunction::Atan
13521347
| BuiltinScalarFunction::Acosh
13531348
| BuiltinScalarFunction::Asinh
@@ -1438,7 +1433,6 @@ impl BuiltinScalarFunction {
14381433
/// Returns all names that can be used to call this function
14391434
pub fn aliases(&self) -> &'static [&'static str] {
14401435
match self {
1441-
BuiltinScalarFunction::Acos => &["acos"],
14421436
BuiltinScalarFunction::Acosh => &["acosh"],
14431437
BuiltinScalarFunction::Asin => &["asin"],
14441438
BuiltinScalarFunction::Asinh => &["asinh"],

datafusion/expr/src/expr_fn.rs

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -531,7 +531,6 @@ scalar_expr!(Sinh, sinh, num, "hyperbolic sine");
531531
scalar_expr!(Cosh, cosh, num, "hyperbolic cosine");
532532
scalar_expr!(Tanh, tanh, num, "hyperbolic tangent");
533533
scalar_expr!(Asin, asin, num, "inverse sine");
534-
scalar_expr!(Acos, acos, num, "inverse cosine");
535534
scalar_expr!(Atan, atan, num, "inverse tangent");
536535
scalar_expr!(Asinh, asinh, num, "inverse hyperbolic sine");
537536
scalar_expr!(Acosh, acosh, num, "inverse hyperbolic cosine");
@@ -1339,7 +1338,6 @@ mod test {
13391338
test_unary_scalar_expr!(Cosh, cosh);
13401339
test_unary_scalar_expr!(Tanh, tanh);
13411340
test_unary_scalar_expr!(Asin, asin);
1342-
test_unary_scalar_expr!(Acos, acos);
13431341
test_unary_scalar_expr!(Atan, atan);
13441342
test_unary_scalar_expr!(Asinh, asinh);
13451343
test_unary_scalar_expr!(Acosh, acosh);

datafusion/functions/src/math/acos.rs

Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,110 @@
1+
// Licensed to the Apache Software Foundation (ASF) under one
2+
// or more contributor license agreements. See the NOTICE file
3+
// distributed with this work for additional information
4+
// regarding copyright ownership. The ASF licenses this file
5+
// to you under the Apache License, Version 2.0 (the
6+
// "License"); you may not use this file except in compliance
7+
// with the License. You may obtain a copy of the License at
8+
//
9+
// http://www.apache.org/licenses/LICENSE-2.0
10+
//
11+
// Unless required by applicable law or agreed to in writing,
12+
// software distributed under the License is distributed on an
13+
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14+
// KIND, either express or implied. See the License for the
15+
// specific language governing permissions and limitations
16+
// under the License.
17+
18+
//! Math function: `acos()`.
19+
20+
use arrow::array::{ArrayRef, Float32Array, Float64Array};
21+
use arrow::datatypes::DataType;
22+
use datafusion_common::{exec_err, plan_datafusion_err, DataFusionError, Result};
23+
use datafusion_expr::ColumnarValue;
24+
use datafusion_expr::{
25+
utils::generate_signature_error_msg, ScalarUDFImpl, Signature, Volatility,
26+
};
27+
use std::any::Any;
28+
use std::sync::Arc;
29+
30+
#[derive(Debug)]
31+
pub struct AcosFunc {
32+
signature: Signature,
33+
}
34+
35+
impl AcosFunc {
36+
pub fn new() -> Self {
37+
use DataType::*;
38+
Self {
39+
signature: Signature::uniform(
40+
1,
41+
vec![Float64, Float32],
42+
Volatility::Immutable,
43+
),
44+
}
45+
}
46+
}
47+
48+
impl ScalarUDFImpl for AcosFunc {
49+
fn as_any(&self) -> &dyn Any {
50+
self
51+
}
52+
fn name(&self) -> &str {
53+
"acos"
54+
}
55+
56+
fn signature(&self) -> &Signature {
57+
&self.signature
58+
}
59+
60+
fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
61+
if arg_types.len() != 1 {
62+
return Err(plan_datafusion_err!(
63+
"{}",
64+
generate_signature_error_msg(
65+
self.name(),
66+
self.signature().clone(),
67+
arg_types,
68+
)
69+
));
70+
}
71+
72+
let arg_type = &arg_types[0];
73+
74+
match arg_type {
75+
DataType::Float64 => Ok(DataType::Float64),
76+
DataType::Float32 => Ok(DataType::Float32),
77+
78+
// For other types (possible values null/int), use Float 64
79+
_ => Ok(DataType::Float64),
80+
}
81+
}
82+
83+
fn invoke(&self, args: &[ColumnarValue]) -> Result<ColumnarValue> {
84+
let args = ColumnarValue::values_to_arrays(args)?;
85+
86+
let arr: ArrayRef = match args[0].data_type() {
87+
DataType::Float64 => Arc::new(make_function_scalar_inputs_return_type!(
88+
&args[0],
89+
self.name(),
90+
Float64Array,
91+
Float64Array,
92+
{ f64::acos }
93+
)),
94+
DataType::Float32 => Arc::new(make_function_scalar_inputs_return_type!(
95+
&args[0],
96+
self.name(),
97+
Float32Array,
98+
Float32Array,
99+
{ f32::acos }
100+
)),
101+
other => {
102+
return exec_err!(
103+
"Unsupported data type {other:?} for function {}",
104+
self.name()
105+
)
106+
}
107+
};
108+
Ok(ColumnarValue::Array(arr))
109+
}
110+
}

datafusion/functions/src/math/mod.rs

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,15 +17,26 @@
1717

1818
//! "math" DataFusion functions
1919
20-
mod nans;
2120
mod abs;
21+
mod acos;
22+
mod nans;
2223

2324
// create UDFs
2425
make_udf_function!(nans::IsNanFunc, ISNAN, isnan);
2526
make_udf_function!(abs::AbsFunc, ABS, abs);
27+
make_udf_function!(acos::AcosFunc, ACOS, acos);
2628

2729
// Export the functions out of this package, both as expr_fn as well as a list of functions
2830
export_functions!(
29-
(isnan, num, "returns true if a given number is +NaN or -NaN otherwise returns false"),
30-
(abs, num, "returns the absolute value of a given number")
31-
);
31+
(
32+
isnan,
33+
num,
34+
"returns true if a given number is +NaN or -NaN otherwise returns false"
35+
),
36+
(abs, num, "returns the absolute value of a given number"),
37+
(
38+
acos,
39+
num,
40+
"returns the arc cosine or inverse cosine of a number"
41+
)
42+
);

datafusion/functions/src/math/nans.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
// specific language governing permissions and limitations
1616
// under the License.
1717

18-
//! Encoding expressions
18+
//! Math function: `isnan()`.
1919
2020
use arrow::datatypes::DataType;
2121
use datafusion_common::{exec_err, DataFusionError, Result};

datafusion/optimizer/src/analyzer/type_coercion.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -889,14 +889,14 @@ mod test {
889889
// test that automatic argument type coercion for scalar functions work
890890
let empty = empty();
891891
let lit_expr = lit(10i64);
892-
let fun: BuiltinScalarFunction = BuiltinScalarFunction::Acos;
892+
let fun: BuiltinScalarFunction = BuiltinScalarFunction::Floor;
893893
let scalar_function_expr =
894894
Expr::ScalarFunction(ScalarFunction::new(fun, vec![lit_expr]));
895895
let plan = LogicalPlan::Projection(Projection::try_new(
896896
vec![scalar_function_expr],
897897
empty,
898898
)?);
899-
let expected = "Projection: acos(CAST(Int64(10) AS Float64))\n EmptyRelation";
899+
let expected = "Projection: floor(CAST(Int64(10) AS Float64))\n EmptyRelation";
900900
assert_analyzed_plan_eq(Arc::new(TypeCoercion::new()), &plan, expected)
901901
}
902902

datafusion/physical-expr/src/functions.rs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -261,7 +261,6 @@ pub fn create_physical_fun(
261261
) -> Result<ScalarFunctionImplementation> {
262262
Ok(match fun {
263263
// math functions
264-
BuiltinScalarFunction::Acos => Arc::new(math_expressions::acos),
265264
BuiltinScalarFunction::Asin => Arc::new(math_expressions::asin),
266265
BuiltinScalarFunction::Atan => Arc::new(math_expressions::atan),
267266
BuiltinScalarFunction::Acosh => Arc::new(math_expressions::acosh),

datafusion/proto/proto/datafusion.proto

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -548,7 +548,7 @@ enum ScalarFunction {
548548
// 0 was Abs before
549549
// The first enum value must be zero for open enums
550550
unknown = 0;
551-
Acos = 1;
551+
// 1 was Acos
552552
Asin = 2;
553553
Atan = 3;
554554
Ascii = 4;

datafusion/proto/src/generated/pbjson.rs

Lines changed: 0 additions & 3 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

datafusion/proto/src/generated/prost.rs

Lines changed: 1 addition & 3 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

datafusion/proto/src/logical_plan/from_proto.rs

Lines changed: 9 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -47,15 +47,15 @@ use datafusion_common::{
4747
use datafusion_expr::expr::Unnest;
4848
use datafusion_expr::window_frame::{check_window_frame, regularize_window_order_by};
4949
use datafusion_expr::{
50-
acos, acosh, array, array_append, array_concat, array_dims, array_distinct,
51-
array_element, array_empty, array_except, array_has, array_has_all, array_has_any,
52-
array_intersect, array_length, array_ndims, array_pop_back, array_pop_front,
53-
array_position, array_positions, array_prepend, array_remove, array_remove_all,
54-
array_remove_n, array_repeat, array_replace, array_replace_all, array_replace_n,
55-
array_resize, array_slice, array_sort, array_union, arrow_typeof, ascii, asin, asinh,
56-
atan, atan2, atanh, bit_length, btrim, cardinality, cbrt, ceil, character_length,
57-
chr, coalesce, concat_expr, concat_ws_expr, cos, cosh, cot, current_date,
58-
current_time, date_bin, date_part, date_trunc, degrees, digest, ends_with, exp,
50+
acosh, array, array_append, array_concat, array_dims, array_distinct, array_element,
51+
array_empty, array_except, array_has, array_has_all, array_has_any, array_intersect,
52+
array_length, array_ndims, array_pop_back, array_pop_front, array_position,
53+
array_positions, array_prepend, array_remove, array_remove_all, array_remove_n,
54+
array_repeat, array_replace, array_replace_all, array_replace_n, array_resize,
55+
array_slice, array_sort, array_union, arrow_typeof, ascii, asin, asinh, atan, atan2,
56+
atanh, bit_length, btrim, cardinality, cbrt, ceil, character_length, chr, coalesce,
57+
concat_expr, concat_ws_expr, cos, cosh, cot, current_date, current_time, date_bin,
58+
date_part, date_trunc, degrees, digest, ends_with, exp,
5959
expr::{self, InList, Sort, WindowFunction},
6060
factorial, find_in_set, flatten, floor, from_unixtime, gcd, gen_range, initcap,
6161
instr, iszero, lcm, left, levenshtein, ln, log, log10, log2,
@@ -450,7 +450,6 @@ impl From<&protobuf::ScalarFunction> for BuiltinScalarFunction {
450450
ScalarFunction::Tan => Self::Tan,
451451
ScalarFunction::Cot => Self::Cot,
452452
ScalarFunction::Asin => Self::Asin,
453-
ScalarFunction::Acos => Self::Acos,
454453
ScalarFunction::Atan => Self::Atan,
455454
ScalarFunction::Sinh => Self::Sinh,
456455
ScalarFunction::Cosh => Self::Cosh,
@@ -1362,7 +1361,6 @@ pub fn parse_expr(
13621361
match scalar_function {
13631362
ScalarFunction::Unknown => Err(proto_error("Unknown scalar function")),
13641363
ScalarFunction::Asin => Ok(asin(parse_expr(&args[0], registry)?)),
1365-
ScalarFunction::Acos => Ok(acos(parse_expr(&args[0], registry)?)),
13661364
ScalarFunction::Asinh => Ok(asinh(parse_expr(&args[0], registry)?)),
13671365
ScalarFunction::Acosh => Ok(acosh(parse_expr(&args[0], registry)?)),
13681366
ScalarFunction::Array => Ok(array(

datafusion/proto/src/logical_plan/to_proto.rs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1432,7 +1432,6 @@ impl TryFrom<&BuiltinScalarFunction> for protobuf::ScalarFunction {
14321432
BuiltinScalarFunction::Cosh => Self::Cosh,
14331433
BuiltinScalarFunction::Tanh => Self::Tanh,
14341434
BuiltinScalarFunction::Asin => Self::Asin,
1435-
BuiltinScalarFunction::Acos => Self::Acos,
14361435
BuiltinScalarFunction::Atan => Self::Atan,
14371436
BuiltinScalarFunction::Asinh => Self::Asinh,
14381437
BuiltinScalarFunction::Acosh => Self::Acosh,

datafusion/proto/tests/cases/roundtrip_physical_plan.rs

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -16,10 +16,6 @@
1616
// under the License.
1717

1818
use arrow::csv::WriterBuilder;
19-
use std::ops::Deref;
20-
use std::sync::Arc;
21-
use std::vec;
22-
2319
use datafusion::arrow::array::ArrayRef;
2420
use datafusion::arrow::compute::kernels::sort::SortOptions;
2521
use datafusion::arrow::datatypes::{DataType, Field, Fields, IntervalUnit, Schema};
@@ -52,6 +48,7 @@ use datafusion::physical_plan::expressions::{
5248
StringAgg, Sum,
5349
};
5450
use datafusion::physical_plan::filter::FilterExec;
51+
use datafusion::physical_plan::functions;
5552
use datafusion::physical_plan::insert::FileSinkExec;
5653
use datafusion::physical_plan::joins::{
5754
HashJoinExec, NestedLoopJoinExec, PartitionMode, StreamJoinPartitionMode,
@@ -66,7 +63,7 @@ use datafusion::physical_plan::windows::{
6663
BuiltInWindowExpr, PlainAggregateWindowExpr, WindowAggExec,
6764
};
6865
use datafusion::physical_plan::{
69-
functions, udaf, AggregateExpr, ExecutionPlan, Partitioning, PhysicalExpr, Statistics,
66+
udaf, AggregateExpr, ExecutionPlan, Partitioning, PhysicalExpr, Statistics,
7067
};
7168
use datafusion::prelude::SessionContext;
7269
use datafusion::scalar::ScalarValue;
@@ -82,6 +79,9 @@ use datafusion_expr::{
8279
};
8380
use datafusion_proto::physical_plan::{AsExecutionPlan, DefaultPhysicalExtensionCodec};
8481
use datafusion_proto::protobuf;
82+
use std::ops::Deref;
83+
use std::sync::Arc;
84+
use std::vec;
8585

8686
/// Perform a serde roundtrip and assert that the string representation of the before and after plans
8787
/// are identical. Note that this often isn't sufficient to guarantee that no information is
@@ -600,10 +600,10 @@ fn roundtrip_builtin_scalar_function() -> Result<()> {
600600
let execution_props = ExecutionProps::new();
601601

602602
let fun_expr =
603-
functions::create_physical_fun(&BuiltinScalarFunction::Acos, &execution_props)?;
603+
functions::create_physical_fun(&BuiltinScalarFunction::Sin, &execution_props)?;
604604

605605
let expr = ScalarFunctionExpr::new(
606-
"acos",
606+
"sin",
607607
fun_expr,
608608
vec![col("a", &schema)?],
609609
DataType::Float64,

0 commit comments

Comments
 (0)