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