ignis-db 0.2.0

A comprehensive PostgreSQL ORM with macro-driven schema management
Documentation
//! PostgreSQL composite type support for Ignis

use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// Represents a PostgreSQL composite type field
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CompositeField {
    pub name: String,
    pub field_type: String,
    pub nullable: bool,
}

/// Represents a PostgreSQL composite type
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CompositeType {
    pub name: String,
    pub fields: Vec<CompositeField>,
    pub schema: Option<String>,
}

impl CompositeType {
    /// Create a new composite type
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            fields: Vec::new(),
            schema: None,
        }
    }

    /// Add a field to the composite type
    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
    }

    /// Set the schema for the composite type
    pub fn with_schema(mut self, schema: impl Into<String>) -> Self {
        self.schema = Some(schema.into());
        self
    }

    /// Generate CREATE TYPE DDL
    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| {
                // PostgreSQL composite types do not support NOT NULL constraints on individual fields
                // The nullability is handled when the composite type is used as a column
                format!("    \"{}\" {}", field.name, field.field_type)
            })
            .collect();

        format!(
            "CREATE TYPE {}\"{}\" AS (\n{}\n);",
            schema_prefix,
            self.name,
            field_definitions.join(",\n")
        )
    }

    /// Generate DROP TYPE DDL
    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
        )
    }

    /// Get the full type name including schema with proper escaping
    pub fn full_name(&self) -> String {
        match &self.schema {
            Some(schema) => format!("\"{}\".\"{}\"", schema, self.name),
            None => format!("\"{}\"", self.name),
        }
    }
}

/// Registry for composite types to support migrations
pub struct CompositeTypeRegistry {
    types: HashMap<String, CompositeType>,
}

impl CompositeTypeRegistry {
    /// Create a new registry
    pub fn new() -> Self {
        Self {
            types: HashMap::new(),
        }
    }

    /// Register a composite type
    pub fn register(&mut self, composite_type: CompositeType) {
        self.types
            .insert(composite_type.full_name(), composite_type);
    }

    /// Get all registered composite types
    pub fn all_types(&self) -> impl Iterator<Item = &CompositeType> {
        self.types.values()
    }

    /// Get a specific composite type by name
    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)"));
        // PostgreSQL composite types do not support NOT NULL constraints on individual fields
        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());
    }
}