1use std::sync::Arc;
19
20use arrow_schema::DataType;
21use arrow_schema::Field;
22use arrow_schema::FieldRef;
23use arrow_schema::Fields;
24use arrow_schema::TimeUnit as ArrowTimeUnit;
25use vortex_array::dtype::DType;
26use vortex_array::dtype::DecimalDType;
27use vortex_array::dtype::FieldName;
28use vortex_array::dtype::Nullability;
29use vortex_array::dtype::PType;
30use vortex_array::dtype::StructFields;
31use vortex_array::extension::datetime::AnyTemporal;
32use vortex_array::extension::datetime::Date;
33use vortex_array::extension::datetime::Duration;
34use vortex_array::extension::datetime::TemporalMetadata;
35use vortex_array::extension::datetime::Time;
36use vortex_array::extension::datetime::TimeUnit;
37use vortex_array::extension::datetime::Timestamp;
38use vortex_error::VortexResult;
39use vortex_error::vortex_bail;
40use vortex_error::vortex_ensure;
41use vortex_error::vortex_ensure_eq;
42use vortex_error::vortex_err;
43use vortex_error::vortex_panic;
44
45pub(crate) fn from_arrow_time_unit(value: ArrowTimeUnit) -> TimeUnit {
47 match value {
48 ArrowTimeUnit::Second => TimeUnit::Seconds,
49 ArrowTimeUnit::Millisecond => TimeUnit::Milliseconds,
50 ArrowTimeUnit::Microsecond => TimeUnit::Microseconds,
51 ArrowTimeUnit::Nanosecond => TimeUnit::Nanoseconds,
52 }
53}
54
55pub(crate) fn to_arrow_time_unit(value: TimeUnit) -> VortexResult<ArrowTimeUnit> {
61 Ok(match value {
62 TimeUnit::Seconds => ArrowTimeUnit::Second,
63 TimeUnit::Milliseconds => ArrowTimeUnit::Millisecond,
64 TimeUnit::Microseconds => ArrowTimeUnit::Microsecond,
65 TimeUnit::Nanoseconds => ArrowTimeUnit::Nanosecond,
66 _ => vortex_bail!("Cannot convert {value} to Arrow TimeUnit"),
67 })
68}
69
70pub(crate) fn ptype_from_arrow(value: &DataType) -> VortexResult<PType> {
72 match value {
73 DataType::Int8 => Ok(PType::I8),
74 DataType::Int16 => Ok(PType::I16),
75 DataType::Int32 => Ok(PType::I32),
76 DataType::Int64 => Ok(PType::I64),
77 DataType::UInt8 => Ok(PType::U8),
78 DataType::UInt16 => Ok(PType::U16),
79 DataType::UInt32 => Ok(PType::U32),
80 DataType::UInt64 => Ok(PType::U64),
81 DataType::Float16 => Ok(PType::F16),
82 DataType::Float32 => Ok(PType::F32),
83 DataType::Float64 => Ok(PType::F64),
84 _ => Err(vortex_err!(
85 "Arrow datatype {:?} cannot be converted to ptype",
86 value
87 )),
88 }
89}
90
91pub(crate) fn from_arrow_data_type(
94 data_type: &DataType,
95 nullability: Nullability,
96) -> VortexResult<DType> {
97 if data_type.is_integer() || data_type.is_floating() {
98 return Ok(DType::Primitive(ptype_from_arrow(data_type)?, nullability));
99 }
100
101 Ok(match data_type {
102 DataType::Null => DType::Null,
103 DataType::Decimal32(precision, scale)
104 | DataType::Decimal64(precision, scale)
105 | DataType::Decimal128(precision, scale)
106 | DataType::Decimal256(precision, scale) => {
107 DType::Decimal(DecimalDType::try_new(*precision, *scale)?, nullability)
108 }
109 DataType::Boolean => DType::Bool(nullability),
110 DataType::Utf8 | DataType::LargeUtf8 | DataType::Utf8View => DType::Utf8(nullability),
111 DataType::Binary | DataType::LargeBinary | DataType::BinaryView => {
112 DType::Binary(nullability)
113 }
114 DataType::Date32 => DType::Extension(Date::new(TimeUnit::Days, nullability).erased()),
115 DataType::Date64 => {
116 DType::Extension(Date::new(TimeUnit::Milliseconds, nullability).erased())
117 }
118 DataType::Time32(unit) => {
119 DType::Extension(Time::new(from_arrow_time_unit(*unit), nullability).erased())
120 }
121 DataType::Time64(unit) => {
122 DType::Extension(Time::new(from_arrow_time_unit(*unit), nullability).erased())
123 }
124 DataType::Timestamp(unit, tz) => DType::Extension(
125 Timestamp::try_new_with_tz(from_arrow_time_unit(*unit), tz.clone(), nullability)?
126 .erased(),
127 ),
128 DataType::Duration(unit) => {
129 DType::Extension(Duration::new(from_arrow_time_unit(*unit), nullability).erased())
130 }
131 DataType::List(e)
132 | DataType::LargeList(e)
133 | DataType::ListView(e)
134 | DataType::LargeListView(e) => {
135 DType::List(Arc::new(from_arrow_field_naive(e.as_ref())?), nullability)
136 }
137 DataType::FixedSizeList(e, size) => DType::FixedSizeList(
138 Arc::new(from_arrow_field_naive(e.as_ref())?),
139 *size as u32,
140 nullability,
141 ),
142 DataType::Struct(f) => DType::Struct(from_arrow_fields_naive(f)?, nullability),
143 DataType::Map(entries, keys_sorted) => {
144 vortex_ensure!(
145 !entries.is_nullable(),
146 "Arrow map entries field must be non-nullable"
147 );
148 let DataType::Struct(fields) = entries.data_type() else {
149 vortex_bail!(
150 "Arrow map entries field must have Struct type, got {:?}",
151 entries.data_type()
152 );
153 };
154 vortex_ensure_eq!(
155 fields.len(),
156 2,
157 "Arrow map entries struct must contain exactly two fields"
158 );
159 let key = &fields[0];
160 let value = &fields[1];
161 vortex_ensure!(
162 !key.is_nullable(),
163 "Arrow map key field must be non-nullable"
164 );
165 DType::map(
166 from_arrow_field_naive(key.as_ref())?,
167 from_arrow_field_naive(value.as_ref())?,
168 *keys_sorted,
169 nullability,
170 )?
171 }
172 DataType::Dictionary(_, value_type) => {
173 from_arrow_data_type(value_type.as_ref(), nullability)?
174 }
175 DataType::RunEndEncoded(_, value_type) => {
176 from_arrow_data_type(value_type.data_type(), nullability)?
177 }
178 _ => vortex_bail!("Arrow data type not supported: {data_type:?}"),
179 })
180}
181
182pub(crate) fn from_arrow_field_naive(field: &Field) -> VortexResult<DType> {
185 if field
186 .metadata()
187 .get("ARROW:extension:name")
188 .map(|s| s.as_str())
189 == Some("arrow.parquet.variant")
190 {
191 return Ok(DType::Variant(field.is_nullable().into()));
192 }
193 from_arrow_data_type(field.data_type(), field.is_nullable().into())
194}
195
196pub(crate) fn from_arrow_fields_naive(fields: &Fields) -> VortexResult<StructFields> {
198 fields
199 .into_iter()
200 .map(|f| {
201 Ok((
202 FieldName::from(f.name().as_str()),
203 from_arrow_field_naive(f.as_ref())?,
204 ))
205 })
206 .collect::<VortexResult<StructFields>>()
207}
208
209pub(crate) fn to_data_type_naive(dtype: &DType) -> VortexResult<DataType> {
211 Ok(match dtype {
212 DType::Null => DataType::Null,
213 DType::Bool(_) => DataType::Boolean,
214 DType::Primitive(ptype, _) => match ptype {
215 PType::U8 => DataType::UInt8,
216 PType::U16 => DataType::UInt16,
217 PType::U32 => DataType::UInt32,
218 PType::U64 => DataType::UInt64,
219 PType::I8 => DataType::Int8,
220 PType::I16 => DataType::Int16,
221 PType::I32 => DataType::Int32,
222 PType::I64 => DataType::Int64,
223 PType::F16 => DataType::Float16,
224 PType::F32 => DataType::Float32,
225 PType::F64 => DataType::Float64,
226 },
227 DType::Decimal(dt, _) => {
228 let precision = dt.precision();
229 let scale = dt.scale();
230
231 match precision {
232 0..=38 => DataType::Decimal128(precision, scale),
239 39.. => DataType::Decimal256(precision, scale),
241 }
242 }
243 DType::Utf8(_) => DataType::Utf8View,
244 DType::Binary(_) => DataType::BinaryView,
245 DType::List(elem_dtype, _) => DataType::List(FieldRef::new(Field::new_list_field(
249 to_data_type_naive(elem_dtype)?,
250 elem_dtype.nullability().into(),
251 ))),
252 DType::FixedSizeList(elem_dtype, size, _) => DataType::FixedSizeList(
253 FieldRef::new(Field::new_list_field(
254 to_data_type_naive(elem_dtype)?,
255 elem_dtype.nullability().into(),
256 )),
257 *size as i32,
258 ),
259 DType::Map(map_dtype, _) => {
260 let key = Field::new("key", to_data_type_naive(&map_dtype.key_dtype())?, false);
261 let value_dtype = map_dtype.value_dtype();
262 let value = Field::new(
263 "value",
264 to_data_type_naive(&value_dtype)?,
265 value_dtype.is_nullable(),
266 );
267 let entries = Field::new_struct("entries", Fields::from(vec![key, value]), false);
268 DataType::Map(FieldRef::new(entries), map_dtype.keys_sorted())
269 }
270 DType::Struct(struct_dtype, _) => {
271 let mut fields = Vec::with_capacity(struct_dtype.names().len());
272 for (field_name, field_dt) in struct_dtype.names().iter().zip(struct_dtype.fields()) {
273 fields.push(FieldRef::from(Field::new(
274 field_name.as_ref(),
275 to_data_type_naive(&field_dt)?,
276 field_dt.is_nullable(),
277 )));
278 }
279
280 DataType::Struct(Fields::from(fields))
281 }
282 DType::Union(..) => vortex_bail!("TODO(connor)[Union]: unimplemented"),
283 DType::Variant(_) => vortex_bail!(
284 "DType::Variant requires Arrow Field metadata; use to_arrow_schema or a Field helper"
285 ),
286 DType::Extension(ext_dtype) => {
287 if let Some(temporal) = ext_dtype.metadata_opt::<AnyTemporal>() {
292 return Ok(match temporal {
293 TemporalMetadata::Timestamp(unit, tz) => {
294 DataType::Timestamp(to_arrow_time_unit(*unit)?, tz.clone())
295 }
296 TemporalMetadata::Date(unit) => match unit {
297 TimeUnit::Days => DataType::Date32,
298 TimeUnit::Milliseconds => DataType::Date64,
299 TimeUnit::Nanoseconds | TimeUnit::Microseconds | TimeUnit::Seconds => {
300 vortex_panic!("Invalid TimeUnit {} for {}", unit, ext_dtype.id())
301 }
302 },
303 TemporalMetadata::Time(unit) => match unit {
304 TimeUnit::Seconds => DataType::Time32(ArrowTimeUnit::Second),
305 TimeUnit::Milliseconds => DataType::Time32(ArrowTimeUnit::Millisecond),
306 TimeUnit::Microseconds => DataType::Time64(ArrowTimeUnit::Microsecond),
307 TimeUnit::Nanoseconds => DataType::Time64(ArrowTimeUnit::Nanosecond),
308 TimeUnit::Days => {
309 vortex_panic!("Invalid TimeUnit {} for {}", unit, ext_dtype.id())
310 }
311 },
312 TemporalMetadata::Duration(unit) => {
313 DataType::Duration(to_arrow_time_unit(*unit)?)
314 }
315 });
316 };
317
318 vortex_bail!("Unsupported extension type \"{}\"", ext_dtype.id())
319 }
320 })
321}
322
323#[cfg(test)]
324mod test {
325 use arrow_schema::DataType;
326 use arrow_schema::Field;
327 use arrow_schema::FieldRef;
328 use arrow_schema::Fields;
329 use arrow_schema::Schema;
330 use rstest::fixture;
331 use rstest::rstest;
332 use vortex_array::dtype::DType;
333 use vortex_array::dtype::FieldName;
334 use vortex_array::dtype::FieldNames;
335 use vortex_array::dtype::Nullability;
336 use vortex_array::dtype::PType;
337 use vortex_array::dtype::StructFields;
338 use vortex_session::VortexSession;
339
340 use super::*;
341 use crate::ArrowSessionExt;
342
343 #[test]
344 fn test_dtype_conversion_success() {
345 assert_eq!(to_data_type_naive(&DType::Null).unwrap(), DataType::Null);
346
347 assert_eq!(
348 to_data_type_naive(&DType::Bool(Nullability::NonNullable)).unwrap(),
349 DataType::Boolean
350 );
351
352 assert_eq!(
353 to_data_type_naive(&DType::Primitive(PType::U64, Nullability::NonNullable)).unwrap(),
354 DataType::UInt64
355 );
356
357 assert_eq!(
358 to_data_type_naive(&DType::Utf8(Nullability::NonNullable)).unwrap(),
359 DataType::Utf8View
360 );
361
362 assert_eq!(
363 to_data_type_naive(&DType::Binary(Nullability::NonNullable)).unwrap(),
364 DataType::BinaryView
365 );
366
367 assert_eq!(
368 to_data_type_naive(&DType::struct_(
369 [
370 ("field_a", DType::Bool(false.into())),
371 ("field_b", DType::Utf8(true.into()))
372 ],
373 Nullability::NonNullable,
374 ))
375 .unwrap(),
376 DataType::Struct(Fields::from(vec![
377 FieldRef::from(Field::new("field_a", DataType::Boolean, false)),
378 FieldRef::from(Field::new("field_b", DataType::Utf8View, true)),
379 ]))
380 );
381 }
382
383 #[test]
384 fn test_reject_timestamp_invalid_timezone() {
385 let dtype = DataType::Timestamp(ArrowTimeUnit::Second, Some("Not/A/Timezone".into()));
386 assert!(from_arrow_data_type(&dtype, Nullability::Nullable).is_err());
387 }
388
389 #[rstest]
390 #[case(1, DataType::Decimal128(1, 0))]
391 #[case(38, DataType::Decimal128(38, 0))]
392 #[case(39, DataType::Decimal256(39, 0))]
393 #[case(76, DataType::Decimal256(76, 0))]
394 fn test_decimal_dtype_to_arrow(#[case] precision: u8, #[case] expected: DataType) {
395 use vortex_array::dtype::DecimalDType;
396
397 let dtype = DType::Decimal(DecimalDType::new(precision, 0), Nullability::NonNullable);
398 assert_eq!(to_data_type_naive(&dtype).unwrap(), expected);
399 }
400
401 #[rstest]
402 #[case::decimal32(DataType::Decimal32(1, 2))]
403 #[case::decimal64(DataType::Decimal64(1, 2))]
404 #[case::decimal128(DataType::Decimal128(1, 2))]
405 #[case::decimal256(DataType::Decimal256(1, 2))]
406 #[case::zero_precision(DataType::Decimal128(0, 0))]
407 #[case::excessive_precision(DataType::Decimal256(77, 0))]
408 fn test_malformed_decimal_dtype_from_arrow(#[case] data_type: DataType) {
409 assert!(from_arrow_data_type(&data_type, Nullability::Nullable).is_err());
410 }
411
412 #[test]
413 fn test_variant_dtype_to_arrow_dtype_errors() {
414 let err = to_data_type_naive(&DType::Variant(Nullability::NonNullable))
415 .unwrap_err()
416 .to_string();
417 assert!(err.contains("Variant"));
418 }
419
420 #[test]
421 fn infer_nullable_list_element() {
422 let list_non_nullable = DType::List(
423 Arc::new(DType::Primitive(PType::I64, Nullability::NonNullable)),
424 Nullability::Nullable,
425 );
426
427 let arrow_list_non_nullable = to_data_type_naive(&list_non_nullable).unwrap();
428
429 let list_nullable = DType::List(
430 Arc::new(DType::Primitive(PType::I64, Nullability::Nullable)),
431 Nullability::Nullable,
432 );
433 let arrow_list_nullable = to_data_type_naive(&list_nullable).unwrap();
434
435 assert_ne!(arrow_list_non_nullable, arrow_list_nullable);
436 assert_eq!(
437 arrow_list_nullable,
438 DataType::List(Arc::new(Field::new_list_field(DataType::Int64, true))),
439 );
440 assert_eq!(
441 arrow_list_non_nullable,
442 DataType::List(Arc::new(Field::new_list_field(DataType::Int64, false))),
443 );
444 }
445
446 #[fixture]
447 fn the_struct() -> StructFields {
448 StructFields::new(
449 FieldNames::from([
450 FieldName::from("field_a"),
451 FieldName::from("field_b"),
452 FieldName::from("field_c"),
453 ]),
454 vec![
455 DType::Bool(Nullability::NonNullable),
456 DType::Utf8(Nullability::NonNullable),
457 DType::Primitive(PType::I32, Nullability::Nullable),
458 ],
459 )
460 }
461
462 #[rstest]
463 fn test_schema_conversion(the_struct: StructFields) {
464 let schema_nonnull = DType::Struct(the_struct, Nullability::NonNullable);
465
466 assert_eq!(
467 VortexSession::empty()
468 .arrow()
469 .to_arrow_schema(&schema_nonnull)
470 .unwrap(),
471 Schema::new(Fields::from(vec![
472 Field::new("field_a", DataType::Boolean, false),
473 Field::new("field_b", DataType::Utf8View, false),
474 Field::new("field_c", DataType::Int32, true),
475 ]))
476 );
477 }
478
479 #[test]
480 fn test_unicode_field_names_roundtrip() {
481 let unicode_field_name = "\u{5}=A";
486 let original_dtype = DType::struct_(
487 [(
488 unicode_field_name,
489 DType::Primitive(PType::I8, Nullability::Nullable),
490 )],
491 Nullability::NonNullable,
492 );
493
494 let arrow_dtype = to_data_type_naive(&original_dtype).unwrap();
495 assert_eq!(
496 arrow_dtype,
497 DataType::Struct(Fields::from(vec![Field::new(
498 "\u{5}=A",
499 DataType::Int8,
500 true
501 )]))
502 );
503 let roundtripped_dtype =
504 from_arrow_data_type(&arrow_dtype, Nullability::NonNullable).unwrap();
505
506 assert_eq!(original_dtype, roundtripped_dtype);
507 }
508
509 #[test]
510 fn test_unicode_field_names_nested_roundtrip() {
511 let inner_struct = DType::struct_(
515 [(
516 "\u{6}=inner",
517 DType::Primitive(PType::I32, Nullability::Nullable),
518 )],
519 Nullability::Nullable,
520 );
521 let original_dtype =
522 DType::struct_([("\u{7}=outer", inner_struct)], Nullability::NonNullable);
523
524 let arrow_dtype = to_data_type_naive(&original_dtype).unwrap();
525 assert_eq!(
526 arrow_dtype,
527 DataType::Struct(Fields::from(vec![Field::new(
528 "\u{7}=outer",
529 DataType::Struct(Fields::from(vec![Field::new(
530 "\u{6}=inner",
531 DataType::Int32,
532 true
533 )])),
534 true
535 )]))
536 );
537 let roundtripped_dtype =
538 from_arrow_data_type(&arrow_dtype, Nullability::NonNullable).unwrap();
539
540 assert_eq!(original_dtype, roundtripped_dtype);
541 }
542
543 #[test]
544 fn map_dtype_roundtrip_uses_conventional_export_names_and_positional_import() -> VortexResult<()>
545 {
546 let dtype = DType::map(
547 DType::Primitive(PType::I32, Nullability::NonNullable),
548 DType::Utf8(Nullability::Nullable),
549 true,
550 Nullability::Nullable,
551 )?;
552
553 let arrow = to_data_type_naive(&dtype)?;
554 let DataType::Map(entries, keys_sorted) = &arrow else {
555 panic!("expected Map, got {arrow:?}");
556 };
557 assert!(*keys_sorted);
558 assert_eq!(entries.name(), "entries");
559 assert!(!entries.is_nullable());
560 let DataType::Struct(fields) = entries.data_type() else {
561 panic!("expected map entries to be a struct");
562 };
563 assert_eq!(fields[0].name(), "key");
564 assert!(!fields[0].is_nullable());
565 assert_eq!(fields[1].name(), "value");
566 assert!(fields[1].is_nullable());
567 assert_eq!(from_arrow_data_type(&arrow, Nullability::Nullable)?, dtype);
568
569 let positional = DataType::Map(
570 Arc::new(Field::new_struct(
571 "anything",
572 Fields::from(vec![
573 Field::new("first", DataType::Int32, false),
574 Field::new("second", DataType::Utf8, true),
575 ]),
576 false,
577 )),
578 false,
579 );
580 assert_eq!(
581 from_arrow_data_type(&positional, Nullability::NonNullable)?,
582 DType::map(
583 DType::Primitive(PType::I32, Nullability::NonNullable),
584 DType::Utf8(Nullability::Nullable),
585 false,
586 Nullability::NonNullable,
587 )?
588 );
589
590 Ok(())
591 }
592
593 #[test]
594 fn map_dtype_import_rejects_invalid_arrow_shape() {
595 let invalid_entries = [
596 Field::new_struct(
597 "entries",
598 Fields::from(vec![
599 Field::new("key", DataType::Int32, false),
600 Field::new("value", DataType::Utf8, true),
601 ]),
602 true,
603 ),
604 Field::new("entries", DataType::Int32, false),
605 Field::new_struct(
606 "entries",
607 Fields::from(vec![Field::new("key", DataType::Int32, false)]),
608 false,
609 ),
610 Field::new_struct(
611 "entries",
612 Fields::from(vec![
613 Field::new("key", DataType::Int32, true),
614 Field::new("value", DataType::Utf8, true),
615 ]),
616 false,
617 ),
618 ];
619
620 for entries in invalid_entries {
621 let data_type = DataType::Map(Arc::new(entries), false);
622 assert!(from_arrow_data_type(&data_type, Nullability::NonNullable).is_err());
623 }
624 }
625
626 #[rstest]
629 #[case::interval(DataType::Interval(arrow_schema::IntervalUnit::DayTime))]
630 #[case::fixed_size_binary(DataType::FixedSizeBinary(3))]
631 fn test_try_from_arrow_unsupported_type_errors(#[case] data_type: DataType) {
632 let err = from_arrow_data_type(&data_type, Nullability::NonNullable)
633 .expect_err("unsupported Arrow type should not convert")
634 .to_string();
635 assert!(err.contains("not supported"), "unexpected error: {err}");
636
637 let field = Field::new("c0", data_type, true);
639 assert!(from_arrow_field_naive(&field).is_err());
640 let schema = Schema::new(vec![field]);
641 assert!(
642 VortexSession::empty()
643 .arrow()
644 .from_arrow_schema(&schema)
645 .is_err()
646 );
647 }
648
649 #[test]
650 fn test_try_from_arrow_supported_type_succeeds() -> VortexResult<()> {
651 let dtype = from_arrow_data_type(&DataType::Int32, Nullability::Nullable)?;
652 assert_eq!(dtype, DType::Primitive(PType::I32, Nullability::Nullable));
653 Ok(())
654 }
655}