alamb commented on code in PR #9544:
URL: https://github.com/apache/arrow-rs/pull/9544#discussion_r2955915857


##########
arrow-cast/src/cast/mod.rs:
##########
@@ -2276,6 +2309,137 @@ fn cast_struct_fields_in_order(
         .collect::<Result<Vec<ArrayRef>, ArrowError>>()
 }
 
+/// Cast a UnionArray to another UnionArray by casting each child array.
+fn cast_union_to_union(
+    array: &UnionArray,
+    from_fields: &UnionFields,
+    to_fields: &UnionFields,
+    _to_mode: UnionMode,
+    cast_options: &CastOptions,
+) -> Result<ArrayRef, ArrowError> {
+    let type_ids = array.type_ids().clone();
+    let offsets = array.offsets().cloned();
+
+    let new_children: Vec<ArrayRef> = from_fields
+        .iter()
+        .map(|(from_id, _from_field)| {
+            let (_, to_field) = to_fields
+                .iter()
+                .find(|(to_id, _)| *to_id == from_id)
+                .ok_or_else(|| {
+                    ArrowError::CastError(format!(
+                        "Cannot cast union: type_id {from_id} not found in 
target union"
+                    ))
+                })?;
+            let child = array.child(from_id);
+            cast_with_options(child.as_ref(), to_field.data_type(), 
cast_options)
+        })
+        .collect::<Result<_, _>>()?;
+
+    let union = UnionArray::try_new(to_fields.clone(), type_ids, offsets, 
new_children)?;
+    Ok(Arc::new(union))
+}
+
+/// Cast a UnionArray to a non-union type.
+///
+/// Finds the first variant whose type matches or can be cast to `to_type`,
+/// extracts values for rows where that variant is active (NULLing other rows),
+/// then casts the result to the target type. Prefers an exact type match over
+/// a cast-compatible one.
+///
+/// Since union extraction inherently introduces nulls for non-matching rows,
+/// the target type's inner fields are made nullable to avoid validation errors
+/// (e.g., casting to `List(non-nullable Utf8)` becomes `List(nullable Utf8)`).
+fn cast_union_to_type(

Review Comment:
   Another potential option is to introduce the behavior into `union_extract`: 
https://docs.rs/arrow/latest/arrow/compute/kernels/union_extract/fn.union_extract.html
   
   For example, maybe `union_extract_with_option` that takes some sort of 
options struct that allows better control over the extraction



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to