Skip to main content

vortex_arrow/
convert.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! Canonical (non-plugin) conversions of Arrow arrays into Vortex arrays.
5//!
6//! Each `from_arrow_*` function converts one Arrow array shape; [`from_arrow_dyn`] dispatches on
7//! the Arrow [`DataType`]. These functions have no awareness of Arrow extension types — the
8//! plugin-aware entry points are the [`ArrowSession`](crate::ArrowSession) methods, which fall
9//! back to these conversions for non-extension data.
10
11use std::ops::Range;
12use std::sync::Arc;
13
14use arrow_array::AnyDictionaryArray;
15use arrow_array::Array as ArrowArray;
16use arrow_array::ArrowPrimitiveType;
17use arrow_array::BooleanArray as ArrowBooleanArray;
18use arrow_array::DictionaryArray;
19use arrow_array::FixedSizeListArray as ArrowFixedSizeListArray;
20use arrow_array::GenericByteArray;
21use arrow_array::GenericByteViewArray;
22use arrow_array::GenericListArray;
23use arrow_array::GenericListViewArray;
24use arrow_array::MapArray as ArrowMapArray;
25use arrow_array::NullArray as ArrowNullArray;
26use arrow_array::OffsetSizeTrait;
27use arrow_array::PrimitiveArray as ArrowPrimitiveArray;
28use arrow_array::RecordBatch;
29use arrow_array::StructArray as ArrowStructArray;
30use arrow_array::cast::AsArray;
31use arrow_array::cast::as_null_array;
32use arrow_array::make_array;
33use arrow_array::types::ArrowDictionaryKeyType;
34use arrow_array::types::ByteArrayType;
35use arrow_array::types::ByteViewType;
36use arrow_array::types::Date32Type;
37use arrow_array::types::Date64Type;
38use arrow_array::types::Decimal32Type;
39use arrow_array::types::Decimal64Type;
40use arrow_array::types::Decimal128Type;
41use arrow_array::types::Decimal256Type;
42use arrow_array::types::Float16Type;
43use arrow_array::types::Float32Type;
44use arrow_array::types::Float64Type;
45use arrow_array::types::Int8Type;
46use arrow_array::types::Int16Type;
47use arrow_array::types::Int32Type;
48use arrow_array::types::Int64Type;
49use arrow_array::types::Time32MillisecondType;
50use arrow_array::types::Time32SecondType;
51use arrow_array::types::Time64MicrosecondType;
52use arrow_array::types::Time64NanosecondType;
53use arrow_array::types::TimestampMicrosecondType;
54use arrow_array::types::TimestampMillisecondType;
55use arrow_array::types::TimestampNanosecondType;
56use arrow_array::types::TimestampSecondType;
57use arrow_array::types::UInt8Type;
58use arrow_array::types::UInt16Type;
59use arrow_array::types::UInt32Type;
60use arrow_array::types::UInt64Type;
61use arrow_buffer::ArrowNativeType;
62use arrow_buffer::BooleanBuffer;
63use arrow_buffer::Buffer as ArrowBuffer;
64use arrow_buffer::ScalarBuffer;
65use arrow_buffer::buffer::NullBuffer;
66use arrow_buffer::buffer::OffsetBuffer;
67use arrow_schema::DataType;
68use arrow_schema::TimeUnit as ArrowTimeUnit;
69use vortex_array::ArrayRef;
70use vortex_array::IntoArray;
71use vortex_array::arrays::BoolArray;
72use vortex_array::arrays::DecimalArray;
73use vortex_array::arrays::DictArray;
74use vortex_array::arrays::ExtensionArray;
75use vortex_array::arrays::FixedSizeListArray;
76use vortex_array::arrays::ListArray;
77use vortex_array::arrays::ListViewArray;
78use vortex_array::arrays::MapArray;
79use vortex_array::arrays::NullArray;
80use vortex_array::arrays::PrimitiveArray;
81use vortex_array::arrays::Struct;
82use vortex_array::arrays::StructArray;
83use vortex_array::arrays::TemporalArray;
84use vortex_array::arrays::VarBinArray;
85use vortex_array::arrays::VarBinViewArray;
86use vortex_array::arrays::decimal::check_precision;
87use vortex_array::arrays::decimal::copy_to_canonical_width;
88use vortex_array::arrays::struct_::StructArrayExt;
89use vortex_array::buffer::BufferHandle;
90use vortex_array::dtype::DType;
91use vortex_array::dtype::DecimalDType;
92use vortex_array::dtype::FieldNames;
93use vortex_array::dtype::IntegerPType;
94use vortex_array::dtype::MapDType;
95use vortex_array::dtype::NativeDecimalType;
96use vortex_array::dtype::NativePType;
97use vortex_array::dtype::Nullability;
98use vortex_array::dtype::PType;
99use vortex_array::dtype::i256;
100use vortex_array::extension::datetime::TimeUnit;
101use vortex_array::extension::datetime::Timestamp;
102use vortex_array::validity::Validity;
103use vortex_buffer::Alignment;
104use vortex_buffer::BitBuffer;
105use vortex_buffer::Buffer;
106use vortex_buffer::ByteBuffer;
107use vortex_error::VortexResult;
108use vortex_error::vortex_bail;
109use vortex_error::vortex_ensure;
110use vortex_error::vortex_ensure_eq;
111use vortex_error::vortex_err;
112use vortex_error::vortex_panic;
113use vortex_mask::Mask;
114
115use crate::dtype::from_arrow_time_unit;
116
117/// Zero-copy conversion of Arrow buffers into non-nullable Vortex arrays.
118///
119/// This mirrors [`IntoArray`] for Arrow buffer types; a separate trait is required because both
120/// [`IntoArray`] and the Arrow buffer types are foreign to this crate.
121pub trait IntoVortexArray {
122    /// Convert this Arrow buffer into a non-nullable Vortex array without copying.
123    fn into_array(self) -> ArrayRef;
124}
125
126impl IntoVortexArray for ArrowBuffer {
127    fn into_array(self) -> ArrayRef {
128        PrimitiveArray::from_byte_buffer(
129            ByteBuffer::from_arrow_buffer(self, Alignment::of::<u8>()),
130            PType::U8,
131            Validity::NonNullable,
132        )
133        .into_array()
134    }
135}
136
137impl IntoVortexArray for BooleanBuffer {
138    fn into_array(self) -> ArrayRef {
139        BoolArray::new(self.into(), Validity::NonNullable).into_array()
140    }
141}
142
143impl<T> IntoVortexArray for ScalarBuffer<T>
144where
145    T: ArrowNativeType + NativePType,
146{
147    fn into_array(self) -> ArrayRef {
148        PrimitiveArray::new(
149            Buffer::<T>::from_arrow_scalar_buffer(self),
150            Validity::NonNullable,
151        )
152        .into_array()
153    }
154}
155
156impl<O> IntoVortexArray for OffsetBuffer<O>
157where
158    O: IntegerPType + OffsetSizeTrait,
159{
160    fn into_array(self) -> ArrayRef {
161        let primitive = PrimitiveArray::new(
162            Buffer::from_arrow_scalar_buffer(self.into_inner()),
163            Validity::NonNullable,
164        );
165
166        primitive.into_array()
167    }
168}
169
170/// Zero-copy conversion of an Arrow numeric primitive array into a Vortex array.
171///
172/// Use [`from_arrow_temporal`] for Arrow temporal arrays, which carry a logical dtype beyond
173/// their physical primitive storage.
174pub fn from_arrow_primitive<T: ArrowPrimitiveType>(
175    value: &ArrowPrimitiveArray<T>,
176    nullable: bool,
177) -> VortexResult<ArrayRef>
178where
179    T::Native: NativePType,
180{
181    let buffer = Buffer::from_arrow_scalar_buffer(value.values().clone());
182    let validity = nulls(value.nulls(), nullable)?;
183    Ok(PrimitiveArray::new(buffer, validity).into_array())
184}
185
186/// Conversion of an Arrow `Decimal32` array into a Vortex decimal array, zero-copy when the Arrow
187/// width is the [canonical width](DecimalDType::canonical_values_type), otherwise a checked copy.
188pub fn from_arrow_decimal32(
189    array: &ArrowPrimitiveArray<Decimal32Type>,
190    nullable: bool,
191) -> VortexResult<ArrayRef> {
192    let values = Buffer::from_arrow_scalar_buffer(array.values().clone());
193    from_arrow_decimal(
194        values,
195        array.nulls(),
196        array.precision(),
197        array.scale(),
198        nullable,
199    )
200}
201
202/// Conversion of an Arrow `Decimal64` array into a Vortex decimal array, zero-copy when the Arrow
203/// width is the [canonical width](DecimalDType::canonical_values_type), otherwise a checked copy.
204pub fn from_arrow_decimal64(
205    array: &ArrowPrimitiveArray<Decimal64Type>,
206    nullable: bool,
207) -> VortexResult<ArrayRef> {
208    let values = Buffer::from_arrow_scalar_buffer(array.values().clone());
209    from_arrow_decimal(
210        values,
211        array.nulls(),
212        array.precision(),
213        array.scale(),
214        nullable,
215    )
216}
217
218/// Conversion of an Arrow `Decimal128` array into a Vortex decimal array, zero-copy when the Arrow
219/// width is the [canonical width](DecimalDType::canonical_values_type), otherwise a checked copy.
220pub fn from_arrow_decimal128(
221    array: &ArrowPrimitiveArray<Decimal128Type>,
222    nullable: bool,
223) -> VortexResult<ArrayRef> {
224    let values = Buffer::from_arrow_scalar_buffer(array.values().clone());
225    from_arrow_decimal(
226        values,
227        array.nulls(),
228        array.precision(),
229        array.scale(),
230        nullable,
231    )
232}
233
234/// Conversion of an Arrow `Decimal256` array into a Vortex decimal array, zero-copy when the Arrow
235/// width is the [canonical width](DecimalDType::canonical_values_type), otherwise a checked copy.
236pub fn from_arrow_decimal256(
237    array: &ArrowPrimitiveArray<Decimal256Type>,
238    nullable: bool,
239) -> VortexResult<ArrayRef> {
240    let values = Buffer::from_arrow_scalar_buffer(array.values().clone());
241    // SAFETY: Our i256 implementation has the same bit-pattern representation of the
242    //  arrow_buffer::i256 type. It is safe to treat values held inside the buffer as values
243    //  of either type.
244    let values = unsafe { std::mem::transmute::<Buffer<arrow_buffer::i256>, Buffer<i256>>(values) };
245    from_arrow_decimal(
246        values,
247        array.nulls(),
248        array.precision(),
249        array.scale(),
250        nullable,
251    )
252}
253
254/// Converts the values of an Arrow decimal array into a Vortex decimal array at the canonical width
255/// of its precision.
256///
257/// arrow-rs does not check that the values of an array fit its precision, so this function checks
258/// every valid value. When `T` is the canonical width, the array keeps the Arrow buffer and
259/// [`check_precision`] checks it. Otherwise [`copy_to_canonical_width`] copies the values, which
260/// writes zeros into the null slots when it narrows. Null slots are never checked.
261///
262/// # Errors
263///
264/// Returns an error if the precision or scale is invalid, if `nullable` is false and the array has
265/// nulls, or if a valid value is outside the precision.
266fn from_arrow_decimal<T: NativeDecimalType>(
267    values: Buffer<T>,
268    arrow_nulls: Option<&NullBuffer>,
269    precision: u8,
270    scale: i8,
271    nullable: bool,
272) -> VortexResult<ArrayRef> {
273    let decimal_dtype = DecimalDType::try_new(precision, scale)?;
274    let validity = nulls(arrow_nulls, nullable)?;
275    let mask = arrow_nulls.map_or_else(
276        || Mask::new_true(values.len()),
277        |arrow_nulls| Mask::from_buffer(BitBuffer::from(arrow_nulls.inner().clone())),
278    );
279
280    let values_type = decimal_dtype.canonical_values_type();
281    let checked_values = if T::DECIMAL_TYPE == values_type {
282        check_precision(values.as_slice(), &mask, decimal_dtype)
283            .map(|()| BufferHandle::new_host(values.into_byte_buffer()))
284    } else {
285        copy_to_canonical_width(values.as_slice(), &mask, decimal_dtype)
286    };
287    let checked_values = checked_values.map_err(|err| {
288        err.with_context(format!(
289            "Arrow decimal import requires every valid value to be within the precision of \
290             {decimal_dtype}; call arrow-rs PrimitiveArray::null_if_overflow_precision before \
291             the import to turn such values into nulls"
292        ))
293    })?;
294
295    // SAFETY: Every valid value is within the precision of `decimal_dtype`. `check_precision`
296    // checked the zero-copy values, and `copy_to_canonical_width` checks a narrowing copy. A
297    // widening copy needs no check: the canonical width is wider than `T` only when the precision
298    // is above `T::MAX_PRECISION`, and every value of `T` has at most `T::MAX_PRECISION + 1`
299    // digits. Arrow keeps its null buffer at the length of the values, so the validity matches.
300    let array = unsafe {
301        DecimalArray::new_unchecked_handle(checked_values, values_type, decimal_dtype, validity)
302    };
303
304    Ok(array.into_array())
305}
306
307/// Conversion of an Arrow temporal array (timestamp/date/time) into a Vortex temporal
308/// extension array.
309pub fn from_arrow_temporal<T: ArrowPrimitiveType>(
310    value: &ArrowPrimitiveArray<T>,
311    nullable: bool,
312) -> VortexResult<ArrayRef>
313where
314    T::Native: NativePType,
315{
316    let arr = PrimitiveArray::new(
317        Buffer::from_arrow_scalar_buffer(value.values().clone()),
318        nulls(value.nulls(), nullable)?,
319    )
320    .into_array();
321
322    Ok(match value.data_type() {
323        DataType::Timestamp(time_unit, tz) => {
324            let dtype = Timestamp::try_new_with_tz(
325                from_arrow_time_unit(*time_unit),
326                tz.clone(),
327                arr.dtype().nullability(),
328            )?;
329            ExtensionArray::try_new(dtype.erased(), arr)?.into_array()
330        }
331        DataType::Time32(time_unit) => {
332            TemporalArray::new_time(arr, from_arrow_time_unit(*time_unit)).into()
333        }
334        DataType::Time64(time_unit) => {
335            TemporalArray::new_time(arr, from_arrow_time_unit(*time_unit)).into()
336        }
337        DataType::Date32 => TemporalArray::new_date(arr, TimeUnit::Days).into(),
338        DataType::Date64 => TemporalArray::new_date(arr, TimeUnit::Milliseconds).into(),
339        DataType::Duration(_) | DataType::Interval(_) => {
340            vortex_bail!("Arrow {} arrays are not supported", value.data_type())
341        }
342        _ => vortex_panic!("Invalid temporal type: {}", value.data_type()),
343    })
344}
345
346/// Rebase a (possibly sliced) Arrow offset buffer to start at zero.
347///
348/// A sliced Arrow string, binary or list array keeps its parent's whole child,
349/// so the returned range selects just the child data its rows reference.
350pub(crate) fn trim_offsets<O: OffsetSizeTrait>(
351    offsets: &OffsetBuffer<O>,
352) -> (OffsetBuffer<O>, Range<usize>) {
353    let first = offsets[0];
354    let referenced = first.as_usize()..offsets[offsets.len() - 1].as_usize();
355    if first.as_usize() == 0 {
356        return (offsets.clone(), referenced);
357    }
358    let rebased = OffsetBuffer::new(offsets.iter().map(|&offset| offset - first).collect());
359    (rebased, referenced)
360}
361
362/// Conversion of an Arrow (large) string/binary array into a Vortex `VarBin` array, sharing its
363/// bytes.
364pub fn from_arrow_bytes<T: ByteArrayType>(
365    value: &GenericByteArray<T>,
366    nullable: bool,
367) -> VortexResult<ArrayRef>
368where
369    <T as ByteArrayType>::Offset: IntegerPType,
370{
371    let dtype = match T::DATA_TYPE {
372        DataType::Binary | DataType::LargeBinary => DType::Binary(nullable.into()),
373        DataType::Utf8 | DataType::LargeUtf8 => DType::Utf8(nullable.into()),
374        dt => vortex_panic!("Invalid data type for ByteArray: {dt}"),
375    };
376    let (offsets, referenced) = trim_offsets(value.offsets());
377    let bytes = value
378        .values()
379        .slice_with_length(referenced.start, referenced.len());
380    // SAFETY: Arrow arrays are already validated (valid UTF-8, valid offsets, correct validity).
381    Ok(unsafe {
382        VarBinArray::new_unchecked(
383            offsets.into_array(),
384            ByteBuffer::from_arrow_buffer(bytes, Alignment::of::<u8>()),
385            dtype,
386            nulls(value.nulls(), nullable)?,
387        )
388    }
389    .into_array())
390}
391
392/// Zero-copy conversion of an Arrow string/binary view array into a Vortex `VarBinView` array.
393pub fn from_arrow_byte_view<T: ByteViewType>(
394    value: &GenericByteViewArray<T>,
395    nullable: bool,
396) -> VortexResult<ArrayRef> {
397    let dtype = match T::DATA_TYPE {
398        DataType::BinaryView => DType::Binary(nullable.into()),
399        DataType::Utf8View => DType::Utf8(nullable.into()),
400        dt => vortex_panic!("Invalid data type for ByteViewArray: {dt}"),
401    };
402
403    let views_buffer = Buffer::from_byte_buffer(
404        Buffer::from_arrow_scalar_buffer(value.views().clone()).into_byte_buffer(),
405    );
406
407    // SAFETY: arrow-rs ByteViewArray already checks the same invariants, we inherit those
408    //  guarantees by zero-copy constructing from one.
409    Ok(unsafe {
410        VarBinViewArray::new_unchecked(
411            views_buffer,
412            Arc::from(
413                value
414                    .data_buffers()
415                    .iter()
416                    .map(|b| ByteBuffer::from_arrow_buffer(b.clone(), Alignment::of::<u8>()))
417                    .collect::<Vec<_>>(),
418            ),
419            dtype,
420            nulls(value.nulls(), nullable)?,
421        )
422        .into_array()
423    })
424}
425
426/// Zero-copy conversion of an Arrow boolean array into a Vortex `Bool` array.
427pub fn from_arrow_boolean(value: &ArrowBooleanArray, nullable: bool) -> VortexResult<ArrayRef> {
428    Ok(BoolArray::new(
429        value.values().clone().into(),
430        nulls(value.nulls(), nullable)?,
431    )
432    .into_array())
433}
434
435/// Strip out the nulls from this array and return a new array without nulls.
436pub(crate) fn remove_nulls(data: arrow_data::ArrayData) -> VortexResult<arrow_data::ArrayData> {
437    if data.null_count() == 0 {
438        // No nulls to remove, return the array as is
439        return Ok(data);
440    }
441
442    let children = match data.data_type() {
443        DataType::Struct(fields) => Some(
444            fields
445                .iter()
446                .zip(data.child_data().iter())
447                .map(|(field, child_data)| {
448                    if field.is_nullable() {
449                        Ok(child_data.clone())
450                    } else {
451                        remove_nulls(child_data.clone())
452                    }
453                })
454                .collect::<VortexResult<Vec<_>>>()?,
455        ),
456        DataType::List(f)
457        | DataType::LargeList(f)
458        | DataType::ListView(f)
459        | DataType::LargeListView(f)
460        | DataType::FixedSizeList(f, _)
461            if !f.is_nullable() =>
462        {
463            // All list types only have one child
464            vortex_ensure_eq!(
465                data.child_data().len(),
466                1,
467                "List types should have one child"
468            );
469            Some(vec![remove_nulls(data.child_data()[0].clone())?])
470        }
471        _ => None,
472    };
473
474    let mut builder = data.into_builder().nulls(None);
475    if let Some(children) = children {
476        builder = builder.child_data(children);
477    }
478    builder
479        .build()
480        .map_err(|e| vortex_err!("Failed to reconstruct Arrow array without nulls: {e}"))
481}
482
483/// Conversion of an Arrow struct array into a Vortex `Struct` array, converting each column.
484pub fn from_arrow_struct(value: &ArrowStructArray, nullable: bool) -> VortexResult<ArrayRef> {
485    Ok(StructArray::try_new(
486        value.column_names().iter().copied().collect(),
487        value
488            .columns()
489            .iter()
490            .zip(value.fields())
491            .map(|(c, field)| {
492                // Arrow pushes down nulls, even into non-nullable fields. So we strip them
493                // out here because Vortex is a little more strict.
494                if c.null_count() > 0 && !field.is_nullable() {
495                    let stripped = make_array(remove_nulls(c.into_data())?);
496                    from_arrow_dyn(stripped.as_ref(), false)
497                } else {
498                    from_arrow_dyn(c.as_ref(), field.is_nullable())
499                }
500            })
501            .collect::<VortexResult<Vec<_>>>()?,
502        value.len(),
503        nulls(value.nulls(), nullable)?,
504    )?
505    .into_array())
506}
507
508/// Conversion of an Arrow (large) list array into a Vortex `List` array.
509pub fn from_arrow_list<O: IntegerPType + OffsetSizeTrait>(
510    value: &GenericListArray<O>,
511    nullable: bool,
512) -> VortexResult<ArrayRef> {
513    // Extract the validity of the underlying element array.
514    let elements_are_nullable = match value.data_type() {
515        DataType::List(field) => field.is_nullable(),
516        DataType::LargeList(field) => field.is_nullable(),
517        dt => vortex_panic!("Invalid data type for ListArray: {dt}"),
518    };
519
520    let (offsets, referenced) = trim_offsets(value.offsets());
521    let elements = from_arrow_dyn(
522        value
523            .values()
524            .slice(referenced.start, referenced.len())
525            .as_ref(),
526        elements_are_nullable,
527    )?;
528    let nulls = nulls(value.nulls(), nullable)?;
529
530    // SAFETY: Arrow offsets are non-negative and sorted, and `trim_offsets` rebases them onto
531    // the referenced values, so the last offset is the elements length. The validity comes from
532    // the same Arrow array, so it has one entry per list.
533    Ok(unsafe { ListArray::new_unchecked(elements, offsets.into_array(), nulls) }.into_array())
534}
535
536/// Conversion of an Arrow (large) list-view array into a Vortex `ListView` array.
537pub fn from_arrow_list_view<O: OffsetSizeTrait + NativePType>(
538    array: &GenericListViewArray<O>,
539    nullable: bool,
540) -> VortexResult<ArrayRef> {
541    // Extract the validity of the underlying element array.
542    let elements_are_nullable = match array.data_type() {
543        DataType::ListView(field) => field.is_nullable(),
544        DataType::LargeListView(field) => field.is_nullable(),
545        dt => vortex_panic!("Invalid data type for ListViewArray: {dt}"),
546    };
547
548    let elements = from_arrow_dyn(array.values().as_ref(), elements_are_nullable)?;
549
550    // `offsets` and `sizes` are always non-nullable.
551    let offsets = array.offsets().clone().into_array();
552    let sizes = array.sizes().clone().into_array();
553    let nulls = nulls(array.nulls(), nullable)?;
554
555    // SAFETY: Arrow list views share one integer type for offsets and sizes, and every view
556    // lies within the values. The validity comes from the same Arrow array.
557    Ok(unsafe { ListViewArray::new_unchecked(elements, offsets, sizes, nulls) }.into_array())
558}
559
560/// Conversion of an Arrow fixed-size list array into a Vortex `FixedSizeList` array.
561pub fn from_arrow_fixed_size_list(
562    array: &ArrowFixedSizeListArray,
563    nullable: bool,
564) -> VortexResult<ArrayRef> {
565    let DataType::FixedSizeList(field, list_size) = array.data_type() else {
566        vortex_panic!("Invalid data type for ListArray: {}", array.data_type());
567    };
568
569    Ok(FixedSizeListArray::try_new(
570        from_arrow_dyn(array.values().as_ref(), field.is_nullable())?,
571        *list_size as u32,
572        nulls(array.nulls(), nullable)?,
573        array.len(),
574    )?
575    .into_array())
576}
577
578pub(crate) fn map_from_arrow_parts(
579    entries: ArrayRef,
580    offsets: &OffsetBuffer<i32>,
581    arrow_nulls: Option<&NullBuffer>,
582    keys_sorted: bool,
583    nullable: bool,
584) -> VortexResult<ArrayRef> {
585    let DType::Struct(struct_dtype, Nullability::NonNullable) = entries.dtype() else {
586        vortex_bail!(
587            "Arrow map entries must import as non-nullable struct, got {}",
588            entries.dtype()
589        );
590    };
591    vortex_ensure_eq!(
592        struct_dtype.nfields(),
593        2,
594        "Arrow map entries struct must contain exactly two fields"
595    );
596
597    let key_dtype = struct_dtype
598        .field_by_index(0)
599        .ok_or_else(|| vortex_err!("Arrow map entries struct missing key field"))?;
600    vortex_ensure!(
601        !key_dtype.is_nullable(),
602        "Arrow map key field must be non-nullable"
603    );
604    let value_dtype = struct_dtype
605        .field_by_index(1)
606        .ok_or_else(|| vortex_err!("Arrow map entries struct missing value field"))?;
607    let map_dtype = MapDType::try_new(key_dtype, value_dtype, keys_sorted)?;
608    let entries_struct = entries.as_::<Struct>();
609    let entries = StructArray::try_new(
610        FieldNames::from(["key", "value"]),
611        vec![
612            entries_struct.unmasked_field(0).clone(),
613            entries_struct.unmasked_field(1).clone(),
614        ],
615        entries.len(),
616        Validity::NonNullable,
617    )?
618    .into_array();
619
620    let len = offsets.len() - 1;
621    let sizes = Buffer::<i32>::from_iter(offsets.windows(2).map(|window| window[1] - window[0]))
622        .into_array();
623    let offsets = offsets.inner().slice(0, len).into_array();
624    let validity = nulls(arrow_nulls, nullable)?;
625    // SAFETY: the sizes are the differences of sorted, non-negative Arrow Map offsets that lie
626    // within the entries, and share their integer type. The validity has one entry per map.
627    let entries = unsafe { ListViewArray::new_unchecked(entries, offsets, sizes, validity) };
628    // SAFETY: Arrow Map offsets are sorted list offsets. Vortex sizes are adjacent offset
629    // differences, so every view's end equals the next view's start. Sliced Arrow arrays may
630    // leave leading or trailing entries unreferenced, which zero-copy-to-list permits.
631    let entries = unsafe { entries.with_zero_copy_to_list(true) };
632
633    Ok(MapArray::try_new(map_dtype, entries)?.into_array())
634}
635
636/// Conversion of an Arrow map array into a Vortex `Map` array.
637pub fn from_arrow_map(array: &ArrowMapArray, nullable: bool) -> VortexResult<ArrayRef> {
638    let DataType::Map(_, keys_sorted) = array.data_type() else {
639        vortex_panic!("Invalid data type for MapArray: {}", array.data_type());
640    };
641    let entries = from_arrow_struct(array.entries(), false)?;
642    map_from_arrow_parts(
643        entries,
644        array.offsets(),
645        array.nulls(),
646        *keys_sorted,
647        nullable,
648    )
649}
650
651/// Conversion of an Arrow null array into a Vortex `Null` array.
652pub fn from_arrow_null(value: &ArrowNullArray, nullable: bool) -> VortexResult<ArrayRef> {
653    vortex_ensure!(
654        nullable,
655        "Cannot convert an Arrow NullArray into a non-nullable Vortex array"
656    );
657    Ok(NullArray::new(value.len()).into_array())
658}
659
660/// Conversion of an Arrow dictionary array into a Vortex `Dict` array.
661pub fn from_arrow_dictionary<K: ArrowDictionaryKeyType>(
662    array: &DictionaryArray<K>,
663    nullable: bool,
664) -> VortexResult<DictArray> {
665    let keys = AnyDictionaryArray::keys(array);
666    let keys = from_arrow_dyn(keys, keys.is_nullable())?;
667    let values = from_arrow_dyn(array.values().as_ref(), nullable)?;
668    // SAFETY: we assume that Arrow has checked the invariants on construction.
669    Ok(unsafe { DictArray::new_unchecked(keys, values) })
670}
671
672/// Convert an Arrow [`NullBuffer`] into a Vortex [`Validity`] for an array of the given
673/// nullability.
674///
675/// # Errors
676///
677/// Returns an error if `nullable` is false but the null buffer contains nulls.
678pub fn nulls(nulls: Option<&NullBuffer>, nullable: bool) -> VortexResult<Validity> {
679    if nullable {
680        Ok(nulls
681            .map(|nulls| {
682                if nulls.null_count() == nulls.len() {
683                    Validity::AllInvalid
684                } else {
685                    Validity::from(BitBuffer::from(nulls.inner().clone()))
686                }
687            })
688            .unwrap_or(Validity::AllValid))
689    } else {
690        let null_count = nulls.map(NullBuffer::null_count).unwrap_or(0);
691        vortex_ensure_eq!(
692            null_count,
693            0,
694            "Cannot convert an Arrow array containing nulls into a non-nullable Vortex array"
695        );
696        Ok(Validity::NonNullable)
697    }
698}
699
700/// Canonical conversion of any supported Arrow array into a Vortex array, dispatching on the
701/// Arrow [`DataType`].
702pub fn from_arrow_dyn(array: &dyn ArrowArray, nullable: bool) -> VortexResult<ArrayRef> {
703    match array.data_type() {
704        DataType::Boolean => from_arrow_boolean(array.as_boolean(), nullable),
705        DataType::UInt8 => from_arrow_primitive(array.as_primitive::<UInt8Type>(), nullable),
706        DataType::UInt16 => from_arrow_primitive(array.as_primitive::<UInt16Type>(), nullable),
707        DataType::UInt32 => from_arrow_primitive(array.as_primitive::<UInt32Type>(), nullable),
708        DataType::UInt64 => from_arrow_primitive(array.as_primitive::<UInt64Type>(), nullable),
709        DataType::Int8 => from_arrow_primitive(array.as_primitive::<Int8Type>(), nullable),
710        DataType::Int16 => from_arrow_primitive(array.as_primitive::<Int16Type>(), nullable),
711        DataType::Int32 => from_arrow_primitive(array.as_primitive::<Int32Type>(), nullable),
712        DataType::Int64 => from_arrow_primitive(array.as_primitive::<Int64Type>(), nullable),
713        DataType::Float16 => from_arrow_primitive(array.as_primitive::<Float16Type>(), nullable),
714        DataType::Float32 => from_arrow_primitive(array.as_primitive::<Float32Type>(), nullable),
715        DataType::Float64 => from_arrow_primitive(array.as_primitive::<Float64Type>(), nullable),
716        DataType::Utf8 => from_arrow_bytes(array.as_string::<i32>(), nullable),
717        DataType::LargeUtf8 => from_arrow_bytes(array.as_string::<i64>(), nullable),
718        DataType::Binary => from_arrow_bytes(array.as_binary::<i32>(), nullable),
719        DataType::LargeBinary => from_arrow_bytes(array.as_binary::<i64>(), nullable),
720        DataType::BinaryView => from_arrow_byte_view(array.as_binary_view(), nullable),
721        DataType::Utf8View => from_arrow_byte_view(array.as_string_view(), nullable),
722        DataType::Struct(_) => from_arrow_struct(array.as_struct(), nullable),
723        DataType::List(_) => from_arrow_list(array.as_list::<i32>(), nullable),
724        DataType::LargeList(_) => from_arrow_list(array.as_list::<i64>(), nullable),
725        DataType::ListView(_) => from_arrow_list_view(array.as_list_view::<i32>(), nullable),
726        DataType::LargeListView(_) => from_arrow_list_view(array.as_list_view::<i64>(), nullable),
727        DataType::FixedSizeList(..) => {
728            from_arrow_fixed_size_list(array.as_fixed_size_list(), nullable)
729        }
730        DataType::Map(..) => from_arrow_map(array.as_map(), nullable),
731        DataType::Null => from_arrow_null(as_null_array(array), nullable),
732        DataType::Timestamp(u, _) => match u {
733            ArrowTimeUnit::Second => {
734                from_arrow_temporal(array.as_primitive::<TimestampSecondType>(), nullable)
735            }
736            ArrowTimeUnit::Millisecond => {
737                from_arrow_temporal(array.as_primitive::<TimestampMillisecondType>(), nullable)
738            }
739            ArrowTimeUnit::Microsecond => {
740                from_arrow_temporal(array.as_primitive::<TimestampMicrosecondType>(), nullable)
741            }
742            ArrowTimeUnit::Nanosecond => {
743                from_arrow_temporal(array.as_primitive::<TimestampNanosecondType>(), nullable)
744            }
745        },
746        DataType::Date32 => from_arrow_temporal(array.as_primitive::<Date32Type>(), nullable),
747        DataType::Date64 => from_arrow_temporal(array.as_primitive::<Date64Type>(), nullable),
748        DataType::Time32(u) => match u {
749            ArrowTimeUnit::Second => {
750                from_arrow_temporal(array.as_primitive::<Time32SecondType>(), nullable)
751            }
752            ArrowTimeUnit::Millisecond => {
753                from_arrow_temporal(array.as_primitive::<Time32MillisecondType>(), nullable)
754            }
755            ArrowTimeUnit::Microsecond | ArrowTimeUnit::Nanosecond => unreachable!(),
756        },
757        DataType::Time64(u) => match u {
758            ArrowTimeUnit::Microsecond => {
759                from_arrow_temporal(array.as_primitive::<Time64MicrosecondType>(), nullable)
760            }
761            ArrowTimeUnit::Nanosecond => {
762                from_arrow_temporal(array.as_primitive::<Time64NanosecondType>(), nullable)
763            }
764            ArrowTimeUnit::Second | ArrowTimeUnit::Millisecond => unreachable!(),
765        },
766        DataType::Decimal32(..) => {
767            from_arrow_decimal32(array.as_primitive::<Decimal32Type>(), nullable)
768        }
769        DataType::Decimal64(..) => {
770            from_arrow_decimal64(array.as_primitive::<Decimal64Type>(), nullable)
771        }
772        DataType::Decimal128(..) => {
773            from_arrow_decimal128(array.as_primitive::<Decimal128Type>(), nullable)
774        }
775        DataType::Decimal256(..) => {
776            from_arrow_decimal256(array.as_primitive::<Decimal256Type>(), nullable)
777        }
778        DataType::Dictionary(key_type, _) => match key_type.as_ref() {
779            DataType::Int8 => Ok(from_arrow_dictionary(
780                array.as_dictionary::<Int8Type>(),
781                nullable,
782            )?
783            .into_array()),
784            DataType::Int16 => Ok(from_arrow_dictionary(
785                array.as_dictionary::<Int16Type>(),
786                nullable,
787            )?
788            .into_array()),
789            DataType::Int32 => Ok(from_arrow_dictionary(
790                array.as_dictionary::<Int32Type>(),
791                nullable,
792            )?
793            .into_array()),
794            DataType::Int64 => Ok(from_arrow_dictionary(
795                array.as_dictionary::<Int64Type>(),
796                nullable,
797            )?
798            .into_array()),
799            DataType::UInt8 => Ok(from_arrow_dictionary(
800                array.as_dictionary::<UInt8Type>(),
801                nullable,
802            )?
803            .into_array()),
804            DataType::UInt16 => Ok(from_arrow_dictionary(
805                array.as_dictionary::<UInt16Type>(),
806                nullable,
807            )?
808            .into_array()),
809            DataType::UInt32 => Ok(from_arrow_dictionary(
810                array.as_dictionary::<UInt32Type>(),
811                nullable,
812            )?
813            .into_array()),
814            DataType::UInt64 => Ok(from_arrow_dictionary(
815                array.as_dictionary::<UInt64Type>(),
816                nullable,
817            )?
818            .into_array()),
819            key_dt => vortex_bail!("Unsupported dictionary key type: {key_dt}"),
820        },
821        dt => {
822            vortex_bail!("Array encoding not implemented for Arrow data type {dt}")
823        }
824    }
825}
826
827/// Canonical conversion of an Arrow [`RecordBatch`] into a Vortex struct array.
828pub fn from_arrow_batch(batch: &RecordBatch, nullable: bool) -> VortexResult<ArrayRef> {
829    from_arrow_struct(&arrow_array::StructArray::from(batch.clone()), nullable)
830}
831
832#[cfg(test)]
833mod tests {
834    use std::ops::Range;
835    use std::sync::Arc;
836    use std::sync::LazyLock;
837
838    use arrow_array::Array as ArrowArray;
839    use arrow_array::BinaryArray;
840    use arrow_array::BooleanArray;
841    use arrow_array::Date32Array;
842    use arrow_array::Date64Array;
843    use arrow_array::Decimal128Array;
844    use arrow_array::Decimal256Array;
845    use arrow_array::FixedSizeListArray as ArrowFixedSizeListArray;
846    use arrow_array::Float32Array;
847    use arrow_array::Float64Array;
848    use arrow_array::GenericListViewArray;
849    use arrow_array::Int8Array;
850    use arrow_array::Int16Array;
851    use arrow_array::Int32Array;
852    use arrow_array::Int64Array;
853    use arrow_array::LargeBinaryArray;
854    use arrow_array::LargeStringArray;
855    use arrow_array::NullArray;
856    use arrow_array::RecordBatch;
857    use arrow_array::StringArray;
858    use arrow_array::StructArray;
859    use arrow_array::Time32MillisecondArray;
860    use arrow_array::Time32SecondArray;
861    use arrow_array::Time64MicrosecondArray;
862    use arrow_array::Time64NanosecondArray;
863    use arrow_array::TimestampMicrosecondArray;
864    use arrow_array::TimestampMillisecondArray;
865    use arrow_array::TimestampNanosecondArray;
866    use arrow_array::TimestampSecondArray;
867    use arrow_array::UInt8Array;
868    use arrow_array::UInt16Array;
869    use arrow_array::UInt32Array;
870    use arrow_array::UInt64Array;
871    use arrow_array::builder::BinaryViewBuilder;
872    use arrow_array::builder::Decimal128Builder;
873    use arrow_array::builder::Decimal256Builder;
874    use arrow_array::builder::Int32Builder;
875    use arrow_array::builder::Int64Builder;
876    use arrow_array::builder::LargeListBuilder;
877    use arrow_array::builder::ListBuilder;
878    use arrow_array::builder::MapBuilder as ArrowMapBuilder;
879    use arrow_array::builder::StringBuilder;
880    use arrow_array::builder::StringViewBuilder;
881    use arrow_array::new_null_array;
882    use arrow_array::types::ArrowPrimitiveType;
883    use arrow_array::types::Float16Type;
884    use arrow_buffer::BooleanBuffer;
885    use arrow_buffer::Buffer as ArrowBuffer;
886    use arrow_buffer::NullBuffer;
887    use arrow_buffer::OffsetBuffer;
888    use arrow_buffer::ScalarBuffer;
889    use arrow_schema::DataType;
890    use arrow_schema::Field;
891    use arrow_schema::Fields;
892    use arrow_schema::Schema;
893    use rstest::rstest;
894    use vortex_array::IntoArray;
895    use vortex_array::VortexSessionExecute as _;
896    use vortex_array::arrays::BoolArray;
897    use vortex_array::arrays::Decimal;
898    use vortex_array::arrays::DecimalArray;
899    use vortex_array::arrays::FixedSizeList;
900    use vortex_array::arrays::FixedSizeListArray as VortexFixedSizeListArray;
901    use vortex_array::arrays::List;
902    use vortex_array::arrays::ListArray;
903    use vortex_array::arrays::ListView;
904    use vortex_array::arrays::ListViewArray;
905    use vortex_array::arrays::NullArray as VortexNullArray;
906    use vortex_array::arrays::Primitive;
907    use vortex_array::arrays::PrimitiveArray;
908    use vortex_array::arrays::Struct;
909    use vortex_array::arrays::StructArray as VortexStructArray;
910    use vortex_array::arrays::TemporalArray;
911    use vortex_array::arrays::VarBinArray;
912    use vortex_array::arrays::VarBinView;
913    use vortex_array::arrays::fixed_size_list::FixedSizeListArrayExt;
914    use vortex_array::arrays::fixed_size_list::FixedSizeListArraySlotsExt;
915    use vortex_array::arrays::list::ListArraySlotsExt;
916    use vortex_array::arrays::listview::ListViewArraySlotsExt;
917    use vortex_array::arrays::struct_::StructArrayExt;
918    use vortex_array::assert_arrays_eq;
919    use vortex_array::dtype::DType;
920    use vortex_array::dtype::DecimalDType;
921    use vortex_array::dtype::DecimalType;
922    use vortex_array::dtype::Nullability;
923    use vortex_array::dtype::PType;
924    use vortex_array::dtype::i256;
925    use vortex_array::extension::datetime::TimeUnit;
926    use vortex_array::extension::datetime::Timestamp;
927    use vortex_array::scalar::Scalar;
928    use vortex_array::validity::Validity;
929    use vortex_buffer::buffer;
930    use vortex_error::VortexResult;
931    use vortex_session::VortexSession;
932
933    use crate::IntoVortexArray as _;
934    use crate::convert::from_arrow_batch;
935    use crate::convert::from_arrow_dyn;
936    use crate::convert::from_arrow_temporal;
937
938    static SESSION: LazyLock<VortexSession> = LazyLock::new(VortexSession::empty);
939
940    #[rstest]
941    #[case::i8(
942        Arc::new(Int8Array::from(vec![Some(1), None, Some(3), Some(4)])),
943        Arc::new(Int8Array::from(vec![1, 2, 3, 4])),
944        PType::I8,
945    )]
946    #[case::i16(
947        Arc::new(Int16Array::from(vec![Some(100), None, Some(300), Some(400)])),
948        Arc::new(Int16Array::from(vec![100, 200, 300, 400])),
949        PType::I16,
950    )]
951    #[case::i32(
952        Arc::new(Int32Array::from(vec![Some(1000), None, Some(3000), Some(4000)])),
953        Arc::new(Int32Array::from(vec![1000, 2000, 3000, 4000])),
954        PType::I32,
955    )]
956    #[case::i64(
957        Arc::new(Int64Array::from(vec![Some(10000), None, Some(30000), Some(40000)])),
958        Arc::new(Int64Array::from(vec![10000_i64, 20000, 30000, 40000])),
959        PType::I64,
960    )]
961    #[case::u8(
962        Arc::new(UInt8Array::from(vec![Some(1), None, Some(3), Some(4)])),
963        Arc::new(UInt8Array::from(vec![1_u8, 2, 3, 4])),
964        PType::U8,
965    )]
966    #[case::u16(
967        Arc::new(UInt16Array::from(vec![Some(100), None, Some(300), Some(400)])),
968        Arc::new(UInt16Array::from(vec![100_u16, 200, 300, 400])),
969        PType::U16,
970    )]
971    #[case::u32(
972        Arc::new(UInt32Array::from(vec![Some(1000), None, Some(3000), Some(4000)])),
973        Arc::new(UInt32Array::from(vec![1000_u32, 2000, 3000, 4000])),
974        PType::U32,
975    )]
976    #[case::u64(
977        Arc::new(UInt64Array::from(vec![Some(10000), None, Some(30000), Some(40000)])),
978        Arc::new(UInt64Array::from(vec![10000_u64, 20000, 30000, 40000])),
979        PType::U64,
980    )]
981    #[case::f32(
982        Arc::new(Float32Array::from(vec![Some(1.5), None, Some(3.5), Some(4.5)])),
983        Arc::new(Float32Array::from(vec![1.5_f32, 2.5, 3.5, 4.5])),
984        PType::F32,
985    )]
986    #[case::f64(
987        Arc::new(Float64Array::from(vec![Some(1.5), None, Some(3.5), Some(4.5)])),
988        Arc::new(Float64Array::from(vec![1.5_f64, 2.5, 3.5, 4.5])),
989        PType::F64,
990    )]
991    fn test_primitive_array_conversion(
992        #[case] nullable: Arc<dyn ArrowArray>,
993        #[case] non_nullable: Arc<dyn ArrowArray>,
994        #[case] expected_ptype: PType,
995    ) {
996        let v_null = from_arrow_dyn(nullable.as_ref(), true).unwrap();
997        let v_non_null = from_arrow_dyn(non_nullable.as_ref(), false).unwrap();
998        assert_eq!(v_null.len(), 4);
999        assert_eq!(v_non_null.len(), 4);
1000        assert_eq!(v_null.as_::<Primitive>().ptype(), expected_ptype);
1001        assert_eq!(v_non_null.as_::<Primitive>().ptype(), expected_ptype);
1002        let (expected_nullable, expected_non_nullable) = match expected_ptype {
1003            PType::I8 => (
1004                PrimitiveArray::from_option_iter([Some(1i8), None, Some(3), Some(4)]),
1005                PrimitiveArray::from_iter([1i8, 2, 3, 4]),
1006            ),
1007            PType::I16 => (
1008                PrimitiveArray::from_option_iter([Some(100i16), None, Some(300), Some(400)]),
1009                PrimitiveArray::from_iter([100i16, 200, 300, 400]),
1010            ),
1011            PType::I32 => (
1012                PrimitiveArray::from_option_iter([Some(1000i32), None, Some(3000), Some(4000)]),
1013                PrimitiveArray::from_iter([1000i32, 2000, 3000, 4000]),
1014            ),
1015            PType::I64 => (
1016                PrimitiveArray::from_option_iter([Some(10000i64), None, Some(30000), Some(40000)]),
1017                PrimitiveArray::from_iter([10000i64, 20000, 30000, 40000]),
1018            ),
1019            PType::U8 => (
1020                PrimitiveArray::from_option_iter([Some(1u8), None, Some(3), Some(4)]),
1021                PrimitiveArray::from_iter([1u8, 2, 3, 4]),
1022            ),
1023            PType::U16 => (
1024                PrimitiveArray::from_option_iter([Some(100u16), None, Some(300), Some(400)]),
1025                PrimitiveArray::from_iter([100u16, 200, 300, 400]),
1026            ),
1027            PType::U32 => (
1028                PrimitiveArray::from_option_iter([Some(1000u32), None, Some(3000), Some(4000)]),
1029                PrimitiveArray::from_iter([1000u32, 2000, 3000, 4000]),
1030            ),
1031            PType::U64 => (
1032                PrimitiveArray::from_option_iter([Some(10000u64), None, Some(30000), Some(40000)]),
1033                PrimitiveArray::from_iter([10000u64, 20000, 30000, 40000]),
1034            ),
1035            PType::F32 => (
1036                PrimitiveArray::from_option_iter([Some(1.5f32), None, Some(3.5), Some(4.5)]),
1037                PrimitiveArray::from_iter([1.5f32, 2.5, 3.5, 4.5]),
1038            ),
1039            PType::F64 => (
1040                PrimitiveArray::from_option_iter([Some(1.5f64), None, Some(3.5), Some(4.5)]),
1041                PrimitiveArray::from_iter([1.5f64, 2.5, 3.5, 4.5]),
1042            ),
1043            _ => unreachable!(),
1044        };
1045        assert_arrays_eq!(
1046            v_null,
1047            expected_nullable,
1048            &mut SESSION.create_execution_ctx()
1049        );
1050        assert_arrays_eq!(
1051            v_non_null,
1052            expected_non_nullable,
1053            &mut SESSION.create_execution_ctx()
1054        );
1055    }
1056
1057    #[test]
1058    fn test_reject_timestamp_array_invalid_timezone() {
1059        let array = TimestampSecondArray::from(vec![0]).with_timezone("Not/A/Timezone");
1060        assert!(from_arrow_temporal(&array, false).is_err());
1061    }
1062
1063    #[test]
1064    fn test_float16_array_conversion() {
1065        let values = vec![
1066            Some(<Float16Type as ArrowPrimitiveType>::Native::from_f32(1.5)),
1067            None,
1068            Some(<Float16Type as ArrowPrimitiveType>::Native::from_f32(3.5)),
1069        ];
1070        let arrow_array = arrow_array::PrimitiveArray::<Float16Type>::from(values);
1071        let vortex_array = from_arrow_dyn(&arrow_array, true).unwrap();
1072
1073        let non_null_values = vec![
1074            <Float16Type as ArrowPrimitiveType>::Native::from_f32(1.5),
1075            <Float16Type as ArrowPrimitiveType>::Native::from_f32(2.5),
1076        ];
1077        let arrow_array_non_null =
1078            arrow_array::PrimitiveArray::<Float16Type>::from(non_null_values);
1079        let vortex_array_non_null = from_arrow_dyn(&arrow_array_non_null, false).unwrap();
1080
1081        assert_eq!(vortex_array.len(), 3);
1082        assert_eq!(vortex_array_non_null.len(), 2);
1083
1084        // Verify metadata - should be PrimitiveArray with F16 ptype
1085        let primitive_array = vortex_array.as_::<Primitive>();
1086        assert_eq!(primitive_array.ptype(), PType::F16);
1087
1088        let primitive_array_non_null = vortex_array_non_null.as_::<Primitive>();
1089        assert_eq!(primitive_array_non_null.ptype(), PType::F16);
1090        assert_arrays_eq!(
1091            vortex_array,
1092            PrimitiveArray::from_option_iter([
1093                Some(<Float16Type as ArrowPrimitiveType>::Native::from_f32(1.5)),
1094                None,
1095                Some(<Float16Type as ArrowPrimitiveType>::Native::from_f32(3.5))
1096            ]),
1097            &mut SESSION.create_execution_ctx()
1098        );
1099        assert_arrays_eq!(
1100            vortex_array_non_null,
1101            PrimitiveArray::from_iter([
1102                <Float16Type as ArrowPrimitiveType>::Native::from_f32(1.5),
1103                <Float16Type as ArrowPrimitiveType>::Native::from_f32(2.5)
1104            ]),
1105            &mut SESSION.create_execution_ctx()
1106        );
1107    }
1108
1109    // Test decimal array conversions
1110    #[test]
1111    fn test_decimal128_array_conversion() {
1112        let mut builder = Decimal128Builder::with_capacity(4);
1113        builder.append_value(12345);
1114        builder.append_null();
1115        builder.append_value(67890);
1116        builder.append_value(11111);
1117        let decimal_array = builder.finish().with_precision_and_scale(10, 2).unwrap();
1118
1119        let vortex_array = from_arrow_dyn(&decimal_array, true).unwrap();
1120        assert_eq!(vortex_array.len(), 4);
1121
1122        let mut builder_non_null = Decimal128Builder::with_capacity(3);
1123        builder_non_null.append_value(12345);
1124        builder_non_null.append_value(67890);
1125        builder_non_null.append_value(11111);
1126        let decimal_array_non_null = builder_non_null
1127            .finish()
1128            .with_precision_and_scale(10, 2)
1129            .unwrap();
1130
1131        let vortex_array_non_null = from_arrow_dyn(&decimal_array_non_null, false).unwrap();
1132        assert_eq!(vortex_array_non_null.len(), 3);
1133
1134        // Verify metadata: a DecimalArray with the precision, scale and canonical width
1135        let decimal_vortex_array = vortex_array.as_::<Decimal>();
1136        assert_eq!(decimal_vortex_array.decimal_dtype().precision(), 10);
1137        assert_eq!(decimal_vortex_array.decimal_dtype().scale(), 2);
1138        assert_eq!(decimal_vortex_array.values_type(), DecimalType::I64);
1139
1140        let decimal_vortex_array_non_null = vortex_array_non_null.as_::<Decimal>();
1141        assert_eq!(
1142            decimal_vortex_array_non_null.decimal_dtype().precision(),
1143            10
1144        );
1145        assert_eq!(decimal_vortex_array_non_null.decimal_dtype().scale(), 2);
1146        assert_eq!(
1147            decimal_vortex_array_non_null.values_type(),
1148            DecimalType::I64
1149        );
1150        assert_arrays_eq!(
1151            vortex_array,
1152            DecimalArray::from_option_iter(
1153                [Some(12345i64), None, Some(67890i64), Some(11111i64)],
1154                DecimalDType::new(10, 2)
1155            ),
1156            &mut SESSION.create_execution_ctx()
1157        );
1158        assert_arrays_eq!(
1159            vortex_array_non_null,
1160            DecimalArray::from_iter([12345i64, 67890i64, 11111i64], DecimalDType::new(10, 2)),
1161            &mut SESSION.create_execution_ctx()
1162        );
1163    }
1164
1165    #[test]
1166    fn test_decimal256_array_conversion() {
1167        let mut builder = Decimal256Builder::with_capacity(4);
1168        builder.append_value(arrow_buffer::i256::from_i128(12345));
1169        builder.append_null();
1170        builder.append_value(arrow_buffer::i256::from_i128(67890));
1171        builder.append_value(arrow_buffer::i256::from_i128(11111));
1172        let decimal_array = builder.finish().with_precision_and_scale(38, 10).unwrap();
1173
1174        let vortex_array = from_arrow_dyn(&decimal_array, true).unwrap();
1175        assert_eq!(vortex_array.len(), 4);
1176
1177        let mut builder_non_null = Decimal256Builder::with_capacity(3);
1178        builder_non_null.append_value(arrow_buffer::i256::from_i128(12345));
1179        builder_non_null.append_value(arrow_buffer::i256::from_i128(67890));
1180        builder_non_null.append_value(arrow_buffer::i256::from_i128(11111));
1181        let decimal_array_non_null = builder_non_null
1182            .finish()
1183            .with_precision_and_scale(38, 10)
1184            .unwrap();
1185
1186        let vortex_array_non_null = from_arrow_dyn(&decimal_array_non_null, false).unwrap();
1187        assert_eq!(vortex_array_non_null.len(), 3);
1188
1189        // Verify metadata: a DecimalArray with the precision, scale and canonical width
1190        let decimal_vortex_array = vortex_array.as_::<Decimal>();
1191        assert_eq!(decimal_vortex_array.decimal_dtype().precision(), 38);
1192        assert_eq!(decimal_vortex_array.decimal_dtype().scale(), 10);
1193        assert_eq!(decimal_vortex_array.values_type(), DecimalType::I128);
1194
1195        let decimal_vortex_array_non_null = vortex_array_non_null.as_::<Decimal>();
1196        assert_eq!(
1197            decimal_vortex_array_non_null.decimal_dtype().precision(),
1198            38
1199        );
1200        assert_eq!(decimal_vortex_array_non_null.decimal_dtype().scale(), 10);
1201        assert_eq!(
1202            decimal_vortex_array_non_null.values_type(),
1203            DecimalType::I128
1204        );
1205        assert_arrays_eq!(
1206            vortex_array,
1207            DecimalArray::from_option_iter(
1208                [Some(12345i128), None, Some(67890i128), Some(11111i128)],
1209                DecimalDType::new(38, 10)
1210            ),
1211            &mut SESSION.create_execution_ctx()
1212        );
1213        assert_arrays_eq!(
1214            vortex_array_non_null,
1215            DecimalArray::from_iter([12345i128, 67890i128, 11111i128], DecimalDType::new(38, 10)),
1216            &mut SESSION.create_execution_ctx()
1217        );
1218    }
1219
1220    #[rstest]
1221    #[case::decimal32_p4(DataType::Decimal32(4, 2), DecimalType::I16, false)]
1222    #[case::decimal64_p9(DataType::Decimal64(9, 2), DecimalType::I32, false)]
1223    #[case::decimal128_p5(DataType::Decimal128(5, 2), DecimalType::I32, false)]
1224    #[case::decimal128_p18(DataType::Decimal128(18, 2), DecimalType::I64, false)]
1225    #[case::decimal128_p38(DataType::Decimal128(38, 2), DecimalType::I128, true)]
1226    #[case::decimal256_p38(DataType::Decimal256(38, 2), DecimalType::I128, false)]
1227    #[case::decimal256_p40(DataType::Decimal256(40, 2), DecimalType::I256, true)]
1228    fn test_decimal_import_canonical_width(
1229        #[case] data_type: DataType,
1230        #[case] values_type: DecimalType,
1231        #[case] zero_copy: bool,
1232    ) -> VortexResult<()> {
1233        let (precision, scale) = match data_type {
1234            DataType::Decimal32(precision, scale)
1235            | DataType::Decimal64(precision, scale)
1236            | DataType::Decimal128(precision, scale)
1237            | DataType::Decimal256(precision, scale) => (precision, scale),
1238            _ => unreachable!("every case is an Arrow decimal type, got {data_type}"),
1239        };
1240
1241        // The largest and smallest values of the precision, around a null and a zero.
1242        let max = i256::from_i128(10).wrapping_pow(u32::from(precision)) - i256::ONE;
1243        let values = [Some(-max), None, Some(i256::ZERO), Some(max)];
1244        let arrow_values = values.map(|value| value.map(arrow_buffer::i256::from));
1245        let bounds =
1246            Decimal256Array::from_iter(arrow_values).with_precision_and_scale(precision, scale)?;
1247        let arrow = arrow_cast::cast(&bounds, &data_type)?;
1248
1249        let imported = from_arrow_dyn(arrow.as_ref(), true)?;
1250        let decimal = imported.as_::<Decimal>();
1251        assert_eq!(decimal.values_type(), values_type);
1252        if zero_copy {
1253            assert_eq!(
1254                decimal.buffer_handle().as_host().as_ptr(),
1255                arrow.to_data().buffers()[0].as_ptr()
1256            );
1257        }
1258
1259        assert_arrays_eq!(
1260            imported,
1261            DecimalArray::from_option_iter(values, DecimalDType::new(precision, scale)),
1262            &mut SESSION.create_execution_ctx()
1263        );
1264        Ok(())
1265    }
1266
1267    /// The null slot holds 10^30, which is outside both precisions and does not fit `i32`.
1268    #[rstest]
1269    #[case::narrowing(5, false)]
1270    #[case::equal_width(20, true)]
1271    fn test_decimal_import_ignores_null_slots(
1272        #[case] precision: u8,
1273        #[case] zero_copy: bool,
1274    ) -> VortexResult<()> {
1275        let arrow = Decimal128Array::new(
1276            ScalarBuffer::from(vec![12_345, 10i128.pow(30), -12_345]),
1277            Some(NullBuffer::from(vec![true, false, true])),
1278        )
1279        .with_precision_and_scale(precision, 2)?;
1280
1281        let imported = from_arrow_dyn(&arrow, true)?;
1282        let decimal = imported.as_::<Decimal>();
1283        if zero_copy {
1284            assert_eq!(
1285                decimal.buffer_handle().as_host().as_ptr(),
1286                arrow.to_data().buffers()[0].as_ptr()
1287            );
1288        } else {
1289            // A narrowing copy writes zeros into the null slots.
1290            assert_eq!(decimal.values_type(), DecimalType::I32);
1291            assert_eq!(decimal.buffer::<i32>().as_slice(), &[12_345, 0, -12_345]);
1292        }
1293
1294        assert_arrays_eq!(
1295            imported,
1296            DecimalArray::from_option_iter(
1297                [Some(12_345i128), None, Some(-12_345)],
1298                DecimalDType::new(precision, 2)
1299            ),
1300            &mut SESSION.create_execution_ctx()
1301        );
1302        Ok(())
1303    }
1304
1305    #[test]
1306    fn test_decimal_import_rejects_value_outside_precision() -> VortexResult<()> {
1307        let arrow =
1308            Decimal128Array::from(vec![12_345, 1_000_000]).with_precision_and_scale(5, 2)?;
1309
1310        let err = from_arrow_dyn(&arrow, true)
1311            .expect_err("a valid value outside the precision must fail the import");
1312        let message = err.to_string();
1313        assert!(message.contains("row 1"), "{message}");
1314        assert!(message.contains("null_if_overflow_precision"), "{message}");
1315        Ok(())
1316    }
1317
1318    #[test]
1319    fn test_decimal_import_zero_copy_rejects_value_outside_precision() -> VortexResult<()> {
1320        let arrow =
1321            Decimal128Array::from(vec![12_345, 10i128.pow(20)]).with_precision_and_scale(20, 2)?;
1322
1323        let err = from_arrow_dyn(&arrow, true)
1324            .expect_err("a valid value outside the precision must fail the import");
1325        let message = err.to_string();
1326        assert!(message.contains("row 1"), "{message}");
1327        assert!(message.contains("null_if_overflow_precision"), "{message}");
1328        Ok(())
1329    }
1330
1331    #[rstest]
1332    #[case::precision_zero(DataType::Decimal128(0, 0))]
1333    #[case::precision_above_max(DataType::Decimal128(77, 0))]
1334    #[case::scale_above_precision(DataType::Decimal128(5, 6))]
1335    fn test_decimal_import_rejects_invalid_precision(#[case] data_type: DataType) {
1336        // `with_data_type` does not validate the precision or scale, as an FFI import would not.
1337        let arrow = Decimal128Array::from(vec![1]).with_data_type(data_type);
1338
1339        assert!(from_arrow_dyn(&arrow, true).is_err());
1340    }
1341
1342    // Test temporal array conversions
1343    #[rstest]
1344    #[case::timestamp_second(
1345        Arc::new(TimestampSecondArray::from(vec![Some(1000), None, Some(3000), Some(4000)])),
1346        Arc::new(TimestampSecondArray::from(vec![1000_i64, 2000, 3000, 4000])),
1347    )]
1348    #[case::timestamp_millisecond(
1349        Arc::new(TimestampMillisecondArray::from(vec![Some(1000), None, Some(3000), Some(4000)])),
1350        Arc::new(TimestampMillisecondArray::from(vec![1000_i64, 2000, 3000, 4000])),
1351    )]
1352    #[case::timestamp_microsecond(
1353        Arc::new(TimestampMicrosecondArray::from(vec![Some(1000), None, Some(3000), Some(4000)])),
1354        Arc::new(TimestampMicrosecondArray::from(vec![1000_i64, 2000, 3000, 4000])),
1355    )]
1356    #[case::timestamp_nanosecond(
1357        Arc::new(TimestampNanosecondArray::from(vec![Some(1000), None, Some(3000), Some(4000)])),
1358        Arc::new(TimestampNanosecondArray::from(vec![1000_i64, 2000, 3000, 4000])),
1359    )]
1360    #[case::time32_second(
1361        Arc::new(Time32SecondArray::from(vec![Some(1000), None, Some(3000), Some(4000)])),
1362        Arc::new(Time32SecondArray::from(vec![1000_i32, 2000, 3000, 4000])),
1363    )]
1364    #[case::time32_millisecond(
1365        Arc::new(Time32MillisecondArray::from(vec![Some(1000), None, Some(3000), Some(4000)])),
1366        Arc::new(Time32MillisecondArray::from(vec![1000_i32, 2000, 3000, 4000])),
1367    )]
1368    #[case::time64_microsecond(
1369        Arc::new(Time64MicrosecondArray::from(vec![Some(1000), None, Some(3000), Some(4000)])),
1370        Arc::new(Time64MicrosecondArray::from(vec![1000_i64, 2000, 3000, 4000])),
1371    )]
1372    #[case::time64_nanosecond(
1373        Arc::new(Time64NanosecondArray::from(vec![Some(1000), None, Some(3000), Some(4000)])),
1374        Arc::new(Time64NanosecondArray::from(vec![1000_i64, 2000, 3000, 4000])),
1375    )]
1376    #[case::date32(
1377        Arc::new(Date32Array::from(vec![Some(18000), None, Some(18002), Some(18003)])),
1378        Arc::new(Date32Array::from(vec![18000_i32, 18001, 18002, 18003])),
1379    )]
1380    #[case::date64(
1381        Arc::new(Date64Array::from(vec![Some(1555200000000), None, Some(1555286400000), Some(1555372800000)]
1382        )),
1383        Arc::new(Date64Array::from(vec![1555200000000_i64, 1555213600000, 1555286400000, 1555372800000]
1384        )),
1385    )]
1386    fn test_temporal_array_conversion(
1387        #[case] nullable: Arc<dyn ArrowArray>,
1388        #[case] non_nullable: Arc<dyn ArrowArray>,
1389    ) {
1390        let v_null = from_arrow_dyn(nullable.as_ref(), true).unwrap();
1391        let v_non_null = from_arrow_dyn(non_nullable.as_ref(), false).unwrap();
1392        assert_eq!(v_null.len(), 4);
1393        assert_eq!(v_non_null.len(), 4);
1394        let expected = |nullable: bool| {
1395            let i32_values = if nullable {
1396                PrimitiveArray::from_option_iter([Some(1000i32), None, Some(3000), Some(4000)])
1397            } else {
1398                PrimitiveArray::from_iter([1000i32, 2000, 3000, 4000])
1399            }
1400            .into_array();
1401            let i64_values = if nullable {
1402                PrimitiveArray::from_option_iter([Some(1000i64), None, Some(3000), Some(4000)])
1403            } else {
1404                PrimitiveArray::from_iter([1000i64, 2000, 3000, 4000])
1405            }
1406            .into_array();
1407            match non_nullable.data_type() {
1408                DataType::Timestamp(unit, _) => {
1409                    let unit = match unit {
1410                        arrow_schema::TimeUnit::Second => TimeUnit::Seconds,
1411                        arrow_schema::TimeUnit::Millisecond => TimeUnit::Milliseconds,
1412                        arrow_schema::TimeUnit::Microsecond => TimeUnit::Microseconds,
1413                        arrow_schema::TimeUnit::Nanosecond => TimeUnit::Nanoseconds,
1414                    };
1415                    TemporalArray::new_timestamp(i64_values, unit, None).into_array()
1416                }
1417                DataType::Time32(arrow_schema::TimeUnit::Second) => {
1418                    TemporalArray::new_time(i32_values, TimeUnit::Seconds).into_array()
1419                }
1420                DataType::Time32(arrow_schema::TimeUnit::Millisecond) => {
1421                    TemporalArray::new_time(i32_values, TimeUnit::Milliseconds).into_array()
1422                }
1423                DataType::Time64(arrow_schema::TimeUnit::Microsecond) => {
1424                    TemporalArray::new_time(i64_values, TimeUnit::Microseconds).into_array()
1425                }
1426                DataType::Time64(arrow_schema::TimeUnit::Nanosecond) => {
1427                    TemporalArray::new_time(i64_values, TimeUnit::Nanoseconds).into_array()
1428                }
1429                DataType::Date32 => TemporalArray::new_date(
1430                    if nullable {
1431                        PrimitiveArray::from_option_iter([
1432                            Some(18000i32),
1433                            None,
1434                            Some(18002),
1435                            Some(18003),
1436                        ])
1437                    } else {
1438                        PrimitiveArray::from_iter([18000i32, 18001, 18002, 18003])
1439                    }
1440                    .into_array(),
1441                    TimeUnit::Days,
1442                )
1443                .into_array(),
1444                DataType::Date64 => TemporalArray::new_date(
1445                    if nullable {
1446                        PrimitiveArray::from_option_iter([
1447                            Some(1555200000000i64),
1448                            None,
1449                            Some(1555286400000),
1450                            Some(1555372800000),
1451                        ])
1452                    } else {
1453                        PrimitiveArray::from_iter([
1454                            1555200000000i64,
1455                            1555213600000,
1456                            1555286400000,
1457                            1555372800000,
1458                        ])
1459                    }
1460                    .into_array(),
1461                    TimeUnit::Milliseconds,
1462                )
1463                .into_array(),
1464                _ => unreachable!(),
1465            }
1466        };
1467        assert_arrays_eq!(v_null, expected(true), &mut SESSION.create_execution_ctx());
1468        assert_arrays_eq!(
1469            v_non_null,
1470            expected(false),
1471            &mut SESSION.create_execution_ctx()
1472        );
1473    }
1474
1475    #[test]
1476    fn test_timestamp_timezone_microsecond_array_conversion() {
1477        let arrow_array =
1478            TimestampMicrosecondArray::from(vec![Some(1000), None, Some(3000), Some(4000)])
1479                .with_timezone("UTC");
1480        let vortex_array = from_arrow_dyn(&arrow_array, true).unwrap();
1481
1482        let arrow_array_non_null =
1483            TimestampMicrosecondArray::from(vec![1000_i64, 2000, 3000, 4000]).with_timezone("UTC");
1484        let vortex_array_non_null = from_arrow_dyn(&arrow_array_non_null, false).unwrap();
1485
1486        assert_eq!(vortex_array.len(), 4);
1487        assert_eq!(
1488            vortex_array.dtype(),
1489            &DType::Extension(
1490                Timestamp::new_with_tz(
1491                    TimeUnit::Microseconds,
1492                    Some("UTC".into()),
1493                    Nullability::Nullable
1494                )
1495                .erased()
1496            ),
1497        );
1498        assert_eq!(vortex_array_non_null.len(), 4);
1499        assert_eq!(
1500            vortex_array_non_null.dtype(),
1501            &DType::Extension(
1502                Timestamp::new_with_tz(
1503                    TimeUnit::Microseconds,
1504                    Some("UTC".into()),
1505                    Nullability::NonNullable
1506                )
1507                .erased()
1508            )
1509        );
1510        assert_arrays_eq!(
1511            vortex_array,
1512            TemporalArray::new_timestamp(
1513                PrimitiveArray::from_option_iter([Some(1000i64), None, Some(3000), Some(4000)])
1514                    .into_array(),
1515                TimeUnit::Microseconds,
1516                Some("UTC".into())
1517            ),
1518            &mut SESSION.create_execution_ctx()
1519        );
1520        assert_arrays_eq!(
1521            vortex_array_non_null,
1522            TemporalArray::new_timestamp(
1523                buffer![1000i64, 2000, 3000, 4000].into_array(),
1524                TimeUnit::Microseconds,
1525                Some("UTC".into())
1526            ),
1527            &mut SESSION.create_execution_ctx()
1528        );
1529    }
1530
1531    // Test string/binary array conversions
1532    #[rstest]
1533    #[case::utf8(
1534        Arc::new(StringArray::from(vec![Some("hello"), None, Some("world"), Some("test")])),
1535        Arc::new(StringArray::from(vec!["hello", "world", "test", "vortex"])),
1536        DType::Utf8(Nullability::NonNullable),
1537    )]
1538    #[case::large_utf8(
1539        Arc::new(LargeStringArray::from(vec![Some("hello"), None, Some("world"), Some("test")])),
1540        Arc::new(LargeStringArray::from(vec!["hello", "world", "test", "vortex"])),
1541        DType::Utf8(Nullability::NonNullable),
1542    )]
1543    #[case::binary(
1544        Arc::new(BinaryArray::from(vec![
1545            Some("hello".as_bytes()), None, Some("world".as_bytes()), Some("test".as_bytes()),
1546        ])),
1547        Arc::new(BinaryArray::from(vec![
1548            "hello".as_bytes(), "world".as_bytes(), "test".as_bytes(), "vortex".as_bytes(),
1549        ])),
1550        DType::Binary(Nullability::NonNullable),
1551    )]
1552    #[case::large_binary(
1553        Arc::new(LargeBinaryArray::from(vec![
1554            Some("hello".as_bytes()), None, Some("world".as_bytes()), Some("test".as_bytes()),
1555        ])),
1556        Arc::new(LargeBinaryArray::from(vec![
1557            "hello".as_bytes(), "world".as_bytes(), "test".as_bytes(), "vortex".as_bytes(),
1558        ])),
1559        DType::Binary(Nullability::NonNullable),
1560    )]
1561    fn test_string_binary_array_conversion(
1562        #[case] nullable: Arc<dyn ArrowArray>,
1563        #[case] non_nullable: Arc<dyn ArrowArray>,
1564        #[case] expected_non_nullable_dtype: DType,
1565    ) {
1566        let v_null = from_arrow_dyn(nullable.as_ref(), true).unwrap();
1567        let v_non_null = from_arrow_dyn(non_nullable.as_ref(), false).unwrap();
1568        assert_eq!(v_null.len(), 4);
1569        assert_eq!(v_non_null.len(), 4);
1570        assert_eq!(v_null.dtype(), &expected_non_nullable_dtype.as_nullable());
1571        assert_eq!(v_non_null.dtype(), &expected_non_nullable_dtype);
1572        assert_arrays_eq!(
1573            v_null,
1574            VarBinArray::from_iter(
1575                [Some("hello"), None, Some("world"), Some("test")],
1576                expected_non_nullable_dtype.as_nullable()
1577            ),
1578            &mut SESSION.create_execution_ctx()
1579        );
1580        assert_arrays_eq!(
1581            v_non_null,
1582            VarBinArray::from_iter_nonnull(
1583                ["hello", "world", "test", "vortex"],
1584                expected_non_nullable_dtype
1585            ),
1586            &mut SESSION.create_execution_ctx()
1587        );
1588    }
1589
1590    #[test]
1591    fn test_utf8_view_array_conversion() {
1592        let mut builder = StringViewBuilder::new();
1593        builder.append_value("hello");
1594        builder.append_null();
1595        builder.append_value("world");
1596        builder.append_value("test");
1597        let arrow_array = builder.finish();
1598        let vortex_array = from_arrow_dyn(&arrow_array, true).unwrap();
1599
1600        let mut builder_non_null = StringViewBuilder::new();
1601        builder_non_null.append_value("hello");
1602        builder_non_null.append_value("world");
1603        builder_non_null.append_value("test");
1604        builder_non_null.append_value("vortex");
1605        let arrow_array_non_null = builder_non_null.finish();
1606        let vortex_array_non_null = from_arrow_dyn(&arrow_array_non_null, false).unwrap();
1607
1608        assert_eq!(vortex_array.len(), 4);
1609        assert_eq!(vortex_array_non_null.len(), 4);
1610
1611        // Verify metadata - should be VarBinViewArray with correct buffer count and dtype
1612        let varbin_view_array = vortex_array.as_::<VarBinView>();
1613        assert_eq!(
1614            varbin_view_array.data_buffers().len(),
1615            arrow_array.data_buffers().len()
1616        );
1617        assert_eq!(varbin_view_array.dtype(), &DType::Utf8(true.into()));
1618
1619        let varbin_view_array_non_null = vortex_array_non_null.as_::<VarBinView>();
1620        assert_eq!(
1621            varbin_view_array_non_null.data_buffers().len(),
1622            arrow_array_non_null.data_buffers().len()
1623        );
1624        assert_eq!(
1625            varbin_view_array_non_null.dtype(),
1626            &DType::Utf8(false.into())
1627        );
1628        assert_arrays_eq!(
1629            vortex_array,
1630            VarBinArray::from_iter(
1631                [Some("hello"), None, Some("world"), Some("test")],
1632                DType::Utf8(Nullability::NonNullable).as_nullable()
1633            ),
1634            &mut SESSION.create_execution_ctx()
1635        );
1636        assert_arrays_eq!(
1637            vortex_array_non_null,
1638            VarBinArray::from_iter_nonnull(
1639                ["hello", "world", "test", "vortex"],
1640                DType::Utf8(Nullability::NonNullable)
1641            ),
1642            &mut SESSION.create_execution_ctx()
1643        );
1644    }
1645
1646    #[test]
1647    fn test_binary_view_array_conversion() {
1648        let mut builder = BinaryViewBuilder::new();
1649        builder.append_value(b"hello");
1650        builder.append_null();
1651        builder.append_value(b"world");
1652        builder.append_value(b"test");
1653        let arrow_array = builder.finish();
1654        let vortex_array = from_arrow_dyn(&arrow_array, true).unwrap();
1655
1656        let mut builder_non_null = BinaryViewBuilder::new();
1657        builder_non_null.append_value(b"hello");
1658        builder_non_null.append_value(b"world");
1659        builder_non_null.append_value(b"test");
1660        builder_non_null.append_value(b"vortex");
1661        let arrow_array_non_null = builder_non_null.finish();
1662        let vortex_array_non_null = from_arrow_dyn(&arrow_array_non_null, false).unwrap();
1663
1664        assert_eq!(vortex_array.len(), 4);
1665        assert_eq!(vortex_array_non_null.len(), 4);
1666
1667        // Verify metadata - should be VarBinViewArray with correct buffer count and dtype
1668        let varbin_view_array = vortex_array.as_::<VarBinView>();
1669        assert_eq!(
1670            varbin_view_array.data_buffers().len(),
1671            arrow_array.data_buffers().len()
1672        );
1673        assert_eq!(varbin_view_array.dtype(), &DType::Binary(true.into()));
1674
1675        let varbin_view_array_non_null = vortex_array_non_null.as_::<VarBinView>();
1676        assert_eq!(
1677            varbin_view_array_non_null.data_buffers().len(),
1678            arrow_array_non_null.data_buffers().len()
1679        );
1680        assert_eq!(
1681            varbin_view_array_non_null.dtype(),
1682            &DType::Binary(false.into())
1683        );
1684        assert_arrays_eq!(
1685            vortex_array,
1686            VarBinArray::from_iter(
1687                [Some("hello"), None, Some("world"), Some("test")],
1688                DType::Binary(Nullability::NonNullable).as_nullable()
1689            ),
1690            &mut SESSION.create_execution_ctx()
1691        );
1692        assert_arrays_eq!(
1693            vortex_array_non_null,
1694            VarBinArray::from_iter_nonnull(
1695                ["hello", "world", "test", "vortex"],
1696                DType::Binary(Nullability::NonNullable)
1697            ),
1698            &mut SESSION.create_execution_ctx()
1699        );
1700    }
1701
1702    // Test boolean array conversions
1703    #[test]
1704    fn test_boolean_array_conversion() {
1705        let arrow_array = BooleanArray::from(vec![Some(true), None, Some(false), Some(true)]);
1706        let vortex_array = from_arrow_dyn(&arrow_array, true).unwrap();
1707
1708        let arrow_array_non_null = BooleanArray::from(vec![true, false, true, false]);
1709        let vortex_array_non_null = from_arrow_dyn(&arrow_array_non_null, false).unwrap();
1710
1711        assert_eq!(vortex_array.len(), 4);
1712        assert_eq!(vortex_array_non_null.len(), 4);
1713        assert_arrays_eq!(
1714            vortex_array,
1715            BoolArray::from_iter([Some(true), None, Some(false), Some(true)]),
1716            &mut SESSION.create_execution_ctx()
1717        );
1718        assert_arrays_eq!(
1719            vortex_array_non_null,
1720            BoolArray::from_iter([true, false, true, false]),
1721            &mut SESSION.create_execution_ctx()
1722        );
1723    }
1724
1725    // Test struct array conversions
1726    #[test]
1727    fn test_struct_array_conversion() {
1728        let fields = vec![
1729            Field::new("field1", DataType::Int32, true),
1730            Field::new("field2", DataType::Utf8, false),
1731        ];
1732        let schema = Fields::from(fields);
1733
1734        let field1_data = Int32Array::from(vec![Some(1), None, Some(3)]);
1735        let field2_data = StringArray::from(vec!["a", "b", "c"]);
1736
1737        let arrow_array = StructArray::new(
1738            schema.clone(),
1739            vec![Arc::new(field1_data), Arc::new(field2_data)],
1740            None,
1741        );
1742
1743        let vortex_array = from_arrow_dyn(&arrow_array, false).unwrap();
1744        assert_eq!(vortex_array.len(), 3);
1745
1746        // Verify metadata - should be StructArray with correct field names
1747        let struct_vortex_array = vortex_array.as_::<Struct>();
1748        assert_eq!(struct_vortex_array.names().len(), 2);
1749        assert_eq!(struct_vortex_array.names()[0], "field1");
1750        assert_eq!(struct_vortex_array.names()[1], "field2");
1751
1752        // Test nullable struct
1753        let nullable_array = StructArray::new(
1754            schema,
1755            vec![
1756                Arc::new(Int32Array::from(vec![Some(1), None, Some(3)])),
1757                Arc::new(StringArray::from(vec!["a", "b", "c"])),
1758            ],
1759            Some(NullBuffer::new(BooleanBuffer::from(vec![
1760                true, false, true,
1761            ]))),
1762        );
1763
1764        let vortex_nullable_array = from_arrow_dyn(&nullable_array, true).unwrap();
1765        assert_eq!(vortex_nullable_array.len(), 3);
1766
1767        // Verify metadata for nullable struct
1768        let struct_vortex_nullable_array = vortex_nullable_array.as_::<Struct>();
1769        assert_eq!(struct_vortex_nullable_array.names().len(), 2);
1770        assert_eq!(struct_vortex_nullable_array.names()[0], "field1");
1771        assert_eq!(struct_vortex_nullable_array.names()[1], "field2");
1772        let expected = |validity| {
1773            VortexStructArray::new(
1774                ["field1", "field2"].into(),
1775                vec![
1776                    PrimitiveArray::from_option_iter([Some(1i32), None, Some(3)]).into_array(),
1777                    VarBinArray::from_iter_nonnull(
1778                        ["a", "b", "c"],
1779                        DType::Utf8(Nullability::NonNullable),
1780                    )
1781                    .into_array(),
1782                ],
1783                3,
1784                validity,
1785            )
1786        };
1787        assert_arrays_eq!(
1788            vortex_array,
1789            expected(Validity::NonNullable),
1790            &mut SESSION.create_execution_ctx()
1791        );
1792        assert_arrays_eq!(
1793            vortex_nullable_array,
1794            expected(Validity::from_iter([true, false, true])),
1795            &mut SESSION.create_execution_ctx()
1796        );
1797    }
1798
1799    // Test list array conversions
1800    #[test]
1801    fn test_list_array_conversion() {
1802        let mut ctx = SESSION.create_execution_ctx();
1803        let mut builder = ListBuilder::new(Int32Builder::new());
1804        builder.append_value([Some(1), None, Some(3)]);
1805        builder.append_null();
1806        builder.append_value([Some(4), Some(5)]);
1807        let arrow_array = builder.finish();
1808
1809        let vortex_array = from_arrow_dyn(&arrow_array, true).unwrap();
1810        assert_eq!(vortex_array.len(), 3);
1811
1812        // Verify metadata - should be ListArray with correct offsets
1813        let list_vortex_array = vortex_array.as_::<List>();
1814        let offsets_array = list_vortex_array.offsets().as_::<Primitive>();
1815        assert_eq!(offsets_array.len(), 4); // n+1 offsets for n lists
1816        assert_eq!(offsets_array.ptype(), PType::I32);
1817
1818        // Test non-nullable list
1819        let mut builder_non_null = ListBuilder::new(Int32Builder::new());
1820        builder_non_null.append_value([Some(1), None, Some(3)]);
1821        builder_non_null.append_value([Some(4), Some(5)]);
1822        let arrow_array_non_null = builder_non_null.finish();
1823
1824        let vortex_array_non_null = from_arrow_dyn(&arrow_array_non_null, false).unwrap();
1825        assert_eq!(vortex_array_non_null.len(), 2);
1826
1827        // Verify metadata for non-nullable list
1828        let list_vortex_array_non_null = vortex_array_non_null.as_::<List>();
1829        let offsets_array_non_null = list_vortex_array_non_null.offsets().as_::<Primitive>();
1830        assert_eq!(offsets_array_non_null.len(), 3); // n+1 offsets for n lists
1831        assert_eq!(offsets_array_non_null.ptype(), PType::I32);
1832
1833        let expected_elements =
1834            PrimitiveArray::from_option_iter([Some(1i32), None, Some(3), Some(4), Some(5)])
1835                .into_array();
1836        let expected = ListArray::new(
1837            expected_elements.clone(),
1838            buffer![0u32, 3, 3, 5].into_array(),
1839            Validity::from_iter([true, false, true]),
1840            &mut ctx,
1841        );
1842        assert_arrays_eq!(vortex_array, expected, &mut SESSION.create_execution_ctx());
1843        let expected = ListArray::new(
1844            expected_elements,
1845            buffer![0u32, 3, 5].into_array(),
1846            Validity::NonNullable,
1847            &mut ctx,
1848        );
1849        assert_arrays_eq!(
1850            vortex_array_non_null,
1851            expected,
1852            &mut SESSION.create_execution_ctx()
1853        );
1854    }
1855
1856    #[test]
1857    fn test_sliced_offset_arrays_import_only_their_rows() -> VortexResult<()> {
1858        let strings = |rows: Range<i64>| {
1859            StringArray::from_iter_values(rows.map(|row| format!("value-{row}")))
1860        };
1861        let lists = |rows: Range<i64>| {
1862            let mut builder = ListBuilder::new(Int64Builder::new());
1863            for row in rows {
1864                builder.append_value([Some(row), Some(row + 1)]);
1865            }
1866            builder.finish()
1867        };
1868        let mut ctx = SESSION.create_execution_ctx();
1869
1870        // A slice keeps its parent's whole child; the import must not.
1871        let sliced = from_arrow_dyn(&strings(0..1000).slice(500, 2), false)?;
1872        let fresh = from_arrow_dyn(&strings(500..502), false)?;
1873        assert_eq!(sliced.nbytes(), fresh.nbytes());
1874        let expected = VarBinArray::from_iter_nonnull(
1875            ["value-500", "value-501"],
1876            DType::Utf8(Nullability::NonNullable),
1877        );
1878        assert_arrays_eq!(sliced, expected, &mut ctx);
1879        assert_arrays_eq!(fresh, expected, &mut ctx);
1880
1881        let sliced = from_arrow_dyn(&lists(0..1000).slice(500, 2), false)?;
1882        let fresh = from_arrow_dyn(&lists(500..502), false)?;
1883        assert_eq!(sliced.nbytes(), fresh.nbytes());
1884        let expected = ListArray::new(
1885            PrimitiveArray::from_option_iter([Some(500i64), Some(501), Some(501), Some(502)])
1886                .into_array(),
1887            buffer![0u32, 2, 4].into_array(),
1888            Validity::NonNullable,
1889            &mut ctx,
1890        );
1891        assert_arrays_eq!(sliced, expected, &mut ctx);
1892        assert_arrays_eq!(fresh, expected, &mut ctx);
1893        Ok(())
1894    }
1895
1896    #[test]
1897    fn test_large_list_array_conversion() {
1898        let mut ctx = SESSION.create_execution_ctx();
1899        let mut builder = LargeListBuilder::new(Int32Builder::new());
1900        builder.append_value([Some(1), None, Some(3)]);
1901        builder.append_null();
1902        builder.append_value([Some(4), Some(5)]);
1903        let arrow_array = builder.finish();
1904
1905        let vortex_array = from_arrow_dyn(&arrow_array, true).unwrap();
1906        assert_eq!(vortex_array.len(), 3);
1907
1908        // Verify metadata - should be ListArray with correct offsets (I64 for large lists)
1909        let list_vortex_array = vortex_array.as_::<List>();
1910        let offsets_array = list_vortex_array.offsets().as_::<Primitive>();
1911        assert_eq!(offsets_array.len(), 4); // n+1 offsets for n lists
1912        assert_eq!(offsets_array.ptype(), PType::I64); // Large lists use I64 offsets
1913
1914        // Test non-nullable large list
1915        let mut builder_non_null = LargeListBuilder::new(Int32Builder::new());
1916        builder_non_null.append_value([Some(1), None, Some(3)]);
1917        builder_non_null.append_value([Some(4), Some(5)]);
1918        let arrow_array_non_null = builder_non_null.finish();
1919
1920        let vortex_array_non_null = from_arrow_dyn(&arrow_array_non_null, false).unwrap();
1921        assert_eq!(vortex_array_non_null.len(), 2);
1922
1923        // Verify metadata for non-nullable large list
1924        let list_vortex_array_non_null = vortex_array_non_null.as_::<List>();
1925        let offsets_array_non_null = list_vortex_array_non_null.offsets().as_::<Primitive>();
1926        assert_eq!(offsets_array_non_null.len(), 3); // n+1 offsets for n lists
1927        assert_eq!(offsets_array_non_null.ptype(), PType::I64); // Large lists use I64 offsets
1928
1929        let expected_elements =
1930            PrimitiveArray::from_option_iter([Some(1i32), None, Some(3), Some(4), Some(5)])
1931                .into_array();
1932        let expected = ListArray::new(
1933            expected_elements.clone(),
1934            buffer![0u32, 3, 3, 5].into_array(),
1935            Validity::from_iter([true, false, true]),
1936            &mut ctx,
1937        );
1938        assert_arrays_eq!(vortex_array, expected, &mut SESSION.create_execution_ctx());
1939        let expected = ListArray::new(
1940            expected_elements,
1941            buffer![0u32, 3, 5].into_array(),
1942            Validity::NonNullable,
1943            &mut ctx,
1944        );
1945        assert_arrays_eq!(
1946            vortex_array_non_null,
1947            expected,
1948            &mut SESSION.create_execution_ctx()
1949        );
1950    }
1951
1952    #[test]
1953    fn test_fixed_size_list_array_conversion() {
1954        // Create elements for the fixed-size lists
1955        let values = Int32Array::from(vec![
1956            Some(1),
1957            Some(2),
1958            Some(3), // First list
1959            Some(4),
1960            None,
1961            Some(6), // Second list (with null element)
1962            Some(7),
1963            Some(8),
1964            Some(9), // Third list
1965            Some(10),
1966            Some(11),
1967            Some(12), // Fourth list
1968        ]);
1969
1970        // Create a FixedSizeListArray with list_size=3
1971        let field = Arc::new(Field::new("item", DataType::Int32, true));
1972        let arrow_array =
1973            ArrowFixedSizeListArray::try_new(Arc::clone(&field), 3, Arc::new(values), None)
1974                .unwrap();
1975        let vortex_array = from_arrow_dyn(&arrow_array, false).unwrap();
1976
1977        assert_eq!(vortex_array.len(), 4);
1978
1979        // Verify metadata - should be FixedSizeListArray with correct list size
1980        let fsl_vortex_array = vortex_array.as_::<FixedSizeList>();
1981        assert_eq!(fsl_vortex_array.list_size(), 3);
1982        assert_eq!(fsl_vortex_array.elements().len(), 12); // 4 lists * 3 elements
1983
1984        // Test nullable fixed-size list
1985        let values_nullable = Int32Array::from(vec![
1986            Some(1),
1987            Some(2),
1988            Some(3), // First list
1989            Some(4),
1990            None,
1991            Some(6), // Second list (will be null)
1992            Some(7),
1993            Some(8),
1994            Some(9), // Third list
1995        ]);
1996
1997        // Create nulls buffer - second list is null
1998        let null_buffer = NullBuffer::new(BooleanBuffer::from(vec![true, false, true]));
1999
2000        let arrow_array_nullable = ArrowFixedSizeListArray::try_new(
2001            field,
2002            3,
2003            Arc::new(values_nullable),
2004            Some(null_buffer),
2005        )
2006        .unwrap();
2007        let vortex_array_nullable = from_arrow_dyn(&arrow_array_nullable, true).unwrap();
2008
2009        assert_eq!(vortex_array_nullable.len(), 3);
2010
2011        // Verify metadata for nullable array
2012        let fsl_vortex_array_nullable = vortex_array_nullable.as_::<FixedSizeList>();
2013        assert_eq!(fsl_vortex_array_nullable.list_size(), 3);
2014        assert_eq!(fsl_vortex_array_nullable.elements().len(), 9); // 3 lists * 3 elements
2015        assert_arrays_eq!(
2016            vortex_array,
2017            VortexFixedSizeListArray::new(
2018                PrimitiveArray::from_option_iter([
2019                    Some(1i32),
2020                    Some(2),
2021                    Some(3),
2022                    Some(4),
2023                    None,
2024                    Some(6),
2025                    Some(7),
2026                    Some(8),
2027                    Some(9),
2028                    Some(10),
2029                    Some(11),
2030                    Some(12)
2031                ])
2032                .into_array(),
2033                3,
2034                Validity::NonNullable,
2035                4
2036            ),
2037            &mut SESSION.create_execution_ctx()
2038        );
2039        assert_arrays_eq!(
2040            vortex_array_nullable,
2041            VortexFixedSizeListArray::new(
2042                PrimitiveArray::from_option_iter([
2043                    Some(1i32),
2044                    Some(2),
2045                    Some(3),
2046                    Some(4),
2047                    None,
2048                    Some(6),
2049                    Some(7),
2050                    Some(8),
2051                    Some(9)
2052                ])
2053                .into_array(),
2054                3,
2055                Validity::from_iter([true, false, true]),
2056                3
2057            ),
2058            &mut SESSION.create_execution_ctx()
2059        );
2060    }
2061
2062    #[test]
2063    fn test_list_view_array_conversion() {
2064        let mut ctx = SESSION.create_execution_ctx();
2065        // Create values array for the lists
2066        let values = Int32Array::from(vec![
2067            Some(1),
2068            Some(2),
2069            Some(3), // First list [1, 2, 3]
2070            Some(4),
2071            Some(5), // Second list [4, 5]
2072            Some(6), // Third list [6]
2073            Some(7),
2074            Some(8),
2075            Some(9),
2076            Some(10), // Fourth list [7, 8, 9, 10]
2077        ]);
2078
2079        // Create offsets and sizes for ListView
2080        let offsets = ScalarBuffer::from(vec![0i32, 3, 5, 6]);
2081        let sizes = ScalarBuffer::from(vec![3i32, 2, 1, 4]);
2082
2083        let field = Arc::new(Field::new("item", DataType::Int32, true));
2084        let arrow_array = GenericListViewArray::try_new(
2085            Arc::clone(&field),
2086            offsets.clone(),
2087            sizes.clone(),
2088            Arc::new(values.clone()),
2089            None,
2090        )
2091        .unwrap();
2092
2093        let vortex_array = from_arrow_dyn(&arrow_array, false).unwrap();
2094        assert_eq!(vortex_array.len(), 4);
2095
2096        // Verify metadata - should be ListViewArray with correct offsets and sizes
2097        let list_view_vortex_array = vortex_array.as_::<ListView>();
2098        let offsets_array = list_view_vortex_array.offsets().as_::<Primitive>();
2099        let sizes_array = list_view_vortex_array.sizes().as_::<Primitive>();
2100
2101        assert_eq!(offsets_array.len(), 4);
2102        assert_eq!(offsets_array.ptype(), PType::I32);
2103        assert_eq!(sizes_array.len(), 4);
2104        assert_eq!(sizes_array.ptype(), PType::I32);
2105
2106        // Test nullable ListView
2107        let null_buffer = NullBuffer::new(BooleanBuffer::from(vec![true, false, true, true]));
2108
2109        let arrow_array_nullable = GenericListViewArray::try_new(
2110            Arc::clone(&field),
2111            offsets,
2112            sizes,
2113            Arc::new(values.clone()),
2114            Some(null_buffer),
2115        )
2116        .unwrap();
2117
2118        let vortex_array_nullable = from_arrow_dyn(&arrow_array_nullable, true).unwrap();
2119        assert_eq!(vortex_array_nullable.len(), 4);
2120
2121        // Test LargeListView (i64 offsets and sizes)
2122        let large_offsets = ScalarBuffer::from(vec![0i64, 3, 5, 6]);
2123        let large_sizes = ScalarBuffer::from(vec![3i64, 2, 1, 4]);
2124
2125        let large_arrow_array = GenericListViewArray::try_new(
2126            field,
2127            large_offsets,
2128            large_sizes,
2129            Arc::new(values),
2130            None,
2131        )
2132        .unwrap();
2133
2134        let large_vortex_array = from_arrow_dyn(&large_arrow_array, false).unwrap();
2135        assert_eq!(large_vortex_array.len(), 4);
2136
2137        // Verify metadata for large ListView
2138        let large_list_view_vortex_array = large_vortex_array.as_::<ListView>();
2139        let large_offsets_array = large_list_view_vortex_array.offsets().as_::<Primitive>();
2140        let large_sizes_array = large_list_view_vortex_array.sizes().as_::<Primitive>();
2141
2142        assert_eq!(large_offsets_array.len(), 4);
2143        assert_eq!(large_offsets_array.ptype(), PType::I64); // Large ListView uses I64 offsets
2144        assert_eq!(large_sizes_array.len(), 4);
2145        assert_eq!(large_sizes_array.ptype(), PType::I64); // Large ListView uses I64 sizes
2146        let mut expected = |validity| {
2147            ListViewArray::new(
2148                PrimitiveArray::from_option_iter((1i32..=10).map(Some)).into_array(),
2149                buffer![0u32, 3, 5, 6].into_array(),
2150                buffer![3u32, 2, 1, 4].into_array(),
2151                validity,
2152                &mut ctx,
2153            )
2154        };
2155        assert_arrays_eq!(
2156            vortex_array,
2157            expected(Validity::NonNullable),
2158            &mut SESSION.create_execution_ctx()
2159        );
2160        assert_arrays_eq!(
2161            vortex_array_nullable,
2162            expected(Validity::from_iter([true, false, true, true])),
2163            &mut SESSION.create_execution_ctx()
2164        );
2165        assert_arrays_eq!(
2166            large_vortex_array,
2167            expected(Validity::NonNullable),
2168            &mut SESSION.create_execution_ctx()
2169        );
2170    }
2171
2172    // Test null array conversions
2173    #[test]
2174    fn test_null_array_conversion() {
2175        let arrow_array = NullArray::new(5);
2176        let vortex_array = from_arrow_dyn(&arrow_array, true).unwrap();
2177        assert_eq!(vortex_array.len(), 5);
2178        assert_arrays_eq!(
2179            vortex_array,
2180            VortexNullArray::new(5),
2181            &mut SESSION.create_execution_ctx()
2182        );
2183    }
2184
2185    // Test buffer conversions
2186    #[test]
2187    fn test_arrow_buffer_conversion() {
2188        let data = vec![1u8, 2, 3, 4, 5];
2189        let arrow_buffer = ArrowBuffer::from_vec(data);
2190        let vortex_array = arrow_buffer.into_array();
2191        assert_eq!(vortex_array.len(), 5);
2192        assert_arrays_eq!(
2193            vortex_array,
2194            buffer![1u8, 2, 3, 4, 5].into_array(),
2195            &mut SESSION.create_execution_ctx()
2196        );
2197    }
2198
2199    #[test]
2200    fn test_boolean_buffer_conversion() {
2201        let data = vec![true, false, true, false, true];
2202        let boolean_buffer = BooleanBuffer::from(data);
2203        let vortex_array = boolean_buffer.into_array();
2204        assert_eq!(vortex_array.len(), 5);
2205        assert_arrays_eq!(
2206            vortex_array,
2207            BoolArray::from_iter([true, false, true, false, true]),
2208            &mut SESSION.create_execution_ctx()
2209        );
2210    }
2211
2212    #[test]
2213    fn test_scalar_buffer_conversion() {
2214        let data = vec![1i32, 2, 3, 4, 5];
2215        let scalar_buffer = ScalarBuffer::from(data);
2216        let vortex_array = scalar_buffer.into_array();
2217        assert_eq!(vortex_array.len(), 5);
2218        assert_arrays_eq!(
2219            vortex_array,
2220            buffer![1i32, 2, 3, 4, 5].into_array(),
2221            &mut SESSION.create_execution_ctx()
2222        );
2223    }
2224
2225    #[test]
2226    fn test_offset_buffer_conversion() {
2227        let data = vec![0i32, 2, 5, 8, 10];
2228        let offset_buffer = OffsetBuffer::new(ScalarBuffer::from(data));
2229        let vortex_array = offset_buffer.into_array();
2230        assert_eq!(vortex_array.len(), 5);
2231        assert_arrays_eq!(
2232            vortex_array,
2233            buffer![0i32, 2, 5, 8, 10].into_array(),
2234            &mut SESSION.create_execution_ctx()
2235        );
2236    }
2237
2238    // Test RecordBatch conversions
2239    #[test]
2240    fn test_record_batch_conversion() {
2241        let schema = Arc::new(Schema::new(vec![
2242            Field::new("field1", DataType::Int32, false),
2243            Field::new("field2", DataType::Utf8, false),
2244        ]));
2245
2246        let field1_data = Arc::new(Int32Array::from(vec![1, 2, 3, 4]));
2247        let field2_data = Arc::new(StringArray::from(vec!["a", "b", "c", "d"]));
2248
2249        let record_batch = RecordBatch::try_new(schema, vec![field1_data, field2_data]).unwrap();
2250
2251        let vortex_array = from_arrow_batch(&record_batch, false).unwrap();
2252        let expected = VortexStructArray::new(
2253            ["field1", "field2"].into(),
2254            vec![
2255                buffer![1i32, 2, 3, 4].into_array(),
2256                VarBinArray::from_iter_nonnull(
2257                    ["a", "b", "c", "d"],
2258                    DType::Utf8(Nullability::NonNullable),
2259                )
2260                .into_array(),
2261            ],
2262            4,
2263            Validity::NonNullable,
2264        );
2265        assert_arrays_eq!(vortex_array, expected, &mut SESSION.create_execution_ctx());
2266
2267        // Test with reference
2268        let schema = Arc::new(Schema::new(vec![
2269            Field::new("field1", DataType::Int32, false),
2270            Field::new("field2", DataType::Utf8, false),
2271        ]));
2272
2273        let field1_data = Arc::new(Int32Array::from(vec![1, 2, 3, 4]));
2274        let field2_data = Arc::new(StringArray::from(vec!["a", "b", "c", "d"]));
2275
2276        let record_batch = RecordBatch::try_new(schema, vec![field1_data, field2_data]).unwrap();
2277
2278        let vortex_array = from_arrow_batch(&record_batch, false).unwrap();
2279        let expected = VortexStructArray::new(
2280            ["field1", "field2"].into(),
2281            vec![
2282                buffer![1i32, 2, 3, 4].into_array(),
2283                VarBinArray::from_iter_nonnull(
2284                    ["a", "b", "c", "d"],
2285                    DType::Utf8(Nullability::NonNullable),
2286                )
2287                .into_array(),
2288            ],
2289            4,
2290            Validity::NonNullable,
2291        );
2292        assert_arrays_eq!(vortex_array, expected, &mut SESSION.create_execution_ctx());
2293    }
2294
2295    // Test dynamic dispatch conversion
2296    #[test]
2297    fn test_dyn_array_conversion() {
2298        let int_array = Int32Array::from(vec![1, 2, 3, 4]);
2299        let dyn_array: &dyn ArrowArray = &int_array;
2300        let vortex_array = from_arrow_dyn(dyn_array, false).unwrap();
2301        assert_arrays_eq!(
2302            vortex_array,
2303            buffer![1i32, 2, 3, 4].into_array(),
2304            &mut SESSION.create_execution_ctx()
2305        );
2306
2307        let string_array = StringArray::from(vec!["a", "b", "c"]);
2308        let dyn_array: &dyn ArrowArray = &string_array;
2309        let vortex_array = from_arrow_dyn(dyn_array, false).unwrap();
2310        assert_arrays_eq!(
2311            vortex_array,
2312            VarBinArray::from_iter_nonnull(["a", "b", "c"], DType::Utf8(Nullability::NonNullable)),
2313            &mut SESSION.create_execution_ctx()
2314        );
2315
2316        let bool_array = BooleanArray::from(vec![true, false, true]);
2317        let dyn_array: &dyn ArrowArray = &bool_array;
2318        let vortex_array = from_arrow_dyn(dyn_array, false).unwrap();
2319        assert_arrays_eq!(
2320            vortex_array,
2321            BoolArray::from_iter([true, false, true]),
2322            &mut SESSION.create_execution_ctx()
2323        );
2324    }
2325
2326    // Existing tests
2327    #[test]
2328    pub fn nullable_may_contain_non_nullable() {
2329        let null_struct_array_with_non_nullable_field = new_null_array(
2330            &DataType::Struct(Fields::from(vec![Field::new(
2331                "non_nullable_inner",
2332                DataType::Int32,
2333                false,
2334            )])),
2335            1,
2336        );
2337        let actual =
2338            from_arrow_dyn(null_struct_array_with_non_nullable_field.as_ref(), true).unwrap();
2339        assert_arrays_eq!(
2340            actual,
2341            VortexStructArray::new(
2342                ["non_nullable_inner"].into(),
2343                vec![buffer![0i32].into_array()],
2344                1,
2345                Validity::AllInvalid
2346            ),
2347            &mut SESSION.create_execution_ctx()
2348        );
2349    }
2350
2351    #[test]
2352    pub fn nullable_may_contain_deeply_nested_non_nullable() {
2353        let null_struct_array_with_non_nullable_field = new_null_array(
2354            &DataType::Struct(Fields::from(vec![Field::new(
2355                "non_nullable_inner",
2356                DataType::Struct(Fields::from(vec![Field::new(
2357                    "non_nullable_deeper_inner",
2358                    DataType::Int32,
2359                    false,
2360                )])),
2361                false,
2362            )])),
2363            1,
2364        );
2365        let actual =
2366            from_arrow_dyn(null_struct_array_with_non_nullable_field.as_ref(), true).unwrap();
2367        assert_arrays_eq!(
2368            actual,
2369            VortexStructArray::new(
2370                ["non_nullable_inner"].into(),
2371                vec![
2372                    VortexStructArray::new(
2373                        ["non_nullable_deeper_inner"].into(),
2374                        vec![buffer![0i32].into_array()],
2375                        1,
2376                        Validity::NonNullable
2377                    )
2378                    .into_array()
2379                ],
2380                1,
2381                Validity::AllInvalid
2382            ),
2383            &mut SESSION.create_execution_ctx()
2384        );
2385    }
2386
2387    #[test]
2388    fn dyn_dispatch_imports_map() -> VortexResult<()> {
2389        let mut builder = ArrowMapBuilder::new(None, StringBuilder::new(), Int32Builder::new());
2390        builder.keys().append_value("joe");
2391        builder.values().append_value(1);
2392        builder.append(true)?;
2393        builder.append(false)?;
2394        let arrow = builder.finish();
2395
2396        let expected = DType::map(
2397            DType::Utf8(Nullability::NonNullable),
2398            DType::Primitive(PType::I32, Nullability::Nullable),
2399            false,
2400            Nullability::Nullable,
2401        )?;
2402
2403        // Dispatching on the Arrow data type must cover maps...
2404        let direct = from_arrow_dyn(&arrow, true)?;
2405        assert_eq!(direct.dtype(), &expected);
2406
2407        // ...including maps reached by recursing into a container.
2408        let batch = RecordBatch::try_from_iter_with_nullable([(
2409            "maps",
2410            Arc::new(arrow) as Arc<dyn ArrowArray>,
2411            true,
2412        )])?;
2413        let imported = from_arrow_batch(&batch, false)?;
2414        assert_eq!(
2415            imported.as_::<Struct>().unmasked_field(0).dtype(),
2416            &expected
2417        );
2418
2419        let row = Scalar::try_map(
2420            expected.clone(),
2421            [(
2422                Scalar::utf8("joe", Nullability::NonNullable),
2423                Scalar::primitive(1i32, Nullability::Nullable),
2424            )],
2425        )?;
2426        let mut ctx = SESSION.create_execution_ctx();
2427        for actual in [&direct, imported.as_::<Struct>().unmasked_field(0)] {
2428            assert_eq!(actual.len(), 2);
2429            assert_eq!(actual.execute_scalar(0, &mut ctx)?, row);
2430            assert_eq!(
2431                actual.execute_scalar(1, &mut ctx)?,
2432                Scalar::null(expected.clone())
2433            );
2434        }
2435        Ok(())
2436    }
2437
2438    #[test]
2439    fn non_nullable_request_rejects_nulls() {
2440        // Requesting `nullable = false` on an Arrow array that physically contains nulls is a
2441        // contradiction and must surface as an error, not a panic.
2442        let arrow_array = Int32Array::from(vec![Some(1), None, Some(3)]);
2443        assert!(from_arrow_dyn(&arrow_array, false).is_err());
2444    }
2445
2446    #[test]
2447    fn non_nullable_request_rejects_null_array() {
2448        // An Arrow NullArray is entirely null, so it cannot be converted to a non-nullable
2449        // Vortex array.
2450        let arrow_array = NullArray::new(5);
2451        assert!(from_arrow_dyn(&arrow_array, false).is_err());
2452    }
2453
2454    #[test]
2455    fn non_nullable_struct_with_nulls_errors() {
2456        // A struct array carrying top-level nulls cannot be converted to a non-nullable Vortex
2457        // struct; the struct-level validity reconciliation must error rather than panic.
2458        let struct_array = new_null_array(
2459            &DataType::Struct(Fields::from(vec![Field::new("a", DataType::Int32, true)])),
2460            3,
2461        );
2462        assert!(from_arrow_dyn(struct_array.as_ref(), false).is_err());
2463    }
2464
2465    #[test]
2466    fn non_nullable_list_with_nulls_errors() {
2467        // Likewise for a list array with a null entry: requesting a non-nullable list must error
2468        // rather than panic.
2469        let mut builder = ListBuilder::new(Int32Builder::new());
2470        builder.append_value([Some(1), Some(2)]);
2471        builder.append_null();
2472        let list = builder.finish();
2473        assert!(from_arrow_dyn(&list, false).is_err());
2474    }
2475
2476    #[test]
2477    pub fn nullable_struct_containing_non_nullable_dictionary_with_nulls_errors() {
2478        // `remove_nulls` cannot strip pushed-down nulls out of a non-nullable dictionary field,
2479        // so the values end up converted with `nullable = false` while still containing nulls.
2480        // This must surface as an error rather than panicking.
2481        let null_struct_array_with_non_nullable_field = new_null_array(
2482            &DataType::Struct(Fields::from(vec![Field::new(
2483                "non_nullable_deeper_inner",
2484                DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8)),
2485                false,
2486            )])),
2487            1,
2488        );
2489
2490        assert!(from_arrow_dyn(null_struct_array_with_non_nullable_field.as_ref(), true).is_err());
2491    }
2492}