Skip to main content

datafusion_common/types/
native.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5use 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/// Representation of a type that DataFusion can handle natively. It is a subset
18/// of the physical variants in Arrow's native [`DataType`].
19#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
20pub enum NativeType {
21    /// Null type
22    Null,
23    /// A boolean type representing the values `true` and `false`.
24    Boolean,
25    /// A signed 8-bit integer.
26    Int8,
27    /// A signed 16-bit integer.
28    Int16,
29    /// A signed 32-bit integer.
30    Int32,
31    /// A signed 64-bit integer.
32    Int64,
33    /// An unsigned 8-bit integer.
34    UInt8,
35    /// An unsigned 16-bit integer.
36    UInt16,
37    /// An unsigned 32-bit integer.
38    UInt32,
39    /// An unsigned 64-bit integer.
40    UInt64,
41    /// A 16-bit floating point number.
42    Float16,
43    /// A 32-bit floating point number.
44    Float32,
45    /// A 64-bit floating point number.
46    Float64,
47    /// A timestamp with an optional timezone.
48    ///
49    /// Time is measured as a Unix epoch, counting the seconds from
50    /// 00:00:00.000 on 1 January 1970, excluding leap seconds,
51    /// as a signed 64-bit integer.
52    ///
53    /// The time zone is a string indicating the name of a time zone, one of:
54    ///
55    /// * As used in the Olson time zone database (the "tz database" or
56    ///   "tzdata"), such as "America/New_York"
57    /// * An absolute time zone offset of the form +XX:XX or -XX:XX, such as +07:30
58    ///
59    /// Timestamps with a non-empty timezone
60    /// ------------------------------------
61    ///
62    /// If a Timestamp column has a non-empty timezone value, its epoch is
63    /// 1970-01-01 00:00:00 (January 1st 1970, midnight) in the *UTC* timezone
64    /// (the Unix epoch), regardless of the Timestamp's own timezone.
65    ///
66    /// Therefore, timestamp values with a non-empty timezone correspond to
67    /// physical points in time together with some additional information about
68    /// how the data was obtained and/or how to display it (the timezone).
69    ///
70    ///   For example, the timestamp value 0 with the timezone string "Europe/Paris"
71    ///   corresponds to "January 1st 1970, 00h00" in the UTC timezone, but the
72    ///   application may prefer to display it as "January 1st 1970, 01h00" in
73    ///   the Europe/Paris timezone (which is the same physical point in time).
74    ///
75    /// One consequence is that timestamp values with a non-empty timezone
76    /// can be compared and ordered directly, since they all share the same
77    /// well-known point of reference (the Unix epoch).
78    ///
79    /// Timestamps with an unset / empty timezone
80    /// -----------------------------------------
81    ///
82    /// If a Timestamp column has no timezone value, its epoch is
83    /// 1970-01-01 00:00:00 (January 1st 1970, midnight) in an *unknown* timezone.
84    ///
85    /// Therefore, timestamp values without a timezone cannot be meaningfully
86    /// interpreted as physical points in time, but only as calendar / clock
87    /// indications ("wall clock time") in an unspecified timezone.
88    ///
89    ///   For example, the timestamp value 0 with an empty timezone string
90    ///   corresponds to "January 1st 1970, 00h00" in an unknown timezone: there
91    ///   is not enough information to interpret it as a well-defined physical
92    ///   point in time.
93    ///
94    /// One consequence is that timestamp values without a timezone cannot
95    /// be reliably compared or ordered, since they may have different points of
96    /// reference.  In particular, it is *not* possible to interpret an unset
97    /// or empty timezone as the same as "UTC".
98    ///
99    /// Conversion between timezones
100    /// ----------------------------
101    ///
102    /// If a Timestamp column has a non-empty timezone, changing the timezone
103    /// to a different non-empty value is a metadata-only operation:
104    /// the timestamp values need not change as their point of reference remains
105    /// the same (the Unix epoch).
106    ///
107    /// However, if a Timestamp column has no timezone value, changing it to a
108    /// non-empty value requires to think about the desired semantics.
109    /// One possibility is to assume that the original timestamp values are
110    /// relative to the epoch of the timezone being set; timestamp values should
111    /// then adjusted to the Unix epoch (for example, changing the timezone from
112    /// empty to "Europe/Paris" would require converting the timestamp values
113    /// from "Europe/Paris" to "UTC", which seems counter-intuitive but is
114    /// nevertheless correct).
115    ///
116    /// ```
117    /// # use arrow::datatypes::{DataType, TimeUnit};
118    /// DataType::Timestamp(TimeUnit::Second, None);
119    /// DataType::Timestamp(TimeUnit::Second, Some("literal".into()));
120    /// DataType::Timestamp(TimeUnit::Second, Some("string".to_string().into()));
121    /// ```
122    Timestamp(TimeUnit, Option<Arc<str>>),
123    /// A signed date representing the elapsed time since UNIX epoch (1970-01-01)
124    /// in days.
125    Date,
126    /// A signed time representing the elapsed time since midnight in the unit of `TimeUnit`.
127    Time(TimeUnit),
128    /// Measure of elapsed time in either seconds, milliseconds, microseconds or nanoseconds.
129    Duration(TimeUnit),
130    /// A "calendar" interval which models types that don't necessarily
131    /// have a precise duration without the context of a base timestamp (e.g.
132    /// days can differ in length during day light savings time transitions).
133    Interval(IntervalUnit),
134    /// Opaque binary data of variable length.
135    Binary,
136    /// Opaque binary data of fixed size.
137    /// Enum parameter specifies the number of bytes per value.
138    FixedSizeBinary(i32),
139    /// A variable-length string in Unicode with UTF-8 encoding.
140    String,
141    /// A list of some logical data type with variable length.
142    List(LogicalFieldRef),
143    /// A list of some logical data type with fixed length.
144    FixedSizeList(LogicalFieldRef, i32),
145    /// A nested type that contains a number of sub-fields.
146    Struct(LogicalFields),
147    /// A nested type that can represent slots of differing types.
148    Union(LogicalUnionFields),
149    /// Decimal value with precision and scale
150    ///
151    /// * precision is the total number of digits
152    /// * scale is the number of digits past the decimal
153    ///
154    /// For example the number 123.45 has precision 5 and scale 2.
155    ///
156    /// In certain situations, scale could be negative number. For
157    /// negative scale, it is the number of padding 0 to the right
158    /// of the digits.
159    ///
160    /// For example the number 12300 could be treated as a decimal
161    /// has precision 3 and scale -2.
162    Decimal(u8, i8),
163    /// A Map is a type that an association between a key and a value.
164    ///
165    /// The key and value types are not constrained, but keys should be
166    /// hashable and unique.
167    ///
168    /// In a field with Map type, key type and the second the value type. The names of the
169    /// child fields may be respectively "entries", "key", and "value", but this is
170    /// not enforced.
171    Map(LogicalFieldRef),
172}
173
174/// Format a [`LogicalField`] for display, matching [`arrow::datatypes::DataType`]'s
175/// Display convention of showing a `"non-null "` prefix for non-nullable fields.
176fn 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 the format used by arrow::datatypes::DataType's Display impl
187        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    /// Returns the default casted type for the given arrow type
263    ///
264    /// For types like String or Date, multiple arrow types mapped to the same logical type
265    /// If the given arrow type is one of them, we return the same type
266    /// Otherwise, we define the default casted type for the given arrow type
267    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            // If given type is Date, return the same type
304            (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            // We don't cast to another kind of binary type if the origin one is already a binary type
315            (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            // We don't cast to another kind of string type if the origin one is already a string type
327            (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            // List array where each element is a len 1 list of the origin type
346            (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            // FixedSizeList array where each element is a len 1 list of the origin type
365            (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            // From https://github.com/apache/arrow-rs/blob/56525efbd5f37b89d1b56aa51709cab9f81bc89e/arrow-cast/src/cast/mod.rs#L189-L196
374            (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            // There is no mode to preserve with null origin, so pick dense encoding
423            (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
450// The following From<DataType>, From<Field>, ... implementations are temporary
451// mapping solutions to provide backwards compatibility while transitioning from
452// the purely physical system to a logical / physical system.
453
454impl 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        // Native types with several physical types: pick a canonical one
656        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        // Decimals pick the narrowest physical type holding the precision
674        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        // nested types
700        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                // The logical `String` field resolves to its canonical type
718                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        // From a `Null` origin there are only type ids, but no mode or string
737        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        // From a union origin both the mode and the encodings are preserved
751        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}