Skip to content

Commit 015162a

Browse files
athlcodeB Vadlamani
andauthored
feat: support spark compatible floor function (apache#21933)
## Which issue does this PR close? Part of apache#15914 - Closes apache#20860 <!-- 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 apache#123` indicates that this PR will close issue apache#123. --> ## Rationale for this change Spark compatible semantics for `floor` function <!-- 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. --> ## What changes are included in this PR? Implements SparkFloor UDF with Spark-compatible return types: - Float/Integer inputs -> Int64 - Decimal128(p, s) -> Decimal128(p-s+1, 0) <!-- 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. --> ## Are these changes tested? Yes . Added unit tests and SLT tests <!-- 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)? --> ## Are there any user-facing changes? <!-- If there are user-facing changes then we may require documentation to be updated before approving the PR. --> <!-- If there are any breaking changes to public APIs, please add the `api change` label. --> --------- Co-authored-by: B Vadlamani <fullcircle289@gmail.com>
1 parent bc6f95b commit 015162a

5 files changed

Lines changed: 588 additions & 25 deletions

File tree

datafusion/spark/Cargo.toml

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,3 +99,7 @@ name = "unhex"
9999
[[bench]]
100100
harness = false
101101
name = "sha2"
102+
103+
[[bench]]
104+
harness = false
105+
name = "floor"

datafusion/spark/benches/floor.rs

Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
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+
use arrow::array::*;
19+
use arrow::datatypes::*;
20+
use criterion::{Criterion, criterion_group, criterion_main};
21+
use datafusion_common::config::ConfigOptions;
22+
use datafusion_expr::{ColumnarValue, ScalarFunctionArgs, ScalarUDFImpl};
23+
use datafusion_spark::function::math::floor::SparkFloor;
24+
use rand::rngs::StdRng;
25+
use rand::{Rng, SeedableRng};
26+
use std::hint::black_box;
27+
use std::sync::Arc;
28+
29+
fn seedable_rng() -> StdRng {
30+
StdRng::seed_from_u64(42)
31+
}
32+
33+
fn generate_float64_data(size: usize, null_density: f32) -> Float64Array {
34+
let mut rng = seedable_rng();
35+
(0..size)
36+
.map(|_| {
37+
if rng.random::<f32>() < null_density {
38+
None
39+
} else {
40+
Some(rng.random_range::<f64, _>(-1_000_000.0..1_000_000.0))
41+
}
42+
})
43+
.collect()
44+
}
45+
46+
fn generate_decimal128_data(size: usize, null_density: f32) -> Decimal128Array {
47+
let mut rng = seedable_rng();
48+
let array: Decimal128Array = (0..size)
49+
.map(|_| {
50+
if rng.random::<f32>() < null_density {
51+
None
52+
} else {
53+
Some(rng.random_range::<i128, _>(-999_999_999..999_999_999))
54+
}
55+
})
56+
.collect();
57+
array.with_precision_and_scale(18, 2).unwrap()
58+
}
59+
60+
fn run_benchmark(
61+
c: &mut Criterion,
62+
name: &str,
63+
size: usize,
64+
array: Arc<dyn Array>,
65+
return_type: &DataType,
66+
) {
67+
let floor_func = SparkFloor::new();
68+
let args = vec![ColumnarValue::Array(array)];
69+
let arg_fields: Vec<_> = args
70+
.iter()
71+
.enumerate()
72+
.map(|(idx, arg)| Field::new(format!("arg_{idx}"), arg.data_type(), true).into())
73+
.collect();
74+
let config_options = Arc::new(ConfigOptions::default());
75+
76+
c.bench_function(&format!("{name}/size={size}"), |b| {
77+
b.iter(|| {
78+
black_box(
79+
floor_func
80+
.invoke_with_args(ScalarFunctionArgs {
81+
args: args.clone(),
82+
arg_fields: arg_fields.clone(),
83+
number_rows: size,
84+
return_field: Arc::new(Field::new(
85+
"f",
86+
return_type.clone(),
87+
true,
88+
)),
89+
config_options: Arc::clone(&config_options),
90+
})
91+
.unwrap(),
92+
)
93+
})
94+
});
95+
}
96+
97+
fn criterion_benchmark(c: &mut Criterion) {
98+
let sizes = vec![1024, 4096, 8192];
99+
let null_density = 0.1;
100+
101+
for &size in &sizes {
102+
let data = generate_float64_data(size, null_density);
103+
run_benchmark(c, "floor_float64", size, Arc::new(data), &DataType::Int64);
104+
}
105+
106+
for &size in &sizes {
107+
let data = generate_decimal128_data(size, null_density);
108+
run_benchmark(
109+
c,
110+
"floor_decimal128",
111+
size,
112+
Arc::new(data),
113+
&DataType::Decimal128(17, 0),
114+
);
115+
}
116+
}
117+
118+
criterion_group!(benches, criterion_benchmark);
119+
criterion_main!(benches);
Lines changed: 182 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,182 @@
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+
use arrow::array::cast::AsArray;
19+
use arrow::array::types::Decimal128Type;
20+
use arrow::array::{ArrowNativeTypeOp, Decimal128Array, Int64Array};
21+
use arrow::compute::kernels::arity::unary;
22+
use arrow::datatypes::{DataType, Field, FieldRef};
23+
use datafusion_common::{DataFusionError, ScalarValue, exec_err, internal_err};
24+
use datafusion_expr::{
25+
ColumnarValue, ReturnFieldArgs, ScalarFunctionArgs, ScalarUDFImpl, Signature,
26+
Volatility,
27+
};
28+
use std::sync::Arc;
29+
30+
/// Spark-compatible `floor` function.
31+
///
32+
/// Differences from DataFusion's floor:
33+
/// - Returns Int64 for float and integer inputs (while DataFusion preserves input type)
34+
/// - For Decimal128(p, s), returns Decimal128(p-s+1, 0) with scale 0
35+
/// (DataFusion preserves original precision and scale)
36+
///
37+
/// <https://spark.apache.org/docs/latest/api/sql/index.html#floor>
38+
#[derive(Debug, PartialEq, Eq, Hash)]
39+
pub struct SparkFloor {
40+
signature: Signature,
41+
}
42+
43+
impl Default for SparkFloor {
44+
fn default() -> Self {
45+
Self::new()
46+
}
47+
}
48+
49+
impl SparkFloor {
50+
pub fn new() -> Self {
51+
Self {
52+
signature: Signature::numeric(1, Volatility::Immutable),
53+
}
54+
}
55+
}
56+
57+
impl ScalarUDFImpl for SparkFloor {
58+
fn name(&self) -> &str {
59+
"floor"
60+
}
61+
62+
fn signature(&self) -> &Signature {
63+
&self.signature
64+
}
65+
66+
fn return_type(
67+
&self,
68+
_arg_types: &[DataType],
69+
) -> datafusion_common::Result<DataType> {
70+
internal_err!("return_field_from_args should be called instead")
71+
}
72+
73+
fn return_field_from_args(
74+
&self,
75+
args: ReturnFieldArgs,
76+
) -> datafusion_common::Result<FieldRef> {
77+
let nullable = args.arg_fields.iter().any(|f| f.is_nullable());
78+
let return_type = match args.arg_fields[0].data_type() {
79+
DataType::Decimal128(p, s) if *s > 0 => {
80+
let new_p = (*p - *s as u8 + 1).clamp(1, 38);
81+
DataType::Decimal128(new_p, 0)
82+
}
83+
DataType::Decimal128(p, s) => DataType::Decimal128(*p, *s),
84+
DataType::Float32
85+
| DataType::Float64
86+
| DataType::Int8
87+
| DataType::Int16
88+
| DataType::Int32
89+
| DataType::Int64 => DataType::Int64,
90+
_ => exec_err!(
91+
"found unsupported return type {:?}",
92+
args.arg_fields[0].data_type()
93+
)?,
94+
};
95+
Ok(Arc::new(Field::new(self.name(), return_type, nullable)))
96+
}
97+
98+
fn invoke_with_args(
99+
&self,
100+
args: ScalarFunctionArgs,
101+
) -> datafusion_common::Result<ColumnarValue> {
102+
spark_floor(&args.args, args.return_field.data_type())
103+
}
104+
}
105+
106+
macro_rules! apply_int64 {
107+
($value:expr, $arr_type:ty, $scalar_variant:path, $f:expr) => {
108+
match $value {
109+
ColumnarValue::Array(array) => {
110+
let result: Int64Array = unary(array.as_primitive::<$arr_type>(), $f);
111+
Ok(ColumnarValue::Array(Arc::new(result)))
112+
}
113+
ColumnarValue::Scalar($scalar_variant(v)) => {
114+
Ok(ColumnarValue::Scalar(ScalarValue::Int64(v.map($f))))
115+
}
116+
other => internal_err!(
117+
"floor: data type mismatch — expected scalar of type {} but got {:?}",
118+
stringify!($scalar_variant),
119+
other.data_type()
120+
),
121+
}
122+
};
123+
}
124+
125+
fn spark_floor(
126+
args: &[ColumnarValue],
127+
return_type: &DataType,
128+
) -> Result<ColumnarValue, DataFusionError> {
129+
let value = &args[0];
130+
match value.data_type() {
131+
DataType::Float32 => apply_int64!(
132+
value,
133+
arrow::datatypes::Float32Type,
134+
ScalarValue::Float32,
135+
|x| x.floor() as i64
136+
),
137+
DataType::Float64 => apply_int64!(
138+
value,
139+
arrow::datatypes::Float64Type,
140+
ScalarValue::Float64,
141+
|x| x.floor() as i64
142+
),
143+
DataType::Int8 | DataType::Int16 | DataType::Int32 | DataType::Int64 => {
144+
value.cast_to(&DataType::Int64, None)
145+
}
146+
DataType::Decimal128(_, scale) if scale > 0 => {
147+
let divisor = 10_i128.pow_wrapping(scale as u32);
148+
let floor_decimal = |x: i128| {
149+
let (d, r) = (x / divisor, x % divisor);
150+
if r < 0 { d - 1 } else { d }
151+
};
152+
match value {
153+
ColumnarValue::Array(array) => {
154+
let result: Decimal128Array =
155+
unary(array.as_primitive::<Decimal128Type>(), floor_decimal);
156+
Ok(ColumnarValue::Array(Arc::new(
157+
result.with_data_type(return_type.clone()),
158+
)))
159+
}
160+
ColumnarValue::Scalar(ScalarValue::Decimal128(v, _, _)) => {
161+
let DataType::Decimal128(new_p, new_s) = return_type else {
162+
return internal_err!(
163+
"floor: data type mismatch — expected Decimal128 return type but got {:?}",
164+
return_type
165+
);
166+
};
167+
Ok(ColumnarValue::Scalar(ScalarValue::Decimal128(
168+
v.map(floor_decimal),
169+
*new_p,
170+
*new_s,
171+
)))
172+
}
173+
other => internal_err!(
174+
"floor: data type mismatch — expected Decimal128 scalar but got {:?}",
175+
other.data_type()
176+
),
177+
}
178+
}
179+
DataType::Decimal128(_, _) => Ok(value.clone()),
180+
other => exec_err!("Unsupported data type {other:?} for function floor"),
181+
}
182+
}

datafusion/spark/src/function/math/mod.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ pub mod bin;
2020
pub mod ceil;
2121
pub mod expm1;
2222
pub mod factorial;
23+
pub mod floor;
2324
pub mod hex;
2425
pub mod modulus;
2526
pub mod negative;
@@ -37,6 +38,7 @@ make_udf_function!(abs::SparkAbs, abs);
3738
make_udf_function!(ceil::SparkCeil, ceil);
3839
make_udf_function!(expm1::SparkExpm1, expm1);
3940
make_udf_function!(factorial::SparkFactorial, factorial);
41+
make_udf_function!(floor::SparkFloor, floor);
4042
make_udf_function!(hex::SparkHex, hex);
4143
make_udf_function!(modulus::SparkMod, modulus);
4244
make_udf_function!(modulus::SparkPmod, pmod);
@@ -60,6 +62,7 @@ pub mod expr_fn {
6062
"Returns the factorial of expr. expr is [0..20]. Otherwise, null.",
6163
arg1
6264
));
65+
export_functions!((floor, "Returns floor of expr.", arg1));
6366
export_functions!((hex, "Computes hex value of the given column.", arg1));
6467
export_functions!((modulus, "Returns the remainder of division of the first argument by the second argument.", arg1 arg2));
6568
export_functions!((pmod, "Returns the positive remainder of division of the first argument by the second argument.", arg1 arg2));
@@ -95,6 +98,7 @@ pub fn functions() -> Vec<Arc<ScalarUDF>> {
9598
ceil(),
9699
expm1(),
97100
factorial(),
101+
floor(),
98102
hex(),
99103
modulus(),
100104
pmod(),

0 commit comments

Comments
 (0)