Skip to main content

vortex_arrow/
datum.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use arrow_array::Array as ArrowArray;
5use arrow_array::ArrayRef as ArrowArrayRef;
6use arrow_array::Datum as ArrowDatum;
7use arrow_schema::DataType;
8use arrow_schema::Field;
9use vortex_array::ArrayRef;
10use vortex_array::ExecutionCtx;
11use vortex_array::IntoArray;
12use vortex_array::arrays::Constant;
13use vortex_array::arrays::ConstantArray;
14use vortex_error::VortexResult;
15use vortex_error::vortex_panic;
16
17use crate::ArrowSessionExt;
18use crate::ExecuteArrowExt;
19
20/// A wrapper around a generic Arrow array that can be used as a Datum in Arrow compute.
21///
22/// A `Datum` has no Arrow field to hold extension metadata, so [`Datum::try_new`] and
23/// [`Datum::try_new_array`] fail for the same types that
24/// [`ArrowSession::default_arrow_export_field`] rejects. [`Datum::try_new_with_target_datatype`]
25/// exports to the given [`DataType`] instead. For an extension array, that type must import as
26/// the extension type, such as an Arrow timestamp for a timestamp array. To pass the storage of an
27/// extension array to Arrow compute, apply [`ext_storage`] to the array first.
28///
29/// [`ArrowSession::default_arrow_export_field`]: crate::ArrowSession::default_arrow_export_field
30/// [`ext_storage`]: vortex_functions::expr::ext_storage
31#[derive(Debug)]
32pub struct Datum {
33    array: ArrowArrayRef,
34    is_scalar: bool,
35}
36
37impl Datum {
38    /// Create a new [`Datum`] from an [`ArrayRef`], which can then be passed to Arrow compute.
39    pub fn try_new(array: &ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult<Self> {
40        if array.is::<Constant>() {
41            Ok(Self {
42                array: array.slice(0..1)?.execute_arrow(None, ctx)?,
43                is_scalar: true,
44            })
45        } else {
46            Ok(Self {
47                array: array.clone().execute_arrow(None, ctx)?,
48                is_scalar: false,
49            })
50        }
51    }
52
53    /// Create a new [`Datum`] from an `DynArrayData`, which can then be passed to Arrow compute.
54    /// This not try and convert the array to a scalar if it is constant.
55    pub fn try_new_array(array: &ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult<Self> {
56        Ok(Self {
57            array: array.clone().execute_arrow(None, ctx)?,
58            is_scalar: false,
59        })
60    }
61
62    pub fn try_new_with_target_datatype(
63        array: &ArrayRef,
64        target_datatype: &DataType,
65        ctx: &mut ExecutionCtx,
66    ) -> VortexResult<Self> {
67        let target_field = Field::new(
68            String::new(),
69            target_datatype.clone(),
70            array.dtype().is_nullable(),
71        );
72
73        if array.is::<Constant>() {
74            Ok(Self {
75                array: array.slice(0..1)?.execute_arrow(Some(&target_field), ctx)?,
76                is_scalar: true,
77            })
78        } else {
79            Ok(Self {
80                array: array.clone().execute_arrow(Some(&target_field), ctx)?,
81                is_scalar: false,
82            })
83        }
84    }
85
86    pub fn data_type(&self) -> &DataType {
87        self.array.data_type()
88    }
89}
90
91impl ArrowDatum for Datum {
92    fn get(&self) -> (&dyn ArrowArray, bool) {
93        (&self.array, self.is_scalar)
94    }
95}
96
97/// Convert an Arrow array to an Array with a specific length, using the provided
98/// [`ExecutionCtx`].
99///
100/// This is useful for compute functions that delegate to Arrow using [Datum],
101/// which will return a scalar (length 1 Arrow array) if the input array is constant.
102///
103/// The array is imported through the [`ArrowSession`](crate::ArrowSession) of `ctx`, so nested
104/// extension fields reach their registered import plugins.
105///
106/// # Error
107///
108/// The provided array must have length `len` or `1`.
109pub fn from_arrow_columnar(
110    array: ArrowArrayRef,
111    len: usize,
112    nullable: bool,
113    ctx: &mut ExecutionCtx,
114) -> VortexResult<ArrayRef> {
115    let session = ctx.session().clone();
116    let array = session.arrow().from_arrow_array(array, nullable)?;
117    if array.len() == len {
118        return Ok(array);
119    }
120
121    if array.len() != 1 {
122        vortex_panic!(
123            "Array length mismatch, expected {} got {} for encoding {}",
124            len,
125            array.len(),
126            array.encoding_id()
127        );
128    }
129
130    Ok(ConstantArray::new(array.execute_scalar(0, ctx)?, len).into_array())
131}