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

alamb 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 55a7768bbb [Variant] Add `variant_to_arrow` `Struct` type support 
(#9572)
55a7768bbb is described below

commit 55a7768bbb95976e1dac29facb2ea337aa4d89b6
Author: Konstantin Tarasov <[email protected]>
AuthorDate: Thu Mar 19 13:41:47 2026 -0400

    [Variant] Add `variant_to_arrow` `Struct` type support (#9572)
    
    # 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.
    -->
    
    - Closes #9529 .
    
    # Rationale for this change
    
    - In a follow up PR, can fix the `variant_get` TODO:
    
    
https://github.com/apache/arrow-rs/blob/3b6179658203dc1b1610b67c1777d5b8beb137fc/parquet-variant-compute/src/variant_get.rs#L89-L92
    - When we know that Struct VariantArray is not shredded can reuse
    `shred_basic_variant`
    <!--
    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?
    
    - Added `StructVariantToArrowRowBuilder` builder.
    - Moved `make_variant_to_arrow_row_builder` logic to
    `make_typed_variant_to_arrow_row_builder` to reuse by `Struct` array's
    inner fields.
    - Changed a `variant_get` test to show that it now handles unshredded
    `Struct` `VariantArray`
    <!--
    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, added `test_struct_row_builder_handles_unshredded_nested_structs`
    - Everything else still works.
    <!--
    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?
    No
    <!--
    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.
    -->
    
    ---------
    
    Co-authored-by: Ryan Johnson <[email protected]>
---
 parquet-variant-compute/src/variant_get.rs      |  26 +++--
 parquet-variant-compute/src/variant_to_arrow.rs | 133 ++++++++++++++++++++----
 2 files changed, 130 insertions(+), 29 deletions(-)

diff --git a/parquet-variant-compute/src/variant_get.rs 
b/parquet-variant-compute/src/variant_get.rs
index a155d04e47..9204dcf708 100644
--- a/parquet-variant-compute/src/variant_get.rs
+++ b/parquet-variant-compute/src/variant_get.rs
@@ -3070,10 +3070,8 @@ mod test {
         assert!(struct_result.is_null(3));
     }
 
-    /// Test that demonstrates the actual struct row builder gap
-    /// This test should fail because it hits unshredded nested structs
     #[test]
-    fn test_struct_row_builder_gap_demonstration() {
+    fn test_struct_row_builder_handles_unshredded_nested_structs() {
         // Create completely unshredded JSON variant (no typed_value at all)
         let json_strings = vec![
             r#"{"outer": {"inner": 42}}"#,
@@ -3082,7 +3080,7 @@ mod test {
         let string_array: Arc<dyn Array> = 
Arc::new(StringArray::from(json_strings));
         let variant_array = json_to_variant(&string_array).unwrap();
 
-        // Request nested struct - this should fail at the row builder level
+        // Request nested struct
         let inner_fields = Fields::from(vec![Field::new("inner", 
DataType::Int32, true)]);
         let inner_struct_type = DataType::Struct(inner_fields);
         let outer_fields = Fields::from(vec![Field::new("outer", 
inner_struct_type, true)]);
@@ -3095,12 +3093,22 @@ mod test {
         };
 
         let variant_array_ref = ArrayRef::from(variant_array);
-        let result = variant_get(&variant_array_ref, options);
+        let result = variant_get(&variant_array_ref, options).unwrap();
 
-        // Should fail with NotYetImplemented when the row builder tries to 
handle struct type
-        assert!(result.is_err());
-        let error = result.unwrap_err();
-        assert!(error.to_string().contains("Not yet implemented"));
+        let outer_struct = result.as_struct();
+        assert_eq!(outer_struct.len(), 2);
+        assert_eq!(outer_struct.num_columns(), 1);
+
+        let inner_struct = outer_struct.column(0).as_struct();
+        assert_eq!(inner_struct.num_columns(), 1);
+
+        let inner_values = inner_struct
+            .column(0)
+            .as_any()
+            .downcast_ref::<Int32Array>()
+            .unwrap();
+        assert_eq!(inner_values.value(0), 42);
+        assert_eq!(inner_values.value(1), 100);
     }
 
     /// Create comprehensive shredded variant with diverse null patterns and 
empty objects
diff --git a/parquet-variant-compute/src/variant_to_arrow.rs 
b/parquet-variant-compute/src/variant_to_arrow.rs
index 106e8915be..dc8fbcd223 100644
--- a/parquet-variant-compute/src/variant_to_arrow.rs
+++ b/parquet-variant-compute/src/variant_to_arrow.rs
@@ -28,12 +28,13 @@ use arrow::array::{
     BinaryViewBuilder, BooleanBuilder, FixedSizeBinaryBuilder, 
GenericListArray,
     GenericListViewArray, LargeBinaryBuilder, LargeStringBuilder, NullArray, 
NullBufferBuilder,
     OffsetSizeTrait, PrimitiveBuilder, StringBuilder, StringLikeArrayBuilder, 
StringViewBuilder,
+    StructArray,
 };
 use arrow::buffer::{OffsetBuffer, ScalarBuffer};
 use arrow::compute::{CastOptions, DecimalCast};
 use arrow::datatypes::{self, DataType, DecimalType};
 use arrow::error::{ArrowError, Result};
-use arrow_schema::{FieldRef, TimeUnit};
+use arrow_schema::{FieldRef, Fields, TimeUnit};
 use parquet_variant::{Variant, VariantPath};
 use std::sync::Arc;
 
@@ -44,6 +45,7 @@ use std::sync::Arc;
 pub(crate) enum VariantToArrowRowBuilder<'a> {
     Primitive(PrimitiveVariantToArrowRowBuilder<'a>),
     Array(ArrayVariantToArrowRowBuilder<'a>),
+    Struct(StructVariantToArrowRowBuilder<'a>),
     BinaryVariant(VariantToBinaryVariantArrowRowBuilder),
 
     // Path extraction wrapper - contains a boxed enum for any of the above
@@ -56,6 +58,7 @@ impl<'a> VariantToArrowRowBuilder<'a> {
         match self {
             Primitive(b) => b.append_null(),
             Array(b) => b.append_null(),
+            Struct(b) => b.append_null(),
             BinaryVariant(b) => b.append_null(),
             WithPath(path_builder) => path_builder.append_null(),
         }
@@ -66,6 +69,7 @@ impl<'a> VariantToArrowRowBuilder<'a> {
         match self {
             Primitive(b) => b.append_value(&value),
             Array(b) => b.append_value(&value),
+            Struct(b) => b.append_value(&value),
             BinaryVariant(b) => b.append_value(value),
             WithPath(path_builder) => path_builder.append_value(value),
         }
@@ -76,12 +80,42 @@ impl<'a> VariantToArrowRowBuilder<'a> {
         match self {
             Primitive(b) => b.finish(),
             Array(b) => b.finish(),
+            Struct(b) => b.finish(),
             BinaryVariant(b) => b.finish(),
             WithPath(path_builder) => path_builder.finish(),
         }
     }
 }
 
+fn make_typed_variant_to_arrow_row_builder<'a>(
+    data_type: &'a DataType,
+    cast_options: &'a CastOptions,
+    capacity: usize,
+) -> Result<VariantToArrowRowBuilder<'a>> {
+    use VariantToArrowRowBuilder::*;
+
+    match data_type {
+        DataType::Struct(fields) => {
+            let builder = StructVariantToArrowRowBuilder::try_new(fields, 
cast_options, capacity)?;
+            Ok(Struct(builder))
+        }
+        data_type @ (DataType::List(_)
+        | DataType::LargeList(_)
+        | DataType::ListView(_)
+        | DataType::LargeListView(_)
+        | DataType::FixedSizeList(..)) => {
+            let builder =
+                ArrayVariantToArrowRowBuilder::try_new(data_type, 
cast_options, capacity)?;
+            Ok(Array(builder))
+        }
+        data_type => {
+            let builder =
+                make_primitive_variant_to_arrow_row_builder(data_type, 
cast_options, capacity)?;
+            Ok(Primitive(builder))
+        }
+    }
+}
+
 pub(crate) fn make_variant_to_arrow_row_builder<'a>(
     metadata: &BinaryViewArray,
     path: VariantPath<'a>,
@@ -97,26 +131,8 @@ pub(crate) fn make_variant_to_arrow_row_builder<'a>(
             metadata.clone(),
             capacity,
         )),
-        Some(DataType::Struct(_)) => {
-            return Err(ArrowError::NotYetImplemented(
-                "Converting unshredded variant objects to arrow 
structs".to_string(),
-            ));
-        }
-        Some(
-            data_type @ (DataType::List(_)
-            | DataType::LargeList(_)
-            | DataType::ListView(_)
-            | DataType::LargeListView(_)
-            | DataType::FixedSizeList(..)),
-        ) => {
-            let builder =
-                ArrayVariantToArrowRowBuilder::try_new(data_type, 
cast_options, capacity)?;
-            Array(builder)
-        }
         Some(data_type) => {
-            let builder =
-                make_primitive_variant_to_arrow_row_builder(data_type, 
cast_options, capacity)?;
-            Primitive(builder)
+            make_typed_variant_to_arrow_row_builder(data_type, cast_options, 
capacity)?
         }
     };
 
@@ -491,6 +507,83 @@ pub(crate) enum ArrayVariantToArrowRowBuilder<'a> {
     LargeListView(VariantToListArrowRowBuilder<'a, i64, true>),
 }
 
+pub(crate) struct StructVariantToArrowRowBuilder<'a> {
+    fields: &'a Fields,
+    field_builders: Vec<VariantToArrowRowBuilder<'a>>,
+    nulls: NullBufferBuilder,
+    cast_options: &'a CastOptions<'a>,
+}
+
+impl<'a> StructVariantToArrowRowBuilder<'a> {
+    fn try_new(
+        fields: &'a Fields,
+        cast_options: &'a CastOptions<'a>,
+        capacity: usize,
+    ) -> Result<Self> {
+        let mut field_builders = Vec::with_capacity(fields.len());
+        for field in fields.iter() {
+            field_builders.push(make_typed_variant_to_arrow_row_builder(
+                field.data_type(),
+                cast_options,
+                capacity,
+            )?);
+        }
+        Ok(Self {
+            fields,
+            field_builders,
+            nulls: NullBufferBuilder::new(capacity),
+            cast_options,
+        })
+    }
+
+    fn append_null(&mut self) -> Result<()> {
+        for builder in &mut self.field_builders {
+            builder.append_null()?;
+        }
+        self.nulls.append_null();
+        Ok(())
+    }
+
+    fn append_value(&mut self, value: &Variant<'_, '_>) -> Result<bool> {
+        let Variant::Object(obj) = value else {
+            if self.cast_options.safe {
+                self.append_null()?;
+                return Ok(false);
+            }
+            return Err(ArrowError::CastError(format!(
+                "Failed to extract struct from variant {:?}",
+                value
+            )));
+        };
+
+        for (index, field) in self.fields.iter().enumerate() {
+            match obj.get(field.name()) {
+                Some(field_value) => {
+                    self.field_builders[index].append_value(field_value)?;
+                }
+                None => {
+                    self.field_builders[index].append_null()?;
+                }
+            }
+        }
+
+        self.nulls.append_non_null();
+        Ok(true)
+    }
+
+    fn finish(mut self) -> Result<ArrayRef> {
+        let mut children = Vec::with_capacity(self.field_builders.len());
+        for builder in self.field_builders {
+            children.push(builder.finish()?);
+        }
+        Ok(Arc::new(StructArray::try_new(
+            self.fields.clone(),
+            children,
+            self.nulls.finish(),
+        )?))
+    }
+}
+
 impl<'a> ArrayVariantToArrowRowBuilder<'a> {
     pub(crate) fn try_new(
         data_type: &'a DataType,

Reply via email to