arrow2/datatypes/
field.rs

1use super::{DataType, Metadata};
2
3#[cfg(feature = "serde_types")]
4use serde_derive::{Deserialize, Serialize};
5
6/// Represents Arrow's metadata of a "column".
7///
8/// A [`Field`] is the closest representation of the traditional "column": a logical type
9/// ([`DataType`]) with a name and nullability.
10/// A Field has optional [`Metadata`] that can be used to annotate the field with custom metadata.
11///
12/// Almost all IO in this crate uses [`Field`] to represent logical information about the data
13/// to be serialized.
14#[derive(Debug, Clone, Eq, PartialEq, Hash)]
15#[cfg_attr(feature = "serde_types", derive(Serialize, Deserialize))]
16pub struct Field {
17    /// Its name
18    pub name: String,
19    /// Its logical [`DataType`]
20    pub data_type: DataType,
21    /// Its nullability
22    pub is_nullable: bool,
23    /// Additional custom (opaque) metadata.
24    pub metadata: Metadata,
25}
26
27impl Field {
28    /// Creates a new [`Field`].
29    pub fn new<T: Into<String>>(name: T, data_type: DataType, is_nullable: bool) -> Self {
30        Field {
31            name: name.into(),
32            data_type,
33            is_nullable,
34            metadata: Default::default(),
35        }
36    }
37
38    /// Creates a new [`Field`] with metadata.
39    #[inline]
40    pub fn with_metadata(self, metadata: Metadata) -> Self {
41        Self {
42            name: self.name,
43            data_type: self.data_type,
44            is_nullable: self.is_nullable,
45            metadata,
46        }
47    }
48
49    /// Returns the [`Field`]'s [`DataType`].
50    #[inline]
51    pub fn data_type(&self) -> &DataType {
52        &self.data_type
53    }
54}
55
56#[cfg(feature = "arrow")]
57impl From<Field> for arrow_schema::Field {
58    fn from(value: Field) -> Self {
59        Self::new(value.name, value.data_type.into(), value.is_nullable)
60            .with_metadata(value.metadata.into_iter().collect())
61    }
62}
63
64#[cfg(feature = "arrow")]
65impl From<arrow_schema::Field> for Field {
66    fn from(value: arrow_schema::Field) -> Self {
67        (&value).into()
68    }
69}
70
71#[cfg(feature = "arrow")]
72impl From<&arrow_schema::Field> for Field {
73    fn from(value: &arrow_schema::Field) -> Self {
74        let data_type = value.data_type().clone().into();
75        let metadata = value
76            .metadata()
77            .iter()
78            .map(|(k, v)| (k.clone(), v.clone()))
79            .collect();
80        Self::new(value.name(), data_type, value.is_nullable()).with_metadata(metadata)
81    }
82}
83
84#[cfg(feature = "arrow")]
85impl From<arrow_schema::FieldRef> for Field {
86    fn from(value: arrow_schema::FieldRef) -> Self {
87        value.as_ref().into()
88    }
89}
90
91#[cfg(feature = "arrow")]
92impl From<&arrow_schema::FieldRef> for Field {
93    fn from(value: &arrow_schema::FieldRef) -> Self {
94        value.as_ref().into()
95    }
96}