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