Skip to content

Apache DataFusion SQL Query Engine

Guard date_trunc lower-bound truncation (#22303)

Sean Kenneth Doherty11a79a621789
diff --git a/datafusion/functions/src/datetime/date_trunc.rs b/datafusion/functions/src/datetime/date_trunc.rs
index 784f593c25..a4b244405c 100644
--- a/datafusion/functions/src/datetime/date_trunc.rs
+++ b/datafusion/functions/src/datetime/date_trunc.rs
@@ -15,6 +15,7 @@
// specific language governing permissions and limitations
// under the License.
+use std::fmt;
use std::num::NonZeroI64;
use std::ops::{Add, Sub};
use std::str::FromStr;
@@ -135,6 +136,24 @@ impl DateTruncGranularity {
}
}
+impl fmt::Display for DateTruncGranularity {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ let value = match self {
+ Self::Microsecond => "microsecond",
+ Self::Millisecond => "millisecond",
+ Self::Second => "second",
+ Self::Minute => "minute",
+ Self::Hour => "hour",
+ Self::Day => "day",
+ Self::Week => "week",
+ Self::Month => "month",
+ Self::Quarter => "quarter",
+ Self::Year => "year",
+ };
+ f.write_str(value)
+ }
+}
+
#[user_doc(
doc_section(label = "Time and Date Functions"),
description = "Truncates a timestamp or time value to a specified precision.",
@@ -629,6 +648,7 @@ fn date_trunc_coarse(
value: i64,
tz: Option<Tz>,
) -> Result<i64> {
+ let input = value;
let value = match tz {
Some(tz) => {
// Use chrono DateTime<Tz> to clear the various fields because need to clear per timezone,
@@ -645,8 +665,11 @@ fn date_trunc_coarse(
}
}?;
- // `with_x(0)` are infallible because `0` are always a valid
- Ok(value.unwrap())
+ value.ok_or_else(|| {
+ exec_datafusion_err!(
+ "Timestamp {input} out of range after truncating to {granularity}"
+ )
+ })
}
/// Fast path for fine granularities (hour and smaller) that can be handled
@@ -879,6 +902,19 @@ mod tests {
});
}
+ #[test]
+ fn date_trunc_out_of_range_lower_bound_returns_error() {
+ let timestamp = string_to_timestamp_nanos("1677-09-22T00:00:00Z").unwrap();
+ let err = date_trunc_coarse(DateTruncGranularity::Year, timestamp, None)
+ .unwrap_err()
+ .to_string();
+
+ assert!(
+ err.contains("out of range after truncating to year"),
+ "{err}"
+ );
+ }
+
#[test]
fn test_date_trunc_timezones() {
let cases = [
diff --git a/datafusion/sqllogictest/test_files/datetime/timestamps.slt b/datafusion/sqllogictest/test_files/datetime/timestamps.slt
index e045abc0f2..958ff86b4f 100644
--- a/datafusion/sqllogictest/test_files/datetime/timestamps.slt
+++ b/datafusion/sqllogictest/test_files/datetime/timestamps.slt
@@ -5345,6 +5345,13 @@ SELECT to_timestamp_millis(arrow_cast(-1.9, 'Float64'));
----
1969-12-31T23:59:59.999
+# Regression test for https://github.com/apache/datafusion/issues/22214
+query error .*out of range after truncating to year
+SELECT date_trunc(
+ 'year',
+ arrow_cast(TIMESTAMP '1677-09-22 00:00:00', 'Timestamp(Nanosecond, None)')
+);
+
##########
## Common timestamp data