coderfender commented on code in PR #21933: URL: https://github.com/apache/datafusion/pull/21933#discussion_r3164365550
########## datafusion/spark/src/function/math/floor.rs: ########## @@ -0,0 +1,195 @@ +// 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 arrow::array::cast::AsArray; +use arrow::array::types::Decimal128Type; +use arrow::array::{ArrowNativeTypeOp, Decimal128Array, Int64Array}; +use arrow::compute::kernels::arity::unary; +use arrow::datatypes::{DataType, Field, FieldRef}; +use datafusion_common::{DataFusionError, ScalarValue, exec_err, internal_err}; +use datafusion_expr::{ + ColumnarValue, ReturnFieldArgs, ScalarFunctionArgs, ScalarUDFImpl, Signature, + Volatility, +}; +use std::sync::Arc; + +/// Spark-compatible `floor` function. +/// +/// Differences from DataFusion's floor: +/// - Returns Int64 for float and integer inputs (while DataFusion preserves input type) +/// - For Decimal128(p, s), returns Decimal128(p-s+1, 0) with scale 0 +/// (DataFusion preserves original precision and scale) +/// +/// <https://spark.apache.org/docs/latest/api/sql/index.html#floor> +#[derive(Debug, PartialEq, Eq, Hash)] +pub struct SparkFloor { + signature: Signature, +} + +impl Default for SparkFloor { + fn default() -> Self { + Self::new() + } +} + +impl SparkFloor { + pub fn new() -> Self { + Self { + signature: Signature::numeric(1, Volatility::Immutable), + } + } +} + +impl ScalarUDFImpl for SparkFloor { + fn name(&self) -> &str { + "floor" + } + + fn signature(&self) -> &Signature { + &self.signature + } + + fn return_type( + &self, + _arg_types: &[DataType], + ) -> datafusion_common::Result<DataType> { + internal_err!("return_field_from_args should be called instead") + } + + fn return_field_from_args( + &self, + args: ReturnFieldArgs, + ) -> datafusion_common::Result<FieldRef> { + let nullable = args.arg_fields.iter().any(|f| f.is_nullable()); + let return_type = match args.arg_fields[0].data_type() { + DataType::Decimal128(p, s) if *s > 0 => { + let new_p = (*p - *s as u8 + 1).clamp(1, 38); + DataType::Decimal128(new_p, 0) + } + DataType::Decimal128(p, s) => DataType::Decimal128(*p, *s), Review Comment: So would have same behavior for 0 scale as well? ########## datafusion/spark/src/function/math/floor.rs: ########## @@ -0,0 +1,195 @@ +// 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 arrow::array::cast::AsArray; +use arrow::array::types::Decimal128Type; +use arrow::array::{ArrowNativeTypeOp, Decimal128Array, Int64Array}; +use arrow::compute::kernels::arity::unary; +use arrow::datatypes::{DataType, Field, FieldRef}; +use datafusion_common::{DataFusionError, ScalarValue, exec_err, internal_err}; +use datafusion_expr::{ + ColumnarValue, ReturnFieldArgs, ScalarFunctionArgs, ScalarUDFImpl, Signature, + Volatility, +}; +use std::sync::Arc; + +/// Spark-compatible `floor` function. +/// +/// Differences from DataFusion's floor: +/// - Returns Int64 for float and integer inputs (while DataFusion preserves input type) +/// - For Decimal128(p, s), returns Decimal128(p-s+1, 0) with scale 0 +/// (DataFusion preserves original precision and scale) +/// +/// <https://spark.apache.org/docs/latest/api/sql/index.html#floor> +#[derive(Debug, PartialEq, Eq, Hash)] +pub struct SparkFloor { + signature: Signature, +} + +impl Default for SparkFloor { + fn default() -> Self { + Self::new() + } +} + +impl SparkFloor { + pub fn new() -> Self { + Self { + signature: Signature::numeric(1, Volatility::Immutable), + } + } +} + +impl ScalarUDFImpl for SparkFloor { + fn name(&self) -> &str { + "floor" Review Comment: Does spark also support 'flooring' like it does with 'ceil' and 'ceiling' ? ########## datafusion/spark/src/function/math/floor.rs: ########## @@ -0,0 +1,195 @@ +// 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 arrow::array::cast::AsArray; +use arrow::array::types::Decimal128Type; +use arrow::array::{ArrowNativeTypeOp, Decimal128Array, Int64Array}; +use arrow::compute::kernels::arity::unary; +use arrow::datatypes::{DataType, Field, FieldRef}; +use datafusion_common::{DataFusionError, ScalarValue, exec_err, internal_err}; +use datafusion_expr::{ + ColumnarValue, ReturnFieldArgs, ScalarFunctionArgs, ScalarUDFImpl, Signature, + Volatility, +}; +use std::sync::Arc; + +/// Spark-compatible `floor` function. +/// +/// Differences from DataFusion's floor: +/// - Returns Int64 for float and integer inputs (while DataFusion preserves input type) +/// - For Decimal128(p, s), returns Decimal128(p-s+1, 0) with scale 0 +/// (DataFusion preserves original precision and scale) +/// +/// <https://spark.apache.org/docs/latest/api/sql/index.html#floor> +#[derive(Debug, PartialEq, Eq, Hash)] +pub struct SparkFloor { + signature: Signature, +} + +impl Default for SparkFloor { + fn default() -> Self { + Self::new() + } +} + +impl SparkFloor { + pub fn new() -> Self { + Self { + signature: Signature::numeric(1, Volatility::Immutable), + } + } +} + +impl ScalarUDFImpl for SparkFloor { + fn name(&self) -> &str { + "floor" + } + + fn signature(&self) -> &Signature { + &self.signature + } + + fn return_type( + &self, + _arg_types: &[DataType], + ) -> datafusion_common::Result<DataType> { + internal_err!("return_field_from_args should be called instead") + } + + fn return_field_from_args( + &self, + args: ReturnFieldArgs, + ) -> datafusion_common::Result<FieldRef> { + let nullable = args.arg_fields.iter().any(|f| f.is_nullable()); + let return_type = match args.arg_fields[0].data_type() { + DataType::Decimal128(p, s) if *s > 0 => { + let new_p = (*p - *s as u8 + 1).clamp(1, 38); + DataType::Decimal128(new_p, 0) + } + DataType::Decimal128(p, s) => DataType::Decimal128(*p, *s), + DataType::Float32 | DataType::Float64 | DataType::Int8 | DataType::Int16 | + DataType::Int32 | DataType::Int64 => { + DataType::Int64 + } + _ => exec_err!( + "found unsupported return type {:?}", + args.arg_fields[0].data_type() + )?, + }; + Ok(Arc::new(Field::new(self.name(), return_type, nullable))) + } + + fn invoke_with_args( + &self, + args: ScalarFunctionArgs, + ) -> datafusion_common::Result<ColumnarValue> { + spark_floor(&args.args, args.return_field.data_type()) + } +} + +macro_rules! apply_int64 { + ($value:expr, $arr_type:ty, $scalar_variant:path, $f:expr) => { + match $value { + ColumnarValue::Array(array) => { + let result: Int64Array = unary(array.as_primitive::<$arr_type>(), $f); + Ok(ColumnarValue::Array(Arc::new(result))) + } + ColumnarValue::Scalar($scalar_variant(v)) => { + Ok(ColumnarValue::Scalar(ScalarValue::Int64(v.map($f)))) + } + other => internal_err!( + "floor: expected {} but got {:?}", Review Comment: Could we make error message a bit more robust to suggest datatype mismatch ? ########## datafusion/sqllogictest/test_files/spark/math/floor.slt: ########## @@ -15,28 +15,206 @@ # specific language governing permissions and limitations # under the License. -# This file was originally created by a porting script from: -# https://github.com/lakehq/sail/tree/43b6ed8221de5c4c4adbedbb267ae1351158b43c/crates/sail-spark-connect/tests/gold_data/function -# This file is part of the implementation of the datafusion-spark function library. -# For more information, please see: -# https://github.com/apache/datafusion/issues/15914 - -## Original Query: SELECT floor(-0.1); -## PySpark 3.5.5 Result: {'FLOOR(-0.1)': Decimal('-1'), 'typeof(FLOOR(-0.1))': 'decimal(1,0)', 'typeof(-0.1)': 'decimal(1,1)'} -#query -#SELECT floor(-0.1::decimal(1,1)); - -## Original Query: SELECT floor(3.1411, -3); -## PySpark 3.5.5 Result: {'floor(3.1411, -3)': Decimal('0'), 'typeof(floor(3.1411, -3))': 'decimal(4,0)', 'typeof(3.1411)': 'decimal(5,4)', 'typeof(-3)': 'int'} -#query -#SELECT floor(3.1411::decimal(5,4), -3::int); - -## Original Query: SELECT floor(3.1411, 3); -## PySpark 3.5.5 Result: {'floor(3.1411, 3)': Decimal('3.141'), 'typeof(floor(3.1411, 3))': 'decimal(5,3)', 'typeof(3.1411)': 'decimal(5,4)', 'typeof(3)': 'int'} -#query -#SELECT floor(3.1411::decimal(5,4), 3::int); - -## Original Query: SELECT floor(5); -## PySpark 3.5.5 Result: {'FLOOR(5)': 5, 'typeof(FLOOR(5))': 'bigint', 'typeof(5)': 'int'} -#query -#SELECT floor(5::int); +############# +## Scalars ## +############# + +# Float64 tests - returns Int64 +query IT +SELECT floor(1.1), arrow_typeof(floor(1.1)); +---- +1 Int64 + +query IT +SELECT floor(-1.1), arrow_typeof(floor(-1.1)); +---- +-2 Int64 + +query IT +SELECT floor(0.0), arrow_typeof(floor(0.0)); +---- +0 Int64 + +# Float32 tests - returns Int64 +query IT +SELECT floor(arrow_cast(1.5, 'Float32')), arrow_typeof(floor(arrow_cast(1.5, 'Float32'))); +---- +1 Int64 Review Comment: Would love to have tests for Nan/ Infinity etc ########## datafusion/sqllogictest/test_files/spark/math/floor.slt: ########## @@ -15,28 +15,206 @@ # specific language governing permissions and limitations # under the License. -# This file was originally created by a porting script from: -# https://github.com/lakehq/sail/tree/43b6ed8221de5c4c4adbedbb267ae1351158b43c/crates/sail-spark-connect/tests/gold_data/function -# This file is part of the implementation of the datafusion-spark function library. -# For more information, please see: -# https://github.com/apache/datafusion/issues/15914 - -## Original Query: SELECT floor(-0.1); -## PySpark 3.5.5 Result: {'FLOOR(-0.1)': Decimal('-1'), 'typeof(FLOOR(-0.1))': 'decimal(1,0)', 'typeof(-0.1)': 'decimal(1,1)'} -#query -#SELECT floor(-0.1::decimal(1,1)); - -## Original Query: SELECT floor(3.1411, -3); -## PySpark 3.5.5 Result: {'floor(3.1411, -3)': Decimal('0'), 'typeof(floor(3.1411, -3))': 'decimal(4,0)', 'typeof(3.1411)': 'decimal(5,4)', 'typeof(-3)': 'int'} -#query -#SELECT floor(3.1411::decimal(5,4), -3::int); - -## Original Query: SELECT floor(3.1411, 3); -## PySpark 3.5.5 Result: {'floor(3.1411, 3)': Decimal('3.141'), 'typeof(floor(3.1411, 3))': 'decimal(5,3)', 'typeof(3.1411)': 'decimal(5,4)', 'typeof(3)': 'int'} -#query -#SELECT floor(3.1411::decimal(5,4), 3::int); - -## Original Query: SELECT floor(5); -## PySpark 3.5.5 Result: {'FLOOR(5)': 5, 'typeof(FLOOR(5))': 'bigint', 'typeof(5)': 'int'} -#query -#SELECT floor(5::int); +############# +## Scalars ## +############# + +# Float64 tests - returns Int64 +query IT +SELECT floor(1.1), arrow_typeof(floor(1.1)); +---- +1 Int64 + +query IT +SELECT floor(-1.1), arrow_typeof(floor(-1.1)); +---- +-2 Int64 + +query IT +SELECT floor(0.0), arrow_typeof(floor(0.0)); +---- +0 Int64 + +# Float32 tests - returns Int64 +query IT +SELECT floor(arrow_cast(1.5, 'Float32')), arrow_typeof(floor(arrow_cast(1.5, 'Float32'))); +---- +1 Int64 + +query IT +SELECT floor(arrow_cast(-1.5, 'Float32')), arrow_typeof(floor(arrow_cast(-1.5, 'Float32'))); +---- +-2 Int64 + +# Integer tests - returns Int64 +query IT +SELECT floor(arrow_cast(5, 'Int8')), arrow_typeof(floor(arrow_cast(5, 'Int8'))); +---- +5 Int64 + +query IT +SELECT floor(arrow_cast(-5, 'Int16')), arrow_typeof(floor(arrow_cast(-5, 'Int16'))); +---- +-5 Int64 + +query IT +SELECT floor(arrow_cast(1000, 'Int32')), arrow_typeof(floor(arrow_cast(1000, 'Int32'))); +---- +1000 Int64 + +query IT +SELECT floor(arrow_cast(-1000, 'Int64')), arrow_typeof(floor(arrow_cast(-1000, 'Int64'))); Review Comment: Could we also add some tests for boundary cases? -- 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]
