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