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

Jefffrey pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/arrow-rs.git


The following commit(s) were added to refs/heads/main by this push:
     new f3399269b8 fix(arrow-cast): preserve null dictionary values when 
casting to a view (#10510)
f3399269b8 is described below

commit f3399269b8f8291a170fe78dff7a88ed2cd11238
Author: Abhishek <[email protected]>
AuthorDate: Tue Aug 4 05:08:44 2026 +0530

    fix(arrow-cast): preserve null dictionary values when casting to a view 
(#10510)
    
    # 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.
    -->
    Split out of #10436 at review request, which is the PR linked to #8985.
    
    
    # Rationale for this change
    
    <!--
    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.
    -->
    
    `view_from_dict_values` appends a view for every non-null key without
    checking whether the value it points at is null, so a null dictionary
    value surfaces as the empty slice its offsets span:
    
      ```rust
      // values ["aa", NULL, "cc"], keys [0, 1, 2]
      cast(&dict, &DataType::Utf8View)  // before: ["aa", "",   "cc"]
                                        //  after: ["aa", null, "cc"]
      cast(&dict, &DataType::Utf8)      // unchanged: ["aa", null, "cc"]
    ```
    unpack_dictionary goes through take, and impl From<&GenericByteArray> for 
GenericByteViewArray branches on is_null, so both already produce null here. 
Only the dictionary to view path disagreed.
    
    # What changes are included in this PR?
    
    <!--
    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.
    -->
    Check value validity before appending a view. Also bounds-check the key 
before indexing the offsets, turning an out of range key from undefined 
behaviour into an InvalidArgumentError.
    
    # Are these changes tested?
    
    <!--
    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)?
    
    If this PR claims a performance improvement, please include evidence such 
as benchmark results.
    -->
    Yes. The new test fails on the unfixed code, giving `Some("")` where `None` 
is expected.
    
    
    # Are there any user-facing changes?
    
    <!--
    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 call them out.
    -->
    `Dictionary<_, Utf8>` -> `Utf8View `and `Dictionary<_, Binary> -> 
BinaryView` now produce null for a null dictionary value instead of an empty 
string.
    
    ---------
    
    Co-authored-by: Jeffrey Vo <[email protected]>
---
 arrow-cast/src/cast/dictionary.rs |  7 +++++++
 arrow-cast/src/cast/mod.rs        | 44 +++++++++++++++++++++++++++++++++++++++
 2 files changed, 51 insertions(+)

diff --git a/arrow-cast/src/cast/dictionary.rs 
b/arrow-cast/src/cast/dictionary.rs
index db3611f551..0a9751dfa8 100644
--- a/arrow-cast/src/cast/dictionary.rs
+++ b/arrow-cast/src/cast/dictionary.rs
@@ -132,6 +132,8 @@ fn view_from_dict_values<K: ArrowDictionaryKeyType, V: 
ByteArrayType, T: ByteVie
 ) -> Result<ArrayRef, ArrowError> {
     let value_buffer = values.values();
     let value_offsets = values.value_offsets();
+    // A null *value* must produce a null row, not the empty slice its offsets 
happen to span.
+    let values_have_nulls = values.null_count() != 0;
     let mut builder = GenericByteViewBuilder::<T>::with_capacity(keys.len());
     builder.append_block(value_buffer.clone());
     for i in keys.iter() {
@@ -141,6 +143,11 @@ fn view_from_dict_values<K: ArrowDictionaryKeyType, V: 
ByteArrayType, T: ByteVie
                     ArrowError::ComputeError("Invalid dictionary 
index".to_string())
                 })?;
 
+                if values_have_nulls && values.is_null(idx) {
+                    builder.append_null();
+                    continue;
+                }
+
                 // Safety
                 // (1) The index is within bounds as they are offsets
                 // (2) The append_view is safe
diff --git a/arrow-cast/src/cast/mod.rs b/arrow-cast/src/cast/mod.rs
index 20a3068e95..3dbafe67a6 100644
--- a/arrow-cast/src/cast/mod.rs
+++ b/arrow-cast/src/cast/mod.rs
@@ -7634,6 +7634,50 @@ mod tests {
         assert_eq!(casted_binary_array.as_ref(), &binary_view_array);
     }
 
+    #[test]
+    fn test_dict_to_view_null_dictionary_value_is_null() {
+        // Ensure we preserve nulls in the values
+        let keys = Int32Array::from_iter([Some(0), Some(1), Some(2), None, 
Some(1)]);
+
+        let values = StringArray::from(vec![Some("aa"), None, Some("a value 
over twelve bytes")]);
+        let dict = DictionaryArray::<Int32Type>::try_new(keys.clone(), 
Arc::new(values)).unwrap();
+        let casted = cast(&dict, &DataType::Utf8View).unwrap();
+        assert_eq!(
+            casted.as_string_view().iter().collect::<Vec<_>>(),
+            vec![
+                Some("aa"),
+                None,
+                Some("a value over twelve bytes"),
+                None,
+                None
+            ]
+        );
+        // the same input cast to Utf8 goes through `unpack_dictionary` and 
always agreed
+        let reference = cast(&dict, &DataType::Utf8).unwrap();
+        assert_eq!(
+            casted.as_string_view().iter().collect::<Vec<_>>(),
+            reference.as_string::<i32>().iter().collect::<Vec<_>>()
+        );
+
+        let values = BinaryArray::from_opt_vec(vec![
+            Some(b"aa".as_slice()),
+            None,
+            Some(b"a value over twelve bytes"),
+        ]);
+        let dict = DictionaryArray::<Int32Type>::try_new(keys, 
Arc::new(values)).unwrap();
+        let casted = cast(&dict, &DataType::BinaryView).unwrap();
+        assert_eq!(
+            casted.as_binary_view().iter().collect::<Vec<_>>(),
+            vec![
+                Some(b"aa".as_slice()),
+                None,
+                Some(b"a value over twelve bytes"),
+                None,
+                None
+            ]
+        );
+    }
+
     #[test]
     fn test_view_to_dict() {
         let string_view_array = StringViewArray::from_iter(VIEW_TEST_DATA);

Reply via email to