Skip to content

Apache DataFusion SQL Query Engine

[fix] Add type coercion from NULL to Interval to make date_bin more postgres compatible (#20499)

Lía Adrianae937cadbccef
diff --git a/datafusion/expr/src/type_coercion/functions.rs b/datafusion/expr/src/type_coercion/functions.rs
index 90c137de24..fe259fb8c9 100644
--- a/datafusion/expr/src/type_coercion/functions.rs
+++ b/datafusion/expr/src/type_coercion/functions.rs
@@ -883,7 +883,7 @@ fn coerced_from<'a>(
Timestamp(TimeUnit::Nanosecond, None),
Null | Timestamp(_, None) | Date32 | Utf8 | LargeUtf8,
) => Some(type_into.clone()),
- (Interval(_), Utf8 | LargeUtf8) => Some(type_into.clone()),
+ (Interval(_), Null | Utf8 | LargeUtf8) => Some(type_into.clone()),
// We can go into a Utf8View from a Utf8 or LargeUtf8
(Utf8View, Utf8 | LargeUtf8 | Null) => Some(type_into.clone()),
// Any type can be coerced into strings
diff --git a/datafusion/functions/src/datetime/date_bin.rs b/datafusion/functions/src/datetime/date_bin.rs
index 7f123d214f..c0984c1ea6 100644
--- a/datafusion/functions/src/datetime/date_bin.rs
+++ b/datafusion/functions/src/datetime/date_bin.rs
@@ -421,6 +421,12 @@ fn date_bin_impl(
origin: &ColumnarValue,
) -> Result<ColumnarValue> {
let stride = match stride {
+ ColumnarValue::Scalar(s) if s.is_null() => {
+ // NULL stride -> NULL result (standard SQL NULL propagation)
+ return Ok(ColumnarValue::Scalar(ScalarValue::try_from(
+ array.data_type(),
+ )?));
+ }
ColumnarValue::Scalar(ScalarValue::IntervalDayTime(Some(v))) => {
let (days, ms) = IntervalDayTimeType::to_parts(*v);
let nanos = (TimeDelta::try_days(days as i64).unwrap()
diff --git a/datafusion/sqllogictest/test_files/datetime/timestamps.slt b/datafusion/sqllogictest/test_files/datetime/timestamps.slt
index 8ed32940e8..9526ccebfd 100644
--- a/datafusion/sqllogictest/test_files/datetime/timestamps.slt
+++ b/datafusion/sqllogictest/test_files/datetime/timestamps.slt
@@ -771,6 +771,18 @@ select to_timestamp_seconds(cast (1 as int));
## test date_bin function
##########
+# NULL stride should return NULL, not a planning error
+query P
+SELECT date_bin(NULL, TIMESTAMP '2023-01-01 12:30:00', TIMESTAMP '2023-01-01 12:00:00')
+----
+NULL
+
+# NULL stride should return NULL, not a planning error
+query P
+SELECT date_bin(NULL, TIMESTAMP '2023-01-01 12:30:00')
+----
+NULL
+
# invalid second arg type
query error
SELECT DATE_BIN(INTERVAL '0 second', 25, TIMESTAMP '1970-01-01T00:00:00Z')