Skip to main content

datafusion_common/
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
5//! [`DataTypeExt`] and [`FieldExt`] extension trait for working with Arrow [`DataType`] and [`Field`]s
6
7use crate::arrow::datatypes::{DataType, Field, FieldRef};
8use crate::metadata::FieldMetadata;
9use std::sync::Arc;
10
11/// DataFusion extension methods for Arrow [`DataType`]
12pub trait DataTypeExt {
13    /// Convert the type to field with nullable type and "" name
14    ///
15    /// This is used to track the places where we convert a [`DataType`]
16    /// into a nameless field to interact with an API that is
17    /// capable of representing an extension type and/or nullability.
18    ///
19    /// For example, it will convert a `DataType::Int32` into
20    /// `Field::new("", DataType::Int32, true)`.
21    ///
22    /// ```
23    /// # use datafusion_common::datatype::DataTypeExt;
24    /// # use arrow::datatypes::DataType;
25    /// let dt = DataType::Utf8;
26    /// let field = dt.into_nullable_field();
27    /// // result is a nullable Utf8 field with "" name
28    /// assert_eq!(field.name(), "");
29    /// assert_eq!(field.data_type(), &DataType::Utf8);
30    /// assert!(field.is_nullable());
31    /// ```
32    fn into_nullable_field(self) -> Field;
33
34    /// Convert the type to [`FieldRef`] with nullable type and "" name
35    ///
36    /// Concise wrapper around [`DataTypeExt::into_nullable_field`] that
37    /// constructs a [`FieldRef`].
38    fn into_nullable_field_ref(self) -> FieldRef;
39}
40
41impl DataTypeExt for DataType {
42    fn into_nullable_field(self) -> Field {
43        Field::new("", self, true)
44    }
45
46    fn into_nullable_field_ref(self) -> FieldRef {
47        Arc::new(Field::new("", self, true))
48    }
49}
50
51/// DataFusion extension methods for Arrow [`Field`] and [`FieldRef`]
52///
53/// This trait is implemented for both [`Field`] and [`FieldRef`] and
54/// provides convenience methods for efficiently working with both types.
55///
56/// For [`FieldRef`], the methods will attempt to unwrap the `Arc`
57/// to avoid unnecessary cloning when possible.
58pub trait FieldExt {
59    /// Ensure the field is named `new_name`, returning the given field if the
60    /// name matches, and a new field if not.
61    ///
62    /// This method avoids `clone`ing fields and names if the name is the same
63    /// as the field's existing name.
64    ///
65    /// Example:
66    /// ```
67    /// # use std::sync::Arc;
68    /// # use arrow::datatypes::{DataType, Field};
69    /// # use datafusion_common::datatype::FieldExt;
70    /// let int_field = Field::new("my_int", DataType::Int32, true);
71    /// // rename to "your_int"
72    /// let renamed_field = int_field.renamed("your_int");
73    /// assert_eq!(renamed_field.name(), "your_int");
74    /// ```
75    fn renamed(self, new_name: &str) -> Self;
76
77    /// Ensure the field has the given data type
78    ///
79    /// Note this is different than simply calling [`Field::with_data_type`] as
80    /// it avoids copying if the data type is already the same.
81    ///
82    /// Example:
83    /// ```
84    /// # use std::sync::Arc;
85    /// # use arrow::datatypes::{DataType, Field};
86    /// # use datafusion_common::datatype::FieldExt;
87    /// let int_field = Field::new("my_int", DataType::Int32, true);
88    /// // change to Float64
89    /// let retyped_field = int_field.retyped(DataType::Float64);
90    /// assert_eq!(retyped_field.data_type(), &DataType::Float64);
91    /// ```
92    fn retyped(self, new_data_type: DataType) -> Self;
93
94    /// Add field metadata to the Field
95    fn with_field_metadata(self, metadata: &FieldMetadata) -> Self;
96
97    /// Add optional field metadata,
98    fn with_field_metadata_opt(self, metadata: Option<&FieldMetadata>) -> Self;
99
100    /// Returns a new Field representing a List of this Field's DataType.
101    ///
102    /// For example if input represents an `Int32`, the return value will
103    /// represent a `List<Int32>`.
104    ///
105    /// Example:
106    /// ```
107    /// # use std::sync::Arc;
108    /// # use arrow::datatypes::{DataType, Field};
109    /// # use datafusion_common::datatype::FieldExt;
110    /// // Int32 field
111    /// let int_field = Field::new("my_int", DataType::Int32, true);
112    /// // convert to a List field
113    /// let list_field = int_field.into_list();
114    /// // List<Int32>
115    /// // Note that the item field name has been renamed to "item"
116    /// assert_eq!(list_field.data_type(), &DataType::List(Arc::new(
117    ///     Field::new("item", DataType::Int32, true)
118    /// )));
119    fn into_list(self) -> Self;
120
121    /// Return a new Field representing this Field as the item type of a
122    /// [`DataType::FixedSizeList`]
123    ///
124    /// For example if input represents an `Int32`, the return value will
125    /// represent a `FixedSizeList<Int32, size>`.
126    ///
127    /// Example:
128    /// ```
129    /// # use std::sync::Arc;
130    /// # use arrow::datatypes::{DataType, Field};
131    /// # use datafusion_common::datatype::FieldExt;
132    /// // Int32 field
133    /// let int_field = Field::new("my_int", DataType::Int32, true);
134    /// // convert to a FixedSizeList field of size 3
135    /// let fixed_size_list_field = int_field.into_fixed_size_list(3);
136    /// // FixedSizeList<Int32, 3>
137    /// // Note that the item field name has been renamed to "item"
138    /// assert_eq!(
139    ///   fixed_size_list_field.data_type(),
140    ///   &DataType::FixedSizeList(Arc::new(
141    ///    Field::new("item", DataType::Int32, true)),
142    ///    3
143    /// ));
144    fn into_fixed_size_list(self, list_size: i32) -> Self;
145
146    /// Update the field to have the default list field name ("item")
147    ///
148    /// Lists are allowed to have an arbitrarily named field; however, a name
149    /// other than 'item' will cause it to fail an == check against a more
150    /// idiomatically created list in arrow-rs which causes issues.
151    ///
152    /// For example, if input represents an `Int32` field named "my_int",
153    /// the return value will represent an `Int32` field named "item".
154    ///
155    /// Example:
156    /// ```
157    /// # use arrow::datatypes::Field;
158    /// # use datafusion_common::datatype::FieldExt;
159    /// let my_field = Field::new("my_int", arrow::datatypes::DataType::Int32, true);
160    /// let item_field = my_field.into_list_item();
161    /// assert_eq!(item_field.name(), Field::LIST_FIELD_DEFAULT_NAME);
162    /// assert_eq!(item_field.name(), "item");
163    /// ```
164    fn into_list_item(self) -> Self;
165}
166
167impl FieldExt for Field {
168    fn renamed(self, new_name: &str) -> Self {
169        // check if this is a new name before allocating a new Field / copying
170        // the existing one
171        if self.name() != new_name {
172            self.with_name(new_name)
173        } else {
174            self
175        }
176    }
177
178    fn retyped(self, new_data_type: DataType) -> Self {
179        self.with_data_type(new_data_type)
180    }
181
182    fn with_field_metadata(self, metadata: &FieldMetadata) -> Self {
183        metadata.add_to_field(self)
184    }
185
186    fn with_field_metadata_opt(self, metadata: Option<&FieldMetadata>) -> Self {
187        if let Some(metadata) = metadata {
188            self.with_field_metadata(metadata)
189        } else {
190            self
191        }
192    }
193
194    fn into_list(self) -> Self {
195        DataType::List(Arc::new(self.into_list_item())).into_nullable_field()
196    }
197
198    fn into_fixed_size_list(self, list_size: i32) -> Self {
199        DataType::FixedSizeList(self.into_list_item().into(), list_size)
200            .into_nullable_field()
201    }
202
203    fn into_list_item(self) -> Self {
204        if self.name() != Field::LIST_FIELD_DEFAULT_NAME {
205            self.with_name(Field::LIST_FIELD_DEFAULT_NAME)
206        } else {
207            self
208        }
209    }
210}
211
212impl FieldExt for Arc<Field> {
213    fn renamed(mut self, new_name: &str) -> Self {
214        if self.name() != new_name {
215            // avoid cloning if possible
216            Arc::make_mut(&mut self).set_name(new_name);
217        }
218        self
219    }
220
221    fn retyped(mut self, new_data_type: DataType) -> Self {
222        if self.data_type() != &new_data_type {
223            // avoid cloning if possible
224            Arc::make_mut(&mut self).set_data_type(new_data_type);
225        }
226        self
227    }
228
229    fn with_field_metadata(self, metadata: &FieldMetadata) -> Self {
230        metadata.add_to_field_ref(self)
231    }
232
233    fn with_field_metadata_opt(self, metadata: Option<&FieldMetadata>) -> Self {
234        if let Some(metadata) = metadata {
235            self.with_field_metadata(metadata)
236        } else {
237            self
238        }
239    }
240
241    fn into_list(self) -> Self {
242        DataType::List(self.into_list_item())
243            .into_nullable_field()
244            .into()
245    }
246
247    fn into_fixed_size_list(self, list_size: i32) -> Self {
248        DataType::FixedSizeList(self.into_list_item(), list_size)
249            .into_nullable_field()
250            .into()
251    }
252
253    fn into_list_item(mut self) -> Self {
254        if self.name() != Field::LIST_FIELD_DEFAULT_NAME {
255            // avoid cloning if possible
256            Arc::make_mut(&mut self).set_name(Field::LIST_FIELD_DEFAULT_NAME);
257        }
258        self
259    }
260}