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


##########
parquet/src/arrow/arrow_reader/mod.rs:
##########
@@ -4431,4 +4431,258 @@ mod tests {
         assert_eq!(c0.len(), c1.len());
         c0.iter().zip(c1.iter()).for_each(|(l, r)| assert_eq!(l, r));
     }
+
+    #[test]
+    #[cfg(feature = "arrow_canonical_extension_types")]

Review Comment:
   one of the benefits of using the existing StructArray mechanism rather than 
a new Array type is that we can likely reuse most of the existing parquet 
writing code, focusing on ensuring the metadata is written/read accurately



##########
arrow-schema/src/extension/canonical/variant.rs:
##########
@@ -0,0 +1,233 @@
+// 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.
+
+//! Variant
+//!
+//! <https://arrow.apache.org/docs/format/CanonicalExtensions.html#variant>
+
+use base64::engine::Engine as _;
+use base64::engine::general_purpose::STANDARD;
+use crate::{extension::ExtensionType, ArrowError, DataType};
+
+/// The extension type for `Variant`.
+///
+/// Extension name: `arrow.variant`.
+///
+/// The storage type of this extension is **Binary or LargeBinary**.
+/// A Variant is a flexible structure that can store **Primitives, Arrays, or 
Objects**.
+/// It is stored as **two binary values**: `metadata` and `value`.
+///
+/// The **metadata field is required** and must be a valid Variant metadata 
string.
+/// The **value field is required** and contains the serialized Variant data.
+///
+/// <https://arrow.apache.org/docs/format/CanonicalExtensions.html#variant>
+#[derive(Debug, Clone, PartialEq)]
+pub struct Variant {
+    metadata: Vec<u8>, // Required binary metadata
+    value: Vec<u8>, // Required binary value
+}
+
+impl Variant {
+    /// Creates a new `Variant` with metadata and value.
+    pub fn new(metadata: Vec<u8>, value: Vec<u8>) -> Self {
+        Self { metadata, value }
+    }
+
+    /// Creates a Variant representing an empty structure.
+    pub fn empty() -> Result<Self, ArrowError> {
+        Err(ArrowError::InvalidArgumentError(
+            "Variant cannot be empty because metadata and value are 
required".to_owned(),
+        ))
+    }
+
+    /// Returns the metadata as a byte array.
+    pub fn metadata(&self) -> &[u8] {
+        &self.metadata
+    }
+
+    /// Returns the value as an byte array.
+    pub fn value(&self) -> &[u8] {
+        &self.value
+    }
+
+    /// Sets the value of the Variant.
+    pub fn set_value(mut self, value: Vec<u8>) -> Self {
+        self.value = value;
+        self
+    }
+}
+
+impl ExtensionType for Variant {
+    const NAME: &'static str = "arrow.variant";
+
+    type Metadata = Vec<u8>; // Metadata is directly Vec<u8>
+
+    fn metadata(&self) -> &Self::Metadata {
+        &self.metadata
+    }
+
+    fn serialize_metadata(&self) -> Option<String> {
+        Some(STANDARD.encode(&self.metadata)) // Encode metadata as STANDARD 
string

Review Comment:
   My understanding of the extension metadata for a variant column isn't the 
same as the metadata for each variant value -- I probably don't fully 
understand the code but I think the extension type metadata is stored for *each 
field* where the variant's metadata is stored for each *row* (basically the 
word metadata is overloaded 😢 )



##########
arrow-schema/src/extension/canonical/variant.rs:
##########
@@ -0,0 +1,233 @@
+// 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.
+
+//! Variant
+//!
+//! <https://arrow.apache.org/docs/format/CanonicalExtensions.html#variant>
+
+use base64::engine::Engine as _;
+use base64::engine::general_purpose::STANDARD;
+use crate::{extension::ExtensionType, ArrowError, DataType};
+
+/// The extension type for `Variant`.
+///
+/// Extension name: `arrow.variant`.
+///
+/// The storage type of this extension is **Binary or LargeBinary**.
+/// A Variant is a flexible structure that can store **Primitives, Arrays, or 
Objects**.
+/// It is stored as **two binary values**: `metadata` and `value`.
+///
+/// The **metadata field is required** and must be a valid Variant metadata 
string.
+/// The **value field is required** and contains the serialized Variant data.
+///
+/// <https://arrow.apache.org/docs/format/CanonicalExtensions.html#variant>
+#[derive(Debug, Clone, PartialEq)]
+pub struct Variant {
+    metadata: Vec<u8>, // Required binary metadata

Review Comment:
   One concern I have with this approach is that it will *require* two 
allocations (and memory copies) to read a Variant value
   
   I am hoping we can use Rust's borrow checker to do this with pointers (well, 
slices in rust) and no copying -- something like
   
   ```rust
   pub struct Variant<'a> {
       metadata: &'a [u8], // Required binary metadata
       value: &'a [u8],
   }
   ```



##########
arrow-array/src/array/variant_array.rs:
##########
@@ -0,0 +1,628 @@
+// 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.
+
+use crate::array::print_long_array;
+use crate::builder::{ArrayBuilder, BinaryBuilder};
+use crate::{Array, ArrayRef};
+use arrow_buffer::{Buffer, NullBuffer, OffsetBuffer, ScalarBuffer};
+use arrow_data::{ArrayData, ArrayDataBuilder};
+use arrow_schema::{ArrowError, DataType, Field};
+
+#[cfg(feature = "canonical_extension_types")]
+use arrow_schema::extension::Variant;
+use std::sync::Arc;
+use std::any::Any;
+
+/// An array of Variant values.
+///
+/// The Variant extension type stores data as two binary values: metadata and 
value.
+/// This array stores each Variant as a concatenated binary value (metadata + 
value).
+///
+/// # Example
+///
+/// ```
+/// use arrow_array::VariantArray;
+/// use arrow_schema::extension::Variant;
+/// use arrow_array::Array; // Import the Array trait
+///
+/// // Create metadata and value for each variant
+/// let metadata = vec![
+///     0x01,  // header: version=1, sorted=0, offset_size=1
+///     0x01,  // dictionary_size = 1
+///     0x00,  // offset 0
+///     0x03,  // offset 3
+///     b'k', b'e', b'y'  // dictionary bytes
+/// ];
+/// let variant_type = Variant::new(metadata.clone(), vec![]);
+/// 
+/// // Create variants with different values
+/// let variants = vec![
+///     Variant::new(metadata.clone(), b"null".to_vec()),
+///     Variant::new(metadata.clone(), b"true".to_vec()),
+///     Variant::new(metadata.clone(), b"{\"a\": 1}".to_vec()),
+/// ];
+/// 
+/// // Create a VariantArray
+/// let variant_array = VariantArray::from_variants(variant_type, 
variants.clone()).expect("Failed to create VariantArray");
+///
+/// // Access variants from the array
+/// assert_eq!(variant_array.len(), 3);
+/// let retrieved = variant_array.value(0).expect("Failed to get value");
+/// assert_eq!(retrieved.metadata(), &metadata);
+/// assert_eq!(retrieved.value(), b"null");
+/// ```
+#[cfg(feature = "canonical_extension_types")]
+pub mod variant_array_module {
+    use super::*;
+
+    /// An array of Variant values.
+    ///
+    /// The Variant extension type stores data as two binary values: metadata 
and value.
+    /// This array stores each Variant as a concatenated binary value 
(metadata + value).
+    ///
+    /// # Example
+    ///
+    /// ```
+    /// use arrow_array::VariantArray;
+    /// use arrow_schema::extension::Variant;
+    /// use arrow_array::Array; // Import the Array trait
+    ///
+    /// // Create metadata and value for each variant
+    /// let metadata = vec![
+    ///     0x01,  // header: version=1, sorted=0, offset_size=1
+    ///     0x01,  // dictionary_size = 1
+    ///     0x00,  // offset 0
+    ///     0x03,  // offset 3
+    ///     b'k', b'e', b'y'  // dictionary bytes
+    /// ];
+    /// let variant_type = Variant::new(metadata.clone(), vec![]);
+    /// 
+    /// // Create variants with different values
+    /// let variants = vec![
+    ///     Variant::new(metadata.clone(), b"null".to_vec()),
+    ///     Variant::new(metadata.clone(), b"true".to_vec()),
+    ///     Variant::new(metadata.clone(), b"{\"a\": 1}".to_vec()),
+    /// ];
+    /// 
+    /// // Create a VariantArray
+    /// let variant_array = VariantArray::from_variants(variant_type, 
variants.clone()).expect("Failed to create VariantArray");
+    ///
+    /// // Access variants from the array
+    /// assert_eq!(variant_array.len(), 3);
+    /// let retrieved = variant_array.value(0).expect("Failed to get value");
+    /// assert_eq!(retrieved.metadata(), &metadata);
+    /// assert_eq!(retrieved.value(), b"null");
+    /// ```
+    #[derive(Clone, Debug)]
+    pub struct VariantArray {

Review Comment:
   One thing that we may want to explore is to model this as a `StructArray` 
with two fields, `"metadata"` and `"value"` which appears to be how @neilechao 
modeled it in the C++ implementation that merged a few days ago
   -  https://github.com/apache/arrow/pull/45375



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