Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions datafusion/functions/benches/datetime_expressions/date_trunc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,33 @@ fn criterion_benchmark(c: &mut Criterion) {
Arc::clone(&nanos),
);
}

// Timezone-aware coarse granularities truncate in local time. Sorted input
// stays within one UTC offset span for long runs; random input does not.
let random_nanos = nanosecond_timestamps();
let mut sorted_values = random_nanos.values().to_vec();
sorted_values.sort_unstable();
let sorted_nanos = TimestampNanosecondArray::from(sorted_values);
for (tz, label, granularities) in [
(
"America/New_York",
"new_york",
&["hour", "day", "month", "year"][..],
),
("UTC", "utc", &["hour", "day"][..]),
] {
for (order, array) in [("random", &random_nanos), ("sorted", &sorted_nanos)] {
let array: ArrayRef = Arc::new(array.clone().with_timezone(tz));
for granularity in granularities {
run_benchmark(
c,
&format!("date_trunc_{granularity}_{label}_{order}_nanos_1000"),
granularity,
Arc::clone(&array),
);
}
}
}
}

criterion_group!(benches, criterion_benchmark);
245 changes: 244 additions & 1 deletion datafusion/functions/src/datetime/date_trunc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,14 @@
// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements

use std::cell::Cell;
use std::num::NonZeroI64;
use std::ops::{Add, Sub};
use std::str::FromStr;
use std::sync::Arc;

use crate::datetime::common::parse_tz;
use crate::datetime::utc_offsets::{UtcOffsetSpan, UtcOffsetSpans};
use arrow::array::temporal_conversions::{
MICROSECONDS, MILLISECONDS, NANOSECONDS, as_datetime_with_timezone,
timestamp_ns_to_datetime,
Expand Down Expand Up @@ -290,6 +292,14 @@ impl ScalarUDFImpl for DateTruncFunc {
return Ok(ColumnarValue::Array(result));
}

if let (Some(tz_name), Some(tz)) = (tz_opt, parsed_tz)
&& let Some(spans) = UtcOffsetSpans::for_timezone(tz_name)
{
let array = date_trunc_coarse_with_spans(array, granularity, tz, &spans)?
.with_timezone_opt(tz_opt.cloned());
return Ok(ColumnarValue::Array(Arc::new(array)));
}

let array: PrimitiveArray<T> = array
.try_unary(|x| general_date_trunc(T::UNIT, x, parsed_tz, granularity))?
.with_timezone_opt(tz_opt.cloned());
Expand Down Expand Up @@ -1145,6 +1155,7 @@ fn days_from_civil(year: i64, month: i64, day: i64) -> i64 {
/// Returns `None` when the truncated timestamp is no longer representable as
/// nanoseconds since the epoch, which the caller reports as an out of range
/// error.
#[inline]
fn _date_trunc_coarse_without_tz(granularity: DatePart, value: i64) -> Option<i64> {
let truncate_to = |unit: i64| value.checked_sub(value.rem_euclid(unit));
let days = || value.div_euclid(NANOS_PER_DAY);
Expand Down Expand Up @@ -1262,6 +1273,74 @@ fn truncates_in_input_unit(granularity: DatePart, tz: Option<&Tz>) -> bool {
|| (tz.is_none() && granularity.is_fine_granularity_utc())
}

/// Truncates `array` to a granularity coarser than minute in the local time of
/// `tz`, with integer arithmetic between the UTC offset transitions of `tz`.
///
/// Like [`general_date_trunc`], it returns the instant that has the truncated
/// local time and the input's UTC offset, when one exists. If the instant
/// `truncated local time - offset` lies in the input's offset span, it has that
/// local time and offset, so it is the result. Otherwise a transition falls
/// between the bucket start and the input, and the value takes the chrono path.
/// That result depends only on the offset and the truncated local time, so the
/// last one is reused, which sorted input hits for the rest of the bucket.
fn date_trunc_coarse_with_spans<T: ArrowTimestampType>(
array: &PrimitiveArray<T>,
granularity: DatePart,
tz: Tz,
spans: &UtcOffsetSpans,
) -> Result<PrimitiveArray<T>> {
let scale = match T::UNIT {
Second => NANOS_PER_SECOND,
Millisecond => NANOS_PER_MILLISECOND,
Microsecond => NANOS_PER_MICROSECOND,
Nanosecond => 1,
};
// Sorted input stays in one span for long runs, so look it up only on a
// change. The initial span contains no instant.
let span = Cell::new(UtcOffsetSpan {
start: i64::MAX,
end: i64::MIN,
offset: 0,
});
let last_chrono_result = Cell::new(None::<(i32, i64, i64)>);
array.try_unary(|value| {
let Some(nanos) = value.checked_mul(scale) else {
return general_date_trunc(T::UNIT, value, Some(tz), granularity);
};
let seconds = nanos.div_euclid(NANOS_PER_SECOND);
let mut current = span.get();
if !current.contains(seconds) {
current = spans.span(seconds);
span.set(current);
}
let offset = i64::from(current.offset) * NANOS_PER_SECOND;
let Some(local) = nanos
.checked_add(offset)
.and_then(|local| _date_trunc_coarse_without_tz(granularity, local))
else {
return general_date_trunc(T::UNIT, value, Some(tz), granularity);
};
if let Some(truncated) = local.checked_sub(offset)
&& current.start <= truncated.div_euclid(NANOS_PER_SECOND)
{
// `truncated` is a whole number of seconds, so dividing is exact.
return Ok(truncated / scale);
}
match last_chrono_result.get() {
Some((offset, truncated_local, result))
if offset == current.offset && truncated_local == local =>
Comment thread
xudong963 marked this conversation as resolved.
Resolved
{
Ok(result)
}
_ => {
let result = general_date_trunc(T::UNIT, value, Some(tz), granularity)?;
last_chrono_result.set(Some((current.offset, local, result)));
Ok(result)
}
}
})
}

/// The length of `granularity` in `tu`, or `None` when `granularity` is no
/// coarser than `tu`, so a value in `tu` is already truncated to it.
fn fine_granularity_unit(tu: TimeUnit, granularity: DatePart) -> Option<NonZeroI64> {
Expand Down Expand Up @@ -1361,11 +1440,14 @@ mod tests {
use std::sync::Arc;

use crate::datetime::date_trunc::{
DateTruncFunc, NANOS_PER_MICROSECOND, date_trunc_coarse, general_date_trunc,
DateTruncFunc, NANOS_PER_MICROSECOND, NANOS_PER_SECOND, date_trunc_coarse,
date_trunc_coarse_with_spans, general_date_trunc,
general_date_trunc_array_fine_granularity, parse_granularity,
};
use crate::datetime::utc_offsets::UtcOffsetSpans;

use arrow::array::cast::as_primitive_array;
use arrow::array::timezone::Tz;
use arrow::array::types::{
ArrowTimestampType, TimestampMicrosecondType, TimestampMillisecondType,
TimestampNanosecondType, TimestampSecondType,
Expand All @@ -1384,6 +1466,167 @@ mod tests {
use datafusion_expr::sort_properties::{ExprProperties, SortProperties};
use datafusion_expr::{ColumnarValue, ScalarFunctionArgs, ScalarUDFImpl};

/// The arithmetic kernel agrees with the chrono path around every transition,
/// for input in ascending and descending order. The zones cover transitions at
/// and near midnight, a skipped day, sub-hour and sub-minute offsets and
/// closely spaced transitions; scanning every zone takes too long unoptimized.
#[test]
fn date_trunc_with_spans_matches_chrono_path() {
fn check<T: ArrowTimestampType>(
zone: &str,
tz: Tz,
spans: &UtcOffsetSpans,
values: &[i64],
) {
for granularity in [
DatePart::Hour,
DatePart::Day,
DatePart::Week,
DatePart::Month,
DatePart::Quarter,
DatePart::Year,
] {
let expected = values
.iter()
.map(|&value| {
general_date_trunc(T::UNIT, value, Some(tz), granularity).unwrap()
})
.collect::<Vec<_>>();
for descending in [false, true] {
let mut values = values.to_vec();
let mut expected = expected.clone();
if descending {
values.reverse();
expected.reverse();
}
let array = PrimitiveArray::<T>::from_iter_values(values.clone());
let actual =
date_trunc_coarse_with_spans(&array, granularity, tz, spans)
.unwrap();
if let Some(i) =
(0..values.len()).find(|&i| actual.value(i) != expected[i])
{
panic!(
"{zone} {granularity} {:?} descending={descending}: {} truncated to {} instead of {}",
T::UNIT,
values[i],
actual.value(i),
expected[i]
);
}
}
}
}

for zone in [
"UTC",
"+05:30",
"-09:30",
"+14:00",
"Africa/Cairo",
"Africa/Casablanca",
"America/Asuncion",
"America/Caracas",
"America/Goose_Bay",
"America/Havana",
"America/New_York",
"America/Santiago",
"America/Sao_Paulo",
"America/St_Johns",
"Antarctica/Troll",
"Asia/Gaza",
"Asia/Kathmandu",
"Asia/Pyongyang",
"Asia/Tehran",
"Australia/Lord_Howe",
"Europe/Dublin",
"Europe/London",
"Europe/Moscow",
"Pacific/Apia",
"Pacific/Chatham",
"Pacific/Kiritimati",
] {
let tz: Tz = zone.parse().unwrap();
let spans = UtcOffsetSpans::for_timezone(zone).unwrap();
let mut seconds = spans
.transitions()
.iter()
.flat_map(|&transition| {
[-86_400, -3600, -1, 0, 1, 3600, 86_400]
.map(|delta| transition + delta)
})
.chain([-1, 0, 1_700_000_000])
.collect::<Vec<_>>();
seconds.sort_unstable();
seconds.dedup();
check::<TimestampSecondType>(zone, tz, &spans, &seconds);
let nanos = seconds
.iter()
.map(|&seconds| seconds * NANOS_PER_SECOND + 123_456_789)
.collect::<Vec<_>>();
check::<TimestampNanosecondType>(zone, tz, &spans, &nanos);
}
}

#[test]
fn date_trunc_with_spans_reports_out_of_range_like_chrono_path() {
// Near `i64::MIN`, adding New York's offset overflows, while Tokyo's
// offset is added and the truncation overflows.
for (zone, granularity) in ["America/New_York", "Asia/Tokyo"]
.into_iter()
.flat_map(|zone| {
[DatePart::Hour, DatePart::Day, DatePart::Year].map(|g| (zone, g))
})
{
let tz: Tz = zone.parse().unwrap();
let spans = UtcOffsetSpans::for_timezone(zone).unwrap();
// Beyond the nanosecond range, and truncated below it.
for value in [i64::MAX / 2, i64::MIN / 1_000_000_000] {
let array = PrimitiveArray::<TimestampSecondType>::from(vec![value]);
assert_eq!(
date_trunc_coarse_with_spans(&array, granularity, tz, &spans)
.unwrap_err()
.strip_backtrace(),
general_date_trunc(TimeUnit::Second, value, Some(tz), granularity)
.unwrap_err()
.strip_backtrace(),
);
}
let array = PrimitiveArray::<TimestampNanosecondType>::from(vec![
Some(i64::MIN + 1),
None,
]);
assert_eq!(
date_trunc_coarse_with_spans(&array, granularity, tz, &spans)
.map_err(|e| e.strip_backtrace()),
general_date_trunc(
TimeUnit::Nanosecond,
i64::MIN + 1,
Some(tz),
granularity
)
.map(|_| array.clone())
.map_err(|e| e.strip_backtrace()),
);
}
}

/// America/Creston fell back at 1944-01-01 00:01, so midnight that day is
/// ambiguous. August (UTC-6) and November (UTC-7) both truncate to it on the
/// chrono path, which picks the instant with the input's offset.
#[test]
fn date_trunc_with_spans_reuses_chrono_result_only_for_same_offset() {
let tz: Tz = "America/Creston".parse().unwrap();
let spans = UtcOffsetSpans::for_timezone("America/Creston").unwrap();
// 1944-08-18T19:39:14Z and 1944-11-08T00:10:20Z
let array =
PrimitiveArray::<TimestampSecondType>::from(vec![-800_598_046, -793_583_380]);
let actual =
date_trunc_coarse_with_spans(&array, DatePart::Year, tz, &spans).unwrap();
// 1944-01-01T00:00-06:00 and 1944-01-01T00:00-07:00
assert_eq!(actual.values(), &[-820_519_200, -820_515_600]);
}

#[test]
fn output_ordering_respects_timestamp_timezone() {
let precision_value = ScalarValue::Utf8(Some("hour".into()));
Expand Down
1 change: 1 addition & 0 deletions datafusion/functions/src/datetime/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ pub mod to_local_time;
pub mod to_time;
pub mod to_timestamp;
pub mod to_unixtime;
pub(crate) mod utc_offsets;

// create UDFs
make_udf_function!(current_date::CurrentDateFunc, current_date);
Expand Down
Loading