Skip to content

Apache DataFusion SQL Query Engine

fix date_bin overflows subtracting extreme nanosecond timestamp origin (#22251)

Zhen Chen1a61a599baa3
diff --git a/datafusion/functions/src/datetime/date_bin.rs b/datafusion/functions/src/datetime/date_bin.rs
index 123375cc26..c26623c46b 100644
--- a/datafusion/functions/src/datetime/date_bin.rs
+++ b/datafusion/functions/src/datetime/date_bin.rs
@@ -321,7 +321,11 @@ impl Interval {
// return time in nanoseconds that the source timestamp falls into based on the stride and origin
fn date_bin_nanos_interval(stride_nanos: i64, source: i64, origin: i64) -> Result<i64> {
- let time_diff = source - origin;
+ let time_diff = source.checked_sub(origin).ok_or_else(|| {
+ arrow::error::ArrowError::InvalidArgumentError(format!(
+ "date_bin source timestamp {source} - origin {origin} overflows i64"
+ ))
+ })?;
// distance from origin to bin
let time_delta = compute_distance(time_diff, stride_nanos);
diff --git a/datafusion/sqllogictest/test_files/date_bin_errors.slt b/datafusion/sqllogictest/test_files/date_bin_errors.slt
index b6cda471d7..b59201eb90 100644
--- a/datafusion/sqllogictest/test_files/date_bin_errors.slt
+++ b/datafusion/sqllogictest/test_files/date_bin_errors.slt
@@ -57,4 +57,14 @@ select date_bin(
timestamp '1984-01-07 00:00:00'
) as b;
----
+NULL
+
+# Extreme timestamp overflow: source - origin overflows i64 (should return NULL, not panic)
+query P
+select date_bin(
+ interval '1 nanosecond',
+ arrow_cast(9223372036854775807, 'Timestamp(Nanosecond, None)'),
+ arrow_cast(-9223372036854775808, 'Timestamp(Nanosecond, None)')
+);
+----
NULL
\ No newline at end of file