coderfender commented on code in PR #20825: URL: https://github.com/apache/datafusion/pull/20825#discussion_r3005777030
########## datafusion/sqllogictest/test_files/spark/datetime/dayname.slt: ########## @@ -0,0 +1,76 @@ +# 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. + +query T +SELECT dayname('2008-02-20'::DATE); +---- +Wed + +query T +SELECT dayname(NULL::DATE); +---- Review Comment: We might also want to check NULL cases for timestamps here as well ? ########## datafusion/spark/src/function/datetime/dayname.rs: ########## @@ -0,0 +1,124 @@ +// 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::{Array, ArrayRef, AsArray, StringArray}; +use arrow::compute::{CastOptions, DatePart, cast_with_options, date_part}; +use arrow::datatypes::{DataType, Field, FieldRef, Int32Type}; +use datafusion::logical_expr::{ + Coercion, ColumnarValue, Signature, TypeSignature, TypeSignatureClass, Volatility, +}; +use datafusion_common::types::{logical_date, logical_string}; +use datafusion_common::utils::take_function_args; +use datafusion_common::{Result, internal_err}; +use datafusion_expr::{ReturnFieldArgs, ScalarFunctionArgs, ScalarUDFImpl}; +use datafusion_functions::utils::make_scalar_function; +use std::sync::Arc; + +#[derive(Debug, PartialEq, Eq, Hash)] +pub struct SparkDayName { + signature: Signature, +} + +impl Default for SparkDayName { + fn default() -> Self { + Self::new() + } +} + +impl SparkDayName { + pub fn new() -> Self { + Self { + signature: Signature::one_of( + vec![ + TypeSignature::Coercible(vec![Coercion::new_exact( + TypeSignatureClass::Timestamp, + )]), + TypeSignature::Coercible(vec![Coercion::new_exact( + TypeSignatureClass::Native(logical_date()), Review Comment: Spark's date `java.util.date` is `Date32` on Rust side of things . Given that we are not handling `Date64` in the match arm , do you still think we should have `logical_date()` as one of the signature supporting Date32 / Date64 ? Perhaps we could change to Date32 ? ########## datafusion/spark/src/function/datetime/dayname.rs: ########## @@ -0,0 +1,124 @@ +// 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::{Array, ArrayRef, AsArray, StringArray}; +use arrow::compute::{CastOptions, DatePart, cast_with_options, date_part}; +use arrow::datatypes::{DataType, Field, FieldRef, Int32Type}; +use datafusion::logical_expr::{ + Coercion, ColumnarValue, Signature, TypeSignature, TypeSignatureClass, Volatility, +}; +use datafusion_common::types::{logical_date, logical_string}; +use datafusion_common::utils::take_function_args; +use datafusion_common::{Result, internal_err}; +use datafusion_expr::{ReturnFieldArgs, ScalarFunctionArgs, ScalarUDFImpl}; +use datafusion_functions::utils::make_scalar_function; +use std::sync::Arc; + +#[derive(Debug, PartialEq, Eq, Hash)] +pub struct SparkDayName { + signature: Signature, +} + +impl Default for SparkDayName { + fn default() -> Self { + Self::new() + } +} + +impl SparkDayName { + pub fn new() -> Self { + Self { + signature: Signature::one_of( + vec![ + TypeSignature::Coercible(vec![Coercion::new_exact( + TypeSignatureClass::Timestamp, + )]), + TypeSignature::Coercible(vec![Coercion::new_exact( + TypeSignatureClass::Native(logical_date()), + )]), + TypeSignature::Coercible(vec![Coercion::new_exact( + TypeSignatureClass::Native(logical_string()), + )]), + ], + Volatility::Immutable, + ), + } + } +} + +impl ScalarUDFImpl for SparkDayName { + fn name(&self) -> &str { + "dayname" + } + + 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> { + Ok(Arc::new(Field::new( + self.name(), + DataType::Utf8, + args.arg_fields[0].is_nullable(), + ))) + } + + fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> { + make_scalar_function(spark_day_name, vec![])(&args.args) + } +} + +fn spark_day_name(args: &[ArrayRef]) -> Result<ArrayRef> { + let [array] = take_function_args("dayname", args)?; + match array.data_type() { + DataType::Date32 | DataType::Timestamp(_, _) => spark_day_name_inner(array), + DataType::Utf8 | DataType::Utf8View | DataType::LargeUtf8 => { + let date_array = + cast_with_options(array, &DataType::Date32, &CastOptions::default())?; + spark_day_name_inner(&date_array) + } + other => { + internal_err!("Unsupported arg {other:?} for Spark function `dayname`") + } + } +} + +fn spark_day_name_inner(array: &ArrayRef) -> Result<ArrayRef> { + let result: StringArray = date_part(array, DatePart::DayOfWeekMonday0)? + .as_primitive::<Int32Type>() + .iter() + .map(|x| x.and_then(get_display_name)) + .collect(); + Ok(Arc::new(result)) +} + +fn get_display_name(day: i32) -> Option<String> { + match day { + 0 => Some(String::from("Mon")), + 1 => Some(String::from("Tue")), + 2 => Some(String::from("Wed")), + 3 => Some(String::from("Thu")), + 4 => Some(String::from("Fri")), + 5 => Some(String::from("Sat")), + 6 => Some(String::from("Sun")), + _ => None, + } +} Review Comment: nit : could we also add unit tests apart from the SQL tests to test out method signatures , invalid inputs , error handling , timezone support etc ? ########## datafusion/sqllogictest/test_files/spark/datetime/dayname.slt: ########## @@ -0,0 +1,76 @@ +# 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. + +query T +SELECT dayname('2008-02-20'::DATE); +---- +Wed + +query T +SELECT dayname(NULL::DATE); +---- +NULL + +query T +SELECT dayname('2026-03-09'::DATE); +---- +Mon + +query T +SELECT dayname('2026-03-08'::DATE); +---- +Sun + +query T +SELECT dayname('1948-08-10'::DATE); +---- +Tue + +query T +SELECT dayname('1987-11-13'::DATE); +---- +Fri + +query T +SELECT dayname('2000-07-27'::DATE); +---- +Thu + +query T +SELECT dayname('2010-04-24'::DATE); +---- +Sat + +query T +SELECT dayname('2010-04-24'::STRING); +---- +Sat + +query T +SELECT dayname(NULL::STRING); +---- +NULL + +query T +SELECT dayname(''::STRING); +---- +NULL + +query T +SELECT dayname('2010-04-24'::TIMESTAMP); +---- +Sat Review Comment: We might need tests to cover various timezones (atleast one apart from UTC) :) ########## datafusion/spark/src/function/datetime/dayname.rs: ########## @@ -0,0 +1,124 @@ +// 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::{Array, ArrayRef, AsArray, StringArray}; +use arrow::compute::{CastOptions, DatePart, cast_with_options, date_part}; +use arrow::datatypes::{DataType, Field, FieldRef, Int32Type}; +use datafusion::logical_expr::{ + Coercion, ColumnarValue, Signature, TypeSignature, TypeSignatureClass, Volatility, +}; +use datafusion_common::types::{logical_date, logical_string}; +use datafusion_common::utils::take_function_args; +use datafusion_common::{Result, internal_err}; +use datafusion_expr::{ReturnFieldArgs, ScalarFunctionArgs, ScalarUDFImpl}; +use datafusion_functions::utils::make_scalar_function; +use std::sync::Arc; + +#[derive(Debug, PartialEq, Eq, Hash)] +pub struct SparkDayName { + signature: Signature, +} + +impl Default for SparkDayName { + fn default() -> Self { + Self::new() + } +} + +impl SparkDayName { + pub fn new() -> Self { + Self { + signature: Signature::one_of( + vec![ + TypeSignature::Coercible(vec![Coercion::new_exact( + TypeSignatureClass::Timestamp, + )]), + TypeSignature::Coercible(vec![Coercion::new_exact( + TypeSignatureClass::Native(logical_date()), + )]), + TypeSignature::Coercible(vec![Coercion::new_exact( + TypeSignatureClass::Native(logical_string()), + )]), + ], + Volatility::Immutable, + ), + } + } +} + +impl ScalarUDFImpl for SparkDayName { + fn name(&self) -> &str { + "dayname" + } + + 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> { + Ok(Arc::new(Field::new( + self.name(), + DataType::Utf8, + args.arg_fields[0].is_nullable(), + ))) + } + + fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> { + make_scalar_function(spark_day_name, vec![])(&args.args) + } +} + +fn spark_day_name(args: &[ArrayRef]) -> Result<ArrayRef> { + let [array] = take_function_args("dayname", args)?; + match array.data_type() { + DataType::Date32 | DataType::Timestamp(_, _) => spark_day_name_inner(array), + DataType::Utf8 | DataType::Utf8View | DataType::LargeUtf8 => { + let date_array = + cast_with_options(array, &DataType::Date32, &CastOptions::default())?; Review Comment: What would happen in case of an invalid string / error here ? Could probably handle it here and throw an error if it is a malformed input ? ########## datafusion/sqllogictest/test_files/spark/datetime/dayname.slt: ########## @@ -0,0 +1,76 @@ +# 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. + +query T +SELECT dayname('2008-02-20'::DATE); +---- +Wed + +query T +SELECT dayname(NULL::DATE); +---- +NULL + +query T +SELECT dayname('2026-03-09'::DATE); +---- +Mon + +query T +SELECT dayname('2026-03-08'::DATE); +---- +Sun + +query T +SELECT dayname('1948-08-10'::DATE); +---- +Tue + +query T +SELECT dayname('1987-11-13'::DATE); +---- +Fri + +query T +SELECT dayname('2000-07-27'::DATE); +---- +Thu + +query T +SELECT dayname('2010-04-24'::DATE); +---- +Sat + +query T +SELECT dayname('2010-04-24'::STRING); +---- +Sat + +query T +SELECT dayname(NULL::STRING); +---- +NULL + +query T +SELECT dayname(''::STRING); +---- +NULL + +query T +SELECT dayname('2010-04-24'::TIMESTAMP); +---- Review Comment: Could we also tests to add actual timestamps instead of dates parsed as timestamps here ? ########## datafusion/spark/src/function/datetime/dayname.rs: ########## @@ -0,0 +1,124 @@ +// 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::{Array, ArrayRef, AsArray, StringArray}; +use arrow::compute::{CastOptions, DatePart, cast_with_options, date_part}; +use arrow::datatypes::{DataType, Field, FieldRef, Int32Type}; +use datafusion::logical_expr::{ + Coercion, ColumnarValue, Signature, TypeSignature, TypeSignatureClass, Volatility, +}; +use datafusion_common::types::{logical_date, logical_string}; +use datafusion_common::utils::take_function_args; +use datafusion_common::{Result, internal_err}; +use datafusion_expr::{ReturnFieldArgs, ScalarFunctionArgs, ScalarUDFImpl}; +use datafusion_functions::utils::make_scalar_function; +use std::sync::Arc; + +#[derive(Debug, PartialEq, Eq, Hash)] +pub struct SparkDayName { + signature: Signature, +} + +impl Default for SparkDayName { + fn default() -> Self { + Self::new() + } +} + +impl SparkDayName { + pub fn new() -> Self { + Self { + signature: Signature::one_of( + vec![ + TypeSignature::Coercible(vec![Coercion::new_exact( + TypeSignatureClass::Timestamp, + )]), + TypeSignature::Coercible(vec![Coercion::new_exact( + TypeSignatureClass::Native(logical_date()), + )]), + TypeSignature::Coercible(vec![Coercion::new_exact( + TypeSignatureClass::Native(logical_string()), + )]), + ], + Volatility::Immutable, + ), + } + } +} + +impl ScalarUDFImpl for SparkDayName { + fn name(&self) -> &str { + "dayname" + } + + 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> { + Ok(Arc::new(Field::new( + self.name(), + DataType::Utf8, + args.arg_fields[0].is_nullable(), + ))) + } + + fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> { + make_scalar_function(spark_day_name, vec![])(&args.args) + } +} + +fn spark_day_name(args: &[ArrayRef]) -> Result<ArrayRef> { + let [array] = take_function_args("dayname", args)?; + match array.data_type() { + DataType::Date32 | DataType::Timestamp(_, _) => spark_day_name_inner(array), + DataType::Utf8 | DataType::Utf8View | DataType::LargeUtf8 => { + let date_array = + cast_with_options(array, &DataType::Date32, &CastOptions::default())?; + spark_day_name_inner(&date_array) + } + other => { + internal_err!("Unsupported arg {other:?} for Spark function `dayname`") + } + } +} + +fn spark_day_name_inner(array: &ArrayRef) -> Result<ArrayRef> { + let result: StringArray = date_part(array, DatePart::DayOfWeekMonday0)? + .as_primitive::<Int32Type>() + .iter() + .map(|x| x.and_then(get_display_name)) + .collect(); + Ok(Arc::new(result)) +} + +fn get_display_name(day: i32) -> Option<String> { + match day { + 0 => Some(String::from("Mon")), + 1 => Some(String::from("Tue")), + 2 => Some(String::from("Wed")), + 3 => Some(String::from("Thu")), + 4 => Some(String::from("Fri")), + 5 => Some(String::from("Sat")), + 6 => Some(String::from("Sun")), + _ => None, Review Comment: nit : we might also want to add a comment saying that the default local is english @kazantsev-maksim (similar to spark) ########## datafusion/spark/src/function/datetime/dayname.rs: ########## @@ -0,0 +1,124 @@ +// 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::{Array, ArrayRef, AsArray, StringArray}; +use arrow::compute::{CastOptions, DatePart, cast_with_options, date_part}; +use arrow::datatypes::{DataType, Field, FieldRef, Int32Type}; +use datafusion::logical_expr::{ + Coercion, ColumnarValue, Signature, TypeSignature, TypeSignatureClass, Volatility, +}; +use datafusion_common::types::{logical_date, logical_string}; +use datafusion_common::utils::take_function_args; +use datafusion_common::{Result, internal_err}; +use datafusion_expr::{ReturnFieldArgs, ScalarFunctionArgs, ScalarUDFImpl}; +use datafusion_functions::utils::make_scalar_function; +use std::sync::Arc; + +#[derive(Debug, PartialEq, Eq, Hash)] +pub struct SparkDayName { + signature: Signature, +} + +impl Default for SparkDayName { + fn default() -> Self { + Self::new() + } +} + +impl SparkDayName { + pub fn new() -> Self { + Self { + signature: Signature::one_of( + vec![ + TypeSignature::Coercible(vec![Coercion::new_exact( + TypeSignatureClass::Timestamp, + )]), + TypeSignature::Coercible(vec![Coercion::new_exact( + TypeSignatureClass::Native(logical_date()), + )]), + TypeSignature::Coercible(vec![Coercion::new_exact( + TypeSignatureClass::Native(logical_string()), + )]), + ], + Volatility::Immutable, + ), + } + } +} + +impl ScalarUDFImpl for SparkDayName { + fn name(&self) -> &str { + "dayname" + } + + 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> { + Ok(Arc::new(Field::new( + self.name(), + DataType::Utf8, + args.arg_fields[0].is_nullable(), + ))) + } + + fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> { + make_scalar_function(spark_day_name, vec![])(&args.args) + } +} + +fn spark_day_name(args: &[ArrayRef]) -> Result<ArrayRef> { + let [array] = take_function_args("dayname", args)?; + match array.data_type() { + DataType::Date32 | DataType::Timestamp(_, _) => spark_day_name_inner(array), + DataType::Utf8 | DataType::Utf8View | DataType::LargeUtf8 => { + let date_array = + cast_with_options(array, &DataType::Date32, &CastOptions::default())?; + spark_day_name_inner(&date_array) + } + other => { + internal_err!("Unsupported arg {other:?} for Spark function `dayname`") + } + } +} + +fn spark_day_name_inner(array: &ArrayRef) -> Result<ArrayRef> { + let result: StringArray = date_part(array, DatePart::DayOfWeekMonday0)? + .as_primitive::<Int32Type>() + .iter() + .map(|x| x.and_then(get_display_name)) + .collect(); + Ok(Arc::new(result)) +} + +fn get_display_name(day: i32) -> Option<String> { + match day { + 0 => Some(String::from("Mon")), + 1 => Some(String::from("Tue")), + 2 => Some(String::from("Wed")), + 3 => Some(String::from("Thu")), + 4 => Some(String::from("Fri")), + 5 => Some(String::from("Sat")), + 6 => Some(String::from("Sun")), + _ => None, + } +} Review Comment: I dont think we are handling timezone's support here ? Spark handles timezone in current implementation and this could produce wrong results -- 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]
