ignis-db 0.2.0

A comprehensive PostgreSQL ORM with macro-driven schema management
Documentation
//! Schema Builder for Ignis-DB
//!
//! This module provides a builder for creating database schemas.

use crate::builders::traits::{
    ConditionalBuilder, InspectableBuilder, SchemaBuilder as SchemaBuilderTrait, ValidatableBuilder,
};
use crate::builders::validation::BuilderValidationError;

/// Builder for constructing database schemas
#[derive(Debug, Clone)]
pub struct DatabaseSchemaBuilder {
    name: String,
    comment: Option<String>,
    owner: Option<String>,
    if_not_exists: bool,
}

impl DatabaseSchemaBuilder {
    /// Create a new schema builder
    ///
    /// # Parameters
    ///
    /// - `name`: The name of the schema
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ignis_db::builders::SchemaBuilder;
    ///
    /// let schema = SchemaBuilder::new("my_schema");
    /// ```
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            comment: None,
            owner: None,
            if_not_exists: true,
        }
    }

    /// Set a comment for the schema
    ///
    /// # Parameters
    ///
    /// - `comment`: The comment text
    ///
    /// # Examples
    ///
    /// ```rust
    /// let schema = SchemaBuilder::new("my_schema")
    ///     .comment("Schema for user data");
    /// ```
    pub fn comment(mut self, comment: impl Into<String>) -> Self {
        self.comment = Some(comment.into());
        self
    }

    /// Set the owner of the schema
    ///
    /// # Parameters
    ///
    /// - `owner`: The owner role name
    ///
    /// # Examples
    ///
    /// ```rust
    /// let schema = SchemaBuilder::new("my_schema")
    ///     .owner("my_user");
    /// ```
    pub fn owner(mut self, owner: impl Into<String>) -> Self {
        self.owner = Some(owner.into());
        self
    }

    /// Set whether to use IF NOT EXISTS
    ///
    /// # Parameters
    ///
    /// - `if_not_exists`: Whether to use IF NOT EXISTS
    ///
    /// # Examples
    ///
    /// ```rust
    /// let schema = SchemaBuilder::new("my_schema")
    ///     .if_not_exists(false);
    /// ```
    pub fn if_not_exists(mut self, if_not_exists: bool) -> Self {
        self.if_not_exists = if_not_exists;
        self
    }

    /// Get the schema name
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Get the comment
    pub fn get_comment(&self) -> Option<&str> {
        self.comment.as_deref()
    }

    /// Get the owner
    pub fn get_owner(&self) -> Option<&str> {
        self.owner.as_deref()
    }

    /// Check if IF NOT EXISTS is enabled
    pub fn is_if_not_exists(&self) -> bool {
        self.if_not_exists
    }

    /// Generate the CREATE SCHEMA SQL
    pub fn to_sql(&self) -> String {
        let mut sql = String::new();

        sql.push_str("CREATE SCHEMA");

        if self.if_not_exists {
            sql.push_str(" IF NOT EXISTS");
        }

        sql.push_str(&format!(" \"{}\"", self.name));

        if let Some(ref owner) = self.owner {
            sql.push_str(&format!(" AUTHORIZATION \"{}\"", owner));
        }

        if let Some(ref comment) = self.comment {
            sql.push_str(&format!(
                "; COMMENT ON SCHEMA \"{}\" IS {}",
                self.name, comment
            ));
        }

        sql.push(';');
        sql
    }
}

impl SchemaBuilderTrait for DatabaseSchemaBuilder {
    type Output = String; // Returns the SQL string
    type Error = BuilderValidationError;

    fn build(self) -> Result<Self::Output, Self::Error> {
        // Validate the configuration
        if !self.is_valid() {
            let errors = self.validation_errors();
            return Err(BuilderValidationError::Generic(format!(
                "SchemaBuilder validation failed: {}",
                errors.join(", ")
            )));
        }

        // Return the SQL string
        Ok(self.to_sql())
    }
}

impl ValidatableBuilder for DatabaseSchemaBuilder {
    fn is_valid(&self) -> bool {
        // Validate schema name
        if self.name.is_empty() {
            return false;
        }

        // Validate schema name format (basic validation)
        if !self.name.chars().all(|c| c.is_alphanumeric() || c == '_') {
            return false;
        }

        true
    }

    fn validation_errors(&self) -> Vec<String> {
        let mut errors = Vec::new();

        // Validate schema name
        if self.name.is_empty() {
            errors.push("Schema name cannot be empty".to_string());
        }

        // Validate schema name format (basic validation)
        if !self.name.chars().all(|c| c.is_alphanumeric() || c == '_') {
            errors.push("Schema name contains invalid characters".to_string());
        }

        errors
    }
}

impl ConditionalBuilder for DatabaseSchemaBuilder {
    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 DatabaseSchemaBuilder {
    fn debug_info(&self) -> String {
        format!(
            "SchemaBuilder {{\n  name: {:?},\n  comment: {:?},\n  owner: {:?},\n  if_not_exists: {}\n}}",
            self.name, self.comment, self.owner, self.if_not_exists
        )
    }

    fn summary(&self) -> String {
        format!("Schema '{}'", self.name)
    }
}

/// Helper function to create a schema builder
pub fn schema(name: impl Into<String>) -> DatabaseSchemaBuilder {
    DatabaseSchemaBuilder::new(name)
}

/// Helper function to extract schema name from a schema-qualified identifier
///
/// # Parameters
///
/// - `qualified_name`: A schema-qualified name like "auth.users" or "public.table"
///
/// # Returns
///
/// - `Some(schema_name)` if the name is schema-qualified
/// - `None` if the name is not schema-qualified
///
/// # Examples
///
/// ```rust
/// use ignis_db::builders::schema::extract_schema_name;
///
/// assert_eq!(extract_schema_name("auth.users"), Some("auth"));
/// assert_eq!(extract_schema_name("users"), None);
/// assert_eq!(extract_schema_name("public.my_table"), Some("public"));
/// ```
pub fn extract_schema_name(qualified_name: &str) -> Option<&str> {
    if let Some(dot_pos) = qualified_name.find('.') {
        Some(&qualified_name[..dot_pos])
    } else {
        None
    }
}

/// Helper function to extract table name from a schema-qualified identifier
///
/// # Parameters
///
/// - `qualified_name`: A schema-qualified name like "auth.users" or "public.table"
///
/// # Returns
///
/// - The table name part (everything after the dot, or the whole string if no dot)
///
/// # Examples
///
/// ```rust
/// use ignis_db::builders::schema::extract_table_name;
///
/// assert_eq!(extract_table_name("auth.users"), "users");
/// assert_eq!(extract_table_name("users"), "users");
/// assert_eq!(extract_table_name("public.my_table"), "my_table");
/// ```
pub fn extract_table_name(qualified_name: &str) -> &str {
    if let Some(dot_pos) = qualified_name.find('.') {
        &qualified_name[dot_pos + 1..]
    } else {
        qualified_name
    }
}