arrow_schema/datatype.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 std::str::FromStr;
6use std::sync::Arc;
7
8use crate::{ArrowError, Field, FieldRef, Fields, UnionFields};
9
10/// Datatypes supported by this implementation of Apache Arrow.
11///
12/// The variants of this enum include primitive fixed size types as well as
13/// parametric or nested types. See [`Schema.fbs`] for Arrow's specification.
14///
15/// # Examples
16///
17/// Primitive types
18/// ```
19/// # use arrow_schema::DataType;
20/// // create a new 32-bit signed integer
21/// let data_type = DataType::Int32;
22/// ```
23///
24/// Nested Types
25/// ```
26/// # use arrow_schema::{DataType, Field};
27/// # use std::sync::Arc;
28/// // create a new list of 32-bit signed integers directly
29/// let list_data_type = DataType::List(Arc::new(Field::new_list_field(DataType::Int32, true)));
30/// // Create the same list type with constructor
31/// let list_data_type2 = DataType::new_list(DataType::Int32, true);
32/// assert_eq!(list_data_type, list_data_type2);
33/// ```
34///
35/// Dictionary Types
36/// ```
37/// # use arrow_schema::{DataType};
38/// // String Dictionary (key type Int32 and value type Utf8)
39/// let data_type = DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8));
40/// ```
41///
42/// Timestamp Types
43/// ```
44/// # use arrow_schema::{DataType, TimeUnit};
45/// // timestamp with millisecond precision without timezone specified
46/// let data_type = DataType::Timestamp(TimeUnit::Millisecond, None);
47/// // timestamp with nanosecond precision in UTC timezone
48/// let data_type = DataType::Timestamp(TimeUnit::Nanosecond, Some("UTC".into()));
49///```
50///
51/// # Display and FromStr
52///
53/// The `Display` and `FromStr` implementations for `DataType` are
54/// human-readable, parseable, and reversible.
55///
56/// ```
57/// # use arrow_schema::DataType;
58/// let data_type = DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8));
59/// let data_type_string = data_type.to_string();
60/// assert_eq!(data_type_string, "Dictionary(Int32, Utf8)");
61/// // display can be parsed back into the original type
62/// let parsed_data_type: DataType = data_type.to_string().parse().unwrap();
63/// assert_eq!(data_type, parsed_data_type);
64/// ```
65///
66/// # Nested Support
67/// Currently, the Rust implementation supports the following nested types:
68/// - `List<T>`
69/// - `LargeList<T>`
70/// - `FixedSizeList<T>`
71/// - `Struct<T, U, V, ...>`
72/// - `Union<T, U, V, ...>`
73/// - `Map<K, V>`
74///
75/// Nested types can themselves be nested within other arrays.
76/// For more information on these types please see
77/// [the physical memory layout of Apache Arrow]
78///
79/// [`Schema.fbs`]: https://github.com/apache/arrow/blob/main/format/Schema.fbs
80/// [the physical memory layout of Apache Arrow]: https://arrow.apache.org/docs/format/Columnar.html#physical-memory-layout
81#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
82#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
83pub enum DataType {
84 /// Null type
85 Null,
86 /// A boolean datatype representing the values `true` and `false`.
87 Boolean,
88 /// A signed 8-bit integer.
89 Int8,
90 /// A signed 16-bit integer.
91 Int16,
92 /// A signed 32-bit integer.
93 Int32,
94 /// A signed 64-bit integer.
95 Int64,
96 /// An unsigned 8-bit integer.
97 UInt8,
98 /// An unsigned 16-bit integer.
99 UInt16,
100 /// An unsigned 32-bit integer.
101 UInt32,
102 /// An unsigned 64-bit integer.
103 UInt64,
104 /// A 16-bit floating point number.
105 Float16,
106 /// A 32-bit floating point number.
107 Float32,
108 /// A 64-bit floating point number.
109 Float64,
110 /// A timestamp with an optional timezone.
111 ///
112 /// Time is measured as a Unix epoch, counting the seconds from
113 /// 00:00:00.000 on 1 January 1970, excluding leap seconds,
114 /// as a signed 64-bit integer.
115 ///
116 /// The time zone is a string indicating the name of a time zone, one of:
117 ///
118 /// * As used in the Olson time zone database (the "tz database" or
119 /// "tzdata"), such as "America/New_York"
120 /// * An absolute time zone offset of the form +XX:XX or -XX:XX, such as +07:30
121 ///
122 /// Timestamps with a non-empty timezone
123 /// ------------------------------------
124 ///
125 /// If a Timestamp column has a non-empty timezone value, its epoch is
126 /// 1970-01-01 00:00:00 (January 1st 1970, midnight) in the *UTC* timezone
127 /// (the Unix epoch), regardless of the Timestamp's own timezone.
128 ///
129 /// Therefore, timestamp values with a non-empty timezone correspond to
130 /// physical points in time together with some additional information about
131 /// how the data was obtained and/or how to display it (the timezone).
132 ///
133 /// For example, the timestamp value 0 with the timezone string "Europe/Paris"
134 /// corresponds to "January 1st 1970, 00h00" in the UTC timezone, but the
135 /// application may prefer to display it as "January 1st 1970, 01h00" in
136 /// the Europe/Paris timezone (which is the same physical point in time).
137 ///
138 /// One consequence is that timestamp values with a non-empty timezone
139 /// can be compared and ordered directly, since they all share the same
140 /// well-known point of reference (the Unix epoch).
141 ///
142 /// Timestamps with an unset / empty timezone
143 /// -----------------------------------------
144 ///
145 /// If a Timestamp column has no timezone value, its epoch is
146 /// 1970-01-01 00:00:00 (January 1st 1970, midnight) in an *unknown* timezone.
147 ///
148 /// Therefore, timestamp values without a timezone cannot be meaningfully
149 /// interpreted as physical points in time, but only as calendar / clock
150 /// indications ("wall clock time") in an unspecified timezone.
151 ///
152 /// For example, the timestamp value 0 with an empty timezone string
153 /// corresponds to "January 1st 1970, 00h00" in an unknown timezone: there
154 /// is not enough information to interpret it as a well-defined physical
155 /// point in time.
156 ///
157 /// One consequence is that timestamp values without a timezone cannot
158 /// be reliably compared or ordered, since they may have different points of
159 /// reference. In particular, it is *not* possible to interpret an unset
160 /// or empty timezone as the same as "UTC".
161 ///
162 /// Conversion between timezones
163 /// ----------------------------
164 ///
165 /// If a Timestamp column has a non-empty timezone, changing the timezone
166 /// to a different non-empty value is a metadata-only operation:
167 /// the timestamp values need not change as their point of reference remains
168 /// the same (the Unix epoch).
169 ///
170 /// However, if a Timestamp column has no timezone value, changing it to a
171 /// non-empty value requires to think about the desired semantics.
172 /// One possibility is to assume that the original timestamp values are
173 /// relative to the epoch of the timezone being set; timestamp values should
174 /// then adjusted to the Unix epoch (for example, changing the timezone from
175 /// empty to "Europe/Paris" would require converting the timestamp values
176 /// from "Europe/Paris" to "UTC", which seems counter-intuitive but is
177 /// nevertheless correct).
178 ///
179 /// ```
180 /// # use arrow_schema::{DataType, TimeUnit};
181 /// DataType::Timestamp(TimeUnit::Second, None);
182 /// DataType::Timestamp(TimeUnit::Second, Some("literal".into()));
183 /// DataType::Timestamp(TimeUnit::Second, Some("string".to_string().into()));
184 /// ```
185 ///
186 /// # Timezone representation
187 /// ----------------------------
188 /// It is possible to use either the timezone string representation, such as "UTC", or the absolute time zone offset "+00:00".
189 /// For timezones with fixed offsets, such as "UTC" or "JST", the offset representation is recommended, as it is more explicit and less ambiguous.
190 ///
191 /// Most arrow-rs functionalities use the absolute offset representation,
192 /// such as [`PrimitiveArray::with_timezone_utc`] that applies a
193 /// UTC timezone to timestamp arrays.
194 ///
195 /// [`PrimitiveArray::with_timezone_utc`]: https://docs.rs/arrow/latest/arrow/array/struct.PrimitiveArray.html#method.with_timezone_utc
196 ///
197 /// Timezone string parsing
198 /// -----------------------
199 /// When neither feature `chrono-tz` nor `jiff` is enabled, allowed timezone strings are fixed offsets of the form "+09:00", "-09" or "+0930".
200 ///
201 /// When feature `chrono-tz` is enabled, additional strings supported by [chrono_tz](https://docs.rs/chrono-tz/latest/chrono_tz/)
202 /// are also allowed, which include [IANA database](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones)
203 /// timezones.
204 ///
205 /// When feature `jiff` is enabled, the same strings are allowed, and named timezones are resolved
206 /// with [jiff](https://docs.rs/jiff/latest/jiff/) instead. `jiff` takes precedence over `chrono-tz`.
207 Timestamp(TimeUnit, Option<Arc<str>>),
208 /// A signed 32-bit date representing the elapsed time since UNIX epoch (1970-01-01)
209 /// in days.
210 Date32,
211 /// A signed 64-bit date representing the elapsed time since UNIX epoch (1970-01-01)
212 /// in milliseconds.
213 ///
214 /// # Valid Ranges
215 ///
216 /// According to the Arrow specification ([Schema.fbs]), values of Date64
217 /// are treated as the number of *days*, in milliseconds, since the UNIX
218 /// epoch. Therefore, values of this type must be evenly divisible by
219 /// `86_400_000`, the number of milliseconds in a standard day.
220 ///
221 /// It is not valid to store milliseconds that do not represent an exact
222 /// day. The reason for this restriction is compatibility with other
223 /// language's native libraries (specifically Java), which historically
224 /// lacked a dedicated date type and only supported timestamps.
225 ///
226 /// # Validation
227 ///
228 /// This library does not validate or enforce that Date64 values are evenly
229 /// divisible by `86_400_000` for performance and usability reasons. Date64
230 /// values are treated similarly to `Timestamp(TimeUnit::Millisecond,
231 /// None)`: values will be displayed with a time of day if the value does
232 /// not represent an exact day, and arithmetic will be done at the
233 /// millisecond granularity.
234 ///
235 /// # Recommendation
236 ///
237 /// Users should prefer [`Date32`] to cleanly represent the number
238 /// of days, or one of the Timestamp variants to include time as part of the
239 /// representation, depending on their use case.
240 ///
241 /// # Further Reading
242 ///
243 /// For more details, see [#5288](https://github.com/apache/arrow-rs/issues/5288).
244 ///
245 /// [`Date32`]: Self::Date32
246 /// [Schema.fbs]: https://github.com/apache/arrow/blob/main/format/Schema.fbs
247 Date64,
248 /// A signed 32-bit time representing the elapsed time since midnight in the unit of `TimeUnit`.
249 /// Must be either seconds or milliseconds.
250 Time32(TimeUnit),
251 /// A signed 64-bit time representing the elapsed time since midnight in the unit of `TimeUnit`.
252 /// Must be either microseconds or nanoseconds.
253 Time64(TimeUnit),
254 /// Measure of elapsed time in either seconds, milliseconds, microseconds or nanoseconds.
255 Duration(TimeUnit),
256 /// A "calendar" interval which models types that don't necessarily
257 /// have a precise duration without the context of a base timestamp (e.g.
258 /// days can differ in length during day light savings time transitions).
259 Interval(IntervalUnit),
260 /// Opaque binary data of variable length.
261 ///
262 /// A single Binary array can store up to [`i32::MAX`] bytes
263 /// of binary data in total.
264 Binary,
265 /// Opaque binary data of fixed size.
266 ///
267 /// Enum parameter specifies the number of bytes per value, defined by the
268 /// [`byteWidth` field] in the Arrow Spec
269 ///
270 /// [`byteWidth` field]: https://github.com/apache/arrow/blob/2a89d03bbefd620b42126b8e00f8ae57e99cd638/format/Schema.fbs#L211
271 FixedSizeBinary(i32),
272 /// Opaque binary data of variable length and 64-bit offsets.
273 ///
274 /// A single LargeBinary array can store up to [`i64::MAX`] bytes
275 /// of binary data in total.
276 LargeBinary,
277 /// Opaque binary data of variable length.
278 ///
279 /// Logically the same as [`Binary`], but the internal representation uses a view
280 /// struct that contains the string length and either the string's entire data
281 /// inline (for small strings) or an inlined prefix, an index of another buffer,
282 /// and an offset pointing to a slice in that buffer (for non-small strings).
283 ///
284 /// [`Binary`]: Self::Binary
285 BinaryView,
286 /// A variable-length string in Unicode with UTF-8 encoding.
287 ///
288 /// A single Utf8 array can store up to [`i32::MAX`] bytes
289 /// of string data in total.
290 Utf8,
291 /// A variable-length string in Unicode with UFT-8 encoding and 64-bit offsets.
292 ///
293 /// A single LargeUtf8 array can store up to [`i64::MAX`] bytes
294 /// of string data in total.
295 LargeUtf8,
296 /// A variable-length string in Unicode with UTF-8 encoding
297 ///
298 /// Logically the same as [`Utf8`], but the internal representation uses a view
299 /// struct that contains the string length and either the string's entire data
300 /// inline (for small strings) or an inlined prefix, an index of another buffer,
301 /// and an offset pointing to a slice in that buffer (for non-small strings).
302 ///
303 /// [`Utf8`]: Self::Utf8
304 Utf8View,
305 /// A list of some logical data type with variable length.
306 ///
307 /// A single List array can store up to [`i32::MAX`] elements in total.
308 List(FieldRef),
309 /// A list of some logical data type with variable length.
310 ///
311 /// Logically the same as [`List`], but the internal representation differs in how child
312 /// data is referenced, allowing flexibility in how data is laid out.
313 ///
314 /// [`List`]: Self::List
315 ListView(FieldRef),
316 /// A list of some logical data type with fixed length.
317 FixedSizeList(FieldRef, i32),
318 /// A list of some logical data type with variable length and 64-bit offsets.
319 ///
320 /// A single LargeList array can store up to [`i64::MAX`] elements in total.
321 LargeList(FieldRef),
322 /// A list of some logical data type with variable length and 64-bit offsets.
323 ///
324 /// Logically the same as [`LargeList`], but the internal representation differs in how child
325 /// data is referenced, allowing flexibility in how data is laid out.
326 ///
327 /// [`LargeList`]: Self::LargeList
328 LargeListView(FieldRef),
329 /// A nested datatype that contains a number of sub-fields.
330 Struct(Fields),
331 /// A nested datatype that can represent slots of differing types. Components:
332 ///
333 /// 1. [`UnionFields`]
334 /// 2. The type of union (Sparse or Dense)
335 Union(UnionFields, UnionMode),
336 /// A dictionary encoded array (`key_type`, `value_type`), where
337 /// each array element is an index of `key_type` into an
338 /// associated dictionary of `value_type`.
339 ///
340 /// Dictionary arrays are used to store columns of `value_type`
341 /// that contain many repeated values using less memory, but with
342 /// a higher CPU overhead for some operations.
343 ///
344 /// This type mostly used to represent low cardinality string
345 /// arrays or a limited set of primitive types as integers.
346 Dictionary(Box<DataType>, Box<DataType>),
347 /// Exact 32-bit width decimal value with precision and scale
348 ///
349 /// * precision is the maximum number of digits in the unscaled value
350 /// * scale controls the position of the decimal point
351 ///
352 /// The represented value is the unscaled integer multiplied by 10^{-scale}.
353 /// For example, the unscaled value 12345 with precision 5 and scale 2
354 /// represents 123.45.
355 ///
356 /// Scale can also be negative. For example, the unscaled value 12 with
357 /// precision 2 and scale -3 represents 12000.
358 Decimal32(u8, i8),
359 /// Exact 64-bit width decimal value with precision and scale
360 ///
361 /// * precision is the maximum number of digits in the unscaled value
362 /// * scale controls the position of the decimal point
363 ///
364 /// The represented value is the unscaled integer multiplied by 10^{-scale}.
365 /// For example, the unscaled value 12345 with precision 5 and scale 2
366 /// represents 123.45.
367 ///
368 /// Scale can also be negative. For example, the unscaled value 12 with
369 /// precision 2 and scale -3 represents 12000.
370 Decimal64(u8, i8),
371 /// Exact 128-bit width decimal value with precision and scale
372 ///
373 /// * precision is the maximum number of digits in the unscaled value
374 /// * scale controls the position of the decimal point
375 ///
376 /// The represented value is the unscaled integer multiplied by 10^{-scale}.
377 /// For example, the unscaled value 12345 with precision 5 and scale 2
378 /// represents 123.45.
379 ///
380 /// Scale can also be negative. For example, the unscaled value 12 with
381 /// precision 2 and scale -3 represents 12000.
382 Decimal128(u8, i8),
383 /// Exact 256-bit width decimal value with precision and scale
384 ///
385 /// * precision is the maximum number of digits in the unscaled value
386 /// * scale controls the position of the decimal point
387 ///
388 /// The represented value is the unscaled integer multiplied by 10^{-scale}.
389 /// For example, the unscaled value 12345 with precision 5 and scale 2
390 /// represents 123.45.
391 ///
392 /// Scale can also be negative. For example, the unscaled value 12 with
393 /// precision 2 and scale -3 represents 12000.
394 Decimal256(u8, i8),
395 /// A Map is a logical nested type that is represented as
396 ///
397 /// `List<entries: Struct<key: K, value: V>>`
398 ///
399 /// The keys and values are each respectively contiguous.
400 /// The key and value types are not constrained, but keys should be
401 /// hashable and unique.
402 /// Whether the keys are sorted can be set in the `bool` after the `Field`.
403 ///
404 /// In a field with Map type, the field has a child Struct field, which then
405 /// has two children: key type and the second the value type. The names of the
406 /// child fields may be respectively "entries", "key", and "value", but this is
407 /// not enforced.
408 ///
409 /// # Requirements
410 /// - The entries [`Field`] (first argument) must be non-nullable.
411 /// - The entries field must be a [`DataType::Struct`] with exactly 2 children.
412 /// - The first child (key) must be non-nullable.
413 Map(FieldRef, bool),
414 /// A run-end encoding (REE) is a variation of run-length encoding (RLE). These
415 /// encodings are well-suited for representing data containing sequences of the
416 /// same value, called runs. Each run is represented as a value and an integer giving
417 /// the index in the array where the run ends.
418 ///
419 /// A run-end encoded array has no buffers by itself, but has two child arrays. The
420 /// first child array, called the run ends array, holds either 16, 32, or 64-bit
421 /// signed integers. The actual values of each run are held in the second child array.
422 ///
423 /// These child arrays are prescribed the standard names of "run_ends" and "values"
424 /// respectively.
425 ///
426 /// # Requirements
427 /// - The run_ends [`Field`] (first argument) must be non-nullable and of type
428 /// [`DataType::Int16`], [`DataType::Int32`], or [`DataType::Int64`].
429 RunEndEncoded(FieldRef, FieldRef),
430}
431
432/// An absolute length of time in seconds, milliseconds, microseconds or nanoseconds.
433#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
434#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
435pub enum TimeUnit {
436 /// Time in seconds.
437 Second,
438 /// Time in milliseconds.
439 Millisecond,
440 /// Time in microseconds.
441 Microsecond,
442 /// Time in nanoseconds.
443 Nanosecond,
444}
445
446impl std::fmt::Display for TimeUnit {
447 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
448 match self {
449 TimeUnit::Second => write!(f, "s"),
450 TimeUnit::Millisecond => write!(f, "ms"),
451 TimeUnit::Microsecond => write!(f, "µs"),
452 TimeUnit::Nanosecond => write!(f, "ns"),
453 }
454 }
455}
456
457/// YEAR_MONTH, DAY_TIME, MONTH_DAY_NANO interval in SQL style.
458#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
459#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
460pub enum IntervalUnit {
461 /// Indicates the number of elapsed whole months, stored as 4-byte integers.
462 YearMonth,
463 /// Indicates the number of elapsed days and milliseconds,
464 /// stored as 2 contiguous 32-bit integers (days, milliseconds) (8-bytes in total).
465 DayTime,
466 /// A triple of the number of elapsed months, days, and nanoseconds.
467 /// The values are stored contiguously in 16 byte blocks. Months and
468 /// days are encoded as 32 bit integers and nanoseconds is encoded as a
469 /// 64 bit integer. All integers are signed. Each field is independent
470 /// (e.g. there is no constraint that nanoseconds have the same sign
471 /// as days or that the quantity of nanoseconds represents less
472 /// than a day's worth of time).
473 MonthDayNano,
474}
475
476/// Sparse or Dense union layouts
477#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Copy)]
478#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
479pub enum UnionMode {
480 /// Sparse union layout
481 Sparse,
482 /// Dense union layout
483 Dense,
484}
485
486/// Parses `str` into a `DataType`.
487///
488/// This is the reverse of [`DataType`]'s `Display`
489/// impl, and maintains the invariant that
490/// `DataType::try_from(&data_type.to_string()).unwrap() == data_type`
491///
492/// # Example
493/// ```
494/// use arrow_schema::DataType;
495///
496/// let data_type: DataType = "Int32".parse().unwrap();
497/// assert_eq!(data_type, DataType::Int32);
498/// ```
499impl FromStr for DataType {
500 type Err = ArrowError;
501
502 fn from_str(s: &str) -> Result<Self, Self::Err> {
503 crate::datatype_parse::parse_data_type(s)
504 }
505}
506
507impl TryFrom<&str> for DataType {
508 type Error = ArrowError;
509
510 fn try_from(value: &str) -> Result<Self, Self::Error> {
511 value.parse()
512 }
513}
514
515impl DataType {
516 /// Returns true if the type is primitive: (numeric, temporal).
517 #[inline]
518 pub fn is_primitive(&self) -> bool {
519 self.is_numeric() || self.is_temporal()
520 }
521
522 /// Returns true if this type is numeric: (UInt*, Int*, Float*, Decimal*).
523 #[inline]
524 pub fn is_numeric(&self) -> bool {
525 use DataType::*;
526 matches!(
527 self,
528 UInt8
529 | UInt16
530 | UInt32
531 | UInt64
532 | Int8
533 | Int16
534 | Int32
535 | Int64
536 | Float16
537 | Float32
538 | Float64
539 | Decimal32(_, _)
540 | Decimal64(_, _)
541 | Decimal128(_, _)
542 | Decimal256(_, _)
543 )
544 }
545
546 /// Returns true if this type is temporal: (Date*, Time*, Duration, or Interval).
547 #[inline]
548 pub fn is_temporal(&self) -> bool {
549 use DataType::*;
550 matches!(
551 self,
552 Date32 | Date64 | Timestamp(_, _) | Time32(_) | Time64(_) | Duration(_) | Interval(_)
553 )
554 }
555
556 /// Returns true if this type is floating: (Float*).
557 #[inline]
558 pub fn is_floating(&self) -> bool {
559 use DataType::*;
560 matches!(self, Float16 | Float32 | Float64)
561 }
562
563 /// Returns true if this type is integer: (Int*, UInt*).
564 #[inline]
565 pub fn is_integer(&self) -> bool {
566 self.is_signed_integer() || self.is_unsigned_integer()
567 }
568
569 /// Returns true if this type is signed integer: (Int*).
570 #[inline]
571 pub fn is_signed_integer(&self) -> bool {
572 use DataType::*;
573 matches!(self, Int8 | Int16 | Int32 | Int64)
574 }
575
576 /// Returns true if this type is unsigned integer: (UInt*).
577 #[inline]
578 pub fn is_unsigned_integer(&self) -> bool {
579 use DataType::*;
580 matches!(self, UInt8 | UInt16 | UInt32 | UInt64)
581 }
582
583 /// Returns true if this type is decimal: (Decimal*).
584 #[inline]
585 pub fn is_decimal(&self) -> bool {
586 use DataType::*;
587 matches!(
588 self,
589 Decimal32(..) | Decimal64(..) | Decimal128(..) | Decimal256(..)
590 )
591 }
592
593 /// Returns true if this type is valid as a dictionary key
594 #[inline]
595 pub fn is_dictionary_key_type(&self) -> bool {
596 self.is_integer()
597 }
598
599 /// Returns true if this type is valid for run-ends array in RunArray
600 #[inline]
601 pub fn is_run_ends_type(&self) -> bool {
602 use DataType::*;
603 matches!(self, Int16 | Int32 | Int64)
604 }
605
606 /// Returns true if this type is nested (List, FixedSizeList, LargeList, ListView. LargeListView, Struct, Union,
607 /// or Map), or a dictionary of a nested type
608 #[inline]
609 pub fn is_nested(&self) -> bool {
610 use DataType::*;
611 match self {
612 Dictionary(_, v) => DataType::is_nested(v.as_ref()),
613 RunEndEncoded(_, v) => DataType::is_nested(v.data_type()),
614 List(_)
615 | FixedSizeList(_, _)
616 | LargeList(_)
617 | ListView(_)
618 | LargeListView(_)
619 | Struct(_)
620 | Union(_, _)
621 | Map(_, _) => true,
622 _ => false,
623 }
624 }
625
626 /// Returns true if this type is DataType::Null.
627 #[inline]
628 pub fn is_null(&self) -> bool {
629 use DataType::*;
630 matches!(self, Null)
631 }
632
633 /// Returns true if this type is a String type
634 #[inline]
635 pub fn is_string(&self) -> bool {
636 use DataType::*;
637 matches!(self, Utf8 | LargeUtf8 | Utf8View)
638 }
639
640 /// Returns true if this type is a List type.
641 ///
642 /// List types include List, LargeList, FixedSizeList, ListView, and LargeListView.
643 #[inline]
644 pub fn is_list(&self) -> bool {
645 use DataType::*;
646 matches!(
647 self,
648 List(_) | LargeList(_) | FixedSizeList(_, _) | ListView(_) | LargeListView(_)
649 )
650 }
651
652 /// Returns true if this type is a Binary type.
653 ///
654 /// Binary types include Binary, LargeBinary, FixedSizeBinary and BinaryView.
655 #[inline]
656 pub fn is_binary(&self) -> bool {
657 use DataType::*;
658 matches!(self, Binary | LargeBinary | FixedSizeBinary(_) | BinaryView)
659 }
660
661 /// Compares the datatype with another, ignoring nested field names
662 /// and metadata.
663 pub fn equals_datatype(&self, other: &DataType) -> bool {
664 match (&self, other) {
665 (DataType::List(a), DataType::List(b))
666 | (DataType::LargeList(a), DataType::LargeList(b))
667 | (DataType::ListView(a), DataType::ListView(b))
668 | (DataType::LargeListView(a), DataType::LargeListView(b)) => {
669 a.is_nullable() == b.is_nullable() && a.data_type().equals_datatype(b.data_type())
670 }
671 (DataType::FixedSizeList(a, a_size), DataType::FixedSizeList(b, b_size)) => {
672 a_size == b_size
673 && a.is_nullable() == b.is_nullable()
674 && a.data_type().equals_datatype(b.data_type())
675 }
676 (DataType::Struct(a), DataType::Struct(b)) => {
677 a.len() == b.len()
678 && a.iter().zip(b).all(|(a, b)| {
679 a.is_nullable() == b.is_nullable()
680 && a.data_type().equals_datatype(b.data_type())
681 })
682 }
683 (DataType::Map(a_field, a_is_sorted), DataType::Map(b_field, b_is_sorted)) => {
684 a_field.is_nullable() == b_field.is_nullable()
685 && a_field.data_type().equals_datatype(b_field.data_type())
686 && a_is_sorted == b_is_sorted
687 }
688 (DataType::Dictionary(a_key, a_value), DataType::Dictionary(b_key, b_value)) => {
689 a_key.equals_datatype(b_key) && a_value.equals_datatype(b_value)
690 }
691 (
692 DataType::RunEndEncoded(a_run_ends, a_values),
693 DataType::RunEndEncoded(b_run_ends, b_values),
694 ) => {
695 a_run_ends.is_nullable() == b_run_ends.is_nullable()
696 && a_run_ends
697 .data_type()
698 .equals_datatype(b_run_ends.data_type())
699 && a_values.is_nullable() == b_values.is_nullable()
700 && a_values.data_type().equals_datatype(b_values.data_type())
701 }
702 (
703 DataType::Union(a_union_fields, a_union_mode),
704 DataType::Union(b_union_fields, b_union_mode),
705 ) => {
706 a_union_mode == b_union_mode
707 && a_union_fields.len() == b_union_fields.len()
708 && a_union_fields.iter().all(|a| {
709 b_union_fields.iter().any(|b| {
710 a.0 == b.0
711 && a.1.is_nullable() == b.1.is_nullable()
712 && a.1.data_type().equals_datatype(b.1.data_type())
713 })
714 })
715 }
716 _ => self == other,
717 }
718 }
719
720 /// Returns the byte width of this type if it is a primitive type
721 ///
722 /// Returns `None` if not a primitive type
723 #[inline]
724 pub fn primitive_width(&self) -> Option<usize> {
725 match self {
726 DataType::Null => None,
727 DataType::Boolean => None,
728 DataType::Int8 | DataType::UInt8 => Some(1),
729 DataType::Int16 | DataType::UInt16 | DataType::Float16 => Some(2),
730 DataType::Int32 | DataType::UInt32 | DataType::Float32 => Some(4),
731 DataType::Int64 | DataType::UInt64 | DataType::Float64 => Some(8),
732 DataType::Timestamp(_, _) => Some(8),
733 DataType::Date32 | DataType::Time32(_) => Some(4),
734 DataType::Date64 | DataType::Time64(_) => Some(8),
735 DataType::Duration(_) => Some(8),
736 DataType::Interval(IntervalUnit::YearMonth) => Some(4),
737 DataType::Interval(IntervalUnit::DayTime) => Some(8),
738 DataType::Interval(IntervalUnit::MonthDayNano) => Some(16),
739 DataType::Decimal32(_, _) => Some(4),
740 DataType::Decimal64(_, _) => Some(8),
741 DataType::Decimal128(_, _) => Some(16),
742 DataType::Decimal256(_, _) => Some(32),
743 DataType::Utf8 | DataType::LargeUtf8 | DataType::Utf8View => None,
744 DataType::Binary | DataType::LargeBinary | DataType::BinaryView => None,
745 DataType::FixedSizeBinary(_) => None,
746 DataType::List(_)
747 | DataType::ListView(_)
748 | DataType::LargeList(_)
749 | DataType::LargeListView(_)
750 | DataType::Map(_, _) => None,
751 DataType::FixedSizeList(_, _) => None,
752 DataType::Struct(_) => None,
753 DataType::Union(_, _) => None,
754 DataType::Dictionary(_, _) => None,
755 DataType::RunEndEncoded(_, _) => None,
756 }
757 }
758
759 /// Return size of this instance in bytes.
760 ///
761 /// Includes the size of `Self`.
762 pub fn size(&self) -> usize {
763 std::mem::size_of_val(self)
764 + match self {
765 DataType::Null
766 | DataType::Boolean
767 | DataType::Int8
768 | DataType::Int16
769 | DataType::Int32
770 | DataType::Int64
771 | DataType::UInt8
772 | DataType::UInt16
773 | DataType::UInt32
774 | DataType::UInt64
775 | DataType::Float16
776 | DataType::Float32
777 | DataType::Float64
778 | DataType::Date32
779 | DataType::Date64
780 | DataType::Time32(_)
781 | DataType::Time64(_)
782 | DataType::Duration(_)
783 | DataType::Interval(_)
784 | DataType::Binary
785 | DataType::FixedSizeBinary(_)
786 | DataType::LargeBinary
787 | DataType::BinaryView
788 | DataType::Utf8
789 | DataType::LargeUtf8
790 | DataType::Utf8View
791 | DataType::Decimal32(_, _)
792 | DataType::Decimal64(_, _)
793 | DataType::Decimal128(_, _)
794 | DataType::Decimal256(_, _) => 0,
795 DataType::Timestamp(_, s) => s.as_ref().map(|s| s.len()).unwrap_or_default(),
796 DataType::List(field)
797 | DataType::ListView(field)
798 | DataType::FixedSizeList(field, _)
799 | DataType::LargeList(field)
800 | DataType::LargeListView(field)
801 | DataType::Map(field, _) => field.size(),
802 DataType::Struct(fields) => fields.size(),
803 DataType::Union(fields, _) => fields.size(),
804 DataType::Dictionary(dt1, dt2) => dt1.size() + dt2.size(),
805 DataType::RunEndEncoded(run_ends, values) => {
806 run_ends.size() - std::mem::size_of_val(run_ends) + values.size()
807 - std::mem::size_of_val(values)
808 }
809 }
810 }
811
812 /// Check to see if `self` is a superset of `other`
813 ///
814 /// If DataType is a nested type, then it will check to see if the nested type is a superset of the other nested type
815 /// else it will check to see if the DataType is equal to the other DataType
816 pub fn contains(&self, other: &DataType) -> bool {
817 match (self, other) {
818 (DataType::List(f1), DataType::List(f2))
819 | (DataType::LargeList(f1), DataType::LargeList(f2))
820 | (DataType::ListView(f1), DataType::ListView(f2))
821 | (DataType::LargeListView(f1), DataType::LargeListView(f2)) => f1.contains(f2),
822 (DataType::FixedSizeList(f1, s1), DataType::FixedSizeList(f2, s2)) => {
823 s1 == s2 && f1.contains(f2)
824 }
825 (DataType::Map(f1, s1), DataType::Map(f2, s2)) => s1 == s2 && f1.contains(f2),
826 (DataType::Struct(f1), DataType::Struct(f2)) => f1.contains(f2),
827 (DataType::Union(f1, s1), DataType::Union(f2, s2)) => {
828 s1 == s2
829 && f2.iter().all(|(other_id, other_field)| {
830 f1.iter().any(|(self_id, self_field)| {
831 self_id == other_id && self_field.contains(other_field)
832 })
833 })
834 }
835 (DataType::Dictionary(k1, v1), DataType::Dictionary(k2, v2)) => {
836 k1.contains(k2) && v1.contains(v2)
837 }
838 _ => self == other,
839 }
840 }
841
842 /// Create a [`DataType::List`] with elements of the specified type
843 /// and nullability, and conventionally named inner [`Field`] (`"item"`).
844 ///
845 /// To specify field level metadata, construct the inner [`Field`]
846 /// directly via [`Field::new`] or [`Field::new_list_field`].
847 pub fn new_list(data_type: DataType, nullable: bool) -> Self {
848 DataType::List(Arc::new(Field::new_list_field(data_type, nullable)))
849 }
850
851 /// Create a [`DataType::LargeList`] with elements of the specified type
852 /// and nullability, and conventionally named inner [`Field`] (`"item"`).
853 ///
854 /// To specify field level metadata, construct the inner [`Field`]
855 /// directly via [`Field::new`] or [`Field::new_list_field`].
856 pub fn new_large_list(data_type: DataType, nullable: bool) -> Self {
857 DataType::LargeList(Arc::new(Field::new_list_field(data_type, nullable)))
858 }
859
860 /// Create a [`DataType::FixedSizeList`] with elements of the specified type, size
861 /// and nullability, and conventionally named inner [`Field`] (`"item"`).
862 ///
863 /// To specify field level metadata, construct the inner [`Field`]
864 /// directly via [`Field::new`] or [`Field::new_list_field`].
865 pub fn new_fixed_size_list(data_type: DataType, size: i32, nullable: bool) -> Self {
866 DataType::FixedSizeList(Arc::new(Field::new_list_field(data_type, nullable)), size)
867 }
868}
869
870/// The maximum precision for [DataType::Decimal32] values
871pub const DECIMAL32_MAX_PRECISION: u8 = 9;
872
873/// The maximum scale for [DataType::Decimal32] values
874pub const DECIMAL32_MAX_SCALE: i8 = 9;
875
876/// The maximum precision for [DataType::Decimal64] values
877pub const DECIMAL64_MAX_PRECISION: u8 = 18;
878
879/// The maximum scale for [DataType::Decimal64] values
880pub const DECIMAL64_MAX_SCALE: i8 = 18;
881
882/// The maximum precision for [DataType::Decimal128] values
883pub const DECIMAL128_MAX_PRECISION: u8 = 38;
884
885/// The maximum scale for [DataType::Decimal128] values
886pub const DECIMAL128_MAX_SCALE: i8 = 38;
887
888/// The maximum precision for [DataType::Decimal256] values
889pub const DECIMAL256_MAX_PRECISION: u8 = 76;
890
891/// The maximum scale for [DataType::Decimal256] values
892pub const DECIMAL256_MAX_SCALE: i8 = 76;
893
894/// The default scale for [DataType::Decimal32] values
895pub const DECIMAL32_DEFAULT_SCALE: i8 = 2;
896
897/// The default scale for [DataType::Decimal64] values
898pub const DECIMAL64_DEFAULT_SCALE: i8 = 6;
899
900/// The default scale for [DataType::Decimal128] and [DataType::Decimal256]
901/// values
902pub const DECIMAL_DEFAULT_SCALE: i8 = 10;
903
904#[cfg(test)]
905mod tests {
906 use super::*;
907
908 #[test]
909 fn test_union_contains_subset() {
910 for mode in [UnionMode::Sparse, UnionMode::Dense] {
911 let number = Field::new("number", DataType::Int32, false);
912 let text = Field::new("text", DataType::Utf8, false);
913 let superset = DataType::Union(
914 UnionFields::try_new([0, 1], [number.clone(), text.clone()]).unwrap(),
915 mode,
916 );
917 let subset =
918 DataType::Union(UnionFields::try_new([0], [number.clone()]).unwrap(), mode);
919 let reordered =
920 DataType::Union(UnionFields::try_new([1, 0], [text, number]).unwrap(), mode);
921 let empty = DataType::Union(UnionFields::empty(), mode);
922
923 assert!(superset.contains(&subset));
924 assert!(!subset.contains(&superset));
925 assert!(superset.contains(&superset));
926 assert!(superset.contains(&reordered));
927 assert!(reordered.contains(&superset));
928 assert!(superset.contains(&empty));
929 assert!(!empty.contains(&superset));
930 assert!(empty.contains(&empty));
931 }
932 }
933
934 #[test]
935 fn test_union_contains_field_compatibility() {
936 for mode in [UnionMode::Sparse, UnionMode::Dense] {
937 let field = Field::new("number", DataType::Int32, false);
938 let union = DataType::Union(UnionFields::try_new([0], [field.clone()]).unwrap(), mode);
939 let nullable = DataType::Union(
940 UnionFields::try_new([0], [field.clone().with_nullable(true)]).unwrap(),
941 mode,
942 );
943 assert!(nullable.contains(&union));
944 assert!(!union.contains(&nullable));
945
946 let different_id =
947 DataType::Union(UnionFields::try_new([1], [field.clone()]).unwrap(), mode);
948 assert!(!union.contains(&different_id));
949 assert!(!different_id.contains(&union));
950
951 let different_type = DataType::Union(
952 UnionFields::try_new([0], [field.clone().with_data_type(DataType::Utf8)]).unwrap(),
953 mode,
954 );
955 assert!(!union.contains(&different_type));
956 assert!(!different_type.contains(&union));
957
958 let other_mode = match mode {
959 UnionMode::Sparse => UnionMode::Dense,
960 UnionMode::Dense => UnionMode::Sparse,
961 };
962 let different_mode =
963 DataType::Union(UnionFields::try_new([0], [field]).unwrap(), other_mode);
964 assert!(!union.contains(&different_mode));
965 assert!(!different_mode.contains(&union));
966 }
967 }
968
969 #[test]
970 #[cfg(feature = "serde")]
971 fn serde_struct_type() {
972 use std::collections::HashMap;
973
974 let kv_array = [("k".to_string(), "v".to_string())];
975 let field_metadata: HashMap<String, String> = kv_array.iter().cloned().collect();
976
977 // Non-empty map: should be converted as JSON obj { ... }
978 let first_name =
979 Field::new("first_name", DataType::Utf8, false).with_metadata(field_metadata);
980
981 // Empty map: should be omitted.
982 let last_name =
983 Field::new("last_name", DataType::Utf8, false).with_metadata(HashMap::default());
984
985 let person = DataType::Struct(Fields::from(vec![
986 first_name,
987 last_name,
988 Field::new(
989 "address",
990 DataType::Struct(Fields::from(vec![
991 Field::new("street", DataType::Utf8, false),
992 Field::new("zip", DataType::UInt16, false),
993 ])),
994 false,
995 ),
996 ]));
997
998 let serialized = serde_json::to_string(&person).unwrap();
999
1000 // NOTE that this is testing the default (derived) serialization format, not the
1001 // JSON format specified in metadata.md
1002
1003 assert_eq!(
1004 "{\"Struct\":[\
1005 {\"name\":\"first_name\",\"data_type\":\"Utf8\",\"nullable\":false,\"dict_id\":0,\"dict_is_ordered\":false,\"metadata\":{\"k\":\"v\"}},\
1006 {\"name\":\"last_name\",\"data_type\":\"Utf8\",\"nullable\":false,\"dict_id\":0,\"dict_is_ordered\":false,\"metadata\":{}},\
1007 {\"name\":\"address\",\"data_type\":{\"Struct\":\
1008 [{\"name\":\"street\",\"data_type\":\"Utf8\",\"nullable\":false,\"dict_id\":0,\"dict_is_ordered\":false,\"metadata\":{}},\
1009 {\"name\":\"zip\",\"data_type\":\"UInt16\",\"nullable\":false,\"dict_id\":0,\"dict_is_ordered\":false,\"metadata\":{}}\
1010 ]},\"nullable\":false,\"dict_id\":0,\"dict_is_ordered\":false,\"metadata\":{}}]}",
1011 serialized
1012 );
1013
1014 let deserialized = serde_json::from_str(&serialized).unwrap();
1015
1016 assert_eq!(person, deserialized);
1017 }
1018
1019 #[test]
1020 fn test_list_datatype_equality() {
1021 // tests that list type equality is checked while ignoring list names
1022 let list_a = DataType::List(Arc::new(Field::new_list_field(DataType::Int32, true)));
1023 let list_b = DataType::List(Arc::new(Field::new("array", DataType::Int32, true)));
1024 let list_c = DataType::List(Arc::new(Field::new_list_field(DataType::Int32, false)));
1025 let list_d = DataType::List(Arc::new(Field::new_list_field(DataType::UInt32, true)));
1026 assert!(list_a.equals_datatype(&list_b));
1027 assert!(!list_a.equals_datatype(&list_c));
1028 assert!(!list_b.equals_datatype(&list_c));
1029 assert!(!list_a.equals_datatype(&list_d));
1030
1031 let list_e =
1032 DataType::FixedSizeList(Arc::new(Field::new_list_field(list_a.clone(), false)), 3);
1033 let list_f =
1034 DataType::FixedSizeList(Arc::new(Field::new("array", list_b.clone(), false)), 3);
1035 let list_g = DataType::FixedSizeList(
1036 Arc::new(Field::new_list_field(DataType::FixedSizeBinary(3), true)),
1037 3,
1038 );
1039 assert!(list_e.equals_datatype(&list_f));
1040 assert!(!list_e.equals_datatype(&list_g));
1041 assert!(!list_f.equals_datatype(&list_g));
1042
1043 let list_h = DataType::Struct(Fields::from(vec![Field::new("f1", list_e, true)]));
1044 let list_i = DataType::Struct(Fields::from(vec![Field::new("f1", list_f.clone(), true)]));
1045 let list_j = DataType::Struct(Fields::from(vec![Field::new("f1", list_f.clone(), false)]));
1046 let list_k = DataType::Struct(Fields::from(vec![
1047 Field::new("f1", list_f.clone(), false),
1048 Field::new("f2", list_g.clone(), false),
1049 Field::new("f3", DataType::Utf8, true),
1050 ]));
1051 let list_l = DataType::Struct(Fields::from(vec![
1052 Field::new("ff1", list_f.clone(), false),
1053 Field::new("ff2", list_g.clone(), false),
1054 Field::new("ff3", DataType::LargeUtf8, true),
1055 ]));
1056 let list_m = DataType::Struct(Fields::from(vec![
1057 Field::new("ff1", list_f, false),
1058 Field::new("ff2", list_g, false),
1059 Field::new("ff3", DataType::Utf8, true),
1060 ]));
1061 assert!(list_h.equals_datatype(&list_i));
1062 assert!(!list_h.equals_datatype(&list_j));
1063 assert!(!list_k.equals_datatype(&list_l));
1064 assert!(list_k.equals_datatype(&list_m));
1065
1066 let list_n = DataType::Map(Arc::new(Field::new("f1", list_a.clone(), true)), true);
1067 let list_o = DataType::Map(Arc::new(Field::new("f2", list_b.clone(), true)), true);
1068 let list_p = DataType::Map(Arc::new(Field::new("f2", list_b.clone(), true)), false);
1069 let list_q = DataType::Map(Arc::new(Field::new("f2", list_c.clone(), true)), true);
1070 let list_r = DataType::Map(Arc::new(Field::new("f1", list_a.clone(), false)), true);
1071
1072 assert!(list_n.equals_datatype(&list_o));
1073 assert!(!list_n.equals_datatype(&list_p));
1074 assert!(!list_n.equals_datatype(&list_q));
1075 assert!(!list_n.equals_datatype(&list_r));
1076
1077 let list_s = DataType::Dictionary(Box::new(DataType::UInt8), Box::new(list_a));
1078 let list_t = DataType::Dictionary(Box::new(DataType::UInt8), Box::new(list_b.clone()));
1079 let list_u = DataType::Dictionary(Box::new(DataType::Int8), Box::new(list_b));
1080 let list_v = DataType::Dictionary(Box::new(DataType::UInt8), Box::new(list_c));
1081
1082 assert!(list_s.equals_datatype(&list_t));
1083 assert!(!list_s.equals_datatype(&list_u));
1084 assert!(!list_s.equals_datatype(&list_v));
1085
1086 let union_a = DataType::Union(
1087 UnionFields::try_new(
1088 vec![1, 2],
1089 vec![
1090 Field::new("f1", DataType::Utf8, false),
1091 Field::new("f2", DataType::UInt8, false),
1092 ],
1093 )
1094 .unwrap(),
1095 UnionMode::Sparse,
1096 );
1097 let union_b = DataType::Union(
1098 UnionFields::try_new(
1099 vec![1, 2],
1100 vec![
1101 Field::new("ff1", DataType::Utf8, false),
1102 Field::new("ff2", DataType::UInt8, false),
1103 ],
1104 )
1105 .unwrap(),
1106 UnionMode::Sparse,
1107 );
1108 let union_c = DataType::Union(
1109 UnionFields::try_new(
1110 vec![2, 1],
1111 vec![
1112 Field::new("fff2", DataType::UInt8, false),
1113 Field::new("fff1", DataType::Utf8, false),
1114 ],
1115 )
1116 .unwrap(),
1117 UnionMode::Sparse,
1118 );
1119 let union_d = DataType::Union(
1120 UnionFields::try_new(
1121 vec![2, 1],
1122 vec![
1123 Field::new("fff1", DataType::Int8, false),
1124 Field::new("fff2", DataType::UInt8, false),
1125 ],
1126 )
1127 .unwrap(),
1128 UnionMode::Sparse,
1129 );
1130 let union_e = DataType::Union(
1131 UnionFields::try_new(
1132 vec![1, 2],
1133 vec![
1134 Field::new("f1", DataType::Utf8, true),
1135 Field::new("f2", DataType::UInt8, false),
1136 ],
1137 )
1138 .unwrap(),
1139 UnionMode::Sparse,
1140 );
1141
1142 assert!(union_a.equals_datatype(&union_b));
1143 assert!(union_a.equals_datatype(&union_c));
1144 assert!(!union_a.equals_datatype(&union_d));
1145 assert!(!union_a.equals_datatype(&union_e));
1146
1147 let list_w = DataType::RunEndEncoded(
1148 Arc::new(Field::new("f1", DataType::Int64, true)),
1149 Arc::new(Field::new("f2", DataType::Utf8, true)),
1150 );
1151 let list_x = DataType::RunEndEncoded(
1152 Arc::new(Field::new("ff1", DataType::Int64, true)),
1153 Arc::new(Field::new("ff2", DataType::Utf8, true)),
1154 );
1155 let list_y = DataType::RunEndEncoded(
1156 Arc::new(Field::new("ff1", DataType::UInt16, true)),
1157 Arc::new(Field::new("ff2", DataType::Utf8, true)),
1158 );
1159 let list_z = DataType::RunEndEncoded(
1160 Arc::new(Field::new("f1", DataType::Int64, false)),
1161 Arc::new(Field::new("f2", DataType::Utf8, true)),
1162 );
1163
1164 assert!(list_w.equals_datatype(&list_x));
1165 assert!(!list_w.equals_datatype(&list_y));
1166 assert!(!list_w.equals_datatype(&list_z));
1167 }
1168
1169 #[test]
1170 fn create_struct_type() {
1171 let _person = DataType::Struct(Fields::from(vec![
1172 Field::new("first_name", DataType::Utf8, false),
1173 Field::new("last_name", DataType::Utf8, false),
1174 Field::new(
1175 "address",
1176 DataType::Struct(Fields::from(vec![
1177 Field::new("street", DataType::Utf8, false),
1178 Field::new("zip", DataType::UInt16, false),
1179 ])),
1180 false,
1181 ),
1182 ]));
1183 }
1184
1185 #[test]
1186 fn test_nested() {
1187 let list = DataType::List(Arc::new(Field::new("foo", DataType::Utf8, true)));
1188 let list_view = DataType::ListView(Arc::new(Field::new("foo", DataType::Utf8, true)));
1189 let large_list_view =
1190 DataType::LargeListView(Arc::new(Field::new("foo", DataType::Utf8, true)));
1191
1192 assert!(!DataType::is_nested(&DataType::Boolean));
1193 assert!(!DataType::is_nested(&DataType::Int32));
1194 assert!(!DataType::is_nested(&DataType::Utf8));
1195 assert!(DataType::is_nested(&list));
1196 assert!(DataType::is_nested(&list_view));
1197 assert!(DataType::is_nested(&large_list_view));
1198
1199 assert!(!DataType::is_nested(&DataType::Dictionary(
1200 Box::new(DataType::Int32),
1201 Box::new(DataType::Boolean)
1202 )));
1203 assert!(!DataType::is_nested(&DataType::Dictionary(
1204 Box::new(DataType::Int32),
1205 Box::new(DataType::Int64)
1206 )));
1207 assert!(!DataType::is_nested(&DataType::Dictionary(
1208 Box::new(DataType::Int32),
1209 Box::new(DataType::LargeUtf8)
1210 )));
1211 assert!(DataType::is_nested(&DataType::Dictionary(
1212 Box::new(DataType::Int32),
1213 Box::new(list)
1214 )));
1215 }
1216
1217 #[test]
1218 fn test_integer() {
1219 // is_integer
1220 assert!(DataType::is_integer(&DataType::Int32));
1221 assert!(DataType::is_integer(&DataType::UInt64));
1222 assert!(!DataType::is_integer(&DataType::Float16));
1223
1224 // is_signed_integer
1225 assert!(DataType::is_signed_integer(&DataType::Int32));
1226 assert!(!DataType::is_signed_integer(&DataType::UInt64));
1227 assert!(!DataType::is_signed_integer(&DataType::Float16));
1228
1229 // is_unsigned_integer
1230 assert!(!DataType::is_unsigned_integer(&DataType::Int32));
1231 assert!(DataType::is_unsigned_integer(&DataType::UInt64));
1232 assert!(!DataType::is_unsigned_integer(&DataType::Float16));
1233
1234 // is_dictionary_key_type
1235 assert!(DataType::is_dictionary_key_type(&DataType::Int32));
1236 assert!(DataType::is_dictionary_key_type(&DataType::UInt64));
1237 assert!(!DataType::is_dictionary_key_type(&DataType::Float16));
1238 }
1239
1240 #[test]
1241 fn test_string() {
1242 assert!(DataType::is_string(&DataType::Utf8));
1243 assert!(DataType::is_string(&DataType::LargeUtf8));
1244 assert!(DataType::is_string(&DataType::Utf8View));
1245 assert!(!DataType::is_string(&DataType::Int32));
1246 }
1247
1248 #[test]
1249 fn test_floating() {
1250 assert!(DataType::is_floating(&DataType::Float16));
1251 assert!(!DataType::is_floating(&DataType::Int32));
1252 }
1253
1254 #[test]
1255 fn test_decimal() {
1256 assert!(DataType::is_decimal(&DataType::Decimal32(4, 2)));
1257 assert!(DataType::is_decimal(&DataType::Decimal64(4, 2)));
1258 assert!(DataType::is_decimal(&DataType::Decimal128(4, 2)));
1259 assert!(DataType::is_decimal(&DataType::Decimal256(4, 2)));
1260 assert!(!DataType::is_decimal(&DataType::Float16));
1261 }
1262
1263 #[test]
1264 fn test_datatype_is_null() {
1265 assert!(DataType::is_null(&DataType::Null));
1266 assert!(!DataType::is_null(&DataType::Int32));
1267 }
1268
1269 #[test]
1270 fn test_is_list() {
1271 assert!(DataType::is_list(&DataType::new_list(
1272 DataType::Int16,
1273 true
1274 )));
1275 assert!(DataType::is_list(&DataType::new_large_list(
1276 DataType::Int16,
1277 true
1278 )));
1279 assert!(DataType::is_list(&DataType::new_fixed_size_list(
1280 DataType::Int16,
1281 5,
1282 true
1283 )));
1284 assert!(DataType::is_list(&DataType::ListView(Arc::new(
1285 Field::new("f", DataType::Int16, true)
1286 ))));
1287 assert!(DataType::is_list(&DataType::LargeListView(Arc::new(
1288 Field::new("f", DataType::Int16, true)
1289 ))));
1290 assert!(!DataType::is_list(&DataType::Binary));
1291 }
1292
1293 #[test]
1294 fn test_is_binary() {
1295 assert!(DataType::is_binary(&DataType::Binary));
1296 assert!(DataType::is_binary(&DataType::LargeBinary));
1297 assert!(DataType::is_binary(&DataType::BinaryView));
1298 assert!(!DataType::is_list(&DataType::Utf8View));
1299 }
1300
1301 #[test]
1302 fn size_should_not_regress() {
1303 assert_eq!(std::mem::size_of::<DataType>(), 24);
1304 }
1305
1306 #[test]
1307 #[should_panic(expected = "duplicate type id: 1")]
1308 fn test_union_with_duplicated_type_id() {
1309 let type_ids = vec![1, 1];
1310 let _union = DataType::Union(
1311 UnionFields::try_new(
1312 type_ids,
1313 vec![
1314 Field::new("f1", DataType::Int32, false),
1315 Field::new("f2", DataType::Utf8, false),
1316 ],
1317 )
1318 .unwrap(),
1319 UnionMode::Dense,
1320 );
1321 }
1322
1323 #[test]
1324 fn test_try_from_str() {
1325 let data_type: DataType = "Int32".try_into().unwrap();
1326 assert_eq!(data_type, DataType::Int32);
1327 }
1328
1329 #[test]
1330 fn test_from_str() {
1331 let data_type: DataType = "UInt64".parse().unwrap();
1332 assert_eq!(data_type, DataType::UInt64);
1333 }
1334
1335 #[test]
1336 #[cfg_attr(miri, ignore)] // fork is not supported
1337 fn test_debug_format_field() {
1338 // Make sure the `Debug` formatting of `DataType` is readable and not too long
1339 insta::assert_debug_snapshot!(DataType::new_list(DataType::Int8, false), @r"
1340 List(
1341 Field {
1342 data_type: Int8,
1343 },
1344 )
1345 ");
1346 }
1347}