Skip to main content

vortex_arrow/
convert.rs

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