datatypes/types/
struct_type.rs1use arrow::datatypes::{DataType as ArrowDataType, Field};
16use arrow_schema::Fields;
17use serde::{Deserialize, Serialize};
18
19use crate::prelude::{ConcreteDataType, DataType, LogicalTypeId};
20use crate::value::Value;
21
22#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
23pub struct StructType {
24 fields: Vec<StructField>,
25}
26
27impl TryFrom<&Fields> for StructType {
28 type Error = crate::error::Error;
29 fn try_from(value: &Fields) -> Result<Self, Self::Error> {
30 let fields = value
31 .iter()
32 .map(|field| {
33 Ok(StructField::new(
34 field.name().to_string(),
35 ConcreteDataType::try_from(field.data_type())?,
36 field.is_nullable(),
37 ))
38 })
39 .collect::<Result<Vec<StructField>, Self::Error>>()?;
40 Ok(StructType { fields })
41 }
42}
43
44impl From<Vec<StructField>> for StructType {
45 fn from(fields: Vec<StructField>) -> Self {
46 StructType { fields }
47 }
48}
49
50impl DataType for StructType {
51 fn name(&self) -> String {
52 format!(
53 "Struct<{}>",
54 self.fields
55 .iter()
56 .map(|f| f.name())
57 .collect::<Vec<_>>()
58 .join(", ")
59 )
60 }
61
62 fn logical_type_id(&self) -> LogicalTypeId {
63 LogicalTypeId::Struct
64 }
65
66 fn default_value(&self) -> Value {
67 Value::Null
68 }
69
70 fn as_arrow_type(&self) -> ArrowDataType {
71 let fields = self
72 .fields
73 .iter()
74 .map(|f| Field::new(f.name.clone(), f.data_type.as_arrow_type(), f.nullable))
75 .collect();
76 ArrowDataType::Struct(fields)
77 }
78
79 fn create_mutable_vector(&self, _capacity: usize) -> Box<dyn crate::prelude::MutableVector> {
80 unimplemented!("What is the mutable vector for StructVector?");
81 }
82
83 fn try_cast(&self, _from: Value) -> Option<Value> {
84 None
86 }
87}
88
89impl StructType {
90 pub fn new(fields: Vec<StructField>) -> Self {
91 StructType { fields }
92 }
93
94 pub fn fields(&self) -> &[StructField] {
95 &self.fields
96 }
97}
98
99#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
100pub struct StructField {
101 name: String,
102 data_type: ConcreteDataType,
103 nullable: bool,
104}
105
106impl StructField {
107 pub fn new(name: String, data_type: ConcreteDataType, nullable: bool) -> Self {
108 StructField {
109 name,
110 data_type,
111 nullable,
112 }
113 }
114
115 pub fn name(&self) -> &str {
116 &self.name
117 }
118
119 pub fn data_type(&self) -> &ConcreteDataType {
120 &self.data_type
121 }
122
123 pub fn is_nullable(&self) -> bool {
124 self.nullable
125 }
126
127 pub fn to_df_field(&self) -> Field {
128 Field::new(
129 self.name.clone(),
130 self.data_type.as_arrow_type(),
131 self.nullable,
132 )
133 }
134}