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;
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        // 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
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}