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) => Ok(Self::new(*precision, *scale)),
65            DataType::Decimal256(precision, scale) => Ok(Self::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            _ => unimplemented!("Arrow data type not yet supported: {:?}", data_type),
131        }
132    }
133}
134
135impl FromArrowType<&Field> for DType {
136    fn from_arrow(field: &Field) -> Self {
137        Self::from_arrow((field.data_type(), field.is_nullable().into()))
138    }
139}
140
141impl DType {
142    /// Convert a Vortex [`DType`] into an Arrow [`Schema`].
143    pub fn to_arrow_schema(&self) -> VortexResult<Schema> {
144        let DType::Struct(struct_dtype, nullable) = self else {
145            vortex_bail!("only DType::Struct can be converted to arrow schema");
146        };
147
148        if *nullable != Nullability::NonNullable {
149            vortex_bail!("top-level struct in Schema must be NonNullable");
150        }
151
152        let mut builder = SchemaBuilder::with_capacity(struct_dtype.names().len());
153        for (field_name, field_dtype) in struct_dtype.names().iter().zip(struct_dtype.fields()) {
154            builder.push(FieldRef::from(Field::new(
155                field_name.to_string(),
156                field_dtype.to_arrow_dtype()?,
157                field_dtype.is_nullable(),
158            )));
159        }
160
161        Ok(builder.finish())
162    }
163
164    /// Returns the Arrow [`DataType`] that best corresponds to this Vortex [`DType`].
165    pub fn to_arrow_dtype(&self) -> VortexResult<DataType> {
166        Ok(match self {
167            DType::Null => DataType::Null,
168            DType::Bool(_) => DataType::Boolean,
169            DType::Primitive(ptype, _) => match ptype {
170                PType::U8 => DataType::UInt8,
171                PType::U16 => DataType::UInt16,
172                PType::U32 => DataType::UInt32,
173                PType::U64 => DataType::UInt64,
174                PType::I8 => DataType::Int8,
175                PType::I16 => DataType::Int16,
176                PType::I32 => DataType::Int32,
177                PType::I64 => DataType::Int64,
178                PType::F16 => DataType::Float16,
179                PType::F32 => DataType::Float32,
180                PType::F64 => DataType::Float64,
181            },
182            DType::Decimal(dt, _) => {
183                if dt.precision() > DECIMAL128_MAX_PRECISION {
184                    DataType::Decimal256(dt.precision(), dt.scale())
185                } else {
186                    DataType::Decimal128(dt.precision(), dt.scale())
187                }
188            }
189            DType::Utf8(_) => DataType::Utf8View,
190            DType::Binary(_) => DataType::BinaryView,
191            DType::Struct(struct_dtype, _) => {
192                let mut fields = Vec::with_capacity(struct_dtype.names().len());
193                for (field_name, field_dt) in struct_dtype.names().iter().zip(struct_dtype.fields())
194                {
195                    fields.push(FieldRef::from(Field::new(
196                        field_name.to_string(),
197                        field_dt.to_arrow_dtype()?,
198                        field_dt.is_nullable(),
199                    )));
200                }
201
202                DataType::Struct(Fields::from(fields))
203            }
204            // There are four kinds of lists: List (32-bit offsets), Large List (64-bit), List View
205            // (32-bit), Large List View (64-bit). We cannot both guarantee zero-copy and commit to an
206            // Arrow dtype because we do not how large our offsets are.
207            DType::List(l, _) => DataType::List(FieldRef::new(Field::new_list_field(
208                l.to_arrow_dtype()?,
209                l.nullability().into(),
210            ))),
211            DType::Extension(ext_dtype) => {
212                // Try and match against the known extension DTypes.
213                if is_temporal_ext_type(ext_dtype.id()) {
214                    make_arrow_temporal_dtype(ext_dtype)
215                } else {
216                    vortex_bail!("Unsupported extension type \"{}\"", ext_dtype.id())
217                }
218            }
219        })
220    }
221}
222
223#[cfg(test)]
224mod test {
225    use arrow_schema::{DataType, Field, FieldRef, Fields, Schema};
226    use rstest::{fixture, rstest};
227
228    use super::*;
229    use crate::{DType, ExtDType, ExtID, FieldName, FieldNames, Nullability, PType, StructFields};
230
231    #[test]
232    fn test_dtype_conversion_success() {
233        assert_eq!(DType::Null.to_arrow_dtype().unwrap(), DataType::Null);
234
235        assert_eq!(
236            DType::Bool(Nullability::NonNullable)
237                .to_arrow_dtype()
238                .unwrap(),
239            DataType::Boolean
240        );
241
242        assert_eq!(
243            DType::Primitive(PType::U64, Nullability::NonNullable)
244                .to_arrow_dtype()
245                .unwrap(),
246            DataType::UInt64
247        );
248
249        assert_eq!(
250            DType::Utf8(Nullability::NonNullable)
251                .to_arrow_dtype()
252                .unwrap(),
253            DataType::Utf8View
254        );
255
256        assert_eq!(
257            DType::Binary(Nullability::NonNullable)
258                .to_arrow_dtype()
259                .unwrap(),
260            DataType::BinaryView
261        );
262
263        assert_eq!(
264            DType::struct_(
265                [
266                    ("field_a", DType::Bool(false.into())),
267                    ("field_b", DType::Utf8(true.into()))
268                ],
269                Nullability::NonNullable,
270            )
271            .to_arrow_dtype()
272            .unwrap(),
273            DataType::Struct(Fields::from(vec![
274                FieldRef::from(Field::new("field_a", DataType::Boolean, false)),
275                FieldRef::from(Field::new("field_b", DataType::Utf8View, true)),
276            ]))
277        );
278    }
279
280    #[test]
281    fn infer_nullable_list_element() {
282        let list_non_nullable = DType::List(
283            Arc::new(DType::Primitive(PType::I64, Nullability::NonNullable)),
284            Nullability::Nullable,
285        );
286
287        let arrow_list_non_nullable = list_non_nullable.to_arrow_dtype().unwrap();
288
289        let list_nullable = DType::List(
290            Arc::new(DType::Primitive(PType::I64, Nullability::Nullable)),
291            Nullability::Nullable,
292        );
293        let arrow_list_nullable = list_nullable.to_arrow_dtype().unwrap();
294
295        assert_ne!(arrow_list_non_nullable, arrow_list_nullable);
296        assert_eq!(
297            arrow_list_nullable,
298            DataType::new_list(DataType::Int64, true)
299        );
300        assert_eq!(
301            arrow_list_non_nullable,
302            DataType::new_list(DataType::Int64, false)
303        );
304    }
305
306    #[test]
307    #[should_panic]
308    fn test_dtype_conversion_panics() {
309        let _ = DType::Extension(Arc::new(ExtDType::new(
310            ExtID::from("my-fake-ext-dtype"),
311            Arc::new(DType::Utf8(Nullability::NonNullable)),
312            None,
313        )))
314        .to_arrow_dtype()
315        .unwrap();
316    }
317
318    #[fixture]
319    fn the_struct() -> StructFields {
320        StructFields::new(
321            FieldNames::from([
322                FieldName::from("field_a"),
323                FieldName::from("field_b"),
324                FieldName::from("field_c"),
325            ]),
326            vec![
327                DType::Bool(Nullability::NonNullable),
328                DType::Utf8(Nullability::NonNullable),
329                DType::Primitive(PType::I32, Nullability::Nullable),
330            ],
331        )
332    }
333
334    #[rstest]
335    fn test_schema_conversion(the_struct: StructFields) {
336        let schema_nonnull = DType::Struct(the_struct, Nullability::NonNullable);
337
338        assert_eq!(
339            schema_nonnull.to_arrow_schema().unwrap(),
340            Schema::new(Fields::from(vec![
341                Field::new("field_a", DataType::Boolean, false),
342                Field::new("field_b", DataType::Utf8View, false),
343                Field::new("field_c", DataType::Int32, true),
344            ]))
345        );
346    }
347
348    #[rstest]
349    #[should_panic]
350    fn test_schema_conversion_panics(the_struct: StructFields) {
351        let schema_null = DType::Struct(the_struct, Nullability::Nullable);
352        let _ = schema_null.to_arrow_schema().unwrap();
353    }
354}