1use super::{
6 LogicalField, LogicalFieldRef, LogicalFields, LogicalType, LogicalUnionFields,
7 TypeSignature,
8};
9use crate::error::{_internal_err, Result};
10use arrow::compute::can_cast_types;
11use arrow::datatypes::{
12 DECIMAL32_MAX_PRECISION, DECIMAL64_MAX_PRECISION, DECIMAL128_MAX_PRECISION, DataType,
13 Field, FieldRef, Fields, IntervalUnit, TimeUnit, UnionFields, UnionMode,
14};
15use std::{fmt::Display, sync::Arc};
16
17#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
20pub enum NativeType {
21 Null,
23 Boolean,
25 Int8,
27 Int16,
29 Int32,
31 Int64,
33 UInt8,
35 UInt16,
37 UInt32,
39 UInt64,
41 Float16,
43 Float32,
45 Float64,
47 Timestamp(TimeUnit, Option<Arc<str>>),
123 Date,
126 Time(TimeUnit),
128 Duration(TimeUnit),
130 Interval(IntervalUnit),
134 Binary,
136 FixedSizeBinary(i32),
139 String,
141 List(LogicalFieldRef),
143 FixedSizeList(LogicalFieldRef, i32),
145 Struct(LogicalFields),
147 Union(LogicalUnionFields),
149 Decimal(u8, i8),
163 Map(LogicalFieldRef),
172}
173
174fn format_logical_field(
177 f: &mut std::fmt::Formatter<'_>,
178 field: &LogicalField,
179) -> std::fmt::Result {
180 let non_null = if field.nullable { "" } else { "non-null " };
181 write!(f, "{:?}: {non_null}{}", field.name, field.logical_type)
182}
183
184impl Display for NativeType {
185 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
186 match self {
188 Self::Null => write!(f, "Null"),
189 Self::Boolean => write!(f, "Boolean"),
190 Self::Int8 => write!(f, "Int8"),
191 Self::Int16 => write!(f, "Int16"),
192 Self::Int32 => write!(f, "Int32"),
193 Self::Int64 => write!(f, "Int64"),
194 Self::UInt8 => write!(f, "UInt8"),
195 Self::UInt16 => write!(f, "UInt16"),
196 Self::UInt32 => write!(f, "UInt32"),
197 Self::UInt64 => write!(f, "UInt64"),
198 Self::Float16 => write!(f, "Float16"),
199 Self::Float32 => write!(f, "Float32"),
200 Self::Float64 => write!(f, "Float64"),
201 Self::Timestamp(unit, Some(tz)) => write!(f, "Timestamp({unit}, {tz:?})"),
202 Self::Timestamp(unit, None) => write!(f, "Timestamp({unit})"),
203 Self::Date => write!(f, "Date"),
204 Self::Time(unit) => write!(f, "Time({unit})"),
205 Self::Duration(unit) => write!(f, "Duration({unit})"),
206 Self::Interval(unit) => write!(f, "Interval({unit:?})"),
207 Self::Binary => write!(f, "Binary"),
208 Self::FixedSizeBinary(size) => write!(f, "FixedSizeBinary({size})"),
209 Self::String => write!(f, "String"),
210 Self::List(field) => {
211 let non_null = if field.nullable { "" } else { "non-null " };
212 write!(f, "List({non_null}{})", field.logical_type)
213 }
214 Self::FixedSizeList(field, size) => {
215 let non_null = if field.nullable { "" } else { "non-null " };
216 write!(
217 f,
218 "FixedSizeList({size} x {non_null}{})",
219 field.logical_type
220 )
221 }
222 Self::Struct(fields) => {
223 write!(f, "Struct(")?;
224 for (i, field) in fields.iter().enumerate() {
225 if i > 0 {
226 write!(f, ", ")?;
227 }
228 format_logical_field(f, field)?;
229 }
230 write!(f, ")")
231 }
232 Self::Union(fields) => {
233 write!(f, "Union(")?;
234 for (i, (type_id, field)) in fields.iter().enumerate() {
235 if i > 0 {
236 write!(f, ", ")?;
237 }
238 write!(f, "{type_id}: (")?;
239 format_logical_field(f, field)?;
240 write!(f, ")")?;
241 }
242 write!(f, ")")
243 }
244 Self::Decimal(precision, scale) => write!(f, "Decimal({precision}, {scale})"),
245 Self::Map(field) => {
246 let non_null = if field.nullable { "" } else { "non-null " };
247 write!(f, "Map({non_null}{})", field.logical_type)
248 }
249 }
250 }
251}
252
253impl LogicalType for NativeType {
254 fn native(&self) -> &NativeType {
255 self
256 }
257
258 fn signature(&self) -> TypeSignature<'_> {
259 TypeSignature::Native(self)
260 }
261
262 fn default_cast_for(&self, origin: &DataType) -> Result<DataType> {
268 use DataType::*;
269
270 fn default_field_cast(to: &LogicalField, from: &Field) -> Result<FieldRef> {
271 Ok(Arc::new(Field::new(
272 to.name.clone(),
273 to.logical_type.default_cast_for(from.data_type())?,
274 to.nullable,
275 )))
276 }
277
278 Ok(match (self, origin) {
279 (Self::Null, _) => Null,
280 (Self::Boolean, _) => Boolean,
281 (Self::Int8, _) => Int8,
282 (Self::Int16, _) => Int16,
283 (Self::Int32, _) => Int32,
284 (Self::Int64, _) => Int64,
285 (Self::UInt8, _) => UInt8,
286 (Self::UInt16, _) => UInt16,
287 (Self::UInt32, _) => UInt32,
288 (Self::UInt64, _) => UInt64,
289 (Self::Float16, _) => Float16,
290 (Self::Float32, _) => Float32,
291 (Self::Float64, _) => Float64,
292 (Self::Decimal(p, s), _) if *p <= DECIMAL32_MAX_PRECISION => {
293 Decimal32(*p, *s)
294 }
295 (Self::Decimal(p, s), _) if *p <= DECIMAL64_MAX_PRECISION => {
296 Decimal64(*p, *s)
297 }
298 (Self::Decimal(p, s), _) if *p <= DECIMAL128_MAX_PRECISION => {
299 Decimal128(*p, *s)
300 }
301 (Self::Decimal(p, s), _) => Decimal256(*p, *s),
302 (Self::Timestamp(tu, tz), _) => Timestamp(*tu, tz.clone()),
303 (Self::Date, Date32 | Date64) => origin.to_owned(),
305 (Self::Date, _) => Date32,
306 (Self::Time(tu), _) => match tu {
307 TimeUnit::Second | TimeUnit::Millisecond => Time32(*tu),
308 TimeUnit::Microsecond | TimeUnit::Nanosecond => Time64(*tu),
309 },
310 (Self::Duration(tu), _) => Duration(*tu),
311 (Self::Interval(iu), _) => Interval(*iu),
312 (Self::Binary, LargeUtf8) => LargeBinary,
313 (Self::Binary, Utf8View) => BinaryView,
314 (Self::Binary, Binary | LargeBinary | BinaryView) => origin.to_owned(),
316 (Self::Binary, data_type) if can_cast_types(data_type, &BinaryView) => {
317 BinaryView
318 }
319 (Self::Binary, data_type) if can_cast_types(data_type, &LargeBinary) => {
320 LargeBinary
321 }
322 (Self::Binary, data_type) if can_cast_types(data_type, &Binary) => Binary,
323 (Self::FixedSizeBinary(size), _) => FixedSizeBinary(*size),
324 (Self::String, LargeBinary) => LargeUtf8,
325 (Self::String, BinaryView) => Utf8View,
326 (Self::String, Utf8 | LargeUtf8 | Utf8View) => origin.to_owned(),
328 (Self::String, data_type) if can_cast_types(data_type, &Utf8View) => Utf8View,
329 (Self::String, data_type) if can_cast_types(data_type, &LargeUtf8) => {
330 LargeUtf8
331 }
332 (Self::String, data_type) if can_cast_types(data_type, &Utf8) => Utf8,
333 (Self::List(to_field), List(from_field) | FixedSizeList(from_field, _)) => {
334 List(default_field_cast(to_field, from_field)?)
335 }
336 (Self::List(to_field), LargeList(from_field)) => {
337 LargeList(default_field_cast(to_field, from_field)?)
338 }
339 (Self::List(to_field), ListView(from_field)) => {
340 ListView(default_field_cast(to_field, from_field)?)
341 }
342 (Self::List(to_field), LargeListView(from_field)) => {
343 LargeListView(default_field_cast(to_field, from_field)?)
344 }
345 (Self::List(field), _) => List(Arc::new(Field::new(
347 field.name.clone(),
348 field.logical_type.default_cast_for(origin)?,
349 field.nullable,
350 ))),
351 (
352 Self::FixedSizeList(to_field, to_size),
353 FixedSizeList(from_field, from_size),
354 ) if from_size == to_size => {
355 FixedSizeList(default_field_cast(to_field, from_field)?, *to_size)
356 }
357 (
358 Self::FixedSizeList(to_field, size),
359 List(from_field)
360 | LargeList(from_field)
361 | ListView(from_field)
362 | LargeListView(from_field),
363 ) => FixedSizeList(default_field_cast(to_field, from_field)?, *size),
364 (Self::FixedSizeList(field, size), _) => FixedSizeList(
366 Arc::new(Field::new(
367 field.name.clone(),
368 field.logical_type.default_cast_for(origin)?,
369 field.nullable,
370 )),
371 *size,
372 ),
373 (Self::Struct(to_fields), Struct(from_fields))
375 if from_fields.len() == to_fields.len() =>
376 {
377 Struct(
378 from_fields
379 .iter()
380 .zip(to_fields.iter())
381 .map(|(from, to)| default_field_cast(to, from))
382 .collect::<Result<Fields>>()?,
383 )
384 }
385 (Self::Struct(to_fields), Null) => Struct(
386 to_fields
387 .iter()
388 .map(|field| {
389 Ok(Arc::new(Field::new(
390 field.name.clone(),
391 field.logical_type.default_cast_for(&Null)?,
392 field.nullable,
393 )))
394 })
395 .collect::<Result<Fields>>()?,
396 ),
397 (Self::Map(to_field), Map(from_field, sorted)) => {
398 Map(default_field_cast(to_field, from_field)?, *sorted)
399 }
400 (Self::Map(field), Null) => Map(
401 Arc::new(Field::new(
402 field.name.clone(),
403 field.logical_type.default_cast_for(&Null)?,
404 field.nullable,
405 )),
406 false,
407 ),
408 (Self::Union(to_fields), Union(from_fields, mode))
409 if from_fields.len() == to_fields.len() =>
410 {
411 Union(
412 from_fields
413 .iter()
414 .zip(to_fields.iter())
415 .map(|((_, from), (i, to))| {
416 Ok((*i, default_field_cast(to, from)?))
417 })
418 .collect::<Result<UnionFields>>()?,
419 *mode,
420 )
421 }
422 (Self::Union(to_fields), Null) => Union(
424 to_fields
425 .iter()
426 .map(|(type_id, field)| {
427 Ok((
428 *type_id,
429 Arc::new(Field::new(
430 field.name.clone(),
431 field.logical_type.default_cast_for(&Null)?,
432 field.nullable,
433 )),
434 ))
435 })
436 .collect::<Result<UnionFields>>()?,
437 UnionMode::Dense,
438 ),
439 _ => {
440 return _internal_err!(
441 "Unavailable default cast for native type {} from physical type {}",
442 self,
443 origin
444 );
445 }
446 })
447 }
448}
449
450impl From<&DataType> for NativeType {
455 fn from(value: &DataType) -> Self {
456 value.clone().into()
457 }
458}
459
460impl From<DataType> for NativeType {
461 fn from(value: DataType) -> Self {
462 use NativeType::*;
463 match value {
464 DataType::Null => Null,
465 DataType::Boolean => Boolean,
466 DataType::Int8 => Int8,
467 DataType::Int16 => Int16,
468 DataType::Int32 => Int32,
469 DataType::Int64 => Int64,
470 DataType::UInt8 => UInt8,
471 DataType::UInt16 => UInt16,
472 DataType::UInt32 => UInt32,
473 DataType::UInt64 => UInt64,
474 DataType::Float16 => Float16,
475 DataType::Float32 => Float32,
476 DataType::Float64 => Float64,
477 DataType::Timestamp(tu, tz) => Timestamp(tu, tz),
478 DataType::Date32 | DataType::Date64 => Date,
479 DataType::Time32(tu) | DataType::Time64(tu) => Time(tu),
480 DataType::Duration(tu) => Duration(tu),
481 DataType::Interval(iu) => Interval(iu),
482 DataType::Binary | DataType::LargeBinary | DataType::BinaryView => Binary,
483 DataType::FixedSizeBinary(size) => FixedSizeBinary(size),
484 DataType::Utf8 | DataType::LargeUtf8 | DataType::Utf8View => String,
485 DataType::List(field)
486 | DataType::ListView(field)
487 | DataType::LargeList(field)
488 | DataType::LargeListView(field) => List(Arc::new(field.as_ref().into())),
489 DataType::FixedSizeList(field, size) => {
490 FixedSizeList(Arc::new(field.as_ref().into()), size)
491 }
492 DataType::Struct(fields) => Struct(LogicalFields::from(&fields)),
493 DataType::Union(union_fields, _) => {
494 Union(LogicalUnionFields::from(&union_fields))
495 }
496 DataType::Decimal32(p, s)
497 | DataType::Decimal64(p, s)
498 | DataType::Decimal128(p, s)
499 | DataType::Decimal256(p, s) => Decimal(p, s),
500 DataType::Map(field, _) => Map(Arc::new(field.as_ref().into())),
501 DataType::Dictionary(_, data_type) => data_type.as_ref().clone().into(),
502 DataType::RunEndEncoded(_, field) => field.data_type().clone().into(),
503 }
504 }
505}
506
507impl NativeType {
508 #[inline]
509 pub fn is_numeric(&self) -> bool {
510 self.is_integer() || self.is_float() || self.is_decimal()
511 }
512
513 #[inline]
514 pub fn is_integer(&self) -> bool {
515 use NativeType::*;
516 matches!(
517 self,
518 UInt8 | UInt16 | UInt32 | UInt64 | Int8 | Int16 | Int32 | Int64
519 )
520 }
521
522 #[inline]
523 pub fn is_timestamp(&self) -> bool {
524 matches!(self, NativeType::Timestamp(_, _))
525 }
526
527 #[inline]
528 pub fn is_date(&self) -> bool {
529 *self == NativeType::Date
530 }
531
532 #[inline]
533 pub fn is_time(&self) -> bool {
534 matches!(self, NativeType::Time(_))
535 }
536
537 #[inline]
538 pub fn is_interval(&self) -> bool {
539 matches!(self, NativeType::Interval(_))
540 }
541
542 #[inline]
543 pub fn is_duration(&self) -> bool {
544 matches!(self, NativeType::Duration(_))
545 }
546
547 #[inline]
548 pub fn is_binary(&self) -> bool {
549 matches!(self, NativeType::Binary | NativeType::FixedSizeBinary(_))
550 }
551
552 #[inline]
553 pub fn is_null(&self) -> bool {
554 *self == NativeType::Null
555 }
556
557 #[inline]
558 pub fn is_decimal(&self) -> bool {
559 matches!(self, Self::Decimal(_, _))
560 }
561
562 #[inline]
563 pub fn is_float(&self) -> bool {
564 matches!(self, Self::Float16 | Self::Float32 | Self::Float64)
565 }
566}
567
568#[cfg(test)]
569mod tests {
570 use super::*;
571 use crate::types::LogicalField;
572 use insta::assert_snapshot;
573
574 #[test]
575 fn test_native_type_display() {
576 assert_snapshot!(NativeType::Null, @"Null");
577 assert_snapshot!(NativeType::Boolean, @"Boolean");
578 assert_snapshot!(NativeType::Int8, @"Int8");
579 assert_snapshot!(NativeType::Int16, @"Int16");
580 assert_snapshot!(NativeType::Int32, @"Int32");
581 assert_snapshot!(NativeType::Int64, @"Int64");
582 assert_snapshot!(NativeType::UInt8, @"UInt8");
583 assert_snapshot!(NativeType::UInt16, @"UInt16");
584 assert_snapshot!(NativeType::UInt32, @"UInt32");
585 assert_snapshot!(NativeType::UInt64, @"UInt64");
586 assert_snapshot!(NativeType::Float16, @"Float16");
587 assert_snapshot!(NativeType::Float32, @"Float32");
588 assert_snapshot!(NativeType::Float64, @"Float64");
589 assert_snapshot!(NativeType::Date, @"Date");
590 assert_snapshot!(NativeType::Binary, @"Binary");
591 assert_snapshot!(NativeType::String, @"String");
592 assert_snapshot!(NativeType::FixedSizeBinary(16), @"FixedSizeBinary(16)");
593 assert_snapshot!(NativeType::Decimal(10, 2), @"Decimal(10, 2)");
594 }
595
596 #[test]
597 fn test_native_type_display_timestamp() {
598 assert_snapshot!(
599 NativeType::Timestamp(TimeUnit::Second, None),
600 @"Timestamp(s)"
601 );
602 assert_snapshot!(
603 NativeType::Timestamp(TimeUnit::Millisecond, None),
604 @"Timestamp(ms)"
605 );
606 assert_snapshot!(
607 NativeType::Timestamp(TimeUnit::Nanosecond, Some(Arc::from("UTC"))),
608 @r#"Timestamp(ns, "UTC")"#
609 );
610 }
611
612 #[test]
613 fn test_native_type_display_time_duration_interval() {
614 assert_snapshot!(NativeType::Time(TimeUnit::Microsecond), @"Time(µs)");
615 assert_snapshot!(NativeType::Duration(TimeUnit::Nanosecond), @"Duration(ns)");
616 assert_snapshot!(NativeType::Interval(IntervalUnit::YearMonth), @"Interval(YearMonth)");
617 assert_snapshot!(NativeType::Interval(IntervalUnit::MonthDayNano), @"Interval(MonthDayNano)");
618 }
619
620 #[test]
621 fn test_native_type_display_nested() {
622 let list = NativeType::List(Arc::new(LogicalField::from(&Field::new(
623 "item",
624 DataType::Int32,
625 true,
626 ))));
627 assert_snapshot!(list, @"List(Int32)");
628
629 let fixed_list = NativeType::FixedSizeList(
630 Arc::new(LogicalField::from(&Field::new(
631 "item",
632 DataType::Float64,
633 false,
634 ))),
635 3,
636 );
637 assert_snapshot!(fixed_list, @"FixedSizeList(3 x non-null Float64)");
638
639 let struct_type = NativeType::Struct(LogicalFields::from(&Fields::from(vec![
640 Field::new("name", DataType::Utf8, false),
641 Field::new("age", DataType::Int32, true),
642 ])));
643 assert_snapshot!(struct_type, @r#"Struct("name": non-null String, "age": Int32)"#);
644
645 let map = NativeType::Map(Arc::new(LogicalField::from(&Field::new(
646 "entries",
647 DataType::Utf8,
648 false,
649 ))));
650 assert_snapshot!(map, @"Map(non-null String)");
651 }
652
653 #[test]
654 fn test_default_cast_for_null_origin() {
655 assert_eq!(
657 NativeType::String
658 .default_cast_for(&DataType::Null)
659 .unwrap(),
660 DataType::Utf8View
661 );
662 assert_eq!(
663 NativeType::Binary
664 .default_cast_for(&DataType::Null)
665 .unwrap(),
666 DataType::BinaryView
667 );
668 assert_eq!(
669 NativeType::Date.default_cast_for(&DataType::Null).unwrap(),
670 DataType::Date32
671 );
672
673 assert_eq!(
675 NativeType::Decimal(9, 2)
676 .default_cast_for(&DataType::Null)
677 .unwrap(),
678 DataType::Decimal32(9, 2)
679 );
680 assert_eq!(
681 NativeType::Decimal(18, 2)
682 .default_cast_for(&DataType::Null)
683 .unwrap(),
684 DataType::Decimal64(18, 2)
685 );
686 assert_eq!(
687 NativeType::Decimal(38, 10)
688 .default_cast_for(&DataType::Null)
689 .unwrap(),
690 DataType::Decimal128(38, 10)
691 );
692 assert_eq!(
693 NativeType::Decimal(50, 2)
694 .default_cast_for(&DataType::Null)
695 .unwrap(),
696 DataType::Decimal256(50, 2)
697 );
698
699 let list = NativeType::List(Arc::new(LogicalField::from(&Field::new(
701 "item",
702 DataType::Int32,
703 true,
704 ))));
705 assert_eq!(
706 list.default_cast_for(&DataType::Null).unwrap(),
707 DataType::List(Arc::new(Field::new("item", DataType::Int32, true)))
708 );
709
710 let struct_type = NativeType::Struct(LogicalFields::from(&Fields::from(vec![
711 Field::new("name", DataType::Utf8, false),
712 Field::new("age", DataType::Int32, true),
713 ])));
714 assert_eq!(
715 struct_type.default_cast_for(&DataType::Null).unwrap(),
716 DataType::Struct(Fields::from(vec![
717 Field::new("name", DataType::Utf8View, false),
719 Field::new("age", DataType::Int32, true),
720 ]))
721 );
722 }
723
724 #[test]
725 fn test_default_cast_for_union() {
726 let origin_fields = UnionFields::try_new(
727 vec![3, 7],
728 vec![
729 Field::new("a", DataType::Int32, true),
730 Field::new("b", DataType::Utf8, false),
731 ],
732 )
733 .unwrap();
734 let union_type = NativeType::Union(LogicalUnionFields::from(&origin_fields));
735
736 let expected_fields = UnionFields::try_new(
738 vec![3, 7],
739 vec![
740 Field::new("a", DataType::Int32, true),
741 Field::new("b", DataType::Utf8View, false),
742 ],
743 )
744 .unwrap();
745 assert_eq!(
746 union_type.default_cast_for(&DataType::Null).unwrap(),
747 DataType::Union(expected_fields, UnionMode::Dense)
748 );
749
750 assert_eq!(
752 union_type
753 .default_cast_for(&DataType::Union(
754 origin_fields.clone(),
755 UnionMode::Sparse
756 ))
757 .unwrap(),
758 DataType::Union(origin_fields, UnionMode::Sparse)
759 );
760 }
761}