use serde::{Deserialize, Serialize};
use std::collections::HashMap;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CompositeField {
pub name: String,
pub field_type: String,
pub nullable: bool,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CompositeType {
pub name: String,
pub fields: Vec<CompositeField>,
pub schema: Option<String>,
}
impl CompositeType {
pub fn new(name: impl Into<String>) -> Self {
Self {
name: name.into(),
fields: Vec::new(),
schema: None,
}
}
pub fn with_field(
mut self,
name: impl Into<String>,
field_type: impl Into<String>,
nullable: bool,
) -> Self {
self.fields.push(CompositeField {
name: name.into(),
field_type: field_type.into(),
nullable,
});
self
}
pub fn with_schema(mut self, schema: impl Into<String>) -> Self {
self.schema = Some(schema.into());
self
}
pub fn generate_create_ddl(&self) -> String {
let schema_prefix = self
.schema
.as_ref()
.map(|s| format!("\"{}\".", s))
.unwrap_or_default();
let field_definitions: Vec<String> = self
.fields
.iter()
.map(|field| {
format!(" \"{}\" {}", field.name, field.field_type)
})
.collect();
format!(
"CREATE TYPE {}\"{}\" AS (\n{}\n);",
schema_prefix,
self.name,
field_definitions.join(",\n")
)
}
pub fn generate_drop_ddl(&self) -> String {
let schema_prefix = self
.schema
.as_ref()
.map(|s| format!("\"{}\".", s))
.unwrap_or_default();
format!(
"DROP TYPE IF EXISTS {}\"{}\" CASCADE;",
schema_prefix, self.name
)
}
pub fn full_name(&self) -> String {
match &self.schema {
Some(schema) => format!("\"{}\".\"{}\"", schema, self.name),
None => format!("\"{}\"", self.name),
}
}
}
pub struct CompositeTypeRegistry {
types: HashMap<String, CompositeType>,
}
impl CompositeTypeRegistry {
pub fn new() -> Self {
Self {
types: HashMap::new(),
}
}
pub fn register(&mut self, composite_type: CompositeType) {
self.types
.insert(composite_type.full_name(), composite_type);
}
pub fn all_types(&self) -> impl Iterator<Item = &CompositeType> {
self.types.values()
}
pub fn get_type(&self, name: &str) -> Option<&CompositeType> {
self.types.get(name)
}
}
impl Default for CompositeTypeRegistry {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_composite_type_creation() {
let address_type = CompositeType::new("address")
.with_field("street", "TEXT", false)
.with_field("city", "TEXT", false)
.with_field("zipcode", "VARCHAR(10)", true);
assert_eq!(address_type.name, "address");
assert_eq!(address_type.fields.len(), 3);
assert_eq!(address_type.fields[0].name, "street");
assert_eq!(address_type.fields[0].field_type, "TEXT");
assert!(!address_type.fields[0].nullable);
assert!(address_type.fields[2].nullable);
}
#[test]
fn test_create_ddl_generation() {
let address_type = CompositeType::new("address")
.with_field("street", "TEXT", false)
.with_field("city", "TEXT", false)
.with_field("zipcode", "VARCHAR(10)", true);
let ddl = address_type.generate_create_ddl();
assert!(ddl.contains("CREATE TYPE \"address\" AS"));
assert!(ddl.contains("\"street\" TEXT"));
assert!(ddl.contains("\"city\" TEXT"));
assert!(ddl.contains("\"zipcode\" VARCHAR(10)"));
assert!(!ddl.contains("NOT NULL"));
}
#[test]
fn test_drop_ddl_generation() {
let address_type = CompositeType::new("address");
let ddl = address_type.generate_drop_ddl();
assert_eq!(ddl, "DROP TYPE IF EXISTS \"address\" CASCADE;");
}
#[test]
fn test_composite_with_schema() {
let address_type = CompositeType::new("address")
.with_schema("public")
.with_field("street", "TEXT", false);
assert_eq!(address_type.full_name(), "\"public\".\"address\"");
let create_ddl = address_type.generate_create_ddl();
assert!(create_ddl.contains("CREATE TYPE \"public\".\"address\" AS"));
let drop_ddl = address_type.generate_drop_ddl();
assert!(drop_ddl.contains("DROP TYPE IF EXISTS \"public\".\"address\" CASCADE"));
}
#[test]
fn test_registry() {
let mut registry = CompositeTypeRegistry::new();
let address_type = CompositeType::new("address").with_field("street", "TEXT", false);
let point_type = CompositeType::new("point")
.with_field("x", "DOUBLE PRECISION", false)
.with_field("y", "DOUBLE PRECISION", false);
registry.register(address_type.clone());
registry.register(point_type);
assert_eq!(registry.all_types().count(), 2);
assert!(registry.get_type("\"address\"").is_some());
assert!(registry.get_type("\"point\"").is_some());
assert!(registry.get_type("nonexistent").is_none());
}
}