You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@datafusion.apache.org by gi...@apache.org on 2026/06/14 03:27:30 UTC

(datafusion) branch gh-readonly-queue/main/pr-22897-78033fa679c6031927e6b25154e664fc5cefcaec created (now cb2542c5be)

This is an automated email from the ASF dual-hosted git repository.

github-merge-queue[bot] pushed a change to branch gh-readonly-queue/main/pr-22897-78033fa679c6031927e6b25154e664fc5cefcaec
in repository https://gitbox.apache.org/repos/asf/datafusion.git


      at cb2542c5be fix: TRY_CAST returns NULL for timestamp/date overflow (#22897)

This branch includes the following new commits:

     new cb2542c5be fix: TRY_CAST returns NULL for timestamp/date overflow (#22897)

The 1 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.



---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@datafusion.apache.org
For additional commands, e-mail: commits-help@datafusion.apache.org


(datafusion) 01/01: fix: TRY_CAST returns NULL for timestamp/date overflow (#22897)

Posted by gi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

github-merge-queue[bot] pushed a commit to branch gh-readonly-queue/main/pr-22897-78033fa679c6031927e6b25154e664fc5cefcaec
in repository https://gitbox.apache.org/repos/asf/datafusion.git

commit cb2542c5bebacb75d014b2138daef24af371663e
Author: fys <40...@users.noreply.github.com>
AuthorDate: Sun Jun 14 11:27:07 2026 +0800

    fix: TRY_CAST returns NULL for timestamp/date overflow (#22897)
    
    ## Which issue does this PR close?
    
    <!--
    We generally require a GitHub issue to be filed for all bug fixes and
    enhancements and this helps us generate change logs for our releases.
    You can link an issue to this PR using the GitHub syntax. For example
    `Closes #123` indicates that this PR will close issue #123.
    -->
    
    - Closes #22896.
    
    ## Rationale for this change
    
    `TRY_CAST` should return NULL on cast failure, but overflowing
    date/timestamp casts returned errors.
    
    <!--
    Why are you proposing this change? If this is already explained clearly
    in the issue then this section is not needed.
    Explaining clearly why changes are proposed helps reviewers understand
    your changes and offer better suggestions for fixes.
    -->
    
    ## What changes are included in this PR?
    
    - Make scalar temporal overflow checks respect CastOptions.safe.
    - Skip DataFusion’s array pre-check for safe casts so Arrow can return
    NULLs.
    - Add regression tests.
    
    <!--
    There is no need to duplicate the description in the issue here but it
    is sometimes worth providing a summary of the individual changes in this
    PR.
    -->
    
    ## Are these changes tested?
    
    Yes:
    
    ```bash
    cargo test -p datafusion-common timestamp_overflow_returns
    cargo test -p datafusion-expr-common timestamp_array_to_timestamp_overflow
    cargo test --test sqllogictests -- datetime/timestamps.slt
    ```
    
    <!--
    We typically require tests for all PRs in order to:
    1. Prevent the code from being accidentally broken by subsequent changes
    2. Serve as another way to document the expected behavior of the code
    
    If tests are not included in your PR, please explain why (for example,
    are they covered by existing tests)?
    -->
    
    ## Are there any user-facing changes?
    
    Yes. TRY_CAST for overflowing date/timestamp casts now returns NULL;
    regular CAST still errors.
    
    <!--
    If there are user-facing changes then we may require documentation to be
    updated before approving the PR.
    -->
    
    <!--
    If there are any breaking changes to public APIs, please add the `api
    change` label.
    -->
    
    ## Known Limitation
    
    This PR does not add Date array-path coverage yet. For example:
    
    ```sql
    SELECT TRY_CAST(d AS TIMESTAMP(9))
    FROM (VALUES (DATE '3000-01-01')) t(d);
    ```
    
    This depends on the upstream Arrow fix in apache/arrow-rs#9825. Once
    DataFusion updates to an Arrow version containing that fix, we can add
    this regression test.
---
 datafusion/common/src/scalar/mod.rs                | 45 +++++++++++++++++++++-
 datafusion/expr-common/src/columnar_value.rs       | 32 ++++++++++++++-
 .../test_files/datetime/timestamps.slt             | 19 +++++++++
 3 files changed, 94 insertions(+), 2 deletions(-)

diff --git a/datafusion/common/src/scalar/mod.rs b/datafusion/common/src/scalar/mod.rs
index c9013af726..8a8a47b3bb 100644
--- a/datafusion/common/src/scalar/mod.rs
+++ b/datafusion/common/src/scalar/mod.rs
@@ -4292,7 +4292,14 @@ impl ScalarValue {
             .or_else(|| timestamp_to_timestamp_multiplier(&source_type, target_type))
             && let Some(value) = self.temporal_scalar_value_as_i64()
         {
-            ensure_timestamp_in_bounds(value, multiplier, &source_type, target_type)?;
+            match ensure_timestamp_in_bounds(value, multiplier, &source_type, target_type)
+            {
+                Ok(()) => {}
+                Err(_) if cast_options.safe => {
+                    return ScalarValue::try_new_null(target_type);
+                }
+                Err(e) => return Err(e),
+            }
         }
 
         let scalar_array = self.to_array()?;
@@ -10190,6 +10197,24 @@ mod tests {
         );
     }
 
+    #[test]
+    fn safe_cast_date_to_timestamp_overflow_returns_null() {
+        let scalar = ScalarValue::Date32(Some(i32::MAX));
+        let safe_options = CastOptions {
+            safe: true,
+            ..DEFAULT_CAST_OPTIONS
+        };
+
+        let casted = scalar
+            .cast_to_with_options(
+                &DataType::Timestamp(TimeUnit::Nanosecond, None),
+                &safe_options,
+            )
+            .expect("expected safe cast to return null");
+
+        assert_eq!(casted, ScalarValue::TimestampNanosecond(None, None));
+    }
+
     #[test]
     fn cast_timestamp_to_timestamp_overflow_returns_error() {
         let scalar = ScalarValue::TimestampSecond(Some(i64::MAX), None);
@@ -10203,6 +10228,24 @@ mod tests {
         );
     }
 
+    #[test]
+    fn safe_cast_timestamp_to_timestamp_overflow_returns_null() {
+        let scalar = ScalarValue::TimestampSecond(Some(i64::MAX), None);
+        let safe_options = CastOptions {
+            safe: true,
+            ..DEFAULT_CAST_OPTIONS
+        };
+
+        let casted = scalar
+            .cast_to_with_options(
+                &DataType::Timestamp(TimeUnit::Nanosecond, None),
+                &safe_options,
+            )
+            .expect("expected safe cast to return null");
+
+        assert_eq!(casted, ScalarValue::TimestampNanosecond(None, None));
+    }
+
     #[test]
     fn null_dictionary_scalar_produces_null_dictionary_array() {
         let dictionary_scalar = ScalarValue::Dictionary(
diff --git a/datafusion/expr-common/src/columnar_value.rs b/datafusion/expr-common/src/columnar_value.rs
index caeb3f10da..ef9192c356 100644
--- a/datafusion/expr-common/src/columnar_value.rs
+++ b/datafusion/expr-common/src/columnar_value.rs
@@ -325,7 +325,9 @@ fn cast_array_by_name(
     ) {
         datafusion_common::nested_struct::cast_column(array, cast_type, cast_options)
     } else {
-        ensure_temporal_array_timestamp_bounds(array, cast_type)?;
+        if !cast_options.safe {
+            ensure_temporal_array_timestamp_bounds(array, cast_type)?;
+        }
         Ok(kernels::cast::cast_with_options(
             array,
             cast_type,
@@ -766,4 +768,32 @@ mod tests {
             "unexpected error: {err}"
         );
     }
+
+    #[test]
+    fn safe_cast_timestamp_array_to_timestamp_overflow_returns_null() {
+        let overflow_value = i64::MAX / 1_000_000_000 + 1;
+        let array: ArrayRef =
+            Arc::new(TimestampSecondArray::from(vec![Some(overflow_value)]));
+        let value = ColumnarValue::Array(array);
+        let safe_options = CastOptions {
+            safe: true,
+            ..DEFAULT_CAST_OPTIONS
+        };
+
+        let casted = value
+            .cast_to(
+                &DataType::Timestamp(TimeUnit::Nanosecond, None),
+                Some(&safe_options),
+            )
+            .expect("expected safe cast to return null");
+
+        let ColumnarValue::Array(array) = casted else {
+            panic!("expected array after cast");
+        };
+        let array = array
+            .as_any()
+            .downcast_ref::<TimestampNanosecondArray>()
+            .expect("expected TimestampNanosecondArray");
+        assert!(array.is_null(0));
+    }
 }
diff --git a/datafusion/sqllogictest/test_files/datetime/timestamps.slt b/datafusion/sqllogictest/test_files/datetime/timestamps.slt
index 89c6f0a121..06740fa0f5 100644
--- a/datafusion/sqllogictest/test_files/datetime/timestamps.slt
+++ b/datafusion/sqllogictest/test_files/datetime/timestamps.slt
@@ -5379,6 +5379,25 @@ SELECT to_timestamp(arrow_cast(-9223372036, 'Int64'));
 query error converted value exceeds the representable i64 range
 SELECT to_timestamp(arrow_cast(9223372037, 'Int64'));
 
+# TRY_CAST returns NULL for timestamp/date casts that overflow
+query P
+SELECT TRY_CAST(arrow_cast(9223372037, 'Timestamp(s)') AS TIMESTAMP(9));
+----
+NULL
+
+query P
+SELECT TRY_CAST(DATE '3000-01-01' AS TIMESTAMP(9));
+----
+NULL
+
+query P
+SELECT TRY_CAST(ts AS TIMESTAMP(9)) AS ts
+FROM (
+    VALUES (arrow_cast(9223372037, 'Timestamp(s)'))
+) t(ts);
+----
+NULL
+
 # Float truncation behavior
 query P
 SELECT to_timestamp_seconds(arrow_cast(-1.9, 'Float64'));


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@datafusion.apache.org
For additional commands, e-mail: commits-help@datafusion.apache.org