Skip to main content

parquet_variant_compute/
variant_array.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! [`VariantArray`] implementation
6
7use crate::VariantArrayBuilder;
8use crate::type_conversion::{
9    generic_conversion_single_value, generic_conversion_single_value_with_result,
10    primitive_conversion_single_value,
11};
12use arrow::array::{
13    Array, ArrayRef, AsArray, StructArray, StructArrayAssembler, downcast_dictionary_array,
14    downcast_run_array, new_null_array,
15};
16use arrow::buffer::NullBuffer;
17use arrow::compute::cast;
18use arrow::datatypes::{
19    Date32Type, Decimal32Type, Decimal64Type, Decimal128Type, Float16Type, Float32Type,
20    Float64Type, Int8Type, Int16Type, Int32Type, Int64Type, Time64MicrosecondType,
21    TimestampMicrosecondType, TimestampNanosecondType,
22};
23use arrow::error::Result;
24use arrow_schema::extension::{ExtensionType, Uuid as UuidExtension};
25use arrow_schema::{ArrowError, DataType, Field, FieldRef, TimeUnit};
26use chrono::{DateTime, NaiveTime};
27use parquet_variant::{
28    Uuid, Variant, VariantDecimal4, VariantDecimal8, VariantDecimal16, VariantDecimalType as _,
29    VariantType,
30};
31
32use std::borrow::Cow;
33use std::sync::Arc;
34
35/// Returns the logical bytes at the given index from a binary-like array, resolving dictionary
36/// and run-end encodings. Returns `None` for nulls or if the logical values aren't binary-like.
37pub(crate) fn binary_array_value(array: &dyn Array, index: usize) -> Option<&[u8]> {
38    if array.is_null(index) {
39        return None;
40    }
41    match array.data_type() {
42        DataType::Binary => Some(array.as_binary::<i32>().value(index)),
43        DataType::LargeBinary => Some(array.as_binary::<i64>().value(index)),
44        DataType::BinaryView => Some(array.as_binary_view().value(index)),
45        DataType::Dictionary(..) => downcast_dictionary_array! {
46            array => {
47                let index = array.key(index)?;
48                binary_array_value(array.values().as_ref(), index)
49            },
50            _ => unreachable!(),
51        },
52        DataType::RunEndEncoded(..) => downcast_run_array! {
53            array => {
54                let index = array.get_physical_index(index);
55                binary_array_value(array.values().as_ref(), index)
56            },
57            _ => unreachable!(),
58        },
59        _ => None,
60    }
61}
62
63/// Returns a [`Variant`] from a `metadata` and `value` byte arrays, returns `None`
64/// if one of them is of invalid type.
65pub(crate) fn variant_from_arrays_at<'m, 'v>(
66    metadata: &'m dyn Array,
67    value: &'v dyn Array,
68    index: usize,
69) -> Option<Variant<'m, 'v>> {
70    let metadata = binary_array_value(metadata, index)?;
71    let value = binary_array_value(value, index)?;
72    Some(Variant::new(metadata, value))
73}
74
75/// Returns an all-null binary `value` column of the given length.
76///
77/// The shredding spec requires the `value` column to always be present in the
78/// schema, so producers that have no unshredded values to store must still
79/// emit an all-null column. See <https://github.com/apache/arrow-rs/issues/10306>.
80pub(crate) fn all_null_value_column(len: usize) -> ArrayRef {
81    new_null_array(&DataType::BinaryView, len)
82}
83
84/// Validates that an array has a binary-like data type.
85pub(crate) fn validate_binary_array(array: &dyn Array, field_name: &str) -> Result<()> {
86    match array.data_type() {
87        DataType::Binary | DataType::LargeBinary | DataType::BinaryView => Ok(()),
88        _ => Err(ArrowError::InvalidArgumentError(format!(
89            "VariantArray '{field_name}' field must be Binary, LargeBinary, or BinaryView, got {}",
90            array.data_type()
91        ))),
92    }
93}
94
95/// An array of Parquet [`Variant`] values
96///
97/// A [`VariantArray`] wraps an Arrow [`StructArray`] that stores the underlying
98/// `metadata` and `value` fields, and adds convenience methods to access
99/// the [`Variant`]s.
100///
101/// See [`VariantArrayBuilder`] for constructing `VariantArray` row by row.
102///
103/// See the examples below from converting between `VariantArray` and
104/// `StructArray`.
105///
106/// # Example: collecting optional values
107///
108/// `VariantArray` can collect optional values that convert into [`Variant`].
109/// `None` creates a null row, while `Some(Variant::Null)` creates a valid row
110/// whose value is `Variant::Null`.
111///
112/// ```
113/// # use parquet_variant::Variant;
114/// # use parquet_variant_compute::VariantArray;
115/// let values = [Some(42_i64), None, Some(-1_i64)];
116/// let array: VariantArray = values.into_iter().collect();
117///
118/// assert_eq!(array.value(0), Variant::Int64(42));
119/// assert!(array.is_null(1));
120/// ```
121///
122/// For an all-null array, specify the type when no `Some` value can infer it:
123///
124/// ```
125/// # use parquet_variant::Variant;
126/// # use parquet_variant_compute::VariantArray;
127/// let null_rows = VariantArray::from_iter(vec![None::<Variant>; 3]);
128/// assert!(null_rows.is_null(0));
129/// ```
130///
131/// [`VariantArrayBuilder`]: crate::VariantArrayBuilder
132///
133/// # Documentation
134///
135/// Variant is documented as a canonical Arrow extension type in the
136/// [Parquet Variant] section of the [official list of extension types] on
137/// the Apache Arrow website.
138///
139/// [Parquet Variant]: https://arrow.apache.org/docs/format/CanonicalExtensions.html#parquet-variant
140/// [official list of extension types]: https://arrow.apache.org/docs/format/CanonicalExtensions.html
141///
142/// # Example: Check if a [`StructArray`] has the [`VariantType`] extension
143///
144/// Arrow Arrays only provide [`DataType`], but the extension type information
145/// is stored on a [`Field`]. Thus, you must have access to the [`Schema`] or
146/// [`Field`] to check for the extension type.
147///
148/// [`Schema`]: arrow_schema::Schema
149/// ```
150/// # use arrow::array::StructArray;
151/// # use arrow_schema::{Schema, Field, DataType};
152/// # use parquet_variant_compute::{VariantArray, VariantType};
153/// # fn get_variant_array() -> VariantArray {
154/// #   VariantArray::from_iter([Some("such wow")])
155/// # }
156/// # fn get_schema() -> Schema {
157/// #   Schema::new(vec![
158/// #     Field::new("id", DataType::Int32, false),
159/// #     get_variant_array().field("var"),
160/// #   ])
161/// # }
162/// let schema = get_schema();
163/// assert_eq!(schema.fields().len(), 2);
164/// // first field is not a Variant
165/// assert!(!schema.field(0).has_valid_extension_type::<VariantType>());
166/// // second field is a Variant
167/// assert!(schema.field(1).has_valid_extension_type::<VariantType>());
168/// ```
169///
170/// # Example: Constructing the correct [`Field`] for a [`VariantArray`]
171///
172/// You can construct the correct [`Field`] for a [`VariantArray`] using the
173/// [`VariantArray::field`] method.
174///
175/// ```
176/// # use arrow_schema::{Schema, Field, DataType};
177/// # use parquet_variant_compute::{VariantArray, VariantType};
178/// # fn get_variant_array() -> VariantArray {
179/// #   VariantArray::from_iter([Some("such wow")])
180/// # }
181/// let variant_array = get_variant_array();
182/// // First field is an integer id, second field is a variant
183/// let schema = Schema::new(vec![
184///   Field::new("id", DataType::Int32, false),
185///   // call VariantArray::field to get the correct Field
186///   variant_array.field("var"),
187/// ]);
188/// ```
189///
190/// You can also construct the [`Field`] using [`VariantType`] directly
191///
192/// ```
193/// # use arrow_schema::{Schema, Field, DataType};
194/// # use parquet_variant_compute::{VariantArray, VariantType};
195/// # fn get_variant_array() -> VariantArray {
196/// #   VariantArray::from_iter([Some("such wow")])
197/// # }
198/// # let variant_array = get_variant_array();
199/// // The DataType of a VariantArray varies depending on how it is shredded
200/// let data_type = variant_array.data_type().clone();
201/// // First field is an integer id, second field is a variant
202/// let schema = Schema::new(vec![
203///   Field::new("id", DataType::Int32, false),
204///   Field::new("var", data_type, false)
205///     // Add extension metadata to the field using `VariantType`
206///     .with_extension_type(VariantType),
207/// ]);
208/// ```
209///
210/// # Example: Converting a [`VariantArray`] to a [`StructArray`]
211///
212/// ```
213/// # use arrow::array::StructArray;
214/// # use parquet_variant_compute::VariantArray;
215/// // Create Variant Array
216/// let variant_array = VariantArray::from_iter([Some("such wow")]);
217/// // convert to StructArray
218/// let struct_array: StructArray = variant_array.into();
219/// ```
220///
221/// # Example: Converting a [`StructArray`] to a [`VariantArray`]
222///
223/// ```
224/// # use arrow::array::StructArray;
225/// # use parquet_variant::Variant;
226/// # use parquet_variant_compute::VariantArray;
227/// # fn get_struct_array() -> StructArray {
228/// #   VariantArray::from_iter([Some("such wow")]).into()
229/// # }
230/// let struct_array: StructArray = get_struct_array();
231/// // try and create a VariantArray from it
232/// let variant_array = VariantArray::try_new(&struct_array).unwrap();
233/// assert_eq!(variant_array.value(0), Variant::from("such wow"));
234/// ```
235///
236#[derive(Debug, Clone)]
237pub struct VariantArray {
238    /// Reference to the underlying StructArray
239    inner: StructArray,
240
241    /// The metadata column of this variant (Binary, LargeBinary, or BinaryView), possibly encoded
242    metadata: ArrayRef,
243
244    /// how is this variant array shredded?
245    shredding_state: ShreddingState,
246}
247
248impl VariantArray {
249    /// Creates a new `VariantArray` from a [`StructArray`].
250    ///
251    /// # Arguments
252    /// - `inner` - The underlying [`StructArray`] that contains the variant data.
253    ///
254    /// # Returns
255    /// - A new instance of `VariantArray`.
256    ///
257    /// # Errors:
258    /// - If the data type is not valid [`VariantType`] storage
259    /// - If `typed_value` contains a type that cannot be shredded
260    ///
261    /// # Requirements of the `StructArray`
262    ///
263    /// See [`VariantType`] for the required fields. `typed_value` can be any
264    /// primitive type or be a list, large_list, fixed_size_list, list_view or
265    /// struct. Fixed-size lists are normalized to variable-length lists on read.
266    ///
267    pub fn try_new(inner: &dyn Array) -> Result<Self> {
268        // Before canonicalizing, which would report a non-Variant struct's fields as illegal
269        // shredded types
270        VariantType.supports_data_type(inner.data_type())?;
271
272        // Canonicalize shredded typed_value fields (e.g. decimal narrowing)
273        let inner = canonicalize_shredded_types(inner)?;
274        let inner = inner.as_struct();
275        let metadata_col = inner
276            .column_by_name("metadata")
277            .expect("checked by VariantType");
278
279        let shredding_state = ShreddingState::try_from(inner)?;
280
281        // `try_from` synthesizes an all-null `value` when the input omits it. Rebuild the inner
282        // struct so `inner()` and write-back carry the column too.
283        if inner.column_by_name("value").is_none() {
284            return Ok(Self::from_parts(
285                metadata_col.clone(),
286                shredding_state.value_column().clone(),
287                shredding_state.typed_value_column().cloned(),
288                inner.nulls().cloned(),
289            ));
290        }
291
292        // Note these clones are cheap, they just bump the ref count
293        Ok(Self {
294            inner: inner.clone(),
295            metadata: metadata_col.clone(),
296            shredding_state,
297        })
298    }
299
300    /// Note: annotates `value` as nullable, which the spec only permits for shredded
301    /// variants. It is also needed by `variant_get`'s unshredded intermediates, whose
302    /// `value` column can contain unmasked nulls. Unshredded producers should use
303    /// [`Self::from_parts_unshredded`] instead.
304    pub(crate) fn from_parts(
305        metadata: ArrayRef,
306        value: ArrayRef,
307        typed_value: Option<ArrayRef>,
308        nulls: Option<NullBuffer>,
309    ) -> Self {
310        Self::from_parts_with_nullable_value(metadata, value, typed_value, nulls, true)
311    }
312
313    /// Construct an unshredded `VariantArray`, annotating `value` as non-nullable as the
314    /// spec requires when there is no `typed_value` column.
315    ///
316    /// # Panics
317    /// If `value` contains nulls not masked by `nulls`.
318    pub(crate) fn from_parts_unshredded(
319        metadata: ArrayRef,
320        value: ArrayRef,
321        nulls: Option<NullBuffer>,
322    ) -> Self {
323        Self::from_parts_with_nullable_value(metadata, value, None, nulls, false)
324    }
325
326    fn from_parts_with_nullable_value(
327        metadata: ArrayRef,
328        value: ArrayRef,
329        typed_value: Option<ArrayRef>,
330        nulls: Option<NullBuffer>,
331        value_nullable: bool,
332    ) -> Self {
333        let mut builder = StructArrayAssembler::new()
334            .with_field("metadata", metadata.clone(), false)
335            .with_field("value", value.clone(), value_nullable);
336        if let Some(typed_value) = typed_value.clone() {
337            builder = builder.with_field_ref(typed_value_field(&typed_value), typed_value);
338        }
339        if let Some(nulls) = nulls {
340            builder = builder.with_nulls(nulls);
341        }
342
343        Self {
344            inner: builder.build().unwrap(),
345            metadata,
346            shredding_state: ShreddingState::new(value, typed_value),
347        }
348    }
349
350    /// Returns a reference to the underlying [`StructArray`].
351    pub fn inner(&self) -> &StructArray {
352        &self.inner
353    }
354
355    /// Returns the inner [`StructArray`], consuming self
356    pub fn into_inner(self) -> StructArray {
357        self.inner
358    }
359
360    /// Return the shredding state of this `VariantArray`
361    pub fn shredding_state(&self) -> &ShreddingState {
362        &self.shredding_state
363    }
364
365    /// Return the [`Variant`] instance stored at the given row
366    ///
367    /// This is a convenience wrapper that calls [`VariantArray::try_value`] and unwraps the `Result`.
368    /// Use `try_value` if you need to handle conversion errors gracefully.
369    ///
370    /// # Panics
371    /// Panics if
372    /// * the index is out of bounds,
373    /// * the `metadata`/`value` bytes of the row are invalid, which includes reading a null row, or
374    /// * both `value` and `typed_value` are non-null for a non-struct `typed_value`.
375    pub fn value(&self, index: usize) -> Variant<'_, '_> {
376        self.try_value(index)
377            .unwrap_or_else(|err| panic!("VariantArray::value({index}) failed: {err}"))
378    }
379
380    /// Return the [`Variant`] instance stored at the given row
381    ///
382    /// Note: This method does not check for nulls and the value is arbitrary
383    /// (but still well-defined) if [`is_null`](Self::is_null) returns true for the index.
384    ///
385    /// # Errors
386    ///
387    /// Errors if
388    /// - the index is out of bounds
389    /// - the data in `typed_value` cannot be interpreted as a valid `Variant`
390    /// - both `value` and `typed_value` are non-null for a non-struct `typed_value`
391    ///
392    /// # Panics
393    ///
394    /// Panics if the unshredded `metadata`/`value` bytes fail basic validation, since those are
395    /// read with [`Variant::new`]. This includes reading a row that is null.
396    ///
397    /// If this is a shredded variant but has no value at the shredded location, it
398    /// will return [`Variant::Null`].
399    ///
400    ///
401    /// # Performance Note
402    ///
403    /// This is certainly not the most efficient way to access values in a
404    /// `VariantArray`, but it is useful for testing and debugging.
405    ///
406    /// Note: Does not do deep validation of the [`Variant`], so it is up to the
407    /// caller to ensure that the metadata and value were constructed correctly.
408    pub fn try_value(&self, index: usize) -> Result<Variant<'_, '_>> {
409        if self.len() <= index {
410            return Err(ArrowError::InvalidArgumentError(format!(
411                "Index {index} out of bounds for VariantArray of length {}",
412                self.len()
413            )));
414        }
415
416        let value = self.value_column();
417        match self.typed_value_column() {
418            // Always prefer typed_value, if available
419            Some(typed_value) if typed_value.is_valid(index) => {
420                if !matches!(typed_value.data_type(), DataType::Struct(_)) && value.is_valid(index) {
421                    // Only a partially shredded struct is allowed to have values for both columns
422                    return Err(ArrowError::InvalidArgumentError(
423                        "Invalid variant, conflicting value and typed_value".to_owned(),
424                    ));
425                }
426                typed_value_to_variant(typed_value, index)
427            }
428            // Otherwise fall back to value, if available
429            _ if value.is_valid(index) => variant_from_arrays_at(&self.metadata, value, index)
430                .ok_or_else(|| {
431                    ArrowError::InvalidArgumentError(format!(
432                        "metadata and value fields must be binary-like arrays, instead got {} and {}",
433                        self.metadata.data_type(),
434                        value.data_type()
435                    ))
436                }),
437            // It is technically invalid for both value and typed_value to be null,
438            // but the spec specifically requires readers to return Variant::Null in this case.
439            _ => Ok(Variant::Null),
440        }
441    }
442
443    /// Return a reference to the `metadata` column of the [`StructArray`]
444    pub fn metadata_column(&self) -> &ArrayRef {
445        &self.metadata
446    }
447
448    /// Return a reference to the `value` column of the [`StructArray`]
449    pub fn value_column(&self) -> &ArrayRef {
450        self.shredding_state.value_column()
451    }
452
453    /// Return a reference to the `typed_value` column of the [`StructArray`], if present
454    pub fn typed_value_column(&self) -> Option<&ArrayRef> {
455        self.shredding_state.typed_value_column()
456    }
457
458    /// Return a field to represent this VariantArray in a `Schema` with
459    /// a particular name
460    pub fn field(&self, name: impl Into<String>) -> Field {
461        Field::new(
462            name.into(),
463            self.data_type().clone(),
464            self.inner.is_nullable(),
465        )
466        .with_extension_type(VariantType)
467    }
468
469    /// Returns a new DataType representing this VariantArray's inner type
470    pub fn data_type(&self) -> &DataType {
471        self.inner.data_type()
472    }
473
474    pub fn slice(&self, offset: usize, length: usize) -> Self {
475        let inner = self.inner.slice(offset, length);
476        let metadata = self.metadata.slice(offset, length);
477        let shredding_state = self.shredding_state.slice(offset, length);
478        Self {
479            inner,
480            metadata,
481            shredding_state,
482        }
483    }
484
485    pub fn len(&self) -> usize {
486        self.inner.len()
487    }
488
489    pub fn is_empty(&self) -> bool {
490        self.inner.is_empty()
491    }
492
493    pub fn nulls(&self) -> Option<&NullBuffer> {
494        self.inner.nulls()
495    }
496
497    /// Is the element at index null?
498    pub fn is_null(&self, index: usize) -> bool {
499        self.nulls().is_some_and(|n| n.is_null(index))
500    }
501
502    /// Is the element at index valid (not null)?
503    pub fn is_valid(&self, index: usize) -> bool {
504        !self.is_null(index)
505    }
506
507    /// Returns an iterator over the values in this array
508    pub fn iter(&self) -> VariantArrayIter<'_> {
509        VariantArrayIter::new(self)
510    }
511}
512
513impl<'a> IntoIterator for &'a VariantArray {
514    type Item = Option<Variant<'a, 'a>>;
515    type IntoIter = VariantArrayIter<'a>;
516
517    fn into_iter(self) -> Self::IntoIter {
518        VariantArrayIter::new(self)
519    }
520}
521
522impl PartialEq for VariantArray {
523    fn eq(&self, other: &Self) -> bool {
524        self.inner == other.inner
525    }
526}
527
528impl From<VariantArray> for StructArray {
529    fn from(variant_array: VariantArray) -> Self {
530        variant_array.into_inner()
531    }
532}
533
534impl From<VariantArray> for ArrayRef {
535    fn from(variant_array: VariantArray) -> Self {
536        Arc::new(variant_array.into_inner())
537    }
538}
539
540impl<'m, 'v, V: Into<Variant<'m, 'v>>> FromIterator<Option<V>> for VariantArray {
541    fn from_iter<T: IntoIterator<Item = Option<V>>>(iter: T) -> Self {
542        let iter = iter.into_iter().map(|value| value.map(Into::into));
543
544        let mut b = VariantArrayBuilder::new(iter.size_hint().0);
545        b.extend(iter);
546        b.build()
547    }
548}
549
550impl<'m, 'v> FromIterator<Variant<'m, 'v>> for VariantArray {
551    fn from_iter<T: IntoIterator<Item = Variant<'m, 'v>>>(iter: T) -> Self {
552        Self::from_iter(iter.into_iter().map(Some))
553    }
554}
555
556/// An iterator over [`VariantArray`]
557///
558/// This iterator returns `Option<Option<Variant<'a, 'a>>>` where:
559/// - `None` indicates the end of iteration
560/// - `Some(None)` indicates a null value at this position
561/// - `Some(Some(variant))` indicates a valid variant value
562///
563/// # Example
564///
565/// ```
566/// # use parquet_variant::Variant;
567/// # use parquet_variant_compute::VariantArrayBuilder;
568/// let mut builder = VariantArrayBuilder::new(10);
569/// builder.append_variant(Variant::from(42));
570/// builder.append_null();
571/// builder.append_variant(Variant::from("hello"));
572/// let array = builder.build();
573///
574/// let values = array.iter().collect::<Vec<_>>();
575/// assert_eq!(values.len(), 3);
576/// assert_eq!(values[0], Some(Variant::from(42)));
577/// assert_eq!(values[1], None);
578/// assert_eq!(values[2], Some(Variant::from("hello")));
579/// ```
580#[derive(Debug)]
581pub struct VariantArrayIter<'a> {
582    array: &'a VariantArray,
583    head_i: usize,
584    tail_i: usize,
585}
586
587impl<'a> VariantArrayIter<'a> {
588    /// Creates a new iterator over the given [`VariantArray`]
589    pub fn new(array: &'a VariantArray) -> Self {
590        Self {
591            array,
592            head_i: 0,
593            tail_i: array.len(),
594        }
595    }
596
597    fn value_opt(&self, i: usize) -> Option<Variant<'a, 'a>> {
598        self.array.is_valid(i).then(|| self.array.value(i))
599    }
600}
601
602impl<'a> Iterator for VariantArrayIter<'a> {
603    type Item = Option<Variant<'a, 'a>>;
604
605    #[inline]
606    fn next(&mut self) -> Option<Self::Item> {
607        if self.head_i == self.tail_i {
608            return None;
609        }
610
611        let out = self.value_opt(self.head_i);
612
613        self.head_i += 1;
614
615        Some(out)
616    }
617
618    fn size_hint(&self) -> (usize, Option<usize>) {
619        let remainder = self.tail_i - self.head_i;
620
621        (remainder, Some(remainder))
622    }
623}
624
625impl DoubleEndedIterator for VariantArrayIter<'_> {
626    fn next_back(&mut self) -> Option<Self::Item> {
627        if self.head_i == self.tail_i {
628            return None;
629        }
630
631        self.tail_i -= 1;
632
633        Some(self.value_opt(self.tail_i))
634    }
635}
636
637impl ExactSizeIterator for VariantArrayIter<'_> {}
638
639/// One shredded field of a partially or perfectly shredded variant. For example, suppose the
640/// shredding schema for variant `v` treats it as an object with a single field `a`, where `a` is
641/// itself a struct with the single field `b` of type INT. Then the physical layout of the column
642/// is:
643///
644/// ```text
645/// v: VARIANT {
646///     metadata: BINARY,
647///     value: BINARY,
648///     typed_value: STRUCT {
649///         a: SHREDDED_VARIANT_FIELD {
650///             value: BINARY,
651///             typed_value: STRUCT {
652///                 a: SHREDDED_VARIANT_FIELD {
653///                     value: BINARY,
654///                     typed_value: INT,
655///                 },
656///             },
657///         },
658///     },
659/// }
660/// ```
661///
662/// In the above, each row of `v.value` is either a variant value (shredding failed, `v` was not an
663/// object at all) or a variant object (partial shredding, `v` was an object but included unexpected
664/// fields other than `a`), or is NULL (perfect shredding, `v` was an object containing only the
665/// single expected field `a`).
666///
667/// A similar story unfolds for each `v.typed_value.a.value` -- a variant value if shredding failed
668/// (`v:a` was not an object at all), or a variant object (`v:a` was an object with unexpected
669/// additional fields), or NULL (`v:a` was an object containing only the single expected field `b`).
670///
671/// Finally, `v.typed_value.a.typed_value.b.value` is either NULL (`v:a.b` was an integer) or else a
672/// variant value (which could be `Variant::Null`).
673#[derive(Debug)]
674pub struct ShreddedVariantFieldArray {
675    /// Reference to the underlying StructArray
676    inner: StructArray,
677    shredding_state: ShreddingState,
678}
679
680impl ShreddedVariantFieldArray {
681    /// Creates a new `ShreddedVariantFieldArray` from a [`StructArray`].
682    ///
683    /// # Arguments
684    /// - `inner` - The underlying [`StructArray`] that contains the variant data.
685    ///
686    /// # Returns
687    /// - A new instance of `ShreddedVariantFieldArray`.
688    ///
689    /// # Errors:
690    /// - If the `StructArray` does not contain the required fields
691    ///
692    /// # Requirements of the `StructArray`
693    ///
694    /// 1. A required field named `value` that is binary, large_binary, or
695    ///    binary_view
696    ///
697    /// 2. An optional field named `typed_value` which can be any primitive type
698    ///    or be a list, large_list, list_view or struct
699    ///
700    pub fn try_new(inner: &dyn Array) -> Result<Self> {
701        let Some(inner_struct) = inner.as_struct_opt() else {
702            return Err(ArrowError::InvalidArgumentError(
703                "Invalid ShreddedVariantFieldArray: requires StructArray as input".to_string(),
704            ));
705        };
706
707        let shredding_state = ShreddingState::try_from(inner_struct)?;
708
709        // `try_from` synthesizes an all-null `value` when the input omits it. Rebuild the inner
710        // struct so `inner()` and write-back carry the column too (see `VariantArray::try_new`).
711        if inner_struct.column_by_name("value").is_none() {
712            return Ok(Self::from_parts(
713                shredding_state.value_column().clone(),
714                shredding_state.typed_value_column().cloned(),
715                inner_struct.nulls().cloned(),
716            ));
717        }
718
719        // Note this clone is cheap, it just bumps the ref count
720        Ok(Self {
721            inner: inner_struct.clone(),
722            shredding_state,
723        })
724    }
725
726    /// Return the shredding state of this `VariantArray`
727    pub fn shredding_state(&self) -> &ShreddingState {
728        &self.shredding_state
729    }
730
731    /// Return a reference to the `value` column of the [`StructArray`]
732    pub fn value_column(&self) -> &ArrayRef {
733        self.shredding_state.value_column()
734    }
735
736    /// Return a reference to the `typed_value` column of the [`StructArray`], if present
737    pub fn typed_value_column(&self) -> Option<&ArrayRef> {
738        self.shredding_state.typed_value_column()
739    }
740
741    /// Returns a reference to the underlying [`StructArray`].
742    pub fn inner(&self) -> &StructArray {
743        &self.inner
744    }
745
746    pub(crate) fn from_parts(
747        value: ArrayRef,
748        typed_value: Option<ArrayRef>,
749        nulls: Option<NullBuffer>,
750    ) -> Self {
751        let mut builder = StructArrayAssembler::new().with_field("value", value.clone(), true);
752        if let Some(typed_value) = typed_value.clone() {
753            builder = builder.with_field_ref(typed_value_field(&typed_value), typed_value);
754        }
755        if let Some(nulls) = nulls {
756            builder = builder.with_nulls(nulls);
757        }
758
759        Self {
760            inner: builder.build().unwrap(),
761            shredding_state: ShreddingState::new(value, typed_value),
762        }
763    }
764
765    /// Returns the inner [`StructArray`], consuming self
766    pub fn into_inner(self) -> StructArray {
767        self.inner
768    }
769
770    pub fn data_type(&self) -> &DataType {
771        self.inner.data_type()
772    }
773
774    pub fn len(&self) -> usize {
775        self.inner.len()
776    }
777
778    pub fn is_empty(&self) -> bool {
779        self.inner.is_empty()
780    }
781
782    pub fn offset(&self) -> usize {
783        self.inner.offset()
784    }
785
786    pub fn nulls(&self) -> Option<&NullBuffer> {
787        // According to the shredding spec, ShreddedVariantFieldArray should be
788        // physically non-nullable - SQL NULL is inferred by both value and
789        // typed_value being physically NULL
790        None
791    }
792    /// Is the element at index null?
793    pub fn is_null(&self, index: usize) -> bool {
794        self.nulls().is_some_and(|n| n.is_null(index))
795    }
796
797    /// Is the element at index valid (not null)?
798    pub fn is_valid(&self, index: usize) -> bool {
799        !self.is_null(index)
800    }
801}
802
803impl From<ShreddedVariantFieldArray> for ArrayRef {
804    fn from(array: ShreddedVariantFieldArray) -> Self {
805        Arc::new(array.into_inner())
806    }
807}
808
809impl From<ShreddedVariantFieldArray> for StructArray {
810    fn from(array: ShreddedVariantFieldArray) -> Self {
811        array.into_inner()
812    }
813}
814
815/// Represents the shredding state of a [`VariantArray`]
816///
817/// [`VariantArray`]s can be shredded according to the [Parquet Variant
818/// Shredding Spec]. Shredding means that the actual value is stored in a typed
819/// `typed_field` instead of the generic `value` field.
820///
821/// The `value` column is always present (the spec requires writers to emit
822/// it); `typed_value` is optional. Values in the two columns must be
823/// interpreted according to the following table (see [Parquet Variant
824/// Shredding Spec] for more details):
825///
826/// | value    | typed_value  | Meaning |
827/// |----------|--------------|---------|
828/// | NULL     | NULL         | The value is missing; only valid for shredded object fields |
829/// | non-NULL | NULL         | The value is present and may be any type, including [`Variant::Null`] |
830/// | NULL     | non-NULL     | The value is present and is the shredded type |
831/// | non-NULL | non-NULL     | The value is present and is a partially shredded object |
832///
833///
834/// Applying the above rules to entire columns, we obtain the following:
835///
836/// | value  | typed_value  | Meaning |
837/// |--------|-------------|---------|
838/// | exists | --          | **Unshredded**: If present, the value may be any type, including [`Variant::Null`]
839/// | exists | exists      | **Shredded**: perfectly if `value` is all-null, otherwise imperfectly |
840///
841/// Note the spec requires the `value` column to always be present in the
842/// schema; structs without one are rejected
843/// (see <https://github.com/apache/arrow-rs/issues/10306>).
844///
845/// NOTE: Partial shredding is a row-wise situation that can arise under imperfect shredding (a
846/// column-wise situation): When both columns exist (imperfect shredding) and the typed_value column
847/// is a struct, then both columns can be non-NULL for the same row if value is a variant object
848/// (partial shredding).
849///
850/// [Parquet Variant Shredding Spec]: https://github.com/apache/parquet-format/blob/master/VariantShredding.md#value-shredding
851#[derive(Debug, Clone)]
852pub struct ShreddingState {
853    value: ArrayRef,
854    typed_value: Option<ArrayRef>,
855}
856
857impl ShreddingState {
858    /// Create a new `ShreddingState` from the given `value` and `typed_value` fields
859    ///
860    /// Note you can create a `ShreddingState` from a &[`StructArray`] using
861    /// `ShreddingState::try_from(&struct_array)`, for example:
862    ///
863    /// ```no_run
864    /// # use arrow::array::StructArray;
865    /// # use parquet_variant_compute::ShreddingState;
866    /// # fn get_struct_array() -> StructArray {
867    /// #   unimplemented!()
868    /// # }
869    /// let struct_array: StructArray = get_struct_array();
870    /// let shredding_state = ShreddingState::try_from(&struct_array).unwrap();
871    /// ```
872    pub fn new(value: ArrayRef, typed_value: Option<ArrayRef>) -> Self {
873        Self { value, typed_value }
874    }
875
876    /// Return a reference to the `value` column
877    pub fn value_column(&self) -> &ArrayRef {
878        &self.value
879    }
880
881    /// Return a reference to the `typed_value` column, if present
882    pub fn typed_value_column(&self) -> Option<&ArrayRef> {
883        self.typed_value.as_ref()
884    }
885
886    /// Slice all the underlying arrays
887    pub fn slice(&self, offset: usize, length: usize) -> Self {
888        Self {
889            value: self.value.slice(offset, length),
890            typed_value: self.typed_value.as_ref().map(|tv| tv.slice(offset, length)),
891        }
892    }
893}
894
895impl TryFrom<&StructArray> for ShreddingState {
896    type Error = ArrowError;
897
898    fn try_from(inner_struct: &StructArray) -> Result<Self> {
899        let typed_value = inner_struct.column_by_name("typed_value").cloned();
900        let value = match inner_struct.column_by_name("value") {
901            Some(value) => {
902                validate_binary_array(value.as_ref(), "value")?;
903                value.clone()
904            }
905            // Lenient read: a shredded group may omit the spec-required `value`. Synthesize an
906            // all-null one so the model always has a `value`.
907            None if typed_value.is_some() => all_null_value_column(inner_struct.len()),
908            None => {
909                return Err(ArrowError::InvalidArgumentError(
910                    "Invalid VariantArray: StructArray must contain a 'value' field".to_string(),
911                ));
912            }
913        };
914        Ok(ShreddingState::new(value, typed_value))
915    }
916}
917
918/// Build the `typed_value` [`FieldRef`] for a shredded column.
919///
920/// The Variant spec maps `FixedSizeBinary(16)` exclusively to UUID, so any
921/// shredded column of that type must carry the canonical [`UuidExtension`]
922/// extension metadata on its field.
923fn typed_value_field(array: &ArrayRef) -> FieldRef {
924    let mut field = Field::new("typed_value", array.data_type().clone(), true);
925    if matches!(array.data_type(), DataType::FixedSizeBinary(16)) {
926        field = field.with_extension_type(UuidExtension);
927    }
928    Arc::new(field)
929}
930
931/// returns the non-null element at index as a Variant
932fn typed_value_to_variant(typed_value: &ArrayRef, index: usize) -> Result<Variant<'_, '_>> {
933    let data_type = typed_value.data_type();
934    match data_type {
935        DataType::Null => Ok(Variant::Null),
936        DataType::Boolean => {
937            let boolean_array = typed_value.as_boolean();
938            let value = boolean_array.value(index);
939            Ok(Variant::from(value))
940        }
941        // 16-byte FixedSizeBinary always corresponds to a UUID; all other sizes are illegal.
942        DataType::FixedSizeBinary(16) => {
943            let array = typed_value.as_fixed_size_binary();
944            let value = array.value(index);
945            Ok(Uuid::from_slice(value).unwrap().into()) // unwrap is safe: slice is always 16 bytes
946        }
947        DataType::Binary => {
948            let array = typed_value.as_binary::<i32>();
949            let value = array.value(index);
950            Ok(Variant::from(value))
951        }
952        DataType::LargeBinary => {
953            let array = typed_value.as_binary::<i64>();
954            let value = array.value(index);
955            Ok(Variant::from(value))
956        }
957        DataType::BinaryView => {
958            let array = typed_value.as_binary_view();
959            let value = array.value(index);
960            Ok(Variant::from(value))
961        }
962        DataType::Utf8 => {
963            let array = typed_value.as_string::<i32>();
964            let value = array.value(index);
965            Ok(Variant::from(value))
966        }
967        DataType::LargeUtf8 => {
968            let array = typed_value.as_string::<i64>();
969            let value = array.value(index);
970            Ok(Variant::from(value))
971        }
972        DataType::Utf8View => {
973            let array = typed_value.as_string_view();
974            let value = array.value(index);
975            Ok(Variant::from(value))
976        }
977        DataType::Int8 => {
978            primitive_conversion_single_value!(Int8Type, typed_value, index)
979        }
980        DataType::Int16 => {
981            primitive_conversion_single_value!(Int16Type, typed_value, index)
982        }
983        DataType::Int32 => {
984            primitive_conversion_single_value!(Int32Type, typed_value, index)
985        }
986        DataType::Int64 => {
987            primitive_conversion_single_value!(Int64Type, typed_value, index)
988        }
989        DataType::Float16 => {
990            primitive_conversion_single_value!(Float16Type, typed_value, index)
991        }
992        DataType::Float32 => {
993            primitive_conversion_single_value!(Float32Type, typed_value, index)
994        }
995        DataType::Float64 => {
996            primitive_conversion_single_value!(Float64Type, typed_value, index)
997        }
998        DataType::Decimal32(_, s) => {
999            generic_conversion_single_value_with_result!(
1000                Decimal32Type,
1001                as_primitive,
1002                |v| VariantDecimal4::try_new(v, *s as u8),
1003                typed_value,
1004                index
1005            )
1006        }
1007        DataType::Decimal64(_, s) => {
1008            generic_conversion_single_value_with_result!(
1009                Decimal64Type,
1010                as_primitive,
1011                |v| VariantDecimal8::try_new(v, *s as u8),
1012                typed_value,
1013                index
1014            )
1015        }
1016        DataType::Decimal128(_, s) => {
1017            generic_conversion_single_value_with_result!(
1018                Decimal128Type,
1019                as_primitive,
1020                |v| VariantDecimal16::try_new(v, *s as u8),
1021                typed_value,
1022                index
1023            )
1024        }
1025        DataType::Date32 => {
1026            generic_conversion_single_value!(
1027                Date32Type,
1028                as_primitive,
1029                |v| Date32Type::to_naive_date_opt(v).unwrap(),
1030                typed_value,
1031                index
1032            )
1033        }
1034        DataType::Time64(TimeUnit::Microsecond) => {
1035            generic_conversion_single_value_with_result!(
1036                Time64MicrosecondType,
1037                as_primitive,
1038                |v| NaiveTime::from_num_seconds_from_midnight_opt(
1039                    (v / 1_000_000) as u32,
1040                    (v % 1_000_000) as u32 * 1000
1041                )
1042                .ok_or_else(|| format!("Invalid microsecond from midnight: {v}")),
1043                typed_value,
1044                index
1045            )
1046        }
1047        DataType::Timestamp(TimeUnit::Microsecond, Some(_)) => {
1048            generic_conversion_single_value!(
1049                TimestampMicrosecondType,
1050                as_primitive,
1051                |v| DateTime::from_timestamp_micros(v).unwrap(),
1052                typed_value,
1053                index
1054            )
1055        }
1056        DataType::Timestamp(TimeUnit::Microsecond, None) => {
1057            generic_conversion_single_value!(
1058                TimestampMicrosecondType,
1059                as_primitive,
1060                |v| DateTime::from_timestamp_micros(v).unwrap().naive_utc(),
1061                typed_value,
1062                index
1063            )
1064        }
1065        DataType::Timestamp(TimeUnit::Nanosecond, Some(_)) => {
1066            generic_conversion_single_value!(
1067                TimestampNanosecondType,
1068                as_primitive,
1069                DateTime::from_timestamp_nanos,
1070                typed_value,
1071                index
1072            )
1073        }
1074        DataType::Timestamp(TimeUnit::Nanosecond, None) => {
1075            generic_conversion_single_value!(
1076                TimestampNanosecondType,
1077                as_primitive,
1078                |v| DateTime::from_timestamp_nanos(v).naive_utc(),
1079                typed_value,
1080                index
1081            )
1082        }
1083        // todo other types here (note this is very similar to cast_to_variant.rs)
1084        // so it would be great to figure out how to share this code
1085        //
1086        // Composite shredded values may require combining `value` and
1087        // `typed_value` and allocating new encoded bytes. `try_value` returns
1088        // borrowed Variant, so callers must unshred the array first.
1089        _ => Err(ArrowError::NotYetImplemented(format!(
1090            "VariantArray::try_value cannot materialize typed_value of type {} \
1091             as a borrowed Variant; call unshred_variant first",
1092            typed_value.data_type()
1093        ))),
1094    }
1095}
1096
1097/// Canonicalize shredded typed_value fields (e.g. decimal narrowing) and
1098/// verify that all data types in the struct are legal for a variant array.
1099fn canonicalize_shredded_types(array: &dyn Array) -> Result<ArrayRef> {
1100    let new_type = canonicalize_and_verify_data_type_impl(array.data_type(), true)?;
1101    if let Cow::Borrowed(_) = new_type
1102        && let Some(array) = array.as_struct_opt()
1103    {
1104        return Ok(Arc::new(array.clone())); // bypass the unnecessary cast
1105    }
1106    cast(array, new_type.as_ref())
1107}
1108
1109/// Recursively visits a data type, ensuring that it only contains data types that can legally
1110/// appear in a (possibly shredded) variant array. It also narrows decimal types to the smallest
1111/// valid precision (e.g. Decimal128 -> Decimal32 when the precision fits).
1112fn canonicalize_and_verify_data_type(data_type: &DataType) -> Result<Cow<'_, DataType>> {
1113    canonicalize_and_verify_data_type_impl(data_type, false)
1114}
1115
1116fn canonicalize_and_verify_data_type_impl(
1117    data_type: &DataType,
1118    skip_top_level_metadata: bool,
1119) -> Result<Cow<'_, DataType>> {
1120    use DataType::*;
1121
1122    // helper macros
1123    macro_rules! fail {
1124        () => {
1125            return Err(ArrowError::InvalidArgumentError(format!(
1126                "Illegal shredded value type: {data_type}"
1127            )))
1128        };
1129    }
1130    macro_rules! borrow {
1131        () => {
1132            Cow::Borrowed(data_type)
1133        };
1134    }
1135
1136    let new_data_type = match data_type {
1137        // Primitive arrow types that have a direct variant counterpart are allowed
1138        Null | Boolean => borrow!(),
1139        Int8 | Int16 | Int32 | Int64 | Float32 | Float64 => borrow!(),
1140
1141        // Unsigned integers and half-float are not allowed
1142        UInt8 | UInt16 | UInt32 | UInt64 | Float16 => fail!(),
1143
1144        // Most decimal types are allowed, with restrictions on precision and scale
1145        //
1146        // NOTE: arrow-parquet reads widens 32- and 64-bit decimals to 128-bit, but the variant spec
1147        // requires using the narrowest decimal type for a given precision. Fix those up first.
1148        Decimal64(p, s) | Decimal128(p, s)
1149            if VariantDecimal4::is_valid_precision_and_scale(p, s) =>
1150        {
1151            Cow::Owned(Decimal32(*p, *s))
1152        }
1153        Decimal128(p, s) if VariantDecimal8::is_valid_precision_and_scale(p, s) => {
1154            Cow::Owned(Decimal64(*p, *s))
1155        }
1156        Decimal32(p, s) if VariantDecimal4::is_valid_precision_and_scale(p, s) => borrow!(),
1157        Decimal64(p, s) if VariantDecimal8::is_valid_precision_and_scale(p, s) => borrow!(),
1158        Decimal128(p, s) if VariantDecimal16::is_valid_precision_and_scale(p, s) => borrow!(),
1159        Decimal32(..) | Decimal64(..) | Decimal128(..) | Decimal256(..) => fail!(),
1160
1161        // Only micro and nano timestamps are allowed
1162        Timestamp(TimeUnit::Microsecond | TimeUnit::Nanosecond, _) => borrow!(),
1163        Timestamp(TimeUnit::Millisecond | TimeUnit::Second, _) => fail!(),
1164
1165        // Only 32-bit dates and 64-bit microsecond time are allowed.
1166        Date32 | Time64(TimeUnit::Microsecond) => borrow!(),
1167        Date64 | Time32(_) | Time64(_) | Duration(_) | Interval(_) => fail!(),
1168
1169        // Binary, string, and their view counterparts are allowed.
1170        Binary | LargeBinary | BinaryView | Utf8 | LargeUtf8 | Utf8View => borrow!(),
1171
1172        // UUID maps to 16-byte fixed-size binary; no other width is allowed
1173        FixedSizeBinary(16) => borrow!(),
1174        FixedSizeBinary(_) => fail!(),
1175
1176        // FixedSizeList is an Arrow-specific distinction. Normalize it to List on read so
1177        // Variant data written by older arrow-rs versions remains readable without treating
1178        // FixedSizeList as a supported shredding target.
1179        FixedSizeList(field, _) => match canonicalize_and_verify_field(field)? {
1180            Cow::Borrowed(_) => Cow::Owned(DataType::List(field.clone())),
1181            Cow::Owned(new_field) => Cow::Owned(DataType::List(new_field)),
1182        },
1183
1184        // List-like containers and struct are allowed, maps and unions are not
1185        List(field) => match canonicalize_and_verify_field(field)? {
1186            Cow::Borrowed(_) => borrow!(),
1187            Cow::Owned(new_field) => Cow::Owned(DataType::List(new_field)),
1188        },
1189        LargeList(field) => match canonicalize_and_verify_field(field)? {
1190            Cow::Borrowed(_) => borrow!(),
1191            Cow::Owned(new_field) => Cow::Owned(DataType::LargeList(new_field)),
1192        },
1193        ListView(field) => match canonicalize_and_verify_field(field)? {
1194            Cow::Borrowed(_) => borrow!(),
1195            Cow::Owned(new_field) => Cow::Owned(DataType::ListView(new_field)),
1196        },
1197        LargeListView(field) => match canonicalize_and_verify_field(field)? {
1198            Cow::Borrowed(_) => borrow!(),
1199            Cow::Owned(new_field) => Cow::Owned(DataType::LargeListView(new_field)),
1200        },
1201        // Struct is used by the internal layout, and can also represent a shredded variant object.
1202        Struct(fields) => {
1203            // Avoid allocation unless at least one field changes, to avoid unnecessary deep cloning
1204            // of the data type. Even if some fields change, the others are shallow arc clones.
1205            let mut new_fields = std::collections::HashMap::new();
1206            for (i, field) in fields.iter().enumerate() {
1207                if skip_top_level_metadata && field.name() == "metadata" {
1208                    continue;
1209                }
1210                if let Cow::Owned(new_field) = canonicalize_and_verify_field(field)? {
1211                    new_fields.insert(i, new_field);
1212                }
1213            }
1214
1215            if new_fields.is_empty() {
1216                borrow!()
1217            } else {
1218                let new_fields = fields
1219                    .iter()
1220                    .enumerate()
1221                    .map(|(i, field)| new_fields.remove(&i).unwrap_or_else(|| field.clone()));
1222                Cow::Owned(DataType::Struct(new_fields.collect()))
1223            }
1224        }
1225        Map(..) | Union(..) => fail!(),
1226
1227        // We can _possibly_ support (some of) these some day?
1228        Dictionary(..) | RunEndEncoded(..) => fail!(),
1229    };
1230    Ok(new_data_type)
1231}
1232
1233fn canonicalize_and_verify_field(field: &Arc<Field>) -> Result<Cow<'_, Arc<Field>>> {
1234    let new_data_type = canonicalize_and_verify_data_type(field.data_type())?;
1235
1236    // A shredded FixedSizeBinary(16) column is always a UUID. Tag it with the UUID extension type
1237    // on read, as a safety net against writers that emit the column without the extension metadata.
1238    // Canonicalization never rewrites FixedSizeBinary(16), so the type is already correct here.
1239    if matches!(new_data_type.as_ref(), DataType::FixedSizeBinary(16))
1240        && !field.has_valid_extension_type::<UuidExtension>()
1241    {
1242        let new_field = field.as_ref().clone().with_extension_type(UuidExtension);
1243        return Ok(Cow::Owned(Arc::new(new_field)));
1244    }
1245
1246    let Cow::Owned(new_data_type) = new_data_type else {
1247        return Ok(Cow::Borrowed(field));
1248    };
1249    let new_field = field.as_ref().clone().with_data_type(new_data_type);
1250    Ok(Cow::Owned(Arc::new(new_field)))
1251}
1252
1253/// Test-only constructors for perfectly shredded arrays, where every value lives in
1254/// `typed_value` and the required `value` column is all-null.
1255#[cfg(test)]
1256impl VariantArray {
1257    pub(crate) fn perfectly_shredded(
1258        metadata: ArrayRef,
1259        typed_value: ArrayRef,
1260        nulls: Option<NullBuffer>,
1261    ) -> Self {
1262        let value = all_null_value_column(typed_value.len());
1263        Self::from_parts(metadata, value, Some(typed_value), nulls)
1264    }
1265}
1266
1267#[cfg(test)]
1268impl ShreddedVariantFieldArray {
1269    pub(crate) fn perfectly_shredded(typed_value: ArrayRef) -> Self {
1270        let value = all_null_value_column(typed_value.len());
1271        Self::from_parts(value, Some(typed_value), None)
1272    }
1273}
1274
1275#[cfg(test)]
1276mod test {
1277    use crate::{GetOptions, VariantArrayBuilder, json_to_variant, variant_get, variant_to_json};
1278    use std::str::FromStr;
1279
1280    use super::*;
1281    use arrow::array::{
1282        BinaryArray, BinaryDictionaryBuilder, BinaryRunBuilder, BinaryViewArray, Decimal32Array,
1283        Decimal64Array, Decimal128Array, FixedSizeBinaryArray, FixedSizeListArray, Int8Array,
1284        Int64Array, LargeBinaryArray, LargeListArray, LargeListViewArray, ListArray, ListViewArray,
1285        StringArray, Time64MicrosecondArray, UInt8Array,
1286    };
1287    use arrow::buffer::{OffsetBuffer, ScalarBuffer};
1288    use arrow_schema::{Field, Fields};
1289    use parquet_variant::{EMPTY_VARIANT_METADATA_BYTES, ShortString};
1290
1291    #[test]
1292    fn invalid_storage_checked_before_canonicalizing() {
1293        // `UInt8` is also an illegal shredded type, but the storage error must win
1294        let array = StructArrayAssembler::new()
1295            .with_field("metadata", make_binary_view_array(), false)
1296            .with_field("value", Arc::new(UInt8Array::from(vec![1])), true)
1297            .build()
1298            .unwrap();
1299        let err = VariantArray::try_new(&array).unwrap_err();
1300        assert_eq!(
1301            err.to_string(),
1302            "Invalid argument error: VariantType 'value' field must be Binary, LargeBinary, or BinaryView, got UInt8"
1303        );
1304    }
1305
1306    #[test]
1307    fn read_missing_value_column() {
1308        // With `typed_value` present, a missing `value` is read leniently: an all-null `value` is
1309        // synthesized and normalized into the inner struct (so a write-back emits it), and values
1310        // still decode from `typed_value`.
1311        let typed_value = Arc::new(Int64Array::from(vec![Some(1), None, Some(3)])) as ArrayRef;
1312        let metadata =
1313            BinaryViewArray::from_iter_values(std::iter::repeat_n(EMPTY_VARIANT_METADATA_BYTES, 3));
1314        let struct_array = StructArrayAssembler::new()
1315            .with_field("metadata", Arc::new(metadata), false)
1316            .with_field("typed_value", typed_value, true)
1317            .build()
1318            .unwrap();
1319        assert!(struct_array.column_by_name("value").is_none());
1320
1321        let variant_array = VariantArray::try_new(&struct_array).unwrap();
1322        assert_eq!(variant_array.value_column().len(), 3);
1323        assert_eq!(variant_array.value_column().null_count(), 3);
1324        assert!(variant_array.inner().column_by_name("value").is_some());
1325        assert!(variant_array.typed_value_column().is_some());
1326        assert_eq!(variant_array.value(0), Variant::from(1i64));
1327        assert_eq!(variant_array.value(1), Variant::Null);
1328        assert_eq!(variant_array.value(2), Variant::from(3i64));
1329    }
1330
1331    #[test]
1332    fn encoded_metadata_supports_nulls_slices_and_variant_get() {
1333        let json: ArrayRef = Arc::new(StringArray::from(vec![
1334            Some(r#"{"a":0}"#),
1335            Some(r#"{"a":1}"#),
1336            None,
1337            Some(r#"{"b":3}"#),
1338            Some(r#"{"b":4}"#),
1339        ]));
1340        let baseline = json_to_variant(&json).unwrap();
1341        let metadata = baseline.metadata_column().as_binary_view();
1342        let metadata_a = metadata.value(0);
1343        let metadata_b = metadata.value(3);
1344
1345        let logical_metadata = [
1346            Some(metadata_a),
1347            Some(metadata_a),
1348            None,
1349            Some(metadata_b),
1350            Some(metadata_b),
1351        ];
1352
1353        let mut dictionary = BinaryDictionaryBuilder::<Int8Type>::new();
1354        dictionary.extend(logical_metadata);
1355        let dictionary: ArrayRef = Arc::new(dictionary.finish());
1356
1357        let mut ree = BinaryRunBuilder::<Int16Type>::new();
1358        ree.extend(logical_metadata);
1359        let run_end_encoded: ArrayRef = Arc::new(ree.finish());
1360
1361        for metadata in [dictionary, run_end_encoded] {
1362            assert_eq!(binary_array_value(metadata.as_ref(), 2), None);
1363            let fields = Fields::from(vec![
1364                Field::new("metadata", metadata.data_type().clone(), false),
1365                Field::new("value", baseline.value_column().data_type().clone(), false),
1366            ]);
1367            let input = StructArray::try_new(
1368                fields,
1369                vec![metadata, baseline.value_column().clone()],
1370                baseline.nulls().cloned(),
1371            )
1372            .unwrap()
1373            .slice(1, 3);
1374
1375            let variant = VariantArray::try_new(&input).unwrap();
1376            assert_eq!(variant.value(0), baseline.value(1));
1377            assert!(variant.is_null(1));
1378            assert_eq!(variant.value(2), baseline.value(3));
1379
1380            let input: ArrayRef = Arc::new(input);
1381            let options = GetOptions::new_with_path("b".try_into().unwrap())
1382                .with_as_type(Some(Arc::new(Field::new("b", DataType::Int8, true))));
1383            let result = variant_get(&input, options).unwrap();
1384            assert_eq!(
1385                result.as_primitive::<Int8Type>(),
1386                &Int8Array::from(vec![None, None, Some(3)])
1387            );
1388            assert_eq!(
1389                variant_to_json(&input).unwrap(),
1390                StringArray::from(vec![Some(r#"{"a":1}"#), None, Some(r#"{"b":3}"#)])
1391            );
1392        }
1393    }
1394
1395    fn make_binary_view_array() -> ArrayRef {
1396        Arc::new(BinaryViewArray::from(vec![b"test" as &[u8]]))
1397    }
1398
1399    fn make_variant_struct_with_typed_value(typed_value: ArrayRef) -> StructArray {
1400        let metadata = BinaryViewArray::from_iter_values(std::iter::repeat_n(
1401            EMPTY_VARIANT_METADATA_BYTES,
1402            typed_value.len(),
1403        ));
1404        let value = new_null_array(&DataType::BinaryView, typed_value.len());
1405        StructArrayAssembler::new()
1406            .with_field("metadata", Arc::new(metadata), false)
1407            .with_field("value", value, true)
1408            .with_field("typed_value", typed_value, true)
1409            .build()
1410            .unwrap()
1411    }
1412
1413    #[test]
1414    fn try_new_tags_untagged_uuid_on_read() {
1415        // Simulate a foreign writer that shredded a UUID column as bare FixedSizeBinary(16),
1416        // omitting the UUID extension type.
1417        let typed_value = FixedSizeBinaryArray::try_from_iter(std::iter::repeat_n([0u8; 16], 2));
1418        let input = make_variant_struct_with_typed_value(Arc::new(typed_value.unwrap()));
1419
1420        // try_new canonicalizes on the read path and attaches the extension.
1421        let variant_array = VariantArray::try_new(&input).unwrap();
1422        let typed_value = variant_array.inner().field_by_name("typed_value").unwrap();
1423        assert_eq!(typed_value.data_type(), &DataType::FixedSizeBinary(16));
1424        assert!(typed_value.has_valid_extension_type::<UuidExtension>());
1425    }
1426
1427    #[test]
1428    fn try_new_tags_untagged_nested_uuid_on_read() {
1429        // A shredded object { id: { typed_value: FixedSizeBinary(16) } } whose inner UUID leaf
1430        // carries no extension type; canonicalization must reach it recursively.
1431        let leaf = FixedSizeBinaryArray::try_from_iter(std::iter::repeat_n([0u8; 16], 1)).unwrap();
1432        let inner = StructArrayAssembler::new()
1433            .with_field("typed_value", Arc::new(leaf), true)
1434            .build()
1435            .unwrap();
1436        let object = StructArrayAssembler::new()
1437            .with_field("id", Arc::new(inner), false)
1438            .build()
1439            .unwrap();
1440        let input = make_variant_struct_with_typed_value(Arc::new(object));
1441
1442        // typed_value (struct) -> id (struct) -> typed_value (the FixedSizeBinary(16) UUID leaf).
1443        let variant_array = VariantArray::try_new(&input).unwrap();
1444        let object = variant_array.typed_value_column().unwrap().as_struct();
1445        let id = object.column_by_name("id").unwrap().as_struct();
1446        let uuid_leaf = id.field_by_name("typed_value").unwrap();
1447        assert!(uuid_leaf.has_valid_extension_type::<UuidExtension>());
1448    }
1449
1450    #[test]
1451    fn all_null_value_column_is_valid_and_unshredded() {
1452        // An all-null `value` column is accepted (only a *missing* column is
1453        // rejected) and the array is unshredded (no typed_value column)
1454        let metadata = BinaryViewArray::from(vec![b"test" as &[u8]; 3]);
1455        let value = new_null_array(&DataType::BinaryView, 3);
1456
1457        let fields = Fields::from(vec![
1458            Field::new("metadata", DataType::BinaryView, false),
1459            Field::new("value", DataType::BinaryView, true),
1460        ]);
1461        let struct_array = StructArray::new(fields, vec![Arc::new(metadata), value], None);
1462
1463        let variant_array = VariantArray::try_new(&struct_array).unwrap();
1464        assert!(variant_array.typed_value_column().is_none());
1465
1466        // The rows are valid but have neither value nor typed_value; the spec
1467        // requires readers to return Variant::Null in this case
1468        for i in 0..variant_array.len() {
1469            assert!(variant_array.is_valid(i));
1470            assert_eq!(variant_array.value(i), Variant::Null);
1471        }
1472    }
1473
1474    #[test]
1475    fn canonicalize_and_verify_list_like_data_types() {
1476        // `parquet/tests/variant_integration.rs` validates Parquet shredded-variant fixtures that
1477        // use Parquet LIST encoding, but those fixtures do not cover Arrow-specific list container
1478        // variants (`LargeList`, `ListView`, `LargeListView`) accepted by `VariantArray::try_new`.
1479        let make_item_binary = || Arc::new(Field::new("item", DataType::Binary, true));
1480        let make_large_binary = || Arc::new(Field::new("item", DataType::LargeBinary, true));
1481        let make_item_binary_view = || Arc::new(Field::new("item", DataType::BinaryView, true));
1482
1483        let cases = vec![
1484            // Binary item
1485            DataType::LargeList(make_item_binary()),
1486            DataType::ListView(make_item_binary()),
1487            DataType::LargeListView(make_item_binary()),
1488            // Large binary item
1489            DataType::LargeList(make_large_binary()),
1490            DataType::ListView(make_large_binary()),
1491            DataType::LargeListView(make_large_binary()),
1492            // Binary view item
1493            DataType::LargeList(make_item_binary_view()),
1494            DataType::ListView(make_item_binary_view()),
1495            DataType::LargeListView(make_item_binary_view()),
1496        ];
1497
1498        for input in cases {
1499            assert_eq!(
1500                canonicalize_and_verify_data_type(&input).unwrap().as_ref(),
1501                &input
1502            );
1503        }
1504    }
1505
1506    #[test]
1507    fn variant_array_try_new_supports_list_like_typed_value() {
1508        let item_field = Arc::new(Field::new("item", DataType::Int64, true));
1509        let values: ArrayRef = Arc::new(Int64Array::from(vec![Some(1), None, Some(3)]));
1510
1511        let typed_values = vec![
1512            Arc::new(ListArray::new(
1513                item_field.clone(),
1514                OffsetBuffer::new(ScalarBuffer::from(vec![0, 2, 3])),
1515                values.clone(),
1516                None,
1517            )) as ArrayRef,
1518            Arc::new(LargeListArray::new(
1519                item_field.clone(),
1520                OffsetBuffer::new(ScalarBuffer::from(vec![0_i64, 2, 3])),
1521                values.clone(),
1522                None,
1523            )) as ArrayRef,
1524            Arc::new(ListViewArray::new(
1525                item_field.clone(),
1526                ScalarBuffer::from(vec![0, 2]),
1527                ScalarBuffer::from(vec![2, 1]),
1528                values.clone(),
1529                None,
1530            )) as ArrayRef,
1531            Arc::new(LargeListViewArray::new(
1532                item_field,
1533                ScalarBuffer::from(vec![0_i64, 2]),
1534                ScalarBuffer::from(vec![2_i64, 1]),
1535                values,
1536                None,
1537            )) as ArrayRef,
1538        ];
1539
1540        for typed_value in typed_values {
1541            let input = make_variant_struct_with_typed_value(typed_value.clone());
1542            let variant_array = VariantArray::try_new(&input).unwrap();
1543            assert_eq!(
1544                variant_array.typed_value_column().unwrap().data_type(),
1545                typed_value.data_type(),
1546            );
1547        }
1548    }
1549
1550    #[test]
1551    fn variant_array_try_new_normalizes_fixed_size_list_typed_value() {
1552        let element_values: ArrayRef =
1553            ShreddedVariantFieldArray::perfectly_shredded(Arc::new(Int64Array::from(vec![
1554                1, 2, 3, 4,
1555            ])))
1556            .into();
1557        let item_field = Arc::new(Field::new("item", element_values.data_type().clone(), true));
1558        let typed_value: ArrayRef = Arc::new(FixedSizeListArray::new(
1559            item_field.clone(),
1560            2,
1561            element_values,
1562            None,
1563        ));
1564        let input = make_variant_struct_with_typed_value(typed_value);
1565
1566        let variant_array = VariantArray::try_new(&input).unwrap();
1567        assert_eq!(
1568            variant_array.typed_value_column().unwrap().data_type(),
1569            &DataType::List(item_field),
1570        );
1571
1572        let unshredded = crate::unshred_variant(&variant_array).unwrap();
1573        assert!(unshredded.typed_value_column().is_none());
1574        assert_eq!(unshredded.len(), 2);
1575    }
1576
1577    #[test]
1578    fn test_try_value_out_of_bounds() {
1579        let mut b = VariantArrayBuilder::new(2);
1580        b.append_variant(Variant::from(1_i8));
1581        b.append_variant(Variant::Null);
1582        let v = b.build();
1583
1584        assert_eq!(v.try_value(0).unwrap(), Variant::Int8(1));
1585        assert_eq!(v.try_value(1).unwrap(), Variant::Null);
1586
1587        let err = v.try_value(2).unwrap_err();
1588        assert_eq!(
1589            err.to_string(),
1590            "Invalid argument error: Index 2 out of bounds for VariantArray of length 2"
1591        );
1592    }
1593
1594    #[test]
1595    fn test_variant_array_iterable() {
1596        let mut b = VariantArrayBuilder::new(6);
1597
1598        b.append_null();
1599        b.append_variant(Variant::from(1_i8));
1600        b.append_variant(Variant::Null);
1601        b.append_variant(Variant::from(2_i32));
1602        b.append_variant(Variant::from(3_i64));
1603        b.append_null();
1604
1605        let v = b.build();
1606
1607        let variants = v.iter().collect::<Vec<_>>();
1608
1609        assert_eq!(
1610            variants,
1611            vec![
1612                None,
1613                Some(Variant::Int8(1)),
1614                Some(Variant::Null),
1615                Some(Variant::Int32(2)),
1616                Some(Variant::Int64(3)),
1617                None,
1618            ]
1619        );
1620    }
1621
1622    #[test]
1623    fn test_variant_array_iter_double_ended() {
1624        let array = VariantArray::from_iter([Some(0_i32), None, Some(2_i32), None, Some(4_i32)]);
1625        let mut iter = array.iter();
1626
1627        assert_eq!(iter.next(), Some(Some(Variant::from(0_i32))));
1628        assert_eq!(iter.next(), Some(None));
1629
1630        assert_eq!(iter.next_back(), Some(Some(Variant::from(4_i32))));
1631        assert_eq!(iter.next_back(), Some(None));
1632        assert_eq!(iter.next_back(), Some(Some(Variant::from(2_i32))));
1633
1634        assert_eq!(iter.next_back(), None);
1635        assert_eq!(iter.next(), None);
1636    }
1637
1638    #[test]
1639    fn test_variant_array_iter_reverse() {
1640        let array = VariantArray::from_iter([Some("a"), None, Some("aaa"), None, Some("aaaaa")]);
1641
1642        let result: Vec<_> = array.iter().rev().collect();
1643        assert_eq!(
1644            result,
1645            vec![
1646                Some(Variant::from("aaaaa")),
1647                None,
1648                Some(Variant::from("aaa")),
1649                None,
1650                Some(Variant::from("a")),
1651            ]
1652        );
1653    }
1654
1655    #[test]
1656    fn test_variant_array_iter_empty() {
1657        let v = VariantArrayBuilder::new(0).build();
1658        let mut i = v.iter();
1659        assert!(i.next().is_none());
1660        assert!(i.next_back().is_none());
1661    }
1662
1663    #[test]
1664    fn test_from_variant_opts_into_variant_array() {
1665        let v = vec![None, Some(Variant::Null), Some(Variant::BooleanFalse), None];
1666
1667        let variant_array = VariantArray::from_iter(v);
1668
1669        assert_eq!(variant_array.len(), 4);
1670
1671        assert!(variant_array.is_null(0));
1672
1673        assert!(!variant_array.is_null(1));
1674        assert_eq!(variant_array.value(1), Variant::Null);
1675
1676        assert!(!variant_array.is_null(2));
1677        assert_eq!(variant_array.value(2), Variant::BooleanFalse);
1678
1679        assert!(variant_array.is_null(3));
1680    }
1681
1682    #[test]
1683    fn test_from_option_into_variants_into_variant_array() {
1684        // Items that convert cleanly to `Variant` can be collected directly,
1685        // without wrapping them in `Some(Variant::from(..))` first
1686        let v = vec![Some(42_i64), None, Some(-1_i64)];
1687
1688        let variant_array = VariantArray::from_iter(v);
1689
1690        assert_eq!(variant_array.len(), 3);
1691
1692        assert!(!variant_array.is_null(0));
1693        assert_eq!(variant_array.value(0), Variant::Int64(42));
1694
1695        assert!(variant_array.is_null(1));
1696
1697        assert!(!variant_array.is_null(2));
1698        assert_eq!(variant_array.value(2), Variant::Int64(-1));
1699    }
1700
1701    #[test]
1702    fn test_from_option_str_into_variant_array() {
1703        let v = vec![
1704            Some("hello"),
1705            None,
1706            Some(
1707                "hello world this is much longer than the maximum short string length of sixty three bytes",
1708            ),
1709        ];
1710
1711        let variant_array: VariantArray = v.into_iter().collect();
1712
1713        assert_eq!(variant_array.len(), 3);
1714
1715        assert!(!variant_array.is_null(0));
1716        assert_eq!(
1717            variant_array.value(0),
1718            Variant::ShortString(ShortString::try_new("hello").unwrap())
1719        );
1720
1721        assert!(variant_array.is_null(1));
1722
1723        assert!(!variant_array.is_null(2));
1724        assert_eq!(
1725            variant_array.value(2),
1726            Variant::String(
1727                "hello world this is much longer than the maximum short string length of sixty three bytes"
1728            )
1729        );
1730    }
1731
1732    #[test]
1733    fn test_from_variants_into_variant_array() {
1734        let v = vec![
1735            Variant::Null,
1736            Variant::BooleanFalse,
1737            Variant::ShortString(ShortString::try_new("norm").unwrap()),
1738        ];
1739
1740        let variant_array = VariantArray::from_iter(v);
1741
1742        assert_eq!(variant_array.len(), 3);
1743
1744        assert!(!variant_array.is_null(0));
1745        assert_eq!(variant_array.value(0), Variant::Null);
1746
1747        assert!(!variant_array.is_null(1));
1748        assert_eq!(variant_array.value(1), Variant::BooleanFalse);
1749
1750        assert!(!variant_array.is_null(2));
1751        assert_eq!(
1752            variant_array.value(2),
1753            Variant::ShortString(ShortString::try_new("norm").unwrap())
1754        );
1755    }
1756
1757    #[test]
1758    fn test_variant_equality() {
1759        let v_iter = [None, Some(Variant::BooleanFalse), Some(Variant::Null), None];
1760        let v = VariantArray::from_iter(v_iter.clone());
1761
1762        {
1763            let v_copy = v.clone();
1764            assert_eq!(v, v_copy);
1765        }
1766
1767        {
1768            let v_iter_reversed = v_iter.iter().cloned().rev();
1769            let v_reversed = VariantArray::from_iter(v_iter_reversed);
1770
1771            assert_ne!(v, v_reversed);
1772        }
1773
1774        {
1775            let v_sliced = v.slice(0, 1);
1776            assert_ne!(v, v_sliced);
1777        }
1778    }
1779
1780    #[test]
1781    fn binary_typed_value_roundtrips() {
1782        // Verify that a shredded variant with Binary typed_value can be read back
1783        let typed_value: ArrayRef = Arc::new(BinaryArray::from(vec![b"hello" as &[u8]]));
1784        let struct_array = make_variant_struct_with_typed_value(typed_value);
1785
1786        let variant_array = VariantArray::try_new(&struct_array).unwrap();
1787        assert_eq!(variant_array.value(0), Variant::from(b"hello" as &[u8]));
1788    }
1789
1790    #[test]
1791    fn large_binary_typed_value_roundtrips() {
1792        // Verify that a shredded variant with LargeBinary typed_value can be read back
1793        let typed_value: ArrayRef = Arc::new(LargeBinaryArray::from(vec![b"world" as &[u8]]));
1794        let struct_array = make_variant_struct_with_typed_value(typed_value);
1795
1796        let variant_array = VariantArray::try_new(&struct_array).unwrap();
1797        assert_eq!(variant_array.value(0), Variant::from(b"world" as &[u8]));
1798    }
1799
1800    macro_rules! invalid_variant_array_test {
1801        ($fn_name: ident, $invalid_typed_value: expr, $error_msg: literal) => {
1802            #[test]
1803            fn $fn_name() {
1804                let invalid_typed_value = $invalid_typed_value;
1805
1806                let struct_array =
1807                    make_variant_struct_with_typed_value(Arc::new(invalid_typed_value));
1808
1809                let array: VariantArray = VariantArray::try_new(&struct_array)
1810                    .expect("should create variant array")
1811                    .into();
1812
1813                let result = array.try_value(0);
1814                assert!(result.is_err());
1815                let error = result.unwrap_err();
1816                assert!(matches!(error, ArrowError::CastError(_)));
1817
1818                let expected: &str = $error_msg;
1819                assert!(
1820                    error.to_string().contains($error_msg),
1821                    "error `{}` did not contain `{}`",
1822                    error,
1823                    expected
1824                )
1825            }
1826        };
1827    }
1828
1829    invalid_variant_array_test!(
1830        test_variant_array_invalid_time,
1831        Time64MicrosecondArray::from(vec![Some(86401000000)]),
1832        "Cast error: Cast failed at index 0 (array type: Time64(µs)): Invalid microsecond from midnight: 86401000000"
1833    );
1834
1835    invalid_variant_array_test!(
1836        test_variant_array_invalid_decimal32,
1837        Decimal32Array::from(vec![Some(1234567890)]),
1838        "Cast error: Cast failed at index 0 (array type: Decimal32(9, 2)): Invalid argument error: 1234567890 is wider than max precision 9"
1839    );
1840
1841    invalid_variant_array_test!(
1842        test_variant_array_invalid_decimal64,
1843        Decimal64Array::from(vec![Some(1234567890123456789)]),
1844        "Cast error: Cast failed at index 0 (array type: Decimal64(18, 6)): Invalid argument error: 1234567890123456789 is wider than max precision 18"
1845    );
1846
1847    invalid_variant_array_test!(
1848        test_variant_array_invalid_decimal128,
1849        Decimal128Array::from(vec![Some(
1850            i128::from_str("123456789012345678901234567890123456789").unwrap()
1851        ),]),
1852        "Cast error: Cast failed at index 0 (array type: Decimal128(38, 10)): Invalid argument error: 123456789012345678901234567890123456789 is wider than max precision 38"
1853    );
1854    #[test]
1855    fn try_value_errors_on_unimplemented_typed_value_type() {
1856        use crate::{json_to_variant, shred_variant};
1857        use arrow::array::StringArray;
1858
1859        let json: ArrayRef = Arc::new(StringArray::from(vec![r#"{"qty": 3}"#]));
1860        let variant = json_to_variant(&json).unwrap();
1861        let shred_type = DataType::Struct(vec![Field::new("qty", DataType::Int64, true)].into());
1862        let shredded = shred_variant(&variant, &shred_type).unwrap();
1863        // Object-shredded typed_value is not yet implemented: reading it must
1864        // error, never silently return Variant::Null
1865        // TODO: https://github.com/apache/arrow-rs/issues/10620
1866        let err = shredded.try_value(0).unwrap_err();
1867        assert!(
1868            err.to_string().starts_with(
1869                "Not yet implemented: VariantArray::try_value cannot materialize typed_value"
1870            ),
1871            "unexpected error: {err}"
1872        );
1873    }
1874}