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


##########
parquet-variant-compute/src/from_json.rs:
##########
@@ -135,43 +68,38 @@ mod test {
             None,
         ]);
         let array_ref: ArrayRef = Arc::new(input);
-        let output = batch_json_string_to_variant(&array_ref).unwrap();
+        let variant_array = batch_json_string_to_variant(&array_ref).unwrap();
 
-        let struct_array = &output;
-        let metadata_array = struct_array
-            .column(0)
-            .as_any()
-            .downcast_ref::<BinaryArray>()
-            .unwrap();
-        let value_array = struct_array
-            .column(1)
-            .as_any()
-            .downcast_ref::<BinaryArray>()
-            .unwrap();
+        let metadata_array = variant_array.metadata_field().as_binary_view();
+        let value_array = variant_array.value_field().as_binary_view();
 
-        assert!(!struct_array.is_null(0));
-        assert!(struct_array.is_null(1));
-        assert!(!struct_array.is_null(2));
-        assert!(!struct_array.is_null(3));
-        assert!(struct_array.is_null(4));
+        // Compare row 0
+        assert!(!variant_array.is_null(0));
+        assert_eq!(variant_array.value(0), Variant::Int8(1));

Review Comment:
   I haven't fully worked out in my head how this will work for shredded 
Variants -- specifically how to avoid copying stuff around when accessing a 
shredded variant. We'll have to figure that out in follow on PRs



##########
parquet-variant-compute/src/from_json.rs:
##########
@@ -18,109 +18,42 @@
 //! Module for transforming a batch of JSON strings into a batch of Variants 
represented as
 //! STRUCT<metadata: BINARY, value: BINARY>
 
-use std::sync::Arc;
-
-use arrow::array::{Array, ArrayRef, BinaryArray, BooleanBufferBuilder, 
StringArray, StructArray};
-use arrow::buffer::{Buffer, NullBuffer, OffsetBuffer, ScalarBuffer};
-use arrow::datatypes::{DataType, Field};
+use crate::{VariantArray, VariantArrayBuilder};
+use arrow::array::{Array, ArrayRef, StringArray};
 use arrow_schema::ArrowError;
 use parquet_variant::VariantBuilder;
 use parquet_variant_json::json_to_variant;
 
-fn variant_arrow_repr() -> DataType {
-    // The subfields are expected to be non-nullable according to the parquet 
variant spec.
-    let metadata_field = Field::new("metadata", DataType::Binary, false);
-    let value_field = Field::new("value", DataType::Binary, false);
-    let fields = vec![metadata_field, value_field];
-    DataType::Struct(fields.into())
-}
-
 /// Parse a batch of JSON strings into a batch of Variants represented as
 /// STRUCT<metadata: BINARY, value: BINARY> where nulls are preserved. The 
JSON strings in the input
 /// must be valid.
-pub fn batch_json_string_to_variant(input: &ArrayRef) -> Result<StructArray, 
ArrowError> {
+pub fn batch_json_string_to_variant(input: &ArrayRef) -> Result<VariantArray, 
ArrowError> {
     let input_string_array = match 
input.as_any().downcast_ref::<StringArray>() {
         Some(string_array) => Ok(string_array),
         None => Err(ArrowError::CastError(
             "Expected reference to StringArray as input".into(),
         )),
     }?;
 
-    // Zero-copy builders
-    let mut metadata_buffer: Vec<u8> = Vec::with_capacity(input.len() * 128);
-    let mut metadata_offsets: Vec<i32> = Vec::with_capacity(input.len() + 1);
-    let mut metadata_validity = BooleanBufferBuilder::new(input.len());
-    let mut metadata_current_offset: i32 = 0;
-    metadata_offsets.push(metadata_current_offset);
-
-    let mut value_buffer: Vec<u8> = Vec::with_capacity(input.len() * 128);
-    let mut value_offsets: Vec<i32> = Vec::with_capacity(input.len() + 1);
-    let mut value_validity = BooleanBufferBuilder::new(input.len());
-    let mut value_current_offset: i32 = 0;
-    value_offsets.push(value_current_offset);
-
-    let mut validity = BooleanBufferBuilder::new(input.len());
+    let mut variant_array_builder = 
VariantArrayBuilder::new(input_string_array.len());
     for i in 0..input.len() {
         if input.is_null(i) {
             // The subfields are expected to be non-nullable according to the 
parquet variant spec.
-            metadata_validity.append(true);
-            value_validity.append(true);
-            metadata_offsets.push(metadata_current_offset);
-            value_offsets.push(value_current_offset);
-            validity.append(false);
+            variant_array_builder.append_null();
         } else {
             let mut vb = VariantBuilder::new();
             json_to_variant(input_string_array.value(i), &mut vb)?;
             let (metadata, value) = vb.finish();
-            validity.append(true);
-
-            metadata_current_offset += metadata.len() as i32;
-            metadata_buffer.extend(metadata);
-            metadata_offsets.push(metadata_current_offset);
-            metadata_validity.append(true);
-
-            value_current_offset += value.len() as i32;
-            value_buffer.extend(value);
-            value_offsets.push(value_current_offset);
-            value_validity.append(true);
+            variant_array_builder.append_variant_buffers(&metadata, &value);

Review Comment:
   This is what I came up with
   - https://github.com/apache/arrow-rs/pull/7911



##########
parquet-variant-compute/src/variant_array.rs:
##########
@@ -0,0 +1,227 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! [`VariantArray`] implementation
+
+use arrow::array::{Array, ArrayData, ArrayRef, AsArray, StructArray};
+use arrow::buffer::NullBuffer;
+use arrow_schema::{ArrowError, DataType};
+use parquet_variant::Variant;
+use std::any::Any;
+use std::sync::Arc;
+
+/// An array of Parquet [`Variant`] values
+///
+/// A [`VariantArray`] wraps an Arrow [`StructArray`] that stores the 
underlying
+/// `metadata` and `value` fields, and adds convenience methods to access
+/// the `Variant`s
+///
+/// See [`VariantArrayBuilder`] for constructing a `VariantArray`.
+///
+/// [`VariantArrayBuilder`]: crate::VariantArrayBuilder
+///
+/// # Specification
+/// 1. This code follows the conventions for storing variants in Arrow Struct 
Array
+///    defined by [Extension Type for Parquet Variant arrow] and this 
[document].
+///    At the time of this writing, this is not yet a standardized Arrow 
extension type.
+///
+/// [Extension Type for Parquet Variant arrow]: 
https://github.com/apache/arrow/issues/46908
+/// [document]: 
https://docs.google.com/document/d/1pw0AWoMQY3SjD7R4LgbPvMjG_xSCtXp3rZHkVp9jpZ4/edit?usp=sharing
+#[derive(Debug)]
+pub struct VariantArray {
+    /// StructArray or up to three fields:
+    /// 1. A required field named metadata which is binary, large_binary, or 
binary_view
+    /// 2. An optional field named value that is binary, large_binary, or 
binary_view
+    /// 3. An optional field named typed_value which can be any primitive type 
or be a list, large_list, list_view or struct
+    ///
+    /// If typed_value is a nested type, its elements must be required and must
+    /// be a struct containing only one of the following:
+    ///
+    /// 1. A single required field, of type binary, large_binary, or 
binary_view named value
+    ///
+    /// 2. An optional field named value of type binary, large_binary, or
+    ///    binary_view AND an optional field named typed_value which follows 
these
+    ///    same rules

Review Comment:
   I agree -- I think I did not read the proposal correctly. I will correct the 
wording
   
   
https://docs.google.com/document/d/1pw0AWoMQY3SjD7R4LgbPvMjG_xSCtXp3rZHkVp9jpZ4/edit?tab=t.0#heading=h.ru2zdn2szuc4



##########
parquet-variant-compute/src/variant_array.rs:
##########
@@ -0,0 +1,227 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! [`VariantArray`] implementation
+
+use arrow::array::{Array, ArrayData, ArrayRef, AsArray, StructArray};
+use arrow::buffer::NullBuffer;
+use arrow_schema::{ArrowError, DataType};
+use parquet_variant::Variant;
+use std::any::Any;
+use std::sync::Arc;
+
+/// An array of Parquet [`Variant`] values
+///
+/// A [`VariantArray`] wraps an Arrow [`StructArray`] that stores the 
underlying
+/// `metadata` and `value` fields, and adds convenience methods to access
+/// the `Variant`s
+///
+/// See [`VariantArrayBuilder`] for constructing a `VariantArray`.
+///
+/// [`VariantArrayBuilder`]: crate::VariantArrayBuilder
+///
+/// # Specification
+/// 1. This code follows the conventions for storing variants in Arrow Struct 
Array
+///    defined by [Extension Type for Parquet Variant arrow] and this 
[document].
+///    At the time of this writing, this is not yet a standardized Arrow 
extension type.
+///
+/// [Extension Type for Parquet Variant arrow]: 
https://github.com/apache/arrow/issues/46908
+/// [document]: 
https://docs.google.com/document/d/1pw0AWoMQY3SjD7R4LgbPvMjG_xSCtXp3rZHkVp9jpZ4/edit?usp=sharing
+#[derive(Debug)]
+pub struct VariantArray {
+    /// StructArray or up to three fields:
+    /// 1. A required field named metadata which is binary, large_binary, or 
binary_view
+    /// 2. An optional field named value that is binary, large_binary, or 
binary_view
+    /// 3. An optional field named typed_value which can be any primitive type 
or be a list, large_list, list_view or struct
+    ///
+    /// If typed_value is a nested type, its elements must be required and must
+    /// be a struct containing only one of the following:
+    ///
+    /// 1. A single required field, of type binary, large_binary, or 
binary_view named value
+    ///
+    /// 2. An optional field named value of type binary, large_binary, or
+    ///    binary_view AND an optional field named typed_value which follows 
these
+    ///    same rules
+    ///
+    /// NOTE: It is also permissible for the metadata field to be
+    /// Dictionary-Encoded, preferably (but not required) with an index type of
+    /// int8.
+    inner: StructArray,

Review Comment:
   I filed a ticket to track
   - https://github.com/apache/arrow-rs/issues/7920



##########
parquet-variant-compute/src/variant_array.rs:
##########
@@ -0,0 +1,227 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! [`VariantArray`] implementation
+
+use arrow::array::{Array, ArrayData, ArrayRef, AsArray, StructArray};
+use arrow::buffer::NullBuffer;
+use arrow_schema::{ArrowError, DataType};
+use parquet_variant::Variant;
+use std::any::Any;
+use std::sync::Arc;
+
+/// An array of Parquet [`Variant`] values
+///
+/// A [`VariantArray`] wraps an Arrow [`StructArray`] that stores the 
underlying
+/// `metadata` and `value` fields, and adds convenience methods to access
+/// the `Variant`s
+///
+/// See [`VariantArrayBuilder`] for constructing a `VariantArray`.
+///
+/// [`VariantArrayBuilder`]: crate::VariantArrayBuilder
+///
+/// # Specification
+/// 1. This code follows the conventions for storing variants in Arrow Struct 
Array
+///    defined by [Extension Type for Parquet Variant arrow] and this 
[document].
+///    At the time of this writing, this is not yet a standardized Arrow 
extension type.
+///
+/// [Extension Type for Parquet Variant arrow]: 
https://github.com/apache/arrow/issues/46908
+/// [document]: 
https://docs.google.com/document/d/1pw0AWoMQY3SjD7R4LgbPvMjG_xSCtXp3rZHkVp9jpZ4/edit?usp=sharing
+#[derive(Debug)]
+pub struct VariantArray {
+    /// StructArray or up to three fields:
+    /// 1. A required field named metadata which is binary, large_binary, or 
binary_view
+    /// 2. An optional field named value that is binary, large_binary, or 
binary_view
+    /// 3. An optional field named typed_value which can be any primitive type 
or be a list, large_list, list_view or struct
+    ///
+    /// If typed_value is a nested type, its elements must be required and must
+    /// be a struct containing only one of the following:
+    ///
+    /// 1. A single required field, of type binary, large_binary, or 
binary_view named value
+    ///
+    /// 2. An optional field named value of type binary, large_binary, or
+    ///    binary_view AND an optional field named typed_value which follows 
these
+    ///    same rules
+    ///
+    /// NOTE: It is also permissible for the metadata field to be
+    /// Dictionary-Encoded, preferably (but not required) with an index type of
+    /// int8.
+    inner: StructArray,
+}
+
+impl VariantArray {
+    /// Creates a new `VariantArray` from a [`StructArray`].
+    ///
+    /// # Arguments
+    /// - `inner` - The underlying [`StructArray`] that contains the variant 
data.
+    ///
+    /// # Returns
+    /// - A new instance of `VariantArray`.
+    ///
+    /// # Errors:
+    /// If the `StructArray` does not contain the required fields
+    pub fn try_new(inner: ArrayRef) -> Result<Self, ArrowError> {
+        let Some(inner) = inner.as_struct_opt() else {
+            return Err(ArrowError::InvalidArgumentError(
+                "Invalid VariantArray: requires StructArray as 
input".to_string(),
+            ));
+        };
+        // Ensure the StructArray has the expected fields
+        if !inner.fields().iter().any(|f| f.name() == "metadata") {
+            return Err(ArrowError::InvalidArgumentError(
+                "Invalid VariantArray: StructArray must contain a 'metadata' 
field".to_string(),
+            ));
+        }
+        if !inner.fields().iter().any(|f| f.name() == "value") {
+            return Err(ArrowError::InvalidArgumentError(
+                "Invalid VariantArray: StructArray must contain a 'value' 
field".to_string(),
+            ));
+        }

Review Comment:
   I don't know either
   



-- 
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: github-unsubscr...@arrow.apache.org

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org

Reply via email to