Jefffrey commented on code in PR #18979:
URL: https://github.com/apache/datafusion/pull/18979#discussion_r2572707972


##########
datafusion/functions/src/math/decimal.rs:
##########
@@ -0,0 +1,207 @@
+// 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::ops::Rem;
+use std::sync::Arc;
+
+use arrow::array::{ArrayRef, AsArray, PrimitiveArray};
+use arrow::datatypes::DecimalType;
+use arrow::error::ArrowError;
+use arrow_buffer::i256;
+use datafusion_common::{exec_err, Result};
+
+/// Operations required to manipulate the native representation of Arrow 
decimal arrays.
+pub(super) trait DecimalNative:

Review Comment:
   Can't help but feel this trait is unnecessary; is there some other existing 
code (traits) we could use instead of implementing this? 🤔 



##########
datafusion/functions/src/math/ceil.rs:
##########
@@ -0,0 +1,173 @@
+// 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::compute::cast;
+use arrow::datatypes::{
+    DataType, Decimal128Type, Decimal256Type, Decimal32Type, Decimal64Type, 
Float32Type,
+    Float64Type,
+};
+use datafusion_common::{exec_err, Result};
+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::Float32 => Ok(DataType::Float32),
+            DataType::Decimal32(precision, scale) => {
+                Ok(DataType::Decimal32(precision, scale))
+            }
+            DataType::Decimal64(precision, scale) => {
+                Ok(DataType::Decimal64(precision, scale))
+            }
+            DataType::Decimal128(precision, scale) => {
+                Ok(DataType::Decimal128(precision, scale))
+            }
+            DataType::Decimal256(precision, scale) => {
+                Ok(DataType::Decimal256(precision, scale))
+            }
+            _ => Ok(DataType::Float64),
+        }
+    }
+
+    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 => cast(value.as_ref(), &DataType::Float64)?,

Review Comment:
   ```suggestion
               DataType::Null => return 
Ok(ColumnarValue::Scalar(ScalarValue::Float64(None))),
   ```



##########
datafusion/functions/src/math/decimal.rs:
##########
@@ -0,0 +1,207 @@
+// 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::ops::Rem;
+use std::sync::Arc;
+
+use arrow::array::{ArrayRef, AsArray, PrimitiveArray};
+use arrow::datatypes::DecimalType;
+use arrow::error::ArrowError;
+use arrow_buffer::i256;
+use datafusion_common::{exec_err, Result};
+
+/// Operations required to manipulate the native representation of Arrow 
decimal arrays.
+pub(super) trait DecimalNative:
+    Copy + Rem<Output = Self> + PartialEq + PartialOrd
+{
+    fn zero() -> Self;
+    fn checked_add(self, other: Self) -> Option<Self>;
+    fn checked_sub(self, other: Self) -> Option<Self>;
+    fn checked_pow10(exp: u32) -> Option<Self>;
+}
+
+impl DecimalNative for i32 {
+    fn zero() -> Self {
+        0
+    }
+
+    fn checked_add(self, other: Self) -> Option<Self> {
+        self.checked_add(other)
+    }
+
+    fn checked_sub(self, other: Self) -> Option<Self> {
+        self.checked_sub(other)
+    }
+
+    fn checked_pow10(exp: u32) -> Option<Self> {
+        10_i32.checked_pow(exp)
+    }
+}
+
+impl DecimalNative for i64 {
+    fn zero() -> Self {
+        0
+    }
+
+    fn checked_add(self, other: Self) -> Option<Self> {
+        self.checked_add(other)
+    }
+
+    fn checked_sub(self, other: Self) -> Option<Self> {
+        self.checked_sub(other)
+    }
+
+    fn checked_pow10(exp: u32) -> Option<Self> {
+        10_i64.checked_pow(exp)
+    }
+}
+
+impl DecimalNative for i128 {
+    fn zero() -> Self {
+        0
+    }
+
+    fn checked_add(self, other: Self) -> Option<Self> {
+        self.checked_add(other)
+    }
+
+    fn checked_sub(self, other: Self) -> Option<Self> {
+        self.checked_sub(other)
+    }
+
+    fn checked_pow10(exp: u32) -> Option<Self> {
+        10_i128.checked_pow(exp)
+    }
+}
+
+impl DecimalNative for i256 {
+    fn zero() -> Self {
+        i256::ZERO
+    }
+
+    fn checked_add(self, other: Self) -> Option<Self> {
+        self.checked_add(other)
+    }
+
+    fn checked_sub(self, other: Self) -> Option<Self> {
+        self.checked_sub(other)
+    }
+
+    fn checked_pow10(exp: u32) -> Option<Self> {
+        i256::from_i128(10).checked_pow(exp)
+    }
+}
+
+pub(super) fn apply_decimal_op<T, F>(
+    array: &ArrayRef,
+    scale: i8,
+    fn_name: &str,
+    op: F,
+) -> Result<ArrayRef>
+where
+    T: DecimalType,
+    T::Native: DecimalNative,
+    F: Fn(T::Native, T::Native) -> std::result::Result<T::Native, ArrowError>,
+{
+    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| op(value, factor))?
+        .with_data_type(data_type);
+
+    Ok(Arc::new(result))
+}
+
+fn decimal_scale_factor<T>(scale: i8, fn_name: &str) -> Result<T::Native>

Review Comment:
   I feel we should just inline this function; doing so would make it clear 
that `scale` was already checked for being non-negative



##########
datafusion/functions/src/math/ceil.rs:
##########
@@ -0,0 +1,273 @@
+// 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::{Array, ArrayRef, AsArray, PrimitiveArray};
+use arrow::datatypes::{DataType, Decimal128Type, Float32Type, Float64Type};
+use arrow::error::ArrowError;
+use datafusion_common::utils::take_function_args;
+use datafusion_common::{exec_err, Result};
+use datafusion_expr::interval_arithmetic::Interval;
+use datafusion_expr::sort_properties::{ExprProperties, SortProperties};
+use datafusion_expr::{
+    ColumnarValue, Documentation, ScalarFunctionArgs, ScalarUDFImpl, Signature,
+    Volatility,
+};
+
+#[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 {
+        Self {
+            signature: Signature::user_defined(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::Float32 => Ok(DataType::Float32),
+            DataType::Decimal128(precision, scale) => {

Review Comment:
   Actually I think this signature can be simplified to:
   
   ```rust
   if arg_types[0].is_null() {
       Ok(DataType::Float64)
   else {
       Ok(arg_types[0].clone())
   }
   ```



##########
datafusion/sqllogictest/test_files/scalar.slt:
##########
@@ -317,6 +317,50 @@ select ceil(100.1234, 1)
 query error DataFusion error: This feature is not implemented: CEIL with 
datetime is not supported
 select ceil(100.1234 to year)
 
+# ceil with decimal argument
+query RRRR
+select
+  ceil(arrow_cast(1.23,'Decimal128(10,2)')),
+  ceil(arrow_cast(-1.23,'Decimal128(10,2)')),
+  ceil(arrow_cast(123.00,'Decimal128(10,2)')),
+  ceil(arrow_cast(-123.00,'Decimal128(10,2)'));
+----
+2 -1 123 -123
+
+# ceil with decimal32 argument (ensure decimal output)
+query TTTTTTTT
+select
+  arrow_typeof(ceil(arrow_cast(9.01,'Decimal32(7,2)'))),
+  arrow_cast(ceil(arrow_cast(9.01,'Decimal32(7,2)')), 'Utf8'),

Review Comment:
   Don't think this cast to utf8 is necessary



##########
datafusion/functions/src/math/floor.rs:
##########
@@ -0,0 +1,173 @@
+// 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::compute::cast;
+use arrow::datatypes::{
+    DataType, Decimal128Type, Decimal256Type, Decimal32Type, Decimal64Type, 
Float32Type,
+    Float64Type,
+};
+use datafusion_common::{exec_err, Result};
+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, floor_decimal_value};
+
+#[user_doc(
+    doc_section(label = "Math Functions"),
+    description = "Returns the nearest integer less than or equal to a 
number.",
+    syntax_example = "floor(numeric_expression)",
+    standard_argument(name = "numeric_expression", prefix = "Numeric"),
+    sql_example = r#"```sql
+> SELECT floor(3.14);
++-------------+
+| floor(3.14) |
++-------------+
+| 3.0         |
++-------------+
+```"#
+)]
+#[derive(Debug, PartialEq, Eq, Hash)]
+pub struct FloorFunc {
+    signature: Signature,
+}
+
+impl Default for FloorFunc {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
+impl FloorFunc {
+    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 FloorFunc {
+    fn as_any(&self) -> &dyn Any {
+        self
+    }
+
+    fn name(&self) -> &str {
+        "floor"
+    }
+
+    fn signature(&self) -> &Signature {
+        &self.signature
+    }
+
+    fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
+        match arg_types[0] {
+            DataType::Float32 => Ok(DataType::Float32),
+            DataType::Decimal32(precision, scale) => {
+                Ok(DataType::Decimal32(precision, scale))
+            }
+            DataType::Decimal64(precision, scale) => {
+                Ok(DataType::Decimal64(precision, scale))
+            }
+            DataType::Decimal128(precision, scale) => {
+                Ok(DataType::Decimal128(precision, scale))
+            }
+            DataType::Decimal256(precision, scale) => {
+                Ok(DataType::Decimal256(precision, scale))
+            }
+            _ => Ok(DataType::Float64),
+        }
+    }
+
+    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::floor),
+            ),
+            DataType::Float32 => Arc::new(
+                value
+                    .as_primitive::<Float32Type>()
+                    .unary::<_, Float32Type>(f32::floor),
+            ),
+            DataType::Null => cast(value.as_ref(), &DataType::Float64)?,
+            DataType::Decimal32(_, scale) => apply_decimal_op::<Decimal32Type, 
_>(
+                value,
+                *scale,
+                self.name(),
+                floor_decimal_value,
+            )?,
+            DataType::Decimal64(_, scale) => apply_decimal_op::<Decimal64Type, 
_>(
+                value,
+                *scale,
+                self.name(),
+                floor_decimal_value,
+            )?,
+            DataType::Decimal128(_, scale) => 
apply_decimal_op::<Decimal128Type, _>(
+                value,
+                *scale,
+                self.name(),
+                floor_decimal_value,
+            )?,
+            DataType::Decimal256(_, scale) => 
apply_decimal_op::<Decimal256Type, _>(
+                value,
+                *scale,
+                self.name(),
+                floor_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)
+    }

Review Comment:
   Ah maybe I was wrong about inlining for ordering & bounds actually 🤔 
   
   Because bounds was generic to all the other functions, and for ordering we 
have tests against it so inlining here leaves that `ceil_order` function 
dangling 🤔 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to