Skip to content
Open
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
139 changes: 133 additions & 6 deletions datafusion/functions/src/datetime/date_trunc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,11 @@
// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements

use std::cell::Cell;
use std::collections::HashMap;
use std::num::NonZeroI64;
use std::ops::{Add, Sub};
use std::str::FromStr;
use std::sync::Arc;
use std::sync::{Arc, LazyLock, Mutex, PoisonError};

use crate::datetime::common::parse_tz;
use crate::datetime::utc_offsets::{UtcOffsetSpan, UtcOffsetSpans};
Expand Down Expand Up @@ -562,10 +563,17 @@ impl ScalarUDFImpl for DateTruncFunc {
// A timezone transition can reverse the order of timestamps
// truncated in local time, but not of those truncated on the
// epoch value.
Timestamp(_, Some(tz)) => {
match (constant_granularity(precision), parse_tz(Some(&tz))) {
Timestamp(_, Some(tz_name)) => {
match (constant_granularity(precision), parse_tz(Some(&tz_name))) {
(Some(granularity), Ok(tz)) => {
truncates_in_input_unit(granularity, tz.as_ref())
|| tz.is_some_and(|tz| {
local_truncation_preserves_order(
&tz_name,
tz,
granularity,
)
})
}
_ => false,
}
Expand Down Expand Up @@ -1341,6 +1349,87 @@ fn date_trunc_coarse_with_spans<T: ArrowTimestampType>(
})
}

/// Whether truncating to `granularity` in the local time of `tz` never reverses
/// two instants. Computed once per timezone name that has transitions.
fn local_truncation_preserves_order(
tz_name: &str,
tz: Tz,
granularity: DatePart,
) -> bool {
static CACHE: LazyLock<Mutex<HashMap<String, LocalTruncationOrder>>> =

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 think we could special case UTC and fixed timezone offsets here (+00:00 etc) as they have no transitions and thus preserve granularity

LazyLock::new(Default::default);
let lock = || CACHE.lock().unwrap_or_else(PoisonError::into_inner);
if let Some(order) = lock().get(tz_name) {
return order.preserves(granularity);
}
let Some(spans) = UtcOffsetSpans::for_timezone(tz_name) else {
return false;
};
// Without transitions, as in `UTC` and fixed offsets, local time is the
// epoch value plus a constant, so truncating it is monotone.
if spans.transitions().is_empty() {
return true;
}
let order = LocalTruncationOrder::new(spans.transitions(), tz);
lock().insert(tz_name.to_owned(), order);
order.preserves(granularity)
}

/// Granularities coarser than minute whose local-time truncation keeps the order
/// in one zone. Day and longer buckets outlast any offset change, so only the
/// instants around each transition can go backwards; `hour` needs no transitions.

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.

Also I had my agent test all the chrono timezones (597 of them) and all their transitions are more than a day

FWIW it seems jiff has a API to enumerate the timezone transitions -- so if we ever moved that library we could remove this assumption and just enumemerate the transitions directly

#[derive(Clone, Copy)]
struct LocalTruncationOrder {
hour: bool,
day: bool,
week: bool,
month: bool,
quarter: bool,
year: bool,
}

impl LocalTruncationOrder {
/// `transitions` are the UTC offset transitions of `tz`, in epoch seconds.
fn new(transitions: &[i64], tz: Tz) -> Self {
Self::from_fn(|granularity| match granularity {
DatePart::Hour => transitions.is_empty(),
_ => transitions.iter().all(|&transition| {
let at = transition * NANOS_PER_SECOND;
matches!(
(
date_trunc_coarse(granularity, at - 1, Some(tz)),
date_trunc_coarse(granularity, at, Some(tz)),
),
(Ok(before), Ok(after)) if before <= after
)
}),
})
}

fn from_fn(preserves: impl Fn(DatePart) -> bool) -> Self {
Self {
hour: preserves(DatePart::Hour),
day: preserves(DatePart::Day),
week: preserves(DatePart::Week),
month: preserves(DatePart::Month),
quarter: preserves(DatePart::Quarter),
year: preserves(DatePart::Year),
}
}

fn preserves(&self, granularity: DatePart) -> bool {
match granularity {
DatePart::Hour => self.hour,
DatePart::Day => self.day,
DatePart::Week => self.week,
DatePart::Month => self.month,
DatePart::Quarter => self.quarter,
DatePart::Year => self.year,
_ => false,
}
}
}

/// 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 @@ -1676,13 +1765,16 @@ mod tests {
};
let ordered = SortProperties::Ordered(SortOptions::default());
let function = DateTruncFunc::new();
let output_ordering = |precision: ExprProperties, unit| {
let data_type = DataType::Timestamp(unit, Some("America/Goose_Bay".into()));
let output_ordering_in = |tz: &str, precision: ExprProperties, unit| {
let data_type = DataType::Timestamp(unit, Some(tz.into()));
let timestamp = ExprProperties::new_unknown()
.with_order(ordered)
.with_range(Interval::make_unbounded(&data_type).unwrap());
function.output_ordering(&[precision, timestamp]).unwrap()
};
let output_ordering = |precision: ExprProperties, unit| {
output_ordering_in("America/Goose_Bay", precision, unit)
};

for unit in [
TimeUnit::Second,
Expand All @@ -1697,13 +1789,48 @@ mod tests {
"{granularity} {unit:?}"
);
}
for granularity in ["hour", "day", "week", "month", "quarter", "year"] {
// Goose_Bay fell back from 00:01 to 23:01 the previous day.
for granularity in ["hour", "day"] {
assert_eq!(
output_ordering(constant(ScalarValue::from(granularity)), unit),
SortProperties::Unordered,
"{granularity} {unit:?}"
);
}
// New York changes its offset at 02:00, away from midnight.
for granularity in ["day", "week", "month", "quarter", "year"] {
assert_eq!(
output_ordering_in(
"America/New_York",
constant(ScalarValue::from(granularity)),
unit
),
ordered,
"{granularity} {unit:?}"
);
}
assert_eq!(
output_ordering_in(
"America/New_York",
constant(ScalarValue::from("hour")),
unit
),
SortProperties::Unordered,
"{unit:?}"
);
for tz in ["UTC", "+05:30"] {
for granularity in ["hour", "day", "year"] {
assert_eq!(
output_ordering_in(
tz,
constant(ScalarValue::from(granularity)),
unit
),
ordered,
"{tz} {granularity} {unit:?}"
);
}
}
}

for precision in [
Expand Down
1 change: 0 additions & 1 deletion datafusion/functions/src/datetime/utc_offsets.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,6 @@ impl UtcOffsetSpans {
}

/// The epoch seconds at which the UTC offset changes, in ascending order.
#[cfg(test)]
pub fn transitions(&self) -> &[i64] {
&self.transitions
}
Expand Down
26 changes: 26 additions & 0 deletions datafusion/sqllogictest/test_files/datetime/timestamps.slt
Original file line number Diff line number Diff line change
Expand Up @@ -2156,6 +2156,32 @@ physical_plan
05)--------RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1, maintains_sort_order=true
06)----------DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/timestamps/goose_bay_epochs.csv]]}, projection=[c], output_ordering=[c@0 ASC NULLS LAST], file_type=csv, has_header=true

# Day buckets keep the order in zones whose transitions never cross local
# midnight, such as New York, so no sort is needed.
query TT
EXPLAIN SELECT date_trunc('day', from_unixtime(c, 'America/New_York')) AS bucket
FROM goose_bay_epochs
ORDER BY bucket;
----
physical_plan
01)SortPreservingMergeExec: [bucket@0 ASC NULLS LAST]
02)--ProjectionExec: expr=[date_trunc(day, from_unixtime(c@0, America/New_York)) as bucket]
03)----RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1, maintains_sort_order=true
04)------DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/timestamps/goose_bay_epochs.csv]]}, projection=[c], output_ordering=[c@0 ASC NULLS LAST], file_type=csv, has_header=true

# Goose_Bay fell back from 00:01 to 23:01 the previous day, so the sort stays.
query TT
EXPLAIN SELECT date_trunc('day', from_unixtime(c, 'America/Goose_Bay')) AS bucket
FROM goose_bay_epochs
ORDER BY bucket;
----
physical_plan
01)SortPreservingMergeExec: [bucket@0 ASC NULLS LAST]
02)--SortExec: expr=[bucket@0 ASC NULLS LAST], preserve_partitioning=[true]
03)----ProjectionExec: expr=[date_trunc(day, from_unixtime(c@0, America/Goose_Bay)) as bucket]
04)------RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1, maintains_sort_order=true
05)--------DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/timestamps/goose_bay_epochs.csv]]}, projection=[c], output_ordering=[c@0 ASC NULLS LAST], file_type=csv, has_header=true

statement ok
DROP TABLE goose_bay_epochs;

Expand Down