use std::fmt;
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum DataType {
Simple {
type_name: String,
},
Decimal {
precision: u32,
scale: u32,
},
Array {
element_type: Box<DataType>,
},
Map {
key_type: Box<DataType>,
value_type: Box<DataType>,
},
Struct(StructType),
}
impl DataType {
pub fn type_name(&self) -> &str {
match self {
DataType::Simple { type_name } => type_name,
DataType::Decimal { .. } => "decimal",
DataType::Array { .. } => "array",
DataType::Map { .. } => "map",
DataType::Struct(_) => "struct",
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct StructField {
pub name: String,
pub data_type: DataType,
pub nullable: bool,
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct StructType {
pub type_name: String,
pub fields: Vec<StructField>,
}
impl StructType {
pub fn new(fields: Vec<StructField>) -> Self {
Self {
type_name: "struct".to_string(),
fields,
}
}
}
impl fmt::Display for DataType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
DataType::Simple { type_name } => write!(f, "{}", type_name),
DataType::Decimal { precision, scale } => write!(f, "decimal({},{})", precision, scale),
DataType::Array { element_type } => write!(f, "array<{}>", element_type),
DataType::Map {
key_type,
value_type,
} => {
write!(f, "map<{},{}>", key_type, value_type)
}
DataType::Struct(_s) => write!(f, "struct<...>"),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_data_type_type_name() {
assert_eq!(
DataType::Simple {
type_name: "long".into()
}
.type_name(),
"long"
);
assert_eq!(
DataType::Decimal {
precision: 10,
scale: 2
}
.type_name(),
"decimal"
);
assert_eq!(
DataType::Array {
element_type: Box::new(DataType::Simple {
type_name: "string".into()
})
}
.type_name(),
"array"
);
assert_eq!(StructType::new(vec![]).type_name, "struct");
}
}