Skip to main content

parquet_variant_compute/
variant_get.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
5use arrow::{
6    array::{
7        self, Array, ArrayRef, GenericListArray, GenericListViewArray, ListLikeArray, StructArray,
8        UInt64Array, make_array,
9    },
10    buffer::NullBuffer,
11    compute::{CastOptions, take},
12    datatypes::Field,
13    error::Result,
14};
15use arrow_schema::{ArrowError, DataType, FieldRef};
16use parquet_variant::{Variant, VariantMetadataView, VariantPath, VariantPathElement, VariantView};
17
18use crate::ShreddingState;
19use crate::variant_array::{BinaryColumn, all_null_value_column};
20use crate::variant_to_arrow::make_variant_to_arrow_row_builder;
21use crate::{VariantArray, VariantType, unshred_variant};
22
23use arrow::array::AsArray;
24use std::sync::Arc;
25
26pub(crate) enum ShreddedPathStep {
27    /// Path step succeeded, return the new shredding state
28    Success {
29        state: ShreddingState,
30        /// Validity after evaluating this path element.
31        path_nulls: Option<NullBuffer>,
32    },
33    /// The path element is not present in the `typed_value` column and the `value` column is
34    /// all-null, so we know it does not exist. It, and all paths under it, are all-NULL.
35    Missing,
36    /// The path element is not present in the `typed_value` column and must be retrieved from the `value`
37    /// column instead. The caller should be prepared to handle any value, including the requested
38    /// type, an arbitrary "wrong" type, or `Variant::Null`.
39    NotShredded,
40}
41
42/// Take one list-like element (at `index`) per input row as the next path step.
43///
44/// Arrays are never stored in `value` when `typed_value` is a list, so when no element can match,
45/// the step is [`ShreddedPathStep::Missing`] without consulting `value`.
46fn follow_list_like_index<L: ListLikeArray + 'static>(
47    typed_value: &dyn Array,
48    index: usize,
49) -> Result<ShreddedPathStep> {
50    let list_array = typed_value.as_any().downcast_ref::<L>().ok_or_else(|| {
51        ArrowError::ComputeError(format!(
52            "Expected array type '{}' while handling list-like path step, got '{}'",
53            std::any::type_name::<L>(),
54            typed_value.data_type()
55        ))
56    })?;
57
58    let values = list_array.values();
59
60    let Some(struct_array) = values.as_struct_opt() else {
61        return Ok(ShreddedPathStep::Missing);
62    };
63    let shredding_state = ShreddingState::try_from(struct_array)?;
64
65    let value_array = shredding_state.value_column();
66    let typed_array = shredding_state.typed_value_column();
67
68    // If list elements have neither typed nor fallback values, this path step is missing.
69    if typed_array.is_none() && value_array.null_count() == value_array.len() {
70        return Ok(ShreddedPathStep::Missing);
71    }
72
73    let mut take_indices = Vec::with_capacity(list_array.len());
74    let mut any_in_bounds = false;
75    for row in 0..list_array.len() {
76        let row_range = list_array.element_range(row);
77        let take_index = (index < row_range.len()).then(|| (row_range.start + index) as u64);
78        any_in_bounds |= take_index.is_some();
79        take_indices.push(take_index);
80    }
81
82    if !any_in_bounds {
83        return Ok(ShreddedPathStep::Missing);
84    }
85
86    let index_array = UInt64Array::from(take_indices);
87    // Keep index validity separate from the gathered child arrays: both child columns are null
88    // for an out-of-bounds index, but that same physical state represents an explicit Variant null
89    // for a present list element.
90    let path_nulls = index_array.nulls().cloned();
91
92    // Gather both typed and fallback values at the requested element index.
93    let taken_value = take(value_array, &index_array, None)?;
94    let taken_typed = typed_array
95        .map(|typed| take(typed, &index_array, None))
96        .transpose()?;
97
98    Ok(ShreddedPathStep::Success {
99        state: ShreddingState::new(taken_value, taken_typed),
100        path_nulls,
101    })
102}
103
104/// Given a shredded variant field -- a `(value?, typed_value?)` pair -- try to take one path step
105/// deeper. For a `VariantPathElement::Field`, if there is no `typed_value` at this level, if
106/// `typed_value` is not a struct, or if the requested field name does not exist, traversal returns
107/// a missing-path step (`Missing` or `NotShredded` depending on whether `value` exists).
108///
109/// Safe-cast behavior (`cast_options.safe = true`):
110/// - Type mismatch during path traversal (for example field access on non-struct, index access on
111///   non-list) returns [`ShreddedPathStep::Missing`] or [`ShreddedPathStep::NotShredded`], allowing
112///   the caller to continue with null/fallback semantics.
113/// - List index out-of-bounds produces nulls for the corresponding rows.
114///
115/// Unsafe-cast behavior (`cast_options.safe = false`):
116/// - Field access on non-struct returns [`ArrowError::CastError`].
117/// - List index path steps follow JSONPath semantics and return missing/null for non-list or
118///   out-of-bounds rows.
119pub(crate) fn follow_shredded_path_element(
120    shredding_state: &ShreddingState,
121    path_element: &VariantPathElement<'_>,
122    _cast_options: &CastOptions,
123) -> Result<ShreddedPathStep> {
124    // If the requested path element is not present in `typed_value`, and `value` is all-null, then
125    // we know it does not exist; it, and all paths under it, are all-NULL.
126    let missing_path_step = || {
127        let value = shredding_state.value_column();
128        if value.null_count() == value.len() {
129            ShreddedPathStep::Missing
130        } else {
131            ShreddedPathStep::NotShredded
132        }
133    };
134
135    let Some(typed_value) = shredding_state.typed_value_column() else {
136        return Ok(missing_path_step());
137    };
138
139    match path_element {
140        VariantPathElement::Field { name } => {
141            // Try to step into the requested field name of a struct.
142            // First, try to downcast to StructArray
143            let Some(struct_array) = typed_value.as_struct_opt() else {
144                // Object field path step follows JSONPath semantics and returns missing path step (NotShredded/Missing) on non-struct path
145                return Ok(missing_path_step());
146            };
147
148            // Now try to find the column - missing column in a present struct is just missing data
149            let Some(field) = struct_array.column_by_name(name) else {
150                // Missing column in a present struct is just missing, not wrong - return Ok
151                return Ok(missing_path_step());
152            };
153
154            let struct_array = field.as_struct_opt().ok_or_else(|| {
155                // Each named child of a shredded object represents a shredded Variant field,
156                // whose physical layout is a Struct containing `value` and/or `typed_value`.
157                ArrowError::InvalidArgumentError(format!(
158                    "Shredded object field '{name}' must be a Struct containing 'value' and/or \
159                     'typed_value', got {}",
160                    field.data_type(),
161                ))
162            })?;
163
164            let state = ShreddingState::try_from(struct_array)?;
165            // Encoded Variant nulls and valid typed structs (including empty objects) are present.
166            let path_nulls = state.value_column().nulls().and_then(|value_nulls| {
167                match state.typed_value_column() {
168                    Some(typed_value) => typed_value.logical_nulls().map(|typed_nulls| {
169                        NullBuffer::new(value_nulls.inner() | typed_nulls.inner())
170                    }),
171                    None => Some(value_nulls.clone()),
172                }
173            });
174            Ok(ShreddedPathStep::Success { state, path_nulls })
175        }
176        VariantPathElement::Index { index } => {
177            let typed_value = typed_value.as_ref();
178            match typed_value.data_type() {
179                DataType::List(_) => {
180                    follow_list_like_index::<GenericListArray<i32>>(typed_value, *index)
181                }
182                DataType::LargeList(_) => {
183                    follow_list_like_index::<GenericListArray<i64>>(typed_value, *index)
184                }
185                DataType::ListView(_) => {
186                    follow_list_like_index::<GenericListViewArray<i32>>(typed_value, *index)
187                }
188                DataType::LargeListView(_) => {
189                    follow_list_like_index::<GenericListViewArray<i64>>(typed_value, *index)
190                }
191                // JSONPath semantics: indexing a non-list yields no match.
192                _ => Ok(missing_path_step()),
193            }
194        }
195        VariantPathElement::ListElement => Err(ArrowError::InvalidArgumentError(
196            "variant_get does not support [*] path elements".to_string(),
197        )),
198    }
199}
200
201/// Extracts `path` from an unshredded variant column, reading each row's encoded bytes directly.
202///
203/// A row reads only the headers and field names along `path`, and decodes only the value it finds.
204fn get_path_from_bytes(
205    target: &VariantArray,
206    path: &[VariantPathElement<'_>],
207    as_type: Option<&DataType>,
208    cast_options: &CastOptions,
209) -> Result<ArrayRef> {
210    let mut builder = make_variant_to_arrow_row_builder(
211        target.metadata_column(),
212        VariantPath::default(),
213        as_type,
214        cast_options,
215        target.len(),
216    )?;
217    let metadata = BinaryColumn::new(target.metadata_column());
218    let value = BinaryColumn::new(target.value_column());
219
220    for i in 0..target.len() {
221        if target.is_null(i) {
222            builder.append_null()?;
223            continue;
224        }
225        // A row with neither `value` nor `typed_value` is `Variant::Null`, which has no fields.
226        let Some(value) = value.value(i) else {
227            match path.is_empty() {
228                true => builder.append_value(Variant::Null).map(drop)?,
229                false => builder.append_null()?,
230            }
231            continue;
232        };
233        let found = row_value(metadata.value(i), value)
234            .and_then(|row| row.get_path(path))
235            .and_then(|found| found.map(|found| found.try_to_variant()).transpose());
236        match found {
237            Ok(Some(found)) => builder.append_value(found).map(drop)?,
238            Ok(None) => builder.append_null()?,
239            Err(_) if cast_options.safe => builder.append_null()?,
240            Err(e) => return Err(e),
241        }
242    }
243    builder.finish()
244}
245
246/// Views a row of an unshredded variant column.
247fn row_value<'a>(metadata: Option<&'a [u8]>, value: &'a [u8]) -> Result<VariantView<'a, 'a>> {
248    let metadata = metadata.ok_or_else(|| {
249        ArrowError::InvalidArgumentError("Variant metadata is null in a non-null row".to_string())
250    })?;
251    VariantView::try_new(VariantMetadataView::try_new(metadata)?, value)
252}
253
254/// Follows the given path as far as possible through shredded variant fields. If the path ends on a
255/// shredded field, return it directly. Otherwise, use a row shredder to follow the rest of the path
256/// and extract the requested value on a per-row basis.
257fn shredded_get_path(
258    input: &VariantArray,
259    path: &[VariantPathElement<'_>],
260    as_field: Option<&Field>,
261    cast_options: &CastOptions,
262) -> Result<ArrayRef> {
263    // Helper that creates a new VariantArray from the given nested value and typed_value columns,
264    // properly accounting for accumulated nulls from path traversal
265    let make_target_variant =
266        |value: ArrayRef, typed_value: Option<ArrayRef>, accumulated_nulls: Option<NullBuffer>| {
267            let metadata = input.metadata_column().clone();
268            VariantArray::from_parts(metadata, value, typed_value, accumulated_nulls)
269        };
270
271    // Helper that extracts the value at `path` and casts it to the requested type, or returns it as
272    // an unshredded binary variant when `Variant` output is requested.
273    let shred_basic_variant =
274        |target: VariantArray, path: VariantPath<'_>, as_field: Option<&Field>| {
275            // A `VariantType` extension on `as_field` requests `Variant` output: return an
276            // unshredded binary variant instead of casting to a concrete Arrow type.
277            let requested_variant =
278                as_field.is_some_and(Field::has_valid_extension_type::<VariantType>);
279
280            // A `typed_value` in that field requests shredded output -- a `VariantArray` with
281            // `typed_value` columns. We produce only unshredded variant output. Shredded output is
282            // tracked in https://github.com/apache/arrow-rs/issues/8153. Reject such a request
283            // instead of silently dropping the shredding it asked for.
284            if requested_variant && requested_field_is_shredded(as_field) {
285                return Err(ArrowError::NotYetImplemented(
286                    "variant_get with shredded `Variant` output is not yet supported".to_string(),
287                ));
288            }
289
290            // Collapse any shredding back to binary. Only the `NotShredded` step below passes a
291            // non-empty `path`, and there `target` is already a plain `value` column (no
292            // `typed_value`) -- so `unshred_variant` hits its clone fast-path, with nothing deeper
293            // to shred. The builder then walks any remaining path per-row, emitting variant output
294            // because `as_type` is `None`.
295            let target = if requested_variant {
296                unshred_variant(&target)?
297            } else {
298                target
299            };
300
301            // Path exhausted, variant requested: return the target directly.
302            if requested_variant && path.is_empty() {
303                return Ok(ArrayRef::from(target));
304            }
305
306            let as_type = if requested_variant {
307                None
308            } else {
309                as_field.map(|f| f.data_type())
310            };
311            if target.typed_value_column().is_none() {
312                return get_path_from_bytes(&target, &path, as_type, cast_options);
313            }
314            let mut builder = make_variant_to_arrow_row_builder(
315                target.metadata_column(),
316                path,
317                as_type,
318                cast_options,
319                target.len(),
320            )?;
321            for i in 0..target.len() {
322                if target.is_null(i) {
323                    builder.append_null()?;
324                } else if !cast_options.safe {
325                    let value = target.try_value(i)?;
326                    builder.append_value(value)?;
327                } else {
328                    let _ = match target.try_value(i) {
329                        Ok(v) => builder.append_value(v)?,
330                        Err(_) => {
331                            builder.append_null()?;
332                            false // add this to make match arms have the same return type
333                        }
334                    };
335                }
336            }
337            builder.finish()
338        };
339
340    // Peel away the prefix of path elements that traverses the shredded parts of this variant
341    // column. Shredding will traverse the rest of the path on a per-row basis.
342    let variant_output = as_field.is_none_or(Field::has_valid_extension_type::<VariantType>);
343    let mut shredding_state = input.shredding_state().clone();
344    let mut accumulated_nulls = input.inner().nulls().cloned();
345    let mut path_index = 0;
346    for path_element in path {
347        match follow_shredded_path_element(&shredding_state, path_element, cast_options)? {
348            ShreddedPathStep::Success { state, path_nulls } => {
349                // Union nulls from the typed_value we just accessed
350                if let Some(typed_value) = shredding_state.typed_value_column() {
351                    accumulated_nulls =
352                        NullBuffer::union(accumulated_nulls.as_ref(), typed_value.nulls());
353                }
354                // Typed outputs skip this: a missing field's null `typed_value` already
355                // yields NULL we can zero-copy.
356                if variant_output || matches!(path_element, VariantPathElement::Index { .. }) {
357                    accumulated_nulls =
358                        NullBuffer::union(accumulated_nulls.as_ref(), path_nulls.as_ref());
359                }
360                shredding_state = state;
361                path_index += 1;
362            }
363            ShreddedPathStep::Missing => {
364                let num_rows = input.len();
365                if let Some(field) =
366                    as_field.filter(|f| !f.has_valid_extension_type::<VariantType>())
367                {
368                    return Ok(array::new_null_array(field.data_type(), num_rows));
369                }
370                let all_nulls = Some(arrow::buffer::NullBuffer::from(vec![false; num_rows]));
371                // Propagating metadata is not necessary for an all-NULL array, but is cheaper than constructing
372                // a new empty metadata array. (n * 3 bytes vs Arc bump)
373                let metadata = input.metadata_column().clone();
374                let arr = VariantArray::from_parts_unshredded(
375                    metadata,
376                    all_null_value_column(num_rows),
377                    all_nulls,
378                );
379                return Ok(ArrayRef::from(arr));
380            }
381            ShreddedPathStep::NotShredded => {
382                let target = make_target_variant(
383                    shredding_state.value_column().clone(),
384                    None,
385                    accumulated_nulls,
386                );
387                return shred_basic_variant(target, path[path_index..].into(), as_field);
388            }
389        }
390    }
391
392    // Path exhausted! Create a new `VariantArray` for the location we landed on.
393    let target = make_target_variant(
394        shredding_state.value_column().clone(),
395        shredding_state.typed_value_column().cloned(),
396        accumulated_nulls,
397    );
398
399    // If our caller did not request any specific type, we can just return whatever we landed on.
400    let Some(as_field) = as_field else {
401        return Ok(ArrayRef::from(target));
402    };
403
404    // Try to return the typed value directly when we have a perfect shredding match.
405    if let Some(shredded) = try_perfect_shredding(&target, as_field) {
406        return Ok(shredded);
407    }
408
409    // Structs are special.
410    //
411    // For fully unshredded targets (`typed_value` absent), delegate to the row builder so we
412    // preserve struct-level cast semantics:
413    // - safe mode: non-object rows become NULL structs
414    // - strict mode: non-object rows raise a cast error
415    //
416    // For shredded/partially-shredded targets (`typed_value` present), recurse into each field
417    // separately to take advantage of deeper shredding in child fields.
418    if !as_field.has_valid_extension_type::<VariantType>()
419        && let DataType::Struct(fields) = as_field.data_type()
420    {
421        if target.typed_value_column().is_none() {
422            return shred_basic_variant(target, VariantPath::default(), Some(as_field));
423        }
424
425        let children = fields
426            .iter()
427            .map(|field| {
428                let path = &[VariantPathElement::from(field.name().as_str())];
429                shredded_get_path(&target, path, Some(field), cast_options)
430            })
431            .collect::<Result<Vec<_>>>()?;
432
433        return Ok(Arc::new(StructArray::try_new(
434            fields.clone(),
435            children,
436            target.nulls().cloned(),
437        )?));
438    }
439
440    // Not a struct, so directly shred the variant as the requested type
441    shred_basic_variant(target, VariantPath::default(), Some(as_field))
442}
443
444/// Returns true if `as_field` requests *shredded* `Variant` output.
445///
446/// Its struct carries a `typed_value` field naming the type to shred to.
447/// A plain variant request has only `metadata` and `value`.
448fn requested_field_is_shredded(as_field: Option<&Field>) -> bool {
449    as_field.is_some_and(|f| match f.data_type() {
450        DataType::Struct(fields) => fields.iter().any(|field| field.name() == "typed_value"),
451        _ => false,
452    })
453}
454
455fn try_perfect_shredding(variant_array: &VariantArray, as_field: &Field) -> Option<ArrayRef> {
456    // Try to return the typed value directly when we have a perfect shredding match.
457    if matches!(as_field.data_type(), DataType::Struct(_)) {
458        return None;
459    }
460    let typed_value = variant_array.typed_value_column()?;
461
462    let value = variant_array.value_column();
463    if typed_value.data_type() == as_field.data_type() && value.null_count() == value.len() {
464        // Here we need to gate against the case where the `typed_value` is null
465        // but data is in the `value` column: only an all-null `value` column
466        // qualifies as perfect shredding.
467
468        // This is a perfect shredding, where the value is entirely shredded out,
469        // so we can just return the typed value after merging the accumulated nulls.
470        let parent_nulls = variant_array.nulls();
471
472        // If we have no nulls OR the shredded array is `Null`, which doesn't support external nulls.
473        let target_array = if parent_nulls.is_none() || typed_value.data_type().is_null() {
474            typed_value.clone()
475        } else {
476            let merged_nulls = NullBuffer::union(parent_nulls, typed_value.nulls());
477            let data = typed_value
478                .to_data()
479                .into_builder()
480                .nulls(merged_nulls)
481                .build()
482                .ok()?;
483            make_array(data)
484        };
485
486        return Some(target_array);
487    }
488
489    None
490}
491
492/// Returns an array with the specified path extracted from the variant values.
493///
494/// The return array type depends on the `as_type` field of the options parameter
495/// 1. `as_type: None`: a VariantArray is returned. The values in this new VariantArray will point
496///    to the specified path.
497/// 2. `as_type: Some(<specific field>)`: an array of the specified type is returned.
498///
499/// # Casting Semantics
500///
501/// Scalar conversion semantics intentionally follow Arrow cast behavior where applicable.
502/// Conversions in this module delegate to Arrow compute cast helpers such as
503/// `num_cast`, `cast_num_to_bool`, `single_bool_to_numeric`, and
504/// `cast_single_string_to_boolean_default`.
505///
506/// - Getting `DataType::Boolean` accepts boolean, numeric, and string variants.
507///   Numeric zero maps to `false`; non-zero maps to `true`. String parsing follows
508///   Arrow UTF8-to-boolean cast rules.
509/// - Getting numeric datatypes such as `DataType::Int8`, `DataType::Int16`, `DataType::Int32`,
510///   `DataType::Int64`, `DataType::UInt8`, `DataType::UInt16`, `DataType::UInt32`, `DataType::UInt64`,
511///   `DataType::Float16`, `DataType::Float32`, `DataType::Float64` accept
512///   boolean and numeric variants (integers, floating-point, and decimals).
513///   They return `None` when conversion is not possible.
514/// - Getting decimals such as `DataType::Decimal32`, `DataType::Decimal64`, `DataType::Decimal128`,
515///   `DataType::Decimal256` accept compatible decimal variants, integer variants,
516///   float variants and string variants.
517///   They return `None` when conversion is not possible.
518///
519/// TODO: How would a caller request a struct or list type where the fields/elements can be any
520/// variant? Caller can pass None as the requested type to fetch a specific path, but it would
521/// quickly become annoying (and inefficient) to call `variant_get` for each leaf value in a struct or
522/// list and then try to assemble the results.
523pub fn variant_get(input: &ArrayRef, options: GetOptions) -> Result<ArrayRef> {
524    let variant_array = VariantArray::try_new(input)?;
525
526    let GetOptions {
527        as_type,
528        path,
529        cast_options,
530    } = options;
531
532    if path
533        .iter()
534        .any(|element| matches!(element, VariantPathElement::ListElement))
535    {
536        return Err(ArrowError::InvalidArgumentError(
537            "variant_get does not support [*] path elements".to_string(),
538        ));
539    }
540
541    shredded_get_path(&variant_array, &path, as_type.as_deref(), &cast_options)
542}
543
544/// Controls the action of the variant_get kernel.
545#[derive(Debug, Clone, Default)]
546pub struct GetOptions<'a> {
547    /// What path to extract
548    pub path: VariantPath<'a>,
549    /// if `as_type` is None, the returned array will itself be a VariantArray.
550    ///
551    /// if `as_type` is `Some(type)` the field is returned as the specified type.
552    pub as_type: Option<FieldRef>,
553    /// Controls the casting behavior (e.g. error vs substituting null on cast error).
554    pub cast_options: CastOptions<'a>,
555}
556
557impl<'a> GetOptions<'a> {
558    /// Construct default options to get the specified path as a variant.
559    pub fn new() -> Self {
560        Default::default()
561    }
562
563    /// Construct options to get the specified path as a variant.
564    pub fn new_with_path(path: VariantPath<'a>) -> Self {
565        Self {
566            path,
567            as_type: None,
568            cast_options: Default::default(),
569        }
570    }
571
572    /// Specify the type to return.
573    pub fn with_as_type(mut self, as_type: Option<FieldRef>) -> Self {
574        self.as_type = as_type;
575        self
576    }
577
578    /// Specify the cast options to use when casting to the specified type.
579    pub fn with_cast_options(mut self, cast_options: CastOptions<'a>) -> Self {
580        self.cast_options = cast_options;
581        self
582    }
583}
584
585#[cfg(test)]
586mod test {
587    use std::str::FromStr;
588    use std::sync::Arc;
589
590    use super::{GetOptions, requested_field_is_shredded, variant_get};
591    use crate::variant_array::{ShreddedVariantFieldArray, all_null_value_column};
592    use crate::{
593        ShreddedSchemaBuilder, VariantArray, VariantArrayBuilder, cast_to_variant, json_to_variant,
594        shred_variant,
595    };
596    use arrow::array::{
597        Array, ArrayRef, AsArray, BinaryArray, BinaryViewArray, BooleanArray, Date32Array,
598        Date64Array, Decimal32Array, Decimal64Array, Decimal128Array, Decimal256Array,
599        FixedSizeListArray, Float32Array, Float64Array, Int8Array, Int16Array, Int32Array,
600        Int64Array, Int64Builder, LargeBinaryArray, LargeListArray, LargeListViewArray,
601        LargeStringArray, ListArray, ListBuilder, ListViewArray, MapBuilder, NullArray,
602        NullBuilder, StringArray, StringBuilder, StringViewArray, StructArray,
603        StructArrayAssembler, Time32MillisecondArray, Time32SecondArray, Time64MicrosecondArray,
604        Time64NanosecondArray, UnionArray,
605    };
606    use arrow::buffer::{NullBuffer, OffsetBuffer, ScalarBuffer};
607    use arrow::compute::{CastOptions, cast};
608    use arrow::datatypes::DataType::{Int16, Int32, Int64};
609    use arrow::datatypes::i256;
610    use arrow::util::display::FormatOptions;
611    use arrow_schema::ArrowError;
612    use arrow_schema::DataType::{Boolean, Float32, Float64, Int8};
613    use arrow_schema::{
614        DataType, Field, FieldRef, Fields, IntervalUnit, TimeUnit, UnionFields, UnionMode,
615    };
616    use chrono::DateTime;
617    use parquet_variant::{
618        EMPTY_VARIANT_METADATA_BYTES, Variant, VariantDecimal4, VariantDecimal8, VariantDecimal16,
619        VariantDecimalType, VariantPath,
620    };
621
622    fn single_variant_get_test(input_json: &str, path: VariantPath, expected_json: &str) {
623        // Create input array from JSON string
624        let input_array_ref: ArrayRef = Arc::new(StringArray::from(vec![Some(input_json)]));
625        let input_variant_array_ref = ArrayRef::from(json_to_variant(&input_array_ref).unwrap());
626
627        let result =
628            variant_get(&input_variant_array_ref, GetOptions::new_with_path(path)).unwrap();
629
630        // Create expected array from JSON string
631        let expected_array_ref: ArrayRef = Arc::new(StringArray::from(vec![Some(expected_json)]));
632        let expected_variant_array = json_to_variant(&expected_array_ref).unwrap();
633
634        let result_array = VariantArray::try_new(&result).unwrap();
635        assert_eq!(
636            result_array.len(),
637            1,
638            "Expected result array to have length 1"
639        );
640        assert!(
641            result_array.nulls().is_none(),
642            "Expected no nulls in result array"
643        );
644        let result_variant = result_array.value(0);
645        let expected_variant = expected_variant_array.value(0);
646        assert_eq!(
647            result_variant, expected_variant,
648            "Result variant does not match expected variant"
649        );
650    }
651
652    #[test]
653    fn get_primitive_variant_field() {
654        single_variant_get_test(
655            r#"{"some_field": 1234}"#,
656            VariantPath::try_from("some_field").unwrap(),
657            "1234",
658        );
659    }
660
661    #[test]
662    fn get_primitive_variant_list_index() {
663        single_variant_get_test("[1234, 5678]", VariantPath::from(0), "1234");
664    }
665
666    #[test]
667    fn get_primitive_variant_inside_object_of_object() {
668        single_variant_get_test(
669            r#"{"top_level_field": {"inner_field": 1234}}"#,
670            VariantPath::try_from("top_level_field")
671                .unwrap()
672                .join("inner_field"),
673            "1234",
674        );
675    }
676
677    #[test]
678    fn get_primitive_variant_inside_list_of_object() {
679        single_variant_get_test(
680            r#"[{"some_field": 1234}]"#,
681            VariantPath::from(0).join("some_field"),
682            "1234",
683        );
684    }
685
686    #[test]
687    fn get_primitive_variant_inside_object_of_list() {
688        single_variant_get_test(
689            r#"{"some_field": [1234]}"#,
690            VariantPath::try_from("some_field[0]").unwrap(),
691            "1234",
692        );
693    }
694
695    #[test]
696    fn get_complex_variant() {
697        single_variant_get_test(
698            r#"{"top_level_field": {"inner_field": 1234}}"#,
699            VariantPath::try_from("top_level_field").unwrap(),
700            r#"{"inner_field": 1234}"#,
701        );
702    }
703
704    /// Partial Shredding: extract a value as a VariantArray
705    macro_rules! numeric_partially_shredded_test {
706        ($primitive_type:ty, $data_fn:ident) => {
707            let array = $data_fn();
708            let options = GetOptions::new();
709            let result = variant_get(&array, options).unwrap();
710
711            // expect the result is a VariantArray
712            let result = VariantArray::try_new(&result).unwrap();
713            assert_eq!(result.len(), 4);
714
715            // Expect the values are the same as the original values
716            assert_eq!(
717                result.value(0),
718                Variant::from(<$primitive_type>::try_from(34u8).unwrap())
719            );
720            assert!(!result.is_valid(1));
721            assert_eq!(result.value(2), Variant::from("n/a"));
722            assert_eq!(
723                result.value(3),
724                Variant::from(<$primitive_type>::try_from(100u8).unwrap())
725            );
726        };
727    }
728
729    /// Build a mixed input [typed, null, fallback, typed] and let shred_variant
730    /// generate the shredded fixture for the requested type.
731    macro_rules! partially_shredded_variant_array_gen {
732        ($func_name:ident,  $typed_value_array_gen: expr) => {
733            partially_shredded_variant_array_gen!(
734                $func_name,
735                $typed_value_array_gen,
736                Variant::from("n/a")
737            );
738        };
739        ($func_name:ident,  $typed_value_array_gen: expr, $fallback_variant:expr) => {
740            fn $func_name() -> ArrayRef {
741                let typed_value: ArrayRef = Arc::new($typed_value_array_gen());
742                let typed_as_variant = cast_to_variant(typed_value.as_ref())
743                    .expect("should cast typed array to variant");
744                let mut input_builder = VariantArrayBuilder::new(typed_as_variant.len());
745                input_builder.append_variant(typed_as_variant.value(0));
746                input_builder.append_null();
747                input_builder.append_variant($fallback_variant);
748                input_builder.append_variant(typed_as_variant.value(3));
749
750                let variant_array = shred_variant(&input_builder.build(), typed_value.data_type())
751                    .expect("should shred variant array");
752                ArrayRef::from(variant_array)
753            }
754        };
755    }
756
757    // Fixture definitions grouped with the partially-shredded tests.
758    macro_rules! numeric_partially_shredded_variant_array_fn {
759        ($func:ident, $array_type:ident, $primitive_type:ty) => {
760            partially_shredded_variant_array_gen!($func, || $array_type::from(vec![
761                Some(<$primitive_type>::try_from(34u8).unwrap()),
762                None,
763                None,
764                Some(<$primitive_type>::try_from(100u8).unwrap()),
765            ]));
766        };
767    }
768
769    numeric_partially_shredded_variant_array_fn!(
770        partially_shredded_int8_variant_array,
771        Int8Array,
772        i8
773    );
774    numeric_partially_shredded_variant_array_fn!(
775        partially_shredded_int16_variant_array,
776        Int16Array,
777        i16
778    );
779    numeric_partially_shredded_variant_array_fn!(
780        partially_shredded_int32_variant_array,
781        Int32Array,
782        i32
783    );
784    numeric_partially_shredded_variant_array_fn!(
785        partially_shredded_int64_variant_array,
786        Int64Array,
787        i64
788    );
789    numeric_partially_shredded_variant_array_fn!(
790        partially_shredded_float32_variant_array,
791        Float32Array,
792        f32
793    );
794    numeric_partially_shredded_variant_array_fn!(
795        partially_shredded_float64_variant_array,
796        Float64Array,
797        f64
798    );
799
800    partially_shredded_variant_array_gen!(partially_shredded_bool_variant_array, || {
801        arrow::array::BooleanArray::from(vec![Some(true), None, None, Some(false)])
802    });
803
804    partially_shredded_variant_array_gen!(
805        partially_shredded_utf8_variant_array,
806        || { StringArray::from(vec![Some("hello"), None, None, Some("world")]) },
807        Variant::from(42i32)
808    );
809
810    partially_shredded_variant_array_gen!(partially_shredded_date32_variant_array, || {
811        Date32Array::from(vec![
812            Some(20348), // 2025-09-17
813            None,
814            None,
815            Some(20340), // 2025-09-09
816        ])
817    });
818
819    #[test]
820    fn get_variant_partially_shredded_int8_as_variant() {
821        numeric_partially_shredded_test!(i8, partially_shredded_int8_variant_array);
822    }
823
824    #[test]
825    fn get_variant_partially_shredded_int16_as_variant() {
826        numeric_partially_shredded_test!(i16, partially_shredded_int16_variant_array);
827    }
828
829    #[test]
830    fn get_variant_partially_shredded_int32_as_variant() {
831        numeric_partially_shredded_test!(i32, partially_shredded_int32_variant_array);
832    }
833
834    #[test]
835    fn get_variant_partially_shredded_int64_as_variant() {
836        numeric_partially_shredded_test!(i64, partially_shredded_int64_variant_array);
837    }
838
839    #[test]
840    fn get_variant_partially_shredded_float32_as_variant() {
841        numeric_partially_shredded_test!(f32, partially_shredded_float32_variant_array);
842    }
843
844    #[test]
845    fn get_variant_partially_shredded_float64_as_variant() {
846        numeric_partially_shredded_test!(f64, partially_shredded_float64_variant_array);
847    }
848
849    #[test]
850    fn get_variant_partially_shredded_bool_as_variant() {
851        let array = partially_shredded_bool_variant_array();
852        let options = GetOptions::new();
853        let result = variant_get(&array, options).unwrap();
854
855        // expect the result is a VariantArray
856        let result = VariantArray::try_new(&result).unwrap();
857        assert_eq!(result.len(), 4);
858
859        // Expect the values are the same as the original values
860        assert_eq!(result.value(0), Variant::from(true));
861        assert!(!result.is_valid(1));
862        assert_eq!(result.value(2), Variant::from("n/a"));
863        assert_eq!(result.value(3), Variant::from(false));
864    }
865
866    #[test]
867    fn get_variant_partially_shredded_utf8_as_variant() {
868        let array = partially_shredded_utf8_variant_array();
869        let options = GetOptions::new();
870        let result = variant_get(&array, options).unwrap();
871
872        // expect the result is a VariantArray
873        let result = VariantArray::try_new(&result).unwrap();
874        assert_eq!(result.len(), 4);
875
876        // Expect the values are the same as the original values
877        assert_eq!(result.value(0), Variant::from("hello"));
878        assert!(!result.is_valid(1));
879        assert_eq!(result.value(2), Variant::from(42i32));
880        assert_eq!(result.value(3), Variant::from("world"));
881    }
882
883    partially_shredded_variant_array_gen!(partially_shredded_binary_view_variant_array, || {
884        BinaryViewArray::from(vec![
885            Some(&[1u8, 2u8, 3u8][..]), // row 0 is shredded
886            None,                       // row 1 is null
887            None,                       // row 2 is a string
888            Some(&[4u8, 5u8, 6u8][..]), // row 3 is shredded
889        ])
890    });
891
892    #[test]
893    fn get_variant_partially_shredded_date32_as_variant() {
894        let array = partially_shredded_date32_variant_array();
895        let options = GetOptions::new();
896        let result = variant_get(&array, options).unwrap();
897
898        // expect the result is a VariantArray
899        let result = VariantArray::try_new(&result).unwrap();
900        assert_eq!(result.len(), 4);
901
902        // Expect the values are the same as the original values
903        use chrono::NaiveDate;
904        let date1 = NaiveDate::from_ymd_opt(2025, 9, 17).unwrap();
905        let date2 = NaiveDate::from_ymd_opt(2025, 9, 9).unwrap();
906        assert_eq!(result.value(0), Variant::from(date1));
907        assert!(!result.is_valid(1));
908        assert_eq!(result.value(2), Variant::from("n/a"));
909        assert_eq!(result.value(3), Variant::from(date2));
910    }
911
912    #[test]
913    fn get_variant_partially_shredded_binary_view_as_variant() {
914        let array = partially_shredded_binary_view_variant_array();
915        let options = GetOptions::new();
916        let result = variant_get(&array, options).unwrap();
917
918        // expect the result is a VariantArray
919        let result = VariantArray::try_new(&result).unwrap();
920        assert_eq!(result.len(), 4);
921
922        // Expect the values are the same as the original values
923        assert_eq!(result.value(0), Variant::from(&[1u8, 2u8, 3u8][..]));
924        assert!(!result.is_valid(1));
925        assert_eq!(result.value(2), Variant::from("n/a"));
926        assert_eq!(result.value(3), Variant::from(&[4u8, 5u8, 6u8][..]));
927    }
928
929    // Timestamp partially-shredded tests grouped with the other partially-shredded cases.
930    macro_rules! assert_variant_get_as_variant_array_with_default_option {
931        ($variant_array: expr, $array_expected: expr) => {{
932            let options = GetOptions::new();
933            let array = $variant_array;
934            let result = variant_get(&array, options).unwrap();
935            let result = VariantArray::try_new(&result).unwrap();
936
937            assert_eq!(result.len(), $array_expected.len());
938
939            for (idx, item) in $array_expected.into_iter().enumerate() {
940                match item {
941                    Some(item) => assert_eq!(result.value(idx), item),
942                    None => assert!(result.is_null(idx)),
943                }
944            }
945        }};
946    }
947
948    partially_shredded_variant_array_gen!(
949        partially_shredded_timestamp_micro_ntz_variant_array,
950        || {
951            arrow::array::TimestampMicrosecondArray::from(vec![
952                Some(-456000),
953                None,
954                None,
955                Some(1758602096000000),
956            ])
957        }
958    );
959
960    #[test]
961    fn get_variant_partial_shredded_timestamp_micro_ntz_as_variant() {
962        let array = partially_shredded_timestamp_micro_ntz_variant_array();
963        assert_variant_get_as_variant_array_with_default_option!(
964            array,
965            vec![
966                Some(Variant::from(
967                    DateTime::from_timestamp_micros(-456000i64)
968                        .unwrap()
969                        .naive_utc(),
970                )),
971                None,
972                Some(Variant::from("n/a")),
973                Some(Variant::from(
974                    DateTime::parse_from_rfc3339("2025-09-23T12:34:56+08:00")
975                        .unwrap()
976                        .naive_utc(),
977                )),
978            ]
979        )
980    }
981
982    partially_shredded_variant_array_gen!(partially_shredded_timestamp_micro_variant_array, || {
983        arrow::array::TimestampMicrosecondArray::from(vec![
984            Some(-456000),
985            None,
986            None,
987            Some(1758602096000000),
988        ])
989        .with_timezone("+00:00")
990    });
991
992    #[test]
993    fn get_variant_partial_shredded_timestamp_micro_as_variant() {
994        let array = partially_shredded_timestamp_micro_variant_array();
995        assert_variant_get_as_variant_array_with_default_option!(
996            array,
997            vec![
998                Some(Variant::from(
999                    DateTime::from_timestamp_micros(-456000i64)
1000                        .unwrap()
1001                        .to_utc(),
1002                )),
1003                None,
1004                Some(Variant::from("n/a")),
1005                Some(Variant::from(
1006                    DateTime::parse_from_rfc3339("2025-09-23T12:34:56+08:00")
1007                        .unwrap()
1008                        .to_utc(),
1009                )),
1010            ]
1011        )
1012    }
1013
1014    partially_shredded_variant_array_gen!(
1015        partially_shredded_timestamp_nano_ntz_variant_array,
1016        || {
1017            arrow::array::TimestampNanosecondArray::from(vec![
1018                Some(-4999999561),
1019                None,
1020                None,
1021                Some(1758602096000000000),
1022            ])
1023        }
1024    );
1025
1026    #[test]
1027    fn get_variant_partial_shredded_timestamp_nano_ntz_as_variant() {
1028        let array = partially_shredded_timestamp_nano_ntz_variant_array();
1029        assert_variant_get_as_variant_array_with_default_option!(
1030            array,
1031            vec![
1032                Some(Variant::from(
1033                    DateTime::from_timestamp(-5, 439).unwrap().naive_utc()
1034                )),
1035                None,
1036                Some(Variant::from("n/a")),
1037                Some(Variant::from(
1038                    DateTime::parse_from_rfc3339("2025-09-23T12:34:56+08:00")
1039                        .unwrap()
1040                        .naive_utc()
1041                )),
1042            ]
1043        )
1044    }
1045
1046    partially_shredded_variant_array_gen!(partially_shredded_timestamp_nano_variant_array, || {
1047        arrow::array::TimestampNanosecondArray::from(vec![
1048            Some(-4999999561),
1049            None,
1050            None,
1051            Some(1758602096000000000),
1052        ])
1053        .with_timezone("+00:00")
1054    });
1055
1056    #[test]
1057    fn get_variant_partial_shredded_timestamp_nano_as_variant() {
1058        let array = partially_shredded_timestamp_nano_variant_array();
1059        assert_variant_get_as_variant_array_with_default_option!(
1060            array,
1061            vec![
1062                Some(Variant::from(
1063                    DateTime::from_timestamp(-5, 439).unwrap().to_utc()
1064                )),
1065                None,
1066                Some(Variant::from("n/a")),
1067                Some(Variant::from(
1068                    DateTime::parse_from_rfc3339("2025-09-23T12:34:56+08:00")
1069                        .unwrap()
1070                        .to_utc()
1071                )),
1072            ]
1073        )
1074    }
1075
1076    /// Shredding: extract a value as an Int32Array
1077    #[test]
1078    fn get_variant_shredded_int32_as_int32_safe_cast() {
1079        // Extract the typed value as Int32Array
1080        let array = partially_shredded_int32_variant_array();
1081        // specify we want the typed value as Int32
1082        let field = Field::new("typed_value", DataType::Int32, true);
1083        let options = GetOptions::new().with_as_type(Some(FieldRef::from(field)));
1084        let result = variant_get(&array, options).unwrap();
1085        let expected: ArrayRef = Arc::new(Int32Array::from(vec![
1086            Some(34),
1087            None,
1088            None, // "n/a" is not an Int32 so converted to null
1089            Some(100),
1090        ]));
1091        assert_eq!(&result, &expected)
1092    }
1093
1094    /// Shredding: extract a value as an Int32Array, unsafe cast (should error on "n/a")
1095    #[test]
1096    fn get_variant_shredded_int32_as_int32_unsafe_cast() {
1097        // Extract the typed value as Int32Array
1098        let array = partially_shredded_int32_variant_array();
1099        let field = Field::new("typed_value", DataType::Int32, true);
1100        let cast_options = CastOptions {
1101            safe: false, // unsafe cast
1102            ..Default::default()
1103        };
1104        let options = GetOptions::new()
1105            .with_as_type(Some(FieldRef::from(field)))
1106            .with_cast_options(cast_options);
1107
1108        let err = variant_get(&array, options).unwrap_err();
1109        // TODO make this error message nicer (not Debug format)
1110        assert_eq!(
1111            err.to_string(),
1112            "Cast error: Failed to extract primitive of type Int32 from variant ShortString(ShortString(\"n/a\")) at path VariantPath([])"
1113        );
1114    }
1115
1116    /// Perfect Shredding: extract the typed value as a VariantArray
1117    macro_rules! numeric_perfectly_shredded_test {
1118        ($primitive_type:ty, $data_fn:ident) => {
1119            let array = $data_fn();
1120            let options = GetOptions::new();
1121            let result = variant_get(&array, options).unwrap();
1122
1123            // expect the result is a VariantArray
1124            let result = VariantArray::try_new(&result).unwrap();
1125            assert_eq!(result.len(), 3);
1126
1127            // Expect the values are the same as the original values
1128            assert_eq!(
1129                result.value(0),
1130                Variant::from(<$primitive_type>::try_from(1u8).unwrap())
1131            );
1132            assert_eq!(
1133                result.value(1),
1134                Variant::from(<$primitive_type>::try_from(2u8).unwrap())
1135            );
1136            assert_eq!(
1137                result.value(2),
1138                Variant::from(<$primitive_type>::try_from(3u8).unwrap())
1139            );
1140        };
1141    }
1142
1143    #[test]
1144    fn get_variant_perfectly_shredded_int8_as_variant() {
1145        numeric_perfectly_shredded_test!(i8, perfectly_shredded_int8_variant_array);
1146    }
1147
1148    #[test]
1149    fn get_variant_perfectly_shredded_int16_as_variant() {
1150        numeric_perfectly_shredded_test!(i16, perfectly_shredded_int16_variant_array);
1151    }
1152
1153    #[test]
1154    fn get_variant_perfectly_shredded_int32_as_variant() {
1155        numeric_perfectly_shredded_test!(i32, perfectly_shredded_int32_variant_array);
1156    }
1157
1158    #[test]
1159    fn get_variant_perfectly_shredded_int64_as_variant() {
1160        numeric_perfectly_shredded_test!(i64, perfectly_shredded_int64_variant_array);
1161    }
1162
1163    #[test]
1164    fn get_variant_perfectly_shredded_float32_as_variant() {
1165        numeric_perfectly_shredded_test!(f32, perfectly_shredded_float32_variant_array);
1166    }
1167
1168    #[test]
1169    fn get_variant_perfectly_shredded_float64_as_variant() {
1170        numeric_perfectly_shredded_test!(f64, perfectly_shredded_float64_variant_array);
1171    }
1172
1173    /// AllNull: extract a value as a VariantArray
1174    #[test]
1175    fn get_variant_all_null_as_variant() {
1176        let array = all_null_variant_array();
1177        let options = GetOptions::new();
1178        let result = variant_get(&array, options).unwrap();
1179
1180        // expect the result is a VariantArray
1181        let result = VariantArray::try_new(&result).unwrap();
1182        assert_eq!(result.len(), 3);
1183
1184        // All values should be null
1185        assert!(!result.is_valid(0));
1186        assert!(!result.is_valid(1));
1187        assert!(!result.is_valid(2));
1188    }
1189
1190    /// AllNull: extract a value as an Int32Array
1191    #[test]
1192    fn get_variant_all_null_as_int32() {
1193        let array = all_null_variant_array();
1194        // specify we want the typed value as Int32
1195        let field = Field::new("typed_value", DataType::Int32, true);
1196        let options = GetOptions::new().with_as_type(Some(FieldRef::from(field)));
1197        let result = variant_get(&array, options).unwrap();
1198
1199        let expected: ArrayRef = Arc::new(Int32Array::from(vec![
1200            Option::<i32>::None,
1201            Option::<i32>::None,
1202            Option::<i32>::None,
1203        ]));
1204        assert_eq!(&result, &expected)
1205    }
1206
1207    macro_rules! perfectly_shredded_to_arrow_primitive_test {
1208        ($name:ident, $primitive_type:expr, $perfectly_shredded_array_gen_fun:ident, $expected_array:expr) => {
1209            #[test]
1210            fn $name() {
1211                let array = $perfectly_shredded_array_gen_fun();
1212                let field = Field::new("typed_value", $primitive_type, true);
1213                let options = GetOptions::new().with_as_type(Some(FieldRef::from(field)));
1214                let result = variant_get(&array, options).unwrap();
1215                let expected_array: ArrayRef = Arc::new($expected_array);
1216                assert_eq!(&result, &expected_array);
1217            }
1218        };
1219    }
1220
1221    perfectly_shredded_to_arrow_primitive_test!(
1222        get_variant_perfectly_shredded_int18_as_int8,
1223        Int8,
1224        perfectly_shredded_int8_variant_array,
1225        Int8Array::from(vec![Some(1), Some(2), Some(3)])
1226    );
1227
1228    perfectly_shredded_to_arrow_primitive_test!(
1229        get_variant_perfectly_shredded_int16_as_int16,
1230        Int16,
1231        perfectly_shredded_int16_variant_array,
1232        Int16Array::from(vec![Some(1), Some(2), Some(3)])
1233    );
1234
1235    perfectly_shredded_to_arrow_primitive_test!(
1236        get_variant_perfectly_shredded_int32_as_int32,
1237        Int32,
1238        perfectly_shredded_int32_variant_array,
1239        Int32Array::from(vec![Some(1), Some(2), Some(3)])
1240    );
1241
1242    perfectly_shredded_to_arrow_primitive_test!(
1243        get_variant_perfectly_shredded_int64_as_int64,
1244        Int64,
1245        perfectly_shredded_int64_variant_array,
1246        Int64Array::from(vec![Some(1), Some(2), Some(3)])
1247    );
1248
1249    perfectly_shredded_to_arrow_primitive_test!(
1250        get_variant_perfectly_shredded_float32_as_float32,
1251        Float32,
1252        perfectly_shredded_float32_variant_array,
1253        Float32Array::from(vec![Some(1.0), Some(2.0), Some(3.0)])
1254    );
1255
1256    perfectly_shredded_to_arrow_primitive_test!(
1257        get_variant_perfectly_shredded_float64_as_float64,
1258        Float64,
1259        perfectly_shredded_float64_variant_array,
1260        Float64Array::from(vec![Some(1.0), Some(2.0), Some(3.0)])
1261    );
1262
1263    perfectly_shredded_to_arrow_primitive_test!(
1264        get_variant_perfectly_shredded_boolean_as_boolean,
1265        Boolean,
1266        perfectly_shredded_bool_variant_array,
1267        BooleanArray::from(vec![Some(true), Some(false), Some(true)])
1268    );
1269
1270    perfectly_shredded_to_arrow_primitive_test!(
1271        get_variant_perfectly_shredded_utf8_as_utf8,
1272        DataType::Utf8,
1273        perfectly_shredded_utf8_variant_array,
1274        StringArray::from(vec![Some("foo"), Some("bar"), Some("baz")])
1275    );
1276
1277    perfectly_shredded_to_arrow_primitive_test!(
1278        get_variant_perfectly_shredded_large_utf8_as_utf8,
1279        DataType::Utf8,
1280        perfectly_shredded_large_utf8_variant_array,
1281        StringArray::from(vec![Some("foo"), Some("bar"), Some("baz")])
1282    );
1283
1284    perfectly_shredded_to_arrow_primitive_test!(
1285        get_variant_perfectly_shredded_utf8_view_as_utf8,
1286        DataType::Utf8,
1287        perfectly_shredded_utf8_view_variant_array,
1288        StringArray::from(vec![Some("foo"), Some("bar"), Some("baz")])
1289    );
1290
1291    macro_rules! perfectly_shredded_variant_array_fn {
1292        ($func:ident, $typed_value_gen:expr) => {
1293            fn $func() -> ArrayRef {
1294                // Prefer producing fixtures with shred_variant from unshredded input.
1295                // Fall back for remaining non-shreddable test-only Arrow types (currently Null).
1296                let typed_value: ArrayRef = Arc::new($typed_value_gen());
1297                if let Some(shredded) = cast_to_variant(typed_value.as_ref())
1298                    .ok()
1299                    .and_then(|unshredded| shred_variant(&unshredded, typed_value.data_type()).ok())
1300                {
1301                    return shredded.into();
1302                }
1303
1304                let metadata = BinaryViewArray::from_iter_values(std::iter::repeat_n(
1305                    EMPTY_VARIANT_METADATA_BYTES,
1306                    typed_value.len(),
1307                ));
1308                VariantArray::perfectly_shredded(Arc::new(metadata), typed_value, None).into()
1309            }
1310        };
1311    }
1312
1313    perfectly_shredded_variant_array_fn!(perfectly_shredded_utf8_variant_array, || {
1314        StringArray::from(vec![Some("foo"), Some("bar"), Some("baz")])
1315    });
1316
1317    perfectly_shredded_variant_array_fn!(perfectly_shredded_large_utf8_variant_array, || {
1318        LargeStringArray::from(vec![Some("foo"), Some("bar"), Some("baz")])
1319    });
1320
1321    perfectly_shredded_variant_array_fn!(perfectly_shredded_utf8_view_variant_array, || {
1322        StringViewArray::from(vec![Some("foo"), Some("bar"), Some("baz")])
1323    });
1324
1325    perfectly_shredded_variant_array_fn!(perfectly_shredded_bool_variant_array, || {
1326        BooleanArray::from(vec![Some(true), Some(false), Some(true)])
1327    });
1328
1329    /// Return a VariantArray that represents a perfectly "shredded" variant
1330    /// for the given typed value.
1331    ///
1332    /// The schema of the corresponding `StructArray` would look like this:
1333    ///
1334    /// ```text
1335    /// StructArray {
1336    ///   metadata: BinaryViewArray,
1337    ///   typed_value: Int32Array,
1338    /// }
1339    /// ```
1340    macro_rules! numeric_perfectly_shredded_variant_array_fn {
1341        ($func:ident, $array_type:ident, $primitive_type:ty) => {
1342            perfectly_shredded_variant_array_fn!($func, || {
1343                $array_type::from(vec![
1344                    Some(<$primitive_type>::try_from(1u8).unwrap()),
1345                    Some(<$primitive_type>::try_from(2u8).unwrap()),
1346                    Some(<$primitive_type>::try_from(3u8).unwrap()),
1347                ])
1348            });
1349        };
1350    }
1351
1352    numeric_perfectly_shredded_variant_array_fn!(
1353        perfectly_shredded_int8_variant_array,
1354        Int8Array,
1355        i8
1356    );
1357    numeric_perfectly_shredded_variant_array_fn!(
1358        perfectly_shredded_int16_variant_array,
1359        Int16Array,
1360        i16
1361    );
1362    numeric_perfectly_shredded_variant_array_fn!(
1363        perfectly_shredded_int32_variant_array,
1364        Int32Array,
1365        i32
1366    );
1367    numeric_perfectly_shredded_variant_array_fn!(
1368        perfectly_shredded_int64_variant_array,
1369        Int64Array,
1370        i64
1371    );
1372    numeric_perfectly_shredded_variant_array_fn!(
1373        perfectly_shredded_float32_variant_array,
1374        Float32Array,
1375        f32
1376    );
1377    numeric_perfectly_shredded_variant_array_fn!(
1378        perfectly_shredded_float64_variant_array,
1379        Float64Array,
1380        f64
1381    );
1382
1383    perfectly_shredded_variant_array_fn!(
1384        perfectly_shredded_timestamp_micro_ntz_variant_array,
1385        || {
1386            arrow::array::TimestampMicrosecondArray::from(vec![
1387                Some(-456000),
1388                Some(1758602096000001),
1389                Some(1758602096000002),
1390            ])
1391        }
1392    );
1393
1394    perfectly_shredded_to_arrow_primitive_test!(
1395        get_variant_perfectly_shredded_timestamp_micro_ntz_as_timestamp_micro_ntz,
1396        DataType::Timestamp(TimeUnit::Microsecond, None),
1397        perfectly_shredded_timestamp_micro_ntz_variant_array,
1398        arrow::array::TimestampMicrosecondArray::from(vec![
1399            Some(-456000),
1400            Some(1758602096000001),
1401            Some(1758602096000002),
1402        ])
1403    );
1404
1405    // test converting micro to nano
1406    perfectly_shredded_to_arrow_primitive_test!(
1407        get_variant_perfectly_shredded_timestamp_micro_ntz_as_nano_ntz,
1408        DataType::Timestamp(TimeUnit::Nanosecond, None),
1409        perfectly_shredded_timestamp_micro_ntz_variant_array,
1410        arrow::array::TimestampNanosecondArray::from(vec![
1411            Some(-456000000),
1412            Some(1758602096000001000),
1413            Some(1758602096000002000)
1414        ])
1415    );
1416
1417    perfectly_shredded_variant_array_fn!(perfectly_shredded_timestamp_micro_variant_array, || {
1418        arrow::array::TimestampMicrosecondArray::from(vec![
1419            Some(-456000),
1420            Some(1758602096000001),
1421            Some(1758602096000002),
1422        ])
1423        .with_timezone("+00:00")
1424    });
1425
1426    perfectly_shredded_to_arrow_primitive_test!(
1427        get_variant_perfectly_shredded_timestamp_micro_as_timestamp_micro,
1428        DataType::Timestamp(TimeUnit::Microsecond, Some(Arc::from("+00:00"))),
1429        perfectly_shredded_timestamp_micro_variant_array,
1430        arrow::array::TimestampMicrosecondArray::from(vec![
1431            Some(-456000),
1432            Some(1758602096000001),
1433            Some(1758602096000002),
1434        ])
1435        .with_timezone("+00:00")
1436    );
1437
1438    // test converting micro to nano
1439    perfectly_shredded_to_arrow_primitive_test!(
1440        get_variant_perfectly_shredded_timestamp_micro_as_nano,
1441        DataType::Timestamp(TimeUnit::Nanosecond, Some(Arc::from("+00:00"))),
1442        perfectly_shredded_timestamp_micro_variant_array,
1443        arrow::array::TimestampNanosecondArray::from(vec![
1444            Some(-456000000),
1445            Some(1758602096000001000),
1446            Some(1758602096000002000)
1447        ])
1448        .with_timezone("+00:00")
1449    );
1450
1451    perfectly_shredded_variant_array_fn!(
1452        perfectly_shredded_timestamp_nano_ntz_variant_array,
1453        || {
1454            arrow::array::TimestampNanosecondArray::from(vec![
1455                Some(-4999999561),
1456                Some(1758602096000000001),
1457                Some(1758602096000000002),
1458            ])
1459        }
1460    );
1461
1462    perfectly_shredded_variant_array_fn!(
1463        perfectly_shredded_timestamp_micro_variant_array_for_second_and_milli_second,
1464        || {
1465            arrow::array::TimestampMicrosecondArray::from(vec![
1466                Some(1234),       // can't be cast to second & millisecond
1467                Some(1234000),    // can be cast to millisecond, but not second
1468                Some(1234000000), // can be cast to second & millisecond
1469            ])
1470            .with_timezone("+00:00")
1471        }
1472    );
1473
1474    // The following two tests wants to cover the micro with timezone -> milli/second cases
1475    // there are three test items, which contains some items can be cast safely, and some can't
1476    perfectly_shredded_to_arrow_primitive_test!(
1477        get_variant_perfectly_shredded_timestamp_micro_as_timestamp_second,
1478        DataType::Timestamp(TimeUnit::Second, Some(Arc::from("+00:00"))),
1479        perfectly_shredded_timestamp_micro_variant_array_for_second_and_milli_second,
1480        arrow::array::TimestampSecondArray::from(vec![
1481            None,
1482            None, // Return None if can't be cast to second safely
1483            Some(1234)
1484        ])
1485        .with_timezone("+00:00")
1486    );
1487
1488    perfectly_shredded_to_arrow_primitive_test!(
1489        get_variant_perfectly_shredded_timestamp_micro_as_timestamp_milli,
1490        DataType::Timestamp(TimeUnit::Millisecond, Some(Arc::from("+00:00"))),
1491        perfectly_shredded_timestamp_micro_variant_array_for_second_and_milli_second,
1492        arrow::array::TimestampMillisecondArray::from(vec![
1493            None, // Return None if can't be cast to millisecond safely
1494            Some(1234),
1495            Some(1234000)
1496        ])
1497        .with_timezone("+00:00")
1498    );
1499
1500    perfectly_shredded_variant_array_fn!(
1501        perfectly_shredded_timestamp_micro_ntz_variant_array_for_second_and_milli_second,
1502        || {
1503            arrow::array::TimestampMicrosecondArray::from(vec![
1504                Some(1234),       // can't be cast to second & millisecond
1505                Some(1234000),    // can be cast to millisecond, but not second
1506                Some(1234000000), // can be cast to second & millisecond
1507            ])
1508        }
1509    );
1510
1511    // The following two tests wants to cover the micro_ntz -> milli/second cases
1512    // there are three test items, which contains some items can be cast safely, and some can't
1513    perfectly_shredded_to_arrow_primitive_test!(
1514        get_variant_perfectly_shredded_timestamp_micro_ntz_as_timestamp_second,
1515        DataType::Timestamp(TimeUnit::Second, None),
1516        perfectly_shredded_timestamp_micro_ntz_variant_array_for_second_and_milli_second,
1517        arrow::array::TimestampSecondArray::from(vec![
1518            None,
1519            None, // Return None if can't be cast to second safely
1520            Some(1234)
1521        ])
1522    );
1523
1524    perfectly_shredded_to_arrow_primitive_test!(
1525        get_variant_perfectly_shredded_timestamp_micro_ntz_as_timestamp_milli,
1526        DataType::Timestamp(TimeUnit::Millisecond, None),
1527        perfectly_shredded_timestamp_micro_ntz_variant_array_for_second_and_milli_second,
1528        arrow::array::TimestampMillisecondArray::from(vec![
1529            None, // Return None if can't be cast to millisecond safely
1530            Some(1234),
1531            Some(1234000)
1532        ])
1533    );
1534
1535    perfectly_shredded_variant_array_fn!(
1536        perfectly_shredded_timestamp_nano_variant_array_for_second_and_milli_second,
1537        || {
1538            arrow::array::TimestampNanosecondArray::from(vec![
1539                Some(1234000),       // can't be cast to second & millisecond
1540                Some(1234000000),    // can be cast to millisecond, but not second
1541                Some(1234000000000), // can be cast to second & millisecond
1542            ])
1543            .with_timezone("+00:00")
1544        }
1545    );
1546
1547    // The following two tests wants to cover the nano with timezone -> milli/second cases
1548    // there are three test items, which contains some items can be cast safely, and some can't
1549    perfectly_shredded_to_arrow_primitive_test!(
1550        get_variant_perfectly_shredded_timestamp_nano_as_timestamp_second,
1551        DataType::Timestamp(TimeUnit::Second, Some(Arc::from("+00:00"))),
1552        perfectly_shredded_timestamp_nano_variant_array_for_second_and_milli_second,
1553        arrow::array::TimestampSecondArray::from(vec![
1554            None,
1555            None, // Return None if can't be cast to second safely
1556            Some(1234)
1557        ])
1558        .with_timezone("+00:00")
1559    );
1560
1561    perfectly_shredded_to_arrow_primitive_test!(
1562        get_variant_perfectly_shredded_timestamp_nano_as_timestamp_milli,
1563        DataType::Timestamp(TimeUnit::Millisecond, Some(Arc::from("+00:00"))),
1564        perfectly_shredded_timestamp_nano_variant_array_for_second_and_milli_second,
1565        arrow::array::TimestampMillisecondArray::from(vec![
1566            None, // Return None if can't be cast to millisecond safely
1567            Some(1234),
1568            Some(1234000)
1569        ])
1570        .with_timezone("+00:00")
1571    );
1572
1573    perfectly_shredded_variant_array_fn!(
1574        perfectly_shredded_timestamp_nano_ntz_variant_array_for_second_and_milli_second,
1575        || {
1576            arrow::array::TimestampNanosecondArray::from(vec![
1577                Some(1234000),       // can't be cast to second & millisecond
1578                Some(1234000000),    // can be cast to millisecond, but not second
1579                Some(1234000000000), // can be cast to second & millisecond
1580            ])
1581        }
1582    );
1583
1584    // The following two tests wants to cover the nano_ntz -> milli/second cases
1585    // there are three test items, which contains some items can be cast safely, and some can't
1586    perfectly_shredded_to_arrow_primitive_test!(
1587        get_variant_perfectly_shredded_timestamp_nano_ntz_as_timestamp_second,
1588        DataType::Timestamp(TimeUnit::Second, None),
1589        perfectly_shredded_timestamp_nano_ntz_variant_array_for_second_and_milli_second,
1590        arrow::array::TimestampSecondArray::from(vec![
1591            None,
1592            None, // Return None if can't be cast to second safely
1593            Some(1234)
1594        ])
1595    );
1596
1597    perfectly_shredded_to_arrow_primitive_test!(
1598        get_variant_perfectly_shredded_timestamp_nano_ntz_as_timestamp_milli,
1599        DataType::Timestamp(TimeUnit::Millisecond, None),
1600        perfectly_shredded_timestamp_nano_ntz_variant_array_for_second_and_milli_second,
1601        arrow::array::TimestampMillisecondArray::from(vec![
1602            None, // Return None if can't be cast to millisecond safely
1603            Some(1234),
1604            Some(1234000)
1605        ])
1606    );
1607
1608    perfectly_shredded_to_arrow_primitive_test!(
1609        get_variant_perfectly_shredded_timestamp_nano_ntz_as_timestamp_nano_ntz,
1610        DataType::Timestamp(TimeUnit::Nanosecond, None),
1611        perfectly_shredded_timestamp_nano_ntz_variant_array,
1612        arrow::array::TimestampNanosecondArray::from(vec![
1613            Some(-4999999561),
1614            Some(1758602096000000001),
1615            Some(1758602096000000002),
1616        ])
1617    );
1618
1619    perfectly_shredded_variant_array_fn!(perfectly_shredded_timestamp_nano_variant_array, || {
1620        arrow::array::TimestampNanosecondArray::from(vec![
1621            Some(-4999999561),
1622            Some(1758602096000000001),
1623            Some(1758602096000000002),
1624        ])
1625        .with_timezone("+00:00")
1626    });
1627
1628    perfectly_shredded_to_arrow_primitive_test!(
1629        get_variant_perfectly_shredded_timestamp_nano_as_timestamp_nano,
1630        DataType::Timestamp(TimeUnit::Nanosecond, Some(Arc::from("+00:00"))),
1631        perfectly_shredded_timestamp_nano_variant_array,
1632        arrow::array::TimestampNanosecondArray::from(vec![
1633            Some(-4999999561),
1634            Some(1758602096000000001),
1635            Some(1758602096000000002),
1636        ])
1637        .with_timezone("+00:00")
1638    );
1639
1640    perfectly_shredded_variant_array_fn!(perfectly_shredded_date_variant_array, || {
1641        Date32Array::from(vec![Some(-12345), Some(17586), Some(20000)])
1642    });
1643
1644    perfectly_shredded_to_arrow_primitive_test!(
1645        get_variant_perfectly_shredded_date_as_date,
1646        DataType::Date32,
1647        perfectly_shredded_date_variant_array,
1648        Date32Array::from(vec![Some(-12345), Some(17586), Some(20000)])
1649    );
1650
1651    perfectly_shredded_to_arrow_primitive_test!(
1652        get_variant_perfectly_shredded_date_as_date64,
1653        DataType::Date64,
1654        perfectly_shredded_date_variant_array,
1655        Date64Array::from(vec![
1656            Some(-1066608000000),
1657            Some(1519430400000),
1658            Some(1728000000000)
1659        ])
1660    );
1661
1662    perfectly_shredded_variant_array_fn!(perfectly_shredded_time_variant_array, || {
1663        Time64MicrosecondArray::from(vec![Some(12345000), Some(87654000), Some(135792000)])
1664    });
1665
1666    perfectly_shredded_to_arrow_primitive_test!(
1667        get_variant_perfectly_shredded_time_as_time,
1668        DataType::Time64(TimeUnit::Microsecond),
1669        perfectly_shredded_time_variant_array,
1670        Time64MicrosecondArray::from(vec![Some(12345000), Some(87654000), Some(135792000)])
1671    );
1672
1673    perfectly_shredded_to_arrow_primitive_test!(
1674        get_variant_perfectly_shredded_time_as_time64_nano,
1675        DataType::Time64(TimeUnit::Nanosecond),
1676        perfectly_shredded_time_variant_array,
1677        Time64NanosecondArray::from(vec![
1678            Some(12345000000),
1679            Some(87654000000),
1680            Some(135792000000)
1681        ])
1682    );
1683
1684    perfectly_shredded_variant_array_fn!(perfectly_shredded_time_variant_array_for_time32, || {
1685        Time64MicrosecondArray::from(vec![
1686            Some(1234),        // This can't be cast to Time32 losslessly
1687            Some(7654000),     // This can be cast to Time32(Millisecond), but not Time32(Second)
1688            Some(35792000000), // This can be cast to Time32(Second) & Time32(Millisecond)
1689        ])
1690    });
1691
1692    perfectly_shredded_to_arrow_primitive_test!(
1693        get_variant_perfectly_shredded_time_as_time32_second,
1694        DataType::Time32(TimeUnit::Second),
1695        perfectly_shredded_time_variant_array_for_time32,
1696        Time32SecondArray::from(vec![
1697            None,
1698            None, // Return None if can't be cast to Time32(Second) safely
1699            Some(35792)
1700        ])
1701    );
1702
1703    perfectly_shredded_to_arrow_primitive_test!(
1704        get_variant_perfectly_shredded_time_as_time32_milli,
1705        DataType::Time32(TimeUnit::Millisecond),
1706        perfectly_shredded_time_variant_array_for_time32,
1707        Time32MillisecondArray::from(vec![
1708            None, // Return None if can't be cast to Time32(Second) safely
1709            Some(7654),
1710            Some(35792000)
1711        ])
1712    );
1713
1714    perfectly_shredded_variant_array_fn!(perfectly_shredded_null_variant_array, || {
1715        let mut builder = NullBuilder::new();
1716        builder.append_nulls(3);
1717        builder.finish()
1718    });
1719
1720    perfectly_shredded_to_arrow_primitive_test!(
1721        get_variant_perfectly_shredded_null_as_null,
1722        DataType::Null,
1723        perfectly_shredded_null_variant_array,
1724        arrow::array::NullArray::new(3)
1725    );
1726
1727    perfectly_shredded_variant_array_fn!(perfectly_shredded_null_variant_array_with_int, || {
1728        Int32Array::from(vec![Some(32), Some(64), Some(48)])
1729    });
1730
1731    // We append null values if type miss match happens in safe mode
1732    perfectly_shredded_to_arrow_primitive_test!(
1733        get_variant_perfectly_shredded_null_with_type_mismatch_in_safe_mode,
1734        DataType::Null,
1735        perfectly_shredded_null_variant_array_with_int,
1736        arrow::array::NullArray::new(3)
1737    );
1738
1739    // We'll return an error if type miss match happens in strict mode
1740    #[test]
1741    fn get_variant_perfectly_shredded_null_as_null_with_type_mismatch_in_strict_mode() {
1742        let array = perfectly_shredded_null_variant_array_with_int();
1743        let field = Field::new("typed_value", DataType::Null, true);
1744        let options = GetOptions::new()
1745            .with_as_type(Some(FieldRef::from(field)))
1746            .with_cast_options(CastOptions {
1747                safe: false,
1748                format_options: FormatOptions::default(),
1749            });
1750
1751        let result = variant_get(&array, options);
1752
1753        assert!(result.is_err());
1754        let error_msg = format!("{}", result.unwrap_err());
1755        assert!(
1756            error_msg
1757                .contains("Cast error: Failed to extract primitive of type Null from variant Int32(32) at path VariantPath([])"),
1758            "Expected=[Cast error: Failed to extract primitive of type Null from variant Int32(32) at path VariantPath([])],\
1759                Got error message=[{error_msg}]"
1760        );
1761    }
1762
1763    perfectly_shredded_variant_array_fn!(perfectly_shredded_decimal4_variant_array, || {
1764        Decimal32Array::from(vec![Some(12345), Some(23400), Some(-12342)])
1765            .with_precision_and_scale(5, 2)
1766            .unwrap()
1767    });
1768
1769    perfectly_shredded_to_arrow_primitive_test!(
1770        get_variant_perfectly_shredded_decimal4_as_decimal4,
1771        DataType::Decimal32(5, 2),
1772        perfectly_shredded_decimal4_variant_array,
1773        Decimal32Array::from(vec![Some(12345), Some(23400), Some(-12342)])
1774            .with_precision_and_scale(5, 2)
1775            .unwrap()
1776    );
1777
1778    perfectly_shredded_variant_array_fn!(
1779        perfectly_shredded_decimal8_variant_array_cast2decimal32,
1780        || {
1781            Decimal64Array::from(vec![Some(123456), Some(145678), Some(-123456)])
1782                .with_precision_and_scale(6, 1)
1783                .unwrap()
1784        }
1785    );
1786
1787    // The input will be cast to Decimal32 when transformed to Variant
1788    // This tests will covert the logic DataType::Decimal64(the original array)
1789    // -> Variant::Decimal4(VariantArray) -> DataType::Decimal64(the result array)
1790    perfectly_shredded_to_arrow_primitive_test!(
1791        get_variant_perfectly_shredded_decimal8_through_decimal32_as_decimal8,
1792        DataType::Decimal64(6, 1),
1793        perfectly_shredded_decimal8_variant_array_cast2decimal32,
1794        Decimal64Array::from(vec![Some(123456), Some(145678), Some(-123456)])
1795            .with_precision_and_scale(6, 1)
1796            .unwrap()
1797    );
1798
1799    // This tests will covert the logic DataType::Decimal64(the original array)
1800    //  -> Variant::Decimal8(VariantArray) -> DataType::Decimal64(the result array)
1801    perfectly_shredded_variant_array_fn!(perfectly_shredded_decimal8_variant_array, || {
1802        Decimal64Array::from(vec![Some(1234567809), Some(1456787000), Some(-1234561203)])
1803            .with_precision_and_scale(10, 1)
1804            .unwrap()
1805    });
1806
1807    perfectly_shredded_to_arrow_primitive_test!(
1808        get_variant_perfectly_shredded_decimal8_as_decimal8,
1809        DataType::Decimal64(10, 1),
1810        perfectly_shredded_decimal8_variant_array,
1811        Decimal64Array::from(vec![Some(1234567809), Some(1456787000), Some(-1234561203)])
1812            .with_precision_and_scale(10, 1)
1813            .unwrap()
1814    );
1815
1816    // This tests will covert the logic DataType::Decimal128(the original array)
1817    //  -> Variant::Decimal4(VariantArray) -> DataType::Decimal128(the result array)
1818    perfectly_shredded_variant_array_fn!(
1819        perfectly_shredded_decimal16_within_decimal4_variant_array,
1820        || {
1821            Decimal128Array::from(vec![
1822                Some(i128::from(1234589)),
1823                Some(i128::from(2344444)),
1824                Some(i128::from(-1234789)),
1825            ])
1826            .with_precision_and_scale(7, 3)
1827            .unwrap()
1828        }
1829    );
1830
1831    // This tests will covert the logic DataType::Decimal128(the original array)
1832    // -> Variant::Decimal4(VariantArray) -> DataType::Decimal128(the result array)
1833    perfectly_shredded_to_arrow_primitive_test!(
1834        get_variant_perfectly_shredded_decimal16_within_decimal4_as_decimal16,
1835        DataType::Decimal128(7, 3),
1836        perfectly_shredded_decimal16_within_decimal4_variant_array,
1837        Decimal128Array::from(vec![
1838            Some(i128::from(1234589)),
1839            Some(i128::from(2344444)),
1840            Some(i128::from(-1234789)),
1841        ])
1842        .with_precision_and_scale(7, 3)
1843        .unwrap()
1844    );
1845
1846    perfectly_shredded_variant_array_fn!(
1847        perfectly_shredded_decimal16_within_decimal8_variant_array,
1848        || {
1849            Decimal128Array::from(vec![Some(1234567809), Some(1456787000), Some(-1234561203)])
1850                .with_precision_and_scale(10, 1)
1851                .unwrap()
1852        }
1853    );
1854
1855    // This tests will covert the logic DataType::Decimal128(the original array)
1856    // -> Variant::Decimal8(VariantArray) -> DataType::Decimal128(the result array)
1857    perfectly_shredded_to_arrow_primitive_test!(
1858        get_variant_perfectly_shredded_decimal16_within8_as_decimal16,
1859        DataType::Decimal128(10, 1),
1860        perfectly_shredded_decimal16_within_decimal8_variant_array,
1861        Decimal128Array::from(vec![Some(1234567809), Some(1456787000), Some(-1234561203)])
1862            .with_precision_and_scale(10, 1)
1863            .unwrap()
1864    );
1865
1866    perfectly_shredded_variant_array_fn!(perfectly_shredded_decimal16_variant_array, || {
1867        Decimal128Array::from(vec![
1868            Some(i128::from_str("12345678901234567899").unwrap()),
1869            Some(i128::from_str("23445677483748324300").unwrap()),
1870            Some(i128::from_str("-12345678901234567899").unwrap()),
1871        ])
1872        .with_precision_and_scale(20, 3)
1873        .unwrap()
1874    });
1875
1876    // This tests will covert the logic DataType::Decimal128(the original array)
1877    // -> Variant::Decimal16(VariantArray) -> DataType::Decimal128(the result array)
1878    perfectly_shredded_to_arrow_primitive_test!(
1879        get_variant_perfectly_shredded_decimal16_as_decimal16,
1880        DataType::Decimal128(20, 3),
1881        perfectly_shredded_decimal16_variant_array,
1882        Decimal128Array::from(vec![
1883            Some(i128::from_str("12345678901234567899").unwrap()),
1884            Some(i128::from_str("23445677483748324300").unwrap()),
1885            Some(i128::from_str("-12345678901234567899").unwrap())
1886        ])
1887        .with_precision_and_scale(20, 3)
1888        .unwrap()
1889    );
1890
1891    perfectly_shredded_variant_array_fn!(perfectly_shredded_binary_variant_array, || {
1892        BinaryArray::from(vec![
1893            Some(b"Apache" as &[u8]),
1894            Some(b"Arrow-rs" as &[u8]),
1895            Some(b"Parquet-variant" as &[u8]),
1896        ])
1897    });
1898
1899    perfectly_shredded_to_arrow_primitive_test!(
1900        get_variant_perfectly_shredded_binary_as_binary,
1901        DataType::Binary,
1902        perfectly_shredded_binary_variant_array,
1903        BinaryArray::from(vec![
1904            Some(b"Apache" as &[u8]),
1905            Some(b"Arrow-rs" as &[u8]),
1906            Some(b"Parquet-variant" as &[u8]),
1907        ])
1908    );
1909
1910    perfectly_shredded_variant_array_fn!(perfectly_shredded_large_binary_variant_array, || {
1911        LargeBinaryArray::from(vec![
1912            Some(b"Apache" as &[u8]),
1913            Some(b"Arrow-rs" as &[u8]),
1914            Some(b"Parquet-variant" as &[u8]),
1915        ])
1916    });
1917
1918    perfectly_shredded_to_arrow_primitive_test!(
1919        get_variant_perfectly_shredded_large_binary_as_large_binary,
1920        DataType::LargeBinary,
1921        perfectly_shredded_large_binary_variant_array,
1922        LargeBinaryArray::from(vec![
1923            Some(b"Apache" as &[u8]),
1924            Some(b"Arrow-rs" as &[u8]),
1925            Some(b"Parquet-variant" as &[u8]),
1926        ])
1927    );
1928
1929    perfectly_shredded_variant_array_fn!(perfectly_shredded_binary_view_variant_array, || {
1930        BinaryViewArray::from(vec![
1931            Some(b"Apache" as &[u8]),
1932            Some(b"Arrow-rs" as &[u8]),
1933            Some(b"Parquet-variant" as &[u8]),
1934        ])
1935    });
1936
1937    perfectly_shredded_to_arrow_primitive_test!(
1938        get_variant_perfectly_shredded_binary_view_as_binary_view,
1939        DataType::BinaryView,
1940        perfectly_shredded_binary_view_variant_array,
1941        BinaryViewArray::from(vec![
1942            Some(b"Apache" as &[u8]),
1943            Some(b"Arrow-rs" as &[u8]),
1944            Some(b"Parquet-variant" as &[u8]),
1945        ])
1946    );
1947
1948    /// Return a VariantArray that represents an "all null" variant
1949    /// for the following example (3 null values):
1950    ///
1951    /// ```text
1952    /// null
1953    /// null
1954    /// null
1955    /// ```
1956    ///
1957    /// The schema of the corresponding `StructArray` would look like this:
1958    ///
1959    /// ```text
1960    /// StructArray {
1961    ///   metadata: BinaryViewArray,
1962    /// }
1963    /// ```
1964    fn all_null_variant_array() -> ArrayRef {
1965        let nulls = NullBuffer::from(vec![
1966            false, // row 0 is null
1967            false, // row 1 is null
1968            false, // row 2 is null
1969        ]);
1970
1971        // metadata is the same for all rows (though they're all null)
1972        let metadata =
1973            BinaryViewArray::from_iter_values(std::iter::repeat_n(EMPTY_VARIANT_METADATA_BYTES, 3));
1974
1975        ArrayRef::from(VariantArray::from_parts(
1976            Arc::new(metadata),
1977            all_null_value_column(3),
1978            None,
1979            Some(nulls),
1980        ))
1981    }
1982
1983    /// This test manually constructs a shredded variant array representing objects
1984    /// like {"x": 1, "y": "foo"} and {"x": 42} and tests extracting the "x" field
1985    /// as VariantArray using variant_get.
1986    #[test]
1987    fn test_shredded_object_field_access() {
1988        let array = shredded_object_with_x_field_variant_array();
1989
1990        // Test: Extract the "x" field as VariantArray first
1991        let options = GetOptions::new_with_path(VariantPath::try_from("x").unwrap());
1992        let result = variant_get(&array, options).unwrap();
1993
1994        let result_variant = VariantArray::try_new(&result).unwrap();
1995        assert_eq!(result_variant.len(), 2);
1996
1997        // Row 0: expect x=1
1998        assert_eq!(result_variant.value(0), Variant::Int32(1));
1999        // Row 1: expect x=42
2000        assert_eq!(result_variant.value(1), Variant::Int32(42));
2001    }
2002
2003    #[test]
2004    fn test_missing_shredded_object_field_preserves_null_semantics() {
2005        let b = DataType::Struct(vec![Field::new("b", DataType::Int64, true)].into());
2006        let schema = DataType::Struct(vec![Field::new("a", b, true)].into());
2007        let rows = [
2008            Some(r#"{"a": {"b": 7}}"#),
2009            Some(r#"{"a": {}}"#),
2010            Some(r#"{"a": 7}"#),
2011            Some(r#"{"a": null}"#),
2012            Some("{}"),
2013            None,
2014        ];
2015        let input =
2016            json_to_variant(&(Arc::new(StringArray::from(rows.to_vec())) as ArrayRef)).unwrap();
2017        let shredded = shred_variant(&input, &schema).unwrap();
2018        let cases = [
2019            (
2020                "a",
2021                [
2022                    Some(r#"{"b":7}"#),
2023                    Some("{}"),
2024                    Some("7"),
2025                    Some("null"),
2026                    None,
2027                    None,
2028                ],
2029            ),
2030            ("a.b", [Some("7"), None, None, None, None, None]),
2031        ];
2032        for (path, expected) in cases {
2033            let options = GetOptions::new_with_path(VariantPath::try_from(path).unwrap());
2034            let expected = StringArray::from(expected.to_vec());
2035            for array in [
2036                ArrayRef::from(input.clone()),
2037                ArrayRef::from(shredded.clone()),
2038            ] {
2039                for offset in [0, 1] {
2040                    let array = array.slice(offset, array.len() - offset);
2041                    let result = variant_get(&array, options.clone()).unwrap();
2042                    let result =
2043                        crate::unshred_variant(&VariantArray::try_new(&result).unwrap()).unwrap();
2044                    let json = crate::variant_to_json(&ArrayRef::from(result)).unwrap();
2045                    assert_eq!(
2046                        json,
2047                        expected.slice(offset, array.len()),
2048                        "{path}, offset={offset}"
2049                    );
2050                }
2051            }
2052        }
2053    }
2054
2055    #[test]
2056    fn test_malformed_shredded_object_field_reports_field_and_type() {
2057        let metadata =
2058            BinaryViewArray::from_iter_values(std::iter::repeat_n(EMPTY_VARIANT_METADATA_BYTES, 2));
2059        let typed_value = StructArray::try_new(
2060            Fields::from(vec![Field::new("x", DataType::Int32, true)]),
2061            vec![Arc::new(Int32Array::from(vec![Some(1), Some(42)]))],
2062            None,
2063        )
2064        .unwrap();
2065        let array = ArrayRef::from(VariantArray::from_parts(
2066            Arc::new(metadata),
2067            all_null_value_column(2),
2068            Some(Arc::new(typed_value)),
2069            None,
2070        ));
2071
2072        let options = GetOptions::new_with_path(VariantPath::try_from("x").unwrap());
2073        let err = variant_get(&array, options).unwrap_err();
2074
2075        assert_eq!(
2076            err.to_string(),
2077            "Invalid argument error: Shredded object field 'x' must be a Struct containing \
2078             'value' and/or 'typed_value', got Int32"
2079        );
2080    }
2081
2082    /// Test extracting shredded object field with type conversion
2083    #[test]
2084    fn test_shredded_object_field_as_int32() {
2085        let array = shredded_object_with_x_field_variant_array();
2086
2087        // Test: Extract the "x" field as Int32Array (type conversion)
2088        let field = Field::new("x", DataType::Int32, false);
2089        let options = GetOptions::new_with_path(VariantPath::try_from("x").unwrap())
2090            .with_as_type(Some(FieldRef::from(field)));
2091        let result = variant_get(&array, options).unwrap();
2092
2093        // Should get Int32Array
2094        let expected: ArrayRef = Arc::new(Int32Array::from(vec![Some(1), Some(42)]));
2095        assert_eq!(&result, &expected);
2096    }
2097
2098    type ShreddedListLikeArrayGen = fn() -> ArrayRef;
2099    type ShreddedListLikeCase = (&'static str, ShreddedListLikeArrayGen);
2100
2101    fn shredded_list_like_cases() -> [ShreddedListLikeCase; 4] {
2102        [
2103            ("list", shredded_list_variant_array),
2104            ("large_list", shredded_large_list_variant_array),
2105            ("list_view", shredded_list_view_variant_array),
2106            ("large_list_view", shredded_large_list_view_variant_array),
2107        ]
2108    }
2109
2110    #[test]
2111    fn test_shredded_list_like_index_access_from_value_field() {
2112        let options = GetOptions::new_with_path(VariantPath::from(1));
2113
2114        for (case, array_gen) in shredded_list_like_cases() {
2115            let array = array_gen();
2116            let result = variant_get(&array, options.clone()).unwrap();
2117            let result_variant = VariantArray::try_new(&result).unwrap();
2118
2119            assert_eq!(result_variant.value(0), Variant::from("drama"), "{case}");
2120            assert_eq!(result_variant.value(1).as_int64(), Some(123), "{case}");
2121        }
2122    }
2123
2124    #[test]
2125    fn test_shredded_list_like_index_out_of_bounds_unsafe_cast_returns_null() {
2126        let options =
2127            GetOptions::new_with_path(VariantPath::from(10)).with_cast_options(CastOptions {
2128                safe: false,
2129                ..Default::default()
2130            });
2131
2132        for (case, array_gen) in shredded_list_like_cases() {
2133            let result = variant_get(&array_gen(), options.clone()).unwrap();
2134            let result_variant = VariantArray::try_new(&result).unwrap();
2135            assert!(result_variant.is_null(0), "{case}");
2136            assert!(result_variant.is_null(1), "{case}");
2137        }
2138    }
2139
2140    /// Test extracting shredded list-like field with type conversion.
2141    #[test]
2142    fn test_shredded_list_like_as_string() {
2143        let field = Field::new("typed_value", DataType::Utf8, false);
2144        let options = GetOptions::new_with_path(VariantPath::from(0))
2145            .with_as_type(Some(FieldRef::from(field)));
2146        let expected: ArrayRef = Arc::new(StringArray::from(vec![Some("comedy"), Some("horror")]));
2147
2148        for (case, array_gen) in shredded_list_like_cases() {
2149            let result = variant_get(&array_gen(), options.clone()).unwrap();
2150            assert_eq!(&result, &expected, "{case}");
2151        }
2152    }
2153
2154    #[test]
2155    fn test_shredded_list_like_index_access_from_value_field_as_int64() {
2156        let field = Field::new("typed_value", DataType::Int64, true);
2157        let options = GetOptions::new_with_path(VariantPath::from(1))
2158            .with_as_type(Some(FieldRef::from(field)));
2159        let expected: ArrayRef = Arc::new(Int64Array::from(vec![None, Some(123)]));
2160
2161        for (case, array_gen) in shredded_list_like_cases() {
2162            let result = variant_get(&array_gen(), options.clone()).unwrap();
2163            // "drama" -> NULL, 123 -> 123.
2164            assert_eq!(&result, &expected, "{case}");
2165        }
2166    }
2167
2168    #[test]
2169    fn test_shredded_list_in_struct_index_access() {
2170        let array = shredded_struct_with_list_variant_array();
2171        let options = GetOptions::new_with_path(VariantPath::try_from("a[1]").unwrap());
2172        let result = variant_get(&array, options).unwrap();
2173        let result_variant = VariantArray::try_new(&result).unwrap();
2174
2175        assert_eq!(result_variant.value(0), Variant::from("drama"));
2176        assert_eq!(result_variant.value(1).as_int64(), Some(123));
2177    }
2178
2179    #[test]
2180    fn test_shredded_struct_in_list_field_access() {
2181        let array = shredded_list_of_struct_variant_array();
2182        let field = Field::new("x", DataType::Int32, true);
2183        let path = VariantPath::from(0).join("x");
2184        let options = GetOptions::new_with_path(path).with_as_type(Some(FieldRef::from(field)));
2185        let result = variant_get(&array, options).unwrap();
2186
2187        let expected: ArrayRef = Arc::new(Int32Array::from(vec![Some(1), Some(3)]));
2188        assert_eq!(&result, &expected);
2189    }
2190
2191    #[test]
2192    fn test_shredded_list_of_lists_index_access() {
2193        let array = shredded_list_of_lists_variant_array();
2194        let path = VariantPath::from(0).join(1);
2195
2196        let result = variant_get(&array, GetOptions::new_with_path(path.clone())).unwrap();
2197        let result_variant = VariantArray::try_new(&result).unwrap();
2198        assert_eq!(result_variant.value(0), Variant::from("b"));
2199        assert_eq!(result_variant.value(1).as_int64(), Some(123));
2200
2201        let field = Field::new("typed_value", DataType::Int64, true);
2202        let casted = variant_get(
2203            &array,
2204            GetOptions::new_with_path(path).with_as_type(Some(FieldRef::from(field))),
2205        )
2206        .unwrap();
2207        let expected: ArrayRef = Arc::new(Int64Array::from(vec![None, Some(123)]));
2208        assert_eq!(&casted, &expected);
2209    }
2210
2211    #[test]
2212    fn test_shredded_list_out_of_bounds_is_null() {
2213        // The non-list row is stored in the list-level `value` column.
2214        let json: ArrayRef = Arc::new(StringArray::from(vec!["[]", "[null]", "[1]", r#""x""#]));
2215        let input = json_to_variant(&json).unwrap();
2216        let list_schema = DataType::new_list(DataType::Int64, true);
2217        let shredded = ArrayRef::from(shred_variant(&input, &list_schema).unwrap());
2218
2219        let options = GetOptions::new_with_path(VariantPath::from(0));
2220        let result = variant_get(&shredded, options).unwrap();
2221        let result = VariantArray::try_new(&result).unwrap();
2222
2223        assert!(result.is_null(0));
2224        assert!(!result.is_null(1));
2225        assert_eq!(result.value(1), Variant::Null);
2226        assert_eq!(result.value(2), Variant::Int64(1));
2227        assert!(result.is_null(3));
2228
2229        let options = GetOptions::new_with_path(VariantPath::from(5));
2230        let result = variant_get(&shredded, options).unwrap();
2231        let result = VariantArray::try_new(&result).unwrap();
2232        assert!((0..4).all(|i| result.is_null(i)));
2233    }
2234
2235    /// Helper to create a shredded list-like variant array used by list index tests.
2236    ///
2237    /// Rows:
2238    /// 1. `["comedy", "drama"]` (fully shred-able as `Utf8`)
2239    /// 2. `["horror", 123]` (partially shredded, with fallback for the numeric element)
2240    fn shredded_list_like_variant_array(list_schema: DataType) -> ArrayRef {
2241        let json_rows: ArrayRef = Arc::new(StringArray::from(vec![
2242            Some(r#"["comedy", "drama"]"#),
2243            Some(r#"["horror", 123]"#),
2244        ]));
2245        let input = json_to_variant(&json_rows).unwrap();
2246
2247        let shredded = shred_variant(&input, &list_schema).unwrap();
2248        ArrayRef::from(shredded)
2249    }
2250
2251    fn shredded_list_of_lists_variant_array() -> ArrayRef {
2252        let json_rows: ArrayRef = Arc::new(StringArray::from(vec![
2253            Some(r#"[["a", "b"], ["c", "d"]]"#),
2254            Some(r#"[["x", 123], ["y", "z"]]"#),
2255        ]));
2256        let input = json_to_variant(&json_rows).unwrap();
2257
2258        let inner_list = DataType::List(Arc::new(Field::new("item", DataType::Utf8, true)));
2259        let outer_list = DataType::List(Arc::new(Field::new("item", inner_list, true)));
2260        let shredded = shred_variant(&input, &outer_list).unwrap();
2261        ArrayRef::from(shredded)
2262    }
2263
2264    fn shredded_list_variant_array() -> ArrayRef {
2265        shredded_list_like_variant_array(DataType::List(Arc::new(Field::new(
2266            "item",
2267            DataType::Utf8,
2268            true,
2269        ))))
2270    }
2271
2272    fn shredded_large_list_variant_array() -> ArrayRef {
2273        shredded_list_like_variant_array(DataType::LargeList(Arc::new(Field::new(
2274            "item",
2275            DataType::Utf8,
2276            true,
2277        ))))
2278    }
2279
2280    fn shredded_list_view_variant_array() -> ArrayRef {
2281        shredded_list_like_variant_array(DataType::ListView(Arc::new(Field::new(
2282            "item",
2283            DataType::Utf8,
2284            true,
2285        ))))
2286    }
2287
2288    fn shredded_large_list_view_variant_array() -> ArrayRef {
2289        shredded_list_like_variant_array(DataType::LargeListView(Arc::new(Field::new(
2290            "item",
2291            DataType::Utf8,
2292            true,
2293        ))))
2294    }
2295
2296    fn shredded_struct_with_list_variant_array() -> ArrayRef {
2297        let json_rows: ArrayRef = Arc::new(StringArray::from(vec![
2298            Some(r#"{"a": ["comedy", "drama"]}"#),
2299            Some(r#"{"a": ["horror", 123]}"#),
2300        ]));
2301        let input = json_to_variant(&json_rows).unwrap();
2302
2303        let list_schema = DataType::List(Arc::new(Field::new("item", DataType::Utf8, true)));
2304        let shredding_schema = ShreddedSchemaBuilder::default()
2305            .with_path("a", &list_schema)
2306            .unwrap()
2307            .build();
2308        let shredded = shred_variant(&input, &shredding_schema).unwrap();
2309        ArrayRef::from(shredded)
2310    }
2311
2312    fn shredded_list_of_struct_variant_array() -> ArrayRef {
2313        let json_rows: ArrayRef = Arc::new(StringArray::from(vec![
2314            Some(r#"[{"x": 1}, {"x": 2}]"#),
2315            Some(r#"[{"x": 3}, {"y": 4}]"#),
2316        ]));
2317        let input = json_to_variant(&json_rows).unwrap();
2318
2319        let struct_type =
2320            DataType::Struct(Fields::from(vec![Field::new("x", DataType::Int32, true)]));
2321        let list_schema = DataType::List(Arc::new(Field::new("item", struct_type, true)));
2322        let shredded = shred_variant(&input, &list_schema).unwrap();
2323        ArrayRef::from(shredded)
2324    }
2325
2326    /// Helper function to create a shredded variant array representing objects
2327    ///
2328    /// This creates an array that represents:
2329    /// Row 0: {"x": 1, "y": "foo"}  (x is shredded, y is in value field)
2330    /// Row 1: {"x": 42}             (x is shredded, perfect shredding)
2331    ///
2332    /// The physical layout follows the shredding spec where:
2333    /// - metadata: contains object metadata
2334    /// - typed_value: StructArray with field "x" (ShreddedVariantFieldArray)
2335    /// - value: contains fallback for unshredded fields like {"y": "foo"}
2336    /// - The "x" field has typed_value=Int32Array and value=NULL (perfect shredding)
2337    fn shredded_object_with_x_field_variant_array() -> ArrayRef {
2338        // Create the base metadata for objects
2339        let (metadata, y_field_value) = {
2340            let mut builder = parquet_variant::VariantBuilder::new();
2341            let mut obj = builder.new_object();
2342            obj.insert("x", Variant::Int32(42));
2343            obj.insert("y", Variant::from("foo"));
2344            obj.finish();
2345            builder.finish()
2346        };
2347
2348        // Create metadata array (same for both rows)
2349        let metadata_array = BinaryViewArray::from_iter_values(std::iter::repeat_n(&metadata, 2));
2350
2351        // Create the main value field per the 3-step shredding spec:
2352        // Step 2: If field not in shredding schema, check value field
2353        // Row 0: {"y": "foo"} (y is not shredded, stays in value for step 2)
2354        // Row 1: {} (empty object - no unshredded fields)
2355        let empty_object_value = {
2356            let mut builder = parquet_variant::VariantBuilder::new();
2357            let obj = builder.new_object();
2358            obj.finish();
2359            let (_, value) = builder.finish();
2360            value
2361        };
2362
2363        let value_array = BinaryViewArray::from(vec![
2364            Some(y_field_value.as_slice()),      // Row 0 has {"y": "foo"}
2365            Some(empty_object_value.as_slice()), // Row 1 has {}
2366        ]);
2367
2368        // Create the "x" field as a ShreddedVariantFieldArray
2369        // This represents the shredded Int32 values for the "x" field
2370        let x_field_typed_value = Int32Array::from(vec![Some(1), Some(42)]);
2371
2372        // For perfect shredding of the x field, no "value" column, only typed_value
2373        let x_field_shredded = ShreddedVariantFieldArray::perfectly_shredded(Arc::new(
2374            x_field_typed_value,
2375        ) as ArrayRef);
2376
2377        // Create the main typed_value as a struct containing the "x" field
2378        let typed_value_fields = Fields::from(vec![Field::new(
2379            "x",
2380            x_field_shredded.data_type().clone(),
2381            true,
2382        )]);
2383        let typed_value_struct = StructArray::try_new(
2384            typed_value_fields,
2385            vec![ArrayRef::from(x_field_shredded)],
2386            None, // No nulls - both rows have the object structure
2387        )
2388        .unwrap();
2389
2390        // Create the main VariantArray
2391        ArrayRef::from(VariantArray::from_parts(
2392            Arc::new(metadata_array),
2393            Arc::new(value_array),
2394            Some(Arc::new(typed_value_struct)),
2395            None,
2396        ))
2397    }
2398
2399    /// Simple test to check if nested paths are supported by current implementation
2400    #[test]
2401    fn test_simple_nested_path_support() {
2402        // Check: How does VariantPath parse different strings?
2403        println!("Testing path parsing:");
2404
2405        let path_x = VariantPath::try_from("x").unwrap();
2406        let elements_x: Vec<_> = path_x.iter().collect();
2407        println!("  'x' -> {} elements: {:?}", elements_x.len(), elements_x);
2408
2409        let path_ax = VariantPath::try_from("a.x").unwrap();
2410        let elements_ax: Vec<_> = path_ax.iter().collect();
2411        println!(
2412            "  'a.x' -> {} elements: {:?}",
2413            elements_ax.len(),
2414            elements_ax
2415        );
2416
2417        let path_ax_alt = VariantPath::try_from("$.a.x").unwrap();
2418        let elements_ax_alt: Vec<_> = path_ax_alt.iter().collect();
2419        println!(
2420            "  '$.a.x' -> {} elements: {:?}",
2421            elements_ax_alt.len(),
2422            elements_ax_alt
2423        );
2424
2425        let path_nested = VariantPath::try_from("a").unwrap().join("x");
2426        let elements_nested: Vec<_> = path_nested.iter().collect();
2427        println!(
2428            "  VariantPath::try_from('a').unwrap().join('x') -> {} elements: {:?}",
2429            elements_nested.len(),
2430            elements_nested
2431        );
2432
2433        // Use your existing simple test data but try "a.x" instead of "x"
2434        let array = shredded_object_with_x_field_variant_array();
2435
2436        // Test if variant_get with REAL nested path throws not implemented error
2437        let real_nested_path = VariantPath::try_from("a").unwrap().join("x");
2438        let options = GetOptions::new_with_path(real_nested_path);
2439        let result = variant_get(&array, options);
2440
2441        match result {
2442            Ok(_) => {
2443                println!("Nested path 'a.x' works unexpectedly!");
2444            }
2445            Err(e) => {
2446                println!("Nested path 'a.x' error: {e}");
2447                if e.to_string().contains("Not yet implemented")
2448                    || e.to_string().contains("NotYetImplemented")
2449                {
2450                    println!("This is expected - nested paths are not implemented");
2451                    return;
2452                }
2453                // Any other error is also expected for now
2454                println!("This shows nested paths need implementation");
2455            }
2456        }
2457    }
2458
2459    /// Test comprehensive variant_get scenarios with Int32 conversion
2460    /// Test depth 0: Direct field access "x" with Int32 conversion
2461    /// Covers shredded vs non-shredded VariantArrays for simple field access
2462    #[test]
2463    fn test_depth_0_int32_conversion() {
2464        println!("=== Testing Depth 0: Direct field access ===");
2465
2466        // Non-shredded test data: [{"x": 42}, {"x": "foo"}, {"y": 10}]
2467        let unshredded_array = create_depth_0_test_data();
2468
2469        let field = Field::new("result", DataType::Int32, true);
2470        let path = VariantPath::try_from("x").unwrap();
2471        let options = GetOptions::new_with_path(path).with_as_type(Some(FieldRef::from(field)));
2472        let result = variant_get(&unshredded_array, options).unwrap();
2473
2474        let expected: ArrayRef = Arc::new(Int32Array::from(vec![
2475            Some(42), // {"x": 42} -> 42
2476            None,     // {"x": "foo"} -> NULL (type mismatch)
2477            None,     // {"y": 10} -> NULL (field missing)
2478        ]));
2479        assert_eq!(&result, &expected);
2480        println!("Depth 0 (unshredded) passed");
2481
2482        // Shredded test data: using simplified approach based on working pattern
2483        let shredded_array = create_depth_0_shredded_test_data_simple();
2484
2485        let field = Field::new("result", DataType::Int32, true);
2486        let path = VariantPath::try_from("x").unwrap();
2487        let options = GetOptions::new_with_path(path).with_as_type(Some(FieldRef::from(field)));
2488        let result = variant_get(&shredded_array, options).unwrap();
2489
2490        let expected: ArrayRef = Arc::new(Int32Array::from(vec![
2491            Some(42), // {"x": 42} -> 42 (from typed_value)
2492            None,     // {"x": "foo"} -> NULL (type mismatch, from value field)
2493        ]));
2494        assert_eq!(&result, &expected);
2495        println!("Depth 0 (shredded) passed");
2496    }
2497
2498    /// Test depth 1: Single nested field access "a.x" with Int32 conversion
2499    /// Covers shredded vs non-shredded VariantArrays for nested field access
2500    #[test]
2501    fn test_depth_1_int32_conversion() {
2502        println!("=== Testing Depth 1: Single nested field access ===");
2503
2504        // Non-shredded test data from the GitHub issue
2505        let unshredded_array = create_nested_path_test_data();
2506
2507        let field = Field::new("result", DataType::Int32, true);
2508        let path = VariantPath::try_from("a.x").unwrap(); // Dot notation!
2509        let options = GetOptions::new_with_path(path).with_as_type(Some(FieldRef::from(field)));
2510        let result = variant_get(&unshredded_array, options).unwrap();
2511
2512        let expected: ArrayRef = Arc::new(Int32Array::from(vec![
2513            Some(55), // {"a": {"x": 55}} -> 55
2514            None,     // {"a": {"x": "foo"}} -> NULL (type mismatch)
2515        ]));
2516        assert_eq!(&result, &expected);
2517        println!("Depth 1 (unshredded) passed");
2518
2519        // Shredded test data: depth 1 nested shredding
2520        let shredded_array = create_depth_1_shredded_test_data_working();
2521
2522        let field = Field::new("result", DataType::Int32, true);
2523        let path = VariantPath::try_from("a.x").unwrap(); // Dot notation!
2524        let options = GetOptions::new_with_path(path).with_as_type(Some(FieldRef::from(field)));
2525        let result = variant_get(&shredded_array, options).unwrap();
2526
2527        let expected: ArrayRef = Arc::new(Int32Array::from(vec![
2528            Some(55), // {"a": {"x": 55}} -> 55 (from nested shredded x)
2529            None,     // {"a": {"x": "foo"}} -> NULL (type mismatch in nested value)
2530        ]));
2531        assert_eq!(&result, &expected);
2532        println!("Depth 1 (shredded) passed");
2533    }
2534
2535    /// Test depth 2: Double nested field access "a.b.x" with Int32 conversion
2536    /// Covers shredded vs non-shredded VariantArrays for deeply nested field access
2537    #[test]
2538    fn test_depth_2_int32_conversion() {
2539        println!("=== Testing Depth 2: Double nested field access ===");
2540
2541        // Non-shredded test data: [{"a": {"b": {"x": 100}}}, {"a": {"b": {"x": "bar"}}}, {"a": {"b": {"y": 200}}}]
2542        let unshredded_array = create_depth_2_test_data();
2543
2544        let field = Field::new("result", DataType::Int32, true);
2545        let path = VariantPath::try_from("a.b.x").unwrap(); // Double nested dot notation!
2546        let options = GetOptions::new_with_path(path).with_as_type(Some(FieldRef::from(field)));
2547        let result = variant_get(&unshredded_array, options).unwrap();
2548
2549        let expected: ArrayRef = Arc::new(Int32Array::from(vec![
2550            Some(100), // {"a": {"b": {"x": 100}}} -> 100
2551            None,      // {"a": {"b": {"x": "bar"}}} -> NULL (type mismatch)
2552            None,      // {"a": {"b": {"y": 200}}} -> NULL (field missing)
2553        ]));
2554        assert_eq!(&result, &expected);
2555        println!("Depth 2 (unshredded) passed");
2556
2557        // Shredded test data: depth 2 nested shredding
2558        let shredded_array = create_depth_2_shredded_test_data_working();
2559
2560        let field = Field::new("result", DataType::Int32, true);
2561        let path = VariantPath::try_from("a.b.x").unwrap(); // Double nested dot notation!
2562        let options = GetOptions::new_with_path(path).with_as_type(Some(FieldRef::from(field)));
2563        let result = variant_get(&shredded_array, options).unwrap();
2564
2565        let expected: ArrayRef = Arc::new(Int32Array::from(vec![
2566            Some(100), // {"a": {"b": {"x": 100}}} -> 100 (from deeply nested shredded x)
2567            None,      // {"a": {"b": {"x": "bar"}}} -> NULL (type mismatch in deep value)
2568            None,      // {"a": {"b": {"y": 200}}} -> NULL (field missing in deep structure)
2569        ]));
2570        assert_eq!(&result, &expected);
2571        println!("Depth 2 (shredded) passed");
2572    }
2573
2574    /// Test that demonstrates what CURRENTLY WORKS
2575    ///
2576    /// This shows that nested path functionality does work, but only when the
2577    /// test data matches what the current implementation expects
2578    #[test]
2579    fn test_current_nested_path_functionality() {
2580        let array = shredded_object_with_x_field_variant_array();
2581
2582        // Test: Extract the "x" field (single level) - this works
2583        let single_path = VariantPath::try_from("x").unwrap();
2584        let field = Field::new("result", DataType::Int32, true);
2585        let options =
2586            GetOptions::new_with_path(single_path).with_as_type(Some(FieldRef::from(field)));
2587        let result = variant_get(&array, options).unwrap();
2588
2589        println!("Single path 'x' works - result: {result:?}");
2590
2591        // Test: Try nested path "a.x" - this is what we need to implement
2592        let nested_path = VariantPath::try_from("a").unwrap().join("x");
2593        let field = Field::new("result", DataType::Int32, true);
2594        let options =
2595            GetOptions::new_with_path(nested_path).with_as_type(Some(FieldRef::from(field)));
2596        let result = variant_get(&array, options).unwrap();
2597
2598        println!("Nested path 'a.x' result: {result:?}");
2599    }
2600
2601    #[test]
2602    fn test_variant_get_as_variant_from_unshredded_input() {
2603        let (unshredded, _) = create_variant_get_as_variant_test_data();
2604        let unshredded_field = VariantArray::try_new(&unshredded).unwrap().field("result");
2605        assert_variant_field_extraction_returns_unshredded_variant(&unshredded, &unshredded_field);
2606    }
2607
2608    #[test]
2609    fn test_variant_get_as_variant_from_shredded_input() {
2610        let (unshredded, shredded) = create_variant_get_as_variant_test_data();
2611        let unshredded_field = VariantArray::try_new(&unshredded).unwrap().field("result");
2612        assert_variant_field_extraction_returns_unshredded_variant(&shredded, &unshredded_field);
2613    }
2614
2615    #[test]
2616    fn test_variant_get_as_shredded_variant_is_not_yet_supported() {
2617        let (_, shredded) = create_variant_get_as_variant_test_data();
2618        // Deriving the request field from the shredded array yields a `VariantType` field whose
2619        // struct carries a `typed_value` -- a request to shred the output. That is unsupported
2620        // (https://github.com/apache/arrow-rs/issues/8153) and must error, not silently return a
2621        // plain binary variant.
2622        let shredded_field = VariantArray::try_new(&shredded).unwrap().field("result");
2623        assert!(requested_field_is_shredded(Some(&shredded_field)));
2624
2625        let options = GetOptions::new_with_path(VariantPath::try_from("field_name").unwrap())
2626            .with_as_type(Some(FieldRef::from(shredded_field)));
2627        let err = variant_get(&shredded, options).unwrap_err();
2628        assert!(
2629            matches!(err, ArrowError::NotYetImplemented(_)),
2630            "expected NotYetImplemented, got {err:?}"
2631        );
2632    }
2633
2634    #[test]
2635    fn test_variant_get_list_element_wildcard_is_invalid_argument() {
2636        let (unshredded, _) = create_variant_get_as_variant_test_data();
2637        let options = GetOptions::new_with_path(VariantPath::try_from("field_name[*]").unwrap());
2638        let err = variant_get(&unshredded, options).unwrap_err();
2639        assert!(
2640            matches!(err, ArrowError::InvalidArgumentError(_)),
2641            "expected InvalidArgumentError, got {err:?}"
2642        );
2643    }
2644
2645    #[test]
2646    fn test_variant_get_missing_path_as_variant_annotates_value_non_nullable() {
2647        let (unshredded, shredded) = create_variant_get_as_variant_test_data();
2648        let variant_field = VariantArray::try_new(&unshredded).unwrap().field("result");
2649
2650        // indexing into a struct typed_value can never match: all-null variant output
2651        for as_type in [Some(FieldRef::from(variant_field)), None] {
2652            let options =
2653                GetOptions::new_with_path(VariantPath::try_from("field_name[0]").unwrap())
2654                    .with_as_type(as_type);
2655            let result = variant_get(&shredded, options).unwrap();
2656            let result_variant = VariantArray::try_new(&result).unwrap();
2657
2658            assert_eq!(result_variant.inner().null_count(), result_variant.len());
2659            let value_field = result_variant.inner().field_by_name("value").unwrap();
2660            assert!(!value_field.is_nullable());
2661        }
2662    }
2663
2664    fn create_variant_get_as_variant_test_data() -> (ArrayRef, ArrayRef) {
2665        let input_json: ArrayRef = Arc::new(StringArray::from(vec![
2666            Some(r#"{"field_name": {"k": 100000}}"#),
2667            Some(r#"{"field_name": {"k": "s"}}"#),
2668        ]));
2669
2670        let unshredded = ArrayRef::from(json_to_variant(&input_json).unwrap());
2671        let unshredded_variant = VariantArray::try_new(&unshredded).unwrap();
2672
2673        let as_type = DataType::Struct(Fields::from(vec![Field::new(
2674            "field_name",
2675            DataType::Struct(Fields::from(vec![Field::new("k", DataType::Int32, true)])),
2676            true,
2677        )]));
2678        let shredded = ArrayRef::from(shred_variant(&unshredded_variant, &as_type).unwrap());
2679
2680        (unshredded, shredded)
2681    }
2682
2683    fn assert_variant_field_extraction_returns_unshredded_variant(
2684        input: &ArrayRef,
2685        variant_field: &Field,
2686    ) {
2687        let options = GetOptions::new_with_path(VariantPath::try_from("field_name").unwrap())
2688            .with_as_type(Some(FieldRef::from(variant_field.clone())));
2689
2690        let result = variant_get(input, options).unwrap();
2691        let result_variant = VariantArray::try_new(&result).unwrap();
2692
2693        assert!(result_variant.typed_value_column().is_none());
2694        assert!(result_variant.value_column().null_count() < result_variant.len());
2695        let value_field = result_variant.inner().field_by_name("value").unwrap();
2696        assert!(!value_field.is_nullable());
2697
2698        let expected_json: ArrayRef = Arc::new(StringArray::from(vec![
2699            Some(r#"{"k":100000}"#),
2700            Some(r#"{"k":"s"}"#),
2701        ]));
2702        let expected = json_to_variant(&expected_json).unwrap();
2703
2704        assert_eq!(result_variant.len(), expected.len());
2705        for i in 0..result_variant.len() {
2706            assert_eq!(result_variant.is_null(i), expected.is_null(i));
2707            if !result_variant.is_null(i) {
2708                assert_eq!(result_variant.value(i), expected.value(i));
2709            }
2710        }
2711    }
2712
2713    /// Create test data for depth 0 (direct field access)
2714    /// [{"x": 42}, {"x": "foo"}, {"y": 10}]
2715    fn create_depth_0_test_data() -> ArrayRef {
2716        let mut builder = crate::VariantArrayBuilder::new(3);
2717
2718        // Row 1: {"x": 42}
2719        {
2720            let json_str = r#"{"x": 42}"#;
2721            let string_array: ArrayRef = Arc::new(StringArray::from(vec![json_str]));
2722            if let Ok(variant_array) = json_to_variant(&string_array) {
2723                builder.append_variant(variant_array.value(0));
2724            } else {
2725                builder.append_null();
2726            }
2727        }
2728
2729        // Row 2: {"x": "foo"}
2730        {
2731            let json_str = r#"{"x": "foo"}"#;
2732            let string_array: ArrayRef = Arc::new(StringArray::from(vec![json_str]));
2733            if let Ok(variant_array) = json_to_variant(&string_array) {
2734                builder.append_variant(variant_array.value(0));
2735            } else {
2736                builder.append_null();
2737            }
2738        }
2739
2740        // Row 3: {"y": 10} (missing "x" field)
2741        {
2742            let json_str = r#"{"y": 10}"#;
2743            let string_array: ArrayRef = Arc::new(StringArray::from(vec![json_str]));
2744            if let Ok(variant_array) = json_to_variant(&string_array) {
2745                builder.append_variant(variant_array.value(0));
2746            } else {
2747                builder.append_null();
2748            }
2749        }
2750
2751        ArrayRef::from(builder.build())
2752    }
2753
2754    /// Create test data for depth 1 (single nested field)
2755    /// This represents the exact scenarios from the GitHub issue: "a.x"
2756    fn create_nested_path_test_data() -> ArrayRef {
2757        let mut builder = crate::VariantArrayBuilder::new(2);
2758
2759        // Row 1: {"a": {"x": 55}, "b": 42}
2760        {
2761            let json_str = r#"{"a": {"x": 55}, "b": 42}"#;
2762            let string_array: ArrayRef = Arc::new(StringArray::from(vec![json_str]));
2763            if let Ok(variant_array) = json_to_variant(&string_array) {
2764                builder.append_variant(variant_array.value(0));
2765            } else {
2766                builder.append_null();
2767            }
2768        }
2769
2770        // Row 2: {"a": {"x": "foo"}, "b": 42}
2771        {
2772            let json_str = r#"{"a": {"x": "foo"}, "b": 42}"#;
2773            let string_array: ArrayRef = Arc::new(StringArray::from(vec![json_str]));
2774            if let Ok(variant_array) = json_to_variant(&string_array) {
2775                builder.append_variant(variant_array.value(0));
2776            } else {
2777                builder.append_null();
2778            }
2779        }
2780
2781        ArrayRef::from(builder.build())
2782    }
2783
2784    /// Create test data for depth 2 (double nested field)
2785    /// [{"a": {"b": {"x": 100}}}, {"a": {"b": {"x": "bar"}}}, {"a": {"b": {"y": 200}}}]
2786    fn create_depth_2_test_data() -> ArrayRef {
2787        let mut builder = crate::VariantArrayBuilder::new(3);
2788
2789        // Row 1: {"a": {"b": {"x": 100}}}
2790        {
2791            let json_str = r#"{"a": {"b": {"x": 100}}}"#;
2792            let string_array: ArrayRef = Arc::new(StringArray::from(vec![json_str]));
2793            if let Ok(variant_array) = json_to_variant(&string_array) {
2794                builder.append_variant(variant_array.value(0));
2795            } else {
2796                builder.append_null();
2797            }
2798        }
2799
2800        // Row 2: {"a": {"b": {"x": "bar"}}}
2801        {
2802            let json_str = r#"{"a": {"b": {"x": "bar"}}}"#;
2803            let string_array: ArrayRef = Arc::new(StringArray::from(vec![json_str]));
2804            if let Ok(variant_array) = json_to_variant(&string_array) {
2805                builder.append_variant(variant_array.value(0));
2806            } else {
2807                builder.append_null();
2808            }
2809        }
2810
2811        // Row 3: {"a": {"b": {"y": 200}}} (missing "x" field)
2812        {
2813            let json_str = r#"{"a": {"b": {"y": 200}}}"#;
2814            let string_array: ArrayRef = Arc::new(StringArray::from(vec![json_str]));
2815            if let Ok(variant_array) = json_to_variant(&string_array) {
2816                builder.append_variant(variant_array.value(0));
2817            } else {
2818                builder.append_null();
2819            }
2820        }
2821
2822        ArrayRef::from(builder.build())
2823    }
2824
2825    /// Create simple shredded test data for depth 0 using a simplified working pattern
2826    /// Creates 2 rows: [{"x": 42}, {"x": "foo"}] with "x" shredded where possible
2827    fn create_depth_0_shredded_test_data_simple() -> ArrayRef {
2828        // Create base metadata using the working pattern
2829        let (metadata, string_x_value) = {
2830            let mut builder = parquet_variant::VariantBuilder::new();
2831            let mut obj = builder.new_object();
2832            obj.insert("x", Variant::from("foo"));
2833            obj.finish();
2834            builder.finish()
2835        };
2836
2837        // Metadata array (same for both rows)
2838        let metadata_array = BinaryViewArray::from_iter_values(std::iter::repeat_n(&metadata, 2));
2839
2840        // Value array following the 3-step shredding spec:
2841        // Row 0: {} (x is shredded, no unshredded fields)
2842        // Row 1: {"x": "foo"} (x is a string, can't be shredded to Int32)
2843        let empty_object_value = {
2844            let mut builder = parquet_variant::VariantBuilder::new();
2845            let obj = builder.new_object();
2846            obj.finish();
2847            let (_, value) = builder.finish();
2848            value
2849        };
2850
2851        let value_array = BinaryViewArray::from(vec![
2852            Some(empty_object_value.as_slice()), // Row 0: {} (x shredded out)
2853            Some(string_x_value.as_slice()),     // Row 1: {"x": "foo"} (fallback)
2854        ]);
2855
2856        // Create the "x" field as a ShreddedVariantFieldArray
2857        let x_field_typed_value = Int32Array::from(vec![Some(42), None]);
2858
2859        // For the x field, only typed_value (perfect shredding when possible)
2860        let x_field_shredded = ShreddedVariantFieldArray::perfectly_shredded(Arc::new(
2861            x_field_typed_value,
2862        ) as ArrayRef);
2863
2864        // Create the main typed_value as a struct containing the "x" field
2865        let typed_value_fields = Fields::from(vec![Field::new(
2866            "x",
2867            x_field_shredded.data_type().clone(),
2868            true,
2869        )]);
2870        let typed_value_struct = StructArray::try_new(
2871            typed_value_fields,
2872            vec![ArrayRef::from(x_field_shredded)],
2873            None,
2874        )
2875        .unwrap();
2876
2877        // Build final VariantArray
2878        ArrayRef::from(VariantArray::from_parts(
2879            Arc::new(metadata_array),
2880            Arc::new(value_array),
2881            Some(Arc::new(typed_value_struct)),
2882            None,
2883        ))
2884    }
2885
2886    /// Create working depth 1 shredded test data based on the existing working pattern
2887    /// This creates a properly structured shredded variant for "a.x" where:
2888    /// - Row 0: {"a": {"x": 55}, "b": 42} with a.x shredded into typed_value
2889    /// - Row 1: {"a": {"x": "foo"}, "b": 42} with a.x fallback to value field due to type mismatch
2890    fn create_depth_1_shredded_test_data_working() -> ArrayRef {
2891        // Create metadata following the working pattern from shredded_object_with_x_field_variant_array
2892        let (metadata, _) = {
2893            // Create nested structure: {"a": {"x": 55}, "b": 42}
2894            let mut builder = parquet_variant::VariantBuilder::new();
2895            let mut obj = builder.new_object();
2896
2897            // Create the nested "a" object
2898            let mut a_obj = obj.new_object("a");
2899            a_obj.insert("x", Variant::Int32(55));
2900            a_obj.finish();
2901
2902            obj.insert("b", Variant::Int32(42));
2903            obj.finish();
2904            builder.finish()
2905        };
2906
2907        let metadata_array = BinaryViewArray::from_iter_values(std::iter::repeat_n(&metadata, 2));
2908
2909        // Create value arrays for the fallback case
2910        // Following the spec: if field cannot be shredded, it stays in value
2911        let empty_object_value = {
2912            let mut builder = parquet_variant::VariantBuilder::new();
2913            let obj = builder.new_object();
2914            obj.finish();
2915            let (_, value) = builder.finish();
2916            value
2917        };
2918
2919        // Row 1 fallback: use the working pattern from the existing shredded test
2920        // This avoids metadata issues by using the simple fallback approach
2921        let row1_fallback = {
2922            let mut builder = parquet_variant::VariantBuilder::new();
2923            let mut obj = builder.new_object();
2924            obj.insert("fallback", Variant::from("data"));
2925            obj.finish();
2926            let (_, value) = builder.finish();
2927            value
2928        };
2929
2930        let value_array = BinaryViewArray::from(vec![
2931            Some(empty_object_value.as_slice()), // Row 0: {} (everything shredded except b in unshredded fields)
2932            Some(row1_fallback.as_slice()), // Row 1: {"a": {"x": "foo"}, "b": 42} (a.x can't be shredded)
2933        ]);
2934
2935        // Create the nested shredded structure
2936        // Level 2: x field (the deepest level)
2937        let x_typed_value = Int32Array::from(vec![Some(55), None]);
2938        let x_field_shredded =
2939            ShreddedVariantFieldArray::perfectly_shredded(Arc::new(x_typed_value) as ArrayRef);
2940
2941        // Level 1: a field containing x field + value field for fallbacks
2942        // The "a" field needs both typed_value (for shredded x) and value (for fallback cases)
2943
2944        // Create the value field for "a" (for cases where a.x can't be shredded)
2945        let a_value_data = {
2946            let mut builder = parquet_variant::VariantBuilder::new();
2947            let obj = builder.new_object();
2948            obj.finish();
2949            let (_, value) = builder.finish();
2950            value
2951        };
2952        let a_value_array = BinaryViewArray::from(vec![
2953            None,                          // Row 0: x is shredded, so no value fallback needed
2954            Some(a_value_data.as_slice()), // Row 1: fallback for a.x="foo" (but logic will check typed_value first)
2955        ]);
2956
2957        let a_inner_fields = Fields::from(vec![Field::new(
2958            "x",
2959            x_field_shredded.data_type().clone(),
2960            true,
2961        )]);
2962        let a_inner_typed_value = Arc::new(
2963            StructArray::try_new(a_inner_fields, vec![ArrayRef::from(x_field_shredded)], None)
2964                .unwrap(),
2965        ) as ArrayRef;
2966        let a_field_shredded = ShreddedVariantFieldArray::from_parts(
2967            Arc::new(a_value_array),
2968            Some(a_inner_typed_value),
2969            None,
2970        );
2971
2972        // Level 0: main typed_value struct containing a field
2973        let typed_value_fields = Fields::from(vec![Field::new(
2974            "a",
2975            a_field_shredded.data_type().clone(),
2976            true,
2977        )]);
2978        let typed_value_struct = StructArray::try_new(
2979            typed_value_fields,
2980            vec![ArrayRef::from(a_field_shredded)],
2981            None,
2982        )
2983        .unwrap();
2984
2985        // Build final VariantArray
2986        ArrayRef::from(VariantArray::from_parts(
2987            Arc::new(metadata_array),
2988            Arc::new(value_array),
2989            Some(Arc::new(typed_value_struct)),
2990            None,
2991        ))
2992    }
2993
2994    /// Create working depth 2 shredded test data for "a.b.x" paths
2995    /// This creates a 3-level nested shredded structure where:
2996    /// - Row 0: {"a": {"b": {"x": 100}}} with a.b.x shredded into typed_value
2997    /// - Row 1: {"a": {"b": {"x": "bar"}}} with type mismatch fallback
2998    /// - Row 2: {"a": {"b": {"y": 200}}} with missing field fallback
2999    fn create_depth_2_shredded_test_data_working() -> ArrayRef {
3000        // Create metadata following the working pattern
3001        let (metadata, _) = {
3002            // Create deeply nested structure: {"a": {"b": {"x": 100}}}
3003            let mut builder = parquet_variant::VariantBuilder::new();
3004            let mut obj = builder.new_object();
3005
3006            // Create the nested "a.b" structure
3007            let mut a_obj = obj.new_object("a");
3008            let mut b_obj = a_obj.new_object("b");
3009            b_obj.insert("x", Variant::Int32(100));
3010            b_obj.finish();
3011            a_obj.finish();
3012
3013            obj.finish();
3014            builder.finish()
3015        };
3016
3017        let metadata_array = BinaryViewArray::from_iter_values(std::iter::repeat_n(&metadata, 3));
3018
3019        // Create value arrays for fallback cases
3020        let empty_object_value = {
3021            let mut builder = parquet_variant::VariantBuilder::new();
3022            let obj = builder.new_object();
3023            obj.finish();
3024            let (_, value) = builder.finish();
3025            value
3026        };
3027
3028        // Simple fallback values - avoiding complex nested metadata
3029        let value_array = BinaryViewArray::from(vec![
3030            Some(empty_object_value.as_slice()), // Row 0: fully shredded
3031            Some(empty_object_value.as_slice()), // Row 1: fallback (simplified)
3032            Some(empty_object_value.as_slice()), // Row 2: fallback (simplified)
3033        ]);
3034
3035        // Create the deeply nested shredded structure: a.b.x
3036
3037        // Level 3: x field (deepest level)
3038        let x_typed_value = Int32Array::from(vec![Some(100), None, None]);
3039        let x_field_shredded =
3040            ShreddedVariantFieldArray::perfectly_shredded(Arc::new(x_typed_value) as ArrayRef);
3041
3042        // Level 2: b field containing x field + value field
3043        let b_value_data = {
3044            let mut builder = parquet_variant::VariantBuilder::new();
3045            let obj = builder.new_object();
3046            obj.finish();
3047            let (_, value) = builder.finish();
3048            value
3049        };
3050        let b_value_array = BinaryViewArray::from(vec![
3051            None,                          // Row 0: x is shredded
3052            Some(b_value_data.as_slice()), // Row 1: fallback for b.x="bar"
3053            Some(b_value_data.as_slice()), // Row 2: fallback for b.y=200
3054        ]);
3055
3056        let b_inner_fields = Fields::from(vec![Field::new(
3057            "x",
3058            x_field_shredded.data_type().clone(),
3059            true,
3060        )]);
3061        let b_inner_typed_value = Arc::new(
3062            StructArray::try_new(b_inner_fields, vec![ArrayRef::from(x_field_shredded)], None)
3063                .unwrap(),
3064        ) as ArrayRef;
3065        let b_field_shredded = ShreddedVariantFieldArray::from_parts(
3066            Arc::new(b_value_array),
3067            Some(b_inner_typed_value),
3068            None,
3069        );
3070
3071        // Level 1: a field containing b field + value field
3072        let a_value_data = {
3073            let mut builder = parquet_variant::VariantBuilder::new();
3074            let obj = builder.new_object();
3075            obj.finish();
3076            let (_, value) = builder.finish();
3077            value
3078        };
3079        let a_value_array = BinaryViewArray::from(vec![
3080            None,                          // Row 0: b is shredded
3081            Some(a_value_data.as_slice()), // Row 1: fallback for a.b.*
3082            Some(a_value_data.as_slice()), // Row 2: fallback for a.b.*
3083        ]);
3084
3085        let a_inner_fields = Fields::from(vec![Field::new(
3086            "b",
3087            b_field_shredded.data_type().clone(),
3088            true,
3089        )]);
3090        let a_inner_typed_value = Arc::new(
3091            StructArray::try_new(a_inner_fields, vec![ArrayRef::from(b_field_shredded)], None)
3092                .unwrap(),
3093        ) as ArrayRef;
3094        let a_field_shredded = ShreddedVariantFieldArray::from_parts(
3095            Arc::new(a_value_array),
3096            Some(a_inner_typed_value),
3097            None,
3098        );
3099
3100        // Level 0: main typed_value struct containing a field
3101        let typed_value_fields = Fields::from(vec![Field::new(
3102            "a",
3103            a_field_shredded.data_type().clone(),
3104            true,
3105        )]);
3106        let typed_value_struct = StructArray::try_new(
3107            typed_value_fields,
3108            vec![ArrayRef::from(a_field_shredded)],
3109            None,
3110        )
3111        .unwrap();
3112
3113        // Build final VariantArray
3114        ArrayRef::from(VariantArray::from_parts(
3115            Arc::new(metadata_array),
3116            Arc::new(value_array),
3117            Some(Arc::new(typed_value_struct)),
3118            None,
3119        ))
3120    }
3121
3122    #[test]
3123    fn test_field_path_non_struct_returns_missing_path_step() {
3124        // Use the existing simple test data that has Int32 as typed_value
3125        let variant_array = perfectly_shredded_int32_variant_array();
3126
3127        for safe in [true, false] {
3128            let options = GetOptions {
3129                path: VariantPath::try_from("nonexistent_field").unwrap(),
3130                as_type: Some(Arc::new(Field::new("result", DataType::Int32, true))),
3131                cast_options: CastOptions {
3132                    safe,
3133                    ..Default::default()
3134                },
3135            };
3136
3137            let result_array = variant_get(&variant_array, options).unwrap();
3138            assert_eq!(result_array.len(), 3);
3139            assert!(result_array.is_null(0));
3140            assert!(result_array.is_null(1));
3141            assert!(result_array.is_null(2));
3142        }
3143    }
3144
3145    #[test]
3146    fn test_strict_cast_options_index_on_non_list_returns_null() {
3147        use arrow::compute::CastOptions;
3148        use arrow::datatypes::{DataType, Field};
3149        use parquet_variant::VariantPath;
3150        use std::sync::Arc;
3151
3152        // Use existing test data that has Int32 typed_value at the top level.
3153        let variant_array = perfectly_shredded_int32_variant_array();
3154        let options = GetOptions {
3155            path: VariantPath::from(0),
3156            as_type: Some(Arc::new(Field::new("result", DataType::Int32, true))),
3157            cast_options: CastOptions {
3158                safe: false,
3159                ..Default::default()
3160            },
3161        };
3162
3163        let variant_array_ref: Arc<dyn Array> = variant_array.clone();
3164        let result = variant_get(&variant_array_ref, options).unwrap();
3165
3166        assert_eq!(result.len(), 3);
3167        assert!(result.is_null(0));
3168        assert!(result.is_null(1));
3169        assert!(result.is_null(2));
3170    }
3171
3172    #[test]
3173    fn test_error_message_boolean_type_display() {
3174        let variant_array: ArrayRef = ArrayRef::from(VariantArray::from_iter([Some("abcd")]));
3175
3176        // Request Boolean with strict casting to force an error
3177        let options = GetOptions {
3178            path: VariantPath::default(),
3179            as_type: Some(Arc::new(Field::new("result", DataType::Boolean, true))),
3180            cast_options: CastOptions {
3181                safe: false,
3182                ..Default::default()
3183            },
3184        };
3185
3186        let err = variant_get(&variant_array, options).unwrap_err();
3187        let msg = err.to_string();
3188        assert!(msg.contains("Failed to extract primitive of type Boolean"));
3189    }
3190
3191    #[test]
3192    fn test_error_message_numeric_type_display() {
3193        let variant_array: ArrayRef = ArrayRef::from(VariantArray::from_iter([Some("abcd")]));
3194
3195        // Request Float32 with strict casting to force an error
3196        let options = GetOptions {
3197            path: VariantPath::default(),
3198            as_type: Some(Arc::new(Field::new("result", DataType::Float32, true))),
3199            cast_options: CastOptions {
3200                safe: false,
3201                ..Default::default()
3202            },
3203        };
3204
3205        let err = variant_get(&variant_array, options).unwrap_err();
3206        let msg = err.to_string();
3207        assert!(msg.contains("Failed to extract primitive of type Float32"));
3208    }
3209
3210    #[test]
3211    fn test_error_message_temporal_type_display() {
3212        let variant_array: ArrayRef = ArrayRef::from(VariantArray::from_iter([Some(false)]));
3213
3214        // Request Timestamp with strict casting to force an error
3215        let options = GetOptions {
3216            path: VariantPath::default(),
3217            as_type: Some(Arc::new(Field::new(
3218                "result",
3219                DataType::Timestamp(TimeUnit::Nanosecond, None),
3220                true,
3221            ))),
3222            cast_options: CastOptions {
3223                safe: false,
3224                ..Default::default()
3225            },
3226        };
3227
3228        let err = variant_get(&variant_array, options).unwrap_err();
3229        let msg = err.to_string();
3230        assert!(msg.contains("Failed to extract primitive of type Timestamp(ns)"));
3231    }
3232
3233    #[test]
3234    fn test_null_buffer_union_for_shredded_paths() {
3235        // Test that null buffers are properly unioned when traversing shredded paths
3236        // This test verifies scovich's null buffer union requirement
3237
3238        // Create a depth-1 shredded variant array where:
3239        // - The top-level variant array has some nulls
3240        // - The nested typed_value also has some nulls
3241        // - The result should be the union of both null buffers
3242
3243        let variant_array = create_depth_1_shredded_test_data_working();
3244
3245        // Get the field "x" which should union nulls from:
3246        // 1. The top-level variant array nulls
3247        // 2. The "a" field's typed_value nulls
3248        // 3. The "x" field's typed_value nulls
3249        let options = GetOptions {
3250            path: VariantPath::try_from("a.x").unwrap(),
3251            as_type: Some(Arc::new(Field::new("result", DataType::Int32, true))),
3252            cast_options: CastOptions::default(),
3253        };
3254
3255        let result = variant_get(&variant_array, options).unwrap();
3256
3257        // Verify the result length matches input
3258        assert_eq!(result.len(), variant_array.len());
3259
3260        // The null pattern should reflect the union of all ancestor nulls
3261        // Row 0: Should have valid data (path exists and is shredded as Int32)
3262        // Row 1: Should be null (due to type mismatch - "foo" can't cast to Int32)
3263        assert!(!result.is_null(0), "Row 0 should have valid Int32 data");
3264        assert!(
3265            result.is_null(1),
3266            "Row 1 should be null due to type casting failure"
3267        );
3268
3269        // Verify the actual values
3270        let int32_result = result.as_any().downcast_ref::<Int32Array>().unwrap();
3271        assert_eq!(int32_result.value(0), 55); // The valid Int32 value
3272    }
3273
3274    #[test]
3275    fn test_struct_null_mask_union_from_children() {
3276        // Test that struct null masks properly union nulls from children field extractions
3277        // This verifies scovich's concern about incomplete null masks in struct construction
3278
3279        // Create test data where some fields will fail type casting
3280        let json_strings = vec![
3281            r#"{"a": 42, "b": "hello"}"#, // Row 0: a=42 (castable to int), b="hello" (not castable to int)
3282            r#"{"a": "world", "b": 100}"#, // Row 1: a="world" (not castable to int), b=100 (castable to int)
3283            r#"{"a": 55, "b": 77}"#,       // Row 2: a=55 (castable to int), b=77 (castable to int)
3284        ];
3285
3286        let string_array: Arc<dyn arrow::array::Array> = Arc::new(StringArray::from(json_strings));
3287        let variant_array = json_to_variant(&string_array).unwrap();
3288
3289        // Request extraction as a struct with both fields as Int32
3290        // This should create child arrays where some fields are null due to casting failures
3291        let struct_fields = Fields::from(vec![
3292            Field::new("a", DataType::Int32, true),
3293            Field::new("b", DataType::Int32, true),
3294        ]);
3295        let struct_type = DataType::Struct(struct_fields);
3296
3297        let options = GetOptions {
3298            path: VariantPath::default(), // Extract the whole object as struct
3299            as_type: Some(Arc::new(Field::new("result", struct_type, true))),
3300            cast_options: CastOptions::default(),
3301        };
3302
3303        let variant_array_ref = ArrayRef::from(variant_array);
3304        let result = variant_get(&variant_array_ref, options).unwrap();
3305
3306        // Verify the result is a StructArray
3307        let struct_result = result.as_struct();
3308        assert_eq!(struct_result.len(), 3);
3309
3310        // Get the individual field arrays
3311        let field_a = struct_result
3312            .column(0)
3313            .as_any()
3314            .downcast_ref::<Int32Array>()
3315            .unwrap();
3316        let field_b = struct_result
3317            .column(1)
3318            .as_any()
3319            .downcast_ref::<Int32Array>()
3320            .unwrap();
3321
3322        // Verify field values and nulls
3323        // Row 0: a=42 (valid), b=null (casting failure)
3324        assert!(!field_a.is_null(0));
3325        assert_eq!(field_a.value(0), 42);
3326        assert!(field_b.is_null(0)); // "hello" can't cast to int
3327
3328        // Row 1: a=null (casting failure), b=100 (valid)
3329        assert!(field_a.is_null(1)); // "world" can't cast to int
3330        assert!(!field_b.is_null(1));
3331        assert_eq!(field_b.value(1), 100);
3332
3333        // Row 2: a=55 (valid), b=77 (valid)
3334        assert!(!field_a.is_null(2));
3335        assert_eq!(field_a.value(2), 55);
3336        assert!(!field_b.is_null(2));
3337        assert_eq!(field_b.value(2), 77);
3338
3339        // Verify the struct-level null mask properly unions child nulls
3340        // The struct should NOT be null in any row because each row has at least one valid field
3341        // (This tests that we're not incorrectly making the entire struct null when children fail)
3342        assert!(!struct_result.is_null(0)); // Has valid field 'a'
3343        assert!(!struct_result.is_null(1)); // Has valid field 'b'
3344        assert!(!struct_result.is_null(2)); // Has both valid fields
3345    }
3346
3347    #[test]
3348    fn test_field_nullability_preservation() {
3349        // Test that field nullability from GetOptions.as_type is preserved in the result
3350
3351        let json_strings = vec![
3352            r#"{"x": 42}"#,                  // Row 0: Valid int that should convert to Int32
3353            r#"{"x": "not_a_number"}"#,      // Row 1: String that can't cast to Int32
3354            r#"{"x": null}"#,                // Row 2: Explicit null value
3355            r#"{"x": "hello"}"#,             // Row 3: Another string (wrong type)
3356            r#"{"y": 100}"#,                 // Row 4: Missing "x" field (SQL NULL case)
3357            r#"{"x": 127}"#, // Row 5: Small int (could be Int8, widening cast candidate)
3358            r#"{"x": 32767}"#, // Row 6: Medium int (could be Int16, widening cast candidate)
3359            r#"{"x": 2147483647}"#, // Row 7: Max Int32 value (fits in Int32)
3360            r#"{"x": 9223372036854775807}"#, // Row 8: Large Int64 value (cannot convert to Int32)
3361        ];
3362
3363        let string_array: Arc<dyn arrow::array::Array> = Arc::new(StringArray::from(json_strings));
3364        let variant_array = json_to_variant(&string_array).unwrap();
3365
3366        // Test 1: nullable field (should allow nulls from cast failures)
3367        let nullable_field = Arc::new(Field::new("result", DataType::Int32, true));
3368        let options_nullable = GetOptions {
3369            path: VariantPath::try_from("x").unwrap(),
3370            as_type: Some(nullable_field.clone()),
3371            cast_options: CastOptions::default(),
3372        };
3373
3374        let variant_array_ref = ArrayRef::from(variant_array);
3375        let result_nullable = variant_get(&variant_array_ref, options_nullable).unwrap();
3376
3377        // Verify we get an Int32Array with nulls for cast failures
3378        let int32_result = result_nullable
3379            .as_any()
3380            .downcast_ref::<Int32Array>()
3381            .unwrap();
3382        assert_eq!(int32_result.len(), 9);
3383
3384        // Row 0: 42 converts successfully to Int32
3385        assert!(!int32_result.is_null(0));
3386        assert_eq!(int32_result.value(0), 42);
3387
3388        // Row 1: "not_a_number" fails to convert -> NULL
3389        assert!(int32_result.is_null(1));
3390
3391        // Row 2: explicit null value -> NULL
3392        assert!(int32_result.is_null(2));
3393
3394        // Row 3: "hello" (wrong type) fails to convert -> NULL
3395        assert!(int32_result.is_null(3));
3396
3397        // Row 4: missing "x" field (SQL NULL case) -> NULL
3398        assert!(int32_result.is_null(4));
3399
3400        // Row 5: 127 (small int, potential Int8 -> Int32 widening)
3401        // Current behavior: JSON parses to Int8, should convert to Int32
3402        assert!(!int32_result.is_null(5));
3403        assert_eq!(int32_result.value(5), 127);
3404
3405        // Row 6: 32767 (medium int, potential Int16 -> Int32 widening)
3406        // Current behavior: JSON parses to Int16, should convert to Int32
3407        assert!(!int32_result.is_null(6));
3408        assert_eq!(int32_result.value(6), 32767);
3409
3410        // Row 7: 2147483647 (max Int32, fits exactly)
3411        // Current behavior: Should convert successfully
3412        assert!(!int32_result.is_null(7));
3413        assert_eq!(int32_result.value(7), 2147483647);
3414
3415        // Row 8: 9223372036854775807 (large Int64, cannot fit in Int32)
3416        // Current behavior: Should fail conversion -> NULL
3417        assert!(int32_result.is_null(8));
3418
3419        // Test 2: non-nullable field (behavior should be the same with safe casting)
3420        let non_nullable_field = Arc::new(Field::new("result", DataType::Int32, false));
3421        let options_non_nullable = GetOptions {
3422            path: VariantPath::try_from("x").unwrap(),
3423            as_type: Some(non_nullable_field.clone()),
3424            cast_options: CastOptions::default(), // safe=true by default
3425        };
3426
3427        // Create variant array again since we moved it
3428        let variant_array_2 = json_to_variant(&string_array).unwrap();
3429        let variant_array_ref_2 = ArrayRef::from(variant_array_2);
3430        let result_non_nullable = variant_get(&variant_array_ref_2, options_non_nullable).unwrap();
3431        let int32_result_2 = result_non_nullable
3432            .as_any()
3433            .downcast_ref::<Int32Array>()
3434            .unwrap();
3435
3436        // Even with a non-nullable field, safe casting should still produce nulls for failures
3437        assert_eq!(int32_result_2.len(), 9);
3438
3439        // Row 0: 42 converts successfully to Int32
3440        assert!(!int32_result_2.is_null(0));
3441        assert_eq!(int32_result_2.value(0), 42);
3442
3443        // Rows 1-4: All should be null due to safe casting behavior
3444        // (non-nullable field specification doesn't override safe casting behavior)
3445        assert!(int32_result_2.is_null(1)); // "not_a_number"
3446        assert!(int32_result_2.is_null(2)); // explicit null
3447        assert!(int32_result_2.is_null(3)); // "hello"
3448        assert!(int32_result_2.is_null(4)); // missing field
3449
3450        // Rows 5-7: These should also convert successfully (numeric widening/fitting)
3451        assert!(!int32_result_2.is_null(5)); // 127 (Int8 -> Int32)
3452        assert_eq!(int32_result_2.value(5), 127);
3453        assert!(!int32_result_2.is_null(6)); // 32767 (Int16 -> Int32)
3454        assert_eq!(int32_result_2.value(6), 32767);
3455        assert!(!int32_result_2.is_null(7)); // 2147483647 (fits in Int32)
3456        assert_eq!(int32_result_2.value(7), 2147483647);
3457
3458        // Row 8: Large Int64 should fail conversion -> NULL
3459        assert!(int32_result_2.is_null(8)); // 9223372036854775807 (too large for Int32)
3460    }
3461
3462    #[test]
3463    fn test_struct_extraction_subset_superset_schema_perfectly_shredded() {
3464        // Create variant with diverse null patterns and empty objects
3465        let variant_array = create_comprehensive_shredded_variant();
3466
3467        // Request struct with fields "a", "b", "d" (skip existing "c", add missing "d")
3468        let struct_fields = Fields::from(vec![
3469            Field::new("a", DataType::Int32, true),
3470            Field::new("b", DataType::Int32, true),
3471            Field::new("d", DataType::Int32, true),
3472        ]);
3473        let struct_type = DataType::Struct(struct_fields);
3474
3475        let options = GetOptions {
3476            path: VariantPath::default(),
3477            as_type: Some(Arc::new(Field::new("result", struct_type, true))),
3478            cast_options: CastOptions::default(),
3479        };
3480
3481        let result = variant_get(&variant_array, options).unwrap();
3482
3483        // Verify the result is a StructArray with 3 fields and 5 rows
3484        let struct_result = result.as_any().downcast_ref::<StructArray>().unwrap();
3485        assert_eq!(struct_result.len(), 5);
3486        assert_eq!(struct_result.num_columns(), 3);
3487
3488        let field_a = struct_result
3489            .column(0)
3490            .as_any()
3491            .downcast_ref::<Int32Array>()
3492            .unwrap();
3493        let field_b = struct_result
3494            .column(1)
3495            .as_any()
3496            .downcast_ref::<Int32Array>()
3497            .unwrap();
3498        let field_d = struct_result
3499            .column(2)
3500            .as_any()
3501            .downcast_ref::<Int32Array>()
3502            .unwrap();
3503
3504        // Row 0: Normal values {"a": 1, "b": 2, "c": 3} → {a: 1, b: 2, d: NULL}
3505        assert!(!struct_result.is_null(0));
3506        assert_eq!(field_a.value(0), 1);
3507        assert_eq!(field_b.value(0), 2);
3508        assert!(field_d.is_null(0)); // Missing field "d"
3509
3510        // Row 1: Top-level NULL → struct-level NULL
3511        assert!(struct_result.is_null(1));
3512
3513        // Row 2: Field "a" missing → {a: NULL, b: 2, d: NULL}
3514        assert!(!struct_result.is_null(2));
3515        assert!(field_a.is_null(2)); // Missing field "a"
3516        assert_eq!(field_b.value(2), 2);
3517        assert!(field_d.is_null(2)); // Missing field "d"
3518
3519        // Row 3: Field "b" missing → {a: 1, b: NULL, d: NULL}
3520        assert!(!struct_result.is_null(3));
3521        assert_eq!(field_a.value(3), 1);
3522        assert!(field_b.is_null(3)); // Missing field "b"
3523        assert!(field_d.is_null(3)); // Missing field "d"
3524
3525        // Row 4: Empty object {} → {a: NULL, b: NULL, d: NULL}
3526        assert!(!struct_result.is_null(4));
3527        assert!(field_a.is_null(4)); // Empty object
3528        assert!(field_b.is_null(4)); // Empty object
3529        assert!(field_d.is_null(4)); // Missing field "d"
3530    }
3531
3532    #[test]
3533    fn test_nested_struct_extraction_perfectly_shredded() {
3534        // Create nested variant with diverse null patterns
3535        let variant_array = create_comprehensive_nested_shredded_variant();
3536        println!("variant_array: {variant_array:?}");
3537
3538        // Request 3-level nested struct type {"outer": {"inner": INT}}
3539        let inner_field = Field::new("inner", DataType::Int32, true);
3540        let inner_type = DataType::Struct(Fields::from(vec![inner_field]));
3541        let outer_field = Field::new("outer", inner_type, true);
3542        let result_type = DataType::Struct(Fields::from(vec![outer_field]));
3543
3544        let options = GetOptions {
3545            path: VariantPath::default(),
3546            as_type: Some(Arc::new(Field::new("result", result_type, true))),
3547            cast_options: CastOptions::default(),
3548        };
3549
3550        let result = variant_get(&variant_array, options).unwrap();
3551        println!("result: {result:?}");
3552
3553        // Verify the result is a StructArray with "outer" field and 4 rows
3554        let outer_struct = result.as_any().downcast_ref::<StructArray>().unwrap();
3555        assert_eq!(outer_struct.len(), 4);
3556        assert_eq!(outer_struct.num_columns(), 1);
3557
3558        // Get the "inner" struct column
3559        let inner_struct = outer_struct
3560            .column(0)
3561            .as_any()
3562            .downcast_ref::<StructArray>()
3563            .unwrap();
3564        assert_eq!(inner_struct.num_columns(), 1);
3565
3566        // Get the "leaf" field (Int32 values)
3567        let leaf_field = inner_struct
3568            .column(0)
3569            .as_any()
3570            .downcast_ref::<Int32Array>()
3571            .unwrap();
3572
3573        // Row 0: Normal nested {"outer": {"inner": {"leaf": 42}}}
3574        assert!(!outer_struct.is_null(0));
3575        assert!(!inner_struct.is_null(0));
3576        assert_eq!(leaf_field.value(0), 42);
3577
3578        // Row 1: "inner" field missing → {outer: {inner: NULL}}
3579        assert!(!outer_struct.is_null(1));
3580        assert!(!inner_struct.is_null(1)); // outer exists, inner exists but leaf is NULL
3581        assert!(leaf_field.is_null(1)); // leaf field is NULL
3582
3583        // Row 2: "outer" field missing → {outer: NULL}
3584        assert!(!outer_struct.is_null(2));
3585        assert!(inner_struct.is_null(2)); // outer field is NULL
3586
3587        // Row 3: Top-level NULL → struct-level NULL
3588        assert!(outer_struct.is_null(3));
3589    }
3590
3591    #[test]
3592    fn test_path_based_null_masks_one_step() {
3593        // Create nested variant with diverse null patterns
3594        let variant_array = create_comprehensive_nested_shredded_variant();
3595
3596        // Extract "outer" field using path-based variant_get
3597        let path = VariantPath::try_from("outer").unwrap();
3598        let inner_field = Field::new("inner", DataType::Int32, true);
3599        let result_type = DataType::Struct(Fields::from(vec![inner_field]));
3600
3601        let options = GetOptions {
3602            path,
3603            as_type: Some(Arc::new(Field::new("result", result_type, true))),
3604            cast_options: CastOptions::default(),
3605        };
3606
3607        let result = variant_get(&variant_array, options).unwrap();
3608
3609        // Verify the result is a StructArray with "inner" field and 4 rows
3610        let outer_result = result.as_any().downcast_ref::<StructArray>().unwrap();
3611        assert_eq!(outer_result.len(), 4);
3612        assert_eq!(outer_result.num_columns(), 1);
3613
3614        // Get the "inner" field (Int32 values)
3615        let inner_field = outer_result
3616            .column(0)
3617            .as_any()
3618            .downcast_ref::<Int32Array>()
3619            .unwrap();
3620
3621        // Row 0: Normal nested {"outer": {"inner": 42}} → {"inner": 42}
3622        assert!(!outer_result.is_null(0));
3623        assert_eq!(inner_field.value(0), 42);
3624
3625        // Row 1: Inner field null {"outer": {"inner": null}} → {"inner": null}
3626        assert!(!outer_result.is_null(1));
3627        assert!(inner_field.is_null(1));
3628
3629        // Row 2: Outer field null {"outer": null} → null (entire struct is null)
3630        assert!(outer_result.is_null(2));
3631
3632        // Row 3: Top-level null → null (entire struct is null)
3633        assert!(outer_result.is_null(3));
3634    }
3635
3636    #[test]
3637    fn test_path_based_null_masks_two_steps() {
3638        // Create nested variant with diverse null patterns
3639        let variant_array = create_comprehensive_nested_shredded_variant();
3640
3641        // Extract "outer.inner" field using path-based variant_get
3642        let path = VariantPath::try_from("outer").unwrap().join("inner");
3643
3644        let options = GetOptions {
3645            path,
3646            as_type: Some(Arc::new(Field::new("result", DataType::Int32, true))),
3647            cast_options: CastOptions::default(),
3648        };
3649
3650        let result = variant_get(&variant_array, options).unwrap();
3651
3652        // Verify the result is an Int32Array with 4 rows
3653        let int_result = result.as_any().downcast_ref::<Int32Array>().unwrap();
3654        assert_eq!(int_result.len(), 4);
3655
3656        // Row 0: Normal nested {"outer": {"inner": 42}} → 42
3657        assert!(!int_result.is_null(0));
3658        assert_eq!(int_result.value(0), 42);
3659
3660        // Row 1: Inner field null {"outer": {"inner": null}} → null
3661        assert!(int_result.is_null(1));
3662
3663        // Row 2: Outer field null {"outer": null} → null (path traversal fails)
3664        assert!(int_result.is_null(2));
3665
3666        // Row 3: Top-level null → null (path traversal fails)
3667        assert!(int_result.is_null(3));
3668    }
3669
3670    #[test]
3671    fn test_struct_extraction_mixed_and_unshredded() {
3672        // Create a partially shredded variant (x shredded, y not)
3673        let variant_array = create_mixed_and_unshredded_variant();
3674
3675        // Request struct with both shredded and unshredded fields
3676        let struct_fields = Fields::from(vec![
3677            Field::new("x", DataType::Int32, true),
3678            Field::new("y", DataType::Int32, true),
3679        ]);
3680        let struct_type = DataType::Struct(struct_fields);
3681
3682        let options = GetOptions {
3683            path: VariantPath::default(),
3684            as_type: Some(Arc::new(Field::new("result", struct_type, true))),
3685            cast_options: CastOptions::default(),
3686        };
3687
3688        let result = variant_get(&variant_array, options).unwrap();
3689
3690        // Verify the mixed shredding works (should succeed with current implementation)
3691        let struct_result = result.as_any().downcast_ref::<StructArray>().unwrap();
3692        assert_eq!(struct_result.len(), 4);
3693        assert_eq!(struct_result.num_columns(), 2);
3694
3695        let field_x = struct_result
3696            .column(0)
3697            .as_any()
3698            .downcast_ref::<Int32Array>()
3699            .unwrap();
3700        let field_y = struct_result
3701            .column(1)
3702            .as_any()
3703            .downcast_ref::<Int32Array>()
3704            .unwrap();
3705
3706        // Row 0: {"x": 1, "y": 42} - x from shredded, y from value field
3707        assert_eq!(field_x.value(0), 1);
3708        assert_eq!(field_y.value(0), 42);
3709
3710        // Row 1: {"x": 2} - x from shredded, y missing (perfect shredding)
3711        assert_eq!(field_x.value(1), 2);
3712        assert!(field_y.is_null(1));
3713
3714        // Row 2: {"x": 3, "y": null} - x from shredded, y explicitly null in value
3715        assert_eq!(field_x.value(2), 3);
3716        assert!(field_y.is_null(2));
3717
3718        // Row 3: top-level null - entire struct row should be null
3719        assert!(struct_result.is_null(3));
3720    }
3721
3722    #[test]
3723    fn test_struct_row_builder_handles_unshredded_nested_structs() {
3724        // Create completely unshredded JSON variant (no typed_value at all)
3725        let json_strings = vec![
3726            r#"{"outer": {"inner": 42}}"#,
3727            r#"{"outer": {"inner": 100}}"#,
3728        ];
3729        let string_array: Arc<dyn Array> = Arc::new(StringArray::from(json_strings));
3730        let variant_array = json_to_variant(&string_array).unwrap();
3731
3732        // Request nested struct
3733        let inner_fields = Fields::from(vec![Field::new("inner", DataType::Int32, true)]);
3734        let inner_struct_type = DataType::Struct(inner_fields);
3735        let outer_fields = Fields::from(vec![Field::new("outer", inner_struct_type, true)]);
3736        let outer_struct_type = DataType::Struct(outer_fields);
3737
3738        let options = GetOptions {
3739            path: VariantPath::default(),
3740            as_type: Some(Arc::new(Field::new("result", outer_struct_type, true))),
3741            cast_options: CastOptions::default(),
3742        };
3743
3744        let variant_array_ref = ArrayRef::from(variant_array);
3745        let result = variant_get(&variant_array_ref, options).unwrap();
3746
3747        let outer_struct = result.as_struct();
3748        assert_eq!(outer_struct.len(), 2);
3749        assert_eq!(outer_struct.num_columns(), 1);
3750
3751        let inner_struct = outer_struct.column(0).as_struct();
3752        assert_eq!(inner_struct.num_columns(), 1);
3753
3754        let inner_values = inner_struct
3755            .column(0)
3756            .as_any()
3757            .downcast_ref::<Int32Array>()
3758            .unwrap();
3759        assert_eq!(inner_values.value(0), 42);
3760        assert_eq!(inner_values.value(1), 100);
3761    }
3762
3763    #[test]
3764    fn test_unshredded_struct_safe_cast_and_field_mismatches() {
3765        let json_strings = vec![r#"{"a": 1, "b": 2, "extra": 3}"#, "123", "{}"];
3766        let string_array: Arc<dyn Array> = Arc::new(StringArray::from(json_strings));
3767        let variant_array_ref = ArrayRef::from(json_to_variant(&string_array).unwrap());
3768
3769        let struct_fields = Fields::from(vec![
3770            Field::new("a", DataType::Int32, true),
3771            Field::new("b", DataType::Int32, true),
3772        ]);
3773        let options = GetOptions {
3774            path: VariantPath::default(),
3775            as_type: Some(Arc::new(Field::new(
3776                "result",
3777                DataType::Struct(struct_fields),
3778                true,
3779            ))),
3780            cast_options: CastOptions::default(),
3781        };
3782
3783        let result = variant_get(&variant_array_ref, options).unwrap();
3784        let struct_result = result.as_struct();
3785        let field_a = struct_result
3786            .column(0)
3787            .as_primitive::<arrow::datatypes::Int32Type>();
3788        let field_b = struct_result
3789            .column(1)
3790            .as_primitive::<arrow::datatypes::Int32Type>();
3791
3792        // Row 0 is an object, so the struct row is valid with extracted fields. Object fields
3793        // that aren't present in the requested struct are ignored.
3794        assert!(!struct_result.is_null(0));
3795        assert_eq!(field_a.value(0), 1);
3796        assert_eq!(field_b.value(0), 2);
3797
3798        // Row 1 is a scalar, so safe struct cast should produce a NULL struct row.
3799        assert!(struct_result.is_null(1));
3800        assert!(field_a.is_null(1));
3801        assert!(field_b.is_null(1));
3802
3803        // Row 2 is an empty object, so the struct row is valid with missing fields as NULL.
3804        assert!(!struct_result.is_null(2));
3805        assert!(field_a.is_null(2));
3806        assert!(field_b.is_null(2));
3807    }
3808
3809    #[test]
3810    fn test_unshredded_struct_missing_non_nullable_field_errors() {
3811        let string_array: Arc<dyn Array> = Arc::new(StringArray::from(vec![r#"{"a": 1}"#]));
3812        let variant_array_ref = ArrayRef::from(json_to_variant(&string_array).unwrap());
3813
3814        let struct_fields = Fields::from(vec![
3815            Field::new("a", DataType::Int32, false),
3816            Field::new("missing", DataType::Int32, false),
3817        ]);
3818        let options = GetOptions {
3819            path: VariantPath::default(),
3820            as_type: Some(Arc::new(Field::new(
3821                "result",
3822                DataType::Struct(struct_fields),
3823                true,
3824            ))),
3825            cast_options: CastOptions::default(),
3826        };
3827
3828        let err = variant_get(&variant_array_ref, options).unwrap_err();
3829        assert!(
3830            err.to_string()
3831                .contains("unmasked nulls for non-nullable StructArray field \"missing\""),
3832            "unexpected error: {err}"
3833        );
3834    }
3835
3836    #[test]
3837    fn test_unshredded_struct_strict_cast_non_object_errors() {
3838        let json_strings = vec![r#"{"a": 1, "b": 2}"#, "123"];
3839        let string_array: Arc<dyn Array> = Arc::new(StringArray::from(json_strings));
3840        let variant_array_ref = ArrayRef::from(json_to_variant(&string_array).unwrap());
3841
3842        let struct_fields = Fields::from(vec![
3843            Field::new("a", DataType::Int32, true),
3844            Field::new("b", DataType::Int32, true),
3845        ]);
3846        let options = GetOptions {
3847            path: VariantPath::default(),
3848            as_type: Some(Arc::new(Field::new(
3849                "result",
3850                DataType::Struct(struct_fields),
3851                true,
3852            ))),
3853            cast_options: CastOptions {
3854                safe: false,
3855                ..Default::default()
3856            },
3857        };
3858
3859        let err = variant_get(&variant_array_ref, options).unwrap_err();
3860        assert!(
3861            err.to_string()
3862                .contains("Failed to extract struct from variant")
3863        );
3864    }
3865
3866    /// Create comprehensive shredded variant with diverse null patterns and empty objects
3867    /// Rows: normal values, top-level null, missing field a, missing field b, empty object
3868    fn create_comprehensive_shredded_variant() -> ArrayRef {
3869        let (metadata, _) = {
3870            let mut builder = parquet_variant::VariantBuilder::new();
3871            let obj = builder.new_object();
3872            obj.finish();
3873            builder.finish()
3874        };
3875
3876        // Create null buffer for top-level nulls
3877        let nulls = NullBuffer::from(vec![
3878            true,  // row 0: normal values
3879            false, // row 1: top-level null
3880            true,  // row 2: missing field a
3881            true,  // row 3: missing field b
3882            true,  // row 4: empty object
3883        ]);
3884
3885        let metadata_array = BinaryViewArray::from_iter_values(std::iter::repeat_n(&metadata, 5));
3886
3887        // Create shredded fields with different null patterns
3888        // Field "a": present in rows 0,3 (missing in rows 1,2,4)
3889        let a_field_typed_value = Int32Array::from(vec![Some(1), None, None, Some(1), None]);
3890        let a_field_shredded = ShreddedVariantFieldArray::perfectly_shredded(Arc::new(
3891            a_field_typed_value,
3892        ) as ArrayRef);
3893
3894        // Field "b": present in rows 0,2 (missing in rows 1,3,4)
3895        let b_field_typed_value = Int32Array::from(vec![Some(2), None, Some(2), None, None]);
3896        let b_field_shredded = ShreddedVariantFieldArray::perfectly_shredded(Arc::new(
3897            b_field_typed_value,
3898        ) as ArrayRef);
3899
3900        // Field "c": present in row 0 only (missing in all other rows)
3901        let c_field_typed_value = Int32Array::from(vec![Some(3), None, None, None, None]);
3902        let c_field_shredded = ShreddedVariantFieldArray::perfectly_shredded(Arc::new(
3903            c_field_typed_value,
3904        ) as ArrayRef);
3905
3906        // Create main typed_value struct
3907        let typed_value_fields = Fields::from(vec![
3908            Field::new("a", a_field_shredded.data_type().clone(), true),
3909            Field::new("b", b_field_shredded.data_type().clone(), true),
3910            Field::new("c", c_field_shredded.data_type().clone(), true),
3911        ]);
3912        let typed_value_struct = StructArray::try_new(
3913            typed_value_fields,
3914            vec![
3915                ArrayRef::from(a_field_shredded),
3916                ArrayRef::from(b_field_shredded),
3917                ArrayRef::from(c_field_shredded),
3918            ],
3919            None,
3920        )
3921        .unwrap();
3922
3923        // Build final VariantArray with top-level nulls
3924        ArrayRef::from(VariantArray::perfectly_shredded(
3925            Arc::new(metadata_array),
3926            Arc::new(typed_value_struct),
3927            Some(nulls),
3928        ))
3929    }
3930
3931    /// Create comprehensive nested shredded variant with diverse null patterns
3932    /// Represents 3-level structure: variant -> outer -> inner (INT value)
3933    /// The shredding schema is: {"metadata": BINARY, "typed_value": {"outer": {"typed_value": {"inner": {"typed_value": INT}}}}}
3934    /// Rows: normal nested value, inner field null, outer field null, top-level null
3935    fn create_comprehensive_nested_shredded_variant() -> ArrayRef {
3936        // Create the inner level: contains typed_value with Int32 values
3937        // Row 0: has value 42, Row 1: inner null, Row 2: outer null, Row 3: top-level null
3938        let inner_typed_value = Int32Array::from(vec![Some(42), None, None, None]); // dummy value for row 2
3939        let inner =
3940            ShreddedVariantFieldArray::perfectly_shredded(Arc::new(inner_typed_value) as ArrayRef);
3941
3942        let outer_typed_value_nulls = NullBuffer::from(vec![
3943            true,  // row 0: inner struct exists with typed_value=42
3944            false, // row 1: inner field NULL
3945            false, // row 2: outer field NULL
3946            false, // row 3: top-level NULL
3947        ]);
3948        let outer_typed_value = StructArrayAssembler::new()
3949            .with_field("inner", ArrayRef::from(inner), false)
3950            .with_nulls(outer_typed_value_nulls)
3951            .build()
3952            .unwrap();
3953
3954        let outer =
3955            ShreddedVariantFieldArray::perfectly_shredded(Arc::new(outer_typed_value) as ArrayRef);
3956
3957        let typed_value_nulls = NullBuffer::from(vec![
3958            true,  // row 0: inner struct exists with typed_value=42
3959            true,  // row 1: inner field NULL
3960            false, // row 2: outer field NULL
3961            false, // row 3: top-level NULL
3962        ]);
3963        let typed_value = StructArrayAssembler::new()
3964            .with_field("outer", ArrayRef::from(outer), false)
3965            .with_nulls(typed_value_nulls)
3966            .build()
3967            .unwrap();
3968
3969        // Build final VariantArray with top-level nulls
3970        let metadata_array =
3971            BinaryViewArray::from_iter_values(std::iter::repeat_n(EMPTY_VARIANT_METADATA_BYTES, 4));
3972        let nulls = NullBuffer::from(vec![
3973            true,  // row 0: inner struct exists with typed_value=42
3974            true,  // row 1: inner field NULL
3975            true,  // row 2: outer field NULL
3976            false, // row 3: top-level NULL
3977        ]);
3978        ArrayRef::from(VariantArray::perfectly_shredded(
3979            Arc::new(metadata_array),
3980            Arc::new(typed_value),
3981            Some(nulls),
3982        ))
3983    }
3984
3985    /// Create variant with mixed shredding (spec-compliant) including null scenarios
3986    /// Field "x" is globally shredded, field "y" is never shredded
3987    fn create_mixed_and_unshredded_variant() -> ArrayRef {
3988        // Create spec-compliant mixed shredding:
3989        // - Field "x" is globally shredded (has typed_value column)
3990        // - Field "y" is never shredded (only appears in value field when present)
3991
3992        let (metadata, y_field_value) = {
3993            let mut builder = parquet_variant::VariantBuilder::new();
3994            let mut obj = builder.new_object();
3995            obj.insert("y", Variant::from(42));
3996            obj.finish();
3997            builder.finish()
3998        };
3999
4000        let metadata_array = BinaryViewArray::from_iter_values(std::iter::repeat_n(&metadata, 4));
4001
4002        // Value field contains objects with unshredded fields only (never contains "x")
4003        // Row 0: {"y": "foo"} - x is shredded out, y remains in value
4004        // Row 1: {} - both x and y are absent (perfect shredding for x, y missing)
4005        // Row 2: {"y": null} - x is shredded out, y explicitly null
4006        // Row 3: top-level null (encoded in VariantArray's null mask, but fields contain valid data)
4007
4008        let empty_object_value = {
4009            let mut builder = parquet_variant::VariantBuilder::new();
4010            builder.new_object().finish();
4011            let (_, value) = builder.finish();
4012            value
4013        };
4014
4015        let y_null_value = {
4016            let mut builder = parquet_variant::VariantBuilder::new();
4017            builder.new_object().with_field("y", Variant::Null).finish();
4018            let (_, value) = builder.finish();
4019            value
4020        };
4021
4022        let value_array = BinaryViewArray::from(vec![
4023            Some(y_field_value.as_slice()),      // Row 0: {"y": 42}
4024            Some(empty_object_value.as_slice()), // Row 1: {}
4025            Some(y_null_value.as_slice()),       // Row 2: {"y": null}
4026            Some(empty_object_value.as_slice()), // Row 3: top-level null (but value field contains valid data)
4027        ]);
4028
4029        // Create shredded field "x" (globally shredded - never appears in value field)
4030        // For top-level null row, the field still needs valid content (not null)
4031        let x_field_typed_value = Int32Array::from(vec![Some(1), Some(2), Some(3), Some(0)]);
4032        let x_field_shredded = ShreddedVariantFieldArray::perfectly_shredded(Arc::new(
4033            x_field_typed_value,
4034        ) as ArrayRef);
4035
4036        // Create main typed_value struct (only contains shredded fields)
4037        let typed_value_struct = StructArrayAssembler::new()
4038            .with_field("x", ArrayRef::from(x_field_shredded), false)
4039            .build()
4040            .unwrap();
4041
4042        // Build VariantArray with both value and typed_value (PartiallyShredded)
4043        // Top-level null is encoded in the main StructArray's null mask
4044        let variant_nulls = NullBuffer::from(vec![true, true, true, false]); // Row 3 is top-level null
4045        ArrayRef::from(VariantArray::from_parts(
4046            Arc::new(metadata_array),
4047            Arc::new(value_array),
4048            Some(Arc::new(typed_value_struct)),
4049            Some(variant_nulls),
4050        ))
4051    }
4052
4053    #[test]
4054    fn get_decimal32_rescaled_to_scale2() {
4055        // Build unshredded variant values with different scales
4056        let mut builder = crate::VariantArrayBuilder::new(5);
4057        builder.append_variant(VariantDecimal4::try_new(1234, 2).unwrap().into()); // 12.34
4058        builder.append_variant(VariantDecimal4::try_new(1234, 3).unwrap().into()); // 1.234
4059        builder.append_variant(VariantDecimal4::try_new(1234, 0).unwrap().into()); // 1234
4060        builder.append_null();
4061        builder.append_variant(
4062            VariantDecimal8::try_new((VariantDecimal4::MAX_UNSCALED_VALUE as i64) + 1, 3)
4063                .unwrap()
4064                .into(),
4065        ); // should fit into Decimal32
4066        let variant_array: ArrayRef = ArrayRef::from(builder.build());
4067
4068        let field = Field::new("result", DataType::Decimal32(9, 2), true);
4069        let options = GetOptions::new().with_as_type(Some(FieldRef::from(field)));
4070        let result = variant_get(&variant_array, options).unwrap();
4071        let result = result.as_any().downcast_ref::<Decimal32Array>().unwrap();
4072
4073        assert_eq!(result.precision(), 9);
4074        assert_eq!(result.scale(), 2);
4075        assert_eq!(result.value(0), 1234);
4076        assert_eq!(result.value(1), 123);
4077        assert_eq!(result.value(2), 123400);
4078        assert!(result.is_null(3));
4079        assert_eq!(
4080            result.value(4),
4081            VariantDecimal4::MAX_UNSCALED_VALUE / 10 + 1
4082        ); // should not be null as the final result fits into Decimal32
4083    }
4084
4085    #[test]
4086    fn get_decimal32_scale_down_rounding() {
4087        let variant_array: ArrayRef = ArrayRef::from(VariantArray::from_iter([
4088            Some(VariantDecimal4::try_new(1235, 0).unwrap()),
4089            Some(VariantDecimal4::try_new(1245, 0).unwrap()),
4090            Some(VariantDecimal4::try_new(-1235, 0).unwrap()),
4091            Some(VariantDecimal4::try_new(-1245, 0).unwrap()),
4092            Some(VariantDecimal4::try_new(1235, 2).unwrap()), // 12.35 rounded down to 10 for scale -1
4093            Some(VariantDecimal4::try_new(1235, 3).unwrap()), // 1.235 rounded down to 0 for scale -1
4094            Some(VariantDecimal4::try_new(5235, 3).unwrap()), // 5.235 rounded up to 10 for scale -1
4095        ]));
4096
4097        let field = Field::new("result", DataType::Decimal32(9, -1), true);
4098        let options = GetOptions::new().with_as_type(Some(FieldRef::from(field)));
4099        let result = variant_get(&variant_array, options).unwrap();
4100        let result = result.as_any().downcast_ref::<Decimal32Array>().unwrap();
4101
4102        assert_eq!(result.precision(), 9);
4103        assert_eq!(result.scale(), -1);
4104        assert_eq!(result.value(0), 124);
4105        assert_eq!(result.value(1), 125);
4106        assert_eq!(result.value(2), -124);
4107        assert_eq!(result.value(3), -125);
4108        assert_eq!(result.value(4), 1);
4109        assert!(result.is_valid(5));
4110        assert_eq!(result.value(5), 0);
4111        assert_eq!(result.value(6), 1);
4112    }
4113
4114    #[test]
4115    fn get_decimal32_large_scale_reduction() {
4116        let variant_array: ArrayRef = ArrayRef::from(VariantArray::from_iter([
4117            Some(VariantDecimal4::try_new(-VariantDecimal4::MAX_UNSCALED_VALUE, 0).unwrap()),
4118            Some(VariantDecimal4::try_new(VariantDecimal4::MAX_UNSCALED_VALUE, 0).unwrap()),
4119        ]));
4120
4121        let field = Field::new("result", DataType::Decimal32(9, -9), true);
4122        let options = GetOptions::new().with_as_type(Some(FieldRef::from(field)));
4123        let result = variant_get(&variant_array, options).unwrap();
4124        let result = result.as_any().downcast_ref::<Decimal32Array>().unwrap();
4125
4126        assert_eq!(result.precision(), 9);
4127        assert_eq!(result.scale(), -9);
4128        assert_eq!(result.value(0), -1);
4129        assert_eq!(result.value(1), 1);
4130
4131        let field = Field::new("result", DataType::Decimal32(9, -10), true);
4132        let options = GetOptions::new().with_as_type(Some(FieldRef::from(field)));
4133        let result = variant_get(&variant_array, options).unwrap();
4134        let result = result.as_any().downcast_ref::<Decimal32Array>().unwrap();
4135
4136        assert_eq!(result.precision(), 9);
4137        assert_eq!(result.scale(), -10);
4138        assert!(result.is_valid(0));
4139        assert_eq!(result.value(0), 0);
4140        assert!(result.is_valid(1));
4141        assert_eq!(result.value(1), 0);
4142    }
4143
4144    #[test]
4145    fn get_decimal32_precision_overflow_safe() {
4146        // Exceed Decimal32 after scaling and rounding
4147        let variant_array = ArrayRef::from(VariantArray::from_iter([
4148            Some(Variant::from(
4149                VariantDecimal4::try_new(VariantDecimal4::MAX_UNSCALED_VALUE, 0).unwrap(),
4150            )),
4151            // integer value round up overflows
4152            Some(Variant::from(
4153                VariantDecimal4::try_new(VariantDecimal4::MAX_UNSCALED_VALUE, 9).unwrap(),
4154            )),
4155            // Float inputs that exceed precision directly or after rounding to 1.00.
4156            Some(Variant::Float(1.1)),
4157            Some(Variant::Double(1.1)),
4158            Some(Variant::Float(0.999)),
4159            Some(Variant::Double(0.999)),
4160        ]));
4161
4162        let field = Field::new("result", DataType::Decimal32(2, 2), true);
4163        let options = GetOptions::new().with_as_type(Some(FieldRef::from(field)));
4164        let result = variant_get(&variant_array, options).unwrap();
4165        let result = result.as_any().downcast_ref::<Decimal32Array>().unwrap();
4166
4167        assert_eq!(result.null_count(), 6); // Even 1.00 exceeds precision 2.
4168    }
4169
4170    #[test]
4171    fn get_decimal32_precision_overflow_unsafe_errors() {
4172        for (value, kind) in [
4173            (
4174                VariantDecimal4::try_new(VariantDecimal4::MAX_UNSCALED_VALUE, 0)
4175                    .unwrap()
4176                    .into(),
4177                "Decimal4",
4178            ),
4179            (Variant::Float(1.1), "Float"),
4180            (Variant::Double(1.1), "Double"),
4181            (Variant::Float(0.999), "Float"),
4182            (Variant::Double(0.999), "Double"),
4183        ] {
4184            let variant_array = ArrayRef::from(VariantArray::from_iter([Some(value)]));
4185            let field = Field::new("result", DataType::Decimal32(2, 2), true);
4186            let options = GetOptions::new()
4187                .with_as_type(Some(FieldRef::from(field)))
4188                .with_cast_options(CastOptions {
4189                    safe: false,
4190                    ..Default::default()
4191                });
4192            let err = variant_get(&variant_array, options).unwrap_err();
4193            assert!(err.to_string().contains(&format!(
4194                "Failed to cast to Decimal32(precision=2, scale=2) from variant {kind}"
4195            )));
4196        }
4197    }
4198
4199    #[test]
4200    fn get_decimal64_rescaled_to_scale2() {
4201        let mut builder = crate::VariantArrayBuilder::new(5);
4202        builder.append_variant(VariantDecimal8::try_new(1234, 2).unwrap().into()); // 12.34
4203        builder.append_variant(VariantDecimal8::try_new(1234, 3).unwrap().into()); // 1.234
4204        builder.append_variant(VariantDecimal8::try_new(1234, 0).unwrap().into()); // 1234
4205        builder.append_null();
4206        builder.append_variant(
4207            VariantDecimal16::try_new((VariantDecimal8::MAX_UNSCALED_VALUE as i128) + 1, 3)
4208                .unwrap()
4209                .into(),
4210        ); // should fit into Decimal64
4211        let variant_array: ArrayRef = ArrayRef::from(builder.build());
4212
4213        let field = Field::new("result", DataType::Decimal64(18, 2), true);
4214        let options = GetOptions::new().with_as_type(Some(FieldRef::from(field)));
4215        let result = variant_get(&variant_array, options).unwrap();
4216        let result = result.as_any().downcast_ref::<Decimal64Array>().unwrap();
4217
4218        assert_eq!(result.precision(), 18);
4219        assert_eq!(result.scale(), 2);
4220        assert_eq!(result.value(0), 1234);
4221        assert_eq!(result.value(1), 123);
4222        assert_eq!(result.value(2), 123400);
4223        assert!(result.is_null(3));
4224        assert_eq!(
4225            result.value(4),
4226            VariantDecimal8::MAX_UNSCALED_VALUE / 10 + 1
4227        ); // should not be null as the final result fits into Decimal64
4228    }
4229
4230    #[test]
4231    fn get_decimal64_scale_down_rounding() {
4232        let variant_array: ArrayRef = ArrayRef::from(VariantArray::from_iter([
4233            Some(VariantDecimal8::try_new(1235, 0).unwrap()),
4234            Some(VariantDecimal8::try_new(1245, 0).unwrap()),
4235            Some(VariantDecimal8::try_new(-1235, 0).unwrap()),
4236            Some(VariantDecimal8::try_new(-1245, 0).unwrap()),
4237            Some(VariantDecimal8::try_new(1235, 2).unwrap()), // 12.35 rounded down to 10 for scale -1
4238            Some(VariantDecimal8::try_new(1235, 3).unwrap()), // 1.235 rounded down to 0 for scale -1
4239            Some(VariantDecimal8::try_new(5235, 3).unwrap()), // 5.235 rounded up to 10 for scale -1
4240        ]));
4241
4242        let field = Field::new("result", DataType::Decimal64(18, -1), true);
4243        let options = GetOptions::new().with_as_type(Some(FieldRef::from(field)));
4244        let result = variant_get(&variant_array, options).unwrap();
4245        let result = result.as_any().downcast_ref::<Decimal64Array>().unwrap();
4246
4247        assert_eq!(result.precision(), 18);
4248        assert_eq!(result.scale(), -1);
4249        assert_eq!(result.value(0), 124);
4250        assert_eq!(result.value(1), 125);
4251        assert_eq!(result.value(2), -124);
4252        assert_eq!(result.value(3), -125);
4253        assert_eq!(result.value(4), 1);
4254        assert!(result.is_valid(5));
4255        assert_eq!(result.value(5), 0);
4256        assert_eq!(result.value(6), 1);
4257    }
4258
4259    #[test]
4260    fn get_decimal64_large_scale_reduction() {
4261        let variant_array: ArrayRef = ArrayRef::from(VariantArray::from_iter([
4262            Some(VariantDecimal8::try_new(-VariantDecimal8::MAX_UNSCALED_VALUE, 0).unwrap()),
4263            Some(VariantDecimal8::try_new(VariantDecimal8::MAX_UNSCALED_VALUE, 0).unwrap()),
4264        ]));
4265
4266        let field = Field::new("result", DataType::Decimal64(18, -18), true);
4267        let options = GetOptions::new().with_as_type(Some(FieldRef::from(field)));
4268        let result = variant_get(&variant_array, options).unwrap();
4269        let result = result.as_any().downcast_ref::<Decimal64Array>().unwrap();
4270
4271        assert_eq!(result.precision(), 18);
4272        assert_eq!(result.scale(), -18);
4273        assert_eq!(result.value(0), -1);
4274        assert_eq!(result.value(1), 1);
4275
4276        let field = Field::new("result", DataType::Decimal64(18, -19), true);
4277        let options = GetOptions::new().with_as_type(Some(FieldRef::from(field)));
4278        let result = variant_get(&variant_array, options).unwrap();
4279        let result = result.as_any().downcast_ref::<Decimal64Array>().unwrap();
4280
4281        assert_eq!(result.precision(), 18);
4282        assert_eq!(result.scale(), -19);
4283        assert!(result.is_valid(0));
4284        assert_eq!(result.value(0), 0);
4285        assert!(result.is_valid(1));
4286        assert_eq!(result.value(1), 0);
4287    }
4288
4289    #[test]
4290    fn get_decimal64_precision_overflow_safe() {
4291        // Exceed Decimal64 after scaling and rounding
4292        let variant_array: ArrayRef = ArrayRef::from(VariantArray::from_iter([
4293            Some(VariantDecimal8::try_new(VariantDecimal8::MAX_UNSCALED_VALUE, 0).unwrap()),
4294            // integer value round up overflows
4295            Some(VariantDecimal8::try_new(VariantDecimal8::MAX_UNSCALED_VALUE, 18).unwrap()),
4296        ]));
4297
4298        let field = Field::new("result", DataType::Decimal64(2, 2), true);
4299        let options = GetOptions::new().with_as_type(Some(FieldRef::from(field)));
4300        let result = variant_get(&variant_array, options).unwrap();
4301        let result = result.as_any().downcast_ref::<Decimal64Array>().unwrap();
4302
4303        assert!(result.is_null(0));
4304        assert!(result.is_null(1));
4305    }
4306
4307    #[test]
4308    fn get_decimal64_precision_overflow_unsafe_errors() {
4309        let variant_array: ArrayRef = ArrayRef::from(VariantArray::from_iter([Some(
4310            VariantDecimal8::try_new(VariantDecimal8::MAX_UNSCALED_VALUE, 0).unwrap(),
4311        )]));
4312
4313        let field = Field::new("result", DataType::Decimal64(18, 2), true);
4314        let cast_options = CastOptions {
4315            safe: false,
4316            ..Default::default()
4317        };
4318        let options = GetOptions::new()
4319            .with_as_type(Some(FieldRef::from(field)))
4320            .with_cast_options(cast_options);
4321        let err = variant_get(&variant_array, options).unwrap_err();
4322
4323        assert!(
4324            err.to_string().contains(
4325                "Failed to cast to Decimal64(precision=18, scale=2) from variant Decimal8"
4326            )
4327        );
4328    }
4329
4330    #[test]
4331    fn get_decimal128_rescaled_to_scale2() {
4332        let variant_array: ArrayRef = ArrayRef::from(VariantArray::from_iter([
4333            Some(VariantDecimal16::try_new(1234, 2).unwrap()),
4334            Some(VariantDecimal16::try_new(1234, 3).unwrap()),
4335            Some(VariantDecimal16::try_new(1234, 0).unwrap()),
4336            None,
4337        ]));
4338
4339        let field = Field::new("result", DataType::Decimal128(38, 2), true);
4340        let options = GetOptions::new().with_as_type(Some(FieldRef::from(field)));
4341        let result = variant_get(&variant_array, options).unwrap();
4342        let result = result.as_any().downcast_ref::<Decimal128Array>().unwrap();
4343
4344        assert_eq!(result.precision(), 38);
4345        assert_eq!(result.scale(), 2);
4346        assert_eq!(result.value(0), 1234);
4347        assert_eq!(result.value(1), 123);
4348        assert_eq!(result.value(2), 123400);
4349        assert!(result.is_null(3));
4350    }
4351
4352    #[test]
4353    fn get_decimal128_scale_down_rounding() {
4354        let variant_array: ArrayRef = ArrayRef::from(VariantArray::from_iter([
4355            Some(VariantDecimal16::try_new(1235, 0).unwrap()),
4356            Some(VariantDecimal16::try_new(1245, 0).unwrap()),
4357            Some(VariantDecimal16::try_new(-1235, 0).unwrap()),
4358            Some(VariantDecimal16::try_new(-1245, 0).unwrap()),
4359            Some(VariantDecimal16::try_new(1235, 2).unwrap()), // 12.35 rounded down to 10 for scale -1
4360            Some(VariantDecimal16::try_new(1235, 3).unwrap()), // 1.235 rounded down to 0 for scale -1
4361            Some(VariantDecimal16::try_new(5235, 3).unwrap()), // 5.235 rounded up to 10 for scale -1
4362        ]));
4363
4364        let field = Field::new("result", DataType::Decimal128(38, -1), true);
4365        let options = GetOptions::new().with_as_type(Some(FieldRef::from(field)));
4366        let result = variant_get(&variant_array, options).unwrap();
4367        let result = result.as_any().downcast_ref::<Decimal128Array>().unwrap();
4368
4369        assert_eq!(result.precision(), 38);
4370        assert_eq!(result.scale(), -1);
4371        assert_eq!(result.value(0), 124);
4372        assert_eq!(result.value(1), 125);
4373        assert_eq!(result.value(2), -124);
4374        assert_eq!(result.value(3), -125);
4375        assert_eq!(result.value(4), 1);
4376        assert!(result.is_valid(5));
4377        assert_eq!(result.value(5), 0);
4378        assert_eq!(result.value(6), 1);
4379    }
4380
4381    #[test]
4382    fn get_decimal128_precision_overflow_safe() {
4383        // Exceed Decimal128 after scaling and rounding
4384        let variant_array: ArrayRef = ArrayRef::from(VariantArray::from_iter([
4385            Some(VariantDecimal16::try_new(VariantDecimal16::MAX_UNSCALED_VALUE, 0).unwrap()),
4386            // integer value round up overflows
4387            Some(VariantDecimal16::try_new(VariantDecimal16::MAX_UNSCALED_VALUE, 38).unwrap()),
4388        ]));
4389
4390        let field = Field::new("result", DataType::Decimal128(2, 2), true);
4391        let options = GetOptions::new().with_as_type(Some(FieldRef::from(field)));
4392        let result = variant_get(&variant_array, options).unwrap();
4393        let result = result.as_any().downcast_ref::<Decimal128Array>().unwrap();
4394
4395        assert!(result.is_null(0));
4396        assert!(result.is_null(1)); // should overflow because 1.00 does not fit into precision (2)
4397    }
4398
4399    #[test]
4400    fn get_decimal128_precision_overflow_unsafe_errors() {
4401        let variant_array: ArrayRef = ArrayRef::from(VariantArray::from_iter([Some(
4402            VariantDecimal16::try_new(VariantDecimal16::MAX_UNSCALED_VALUE, 0).unwrap(),
4403        )]));
4404
4405        let field = Field::new("result", DataType::Decimal128(38, 2), true);
4406        let cast_options = CastOptions {
4407            safe: false,
4408            ..Default::default()
4409        };
4410        let options = GetOptions::new()
4411            .with_as_type(Some(FieldRef::from(field)))
4412            .with_cast_options(cast_options);
4413        let err = variant_get(&variant_array, options).unwrap_err();
4414
4415        assert!(err.to_string().contains(
4416            "Failed to cast to Decimal128(precision=38, scale=2) from variant Decimal16"
4417        ));
4418    }
4419
4420    #[test]
4421    fn get_decimal256_rescaled_to_scale2() {
4422        // Build unshredded variant values with different scales using Decimal16 source
4423        let variant_array: ArrayRef = ArrayRef::from(VariantArray::from_iter([
4424            Some(VariantDecimal16::try_new(1234, 2).unwrap()), // 12.34
4425            Some(VariantDecimal16::try_new(1234, 3).unwrap()), // 1.234
4426            Some(VariantDecimal16::try_new(1234, 0).unwrap()), // 1234
4427            None,
4428        ]));
4429
4430        let field = Field::new("result", DataType::Decimal256(76, 2), true);
4431        let options = GetOptions::new().with_as_type(Some(FieldRef::from(field)));
4432        let result = variant_get(&variant_array, options).unwrap();
4433        let result = result.as_any().downcast_ref::<Decimal256Array>().unwrap();
4434
4435        assert_eq!(result.precision(), 76);
4436        assert_eq!(result.scale(), 2);
4437        assert_eq!(result.value(0), i256::from_i128(1234));
4438        assert_eq!(result.value(1), i256::from_i128(123));
4439        assert_eq!(result.value(2), i256::from_i128(123400));
4440        assert!(result.is_null(3));
4441    }
4442
4443    #[test]
4444    fn get_decimal256_scale_down_rounding() {
4445        let variant_array: ArrayRef = ArrayRef::from(VariantArray::from_iter([
4446            Some(VariantDecimal16::try_new(1235, 0).unwrap()),
4447            Some(VariantDecimal16::try_new(1245, 0).unwrap()),
4448            Some(VariantDecimal16::try_new(-1235, 0).unwrap()),
4449            Some(VariantDecimal16::try_new(-1245, 0).unwrap()),
4450            Some(VariantDecimal16::try_new(1235, 2).unwrap()), // 12.35 rounded down to 10 for scale -1
4451            Some(VariantDecimal16::try_new(1235, 3).unwrap()), // 1.235 rounded down to 0 for scale -1
4452            Some(VariantDecimal16::try_new(5235, 3).unwrap()), // 5.235 rounded up to 10 for scale -1
4453        ]));
4454
4455        let field = Field::new("result", DataType::Decimal256(76, -1), true);
4456        let options = GetOptions::new().with_as_type(Some(FieldRef::from(field)));
4457        let result = variant_get(&variant_array, options).unwrap();
4458        let result = result.as_any().downcast_ref::<Decimal256Array>().unwrap();
4459
4460        assert_eq!(result.precision(), 76);
4461        assert_eq!(result.scale(), -1);
4462        assert_eq!(result.value(0), i256::from_i128(124));
4463        assert_eq!(result.value(1), i256::from_i128(125));
4464        assert_eq!(result.value(2), i256::from_i128(-124));
4465        assert_eq!(result.value(3), i256::from_i128(-125));
4466        assert_eq!(result.value(4), i256::from_i128(1));
4467        assert!(result.is_valid(5));
4468        assert_eq!(result.value(5), i256::from_i128(0));
4469        assert_eq!(result.value(6), i256::from_i128(1));
4470    }
4471
4472    #[test]
4473    fn get_decimal256_precision_overflow_safe() {
4474        // Exceed Decimal128 max precision (38) after scaling
4475        let variant_array: ArrayRef = ArrayRef::from(VariantArray::from_iter([
4476            Some(VariantDecimal16::try_new(VariantDecimal16::MAX_UNSCALED_VALUE, 1).unwrap()),
4477            Some(VariantDecimal16::try_new(VariantDecimal16::MAX_UNSCALED_VALUE, 0).unwrap()),
4478        ]));
4479
4480        let field = Field::new("result", DataType::Decimal256(76, 39), true);
4481        let options = GetOptions::new().with_as_type(Some(FieldRef::from(field)));
4482        let result = variant_get(&variant_array, options).unwrap();
4483        let result = result.as_any().downcast_ref::<Decimal256Array>().unwrap();
4484
4485        // Input is Decimal16 with integer = 10^38-1 and scale = 1, target scale = 39
4486        // So expected integer is (10^38-1) * 10^(39-1) = (10^38-1) * 10^38
4487        let base = i256::from_i128(10);
4488        let factor = base.checked_pow(38).unwrap();
4489        let expected = i256::from_i128(VariantDecimal16::MAX_UNSCALED_VALUE)
4490            .checked_mul(factor)
4491            .unwrap();
4492        assert_eq!(result.value(0), expected);
4493        assert!(result.is_null(1));
4494    }
4495
4496    #[test]
4497    fn get_decimal256_precision_overflow_unsafe_errors() {
4498        // Exceed Decimal128 max precision (38) after scaling
4499        let variant_array: ArrayRef = ArrayRef::from(VariantArray::from_iter([
4500            Some(VariantDecimal16::try_new(VariantDecimal16::MAX_UNSCALED_VALUE, 1).unwrap()),
4501            Some(VariantDecimal16::try_new(VariantDecimal16::MAX_UNSCALED_VALUE, 0).unwrap()),
4502        ]));
4503
4504        let field = Field::new("result", DataType::Decimal256(76, 39), true);
4505        let cast_options = CastOptions {
4506            safe: false,
4507            ..Default::default()
4508        };
4509        let options = GetOptions::new()
4510            .with_as_type(Some(FieldRef::from(field)))
4511            .with_cast_options(cast_options);
4512        let err = variant_get(&variant_array, options).unwrap_err();
4513
4514        assert!(err.to_string().contains(
4515            "Failed to cast to Decimal256(precision=76, scale=39) from variant Decimal16"
4516        ));
4517    }
4518
4519    #[test]
4520    fn get_non_supported_temporal_types_error() {
4521        let values = vec![None, Some(Variant::Null), Some(Variant::BooleanFalse)];
4522        let variant_array: ArrayRef = ArrayRef::from(VariantArray::from_iter(values));
4523
4524        let test_cases = vec![
4525            FieldRef::from(Field::new(
4526                "result",
4527                DataType::Duration(TimeUnit::Microsecond),
4528                true,
4529            )),
4530            FieldRef::from(Field::new(
4531                "result",
4532                DataType::Interval(IntervalUnit::YearMonth),
4533                true,
4534            )),
4535        ];
4536
4537        for field in test_cases {
4538            let options = GetOptions::new().with_as_type(Some(field));
4539            let err = variant_get(&variant_array, options).unwrap_err();
4540            assert!(
4541                err.to_string()
4542                    .contains("Casting Variant to duration/interval types is not supported")
4543            );
4544        }
4545    }
4546
4547    #[test]
4548    fn get_variant_as_dictionary() {
4549        let variant_array: ArrayRef = ArrayRef::from(VariantArray::from_iter([
4550            Some("apple"),
4551            Some("banana"),
4552            None,
4553            Some("apple"),
4554        ]));
4555        let data_type = DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8));
4556        let options = GetOptions::new().with_as_type(Some(FieldRef::from(Field::new(
4557            "dict",
4558            data_type.clone(),
4559            true,
4560        ))));
4561
4562        let result = variant_get(&variant_array, options).unwrap();
4563        assert_eq!(result.data_type(), &data_type);
4564
4565        let decoded = cast(result.as_ref(), &DataType::Utf8).unwrap();
4566        let expected = StringArray::from(vec![Some("apple"), Some("banana"), None, Some("apple")]);
4567        assert_eq!(decoded.as_ref(), &expected);
4568    }
4569
4570    #[test]
4571    fn get_variant_as_numeric_dictionary() {
4572        let variant_array: ArrayRef =
4573            ArrayRef::from(VariantArray::from_iter([Some(42), Some(7), None, Some(42)]));
4574        let data_type = DataType::Dictionary(Box::new(DataType::Int16), Box::new(DataType::Int32));
4575        let options = GetOptions::new().with_as_type(Some(FieldRef::from(Field::new(
4576            "dict",
4577            data_type.clone(),
4578            true,
4579        ))));
4580
4581        let result = variant_get(&variant_array, options).unwrap();
4582        assert_eq!(result.data_type(), &data_type);
4583
4584        let decoded = cast(result.as_ref(), &DataType::Int32).unwrap();
4585        let expected = Int32Array::from(vec![Some(42), Some(7), None, Some(42)]);
4586        assert_eq!(decoded.as_ref(), &expected);
4587    }
4588
4589    #[test]
4590    fn get_variant_as_run_end_encoded() {
4591        let variant_array: ArrayRef = ArrayRef::from(VariantArray::from_iter([
4592            Some("apple"),
4593            Some("apple"),
4594            None,
4595            Some("banana"),
4596            Some("banana"),
4597        ]));
4598        let run_ends = Arc::new(Field::new(
4599            Field::REE_RUN_ENDS_FIELD_DEFAULT_NAME,
4600            DataType::Int32,
4601            false,
4602        ));
4603        let values = Arc::new(Field::new(
4604            Field::REE_VALUES_FIELD_DEFAULT_NAME,
4605            DataType::Utf8,
4606            true,
4607        ));
4608        let data_type = DataType::RunEndEncoded(run_ends, values);
4609        let options = GetOptions::new().with_as_type(Some(FieldRef::from(Field::new(
4610            "ree",
4611            data_type.clone(),
4612            true,
4613        ))));
4614
4615        let result = variant_get(&variant_array, options).unwrap();
4616        assert_eq!(result.data_type(), &data_type);
4617
4618        let decoded = cast(result.as_ref(), &DataType::Utf8).unwrap();
4619        let expected = StringArray::from(vec![
4620            Some("apple"),
4621            Some("apple"),
4622            None,
4623            Some("banana"),
4624            Some("banana"),
4625        ]);
4626        assert_eq!(decoded.as_ref(), &expected);
4627    }
4628
4629    /// Map data type with `MapBuilder`'s default field names, so results can be
4630    /// compared against arrays built by `MapBuilder`.
4631    fn map_data_type(value_type: DataType) -> DataType {
4632        DataType::Map(
4633            Arc::new(Field::new(
4634                "entries",
4635                DataType::Struct(Fields::from(vec![
4636                    Field::new("keys", DataType::Utf8, false),
4637                    Field::new("values", value_type, true),
4638                ])),
4639                false,
4640            )),
4641            false,
4642        )
4643    }
4644
4645    fn map_get_options(data_type: &DataType) -> GetOptions<'static> {
4646        GetOptions::new().with_as_type(Some(FieldRef::from(Field::new(
4647            "map",
4648            data_type.clone(),
4649            true,
4650        ))))
4651    }
4652
4653    #[test]
4654    fn get_variant_as_map() {
4655        let input: ArrayRef = Arc::new(StringArray::from(vec![
4656            Some(r#"{"a": 1, "b": 2}"#),
4657            Some(r#"{"c": 3}"#),
4658            None,
4659            Some("{}"),
4660            Some(r#"{"d": null}"#),
4661        ]));
4662        let variant_array = ArrayRef::from(json_to_variant(&input).unwrap());
4663
4664        let data_type = map_data_type(DataType::Int64);
4665        let result = variant_get(&variant_array, map_get_options(&data_type)).unwrap();
4666        assert_eq!(result.data_type(), &data_type);
4667
4668        let mut expected = MapBuilder::new(None, StringBuilder::new(), Int64Builder::new());
4669        expected.keys().append_value("a");
4670        expected.values().append_value(1);
4671        expected.keys().append_value("b");
4672        expected.values().append_value(2);
4673        expected.append(true).unwrap();
4674        expected.keys().append_value("c");
4675        expected.values().append_value(3);
4676        expected.append(true).unwrap();
4677        expected.append(false).unwrap(); // null row
4678        expected.append(true).unwrap(); // empty object -> empty map
4679        expected.keys().append_value("d");
4680        expected.values().append_null(); // variant null -> null map value
4681        expected.append(true).unwrap();
4682        let expected = expected.finish();
4683        assert_eq!(result.as_ref(), &expected);
4684    }
4685
4686    #[test]
4687    fn get_variant_as_map_of_lists() {
4688        let input: ArrayRef = Arc::new(StringArray::from(vec![
4689            Some(r#"{"a": [1, 2], "b": []}"#),
4690            Some(r#"{"c": [3]}"#),
4691        ]));
4692        let variant_array = ArrayRef::from(json_to_variant(&input).unwrap());
4693
4694        let data_type = map_data_type(DataType::List(Arc::new(Field::new(
4695            "item",
4696            DataType::Int64,
4697            true,
4698        ))));
4699        let result = variant_get(&variant_array, map_get_options(&data_type)).unwrap();
4700        assert_eq!(result.data_type(), &data_type);
4701
4702        let mut expected = MapBuilder::new(
4703            None,
4704            StringBuilder::new(),
4705            ListBuilder::new(Int64Builder::new()),
4706        );
4707        expected.keys().append_value("a");
4708        expected.values().append_value([Some(1), Some(2)]);
4709        expected.keys().append_value("b");
4710        expected.values().append_value([]);
4711        expected.append(true).unwrap();
4712        expected.keys().append_value("c");
4713        expected.values().append_value([Some(3)]);
4714        expected.append(true).unwrap();
4715        let expected = expected.finish();
4716        assert_eq!(result.as_ref(), &expected);
4717    }
4718
4719    #[test]
4720    fn get_variant_as_map_non_object_rows() {
4721        let input: ArrayRef = Arc::new(StringArray::from(vec![
4722            Some(r#"{"a": 1}"#),
4723            Some("42"), // not an object
4724        ]));
4725        let variant_array = ArrayRef::from(json_to_variant(&input).unwrap());
4726        let data_type = map_data_type(DataType::Int64);
4727
4728        // With safe casting (the default), non-object rows become null
4729        let result = variant_get(&variant_array, map_get_options(&data_type)).unwrap();
4730        let mut expected = MapBuilder::new(None, StringBuilder::new(), Int64Builder::new());
4731        expected.keys().append_value("a");
4732        expected.values().append_value(1);
4733        expected.append(true).unwrap();
4734        expected.append(false).unwrap();
4735        let expected = expected.finish();
4736        assert_eq!(result.as_ref(), &expected);
4737
4738        // With strict casting, non-object rows are an error
4739        let options = map_get_options(&data_type).with_cast_options(CastOptions {
4740            safe: false,
4741            format_options: FormatOptions::default(),
4742        });
4743        let err = variant_get(&variant_array, options).unwrap_err();
4744        assert!(
4745            err.to_string().contains("Failed to extract object"),
4746            "unexpected error: {err}"
4747        );
4748    }
4749
4750    #[test]
4751    fn get_variant_as_map_invalid_entries() {
4752        let input: ArrayRef = Arc::new(StringArray::from(vec![Some(r#"{"a": 1}"#)]));
4753        let variant_array = ArrayRef::from(json_to_variant(&input).unwrap());
4754
4755        // Entries type is not a struct
4756        let data_type = DataType::Map(
4757            Arc::new(Field::new("entries", DataType::Int32, false)),
4758            false,
4759        );
4760        let err = variant_get(&variant_array, map_get_options(&data_type)).unwrap_err();
4761        assert!(
4762            err.to_string().contains("Map entries must be Struct"),
4763            "unexpected error: {err}"
4764        );
4765
4766        // Entries struct does not have exactly two fields
4767        let data_type = DataType::Map(
4768            Arc::new(Field::new(
4769                "entries",
4770                DataType::Struct(Fields::from(vec![Field::new(
4771                    "keys",
4772                    DataType::Utf8,
4773                    false,
4774                )])),
4775                false,
4776            )),
4777            false,
4778        );
4779        let err = variant_get(&variant_array, map_get_options(&data_type)).unwrap_err();
4780        assert!(
4781            err.to_string()
4782                .contains("Map entries must have exactly two fields"),
4783            "unexpected error: {err}"
4784        );
4785    }
4786
4787    fn invalid_time_variant_array() -> ArrayRef {
4788        // 86401000000 is invalid for Time64Microsecond (max is 86400000000)
4789        ArrayRef::from(VariantArray::from_iter([Some(86401000000_i64); 3]))
4790    }
4791
4792    #[test]
4793    fn test_variant_get_error_when_cast_failure_and_safe_false() {
4794        let variant_array = invalid_time_variant_array();
4795
4796        let field = Field::new("result", DataType::Time64(TimeUnit::Microsecond), true);
4797        let cast_options = CastOptions {
4798            safe: false, // Will error on cast failure
4799            ..Default::default()
4800        };
4801        let options = GetOptions::new()
4802            .with_as_type(Some(FieldRef::from(field)))
4803            .with_cast_options(cast_options);
4804        let err = variant_get(&variant_array, options).unwrap_err();
4805        assert!(
4806            err.to_string().contains(
4807                "Cast error: Failed to extract primitive of type Time64(µs) from variant Int64(86401000000) at path VariantPath([])"
4808            ),
4809            "actual: {err}",
4810        );
4811    }
4812
4813    #[test]
4814    fn test_variant_get_return_null_when_cast_failure_and_safe_true() {
4815        let variant_array = invalid_time_variant_array();
4816
4817        let field = Field::new("result", DataType::Time64(TimeUnit::Microsecond), true);
4818        let cast_options = CastOptions {
4819            safe: true, // Will return null on cast failure
4820            ..Default::default()
4821        };
4822        let options = GetOptions::new()
4823            .with_as_type(Some(FieldRef::from(field)))
4824            .with_cast_options(cast_options);
4825        let result = variant_get(&variant_array, options).unwrap();
4826        assert_eq!(3, result.len());
4827
4828        for i in 0..3 {
4829            assert!(result.is_null(i));
4830        }
4831    }
4832
4833    #[test]
4834    fn test_perfect_shredding_returns_same_arc_ptr() {
4835        let variant_array = perfectly_shredded_int32_variant_array();
4836
4837        let variant_array_ref = VariantArray::try_new(&variant_array).unwrap();
4838        let typed_value_arc = variant_array_ref.typed_value_column().unwrap().clone();
4839
4840        let field = Field::new("result", DataType::Int32, true);
4841        let options = GetOptions::new().with_as_type(Some(FieldRef::from(field)));
4842        let result = variant_get(&variant_array, options).unwrap();
4843
4844        assert!(Arc::ptr_eq(&typed_value_arc, &result));
4845    }
4846
4847    #[test]
4848    fn test_perfect_shredding_three_typed_value_columns() {
4849        // Column 1: perfectly shredded primitive with all nulls
4850        let all_nulls_values: Arc<Int32Array> = Arc::new(Int32Array::from(vec![
4851            Option::<i32>::None,
4852            Option::<i32>::None,
4853            Option::<i32>::None,
4854        ]));
4855        let all_nulls_erased: ArrayRef = all_nulls_values.clone();
4856        let all_nulls_field =
4857            ShreddedVariantFieldArray::perfectly_shredded(all_nulls_erased.clone());
4858        let all_nulls_type = all_nulls_field.data_type().clone();
4859        let all_nulls_struct: ArrayRef = ArrayRef::from(all_nulls_field);
4860
4861        // Column 2: perfectly shredded primitive with some nulls
4862        let some_nulls_values: Arc<Int32Array> =
4863            Arc::new(Int32Array::from(vec![Some(10), None, Some(30)]));
4864        let some_nulls_erased: ArrayRef = some_nulls_values.clone();
4865        let some_nulls_field =
4866            ShreddedVariantFieldArray::perfectly_shredded(some_nulls_erased.clone());
4867        let some_nulls_type = some_nulls_field.data_type().clone();
4868        let some_nulls_struct: ArrayRef = ArrayRef::from(some_nulls_field);
4869
4870        // Column 3: perfectly shredded nested struct
4871        let inner_values: Arc<Int32Array> =
4872            Arc::new(Int32Array::from(vec![Some(111), None, Some(333)]));
4873        let inner_erased: ArrayRef = inner_values.clone();
4874        let inner_field = ShreddedVariantFieldArray::perfectly_shredded(inner_erased.clone());
4875        let inner_field_type = inner_field.data_type().clone();
4876        let inner_struct_array: ArrayRef = ArrayRef::from(inner_field);
4877
4878        let nested_struct = Arc::new(
4879            StructArray::try_new(
4880                Fields::from(vec![Field::new("inner", inner_field_type, true)]),
4881                vec![inner_struct_array],
4882                None,
4883            )
4884            .unwrap(),
4885        );
4886        let nested_struct_erased: ArrayRef = nested_struct.clone();
4887        let struct_field =
4888            ShreddedVariantFieldArray::perfectly_shredded(nested_struct_erased.clone());
4889        let struct_field_type = struct_field.data_type().clone();
4890        let struct_field_struct: ArrayRef = ArrayRef::from(struct_field);
4891
4892        // Assemble the top-level typed_value struct with the three columns above
4893        let typed_value_struct = StructArray::try_new(
4894            Fields::from(vec![
4895                Field::new("all_nulls", all_nulls_type, true),
4896                Field::new("some_nulls", some_nulls_type, true),
4897                Field::new("struct_field", struct_field_type, true),
4898            ]),
4899            vec![all_nulls_struct, some_nulls_struct, struct_field_struct],
4900            None,
4901        )
4902        .unwrap();
4903
4904        let metadata = BinaryViewArray::from_iter_values(std::iter::repeat_n(
4905            EMPTY_VARIANT_METADATA_BYTES,
4906            all_nulls_values.len(),
4907        ));
4908        let variant_array: ArrayRef = VariantArray::perfectly_shredded(
4909            Arc::new(metadata),
4910            Arc::new(typed_value_struct),
4911            None,
4912        )
4913        .into();
4914
4915        // Case 1: all-null primitive column should reuse the typed_value Arc directly
4916        let all_nulls_field_ref = FieldRef::from(Field::new("result", DataType::Int32, true));
4917        let all_nulls_result = variant_get(
4918            &variant_array,
4919            GetOptions::new_with_path(VariantPath::try_from("all_nulls").unwrap())
4920                .with_as_type(Some(all_nulls_field_ref)),
4921        )
4922        .unwrap();
4923        assert!(Arc::ptr_eq(&all_nulls_result, &all_nulls_erased));
4924
4925        // Case 2: primitive column with some nulls should also reuse its typed_value Arc
4926        let some_nulls_field_ref = FieldRef::from(Field::new("result", DataType::Int32, true));
4927        let some_nulls_result = variant_get(
4928            &variant_array,
4929            GetOptions::new_with_path(VariantPath::try_from("some_nulls").unwrap())
4930                .with_as_type(Some(some_nulls_field_ref)),
4931        )
4932        .unwrap();
4933        assert!(Arc::ptr_eq(&some_nulls_result, &some_nulls_erased));
4934
4935        // Case 3: struct column should return a StructArray composed from the nested field
4936        let struct_child_fields = Fields::from(vec![Field::new("inner", DataType::Int32, true)]);
4937        let struct_field_ref = FieldRef::from(Field::new(
4938            "result",
4939            DataType::Struct(struct_child_fields.clone()),
4940            true,
4941        ));
4942        let struct_result = variant_get(
4943            &variant_array,
4944            GetOptions::new_with_path(VariantPath::try_from("struct_field").unwrap())
4945                .with_as_type(Some(struct_field_ref)),
4946        )
4947        .unwrap();
4948        let struct_array = struct_result
4949            .as_any()
4950            .downcast_ref::<StructArray>()
4951            .unwrap();
4952        assert_eq!(struct_array.len(), 3);
4953        assert_eq!(struct_array.null_count(), 0);
4954
4955        let inner_values_result = struct_array
4956            .column(0)
4957            .as_any()
4958            .downcast_ref::<Int32Array>()
4959            .unwrap();
4960        assert_eq!(inner_values_result.len(), 3);
4961        assert_eq!(inner_values_result.value(0), 111);
4962        assert!(inner_values_result.is_null(1));
4963        assert_eq!(inner_values_result.value(2), 333);
4964    }
4965
4966    #[test]
4967    fn test_variant_get_list_like_safe_cast() {
4968        let string_array: ArrayRef = Arc::new(StringArray::from(vec![
4969            r#"{"outer":{"list":[1, "two", 3]}}"#,
4970            r#"{"outer":{"list":"not a list"}}"#,
4971        ]));
4972        let variant_array = ArrayRef::from(json_to_variant(&string_array).unwrap());
4973
4974        let element_array: ArrayRef = Arc::new(Int64Array::from(vec![Some(1), None, Some(3)]));
4975        let field = Arc::new(Field::new("item", Int64, true));
4976
4977        let expectations = vec![
4978            (
4979                DataType::List(field.clone()),
4980                Arc::new(ListArray::new(
4981                    field.clone(),
4982                    OffsetBuffer::new(ScalarBuffer::from(vec![0, 3, 3])),
4983                    element_array.clone(),
4984                    Some(NullBuffer::from(vec![true, false])),
4985                )) as ArrayRef,
4986            ),
4987            (
4988                DataType::LargeList(field.clone()),
4989                Arc::new(LargeListArray::new(
4990                    field.clone(),
4991                    OffsetBuffer::new(ScalarBuffer::from(vec![0, 3, 3])),
4992                    element_array.clone(),
4993                    Some(NullBuffer::from(vec![true, false])),
4994                )) as ArrayRef,
4995            ),
4996            (
4997                DataType::ListView(field.clone()),
4998                Arc::new(ListViewArray::new(
4999                    field.clone(),
5000                    ScalarBuffer::from(vec![0, 3]),
5001                    ScalarBuffer::from(vec![3, 0]),
5002                    element_array.clone(),
5003                    Some(NullBuffer::from(vec![true, false])),
5004                )) as ArrayRef,
5005            ),
5006            (
5007                DataType::LargeListView(field.clone()),
5008                Arc::new(LargeListViewArray::new(
5009                    field.clone(),
5010                    ScalarBuffer::from(vec![0, 3]),
5011                    ScalarBuffer::from(vec![3, 0]),
5012                    element_array,
5013                    Some(NullBuffer::from(vec![true, false])),
5014                )) as ArrayRef,
5015            ),
5016            (
5017                DataType::FixedSizeList(field.clone(), 3),
5018                Arc::new(FixedSizeListArray::new(
5019                    field,
5020                    3,
5021                    Arc::new(Int64Array::from(vec![
5022                        Some(1),
5023                        None,
5024                        Some(3),
5025                        None,
5026                        None,
5027                        None,
5028                    ])),
5029                    Some(NullBuffer::from(vec![true, false])),
5030                )) as ArrayRef,
5031            ),
5032        ];
5033
5034        for (request_type, expected) in expectations {
5035            let options =
5036                GetOptions::new_with_path(VariantPath::try_from("outer").unwrap().join("list"))
5037                    .with_as_type(Some(FieldRef::from(Field::new(
5038                        "result",
5039                        request_type.clone(),
5040                        true,
5041                    ))));
5042
5043            let result = variant_get(&variant_array, options).unwrap();
5044            assert_eq!(result.data_type(), expected.data_type());
5045            assert_eq!(&result, &expected);
5046        }
5047
5048        for (idx, expected) in [
5049            (0, vec![Some(1), None]),
5050            (1, vec![None, None]),
5051            (2, vec![Some(3), None]),
5052        ] {
5053            let index_options = GetOptions::new_with_path(
5054                VariantPath::try_from("outer")
5055                    .unwrap()
5056                    .join("list")
5057                    .join(idx),
5058            )
5059            .with_as_type(Some(FieldRef::from(Field::new(
5060                "result",
5061                DataType::Int64,
5062                true,
5063            ))));
5064            let index_result = variant_get(&variant_array, index_options).unwrap();
5065            let index_expected: ArrayRef = Arc::new(Int64Array::from(expected));
5066            assert_eq!(&index_result, &index_expected);
5067        }
5068    }
5069
5070    #[test]
5071    fn test_variant_get_nested_list() {
5072        use arrow::datatypes::Int64Type;
5073
5074        let string_array: ArrayRef = Arc::new(StringArray::from(vec![
5075            "[[1, 2], [3]]",
5076            r#"[[4], "not a list", [5, 6]]"#,
5077        ]));
5078        let variant_array = ArrayRef::from(json_to_variant(&string_array).unwrap());
5079
5080        let inner_field = Arc::new(Field::new("item", Int64, true));
5081        let outer_field = Arc::new(Field::new(
5082            "item",
5083            DataType::List(inner_field.clone()),
5084            true,
5085        ));
5086        let request_type = DataType::List(outer_field.clone());
5087
5088        let options = GetOptions::new().with_as_type(Some(FieldRef::from(Field::new(
5089            "result",
5090            request_type,
5091            true,
5092        ))));
5093        let result = variant_get(&variant_array, options).unwrap();
5094        let outer = result.as_list::<i32>();
5095
5096        // Row 0: [[1, 2], [3]]
5097        let row0 = outer.value(0);
5098        let row0 = row0.as_list::<i32>();
5099        assert_eq!(row0.len(), 2);
5100        let elem0 = row0.value(0);
5101        assert_eq!(elem0.as_primitive::<Int64Type>().values(), &[1, 2]);
5102        let elem1 = row0.value(1);
5103        assert_eq!(elem1.as_primitive::<Int64Type>().values(), &[3]);
5104
5105        // Row 1: [[4], null, [5, 6]] — "not a list" becomes null inner list
5106        let row1 = outer.value(1);
5107        let row1 = row1.as_list::<i32>();
5108        assert_eq!(row1.len(), 3);
5109        let elem0 = row1.value(0);
5110        assert_eq!(elem0.as_primitive::<Int64Type>().values(), &[4]);
5111        assert!(row1.is_null(1));
5112        let elem2 = row1.value(2);
5113        assert_eq!(elem2.as_primitive::<Int64Type>().values(), &[5, 6]);
5114    }
5115
5116    #[test]
5117    fn test_variant_get_list_like_unsafe_cast_errors_on_element_mismatch() {
5118        let string_array: ArrayRef =
5119            Arc::new(StringArray::from(vec![r#"[1, "two", 3]"#, "[4, 5]"]));
5120        let variant_array = ArrayRef::from(json_to_variant(&string_array).unwrap());
5121        let cast_options = CastOptions {
5122            safe: false,
5123            ..Default::default()
5124        };
5125
5126        let item_field = Arc::new(Field::new("item", DataType::Int64, true));
5127        let request_types = vec![
5128            DataType::List(item_field.clone()),
5129            DataType::LargeList(item_field.clone()),
5130            DataType::ListView(item_field.clone()),
5131            DataType::LargeListView(item_field),
5132        ];
5133
5134        for request_type in request_types {
5135            let options = GetOptions::new()
5136                .with_as_type(Some(FieldRef::from(Field::new(
5137                    "result",
5138                    request_type.clone(),
5139                    true,
5140                ))))
5141                .with_cast_options(cast_options.clone());
5142
5143            let err = variant_get(&variant_array, options).unwrap_err();
5144            assert!(
5145                err.to_string()
5146                    .contains("Failed to extract primitive of type Int64")
5147            );
5148        }
5149    }
5150
5151    #[test]
5152    fn test_variant_get_list_like_unsafe_cast_preserves_null_elements() {
5153        let string_array: ArrayRef = Arc::new(StringArray::from(vec!["[1, null, 3]"]));
5154        let variant_array = ArrayRef::from(json_to_variant(&string_array).unwrap());
5155        let cast_options = CastOptions {
5156            safe: false,
5157            ..Default::default()
5158        };
5159        let options = GetOptions::new()
5160            .with_as_type(Some(FieldRef::from(Field::new(
5161                "result",
5162                DataType::List(Arc::new(Field::new("item", DataType::Int64, true))),
5163                true,
5164            ))))
5165            .with_cast_options(cast_options);
5166
5167        let result = variant_get(&variant_array, options).unwrap();
5168        let list_array = result.as_any().downcast_ref::<ListArray>().unwrap();
5169        let values = list_array
5170            .values()
5171            .as_any()
5172            .downcast_ref::<Int64Array>()
5173            .unwrap();
5174
5175        assert_eq!(values.len(), 3);
5176        assert_eq!(values.value(0), 1);
5177        assert!(values.is_null(1));
5178        assert_eq!(values.value(2), 3);
5179    }
5180
5181    #[test]
5182    fn test_variant_get_list_like_null_element_in_non_nullable_item() {
5183        let item_field = Arc::new(Field::new("item", Int64, false));
5184        let data_types = [
5185            (DataType::List(item_field.clone()), "ListArray"),
5186            (DataType::LargeList(item_field.clone()), "LargeListArray"),
5187            (DataType::ListView(item_field.clone()), "ListViewArray"),
5188            (DataType::LargeListView(item_field), "LargeListViewArray"),
5189        ];
5190        // A null element, and an element that a safe cast turns into null
5191        for json in ["[1, null, 3]", r#"[1, "two", 3]"#] {
5192            let string_array: ArrayRef = Arc::new(StringArray::from(vec![json]));
5193            let variant_array = ArrayRef::from(json_to_variant(&string_array).unwrap());
5194            for (data_type, array_name) in &data_types {
5195                let options = GetOptions::new().with_as_type(Some(FieldRef::from(Field::new(
5196                    "result",
5197                    data_type.clone(),
5198                    true,
5199                ))));
5200                let err = variant_get(&variant_array, options).unwrap_err();
5201                assert_eq!(
5202                    err.to_string(),
5203                    format!(
5204                        "Invalid argument error: Non-nullable field of {array_name} \"item\" cannot contain nulls"
5205                    )
5206                );
5207            }
5208        }
5209    }
5210
5211    #[test]
5212    fn test_variant_get_list_like_unsafe_cast_errors_on_non_list() {
5213        let string_array: ArrayRef = Arc::new(StringArray::from(vec!["[1, 2]", "\"not a list\""]));
5214        let variant_array = ArrayRef::from(json_to_variant(&string_array).unwrap());
5215        let cast_options = CastOptions {
5216            safe: false,
5217            ..Default::default()
5218        };
5219        let item_field = Arc::new(Field::new("item", Int64, true));
5220        let data_types = vec![
5221            DataType::List(item_field.clone()),
5222            DataType::LargeList(item_field.clone()),
5223            DataType::ListView(item_field.clone()),
5224            DataType::LargeListView(item_field.clone()),
5225            DataType::FixedSizeList(item_field, 2),
5226        ];
5227
5228        for data_type in data_types {
5229            let options = GetOptions::new()
5230                .with_as_type(Some(FieldRef::from(Field::new("result", data_type, true))))
5231                .with_cast_options(cast_options.clone());
5232
5233            let err = variant_get(&variant_array, options).unwrap_err();
5234            assert!(
5235                err.to_string()
5236                    .contains("Failed to extract list from variant"),
5237            );
5238        }
5239    }
5240
5241    #[test]
5242    fn test_variant_get_fixed_size_list_wrong_size() {
5243        let string_array: ArrayRef = Arc::new(StringArray::from(vec!["[1, 2, 3]"]));
5244        let variant_array = ArrayRef::from(json_to_variant(&string_array).unwrap());
5245        let item_field = Arc::new(Field::new("item", Int64, true));
5246
5247        // With `safe` set to true, size mismatch should return Null.
5248        let options = GetOptions::new()
5249            .with_as_type(Some(FieldRef::from(Field::new(
5250                "result",
5251                DataType::FixedSizeList(item_field.clone(), 2),
5252                true,
5253            ))))
5254            .with_cast_options(CastOptions {
5255                safe: true,
5256                ..Default::default()
5257            });
5258        let result = variant_get(&variant_array, options).unwrap();
5259        let fixed_size_list = result
5260            .as_any()
5261            .downcast_ref::<FixedSizeListArray>()
5262            .expect("Expected FixedSizeListArray");
5263        assert_eq!(fixed_size_list.len(), 1);
5264        assert!(fixed_size_list.is_null(0));
5265
5266        // With `safe` set to false, error should be raised on wrong sized fixed list.
5267        let options = GetOptions::new()
5268            .with_as_type(Some(FieldRef::from(Field::new(
5269                "result",
5270                DataType::FixedSizeList(item_field.clone(), 2),
5271                true,
5272            ))))
5273            .with_cast_options(CastOptions {
5274                safe: false,
5275                ..Default::default()
5276            });
5277        let err = variant_get(&variant_array, options).unwrap_err();
5278        assert!(
5279            err.to_string()
5280                .contains("Expected fixed size list of size 2, got size 3"),
5281            "got: {err}",
5282        );
5283    }
5284
5285    macro_rules! perfectly_shredded_preserves_top_level_nulls_test {
5286        ($name:ident, $result_type:expr, $typed_value:expr, $expected_array:expr) => {
5287            perfectly_shredded_preserves_top_level_nulls_test!(
5288                $name,
5289                $result_type,
5290                $typed_value,
5291                Some(NullBuffer::from(vec![true, false, true])),
5292                $expected_array
5293            );
5294        };
5295        ($name:ident, $result_type:expr, $typed_value:expr, $parent_nulls:expr, $expected_array:expr) => {
5296            #[test]
5297            fn $name() {
5298                let metadata = Arc::new(BinaryViewArray::from_iter_values(std::iter::repeat_n(
5299                    EMPTY_VARIANT_METADATA_BYTES,
5300                    3,
5301                )));
5302                let typed_value: ArrayRef = Arc::new($typed_value);
5303                let variant_array: ArrayRef =
5304                    VariantArray::perfectly_shredded(metadata, typed_value, $parent_nulls).into();
5305
5306                let result = variant_get(
5307                    &variant_array,
5308                    GetOptions::new().with_as_type(Some(FieldRef::from(Field::new(
5309                        "result",
5310                        $result_type,
5311                        true,
5312                    )))),
5313                )
5314                .unwrap();
5315
5316                let expected_array: ArrayRef = Arc::new($expected_array);
5317                assert_eq!(&result, &expected_array);
5318            }
5319        };
5320    }
5321
5322    perfectly_shredded_preserves_top_level_nulls_test!(
5323        test_variant_get_perfectly_shredded_integer_preserves_top_level_nulls,
5324        DataType::Int32,
5325        Int32Array::from(vec![Some(0_i32), Some(1_i32), Some(2_i32)]),
5326        Int32Array::from(vec![Some(0_i32), None, Some(2_i32)])
5327    );
5328
5329    perfectly_shredded_preserves_top_level_nulls_test!(
5330        test_variant_get_perfectly_shredded_integer_unions_child_and_top_level_nulls,
5331        DataType::Int32,
5332        Int32Array::from(vec![None, Some(1_i32), Some(2_i32)]),
5333        Some(NullBuffer::from(vec![true, false, true])),
5334        Int32Array::from(vec![None, None, Some(2_i32)])
5335    );
5336
5337    perfectly_shredded_preserves_top_level_nulls_test!(
5338        test_variant_get_perfectly_shredded_null_preserves_top_level_nulls,
5339        DataType::Null,
5340        NullArray::new(3),
5341        NullArray::new(3)
5342    );
5343
5344    perfectly_shredded_preserves_top_level_nulls_test!(
5345        test_variant_get_perfectly_shredded_binary_view_preserves_top_level_nulls,
5346        DataType::BinaryView,
5347        BinaryViewArray::from(vec![
5348            Some(b"Apache" as &[u8]),
5349            Some(b"masked-null" as &[u8]),
5350            Some(b"Parquet-variant" as &[u8]),
5351        ]),
5352        BinaryViewArray::from(vec![
5353            Some(b"Apache" as &[u8]),
5354            None,
5355            Some(b"Parquet-variant" as &[u8]),
5356        ])
5357    );
5358
5359    perfectly_shredded_preserves_top_level_nulls_test!(
5360        test_variant_get_perfectly_shredded_binary_preserves_top_level_nulls,
5361        DataType::Binary,
5362        BinaryArray::from(vec![
5363            Some(b"Apache" as &[u8]),
5364            Some(b"masked-null" as &[u8]),
5365            Some(b"Parquet-variant" as &[u8]),
5366        ]),
5367        BinaryArray::from(vec![
5368            Some(b"Apache" as &[u8]),
5369            None,
5370            Some(b"Parquet-variant" as &[u8]),
5371        ])
5372    );
5373
5374    perfectly_shredded_preserves_top_level_nulls_test!(
5375        test_variant_get_perfectly_shredded_decimal4_preserves_top_level_nulls,
5376        DataType::Decimal32(5, 2),
5377        Decimal32Array::from(vec![Some(12345), Some(23400), Some(-12342)])
5378            .with_precision_and_scale(5, 2)
5379            .unwrap(),
5380        Decimal32Array::from(vec![Some(12345), None, Some(-12342)])
5381            .with_precision_and_scale(5, 2)
5382            .unwrap()
5383    );
5384
5385    perfectly_shredded_preserves_top_level_nulls_test!(
5386        test_variant_get_perfectly_shredded_decimal8_preserves_top_level_nulls,
5387        DataType::Decimal64(10, 1),
5388        Decimal64Array::from(vec![Some(1234567809), Some(1456787000), Some(-1234561203)])
5389            .with_precision_and_scale(10, 1)
5390            .unwrap(),
5391        Decimal64Array::from(vec![Some(1234567809), None, Some(-1234561203)])
5392            .with_precision_and_scale(10, 1)
5393            .unwrap()
5394    );
5395
5396    perfectly_shredded_preserves_top_level_nulls_test!(
5397        test_variant_get_perfectly_shredded_decimal16_preserves_top_level_nulls,
5398        DataType::Decimal128(20, 3),
5399        Decimal128Array::from(vec![
5400            Some(i128::from_str("12345678901234567899").unwrap()),
5401            Some(i128::from_str("23445677483748324300").unwrap()),
5402            Some(i128::from_str("-12345678901234567899").unwrap()),
5403        ])
5404        .with_precision_and_scale(20, 3)
5405        .unwrap(),
5406        Decimal128Array::from(vec![
5407            Some(i128::from_str("12345678901234567899").unwrap()),
5408            None,
5409            Some(i128::from_str("-12345678901234567899").unwrap()),
5410        ])
5411        .with_precision_and_scale(20, 3)
5412        .unwrap()
5413    );
5414
5415    fn union_get_options(fields: &UnionFields, mode: UnionMode) -> GetOptions<'static> {
5416        let field = Field::new("union", DataType::Union(fields.clone(), mode), true);
5417        GetOptions::new().with_as_type(Some(FieldRef::from(field)))
5418    }
5419
5420    fn int_str_bool_union_fields() -> UnionFields {
5421        UnionFields::try_new(
5422            vec![0, 1, 2],
5423            vec![
5424                Field::new("int", DataType::Int64, true),
5425                Field::new("str", DataType::Utf8, true),
5426                Field::new("bool", DataType::Boolean, true),
5427            ],
5428        )
5429        .unwrap()
5430    }
5431
5432    /// int8, string, bool, array-level null, `Variant::Null`, double (no matching field), int64
5433    fn mixed_variant_array() -> ArrayRef {
5434        let mut builder = VariantArrayBuilder::new(7);
5435        builder.append_variant(Variant::Int8(1));
5436        builder.append_variant(Variant::from("hello"));
5437        builder.append_variant(Variant::from(true));
5438        builder.append_null();
5439        builder.append_variant(Variant::Null);
5440        builder.append_variant(Variant::Double(2.5));
5441        builder.append_variant(Variant::Int64(5_000_000_000));
5442        ArrayRef::from(builder.build())
5443    }
5444
5445    #[test]
5446    fn get_variant_as_dense_union() {
5447        let fields = int_str_bool_union_fields();
5448        let array = mixed_variant_array();
5449        let result = variant_get(&array, union_get_options(&fields, UnionMode::Dense)).unwrap();
5450
5451        // nulls, `Variant::Null`, and the unmatched Double all land as nulls in the first child
5452        let expected: ArrayRef = Arc::new(
5453            UnionArray::try_new(
5454                fields,
5455                ScalarBuffer::from(vec![0i8, 1, 2, 0, 0, 0, 0]),
5456                Some(ScalarBuffer::from(vec![0i32, 0, 0, 1, 2, 3, 4])),
5457                vec![
5458                    Arc::new(Int64Array::from(vec![
5459                        Some(1),
5460                        None,
5461                        None,
5462                        None,
5463                        Some(5_000_000_000),
5464                    ])),
5465                    Arc::new(StringArray::from(vec!["hello"])),
5466                    Arc::new(BooleanArray::from(vec![true])),
5467                ],
5468            )
5469            .unwrap(),
5470        );
5471        assert_eq!(&result, &expected);
5472    }
5473
5474    #[test]
5475    fn get_variant_as_sparse_union() {
5476        let fields = int_str_bool_union_fields();
5477        let array = mixed_variant_array();
5478        let result = variant_get(&array, union_get_options(&fields, UnionMode::Sparse)).unwrap();
5479
5480        let expected: ArrayRef = Arc::new(
5481            UnionArray::try_new(
5482                fields,
5483                ScalarBuffer::from(vec![0i8, 1, 2, 0, 0, 0, 0]),
5484                None,
5485                vec![
5486                    Arc::new(Int64Array::from(vec![
5487                        Some(1),
5488                        None,
5489                        None,
5490                        None,
5491                        None,
5492                        None,
5493                        Some(5_000_000_000),
5494                    ])),
5495                    Arc::new(StringArray::from(vec![
5496                        None,
5497                        Some("hello"),
5498                        None,
5499                        None,
5500                        None,
5501                        None,
5502                        None,
5503                    ])),
5504                    Arc::new(BooleanArray::from(vec![
5505                        None,
5506                        None,
5507                        Some(true),
5508                        None,
5509                        None,
5510                        None,
5511                        None,
5512                    ])),
5513                ],
5514            )
5515            .unwrap(),
5516        );
5517        assert_eq!(&result, &expected);
5518    }
5519
5520    #[test]
5521    fn get_variant_as_union_prefers_most_exact_field() {
5522        // Int8 picks the later-declared Int32 over Int64: exactness wins over declaration order
5523        let fields = UnionFields::try_new(
5524            vec![0, 1],
5525            vec![
5526                Field::new("big", DataType::Int64, true),
5527                Field::new("small", DataType::Int32, true),
5528            ],
5529        )
5530        .unwrap();
5531        let mut builder = VariantArrayBuilder::new(3);
5532        builder.append_variant(Variant::Int8(1));
5533        builder.append_variant(Variant::Int32(2));
5534        builder.append_variant(Variant::Int64(3));
5535        let array = ArrayRef::from(builder.build());
5536
5537        let result = variant_get(&array, union_get_options(&fields, UnionMode::Dense)).unwrap();
5538
5539        let expected: ArrayRef = Arc::new(
5540            UnionArray::try_new(
5541                fields,
5542                ScalarBuffer::from(vec![1i8, 1, 0]),
5543                Some(ScalarBuffer::from(vec![0i32, 1, 0])),
5544                vec![
5545                    Arc::new(Int64Array::from(vec![3])),
5546                    Arc::new(Int32Array::from(vec![1, 2])),
5547                ],
5548            )
5549            .unwrap(),
5550        );
5551        assert_eq!(&result, &expected);
5552    }
5553
5554    #[test]
5555    fn get_variant_as_union_with_encoded_children() {
5556        let encoded_types = [
5557            DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8)),
5558            DataType::RunEndEncoded(
5559                Arc::new(Field::new(
5560                    Field::REE_RUN_ENDS_FIELD_DEFAULT_NAME,
5561                    DataType::Int32,
5562                    false,
5563                )),
5564                Arc::new(Field::new(
5565                    Field::REE_VALUES_FIELD_DEFAULT_NAME,
5566                    DataType::Utf8,
5567                    true,
5568                )),
5569            ),
5570        ];
5571
5572        for data_type in encoded_types {
5573            let fields = UnionFields::try_new(
5574                vec![0],
5575                vec![Field::new("encoded", data_type.clone(), true)],
5576            )
5577            .unwrap();
5578            let array = ArrayRef::from(VariantArray::from_iter([Some("apple"), Some("banana")]));
5579            let options =
5580                union_get_options(&fields, UnionMode::Dense).with_cast_options(CastOptions {
5581                    safe: false,
5582                    ..Default::default()
5583                });
5584
5585            let result = variant_get(&array, options).unwrap();
5586            let union = result.as_any().downcast_ref::<UnionArray>().unwrap();
5587            assert_eq!(union.type_ids(), &[0i8, 0]);
5588            assert_eq!(union.child(0).data_type(), &data_type);
5589
5590            let decoded = cast(union.child(0).as_ref(), &DataType::Utf8).unwrap();
5591            let expected = StringArray::from(vec!["apple", "banana"]);
5592            assert_eq!(decoded.as_ref(), &expected);
5593        }
5594    }
5595
5596    #[test]
5597    fn get_variant_as_union_with_fixed_size_list_child() {
5598        let item = Arc::new(Field::new("item", DataType::Int64, true));
5599        let fields = UnionFields::try_new(
5600            vec![0],
5601            vec![Field::new("fixed", DataType::FixedSizeList(item, 2), true)],
5602        )
5603        .unwrap();
5604        let json = StringArray::from(vec!["[1, 2]"]);
5605        let array = ArrayRef::from(json_to_variant(&(Arc::new(json) as ArrayRef)).unwrap());
5606
5607        for safe in [true, false] {
5608            let options =
5609                union_get_options(&fields, UnionMode::Dense).with_cast_options(CastOptions {
5610                    safe,
5611                    ..Default::default()
5612                });
5613            let result = variant_get(&array, options).unwrap();
5614            let union = result.as_any().downcast_ref::<UnionArray>().unwrap();
5615            assert_eq!(union.type_ids(), &[0i8]);
5616            let list = union
5617                .child(0)
5618                .as_any()
5619                .downcast_ref::<FixedSizeListArray>()
5620                .unwrap();
5621            assert_eq!(
5622                list.value(0)
5623                    .as_primitive::<arrow::datatypes::Int64Type>()
5624                    .values(),
5625                &[1, 2]
5626            );
5627        }
5628    }
5629
5630    #[test]
5631    fn get_variant_as_union_skips_decimal_that_cannot_fit() {
5632        let fields = UnionFields::try_new(
5633            vec![0, 1],
5634            vec![
5635                Field::new("too_narrow", DataType::Decimal32(3, 2), true),
5636                Field::new("fits", DataType::Decimal32(5, 2), true),
5637            ],
5638        )
5639        .unwrap();
5640        let array = ArrayRef::from(VariantArray::from_iter([Some(
5641            VariantDecimal4::try_new(12_345, 2).unwrap(),
5642        )]));
5643
5644        for safe in [true, false] {
5645            let options =
5646                union_get_options(&fields, UnionMode::Dense).with_cast_options(CastOptions {
5647                    safe,
5648                    ..Default::default()
5649                });
5650            let result = variant_get(&array, options).unwrap();
5651            let union = result.as_any().downcast_ref::<UnionArray>().unwrap();
5652            assert_eq!(union.type_ids(), &[1i8]);
5653            let decimal = union
5654                .child(1)
5655                .as_any()
5656                .downcast_ref::<Decimal32Array>()
5657                .unwrap();
5658            assert_eq!(decimal.value(0), 12_345);
5659        }
5660    }
5661
5662    #[test]
5663    fn get_variant_as_union_with_null_field() {
5664        // nulls and unmatched values land in the Null-typed field instead of the first one
5665        let fields = UnionFields::try_new(
5666            vec![0, 1],
5667            vec![
5668                Field::new("int", DataType::Int64, true),
5669                Field::new("null", DataType::Null, true),
5670            ],
5671        )
5672        .unwrap();
5673        let mut builder = VariantArrayBuilder::new(4);
5674        builder.append_variant(Variant::Int8(1));
5675        builder.append_null();
5676        builder.append_variant(Variant::Null);
5677        builder.append_variant(Variant::from("no matching field"));
5678        let array = ArrayRef::from(builder.build());
5679
5680        let result = variant_get(&array, union_get_options(&fields, UnionMode::Dense)).unwrap();
5681
5682        let expected: ArrayRef = Arc::new(
5683            UnionArray::try_new(
5684                fields,
5685                ScalarBuffer::from(vec![0i8, 1, 1, 1]),
5686                Some(ScalarBuffer::from(vec![0i32, 0, 1, 2])),
5687                vec![
5688                    Arc::new(Int64Array::from(vec![1])),
5689                    Arc::new(NullArray::new(3)),
5690                ],
5691            )
5692            .unwrap(),
5693        );
5694        assert_eq!(&result, &expected);
5695    }
5696
5697    #[test]
5698    fn get_variant_as_union_of_nested_types() {
5699        let fields = UnionFields::try_new(
5700            vec![0, 1, 2],
5701            vec![
5702                Field::new(
5703                    "struct",
5704                    DataType::Struct(Fields::from(vec![Field::new("a", DataType::Int64, true)])),
5705                    true,
5706                ),
5707                Field::new(
5708                    "list",
5709                    DataType::List(Arc::new(Field::new("item", DataType::Int64, true))),
5710                    true,
5711                ),
5712                Field::new("str", DataType::Utf8, true),
5713            ],
5714        )
5715        .unwrap();
5716        let json = StringArray::from(vec![r#"{"a": 1}"#, "[1, 2, 3]", "\"s\""]);
5717        let array = ArrayRef::from(json_to_variant(&(Arc::new(json) as ArrayRef)).unwrap());
5718
5719        let result = variant_get(&array, union_get_options(&fields, UnionMode::Dense)).unwrap();
5720
5721        let mut list_builder = ListBuilder::new(Int64Builder::new());
5722        list_builder.append_value([Some(1), Some(2), Some(3)]);
5723        let expected: ArrayRef = Arc::new(
5724            UnionArray::try_new(
5725                fields,
5726                ScalarBuffer::from(vec![0i8, 1, 2]),
5727                Some(ScalarBuffer::from(vec![0i32, 0, 0])),
5728                vec![
5729                    Arc::new(StructArray::from(vec![(
5730                        Arc::new(Field::new("a", DataType::Int64, true)),
5731                        Arc::new(Int64Array::from(vec![1])) as ArrayRef,
5732                    )])),
5733                    Arc::new(list_builder.finish()),
5734                    Arc::new(StringArray::from(vec!["s"])),
5735                ],
5736            )
5737            .unwrap(),
5738        );
5739        assert_eq!(&result, &expected);
5740    }
5741
5742    #[test]
5743    fn get_variant_as_union_with_map_field() {
5744        // With no Struct field in the union, an object routes to the Map child.
5745        let fields = UnionFields::try_new(
5746            vec![0, 1],
5747            vec![
5748                Field::new("map", map_data_type(DataType::Int64), true),
5749                Field::new("str", DataType::Utf8, true),
5750            ],
5751        )
5752        .unwrap();
5753        let json = StringArray::from(vec![r#"{"a": 1, "b": 2}"#, "\"hi\""]);
5754        let array = ArrayRef::from(json_to_variant(&(Arc::new(json) as ArrayRef)).unwrap());
5755
5756        let result = variant_get(&array, union_get_options(&fields, UnionMode::Dense)).unwrap();
5757
5758        let mut map_builder = MapBuilder::new(None, StringBuilder::new(), Int64Builder::new());
5759        map_builder.keys().append_value("a");
5760        map_builder.values().append_value(1);
5761        map_builder.keys().append_value("b");
5762        map_builder.values().append_value(2);
5763        map_builder.append(true).unwrap();
5764        let expected: ArrayRef = Arc::new(
5765            UnionArray::try_new(
5766                fields,
5767                ScalarBuffer::from(vec![0i8, 1]),
5768                Some(ScalarBuffer::from(vec![0i32, 0])),
5769                vec![
5770                    Arc::new(map_builder.finish()),
5771                    Arc::new(StringArray::from(vec!["hi"])),
5772                ],
5773            )
5774            .unwrap(),
5775        );
5776        assert_eq!(&result, &expected);
5777    }
5778
5779    #[test]
5780    fn get_variant_as_union_prefers_struct_over_map() {
5781        // Both a Struct and a Map field can hold an object; the object routes to Struct because
5782        // it represents the object more exactly (rank 0 vs 1).
5783        let fields = UnionFields::try_new(
5784            vec![0, 1],
5785            vec![
5786                Field::new("map", map_data_type(DataType::Int64), true),
5787                Field::new(
5788                    "struct",
5789                    DataType::Struct(Fields::from(vec![Field::new("a", DataType::Int64, true)])),
5790                    true,
5791                ),
5792            ],
5793        )
5794        .unwrap();
5795        let json = StringArray::from(vec![r#"{"a": 1}"#]);
5796        let array = ArrayRef::from(json_to_variant(&(Arc::new(json) as ArrayRef)).unwrap());
5797
5798        let result = variant_get(&array, union_get_options(&fields, UnionMode::Dense)).unwrap();
5799        let union = result.as_any().downcast_ref::<UnionArray>().unwrap();
5800        // type_id 1 == the struct child
5801        assert_eq!(union.type_ids(), &[1i8]);
5802    }
5803
5804    #[test]
5805    fn get_variant_as_union_no_matching_field() {
5806        // Like other requested fields, union child nullability does not override safe casting.
5807        let fields =
5808            UnionFields::try_new(vec![0], vec![Field::new("str", DataType::Utf8, false)]).unwrap();
5809        let mut builder = VariantArrayBuilder::new(2);
5810        builder.append_variant(Variant::from("kept"));
5811        builder.append_variant(Variant::Int8(1));
5812        let array = ArrayRef::from(builder.build());
5813
5814        // Safe mode: the Int8 row becomes a null in the first (only) child.
5815        let result = variant_get(&array, union_get_options(&fields, UnionMode::Dense)).unwrap();
5816        let expected: ArrayRef = Arc::new(
5817            UnionArray::try_new(
5818                fields.clone(),
5819                ScalarBuffer::from(vec![0i8, 0]),
5820                Some(ScalarBuffer::from(vec![0i32, 1])),
5821                vec![Arc::new(StringArray::from(vec![Some("kept"), None]))],
5822            )
5823            .unwrap(),
5824        );
5825        assert_eq!(&result, &expected);
5826
5827        // Strict mode: the same row is a cast error.
5828        let options = union_get_options(&fields, UnionMode::Dense).with_cast_options(CastOptions {
5829            safe: false,
5830            ..Default::default()
5831        });
5832        let err = variant_get(&array, options).unwrap_err();
5833        assert!(
5834            err.to_string().contains("no field can represent it"),
5835            "unexpected error: {err}"
5836        );
5837    }
5838
5839    #[test]
5840    fn get_variant_as_union_empty_fields_errors() {
5841        let array = ArrayRef::from(VariantArray::from_iter([Some(1_i8)]));
5842
5843        let err = variant_get(
5844            &array,
5845            union_get_options(&UnionFields::empty(), UnionMode::Dense),
5846        )
5847        .unwrap_err();
5848        assert!(
5849            err.to_string().contains("at least one union field"),
5850            "unexpected error: {err}"
5851        );
5852    }
5853}