-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Add Decimal128 support to Ceil and Floor #18979
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
kumarUjjawal
wants to merge
6
commits into
apache:main
Choose a base branch
from
kumarUjjawal:feat/decimal_ceil_floor
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+559
−67
Open
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
08dbd6e
Add Decimal128 support to Ceil and Floor
kumarUjjawal 47b8f26
created new module for decimal shared generic code
kumarUjjawal 7ac92ff
Update datafusion/functions/src/math/ceil.rs
kumarUjjawal ae2fbd0
used alreay present traits for decimal
kumarUjjawal df2be81
fixed tests and updated docs
kumarUjjawal fc22f63
tests for floor/ceil overflow
kumarUjjawal File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,174 @@ | ||
| // 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. | ||
|
|
||
| use std::any::Any; | ||
| use std::sync::Arc; | ||
|
|
||
| use arrow::array::{ArrayRef, AsArray}; | ||
| use arrow::datatypes::{ | ||
| DataType, Decimal128Type, Decimal256Type, Decimal32Type, Decimal64Type, Float32Type, | ||
| Float64Type, | ||
| }; | ||
| use datafusion_common::{exec_err, Result, ScalarValue}; | ||
| use datafusion_expr::interval_arithmetic::Interval; | ||
| use datafusion_expr::sort_properties::{ExprProperties, SortProperties}; | ||
| use datafusion_expr::{ | ||
| Coercion, ColumnarValue, Documentation, ScalarFunctionArgs, ScalarUDFImpl, Signature, | ||
| TypeSignature, TypeSignatureClass, Volatility, | ||
| }; | ||
| use datafusion_macros::user_doc; | ||
|
|
||
| use super::decimal::{apply_decimal_op, ceil_decimal_value}; | ||
|
|
||
| #[user_doc( | ||
| doc_section(label = "Math Functions"), | ||
| description = "Returns the nearest integer greater than or equal to a number.", | ||
| syntax_example = "ceil(numeric_expression)", | ||
| standard_argument(name = "numeric_expression", prefix = "Numeric"), | ||
| sql_example = r#"```sql | ||
| > SELECT ceil(3.14); | ||
| +------------+ | ||
| | ceil(3.14) | | ||
| +------------+ | ||
| | 4.0 | | ||
| +------------+ | ||
| ```"# | ||
| )] | ||
| #[derive(Debug, PartialEq, Eq, Hash)] | ||
| pub struct CeilFunc { | ||
| signature: Signature, | ||
| } | ||
|
|
||
| impl Default for CeilFunc { | ||
| fn default() -> Self { | ||
| Self::new() | ||
| } | ||
| } | ||
|
|
||
| impl CeilFunc { | ||
| pub fn new() -> Self { | ||
| let decimal_sig = Coercion::new_exact(TypeSignatureClass::Decimal); | ||
| Self { | ||
| signature: Signature::one_of( | ||
| vec![ | ||
| TypeSignature::Coercible(vec![decimal_sig]), | ||
| TypeSignature::Uniform(1, vec![DataType::Float64, DataType::Float32]), | ||
| ], | ||
| Volatility::Immutable, | ||
| ), | ||
| } | ||
| } | ||
| } | ||
|
|
||
| impl ScalarUDFImpl for CeilFunc { | ||
| fn as_any(&self) -> &dyn Any { | ||
| self | ||
| } | ||
|
|
||
| fn name(&self) -> &str { | ||
| "ceil" | ||
| } | ||
|
|
||
| fn signature(&self) -> &Signature { | ||
| &self.signature | ||
| } | ||
|
|
||
| fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> { | ||
| match &arg_types[0] { | ||
| DataType::Null => Ok(DataType::Float64), | ||
| other => Ok(other.clone()), | ||
| } | ||
| } | ||
|
|
||
| fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> { | ||
| let args = ColumnarValue::values_to_arrays(&args.args)?; | ||
| let value = &args[0]; | ||
|
|
||
| let result: ArrayRef = match value.data_type() { | ||
| DataType::Float64 => Arc::new( | ||
| value | ||
| .as_primitive::<Float64Type>() | ||
| .unary::<_, Float64Type>(f64::ceil), | ||
| ), | ||
| DataType::Float32 => Arc::new( | ||
| value | ||
| .as_primitive::<Float32Type>() | ||
| .unary::<_, Float32Type>(f32::ceil), | ||
| ), | ||
| DataType::Null => { | ||
| return Ok(ColumnarValue::Scalar(ScalarValue::Float64(None))) | ||
| } | ||
| DataType::Decimal32(precision, scale) => { | ||
| apply_decimal_op::<Decimal32Type, _>( | ||
| value, | ||
| *precision, | ||
| *scale, | ||
| self.name(), | ||
| ceil_decimal_value, | ||
| )? | ||
| } | ||
| DataType::Decimal64(precision, scale) => { | ||
| apply_decimal_op::<Decimal64Type, _>( | ||
| value, | ||
| *precision, | ||
| *scale, | ||
| self.name(), | ||
| ceil_decimal_value, | ||
| )? | ||
| } | ||
| DataType::Decimal128(precision, scale) => { | ||
| apply_decimal_op::<Decimal128Type, _>( | ||
| value, | ||
| *precision, | ||
| *scale, | ||
| self.name(), | ||
| ceil_decimal_value, | ||
| )? | ||
| } | ||
| DataType::Decimal256(precision, scale) => { | ||
| apply_decimal_op::<Decimal256Type, _>( | ||
| value, | ||
| *precision, | ||
| *scale, | ||
| self.name(), | ||
| ceil_decimal_value, | ||
| )? | ||
| } | ||
| other => { | ||
| return exec_err!( | ||
| "Unsupported data type {other:?} for function {}", | ||
| self.name() | ||
| ) | ||
| } | ||
| }; | ||
|
|
||
| Ok(ColumnarValue::Array(result)) | ||
| } | ||
|
|
||
| fn output_ordering(&self, input: &[ExprProperties]) -> Result<SortProperties> { | ||
| Ok(input[0].sort_properties) | ||
| } | ||
|
|
||
| fn evaluate_bounds(&self, inputs: &[&Interval]) -> Result<Interval> { | ||
| let data_type = inputs[0].data_type(); | ||
| Interval::make_unbounded(&data_type) | ||
| } | ||
|
|
||
| fn documentation(&self) -> Option<&Documentation> { | ||
| self.doc() | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,107 @@ | ||
| // 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. | ||
|
|
||
| use std::sync::Arc; | ||
|
|
||
| use arrow::array::{ArrayRef, AsArray, PrimitiveArray}; | ||
| use arrow::datatypes::{ArrowNativeTypeOp, DecimalType}; | ||
| use arrow::error::ArrowError; | ||
| use arrow_buffer::ArrowNativeType; | ||
| use datafusion_common::{DataFusionError, Result}; | ||
|
|
||
| pub(super) fn apply_decimal_op<T, F>( | ||
| array: &ArrayRef, | ||
| precision: u8, | ||
| scale: i8, | ||
| fn_name: &str, | ||
| op: F, | ||
| ) -> Result<ArrayRef> | ||
| where | ||
| T: DecimalType, | ||
| T::Native: ArrowNativeType + ArrowNativeTypeOp, | ||
| F: Fn(T::Native, T::Native) -> T::Native, | ||
| { | ||
| if scale <= 0 { | ||
| return Ok(Arc::clone(array)); | ||
| } | ||
|
|
||
| let factor = decimal_scale_factor::<T>(scale, fn_name)?; | ||
| let decimal = array.as_primitive::<T>(); | ||
| let data_type = array.data_type().clone(); | ||
|
|
||
| let result: PrimitiveArray<T> = decimal.try_unary(|value| { | ||
| let new_value = op(value, factor); | ||
| T::validate_decimal_precision(new_value, precision, scale).map_err(|_| { | ||
| ArrowError::ComputeError(format!("Decimal overflow while applying {fn_name}")) | ||
| })?; | ||
| Ok::<_, ArrowError>(new_value) | ||
| })?; | ||
|
|
||
| let result = result.with_data_type(data_type); | ||
|
|
||
| Ok(Arc::new(result)) | ||
| } | ||
|
|
||
| fn decimal_scale_factor<T>(scale: i8, fn_name: &str) -> Result<T::Native> | ||
| where | ||
| T: DecimalType, | ||
| T::Native: ArrowNativeType + ArrowNativeTypeOp, | ||
| { | ||
| let base = <T::Native as ArrowNativeType>::from_usize(10).ok_or_else(|| { | ||
| DataFusionError::Execution(format!("Decimal overflow while applying {fn_name}")) | ||
| })?; | ||
|
|
||
| base.pow_checked(scale as u32).map_err(|_| { | ||
| DataFusionError::Execution(format!("Decimal overflow while applying {fn_name}")) | ||
| }) | ||
| } | ||
|
|
||
| pub(super) fn ceil_decimal_value<T>(value: T, factor: T) -> T | ||
| where | ||
| T: ArrowNativeTypeOp + std::ops::Rem<Output = T>, | ||
| { | ||
| let remainder = value % factor; | ||
|
|
||
| if remainder == T::ZERO { | ||
| return value; | ||
| } | ||
|
|
||
| if value >= T::ZERO { | ||
| let increment = factor.sub_wrapping(remainder); | ||
| value.add_wrapping(increment) | ||
| } else { | ||
| value.sub_wrapping(remainder) | ||
| } | ||
| } | ||
|
|
||
| pub(super) fn floor_decimal_value<T>(value: T, factor: T) -> T | ||
| where | ||
| T: ArrowNativeTypeOp + std::ops::Rem<Output = T>, | ||
| { | ||
| let remainder = value % factor; | ||
|
|
||
| if remainder == T::ZERO { | ||
| return value; | ||
| } | ||
|
|
||
| if value >= T::ZERO { | ||
| value.sub_wrapping(remainder) | ||
| } else { | ||
| let adjustment = factor.add_wrapping(remainder); | ||
| value.sub_wrapping(adjustment) | ||
| } | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I feel we should just inline this function; doing so would make it clear that
scalewas already checked for being non-negative