use crate::builders::traits::{
ConditionalBuilder, InspectableBuilder, SchemaBuilder, ValidatableBuilder,
};
use crate::builders::validation::CompositeTypeBuildError;
use crate::schema::{CompositeField, CompositeType};
use std::collections::HashSet;
#[derive(Debug, Clone)]
pub struct CompositeTypeBuilder {
name: Option<String>,
schema: Option<String>,
fields: Vec<CompositeField>,
comment: Option<String>,
}
impl CompositeTypeBuilder {
pub fn new() -> Self {
Self {
name: None,
schema: None,
fields: Vec::new(),
comment: None,
}
}
pub fn name(mut self, name: impl Into<String>) -> Self {
self.name = Some(name.into());
self
}
pub fn set_name(&mut self, name: impl Into<String>) {
self.name = Some(name.into());
}
pub fn in_schema(mut self, schema: impl Into<String>) -> Self {
self.schema = Some(schema.into());
self
}
pub fn set_schema(&mut self, schema: impl Into<String>) {
self.schema = Some(schema.into());
}
pub fn field(mut self, name: impl Into<String>, field_type: impl Into<String>) -> Self {
let field = CompositeField {
name: name.into(),
field_type: field_type.into(),
nullable: true, };
self.fields.push(field);
self
}
pub fn add_field(&mut self, name: impl Into<String>, field_type: impl Into<String>) {
let field = CompositeField {
name: name.into(),
field_type: field_type.into(),
nullable: true, };
self.fields.push(field);
}
pub fn fields(
mut self,
fields: impl IntoIterator<Item = (impl Into<String>, impl Into<String>)>,
) -> Self {
for (name, field_type) in fields {
let field = CompositeField {
name: name.into(),
field_type: field_type.into(),
nullable: true, };
self.fields.push(field);
}
self
}
pub fn add_fields(
&mut self,
fields: impl IntoIterator<Item = (impl Into<String>, impl Into<String>)>,
) {
for (name, field_type) in fields {
let field = CompositeField {
name: name.into(),
field_type: field_type.into(),
nullable: true, };
self.fields.push(field);
}
}
pub fn comment(mut self, comment: impl Into<String>) -> Self {
self.comment = Some(comment.into());
self
}
pub fn set_comment(&mut self, comment: impl Into<String>) {
self.comment = Some(comment.into());
}
pub fn point() -> Self {
Self::new()
.field("x", "DOUBLE PRECISION")
.field("y", "DOUBLE PRECISION")
}
pub fn rectangle() -> Self {
Self::new()
.field("x1", "DOUBLE PRECISION")
.field("y1", "DOUBLE PRECISION")
.field("x2", "DOUBLE PRECISION")
.field("y2", "DOUBLE PRECISION")
}
pub fn circle() -> Self {
Self::new()
.field("center_x", "DOUBLE PRECISION")
.field("center_y", "DOUBLE PRECISION")
.field("radius", "DOUBLE PRECISION")
}
pub fn line() -> Self {
Self::new()
.field("point1_x", "DOUBLE PRECISION")
.field("point1_y", "DOUBLE PRECISION")
.field("point2_x", "DOUBLE PRECISION")
.field("point2_y", "DOUBLE PRECISION")
}
pub fn polygon() -> Self {
Self::new().field("points", "JSONB")
}
pub fn address() -> Self {
Self::new()
.field("street", "VARCHAR(255)")
.field("city", "VARCHAR(100)")
.field("state", "VARCHAR(50)")
.field("postal_code", "VARCHAR(20)")
.field("country", "VARCHAR(100)")
}
pub fn contact_info() -> Self {
Self::new()
.field("email", "VARCHAR(255)")
.field("phone", "VARCHAR(20)")
.field("website", "VARCHAR(255)")
}
pub fn money() -> Self {
Self::new()
.field("amount", "NUMERIC(19,4)")
.field("currency", "VARCHAR(3)")
}
pub fn date_range() -> Self {
Self::new()
.field("start_date", "DATE")
.field("end_date", "DATE")
}
pub fn time_range() -> Self {
Self::new()
.field("start_time", "TIME")
.field("end_time", "TIME")
}
pub fn timestamp_range() -> Self {
Self::new()
.field("start_timestamp", "TIMESTAMPTZ")
.field("end_timestamp", "TIMESTAMPTZ")
}
pub fn get_name(&self) -> Option<&str> {
self.name.as_deref()
}
pub fn get_schema(&self) -> Option<&str> {
self.schema.as_deref()
}
pub fn get_fields(&self) -> &[CompositeField] {
&self.fields
}
pub fn get_comment(&self) -> Option<&str> {
self.comment.as_deref()
}
pub fn field_count(&self) -> usize {
self.fields.len()
}
pub fn has_field(&self, field_name: &str) -> bool {
self.fields.iter().any(|f| f.name == field_name)
}
pub fn get_field(&self, field_name: &str) -> Option<&CompositeField> {
self.fields.iter().find(|f| f.name == field_name)
}
pub fn has_name(&self) -> bool {
self.name.is_some()
}
pub fn has_schema(&self) -> bool {
self.schema.is_some()
}
pub fn has_comment(&self) -> bool {
self.comment.is_some()
}
pub fn has_fields(&self) -> bool {
!self.fields.is_empty()
}
}
impl SchemaBuilder for CompositeTypeBuilder {
type Output = CompositeType;
type Error = CompositeTypeBuildError;
fn build(self) -> Result<Self::Output, Self::Error> {
if !self.is_valid() {
let errors = self.validation_errors();
return Err(CompositeTypeBuildError::ValidationError(errors.join("; ")));
}
let composite_type = CompositeType {
name: self.name.unwrap_or_else(|| "composite_type".to_string()),
fields: self.fields,
schema: self.schema,
};
Ok(composite_type)
}
}
impl ValidatableBuilder for CompositeTypeBuilder {
fn is_valid(&self) -> bool {
self.validation_errors().is_empty()
}
fn validation_errors(&self) -> Vec<String> {
let mut errors = Vec::new();
if self.fields.is_empty() {
errors.push("Composite type must specify at least one field".to_string());
}
for (i, field) in self.fields.iter().enumerate() {
if field.name.trim().is_empty() {
errors.push(format!("Field {} at index {} cannot be empty", i, i));
}
}
let mut seen_fields = HashSet::new();
for field in &self.fields {
if !seen_fields.insert(&field.name) {
errors.push(format!("Duplicate field name: {}", field.name));
}
}
if let Some(ref name) = self.name {
if name.trim().is_empty() {
errors.push("Composite type name cannot be empty".to_string());
}
}
if let Some(ref schema) = self.schema {
if schema.trim().is_empty() {
errors.push("Schema name cannot be empty".to_string());
}
}
errors
}
}
impl ConditionalBuilder for CompositeTypeBuilder {
fn when<F>(mut self, condition: bool, config_fn: F) -> Self
where
F: FnOnce(&mut Self),
Self: Sized,
{
if condition {
config_fn(&mut self);
}
self
}
}
impl InspectableBuilder for CompositeTypeBuilder {
fn debug_info(&self) -> String {
format!(
"CompositeTypeBuilder {{ name: {:?}, schema: {:?}, fields: {:?} }}",
self.name, self.schema, self.fields
)
}
fn summary(&self) -> String {
let mut parts = Vec::new();
parts.push("Composite type".to_string());
if let Some(ref name) = self.name {
if let Some(ref schema) = self.schema {
parts.push(format!("{}.{}", schema, name));
} else {
parts.push(format!("'{}'", name));
}
}
if !self.fields.is_empty() {
let field_descriptions: Vec<String> = self
.fields
.iter()
.map(|f| format!("{}: {:?}", f.name, f.field_type))
.collect();
parts.push(format!("with fields: {}", field_descriptions.join(", ")));
}
if let Some(ref comment) = self.comment {
parts.push(format!("with comment: {}", comment));
}
parts.join(", ")
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::schema::ColumnType;
#[test]
fn test_basic_composite_type() {
let composite_type = CompositeTypeBuilder::new()
.name("point_2d")
.field("x", "DOUBLE PRECISION")
.field("y", "DOUBLE PRECISION")
.build()
.unwrap();
assert_eq!(composite_type.name, "point_2d");
assert_eq!(composite_type.fields.len(), 2);
assert_eq!(composite_type.fields[0].name, "x");
assert_eq!(composite_type.fields[0].field_type, "DOUBLE PRECISION");
assert_eq!(composite_type.fields[1].name, "y");
assert_eq!(composite_type.fields[1].field_type, "DOUBLE PRECISION");
}
#[test]
fn test_composite_type_with_schema() {
let composite_type = CompositeTypeBuilder::new()
.name("address")
.in_schema("public")
.field("street", "TEXT")
.field("city", "TEXT")
.build()
.unwrap();
assert_eq!(composite_type.name, "address");
assert_eq!(composite_type.schema, Some("public".to_string()));
assert_eq!(composite_type.fields.len(), 2);
}
#[test]
fn test_convenience_methods() {
let point_type = CompositeTypeBuilder::point()
.name("point_2d")
.build()
.unwrap();
let rectangle_type = CompositeTypeBuilder::rectangle()
.name("rectangle_2d")
.build()
.unwrap();
let address_type = CompositeTypeBuilder::address()
.name("address_info")
.build()
.unwrap();
assert_eq!(point_type.name, "point_2d");
assert_eq!(point_type.fields.len(), 2);
assert_eq!(rectangle_type.name, "rectangle_2d");
assert_eq!(rectangle_type.fields.len(), 4);
assert_eq!(address_type.name, "address_info");
assert_eq!(address_type.fields.len(), 5);
}
#[test]
fn test_composite_type_with_multiple_fields() {
let composite_type = CompositeTypeBuilder::new()
.name("user_profile")
.fields(vec![
("id", "INTEGER"),
("name", "TEXT"),
("email", "VARCHAR(255)"),
("age", "INTEGER"),
("is_active", "BOOLEAN"),
])
.build()
.unwrap();
assert_eq!(composite_type.name, "user_profile");
assert_eq!(composite_type.fields.len(), 5);
assert_eq!(composite_type.fields[0].name, "id");
assert_eq!(composite_type.fields[0].field_type, "INTEGER");
assert_eq!(composite_type.fields[4].name, "is_active");
assert_eq!(composite_type.fields[4].field_type, "BOOLEAN");
}
#[test]
fn test_composite_type_with_comment() {
let composite_type = CompositeTypeBuilder::new()
.name("coordinates")
.field("latitude", "DOUBLE PRECISION")
.field("longitude", "DOUBLE PRECISION")
.comment("Geographic coordinates in decimal degrees")
.build()
.unwrap();
assert_eq!(composite_type.name, "coordinates");
}
#[test]
fn test_validation_errors() {
let result = CompositeTypeBuilder::new().name("test").build();
assert!(result.is_err());
assert!(matches!(
result.unwrap_err(),
CompositeTypeBuildError::ValidationError(_)
));
let result = CompositeTypeBuilder::new()
.name("test")
.field("", "TEXT")
.build();
assert!(result.is_err());
assert!(matches!(
result.unwrap_err(),
CompositeTypeBuildError::ValidationError(_)
));
}
#[test]
fn test_conditional_builder() {
let condition = true;
let composite_type = CompositeTypeBuilder::new()
.when(condition, |c| {
c.set_name("point_when_true");
c.add_field("x", "DOUBLE PRECISION");
c.add_field("y", "DOUBLE PRECISION");
})
.build()
.unwrap();
assert_eq!(composite_type.name, "point_when_true");
assert_eq!(composite_type.fields.len(), 2);
}
#[test]
fn test_inspection_methods() {
let builder = CompositeTypeBuilder::new()
.name("test_type")
.in_schema("public")
.fields(vec![("field1", "TEXT"), ("field2", "INTEGER")]);
assert_eq!(builder.get_name(), Some("test_type"));
assert_eq!(builder.get_schema(), Some("public"));
assert_eq!(builder.get_fields().len(), 2);
assert_eq!(builder.field_count(), 2);
assert!(builder.has_field("field1"));
assert!(!builder.has_field("nonexistent"));
assert!(builder.has_name());
assert!(builder.has_schema());
assert!(builder.has_fields());
assert!(!builder.has_comment());
let field = builder.get_field("field1");
assert!(field.is_some());
assert_eq!(field.unwrap().name, "field1");
assert_eq!(field.unwrap().field_type, "TEXT");
}
#[test]
fn test_debug_info_and_summary() {
let builder = CompositeTypeBuilder::new()
.name("point_3d")
.in_schema("geometry")
.fields(vec![
("x", "DOUBLE PRECISION"),
("y", "DOUBLE PRECISION"),
("z", "DOUBLE PRECISION"),
])
.comment("3D point coordinates");
let debug_info = builder.debug_info();
let summary = builder.summary();
assert!(debug_info.contains("CompositeTypeBuilder"));
assert!(debug_info.contains("point_3d"));
assert!(debug_info.contains("geometry"));
assert!(summary.contains("Composite type"));
assert!(summary.contains("geometry.point_3d"));
assert!(summary.contains("with fields: x: \"DOUBLE PRECISION\", y: \"DOUBLE PRECISION\", z: \"DOUBLE PRECISION\""));
assert!(summary.contains("with comment: 3D point coordinates"));
}
#[test]
fn test_geometric_types() {
let point = CompositeTypeBuilder::point()
.name("point_2d")
.build()
.unwrap();
let circle = CompositeTypeBuilder::circle()
.name("circle_2d")
.build()
.unwrap();
let line = CompositeTypeBuilder::line()
.name("line_2d")
.build()
.unwrap();
assert_eq!(point.fields.len(), 2);
assert_eq!(circle.fields.len(), 3);
assert_eq!(line.fields.len(), 4);
}
#[test]
fn test_business_types() {
let money = CompositeTypeBuilder::money()
.name("currency_amount")
.build()
.unwrap();
let date_range = CompositeTypeBuilder::date_range()
.name("period")
.build()
.unwrap();
let contact = CompositeTypeBuilder::contact_info()
.name("contact_details")
.build()
.unwrap();
assert_eq!(money.fields.len(), 2);
assert_eq!(date_range.fields.len(), 2);
assert_eq!(contact.fields.len(), 3);
}
}