Skip to content
Open
124 changes: 124 additions & 0 deletions datafusion/spark/src/function/datetime/dayname.rs
Original file line number Diff line number Diff line change
@@ -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()),
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 ?

)]),
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())?;
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 ?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Invalid strings will be replaced with null values.

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,
Comment thread
kazantsev-maksim marked this conversation as resolved.
}
}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I dont think we are handling timezone's support here ? Spark handles timezone in current implementation and this could produce wrong results

Comment thread
kazantsev-maksim marked this conversation as resolved.
8 changes: 8 additions & 0 deletions datafusion/spark/src/function/datetime/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ pub mod date_diff;
pub mod date_part;
pub mod date_sub;
pub mod date_trunc;
pub mod dayname;
pub mod extract;
pub mod from_utc_timestamp;
pub mod last_day;
Expand Down Expand Up @@ -72,6 +73,7 @@ make_udf_function!(
unix_seconds,
unix::SparkUnixTimestamp::seconds
);
make_udf_function!(dayname::SparkDayName, dayname);

pub mod expr_fn {
use datafusion_functions::export_functions;
Expand Down Expand Up @@ -179,6 +181,11 @@ pub mod expr_fn {
"Returns the number of seconds since epoch (1970-01-01 00:00:00 UTC) for the given timestamp `ts`.",
ts
));
export_functions!((
dayname,
"Returns the three-letter abbreviated day name from the given date.",
arg1
));
}

pub fn functions() -> Vec<Arc<ScalarUDF>> {
Expand All @@ -204,5 +211,6 @@ pub fn functions() -> Vec<Arc<ScalarUDF>> {
unix_micros(),
unix_millis(),
unix_seconds(),
dayname(),
]
}
76 changes: 76 additions & 0 deletions datafusion/sqllogictest/test_files/spark/datetime/dayname.slt
Original file line number Diff line number Diff line change
@@ -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);
----
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we also verify that the data type matches the spark data types (Itf8 / LargeUtf8 / Utf8View)

Comment thread
kazantsev-maksim marked this conversation as resolved.
Wed

query T
SELECT dayname(NULL::DATE);
----
Comment thread
kazantsev-maksim marked this conversation as resolved.
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
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I tested this in Spark 4.1.1 and found that the empty string behavior depends on ANSI mode:

-- ANSI on (Spark 4 default):
spark-sql> SELECT dayname('');
[CAST_INVALID_INPUT] The value '' of the type "STRING" cannot be cast to "DATE" ...

-- ANSI off:
spark-sql> SET spark.sql.ansi.enabled=false;
spark-sql> SELECT dayname('');
NULL

The current implementation returns NULL, which matches the non-ANSI behavior. Since Spark 4 defaults to ANSI mode, it might be worth supporting both behaviors here — maybe through an enable_ansi_mode flag similar to how mod/pmod handle it in the same crate. That way the caller (e.g. Comet or another Spark-compatible engine) can choose whether invalid string-to-date casts should error or return NULL, matching whichever ANSI mode the user has configured.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How does this work in terms of nullability? The nullability of dayname seems accurate to Spark (depends on input) but if invalid strings are returned as null, that could violate the contract here. Is it because in Spark that config applies at a previous cast layer instead of during the function execution as in here?

SELECT dayname(''::STRING);
----
NULL

query T
SELECT dayname('2010-04-24'::TIMESTAMP);
----
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we also tests to add actual timestamps instead of dates parsed as timestamps here ?

Sat
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We might need tests to cover various timezones (atleast one apart from UTC) :)

Loading