datatypes/types/
struct_type.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use 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;
21use crate::vectors::StructVectorBuilder;
22
23#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
24pub struct StructType {
25    fields: Vec<StructField>,
26}
27
28impl TryFrom<&Fields> for StructType {
29    type Error = crate::error::Error;
30    fn try_from(value: &Fields) -> Result<Self, Self::Error> {
31        let fields = value
32            .iter()
33            .map(|field| {
34                Ok(StructField::new(
35                    field.name().clone(),
36                    ConcreteDataType::try_from(field.data_type())?,
37                    field.is_nullable(),
38                ))
39            })
40            .collect::<Result<Vec<StructField>, Self::Error>>()?;
41        Ok(StructType { fields })
42    }
43}
44
45impl From<Vec<StructField>> for StructType {
46    fn from(fields: Vec<StructField>) -> Self {
47        StructType { fields }
48    }
49}
50
51impl DataType for StructType {
52    fn name(&self) -> String {
53        format!(
54            "Struct<{}>",
55            self.fields
56                .iter()
57                .map(|f| f.name())
58                .collect::<Vec<_>>()
59                .join(", ")
60        )
61    }
62
63    fn logical_type_id(&self) -> LogicalTypeId {
64        LogicalTypeId::Struct
65    }
66
67    fn default_value(&self) -> Value {
68        Value::Null
69    }
70
71    fn as_arrow_type(&self) -> ArrowDataType {
72        let fields = self.as_arrow_fields();
73        ArrowDataType::Struct(fields)
74    }
75
76    fn create_mutable_vector(&self, capacity: usize) -> Box<dyn crate::prelude::MutableVector> {
77        Box::new(StructVectorBuilder::with_type_and_capacity(
78            self.clone(),
79            capacity,
80        ))
81    }
82
83    fn try_cast(&self, _from: Value) -> Option<Value> {
84        // TODO(discord9): what is the meaning of casting from Value to StructFields?
85        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    pub fn as_arrow_fields(&self) -> Fields {
99        self.fields
100            .iter()
101            .map(|f| Field::new(f.name.clone(), f.data_type.as_arrow_type(), f.nullable))
102            .collect()
103    }
104}
105
106#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
107pub struct StructField {
108    name: String,
109    data_type: ConcreteDataType,
110    nullable: bool,
111}
112
113impl StructField {
114    pub fn new(name: String, data_type: ConcreteDataType, nullable: bool) -> Self {
115        StructField {
116            name,
117            data_type,
118            nullable,
119        }
120    }
121
122    pub fn name(&self) -> &str {
123        &self.name
124    }
125
126    pub fn data_type(&self) -> &ConcreteDataType {
127        &self.data_type
128    }
129
130    pub fn is_nullable(&self) -> bool {
131        self.nullable
132    }
133
134    pub fn to_df_field(&self) -> Field {
135        Field::new(
136            self.name.clone(),
137            self.data_type.as_arrow_type(),
138            self.nullable,
139        )
140    }
141}