use serde_derive::{Deserialize, Serialize};
#[cfg(test)]
use serde_json::json;
use std::fmt;
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct Table {
pub name: String,
pub columns: Vec<Column>,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct Column {
pub name: String,
pub is_nullable: bool,
pub data_type: DataType,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub comment: Option<String>,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum DataType {
Array(Box<DataType>),
Bool,
Date,
Decimal,
Float32,
Float64,
GeoJson(Srid),
Int16,
Int32,
Int64,
Json,
Other(String),
Text,
TimestampWithoutTimeZone,
TimestampWithTimeZone,
Uuid,
}
#[test]
fn data_type_serialization_examples() {
let examples = &[
(
DataType::Array(Box::new(DataType::Text)),
json!({"array":"text"}),
),
(DataType::Bool, json!("bool")),
(DataType::Date, json!("date")),
(DataType::Decimal, json!("decimal")),
(DataType::Float32, json!("float32")),
(DataType::Float64, json!("float64")),
(DataType::Int16, json!("int16")),
(DataType::Int32, json!("int32")),
(DataType::Int64, json!("int64")),
(DataType::Json, json!("json")),
(
DataType::Other("custom".to_owned()),
json!({"other":"custom"}),
),
(DataType::Text, json!("text")),
(
DataType::TimestampWithoutTimeZone,
json!("timestamp_without_time_zone"),
),
(
DataType::TimestampWithTimeZone,
json!("timestamp_with_time_zone"),
),
(DataType::Uuid, json!("uuid")),
];
for (data_type, serialized) in examples {
assert_eq!(&json!(data_type), serialized);
}
}
#[test]
fn data_type_roundtrip() {
use serde_json;
let data_types = vec![
DataType::Array(Box::new(DataType::Text)),
DataType::Bool,
DataType::Date,
DataType::Decimal,
DataType::Float32,
DataType::Float64,
DataType::Int16,
DataType::Int32,
DataType::Int64,
DataType::Json,
DataType::Other("custom".to_owned()),
DataType::Text,
DataType::TimestampWithoutTimeZone,
DataType::TimestampWithTimeZone,
DataType::Uuid,
];
for data_type in &data_types {
let serialized = serde_json::to_string(data_type).unwrap();
println!("{:?}: {}", data_type, serialized);
let parsed: DataType = serde_json::from_str(&serialized).unwrap();
assert_eq!(&parsed, data_type);
}
}
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(transparent)]
pub struct Srid(u32);
impl Srid {
pub fn wgs84() -> Srid {
Srid(4326)
}
pub fn new(srid: u32) -> Srid {
Srid(srid)
}
pub fn to_u32(self) -> u32 {
self.0
}
}
impl Default for Srid {
fn default() -> Self {
Self::wgs84()
}
}
impl fmt::Display for Srid {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.0.fmt(f)
}
}