Skip to main content

vortex_arrow/executor/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! Execution of Vortex arrays into Arrow arrays.
5//!
6//! [`ExecuteArrowExt`] is the entry point for every export of a Vortex array to Arrow. Most targets
7//! go to the canonical export, which maps the array to the Arrow type of the target. Only a target
8//! with an Arrow extension name goes to the export plugins of the [`ArrowSession`] first. Each
9//! submodule exports one family of Arrow types.
10//!
11//! [`ArrowSession`]: crate::ArrowSession
12
13pub mod bool;
14mod byte;
15pub mod byte_view;
16mod decimal;
17mod dictionary;
18mod fixed_size_list;
19mod list;
20mod list_view;
21mod map;
22pub mod null;
23pub mod primitive;
24mod run_end;
25mod struct_;
26mod temporal;
27mod validity;
28
29use arrow_array::ArrayRef as ArrowArrayRef;
30use arrow_array::types::*;
31use arrow_schema::DataType;
32use arrow_schema::Field;
33use arrow_schema::FieldRef;
34use tracing::debug;
35use tracing::trace;
36use vortex_array::ArrayRef;
37use vortex_array::ExecutionCtx;
38use vortex_array::IntoArray;
39use vortex_array::arrays::List;
40use vortex_array::arrays::VarBin;
41use vortex_array::arrays::list::ListArraySlotsExt;
42use vortex_array::arrays::varbin::VarBinArraySlotsExt;
43use vortex_array::dtype::DType;
44use vortex_array::dtype::PType;
45use vortex_array::dtype::extension::ExtDTypeRef;
46use vortex_error::VortexResult;
47use vortex_error::vortex_bail;
48use vortex_error::vortex_ensure;
49use vortex_error::vortex_ensure_eq;
50use vortex_expr::ArrayExprExt;
51use vortex_expr::root;
52use vortex_functions::expr::ext_storage;
53use vortex_session::registry::Id;
54
55use crate::ArrowExport;
56use crate::ArrowExportOptions;
57use crate::executor::bool::to_arrow_bool;
58use crate::executor::byte::to_arrow_byte_array;
59use crate::executor::byte_view::to_arrow_byte_view;
60use crate::executor::decimal::to_arrow_decimal;
61use crate::executor::dictionary::to_arrow_dictionary;
62use crate::executor::fixed_size_list::to_arrow_fixed_list;
63use crate::executor::list::to_arrow_list;
64use crate::executor::list_view::to_arrow_list_view;
65use crate::executor::map::to_arrow_map;
66use crate::executor::null::to_arrow_null;
67use crate::executor::primitive::to_arrow_primitive;
68use crate::executor::run_end::to_arrow_run_end;
69use crate::executor::struct_::to_arrow_struct;
70use crate::executor::temporal::to_arrow_date;
71use crate::executor::temporal::to_arrow_time;
72use crate::executor::temporal::to_arrow_timestamp;
73use crate::session::ArrowSessionExt;
74
75/// Execution of a Vortex array into an Arrow array, for every type that implements [`IntoArray`].
76///
77/// An export uses the [`ArrowSession`] of its [`ExecutionCtx`] for every decision: the export
78/// plugins, the checks of the target, and the Arrow types of nested arrays. It takes no other
79/// session, so one export can never mix the plugins of two sessions.
80///
81/// ```
82/// # use arrow_array::Array;
83/// # use vortex_array::IntoArray;
84/// # use vortex_array::VortexSessionExecute;
85/// # use vortex_array::arrays::VarBinViewArray;
86/// use vortex_arrow::ExecuteArrowExt;
87/// # use vortex_session::VortexSession;
88///
89/// let session = VortexSession::empty();
90/// let array = VarBinViewArray::from_iter_str(["a", "b"]).into_array();
91/// let arrow = array.execute_arrow(None, &mut session.create_execution_ctx())?;
92/// assert_eq!(arrow.len(), 2);
93/// # Ok::<(), vortex_error::VortexError>(())
94/// ```
95///
96/// [`ArrowSession`]: crate::ArrowSession
97pub trait ExecuteArrowExt: IntoArray + Sized {
98    /// Execute this array into an Arrow array of the type of `target`, with the default
99    /// [`ArrowExportOptions`].
100    ///
101    /// A `target` with an Arrow extension name goes to the plugins registered for that name, in
102    /// registration order. If none of them accepts the array, but the name is the Vortex ID of the
103    /// array, the array exports as its storage (see [`ArrowSession`]).
104    ///
105    /// Without a `target`, the array exports to the field from
106    /// [`ArrowSession::default_arrow_export_field`], so it fails for the same types.
107    ///
108    /// [`ArrowSession`]: crate::ArrowSession
109    /// [`ArrowSession::default_arrow_export_field`]: crate::ArrowSession::default_arrow_export_field
110    fn execute_arrow(
111        self,
112        target: Option<&Field>,
113        ctx: &mut ExecutionCtx,
114    ) -> VortexResult<ArrowArrayRef> {
115        self.execute_arrow_with_options(target, &ArrowExportOptions::default(), ctx)
116    }
117
118    /// Execute this array into an Arrow array with `options`, which reach every nested array and
119    /// every export plugin.
120    ///
121    /// Otherwise, this behaves like [`execute_arrow`](Self::execute_arrow).
122    ///
123    /// ```
124    /// # use arrow_array::Array;
125    /// # use vortex_array::IntoArray;
126    /// # use vortex_array::VortexSessionExecute;
127    /// # use vortex_array::arrays::VarBinViewArray;
128    /// # use vortex_arrow::ArrowExportOptions;
129    /// # use vortex_arrow::CompactBuffers;
130    /// use vortex_arrow::ExecuteArrowExt;
131    /// # use vortex_session::VortexSession;
132    ///
133    /// let session = VortexSession::empty();
134    /// let array = VarBinViewArray::from_iter_str(["a", "b"]).into_array();
135    /// let options = ArrowExportOptions::default().with(CompactBuffers(false));
136    /// let arrow =
137    ///     array.execute_arrow_with_options(None, &options, &mut session.create_execution_ctx())?;
138    /// assert_eq!(arrow.len(), 2);
139    /// # Ok::<(), vortex_error::VortexError>(())
140    /// ```
141    fn execute_arrow_with_options(
142        self,
143        target: Option<&Field>,
144        options: &ArrowExportOptions,
145        ctx: &mut ExecutionCtx,
146    ) -> VortexResult<ArrowArrayRef> {
147        execute_arrow_array(self.into_array(), target, options, ctx)
148    }
149}
150
151impl<T: IntoArray> ExecuteArrowExt for T {}
152
153/// Export `array` to `target`, or to the default field of its dtype if there is no target.
154fn execute_arrow_array(
155    array: ArrayRef,
156    target: Option<&Field>,
157    options: &ArrowExportOptions,
158    ctx: &mut ExecutionCtx,
159) -> VortexResult<ArrowArrayRef> {
160    // NOTE(aduffy): this looks strange, but we do this to keep target_field as &Field so
161    //  we can avoid cloning target when it is provided. It contains a HashMap internally that
162    //  can be expensive to copy.
163    let arrow_field;
164    let target_field = match target {
165        Some(field) => field,
166        None => {
167            arrow_field = ctx
168                .session()
169                .arrow()
170                .default_arrow_export_field(array.dtype())?;
171            &arrow_field
172        }
173    };
174
175    if let Some(target) = target
176        && let Some(ext_dtype) = array.dtype().as_extension_opt()
177    {
178        ensure_field_keeps_extension(ext_dtype, target, ctx)?;
179    }
180
181    if let DataType::Dictionary(codes, values) = target_field.data_type() {
182        let values_field = target_field.clone().with_data_type(values.as_ref().clone());
183        return to_arrow_dictionary(array, codes, &values_field, options, ctx);
184    }
185
186    if let Some(arrow_ext_name) = target_field.extension_type_name() {
187        return execute_arrow_extension(array, arrow_ext_name, target_field, options, ctx);
188    }
189
190    execute_arrow_naive(array, target.map(Field::data_type), options, ctx)
191}
192
193/// Export `array` to `target`, whose Arrow extension name is `arrow_ext_name`, through the first
194/// export plugin that accepts it, or as its storage if `arrow_ext_name` is its Vortex ID.
195#[expect(clippy::disallowed_methods, reason = "interning a dynamic id")]
196fn execute_arrow_extension(
197    array: ArrayRef,
198    arrow_ext_name: &str,
199    target: &Field,
200    options: &ArrowExportOptions,
201    ctx: &mut ExecutionCtx,
202) -> VortexResult<ArrowArrayRef> {
203    let arrow_ext_id = Id::new(arrow_ext_name);
204    let exporters = ctx.session().arrow().exporters(&arrow_ext_id);
205
206    // There can be multiple plugins that report support for a particular extension type. We try
207    // them in order until one of them reports a successful conversion.
208    let len = array.len();
209    let mut current = array;
210
211    for plugin in exporters.iter() {
212        trace!(
213            plugin = ?plugin,
214            extension_name = arrow_ext_name,
215            "probing plugin for converting Arrow array"
216        );
217
218        match plugin.execute_arrow(current, target, options, ctx)? {
219            ArrowExport::Exported(arrow) => {
220                vortex_ensure_eq!(
221                    arrow.len(),
222                    len,
223                    "Arrow array length does not match Vortex array length after conversion to {:?}",
224                    arrow
225                );
226                return Ok(arrow);
227            }
228            ArrowExport::Unsupported(array) => current = array,
229        }
230    }
231
232    // The extension name can be an alias, which the dtype registry resolves to the Vortex ID of its
233    // type, so the array can match either of them.
234    let named_vortex_id = ctx.session().arrow().known_vortex_id(&arrow_ext_id);
235
236    if let Some(ext_dtype) = current
237        .dtype()
238        .as_extension_opt()
239        .filter(|ext_dtype| {
240            ext_dtype.id() == arrow_ext_id || Some(ext_dtype.id()) == named_vortex_id
241        })
242        .cloned()
243    {
244        return execute_arrow_ext_storage(current, &ext_dtype, target, options, ctx);
245    }
246
247    // An extension array of another type must not export to a field that names this Vortex ID. A
248    // plain array can, because a plugin such as `Vector` exports its storage to the same field that
249    // it received.
250    if let (Some(ext_dtype), Some(named_vortex_id)) =
251        (current.dtype().as_extension_opt(), named_vortex_id)
252    {
253        vortex_bail!(
254            "Arrow field {:?} names the extension type {named_vortex_id}, so the array must have that type, got {ext_dtype}",
255            target.name()
256        );
257    }
258
259    debug!(
260        extension_id = arrow_ext_name,
261        data_type = ?target.data_type(),
262        "unsupported Arrow extension type encountered, falling back to naive execution"
263    );
264
265    // No plugin accepted the array and the name is not its Vortex ID, so only the Arrow type can
266    // still describe an extension array.
267    if let Some(ext_dtype) = current.dtype().as_extension_opt() {
268        ensure_data_type_keeps_extension(ext_dtype, target.data_type(), ctx)?;
269    }
270
271    execute_arrow_naive(current, Some(target.data_type()), options, ctx)
272}
273
274/// Checks that exporting an array of the extension type `ext_dtype` to `target` keeps the type.
275///
276/// An extension array is unwrapped to its storage only on request: the caller applies
277/// [`ext_storage`] or names the Vortex ID of the type in `target`, which then records the type.
278/// A target without an extension name keeps the type only if its Arrow type imports as it, such
279/// as an Arrow timestamp for a [`Timestamp`](vortex_array::extension::datetime::Timestamp). A
280/// dictionary or run-end target keeps it if its values do.
281fn ensure_field_keeps_extension(
282    ext_dtype: &ExtDTypeRef,
283    target: &Field,
284    ctx: &ExecutionCtx,
285) -> VortexResult<()> {
286    match target.data_type() {
287        DataType::Dictionary(_, values) => ensure_field_keeps_extension(
288            ext_dtype,
289            &target.clone().with_data_type(values.as_ref().clone()),
290            ctx,
291        ),
292        DataType::RunEndEncoded(_, values) => ensure_field_keeps_extension(ext_dtype, values, ctx),
293        // The plugins and the Vortex ID export check a target that names an extension type.
294        _ if target.extension_type_name().is_some() => Ok(()),
295        data_type => ensure_data_type_keeps_extension(ext_dtype, data_type, ctx),
296    }
297}
298
299/// Checks that `data_type` imports as `ext_dtype`, so that an export to it keeps the type.
300fn ensure_data_type_keeps_extension(
301    ext_dtype: &ExtDTypeRef,
302    data_type: &DataType,
303    ctx: &ExecutionCtx,
304) -> VortexResult<()> {
305    let target_dtype = ctx
306        .session()
307        .arrow()
308        .from_arrow_datatype(data_type, ext_dtype.nullability())?;
309
310    vortex_ensure!(
311        target_dtype
312            .as_extension_opt()
313            .is_some_and(|target| target.eq_ignore_nullability(ext_dtype)),
314        "Cannot export {ext_dtype} to Arrow type {data_type}, which does not describe it. Export to the field from ArrowSession::to_arrow_field to keep the type, or apply ext_storage to export the storage."
315    );
316    Ok(())
317}
318
319/// Export `array`, whose type is `ext_dtype`, to `target`, whose extension name is the Vortex ID of
320/// `ext_dtype`. [`ArrowSession`](crate::ArrowSession) describes the checks on `target`.
321fn execute_arrow_ext_storage(
322    array: ArrayRef,
323    ext_dtype: &ExtDTypeRef,
324    target: &Field,
325    options: &ArrowExportOptions,
326    ctx: &mut ExecutionCtx,
327) -> VortexResult<ArrowArrayRef> {
328    ctx.session()
329        .arrow()
330        .ensure_ext_storage_metadata(ext_dtype, target)?;
331
332    let target_dtype = ctx
333        .session()
334        .arrow()
335        .from_arrow_datatype(target.data_type(), ext_dtype.nullability())?;
336
337    // If the Arrow type of the target imports as the extension type itself, such as an Arrow
338    // timestamp, export the array to it. The executor of that Arrow type then checks the parameters
339    // of the type, such as the time unit of a timestamp.
340    if target_dtype.eq_ignore_nullability(array.dtype()) {
341        return execute_arrow_naive(array, Some(target.data_type()), options, ctx);
342    }
343
344    vortex_ensure!(
345        eq_storage_layout(&target_dtype, ext_dtype.storage_dtype()),
346        "Arrow field {:?} must have an Arrow type that imports as the storage of {ext_dtype}, got {}",
347        target.name(),
348        target.data_type()
349    );
350
351    let storage = array.apply(&ext_storage(root()))?;
352    execute_arrow_naive(storage, Some(target.data_type()), options, ctx)
353}
354
355/// Returns whether `lhs` and `rhs` have the same storage layout, which means that they are equal,
356/// ignoring nullability, after every nested extension type is replaced by its storage type. The
357/// types at the top level are compared as they are.
358///
359/// A nested field of an explicit target can import as storage, for example when it names an
360/// unregistered Vortex ID or a plugin imports less than it exported, so export compares its
361/// inferred type with the storage layout. Each nested field is checked when it is exported, and
362/// one without extension metadata must have an Arrow type that imports as its extension type.
363fn eq_storage_layout(lhs: &DType, rhs: &DType) -> bool {
364    match (lhs, rhs) {
365        (DType::List(lhs, _), DType::List(rhs, _)) => eq_nested_storage_layout(lhs, rhs),
366        (DType::FixedSizeList(lhs, lhs_size, _), DType::FixedSizeList(rhs, rhs_size, _)) => {
367            lhs_size == rhs_size && eq_nested_storage_layout(lhs, rhs)
368        }
369        (DType::Map(lhs, _), DType::Map(rhs, _)) => {
370            lhs.keys_sorted() == rhs.keys_sorted()
371                && eq_nested_storage_layout(&lhs.key_dtype(), &rhs.key_dtype())
372                && eq_nested_storage_layout(&lhs.value_dtype(), &rhs.value_dtype())
373        }
374        (DType::Struct(lhs, _), DType::Struct(rhs, _)) => {
375            lhs.names() == rhs.names()
376                && lhs
377                    .fields()
378                    .zip(rhs.fields())
379                    .all(|(lhs, rhs)| eq_nested_storage_layout(&lhs, &rhs))
380        }
381        _ => lhs.eq_ignore_nullability(rhs),
382    }
383}
384
385/// [`eq_storage_layout`] for two nested types, which replaces their own extension types by their
386/// storage types too.
387fn eq_nested_storage_layout(lhs: &DType, rhs: &DType) -> bool {
388    eq_storage_layout(innermost_storage_dtype(lhs), innermost_storage_dtype(rhs))
389}
390
391/// Returns `dtype` without its extension types, which can wrap each other.
392fn innermost_storage_dtype(mut dtype: &DType) -> &DType {
393    while let Some(ext_dtype) = dtype.as_extension_opt() {
394        dtype = ext_dtype.storage_dtype();
395    }
396
397    dtype
398}
399
400/// Execute an arbitrary Vortex array into an Arrow array, dispatched by [`DataType`]. This pathway
401/// is naive to any extension type information, and only seeks to map canonical Vortex arrays to
402/// some target Arrow physical encoding.
403///
404/// Public callers should go through [`ExecuteArrowExt`] instead.
405pub(crate) fn execute_arrow_naive(
406    array: ArrayRef,
407    data_type: Option<&DataType>,
408    options: &ArrowExportOptions,
409    ctx: &mut ExecutionCtx,
410) -> VortexResult<ArrowArrayRef> {
411    let len = array.len();
412
413    let resolved_type: DataType = match data_type {
414        Some(dt) => dt.clone(),
415        None => infer_nearest_arrow_type(&array, ctx)?,
416    };
417
418    let arrow = match &resolved_type {
419        DataType::Null => to_arrow_null(array, ctx),
420        DataType::Boolean => to_arrow_bool(array, ctx),
421        DataType::Int8 => to_arrow_primitive::<Int8Type>(array, ctx),
422        DataType::Int16 => to_arrow_primitive::<Int16Type>(array, ctx),
423        DataType::Int32 => to_arrow_primitive::<Int32Type>(array, ctx),
424        DataType::Int64 => to_arrow_primitive::<Int64Type>(array, ctx),
425        DataType::UInt8 => to_arrow_primitive::<UInt8Type>(array, ctx),
426        DataType::UInt16 => to_arrow_primitive::<UInt16Type>(array, ctx),
427        DataType::UInt32 => to_arrow_primitive::<UInt32Type>(array, ctx),
428        DataType::UInt64 => to_arrow_primitive::<UInt64Type>(array, ctx),
429        DataType::Float16 => to_arrow_primitive::<Float16Type>(array, ctx),
430        DataType::Float32 => to_arrow_primitive::<Float32Type>(array, ctx),
431        DataType::Float64 => to_arrow_primitive::<Float64Type>(array, ctx),
432        DataType::Binary => to_arrow_byte_array::<BinaryType>(array, ctx),
433        DataType::LargeBinary => to_arrow_byte_array::<LargeBinaryType>(array, ctx),
434        DataType::Utf8 => to_arrow_byte_array::<Utf8Type>(array, ctx),
435        DataType::LargeUtf8 => to_arrow_byte_array::<LargeUtf8Type>(array, ctx),
436        DataType::BinaryView => to_arrow_byte_view::<BinaryViewType>(array, options, ctx),
437        DataType::Utf8View => to_arrow_byte_view::<StringViewType>(array, options, ctx),
438        // TODO(joe): pass down preferred
439        DataType::List(elements_field) => to_arrow_list::<i32>(array, elements_field, options, ctx),
440        // TODO(joe): pass down preferred
441        DataType::LargeList(elements_field) => {
442            to_arrow_list::<i64>(array, elements_field, options, ctx)
443        }
444        // TODO(joe): pass down preferred
445        DataType::FixedSizeList(elements_field, list_size) => {
446            to_arrow_fixed_list(array, *list_size, elements_field, options, ctx)
447        }
448        // TODO(joe): pass down preferred
449        DataType::ListView(elements_field) => {
450            to_arrow_list_view::<i32>(array, elements_field, options, ctx)
451        }
452        // TODO(joe): pass down preferred
453        DataType::LargeListView(elements_field) => {
454            to_arrow_list_view::<i64>(array, elements_field, options, ctx)
455        }
456        DataType::Struct(fields) => {
457            let fields = if data_type.is_none() {
458                None
459            } else {
460                Some(fields)
461            };
462            to_arrow_struct(array, fields, options, ctx)
463        }
464        // TODO(joe): pass down preferred
465        DataType::Dictionary(codes_type, values_type) => to_arrow_dictionary(
466            array.clone(),
467            codes_type,
468            &Field::new(
469                "",
470                values_type.as_ref().clone(),
471                array.dtype().is_nullable(),
472            ),
473            options,
474            ctx,
475        ),
476        dt @ DataType::Decimal32(..) => to_arrow_decimal(array, dt, ctx),
477        dt @ DataType::Decimal64(..) => to_arrow_decimal(array, dt, ctx),
478        dt @ DataType::Decimal128(..) => to_arrow_decimal(array, dt, ctx),
479        dt @ DataType::Decimal256(..) => to_arrow_decimal(array, dt, ctx),
480        // TODO(joe): pass down preferred
481        DataType::RunEndEncoded(ends_type, values_type) => {
482            to_arrow_run_end(array, ends_type.data_type(), values_type, options, ctx)
483        }
484        dt @ (DataType::Date32 | DataType::Date64) => to_arrow_date(array, dt, ctx),
485        dt @ (DataType::Time32(_) | DataType::Time64(_)) => to_arrow_time(array, dt, ctx),
486        dt @ DataType::Timestamp(..) => to_arrow_timestamp(array, dt, ctx),
487        DataType::Map(entries_field, keys_sorted) => {
488            to_arrow_map(array, entries_field, *keys_sorted, options, ctx)
489        }
490        DataType::FixedSizeBinary(_)
491        | DataType::Duration(_)
492        | DataType::Interval(_)
493        | DataType::Union(..) => {
494            vortex_bail!("Conversion to Arrow type {resolved_type} is not supported");
495        }
496    }?;
497
498    vortex_ensure_eq!(
499        arrow.len(),
500        len,
501        "Arrow array length does not match Vortex array length after conversion to {:?}",
502        arrow
503    );
504
505    Ok(arrow)
506}
507
508/// Determine the preferred (cheapest) Arrow type for an array.
509///
510/// For most arrays, this returns the canonical Arrow type for the array's dtype.
511/// However, some encodings have cheaper Arrow representations:
512/// - `VarBinArray`: Uses `Utf8`/`Binary` (offset-based) instead of `Utf8View`/`BinaryView`
513/// - `ListArray`: Uses `List` instead of `ListView`
514fn infer_nearest_arrow_type(array: &ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult<DataType> {
515    // VarBinArray: use offset-based Binary/Utf8 instead of View types
516    if let Some(varbin) = array.as_opt::<VarBin>() {
517        let offsets_ptype = PType::try_from(varbin.offsets().dtype())?;
518        let use_large = matches!(offsets_ptype, PType::I64 | PType::U64);
519
520        return Ok(match (varbin.dtype(), use_large) {
521            (DType::Utf8(_), false) => DataType::Utf8,
522            (DType::Utf8(_), true) => DataType::LargeUtf8,
523            (DType::Binary(_), false) => DataType::Binary,
524            (DType::Binary(_), true) => DataType::LargeBinary,
525            _ => unreachable!("VarBinArray must have Utf8 or Binary dtype"),
526        });
527    }
528
529    // ListArray: use List with appropriate offset size
530    if let Some(list) = array.as_opt::<List>() {
531        let offsets_ptype = PType::try_from(list.offsets().dtype())?;
532        let use_large = matches!(offsets_ptype, PType::I64 | PType::U64);
533        // Recursively get the preferred field for elements, so extension elements keep the
534        // `ARROW:extension:name` metadata their export plugin assigns.
535        let field = FieldRef::new(infer_nearest_arrow_field(
536            list.elements(),
537            Field::LIST_FIELD_DEFAULT_NAME,
538            ctx,
539        )?);
540
541        return Ok(if use_large {
542            DataType::LargeList(field)
543        } else {
544            DataType::List(field)
545        });
546    }
547
548    // Everything else: defer to the session's canonical conversion, which additionally resolves
549    // extension dtypes (including ones nested inside containers) through their export plugins.
550    Ok(infer_nearest_arrow_field(array, "", ctx)?
551        .data_type()
552        .clone())
553}
554
555/// Determine the preferred (cheapest) Arrow [`Field`] for an array.
556///
557/// Unlike [`infer_nearest_arrow_type`] this preserves the Field-level `ARROW:extension:name`
558/// metadata that export plugins assign, which a bare [`DataType`] cannot carry.
559pub(crate) fn infer_nearest_arrow_field(
560    array: &ArrayRef,
561    name: &str,
562    ctx: &mut ExecutionCtx,
563) -> VortexResult<Field> {
564    // Only the encodings with a cheaper-than-canonical Arrow type need the inference; every other
565    // dtype goes through the session, which is the only thing that knows how to map extensions.
566    if array.is::<VarBin>() || array.is::<List>() {
567        let data_type = infer_nearest_arrow_type(array, ctx)?;
568        return Ok(Field::new(name, data_type, array.dtype().is_nullable()));
569    }
570    ctx.session().arrow().to_arrow_field(name, array.dtype())
571}
572
573#[cfg(test)]
574mod tests {
575    use std::sync::Arc;
576    use std::sync::LazyLock;
577
578    use arrow_array::Array;
579    use arrow_array::ArrayRef as ArrowArrayRef;
580    use arrow_array::BinaryArray;
581    use arrow_array::Date32Array;
582    use arrow_array::Float64Array;
583    use arrow_array::Int32Array;
584    use arrow_array::Int64Array;
585    use arrow_array::LargeStringArray;
586    use arrow_array::Time32SecondArray;
587    use arrow_array::TimestampMicrosecondArray;
588    use arrow_array::TimestampMillisecondArray;
589    use arrow_schema::DataType;
590    use arrow_schema::Field;
591    use arrow_schema::TimeUnit;
592    use rstest::rstest;
593    use vortex_array::ArrayRef;
594    use vortex_array::IntoArray;
595    use vortex_array::VortexSessionExecute;
596    use vortex_array::arrays::BoolArray;
597    use vortex_array::arrays::ConstantArray;
598    use vortex_array::arrays::PrimitiveArray;
599    use vortex_array::arrays::StructArray;
600    use vortex_array::arrays::TemporalArray;
601    use vortex_array::arrays::VarBinViewArray;
602    use vortex_array::dtype::DType;
603    use vortex_array::dtype::Nullability;
604    use vortex_array::extension::datetime::TimeUnit as VortexTimeUnit;
605    use vortex_array::extension::datetime::Timestamp;
606    use vortex_array::scalar::Scalar;
607    use vortex_error::VortexExpect;
608    use vortex_error::VortexResult;
609    use vortex_expr::ArrayExprExt;
610    use vortex_expr::root;
611    use vortex_functions::expr::ext_storage;
612    use vortex_session::VortexSession;
613
614    use crate::ExecuteArrowExt;
615
616    static SESSION: LazyLock<VortexSession> = LazyLock::new(VortexSession::empty);
617
618    /// An export unwraps an extension array only on request, so a target without extension
619    /// metadata must describe the type, whatever the values or the nesting.
620    #[rstest]
621    #[case::storage(timestamps(), Field::new("ts", DataType::Int64, false))]
622    #[case::dictionary_of_storage(timestamps(), dictionary_field(DataType::Int64))]
623    #[case::null_dictionary_of_storage(null_timestamps(), dictionary_field(DataType::Int64))]
624    #[case::nested_storage(
625        StructArray::from_fields(&[("ts", timestamps())])
626            .vortex_expect("a struct of one field is valid")
627            .into_array(),
628        Field::new_struct("s", vec![Field::new("ts", DataType::Int64, false)], false),
629    )]
630    fn export_rejects_targets_that_drop_the_extension(
631        #[case] input: ArrayRef,
632        #[case] target: Field,
633    ) {
634        let error = input
635            .execute_arrow(Some(&target), &mut SESSION.create_execution_ctx())
636            .expect_err("the target does not describe the timestamp");
637        assert!(
638            error.to_string().contains("does not describe it"),
639            "{error}"
640        );
641    }
642
643    #[test]
644    fn ext_storage_exports_timestamp_storage() -> VortexResult<()> {
645        let mut ctx = SESSION.create_execution_ctx();
646        let target = Field::new("ts", DataType::Int64, false);
647
648        let exported = timestamps()
649            .apply(&ext_storage(root()))?
650            .execute_arrow(Some(&target), &mut ctx)?;
651
652        assert_eq!(
653            exported.to_data(),
654            Int64Array::from(vec![1_000, 2_000]).to_data(),
655        );
656        Ok(())
657    }
658
659    #[test]
660    fn timestamp_exports_to_dictionary_of_timestamps() -> VortexResult<()> {
661        let target = dictionary_field(DataType::Timestamp(TimeUnit::Millisecond, None));
662
663        let exported =
664            timestamps().execute_arrow(Some(&target), &mut SESSION.create_execution_ctx())?;
665
666        assert_eq!(exported.data_type(), target.data_type());
667        Ok(())
668    }
669
670    #[rstest]
671    #[case::date(
672        TemporalArray::new_date(primitive(), VortexTimeUnit::Days),
673        Arc::new(Date32Array::from(vec![1, 2])),
674    )]
675    #[case::time(
676        TemporalArray::new_time(primitive(), VortexTimeUnit::Seconds),
677        Arc::new(Time32SecondArray::from(vec![1, 2])),
678    )]
679    #[case::timestamp(
680        TemporalArray::new_timestamp(
681            PrimitiveArray::from_option_iter([Some(1_000i64), None, Some(2_000)]).into_array(),
682            VortexTimeUnit::Milliseconds,
683            Some("UTC".into()),
684        ),
685        Arc::new(
686            TimestampMillisecondArray::from(vec![Some(1_000), None, Some(2_000)])
687                .with_timezone("UTC"),
688        ),
689    )]
690    fn exports_native_temporals(
691        #[case] input: TemporalArray,
692        #[case] expected: ArrowArrayRef,
693    ) -> VortexResult<()> {
694        let mut ctx = SESSION.create_execution_ctx();
695        let exported = input.execute_arrow(None, &mut ctx)?;
696        assert_eq!(exported.to_data(), expected.to_data());
697        Ok(())
698    }
699
700    fn timestamps() -> ArrayRef {
701        TemporalArray::new_timestamp(
702            PrimitiveArray::from_iter([1_000i64, 2_000]).into_array(),
703            VortexTimeUnit::Milliseconds,
704            None,
705        )
706        .into_array()
707    }
708
709    fn null_timestamps() -> ArrayRef {
710        let dtype = Timestamp::new(VortexTimeUnit::Milliseconds, Nullability::Nullable);
711        ConstantArray::new(Scalar::null(DType::Extension(dtype.erased())), 2).into_array()
712    }
713
714    fn dictionary_field(values: DataType) -> Field {
715        Field::new(
716            "ts",
717            DataType::Dictionary(Box::new(DataType::Int32), Box::new(values)),
718            true,
719        )
720    }
721
722    fn utf8() -> ArrayRef {
723        VarBinViewArray::from_iter_str(["a", "bb"]).into_array()
724    }
725
726    fn primitive() -> ArrayRef {
727        PrimitiveArray::from_iter([1i32, 2]).into_array()
728    }
729
730    fn boolean() -> ArrayRef {
731        BoolArray::from_iter([true, false]).into_array()
732    }
733
734    fn list_target() -> DataType {
735        DataType::List(Arc::new(Field::new("item", DataType::Int32, true)))
736    }
737
738    fn map_target() -> DataType {
739        let entries = Field::new_struct(
740            "entries",
741            vec![
742                Field::new("key", DataType::Int32, false),
743                Field::new("value", DataType::Int32, true),
744            ],
745            false,
746        );
747        DataType::Map(Arc::new(entries), false)
748    }
749
750    /// Must error rather than panic inside `execute::<T>`.
751    #[rstest]
752    #[case::bool_from_utf8(utf8(), DataType::Boolean)]
753    #[case::bool_from_primitive(primitive(), DataType::Boolean)]
754    #[case::null_from_utf8(utf8(), DataType::Null)]
755    #[case::null_from_primitive(primitive(), DataType::Null)]
756    #[case::decimal_from_utf8(utf8(), DataType::Decimal128(10, 2))]
757    #[case::decimal_from_primitive(primitive(), DataType::Decimal128(10, 2))]
758    #[case::list_from_utf8(utf8(), list_target())]
759    #[case::list_from_primitive(primitive(), list_target())]
760    #[case::list_view_from_primitive(
761        primitive(),
762        DataType::ListView(Arc::new(Field::new("item", DataType::Int32, true)))
763    )]
764    #[case::fixed_size_list_from_utf8(
765        utf8(),
766        DataType::FixedSizeList(Arc::new(Field::new("item", DataType::Int32, true)), 2)
767    )]
768    #[case::map_from_primitive(primitive(), map_target())]
769    #[case::byte_from_primitive(primitive(), DataType::Utf8)]
770    #[case::byte_from_bool(boolean(), DataType::Binary)]
771    fn incompatible_target_returns_error(#[case] array: ArrayRef, #[case] target: DataType) {
772        let mut ctx = SESSION.create_execution_ctx();
773        let field = Field::new("f", target.clone(), array.dtype().is_nullable());
774
775        let result = array.execute_arrow(Some(&field), &mut ctx);
776
777        assert!(
778            result.is_err(),
779            "expected an error exporting to {target:?}, got Ok"
780        );
781    }
782
783    /// Cross-class conversions that are genuinely supported must keep working.
784    #[rstest]
785    #[case::bool_to_int32(boolean(), DataType::Int32, Arc::new(Int32Array::from(vec![1, 0])))]
786    #[case::bool_to_float64(boolean(), DataType::Float64, Arc::new(Float64Array::from(vec![1., 0.])))]
787    #[case::primitive_to_int64(primitive(), DataType::Int64, Arc::new(Int64Array::from(vec![1, 2])))]
788    #[case::primitive_to_date32(primitive(), DataType::Date32, Arc::new(Date32Array::from(vec![1, 2])))]
789    #[case::primitive_to_timestamp(primitive(), DataType::Timestamp(TimeUnit::Microsecond, None), Arc::new(TimestampMicrosecondArray::from(vec![1, 2])))]
790    #[case::utf8_to_binary(utf8(), DataType::Binary, Arc::new(BinaryArray::from(vec![b"a".as_slice(), b"bb".as_slice()])))]
791    #[case::utf8_to_large_utf8(utf8(), DataType::LargeUtf8, Arc::new(LargeStringArray::from(vec!["a", "bb"])))]
792    fn supported_cross_class_target_still_works(
793        #[case] array: ArrayRef,
794        #[case] target: DataType,
795        #[case] expected: ArrowArrayRef,
796    ) {
797        let mut ctx = SESSION.create_execution_ctx();
798        let field = Field::new("f", target, array.dtype().is_nullable());
799
800        let result = array.execute_arrow(Some(&field), &mut ctx);
801
802        assert_eq!(result.unwrap().to_data(), expected.to_data());
803    }
804}