martin-g commented on code in PR #19845: URL: https://github.com/apache/datafusion/pull/19845#discussion_r2698275530
########## datafusion/sqllogictest/test_files/spark/datetime/date_diff.slt: ########## @@ -15,18 +15,100 @@ # 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 date_diff('2009-07-30', '2009-07-31'); -## PySpark 3.5.5 Result: {'date_diff(2009-07-30, 2009-07-31)': -1, 'typeof(date_diff(2009-07-30, 2009-07-31))': 'int', 'typeof(2009-07-30)': 'string', 'typeof(2009-07-31)': 'string'} -#query -#SELECT date_diff('2009-07-30'::string, '2009-07-31'::string); - -## Original Query: SELECT date_diff('2009-07-31', '2009-07-30'); -## PySpark 3.5.5 Result: {'date_diff(2009-07-31, 2009-07-30)': 1, 'typeof(date_diff(2009-07-31, 2009-07-30))': 'int', 'typeof(2009-07-31)': 'string', 'typeof(2009-07-30)': 'string'} -#query -#SELECT date_diff('2009-07-31'::string, '2009-07-30'::string); +# date input +query I +SELECT date_diff('2009-07-30'::date, '2009-07-31'::date); +---- +-1 + +query I +SELECT date_diff('2009-07-31'::date, '2009-07-30'::date); +---- +1 + +# Same date returns 0 +query I +SELECT date_diff('2009-07-30'::date, '2009-07-30'::date); +---- +0 + +# Large difference +query I +SELECT date_diff('2020-01-01'::date, '1970-01-01'::date); +---- +18262 + +# timestamp input +query I +SELECT date_diff('2009-07-30 12:34:56'::timestamp, '2009-07-31 23:45:01'::timestamp); +---- +-1 + +query I +SELECT date_diff('2009-07-31 23:45:01'::timestamp, '2009-07-30 12:34:56'::timestamp); +---- +1 + +# string input +query I +SELECT date_diff('2009-07-30', '2009-07-31'); +---- +-1 + +query I +SELECT date_diff('2009-07-31', '2009-07-30'); +---- +1 + +# NULL handling +query I +SELECT date_diff(NULL::date, '2009-07-30'::date); +---- +NULL + +query I +SELECT date_diff('2009-07-31'::date, NULL::date); +---- +NULL + +query I +SELECT date_diff(NULL::date, NULL::date); +---- +NULL + +query I +SELECT date_diff(column1, column2) +FROM VALUES +('2009-07-30'::date, '2009-07-31'::date), +('2009-07-31'::date, '2009-07-30'::date), Review Comment: and also a Timestamp and a Date ```suggestion ('2009-07-31 23:45:01'::timestamp, '2009-07-30'::date), ``` ########## datafusion/spark/src/function/datetime/date_diff.rs: ########## @@ -0,0 +1,118 @@ +// 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::datatypes::{DataType, Field, FieldRef}; +use datafusion_common::types::{NativeType, logical_date, logical_string}; +use datafusion_common::utils::take_function_args; +use datafusion_common::{Result, internal_err}; +use datafusion_expr::simplify::{ExprSimplifyResult, SimplifyContext}; +use datafusion_expr::{ + Coercion, ColumnarValue, Expr, ExprSchemable, Operator, ReturnFieldArgs, + ScalarFunctionArgs, ScalarUDFImpl, Signature, TypeSignatureClass, Volatility, + binary_expr, +}; + +/// <https://spark.apache.org/docs/latest/api/sql/index.html#date_diff> +#[derive(Debug, PartialEq, Eq, Hash)] +pub struct SparkDateDiff { + signature: Signature, + aliases: Vec<String>, +} + +impl Default for SparkDateDiff { + fn default() -> Self { + Self::new() + } +} + +impl SparkDateDiff { + pub fn new() -> Self { + Self { + signature: Signature::coercible( + vec![ + Coercion::new_implicit( + TypeSignatureClass::Native(logical_date()), + vec![ + TypeSignatureClass::Native(logical_string()), + TypeSignatureClass::Timestamp, + ], + NativeType::Date, + ), + Coercion::new_implicit( + TypeSignatureClass::Native(logical_date()), + vec![ + TypeSignatureClass::Native(logical_string()), + TypeSignatureClass::Timestamp, + ], + NativeType::Date, + ), + ], + Volatility::Immutable, + ), + aliases: vec!["datediff".to_string()], + } + } +} + +impl ScalarUDFImpl for SparkDateDiff { + fn as_any(&self) -> &dyn Any { + self + } + + fn name(&self) -> &str { + "date_diff" + } + + fn aliases(&self) -> &[String] { + &self.aliases + } + + fn signature(&self) -> &Signature { + &self.signature + } + + fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> { + internal_err!("return_field_from_args should be used instead") + } + + fn return_field_from_args(&self, args: ReturnFieldArgs) -> Result<FieldRef> { + let nullable = args.arg_fields.iter().any(|f| f.is_nullable()); + Ok(Arc::new(Field::new(self.name(), DataType::Int32, nullable))) + } + + fn invoke_with_args(&self, _args: ScalarFunctionArgs) -> Result<ColumnarValue> { + internal_err!( + "spark date_diff should have been simplified to standard subtraction" Review Comment: ```suggestion "Spark `date_diff` should have been simplified to standard subtraction" ``` I am not sure whether ASF branding rules should be obeyed here. Usually all Apache projects should be referred with `Apache ` in front, i.e. `Apache Spark ...` ########## datafusion/sqllogictest/test_files/spark/datetime/date_diff.slt: ########## @@ -15,18 +15,100 @@ # 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 date_diff('2009-07-30', '2009-07-31'); -## PySpark 3.5.5 Result: {'date_diff(2009-07-30, 2009-07-31)': -1, 'typeof(date_diff(2009-07-30, 2009-07-31))': 'int', 'typeof(2009-07-30)': 'string', 'typeof(2009-07-31)': 'string'} -#query -#SELECT date_diff('2009-07-30'::string, '2009-07-31'::string); - -## Original Query: SELECT date_diff('2009-07-31', '2009-07-30'); -## PySpark 3.5.5 Result: {'date_diff(2009-07-31, 2009-07-30)': 1, 'typeof(date_diff(2009-07-31, 2009-07-30))': 'int', 'typeof(2009-07-31)': 'string', 'typeof(2009-07-30)': 'string'} -#query -#SELECT date_diff('2009-07-31'::string, '2009-07-30'::string); +# date input +query I +SELECT date_diff('2009-07-30'::date, '2009-07-31'::date); +---- +-1 + +query I +SELECT date_diff('2009-07-31'::date, '2009-07-30'::date); +---- +1 + +# Same date returns 0 +query I +SELECT date_diff('2009-07-30'::date, '2009-07-30'::date); +---- +0 + +# Large difference +query I +SELECT date_diff('2020-01-01'::date, '1970-01-01'::date); +---- +18262 + +# timestamp input +query I +SELECT date_diff('2009-07-30 12:34:56'::timestamp, '2009-07-31 23:45:01'::timestamp); +---- +-1 + +query I +SELECT date_diff('2009-07-31 23:45:01'::timestamp, '2009-07-30 12:34:56'::timestamp); +---- +1 + +# string input +query I +SELECT date_diff('2009-07-30', '2009-07-31'); +---- +-1 + +query I +SELECT date_diff('2009-07-31', '2009-07-30'); +---- +1 + +# NULL handling +query I +SELECT date_diff(NULL::date, '2009-07-30'::date); +---- +NULL + +query I +SELECT date_diff('2009-07-31'::date, NULL::date); +---- +NULL + +query I +SELECT date_diff(NULL::date, NULL::date); +---- +NULL + +query I +SELECT date_diff(column1, column2) +FROM VALUES +('2009-07-30'::date, '2009-07-31'::date), +('2009-07-31'::date, '2009-07-30'::date), Review Comment: Does it make sense to add a test case for different input types ? E.g. a Date and a String: ```suggestion ('2009-07-31'::date, '2009-07-30'::date), ('2009-07-31'::date, '2009-07-30'), ``` ########## datafusion/spark/src/function/datetime/date_diff.rs: ########## @@ -0,0 +1,118 @@ +// 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::datatypes::{DataType, Field, FieldRef}; +use datafusion_common::types::{NativeType, logical_date, logical_string}; +use datafusion_common::utils::take_function_args; +use datafusion_common::{Result, internal_err}; +use datafusion_expr::simplify::{ExprSimplifyResult, SimplifyContext}; +use datafusion_expr::{ + Coercion, ColumnarValue, Expr, ExprSchemable, Operator, ReturnFieldArgs, + ScalarFunctionArgs, ScalarUDFImpl, Signature, TypeSignatureClass, Volatility, + binary_expr, +}; + +/// <https://spark.apache.org/docs/latest/api/sql/index.html#date_diff> +#[derive(Debug, PartialEq, Eq, Hash)] +pub struct SparkDateDiff { + signature: Signature, + aliases: Vec<String>, +} + +impl Default for SparkDateDiff { + fn default() -> Self { + Self::new() + } +} + +impl SparkDateDiff { + pub fn new() -> Self { + Self { + signature: Signature::coercible( + vec![ + Coercion::new_implicit( + TypeSignatureClass::Native(logical_date()), + vec![ + TypeSignatureClass::Native(logical_string()), + TypeSignatureClass::Timestamp, + ], + NativeType::Date, + ), + Coercion::new_implicit( + TypeSignatureClass::Native(logical_date()), + vec![ + TypeSignatureClass::Native(logical_string()), + TypeSignatureClass::Timestamp, + ], + NativeType::Date, + ), + ], + Volatility::Immutable, + ), + aliases: vec!["datediff".to_string()], + } + } +} + +impl ScalarUDFImpl for SparkDateDiff { + fn as_any(&self) -> &dyn Any { + self + } + + fn name(&self) -> &str { + "date_diff" + } + + fn aliases(&self) -> &[String] { + &self.aliases + } + + fn signature(&self) -> &Signature { + &self.signature + } + + fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> { + internal_err!("return_field_from_args should be used instead") + } + + fn return_field_from_args(&self, args: ReturnFieldArgs) -> Result<FieldRef> { + let nullable = args.arg_fields.iter().any(|f| f.is_nullable()); + Ok(Arc::new(Field::new(self.name(), DataType::Int32, nullable))) + } + + fn invoke_with_args(&self, _args: ScalarFunctionArgs) -> Result<ColumnarValue> { + internal_err!( + "spark date_diff should have been simplified to standard subtraction" + ) + } + + fn simplify( + &self, + args: Vec<Expr>, + info: &SimplifyContext, + ) -> Result<ExprSimplifyResult> { + let [end, start] = take_function_args(self.name(), args)?; + Ok(ExprSimplifyResult::Simplified(binary_expr( + end.cast_to(&DataType::Int32, info.schema())?, + Operator::Minus, + start.cast_to(&DataType::Int32, info.schema())?, Review Comment: What if the argument data type is Date64 ? The signature allows it. Date32 keeps the seconds since epoch, but Date64 keeps the milliseconds since epoch. -- 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]
