Skip to content

Commit d493f3d

Browse files
Add Decimal support to Ceil and Floor (#18979)
## 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. --> - Closes #7689. ## 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. --> ## What changes are included in this PR? - Added dedicated ceil/floor UDF implementations that keep existing float/int behavior but operate directly on Decimal128 arrays, including overflow checks and metadata preservation. - Updated the math module wiring plus sqllogictest coverage so decimal cases are executed and validated end to end. <!-- 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? - All existing tests pass - Added new tests for the changes <!-- 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: Jeffrey Vo <[email protected]>
1 parent cbf33d1 commit d493f3d

File tree

7 files changed

+561
-65
lines changed

7 files changed

+561
-65
lines changed
Lines changed: 174 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,174 @@
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 std::any::Any;
19+
use std::sync::Arc;
20+
21+
use arrow::array::{ArrayRef, AsArray};
22+
use arrow::datatypes::{
23+
DataType, Decimal32Type, Decimal64Type, Decimal128Type, Decimal256Type, Float32Type,
24+
Float64Type,
25+
};
26+
use datafusion_common::{Result, ScalarValue, exec_err};
27+
use datafusion_expr::interval_arithmetic::Interval;
28+
use datafusion_expr::sort_properties::{ExprProperties, SortProperties};
29+
use datafusion_expr::{
30+
Coercion, ColumnarValue, Documentation, ScalarFunctionArgs, ScalarUDFImpl, Signature,
31+
TypeSignature, TypeSignatureClass, Volatility,
32+
};
33+
use datafusion_macros::user_doc;
34+
35+
use super::decimal::{apply_decimal_op, ceil_decimal_value};
36+
37+
#[user_doc(
38+
doc_section(label = "Math Functions"),
39+
description = "Returns the nearest integer greater than or equal to a number.",
40+
syntax_example = "ceil(numeric_expression)",
41+
standard_argument(name = "numeric_expression", prefix = "Numeric"),
42+
sql_example = r#"```sql
43+
> SELECT ceil(3.14);
44+
+------------+
45+
| ceil(3.14) |
46+
+------------+
47+
| 4.0 |
48+
+------------+
49+
```"#
50+
)]
51+
#[derive(Debug, PartialEq, Eq, Hash)]
52+
pub struct CeilFunc {
53+
signature: Signature,
54+
}
55+
56+
impl Default for CeilFunc {
57+
fn default() -> Self {
58+
Self::new()
59+
}
60+
}
61+
62+
impl CeilFunc {
63+
pub fn new() -> Self {
64+
let decimal_sig = Coercion::new_exact(TypeSignatureClass::Decimal);
65+
Self {
66+
signature: Signature::one_of(
67+
vec![
68+
TypeSignature::Coercible(vec![decimal_sig]),
69+
TypeSignature::Uniform(1, vec![DataType::Float64, DataType::Float32]),
70+
],
71+
Volatility::Immutable,
72+
),
73+
}
74+
}
75+
}
76+
77+
impl ScalarUDFImpl for CeilFunc {
78+
fn as_any(&self) -> &dyn Any {
79+
self
80+
}
81+
82+
fn name(&self) -> &str {
83+
"ceil"
84+
}
85+
86+
fn signature(&self) -> &Signature {
87+
&self.signature
88+
}
89+
90+
fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
91+
match &arg_types[0] {
92+
DataType::Null => Ok(DataType::Float64),
93+
other => Ok(other.clone()),
94+
}
95+
}
96+
97+
fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
98+
let args = ColumnarValue::values_to_arrays(&args.args)?;
99+
let value = &args[0];
100+
101+
let result: ArrayRef = match value.data_type() {
102+
DataType::Float64 => Arc::new(
103+
value
104+
.as_primitive::<Float64Type>()
105+
.unary::<_, Float64Type>(f64::ceil),
106+
),
107+
DataType::Float32 => Arc::new(
108+
value
109+
.as_primitive::<Float32Type>()
110+
.unary::<_, Float32Type>(f32::ceil),
111+
),
112+
DataType::Null => {
113+
return Ok(ColumnarValue::Scalar(ScalarValue::Float64(None)));
114+
}
115+
DataType::Decimal32(precision, scale) => {
116+
apply_decimal_op::<Decimal32Type, _>(
117+
value,
118+
*precision,
119+
*scale,
120+
self.name(),
121+
ceil_decimal_value,
122+
)?
123+
}
124+
DataType::Decimal64(precision, scale) => {
125+
apply_decimal_op::<Decimal64Type, _>(
126+
value,
127+
*precision,
128+
*scale,
129+
self.name(),
130+
ceil_decimal_value,
131+
)?
132+
}
133+
DataType::Decimal128(precision, scale) => {
134+
apply_decimal_op::<Decimal128Type, _>(
135+
value,
136+
*precision,
137+
*scale,
138+
self.name(),
139+
ceil_decimal_value,
140+
)?
141+
}
142+
DataType::Decimal256(precision, scale) => {
143+
apply_decimal_op::<Decimal256Type, _>(
144+
value,
145+
*precision,
146+
*scale,
147+
self.name(),
148+
ceil_decimal_value,
149+
)?
150+
}
151+
other => {
152+
return exec_err!(
153+
"Unsupported data type {other:?} for function {}",
154+
self.name()
155+
);
156+
}
157+
};
158+
159+
Ok(ColumnarValue::Array(result))
160+
}
161+
162+
fn output_ordering(&self, input: &[ExprProperties]) -> Result<SortProperties> {
163+
Ok(input[0].sort_properties)
164+
}
165+
166+
fn evaluate_bounds(&self, inputs: &[&Interval]) -> Result<Interval> {
167+
let data_type = inputs[0].data_type();
168+
Interval::make_unbounded(&data_type)
169+
}
170+
171+
fn documentation(&self) -> Option<&Documentation> {
172+
self.doc()
173+
}
174+
}
Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
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 std::sync::Arc;
19+
20+
use arrow::array::{ArrayRef, AsArray, PrimitiveArray};
21+
use arrow::datatypes::{ArrowNativeTypeOp, DecimalType};
22+
use arrow::error::ArrowError;
23+
use arrow_buffer::ArrowNativeType;
24+
use datafusion_common::{DataFusionError, Result};
25+
26+
pub(super) fn apply_decimal_op<T, F>(
27+
array: &ArrayRef,
28+
precision: u8,
29+
scale: i8,
30+
fn_name: &str,
31+
op: F,
32+
) -> Result<ArrayRef>
33+
where
34+
T: DecimalType,
35+
T::Native: ArrowNativeType + ArrowNativeTypeOp,
36+
F: Fn(T::Native, T::Native) -> T::Native,
37+
{
38+
if scale <= 0 {
39+
return Ok(Arc::clone(array));
40+
}
41+
42+
let factor = decimal_scale_factor::<T>(scale, fn_name)?;
43+
let decimal = array.as_primitive::<T>();
44+
let data_type = array.data_type().clone();
45+
46+
let result: PrimitiveArray<T> = decimal.try_unary(|value| {
47+
let new_value = op(value, factor);
48+
T::validate_decimal_precision(new_value, precision, scale).map_err(|_| {
49+
ArrowError::ComputeError(format!("Decimal overflow while applying {fn_name}"))
50+
})?;
51+
Ok::<_, ArrowError>(new_value)
52+
})?;
53+
54+
let result = result.with_data_type(data_type);
55+
56+
Ok(Arc::new(result))
57+
}
58+
59+
fn decimal_scale_factor<T>(scale: i8, fn_name: &str) -> Result<T::Native>
60+
where
61+
T: DecimalType,
62+
T::Native: ArrowNativeType + ArrowNativeTypeOp,
63+
{
64+
let base = <T::Native as ArrowNativeType>::from_usize(10).ok_or_else(|| {
65+
DataFusionError::Execution(format!(
66+
"Cannot get 10_{} from usize: {:?}",
67+
std::any::type_name::<T::Native>(),
68+
10_usize
69+
))
70+
})?;
71+
72+
base.pow_checked(scale as u32).map_err(|_| {
73+
DataFusionError::Execution(format!("Decimal overflow while applying {fn_name}"))
74+
})
75+
}
76+
77+
pub(super) fn ceil_decimal_value<T>(value: T, factor: T) -> T
78+
where
79+
T: ArrowNativeTypeOp + std::ops::Rem<Output = T>,
80+
{
81+
let remainder = value % factor;
82+
83+
if remainder == T::ZERO {
84+
return value;
85+
}
86+
87+
if value >= T::ZERO {
88+
let increment = factor.sub_wrapping(remainder);
89+
value.add_wrapping(increment)
90+
} else {
91+
value.sub_wrapping(remainder)
92+
}
93+
}
94+
95+
pub(super) fn floor_decimal_value<T>(value: T, factor: T) -> T
96+
where
97+
T: ArrowNativeTypeOp + std::ops::Rem<Output = T>,
98+
{
99+
let remainder = value % factor;
100+
101+
if remainder == T::ZERO {
102+
return value;
103+
}
104+
105+
if value >= T::ZERO {
106+
value.sub_wrapping(remainder)
107+
} else {
108+
let adjustment = factor.add_wrapping(remainder);
109+
value.sub_wrapping(adjustment)
110+
}
111+
}

0 commit comments

Comments
 (0)