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


##########
parquet-variant-compute/src/variant_array.rs:
##########
@@ -186,13 +340,11 @@ impl Array for VariantArray {
     }
 
     fn slice(&self, offset: usize, length: usize) -> ArrayRef {
-        let slice = self.inner.slice(offset, length);
-        let met = self.metadata_ref.slice(offset, length);
-        let val = self.value_ref.slice(offset, length);
+        let inner = self.inner.slice(offset, length);
+        let shredding_state = self.shredding_state.slice(offset, length);
         Arc::new(Self {

Review Comment:
   I agree I don't expect any measurable performance improvement



##########
parquet-variant-compute/src/variant_get/output/primitive.rs:
##########
@@ -0,0 +1,166 @@
+// 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::variant_get::output::OutputBuilder;
+use crate::VariantArray;
+use arrow::error::Result;
+
+use arrow::array::{
+    Array, ArrayRef, ArrowPrimitiveType, AsArray, BinaryViewArray, 
NullBufferBuilder,
+    PrimitiveArray,
+};
+use arrow::compute::{cast_with_options, CastOptions};
+use arrow::datatypes::Int32Type;
+use arrow_schema::{ArrowError, FieldRef};
+use parquet_variant::{Variant, VariantPath};
+use std::marker::PhantomData;
+use std::sync::Arc;
+
+/// Trait for Arrow primitive types that can be used in the output builder
+///
+/// This just exists to add a generic way to convert from Variant to the 
primitive type
+pub(super) trait ArrowPrimitiveVariant: ArrowPrimitiveType {
+    /// Try to extract the primitive value from a Variant, returning None if it
+    /// cannot be converted
+    ///
+    /// TODO: figure out how to handle coercion/casting
+    fn from_variant(variant: &Variant) -> Option<Self::Native>;
+}
+
+/// Outputs Primitive arrays
+pub(super) struct PrimitiveOutputBuilder<'a, T: ArrowPrimitiveVariant> {
+    /// What path to extract
+    path: VariantPath<'a>,
+    /// Returned output type
+    as_type: FieldRef,
+    /// Controls the casting behavior (e.g. error vs substituting null on cast 
error).
+    cast_options: CastOptions<'a>,
+    /// Phantom data for the primitive type
+    _phantom: PhantomData<T>,
+}
+
+impl<'a, T: ArrowPrimitiveVariant> PrimitiveOutputBuilder<'a, T> {
+    pub(super) fn new(
+        path: VariantPath<'a>,
+        as_type: FieldRef,
+        cast_options: CastOptions<'a>,
+    ) -> Self {
+        Self {
+            path,
+            as_type,
+            cast_options,
+            _phantom: PhantomData,
+        }
+    }
+}
+
+impl<'a, T: ArrowPrimitiveVariant> OutputBuilder for 
PrimitiveOutputBuilder<'a, T> {
+    fn partially_shredded(
+        &self,
+        variant_array: &VariantArray,
+        _metadata: &BinaryViewArray,
+        _value_field: &BinaryViewArray,
+        typed_value: &ArrayRef,
+    ) -> arrow::error::Result<ArrayRef> {
+        // build up the output array element by element
+        let mut nulls = NullBufferBuilder::new(variant_array.len());
+        let mut values = Vec::with_capacity(variant_array.len());
+        let typed_value =
+            cast_with_options(typed_value, self.as_type.data_type(), 
&self.cast_options)?;
+        // downcast to the primitive array (e.g. Int32Array, Float64Array, etc)
+        let typed_value = typed_value.as_primitive::<T>();
+
+        for i in 0..variant_array.len() {
+            if variant_array.is_null(i) {
+                nulls.append_null();
+                values.push(T::default_value()); // not used, placeholder
+                continue;
+            }
+
+            // if the typed value is null, decode the variant and extract the 
value
+            if typed_value.is_null(i) {
+                // todo follow path
+                let variant = variant_array.value(i);
+                let Some(value) = T::from_variant(&variant) else {
+                    if self.cast_options.safe {
+                        // safe mode: append null if we can't convert
+                        nulls.append_null();
+                        values.push(T::default_value()); // not used, 
placeholder
+                        continue;
+                    } else {
+                        return Err(ArrowError::CastError(format!(
+                            "Failed to extract primitive of type {} from 
variant {:?} at path {:?}",
+                            self.as_type.data_type(),
+                            variant,
+                            self.path
+                        )));
+                    }
+                };
+
+                nulls.append_non_null();
+                values.push(value)
+            } else {
+                // otherwise we have a typed value, so we can use it directly
+                nulls.append_non_null();
+                values.push(typed_value.value(i));
+            }
+        }
+
+        let nulls = nulls.finish();
+        let array = PrimitiveArray::<T>::new(values.into(), nulls)
+            .with_data_type(self.as_type.data_type().clone());
+        Ok(Arc::new(array))
+    }
+
+    fn fully_shredded(
+        &self,
+        _variant_array: &VariantArray,
+        _metadata: &BinaryViewArray,
+        typed_value: &ArrayRef,
+    ) -> arrow::error::Result<ArrayRef> {
+        // if the types match exactly, we can just return the typed_value
+        if typed_value.data_type() == self.as_type.data_type() {
+            Ok(typed_value.clone())
+        } else {
+            // TODO: try to cast the typed_value to the desired type?
+            Err(ArrowError::NotYetImplemented(format!(

Review Comment:
   Yeah, I am not sure what to do with this casting -- I will file a follow on 
ticket for us to sort it out



##########
parquet-variant-compute/src/variant_get/mod.rs:
##########
@@ -0,0 +1,430 @@
+// 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 arrow::{
+    array::{Array, ArrayRef},
+    compute::CastOptions,
+    error::Result,
+};
+use arrow_schema::{ArrowError, FieldRef};
+use parquet_variant::VariantPath;
+
+use crate::variant_array::ShreddingState;
+use crate::variant_get::output::instantiate_output_builder;
+use crate::VariantArray;
+
+mod output;
+
+/// Returns an array with the specified path extracted from the variant values.
+///
+/// The return array type depends on the `as_type` field of the options 
parameter
+/// 1. `as_type: None`: a VariantArray is returned. The values in this new 
VariantArray will point
+///    to the specified path.
+/// 2. `as_type: Some(<specific field>)`: an array of the specified type is 
returned.
+pub fn variant_get(input: &ArrayRef, options: GetOptions) -> Result<ArrayRef> {
+    let variant_array: &VariantArray = 
input.as_any().downcast_ref().ok_or_else(|| {
+        ArrowError::InvalidArgumentError(
+            "expected a VariantArray as the input for variant_get".to_owned(),
+        )
+    })?;
+
+    // Create the output writer based on the specified output options
+    let output_builder = instantiate_output_builder(options.clone())?;
+
+    // Dispatch based on the shredding state of the input variant array
+    match variant_array.shredding_state() {

Review Comment:
   Yeah, exactly, this I think is the key challenge of this code -- each 
different type of output needs to handle all the possible input shredding types 
as well. 



##########
parquet-variant-compute/src/variant_get/output/mod.rs:
##########


Review Comment:
   I think this aligns with my thinking and is nicely described -- I will use 
it as the base for the next set of tickets perhaps



##########
parquet-variant-compute/src/variant_get/output/primitive.rs:
##########
@@ -0,0 +1,166 @@
+// 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::variant_get::output::OutputBuilder;
+use crate::VariantArray;
+use arrow::error::Result;
+
+use arrow::array::{
+    Array, ArrayRef, ArrowPrimitiveType, AsArray, BinaryViewArray, 
NullBufferBuilder,
+    PrimitiveArray,
+};
+use arrow::compute::{cast_with_options, CastOptions};
+use arrow::datatypes::Int32Type;
+use arrow_schema::{ArrowError, FieldRef};
+use parquet_variant::{Variant, VariantPath};
+use std::marker::PhantomData;
+use std::sync::Arc;
+
+/// Trait for Arrow primitive types that can be used in the output builder
+///
+/// This just exists to add a generic way to convert from Variant to the 
primitive type
+pub(super) trait ArrowPrimitiveVariant: ArrowPrimitiveType {
+    /// Try to extract the primitive value from a Variant, returning None if it
+    /// cannot be converted
+    ///
+    /// TODO: figure out how to handle coercion/casting
+    fn from_variant(variant: &Variant) -> Option<Self::Native>;
+}
+
+/// Outputs Primitive arrays
+pub(super) struct PrimitiveOutputBuilder<'a, T: ArrowPrimitiveVariant> {
+    /// What path to extract
+    path: VariantPath<'a>,
+    /// Returned output type
+    as_type: FieldRef,
+    /// Controls the casting behavior (e.g. error vs substituting null on cast 
error).
+    cast_options: CastOptions<'a>,
+    /// Phantom data for the primitive type
+    _phantom: PhantomData<T>,
+}
+
+impl<'a, T: ArrowPrimitiveVariant> PrimitiveOutputBuilder<'a, T> {
+    pub(super) fn new(
+        path: VariantPath<'a>,
+        as_type: FieldRef,
+        cast_options: CastOptions<'a>,
+    ) -> Self {
+        Self {
+            path,
+            as_type,
+            cast_options,
+            _phantom: PhantomData,
+        }
+    }
+}
+
+impl<'a, T: ArrowPrimitiveVariant> OutputBuilder for 
PrimitiveOutputBuilder<'a, T> {
+    fn partially_shredded(
+        &self,
+        variant_array: &VariantArray,
+        _metadata: &BinaryViewArray,
+        _value_field: &BinaryViewArray,
+        typed_value: &ArrayRef,
+    ) -> arrow::error::Result<ArrayRef> {
+        // build up the output array element by element
+        let mut nulls = NullBufferBuilder::new(variant_array.len());
+        let mut values = Vec::with_capacity(variant_array.len());
+        let typed_value =
+            cast_with_options(typed_value, self.as_type.data_type(), 
&self.cast_options)?;
+        // downcast to the primitive array (e.g. Int32Array, Float64Array, etc)
+        let typed_value = typed_value.as_primitive::<T>();
+
+        for i in 0..variant_array.len() {
+            if variant_array.is_null(i) {
+                nulls.append_null();
+                values.push(T::default_value()); // not used, placeholder
+                continue;
+            }
+
+            // if the typed value is null, decode the variant and extract the 
value
+            if typed_value.is_null(i) {
+                // todo follow path

Review Comment:
   > We'd either have to do all the pathing here (recursively), or caller would 
have to to extract the struct/array once and recurse on its fields.
   
   Yes, I was imagining that this would do the pathing here on each row -- I am 
not sure what you mean by extract the struct array (as I don't think we can 
extract variants as structs in general, as the structures vary row by row)



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