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#![expect(
5    deprecated,
6    reason = "This module defines and implements a deprecated trait `ArrowArrayExecutor`"
7)]
8
9pub mod bool;
10mod byte;
11pub mod byte_view;
12mod decimal;
13mod dictionary;
14mod fixed_size_list;
15mod list;
16mod list_view;
17mod map;
18pub mod null;
19pub mod primitive;
20mod run_end;
21mod struct_;
22mod temporal;
23mod validity;
24
25use arrow_array::ArrayRef as ArrowArrayRef;
26use arrow_array::RecordBatch;
27use arrow_array::cast::AsArray;
28use arrow_array::types::*;
29use arrow_schema::DataType;
30use arrow_schema::Field;
31use arrow_schema::FieldRef;
32use arrow_schema::Schema;
33use itertools::Itertools;
34use vortex_array::ArrayRef;
35use vortex_array::ExecutionCtx;
36use vortex_array::arrays::List;
37use vortex_array::arrays::VarBin;
38use vortex_array::arrays::list::ListArraySlotsExt;
39use vortex_array::arrays::varbin::VarBinArraySlotsExt;
40use vortex_array::dtype::DType;
41use vortex_array::dtype::PType;
42use vortex_error::VortexResult;
43use vortex_error::vortex_bail;
44use vortex_error::vortex_ensure;
45
46use crate::executor::bool::to_arrow_bool;
47use crate::executor::byte::to_arrow_byte_array;
48use crate::executor::byte_view::to_arrow_byte_view;
49use crate::executor::decimal::to_arrow_decimal;
50use crate::executor::dictionary::to_arrow_dictionary;
51use crate::executor::fixed_size_list::to_arrow_fixed_list;
52use crate::executor::list::to_arrow_list;
53use crate::executor::list_view::to_arrow_list_view;
54use crate::executor::map::to_arrow_map;
55use crate::executor::null::to_arrow_null;
56use crate::executor::primitive::to_arrow_primitive;
57use crate::executor::run_end::to_arrow_run_end;
58use crate::executor::struct_::to_arrow_struct;
59use crate::executor::temporal::to_arrow_date;
60use crate::executor::temporal::to_arrow_time;
61use crate::executor::temporal::to_arrow_timestamp;
62use crate::session::ArrowSessionExt;
63
64/// Trait for executing a Vortex array to produce an Arrow array.
65#[deprecated(note = "Use an `ArrowSession` to perform conversions to/from Arrow arrays")]
66pub trait ArrowArrayExecutor: Sized {
67    /// Execute the array to produce an Arrow array.
68    ///
69    /// If a [`DataType`] is given, the array will be converted to the desired Arrow type.
70    /// If `None`, the array's preferred (cheapest) Arrow type will be used.
71    #[deprecated(note = "Use an `ArrowSession` to perform conversions to/from Arrow arrays")]
72    fn execute_arrow(
73        self,
74        data_type: Option<&DataType>,
75        ctx: &mut ExecutionCtx,
76    ) -> VortexResult<ArrowArrayRef>;
77
78    /// Execute the array to produce an Arrow `RecordBatch` with the given schema.
79    #[deprecated(note = "Use an `ArrowSession` to perform conversions to/from Arrow arrays")]
80    fn execute_record_batch(
81        self,
82        schema: &Schema,
83        ctx: &mut ExecutionCtx,
84    ) -> VortexResult<RecordBatch> {
85        let array = self.execute_arrow(Some(&DataType::Struct(schema.fields.clone())), ctx)?;
86        Ok(RecordBatch::from(array.as_struct()))
87    }
88
89    /// Execute the array to produce Arrow `RecordBatch`'s with the given schema.
90    #[deprecated(note = "Use an `ArrowSession` to perform conversions to/from Arrow arrays")]
91    fn execute_record_batches(
92        self,
93        schema: &Schema,
94        ctx: &mut ExecutionCtx,
95    ) -> VortexResult<Vec<RecordBatch>>;
96}
97
98#[expect(deprecated, reason = "backward compatibility")]
99impl ArrowArrayExecutor for ArrayRef {
100    fn execute_arrow(
101        self,
102        data_type: Option<&DataType>,
103        ctx: &mut ExecutionCtx,
104    ) -> VortexResult<ArrowArrayRef> {
105        let target = data_type.map(|dt| Field::new("", dt.clone(), self.dtype().is_nullable()));
106        let session = ctx.session().clone();
107        session.arrow().execute_arrow(self, target.as_ref(), ctx)
108    }
109
110    fn execute_record_batches(
111        self,
112        schema: &Schema,
113        ctx: &mut ExecutionCtx,
114    ) -> VortexResult<Vec<RecordBatch>> {
115        self.to_array_iterator()
116            .map(|a| a?.execute_record_batch(schema, ctx))
117            .try_collect()
118    }
119}
120
121/// Execute an arbitrary Vortex array into an Arrow array, dispatched by [`DataType`]. This pathway
122/// is naive to any extension type information, and only seeks to map canonical Vortex arrays to
123/// some target Arrow physical encoding.
124///
125/// Public callers should go through the `ArrowSession` instead.
126pub(crate) fn execute_arrow_naive(
127    array: ArrayRef,
128    data_type: Option<&DataType>,
129    ctx: &mut ExecutionCtx,
130) -> VortexResult<ArrowArrayRef> {
131    let len = array.len();
132
133    let resolved_type: DataType = match data_type {
134        Some(dt) => dt.clone(),
135        None => infer_nearest_arrow_type(&array, ctx)?,
136    };
137
138    let arrow = match &resolved_type {
139        DataType::Null => to_arrow_null(array, ctx),
140        DataType::Boolean => to_arrow_bool(array, ctx),
141        DataType::Int8 => to_arrow_primitive::<Int8Type>(array, ctx),
142        DataType::Int16 => to_arrow_primitive::<Int16Type>(array, ctx),
143        DataType::Int32 => to_arrow_primitive::<Int32Type>(array, ctx),
144        DataType::Int64 => to_arrow_primitive::<Int64Type>(array, ctx),
145        DataType::UInt8 => to_arrow_primitive::<UInt8Type>(array, ctx),
146        DataType::UInt16 => to_arrow_primitive::<UInt16Type>(array, ctx),
147        DataType::UInt32 => to_arrow_primitive::<UInt32Type>(array, ctx),
148        DataType::UInt64 => to_arrow_primitive::<UInt64Type>(array, ctx),
149        DataType::Float16 => to_arrow_primitive::<Float16Type>(array, ctx),
150        DataType::Float32 => to_arrow_primitive::<Float32Type>(array, ctx),
151        DataType::Float64 => to_arrow_primitive::<Float64Type>(array, ctx),
152        DataType::Binary => to_arrow_byte_array::<BinaryType>(array, ctx),
153        DataType::LargeBinary => to_arrow_byte_array::<LargeBinaryType>(array, ctx),
154        DataType::Utf8 => to_arrow_byte_array::<Utf8Type>(array, ctx),
155        DataType::LargeUtf8 => to_arrow_byte_array::<LargeUtf8Type>(array, ctx),
156        DataType::BinaryView => to_arrow_byte_view::<BinaryViewType>(array, ctx),
157        DataType::Utf8View => to_arrow_byte_view::<StringViewType>(array, ctx),
158        // TODO(joe): pass down preferred
159        DataType::List(elements_field) => to_arrow_list::<i32>(array, elements_field, ctx),
160        // TODO(joe): pass down preferred
161        DataType::LargeList(elements_field) => to_arrow_list::<i64>(array, elements_field, ctx),
162        // TODO(joe): pass down preferred
163        DataType::FixedSizeList(elements_field, list_size) => {
164            to_arrow_fixed_list(array, *list_size, elements_field, ctx)
165        }
166        // TODO(joe): pass down preferred
167        DataType::ListView(elements_field) => to_arrow_list_view::<i32>(array, elements_field, ctx),
168        // TODO(joe): pass down preferred
169        DataType::LargeListView(elements_field) => {
170            to_arrow_list_view::<i64>(array, elements_field, ctx)
171        }
172        DataType::Struct(fields) => {
173            let fields = if data_type.is_none() {
174                None
175            } else {
176                Some(fields)
177            };
178            to_arrow_struct(array, fields, ctx)
179        }
180        // TODO(joe): pass down preferred
181        DataType::Dictionary(codes_type, values_type) => {
182            to_arrow_dictionary(array, codes_type, values_type, ctx)
183        }
184        dt @ DataType::Decimal32(..) => to_arrow_decimal(array, dt, ctx),
185        dt @ DataType::Decimal64(..) => to_arrow_decimal(array, dt, ctx),
186        dt @ DataType::Decimal128(..) => to_arrow_decimal(array, dt, ctx),
187        dt @ DataType::Decimal256(..) => to_arrow_decimal(array, dt, ctx),
188        // TODO(joe): pass down preferred
189        DataType::RunEndEncoded(ends_type, values_type) => {
190            to_arrow_run_end(array, ends_type.data_type(), values_type, ctx)
191        }
192        dt @ (DataType::Date32 | DataType::Date64) => to_arrow_date(array, dt, ctx),
193        dt @ (DataType::Time32(_) | DataType::Time64(_)) => to_arrow_time(array, dt, ctx),
194        dt @ DataType::Timestamp(..) => to_arrow_timestamp(array, dt, ctx),
195        DataType::Map(entries_field, keys_sorted) => {
196            to_arrow_map(array, entries_field, *keys_sorted, ctx)
197        }
198        DataType::FixedSizeBinary(_)
199        | DataType::Duration(_)
200        | DataType::Interval(_)
201        | DataType::Union(..) => {
202            vortex_bail!("Conversion to Arrow type {resolved_type} is not supported");
203        }
204    }?;
205
206    vortex_ensure!(
207        arrow.len() == len,
208        "Arrow array length does not match Vortex array length after conversion to {:?}",
209        arrow
210    );
211
212    Ok(arrow)
213}
214
215/// Determine the preferred (cheapest) Arrow type for an array.
216///
217/// For most arrays, this returns the canonical Arrow type for the array's dtype.
218/// However, some encodings have cheaper Arrow representations:
219/// - `VarBinArray`: Uses `Utf8`/`Binary` (offset-based) instead of `Utf8View`/`BinaryView`
220/// - `ListArray`: Uses `List` instead of `ListView`
221fn infer_nearest_arrow_type(array: &ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult<DataType> {
222    // VarBinArray: use offset-based Binary/Utf8 instead of View types
223    if let Some(varbin) = array.as_opt::<VarBin>() {
224        let offsets_ptype = PType::try_from(varbin.offsets().dtype())?;
225        let use_large = matches!(offsets_ptype, PType::I64 | PType::U64);
226
227        return Ok(match (varbin.dtype(), use_large) {
228            (DType::Utf8(_), false) => DataType::Utf8,
229            (DType::Utf8(_), true) => DataType::LargeUtf8,
230            (DType::Binary(_), false) => DataType::Binary,
231            (DType::Binary(_), true) => DataType::LargeBinary,
232            _ => unreachable!("VarBinArray must have Utf8 or Binary dtype"),
233        });
234    }
235
236    // ListArray: use List with appropriate offset size
237    if let Some(list) = array.as_opt::<List>() {
238        let offsets_ptype = PType::try_from(list.offsets().dtype())?;
239        let use_large = matches!(offsets_ptype, PType::I64 | PType::U64);
240        // Recursively get the preferred field for elements, so extension elements keep the
241        // `ARROW:extension:name` metadata their export plugin assigns.
242        let field = FieldRef::new(infer_nearest_arrow_field(
243            list.elements(),
244            Field::LIST_FIELD_DEFAULT_NAME,
245            ctx,
246        )?);
247
248        return Ok(if use_large {
249            DataType::LargeList(field)
250        } else {
251            DataType::List(field)
252        });
253    }
254
255    // Everything else: defer to the session's canonical conversion, which additionally resolves
256    // extension dtypes (including ones nested inside containers) through their export plugins.
257    Ok(infer_nearest_arrow_field(array, "", ctx)?
258        .data_type()
259        .clone())
260}
261
262/// Determine the preferred (cheapest) Arrow [`Field`] for an array.
263///
264/// Unlike [`infer_nearest_arrow_type`] this preserves the Field-level `ARROW:extension:name`
265/// metadata that export plugins assign, which a bare [`DataType`] cannot carry.
266pub(crate) fn infer_nearest_arrow_field(
267    array: &ArrayRef,
268    name: &str,
269    ctx: &mut ExecutionCtx,
270) -> VortexResult<Field> {
271    // Only the encodings with a cheaper-than-canonical Arrow type need the inference; every other
272    // dtype goes through the session, which is the only thing that knows how to map extensions.
273    if array.is::<VarBin>() || array.is::<List>() {
274        let data_type = infer_nearest_arrow_type(array, ctx)?;
275        return Ok(Field::new(name, data_type, array.dtype().is_nullable()));
276    }
277    ctx.session()
278        .clone()
279        .arrow()
280        .to_arrow_field(name, array.dtype())
281}
282
283#[cfg(test)]
284mod tests {
285    use std::sync::Arc;
286
287    use arrow_schema::DataType;
288    use arrow_schema::Field;
289    use arrow_schema::TimeUnit;
290    use rstest::rstest;
291    use vortex_array::ArrayRef;
292    use vortex_array::IntoArray;
293    use vortex_array::VortexSessionExecute;
294    use vortex_array::array_session;
295    use vortex_array::arrays::BoolArray;
296    use vortex_array::arrays::PrimitiveArray;
297    use vortex_array::arrays::VarBinViewArray;
298
299    use crate::ArrowSessionExt;
300
301    fn utf8() -> ArrayRef {
302        VarBinViewArray::from_iter_str(["a", "bb"]).into_array()
303    }
304
305    fn primitive() -> ArrayRef {
306        PrimitiveArray::from_iter([1i32, 2]).into_array()
307    }
308
309    fn boolean() -> ArrayRef {
310        BoolArray::from_iter([true, false]).into_array()
311    }
312
313    fn list_target() -> DataType {
314        DataType::List(Arc::new(Field::new("item", DataType::Int32, true)))
315    }
316
317    /// Must error rather than panic inside `execute::<T>`.
318    #[rstest]
319    #[case::bool_from_utf8(utf8(), DataType::Boolean)]
320    #[case::bool_from_primitive(primitive(), DataType::Boolean)]
321    #[case::null_from_utf8(utf8(), DataType::Null)]
322    #[case::null_from_primitive(primitive(), DataType::Null)]
323    #[case::decimal_from_utf8(utf8(), DataType::Decimal128(10, 2))]
324    #[case::decimal_from_primitive(primitive(), DataType::Decimal128(10, 2))]
325    #[case::list_from_utf8(utf8(), list_target())]
326    #[case::list_from_primitive(primitive(), list_target())]
327    #[case::list_view_from_primitive(
328        primitive(),
329        DataType::ListView(Arc::new(Field::new("item", DataType::Int32, true)))
330    )]
331    #[case::fixed_size_list_from_utf8(
332        utf8(),
333        DataType::FixedSizeList(Arc::new(Field::new("item", DataType::Int32, true)), 2)
334    )]
335    #[case::byte_from_primitive(primitive(), DataType::Utf8)]
336    #[case::byte_from_bool(boolean(), DataType::Binary)]
337    fn incompatible_target_returns_error(#[case] array: ArrayRef, #[case] target: DataType) {
338        let session = array_session();
339        let mut ctx = session.create_execution_ctx();
340        let field = Field::new("f", target.clone(), array.dtype().is_nullable());
341
342        let result = session.arrow().execute_arrow(array, Some(&field), &mut ctx);
343
344        assert!(
345            result.is_err(),
346            "expected an error exporting to {target:?}, got Ok"
347        );
348    }
349
350    /// Cross-class conversions that are genuinely supported must keep working.
351    #[rstest]
352    #[case::bool_to_int32(boolean(), DataType::Int32)]
353    #[case::bool_to_float64(boolean(), DataType::Float64)]
354    #[case::primitive_to_int64(primitive(), DataType::Int64)]
355    #[case::primitive_to_date32(primitive(), DataType::Date32)]
356    #[case::primitive_to_timestamp(primitive(), DataType::Timestamp(TimeUnit::Microsecond, None))]
357    #[case::utf8_to_binary(utf8(), DataType::Binary)]
358    #[case::utf8_to_large_utf8(utf8(), DataType::LargeUtf8)]
359    fn supported_cross_class_target_still_works(#[case] array: ArrayRef, #[case] target: DataType) {
360        let session = array_session();
361        let mut ctx = session.create_execution_ctx();
362        let field = Field::new("f", target.clone(), array.dtype().is_nullable());
363
364        let result = session.arrow().execute_arrow(array, Some(&field), &mut ctx);
365
366        assert!(
367            result.is_ok(),
368            "expected {target:?} export to succeed, got {:?}",
369            result.err()
370        );
371    }
372}