sdf-jkl commented on code in PR #12211:
URL: https://github.com/apache/arrow-rs/pull/12211#discussion_r4685245792


##########
parquet-variant-compute/src/arrow_to_variant.rs:
##########
@@ -497,6 +518,34 @@ impl NullArrowToVariantBuilder {
     }
 }
 
+/// Builder for a child array that is already a [`VariantArray`]. Rows are 
copied
+/// through unchanged instead of being re-serialized as objects, including rows
+/// stored as shredded `typed_value`s.
+pub(crate) struct VariantArrowToVariantBuilder {
+    variant_array: VariantArray,
+}
+
+impl VariantArrowToVariantBuilder {
+    pub(crate) fn new(array: &dyn Array) -> Result<Self, ArrowError> {
+        Ok(Self {
+            variant_array: VariantArray::try_new(array)?,

Review Comment:
   `try_value` can't build a borrowed `Variant` from a struct or list 
`typed_value`. It returns `NotYetImplemented`. So a child shredded as an object 
or array fails the whole cast.
   
   Repro: shred `[{"x":1,"y":"e"}, {"x":"s"}, 42]` with `Struct(x: Int64)`, 
then wrap it as Variant field `a` in a struct. `cast_to_variant` returns:
   
   ```
   NotYetImplemented("VariantArray::try_value cannot materialize typed_value of 
type Struct(\"x\": ...) as a borrowed Variant; call unshred_variant first")
   ```
   
   Before this PR the same input did not error (the output was the storage 
object, so still wrong). `variant_get` unshreds before returning Variant output 
(`variant_get.rs:236`), and the same works here:
   
   ```suggestion
               // `try_value` cannot materialize struct or list `typed_value`
               variant_array: 
crate::unshred_variant(&VariantArray::try_new(array)?)?,
   ```
   
   `unshred_variant` returns a clone when there is no `typed_value`, so 
unshredded children pay nothing extra. Please also replace the `Int32` 
shredding in `test_cast_to_variant_struct_with_shredded_variant_child` with the 
object shredding above. `try_value` supports `Int32`, so the current test 
doesn't catch this.



##########
parquet-variant-compute/src/arrow_to_variant.rs:
##########
@@ -273,6 +276,24 @@ pub(crate) fn make_arrow_to_variant_row_builder<'a>(
     Ok(builder)
 }
 
+/// Builds the row builder for a child array described by `field`.
+///
+/// When the field carries a valid [`VariantType`] extension, the child is 
already
+/// a [`VariantArray`] and its rows are copied through unchanged; otherwise 
this
+/// falls back to dispatching on the field's data type.

Review Comment:
   The doc comments mostly repeat the code. One line is enough:
   
   ```suggestion
   /// Like [`make_arrow_to_variant_row_builder`], but reads a 
Variant-annotated child as Variant
   /// values instead of as its storage struct.
   ```



##########
parquet-variant-compute/src/arrow_to_variant.rs:
##########
@@ -497,6 +518,34 @@ impl NullArrowToVariantBuilder {
     }
 }
 
+/// Builder for a child array that is already a [`VariantArray`]. Rows are 
copied
+/// through unchanged instead of being re-serialized as objects, including rows
+/// stored as shredded `typed_value`s.

Review Comment:
   Same here:
   
   ```suggestion
   /// Builder for a Variant-annotated child array.
   ```



##########
parquet-variant-compute/src/arrow_to_variant.rs:
##########
@@ -507,8 +556,21 @@ pub(crate) struct ListArrowToVariantBuilder<'a, L: 
ListLikeArray> {
 impl<'a, L: ListLikeArray> ListArrowToVariantBuilder<'a, L> {
     pub(crate) fn new(array: &'a L, options: &'a CastOptions) -> Result<Self, 
ArrowError> {
         let values = array.values();
+        // The values field carries the extension type of the values, if any.
+        let values_field: &Field = match array.data_type() {

Review Comment:
   The error arm can't be reached, because `ListLikeArray` is only implemented 
for these five types. `make_arrow_to_variant_row_builder` already matches 
`DataType::List(_)` and the other list types, so it can pass the field in and 
this `match` goes away:
   
   ```rust
   DataType::List(f) => List(ListArrowToVariantBuilder::new(f, array.as_list(), 
options)?),
   // same for LargeList, ListView, LargeListView, FixedSizeList(f, _)
   ```
   
   ```rust
   pub(crate) fn new(
       values_field: &'a Field,
       array: &'a L,
       options: &'a CastOptions,
   ) -> Result<Self, ArrowError> {
       let values_builder =
           make_arrow_to_variant_row_builder_for_field(values_field, 
array.values(), options)?;
   ```



##########
parquet-variant-compute/src/cast_to_variant.rs:
##########
@@ -2236,6 +2237,214 @@ mod tests {
         );
     }
 
+    #[test]
+    fn test_cast_to_variant_struct_with_variant_child() {

Review Comment:
   The tests can be much shorter without losing coverage. The new builder has 
two branches (`is_null` and `try_value`) and each container needs its child 
field wired, so one row per container is enough. Building the child from JSON 
and comparing JSON output also removes the two `VariantBuilder` blocks for the 
expected list values:
   
   ```rust
   /// `None` is SQL NULL.
   fn json_variants(json: &[Option<&str>]) -> VariantArray {
       json_to_variant(&(Arc::new(StringArray::from(json.to_vec())) as 
ArrayRef)).unwrap()
   }
   
   fn assert_cast_json(input: &dyn Array, expected: &str) {
       let output = ArrayRef::from(cast_to_variant(input).unwrap());
       assert_eq!(variant_to_json(&output).unwrap().value(0), expected);
   }
   
   #[test]
   fn test_cast_to_variant_list_with_variant_values() {
       let values = json_variants(&[Some(r#"{"k":[2]}"#), None]);
       let field = Arc::new(values.field("item"));
       let input = ListArray::new(field, OffsetBuffer::from_lengths([2]), 
values.into(), None);
       assert_cast_json(&input, r#"[{"k":[2]},null]"#);
   }
   ```
   
   The nested `{"k":[2]}` value also checks that field names from the child's 
metadata end up in the output metadata, which no current test covers. The 
`None` element covers the `is_null` branch.
   
   The shredded case fits in the struct test as a third column, next to the 
annotated and unannotated ones:
   
   ```rust
   let input = StructArray::from(vec![
       (Arc::new(child.field("a")), ArrayRef::from(child.clone())),
       (Arc::new(Field::new("b", child.inner().data_type().clone(), true)), 
child.into()),
       (Arc::new(shredded.field("c")), shredded.into()),
   ]);
   assert_cast_json(&input, 
r#"{"a":1,"b":{"metadata":"AQAA","value":"DAE="},"c":{"x":1,"y":"e"}}"#);
   ```
   
   I would drop the null row from the struct test. `obj1.get("a") == None` pins 
the current "drop null members" behaviour, which #11965 (open) changes, and it 
is not what this PR is about. The list test covers the SQL NULL branch already.
   
   For the union, a single Variant field is enough 
(`UnionFields::from_fields(vec![child.field("v")])`). The `Int32` child goes 
through the existing path.



##########
parquet-variant-compute/src/arrow_to_variant.rs:
##########
@@ -669,11 +729,19 @@ impl<'a> UnionArrowToVariantBuilder<'a> {
         let mut child_builders = HashMap::new();
         for &type_id in type_ids {
             let child_array = union_array.child(type_id);
-            let child_builder = make_arrow_to_variant_row_builder(
-                child_array.data_type(),
-                child_array.as_ref(),
-                options,
-            )?;
+            let child_builder = match 
union_array.fields().find_by_type_id(type_id) {

Review Comment:
   #12246 changed this loop on main to `for (type_id, _) in 
union_array.fields().iter()`. After the rebase the field is already in hand, so 
`find_by_type_id` and the `None` arm can go (`union_array.child(type_id)` 
panics for an unknown id before `None` could matter):
   
   ```rust
   for (type_id, child_field) in union_array.fields().iter() {
       let child_array = union_array.child(type_id);
       let child_builder =
           make_arrow_to_variant_row_builder_for_field(child_field, 
child_array.as_ref(), options)?;
       child_builders.insert(type_id, Box::new(child_builder));
   }
   ```



-- 
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