vortex_dtype/
arrow.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! Convert between Vortex [`crate::DType`] and Apache Arrow [`arrow_schema::DataType`].
5//!
6//! Apache Arrow's type system includes physical information, which could lead to ambiguities as
7//! Vortex treats encodings as separate from logical types.
8//!
9//! [`DType::to_arrow_schema`] and its sibling [`DType::to_arrow_dtype`] use a simple algorithm,
10//! where every logical type is encoded in its simplest corresponding Arrow type. This reflects the
11//! reality that most compute engines don't make use of the entire type range arrow-rs supports.
12//!
13//! For this reason, it's recommended to do as much computation as possible within Vortex, and then
14//! materialize an Arrow ArrayRef at the very end of the processing chain.
15
16use std::sync::Arc;
17
18use arrow_schema::{
19    DECIMAL128_MAX_PRECISION, DataType, Field, FieldRef, Fields, Schema, SchemaBuilder, SchemaRef,
20};
21use vortex_error::{VortexExpect, VortexResult, vortex_bail, vortex_err};
22
23use crate::datetime::arrow::{make_arrow_temporal_dtype, make_temporal_ext_dtype};
24use crate::datetime::is_temporal_ext_type;
25use crate::{DType, DecimalDType, FieldName, Nullability, PType, StructFields};
26
27/// Trait for converting Arrow types to Vortex types.
28pub trait FromArrowType<T>: Sized {
29    /// Convert the Arrow type to a Vortex type.
30    fn from_arrow(value: T) -> Self;
31}
32
33/// Trait for converting Vortex types to Arrow types.
34pub trait TryFromArrowType<T>: Sized {
35    /// Convert the Arrow type to a Vortex type.
36    fn try_from_arrow(value: T) -> VortexResult<Self>;
37}
38
39impl TryFromArrowType<&DataType> for PType {
40    fn try_from_arrow(value: &DataType) -> VortexResult<Self> {
41        match value {
42            DataType::Int8 => Ok(Self::I8),
43            DataType::Int16 => Ok(Self::I16),
44            DataType::Int32 => Ok(Self::I32),
45            DataType::Int64 => Ok(Self::I64),
46            DataType::UInt8 => Ok(Self::U8),
47            DataType::UInt16 => Ok(Self::U16),
48            DataType::UInt32 => Ok(Self::U32),
49            DataType::UInt64 => Ok(Self::U64),
50            DataType::Float16 => Ok(Self::F16),
51            DataType::Float32 => Ok(Self::F32),
52            DataType::Float64 => Ok(Self::F64),
53            _ => Err(vortex_err!(
54                "Arrow datatype {:?} cannot be converted to ptype",
55                value
56            )),
57        }
58    }
59}
60
61impl TryFromArrowType<&DataType> for DecimalDType {
62    fn try_from_arrow(value: &DataType) -> VortexResult<Self> {
63        match value {
64            DataType::Decimal128(precision, scale) => Self::try_new(*precision, *scale),
65            DataType::Decimal256(precision, scale) => Self::try_new(*precision, *scale),
66            _ => Err(vortex_err!(
67                "Arrow datatype {:?} cannot be converted to DecimalDType",
68                value
69            )),
70        }
71    }
72}
73
74impl FromArrowType<SchemaRef> for DType {
75    fn from_arrow(value: SchemaRef) -> Self {
76        Self::from_arrow(value.as_ref())
77    }
78}
79
80impl FromArrowType<&Schema> for DType {
81    fn from_arrow(value: &Schema) -> Self {
82        Self::Struct(
83            StructFields::from_arrow(value.fields()),
84            Nullability::NonNullable, // Must match From<RecordBatch> for Array
85        )
86    }
87}
88
89impl FromArrowType<&Fields> for StructFields {
90    fn from_arrow(value: &Fields) -> Self {
91        StructFields::from_iter(value.into_iter().map(|f| {
92            (
93                FieldName::from(f.name().as_str()),
94                DType::from_arrow(f.as_ref()),
95            )
96        }))
97    }
98}
99
100impl FromArrowType<(&DataType, Nullability)> for DType {
101    fn from_arrow((data_type, nullability): (&DataType, Nullability)) -> Self {
102        use crate::DType::*;
103
104        if data_type.is_integer() || data_type.is_floating() {
105            return Primitive(
106                PType::try_from_arrow(data_type).vortex_expect("arrow float/integer to ptype"),
107                nullability,
108            );
109        }
110
111        match data_type {
112            DataType::Null => Null,
113            DataType::Decimal128(precision, scale) | DataType::Decimal256(precision, scale) => {
114                Decimal(DecimalDType::new(*precision, *scale), nullability)
115            }
116            DataType::Boolean => Bool(nullability),
117            DataType::Utf8 | DataType::LargeUtf8 | DataType::Utf8View => Utf8(nullability),
118            DataType::Binary | DataType::LargeBinary | DataType::BinaryView => Binary(nullability),
119            DataType::Date32
120            | DataType::Date64
121            | DataType::Time32(_)
122            | DataType::Time64(_)
123            | DataType::Timestamp(..) => Extension(Arc::new(
124                make_temporal_ext_dtype(data_type).with_nullability(nullability),
125            )),
126            DataType::List(e) | DataType::LargeList(e) => {
127                List(Arc::new(Self::from_arrow(e.as_ref())), nullability)
128            }
129            DataType::Struct(f) => Struct(StructFields::from_arrow(f), nullability),
130            DataType::Dictionary(_, value_type) => {
131                Self::from_arrow((value_type.as_ref(), nullability))
132            }
133            _ => unimplemented!("Arrow data type not yet supported: {:?}", data_type),
134        }
135    }
136}
137
138impl FromArrowType<&Field> for DType {
139    fn from_arrow(field: &Field) -> Self {
140        Self::from_arrow((field.data_type(), field.is_nullable().into()))
141    }
142}
143
144impl DType {
145    /// Convert a Vortex [`DType`] into an Arrow [`Schema`].
146    pub fn to_arrow_schema(&self) -> VortexResult<Schema> {
147        let DType::Struct(struct_dtype, nullable) = self else {
148            vortex_bail!("only DType::Struct can be converted to arrow schema");
149        };
150
151        if *nullable != Nullability::NonNullable {
152            vortex_bail!("top-level struct in Schema must be NonNullable");
153        }
154
155        let mut builder = SchemaBuilder::with_capacity(struct_dtype.names().len());
156        for (field_name, field_dtype) in struct_dtype.names().iter().zip(struct_dtype.fields()) {
157            builder.push(FieldRef::from(Field::new(
158                field_name.to_string(),
159                field_dtype.to_arrow_dtype()?,
160                field_dtype.is_nullable(),
161            )));
162        }
163
164        Ok(builder.finish())
165    }
166
167    /// Returns the Arrow [`DataType`] that best corresponds to this Vortex [`DType`].
168    pub fn to_arrow_dtype(&self) -> VortexResult<DataType> {
169        Ok(match self {
170            DType::Null => DataType::Null,
171            DType::Bool(_) => DataType::Boolean,
172            DType::Primitive(ptype, _) => match ptype {
173                PType::U8 => DataType::UInt8,
174                PType::U16 => DataType::UInt16,
175                PType::U32 => DataType::UInt32,
176                PType::U64 => DataType::UInt64,
177                PType::I8 => DataType::Int8,
178                PType::I16 => DataType::Int16,
179                PType::I32 => DataType::Int32,
180                PType::I64 => DataType::Int64,
181                PType::F16 => DataType::Float16,
182                PType::F32 => DataType::Float32,
183                PType::F64 => DataType::Float64,
184            },
185            DType::Decimal(dt, _) => {
186                if dt.precision() > DECIMAL128_MAX_PRECISION {
187                    DataType::Decimal256(dt.precision(), dt.scale())
188                } else {
189                    DataType::Decimal128(dt.precision(), dt.scale())
190                }
191            }
192            DType::Utf8(_) => DataType::Utf8View,
193            DType::Binary(_) => DataType::BinaryView,
194            DType::Struct(struct_dtype, _) => {
195                let mut fields = Vec::with_capacity(struct_dtype.names().len());
196                for (field_name, field_dt) in struct_dtype.names().iter().zip(struct_dtype.fields())
197                {
198                    fields.push(FieldRef::from(Field::new(
199                        field_name.to_string(),
200                        field_dt.to_arrow_dtype()?,
201                        field_dt.is_nullable(),
202                    )));
203                }
204
205                DataType::Struct(Fields::from(fields))
206            }
207            // There are four kinds of lists: List (32-bit offsets), Large List (64-bit), List View
208            // (32-bit), Large List View (64-bit). We cannot both guarantee zero-copy and commit to an
209            // Arrow dtype because we do not how large our offsets are.
210            DType::List(l, _) => DataType::List(FieldRef::new(Field::new_list_field(
211                l.to_arrow_dtype()?,
212                l.nullability().into(),
213            ))),
214            DType::Extension(ext_dtype) => {
215                // Try and match against the known extension DTypes.
216                if is_temporal_ext_type(ext_dtype.id()) {
217                    make_arrow_temporal_dtype(ext_dtype)
218                } else {
219                    vortex_bail!("Unsupported extension type \"{}\"", ext_dtype.id())
220                }
221            }
222        })
223    }
224}
225
226#[cfg(test)]
227mod test {
228    use arrow_schema::{DataType, Field, FieldRef, Fields, Schema};
229    use rstest::{fixture, rstest};
230
231    use super::*;
232    use crate::{DType, ExtDType, ExtID, FieldName, FieldNames, Nullability, PType, StructFields};
233
234    #[test]
235    fn test_dtype_conversion_success() {
236        assert_eq!(DType::Null.to_arrow_dtype().unwrap(), DataType::Null);
237
238        assert_eq!(
239            DType::Bool(Nullability::NonNullable)
240                .to_arrow_dtype()
241                .unwrap(),
242            DataType::Boolean
243        );
244
245        assert_eq!(
246            DType::Primitive(PType::U64, Nullability::NonNullable)
247                .to_arrow_dtype()
248                .unwrap(),
249            DataType::UInt64
250        );
251
252        assert_eq!(
253            DType::Utf8(Nullability::NonNullable)
254                .to_arrow_dtype()
255                .unwrap(),
256            DataType::Utf8View
257        );
258
259        assert_eq!(
260            DType::Binary(Nullability::NonNullable)
261                .to_arrow_dtype()
262                .unwrap(),
263            DataType::BinaryView
264        );
265
266        assert_eq!(
267            DType::struct_(
268                [
269                    ("field_a", DType::Bool(false.into())),
270                    ("field_b", DType::Utf8(true.into()))
271                ],
272                Nullability::NonNullable,
273            )
274            .to_arrow_dtype()
275            .unwrap(),
276            DataType::Struct(Fields::from(vec![
277                FieldRef::from(Field::new("field_a", DataType::Boolean, false)),
278                FieldRef::from(Field::new("field_b", DataType::Utf8View, true)),
279            ]))
280        );
281    }
282
283    #[test]
284    fn infer_nullable_list_element() {
285        let list_non_nullable = DType::List(
286            Arc::new(DType::Primitive(PType::I64, Nullability::NonNullable)),
287            Nullability::Nullable,
288        );
289
290        let arrow_list_non_nullable = list_non_nullable.to_arrow_dtype().unwrap();
291
292        let list_nullable = DType::List(
293            Arc::new(DType::Primitive(PType::I64, Nullability::Nullable)),
294            Nullability::Nullable,
295        );
296        let arrow_list_nullable = list_nullable.to_arrow_dtype().unwrap();
297
298        assert_ne!(arrow_list_non_nullable, arrow_list_nullable);
299        assert_eq!(
300            arrow_list_nullable,
301            DataType::new_list(DataType::Int64, true)
302        );
303        assert_eq!(
304            arrow_list_non_nullable,
305            DataType::new_list(DataType::Int64, false)
306        );
307    }
308
309    #[test]
310    #[should_panic]
311    fn test_dtype_conversion_panics() {
312        let _ = DType::Extension(Arc::new(ExtDType::new(
313            ExtID::from("my-fake-ext-dtype"),
314            Arc::new(DType::Utf8(Nullability::NonNullable)),
315            None,
316        )))
317        .to_arrow_dtype()
318        .unwrap();
319    }
320
321    #[fixture]
322    fn the_struct() -> StructFields {
323        StructFields::new(
324            FieldNames::from([
325                FieldName::from("field_a"),
326                FieldName::from("field_b"),
327                FieldName::from("field_c"),
328            ]),
329            vec![
330                DType::Bool(Nullability::NonNullable),
331                DType::Utf8(Nullability::NonNullable),
332                DType::Primitive(PType::I32, Nullability::Nullable),
333            ],
334        )
335    }
336
337    #[rstest]
338    fn test_schema_conversion(the_struct: StructFields) {
339        let schema_nonnull = DType::Struct(the_struct, Nullability::NonNullable);
340
341        assert_eq!(
342            schema_nonnull.to_arrow_schema().unwrap(),
343            Schema::new(Fields::from(vec![
344                Field::new("field_a", DataType::Boolean, false),
345                Field::new("field_b", DataType::Utf8View, false),
346                Field::new("field_c", DataType::Int32, true),
347            ]))
348        );
349    }
350
351    #[rstest]
352    #[should_panic]
353    fn test_schema_conversion_panics(the_struct: StructFields) {
354        let schema_null = DType::Struct(the_struct, Nullability::Nullable);
355        let _ = schema_null.to_arrow_schema().unwrap();
356    }
357}