ignis-db 0.2.0

A comprehensive PostgreSQL ORM with macro-driven schema management
Documentation
//! Core Builder Traits for Ignis-DB
//!
//! This module defines the fundamental traits that all builders implement,
//! providing a consistent interface for schema object construction.

/// Core trait for all schema builders
///
/// This trait defines the common interface that all builders must implement.
/// It ensures that every builder has a `build()` method that produces
/// the final schema object.
///
/// # Generic Parameters
///
/// - `Output`: The type of schema object that this builder produces
///
/// # Examples
///
/// ```rust
/// use ignis_db::builders::SchemaBuilder;
///
/// // All builders implement this trait
/// let table_builder: TableBuilder = TableBuilder::new("users");
/// let column_builder: ColumnBuilder = ColumnBuilder::new("id", ColumnType::Int4);
///
/// // All can be built into their final form
/// let table = table_builder.build()?;
/// let column = column_builder.build()?;
/// ```
pub trait SchemaBuilder {
    /// The type of schema object that this builder produces
    type Output;

    /// The type of error that can occur during building
    type Error;

    /// Build the final schema object from the builder configuration
    ///
    /// This method consumes the builder and returns either the final
    /// schema object or an error if the configuration is invalid.
    ///
    /// # Returns
    ///
    /// - `Ok(Output)`: The successfully built schema object
    /// - `Err(Error)`: An error describing what went wrong during building
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ignis_db::builders::{TableBuilder, ColumnBuilder};
    ///
    /// let table = TableBuilder::new("users")
    ///     .column(ColumnBuilder::new("id", ColumnType::Int4).primary_key())
    ///     .build()?; // Returns Result<Table, TableBuildError>
    /// ```
    fn build(self) -> Result<Self::Output, Self::Error>;
}

/// Trait for builders that can be validated before building
///
/// This trait provides a way to validate builder configuration
/// without consuming the builder. This is useful for checking
/// configuration validity before attempting to build.
///
/// # Examples
///
/// ```rust
/// use ignis_db::builders::ValidatableBuilder;
///
/// let table_builder = TableBuilder::new("users");
///
/// // Check if the configuration is valid
/// if table_builder.is_valid() {
///     let table = table_builder.build()?;
/// } else {
///     // Handle validation errors
///     for error in table_builder.validation_errors() {
///         eprintln!("Validation error: {}", error);
///     }
/// }
/// ```
pub trait ValidatableBuilder: SchemaBuilder {
    /// Check if the current builder configuration is valid
    ///
    /// This method performs validation without consuming the builder.
    /// It returns `true` if the configuration is valid, `false` otherwise.
    ///
    /// # Returns
    ///
    /// `true` if the configuration is valid, `false` otherwise
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ignis_db::builders::ValidatableBuilder;
    ///
    /// let table_builder = TableBuilder::new("users");
    ///
    /// if table_builder.is_valid() {
    ///     println!("Configuration is valid!");
    /// } else {
    ///     println!("Configuration has validation errors");
    /// }
    /// ```
    fn is_valid(&self) -> bool;

    /// Get a list of validation errors for the current configuration
    ///
    /// This method returns a collection of validation errors without
    /// consuming the builder. If there are no errors, an empty collection
    /// is returned.
    ///
    /// # Returns
    ///
    /// A collection of validation errors, or an empty collection if valid
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ignis_db::builders::ValidatableBuilder;
    ///
    /// let table_builder = TableBuilder::new("users");
    ///
    /// for error in table_builder.validation_errors() {
    ///     eprintln!("Validation error: {}", error);
    /// }
    /// ```
    fn validation_errors(&self) -> Vec<String>;
}

/// Trait for builders that support conditional configuration
///
/// This trait provides methods for conditionally applying configuration
/// based on runtime conditions. This is useful for building schemas
/// that depend on external factors or configuration.
///
/// # Examples
///
/// ```rust
/// use ignis_db::builders::ConditionalBuilder;
///
/// let is_production = std::env::var("ENV").unwrap_or_default() == "production";
///
/// let table = TableBuilder::new("users")
///     .column(ColumnBuilder::new("id", ColumnType::Int4).primary_key())
///     .when(is_production, |t| t.comment("Production users table"))
///     .when(!is_production, |t| t.comment("Development users table"))
///     .build()?;
/// ```
pub trait ConditionalBuilder: SchemaBuilder {
    /// Apply configuration conditionally
    ///
    /// This method applies the given configuration function only if
    /// the condition is true. The function receives a mutable reference
    /// to the builder and can modify it as needed.
    ///
    /// # Parameters
    ///
    /// - `condition`: The condition that determines whether to apply the configuration
    /// - `config_fn`: A function that takes a mutable reference to the builder and modifies it
    ///
    /// # Returns
    ///
    /// `self` for method chaining
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ignis_db::builders::ConditionalBuilder;
    ///
    /// let table = TableBuilder::new("users")
    ///     .column(ColumnBuilder::new("id", ColumnType::Int4).primary_key())
    ///     .when(true, |t| t.comment("This comment will be applied"))
    ///     .when(false, |t| t.comment("This comment will NOT be applied"))
    ///     .build()?;
    /// ```
    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
    }

    /// Apply configuration conditionally with a default fallback
    ///
    /// This method applies one configuration function if the condition is true,
    /// and a different configuration function if the condition is false.
    ///
    /// # Parameters
    ///
    /// - `condition`: The condition that determines which configuration to apply
    /// - `if_true`: Function to apply when condition is true
    /// - `if_false`: Function to apply when condition is false
    ///
    /// # Returns
    ///
    /// `self` for method chaining
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ignis_db::builders::ConditionalBuilder;
    ///
    /// let is_production = std::env::var("ENV").unwrap_or_default() == "production";
    ///
    /// let table = TableBuilder::new("users")
    ///     .column(ColumnBuilder::new("id", ColumnType::Int4).primary_key())
    ///     .when_else(
    ///         is_production,
    ///         |t| t.comment("Production table"),
    ///         |t| t.comment("Development table")
    ///     )
    ///     .build()?;
    /// ```
    fn when_else<F, G>(mut self, condition: bool, if_true: F, if_false: G) -> Self
    where
        F: FnOnce(&mut Self),
        G: FnOnce(&mut Self),
        Self: Sized,
    {
        if condition {
            if_true(&mut self);
        } else {
            if_false(&mut self);
        }
        self
    }
}

/// Trait for builders that can be cloned for modification
///
/// This trait provides methods for creating modified copies of builders
/// without consuming the original. This is useful for creating multiple
/// variations of a schema or for testing different configurations.
///
/// # Examples
///
/// ```rust
/// use ignis_db::builders::CloneableBuilder;
///
/// let base_table = TableBuilder::new("users")
///     .column(ColumnBuilder::new("id", ColumnType::Int4).primary_key());
///
/// // Create a development version
/// let dev_table = base_table.clone()
///     .comment("Development users table")
///     .build()?;
///
/// // Create a production version
/// let prod_table = base_table.clone()
///     .comment("Production users table")
///     .build()?;
/// ```
pub trait CloneableBuilder: SchemaBuilder + Clone {
    /// Create a modified copy of this builder
    ///
    /// This method creates a new builder with the same configuration
    /// as the current one, allowing you to modify it without affecting
    /// the original.
    ///
    /// # Parameters
    ///
    /// - `modify_fn`: A function that takes a mutable reference to the new builder and modifies it
    ///
    /// # Returns
    ///
    /// A new builder with the modified configuration
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ignis_db::builders::CloneableBuilder;
    ///
    /// let base_table = TableBuilder::new("users")
    ///     .column(ColumnBuilder::new("id", ColumnType::Int4).primary_key());
    ///
    /// let modified_table = base_table.modify(|t| {
    ///     t.comment("Modified table");
    /// });
    ///
    /// // Both builders can now be used independently
    /// let table1 = base_table.build()?;
    /// let table2 = modified_table.build()?;
    /// ```
    fn modify<F>(self, modify_fn: F) -> Self
    where
        F: FnOnce(&mut Self),
        Self: Sized,
    {
        let mut new_builder = self.clone();
        modify_fn(&mut new_builder);
        new_builder
    }
}

/// Trait for builders that support debugging and inspection
///
/// This trait provides methods for inspecting the current state of a builder
/// without consuming it. This is useful for debugging, logging, and
/// understanding what configuration has been applied.
///
/// # Examples
///
/// ```rust
/// use ignis_db::builders::InspectableBuilder;
///
/// let table_builder = TableBuilder::new("users")
///     .column(ColumnBuilder::new("id", ColumnType::Int4).primary_key());
///
/// // Inspect the current configuration
/// println!("Table name: {}", table_builder.name());
/// println!("Column count: {}", table_builder.column_count());
/// println!("Has primary key: {}", table_builder.has_primary_key());
/// ```
pub trait InspectableBuilder: SchemaBuilder {
    /// Get a debug representation of the current builder state
    ///
    /// This method returns a debug representation that shows the current
    /// configuration of the builder. This is useful for debugging and
    /// understanding what has been configured.
    ///
    /// # Returns
    ///
    /// A debug representation of the builder state
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ignis_db::builders::InspectableBuilder;
    ///
    /// let table_builder = TableBuilder::new("users")
    ///     .column(ColumnBuilder::new("id", ColumnType::Int4).primary_key());
    ///
    /// println!("Builder state: {:?}", table_builder.debug_info());
    /// ```
    fn debug_info(&self) -> String;

    /// Get a summary of the current configuration
    ///
    /// This method returns a human-readable summary of the current
    /// builder configuration. This is useful for logging and user
    /// feedback.
    ///
    /// # Returns
    ///
    /// A human-readable summary of the configuration
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ignis_db::builders::InspectableBuilder;
    ///
    /// let table_builder = TableBuilder::new("users")
    ///     .column(ColumnBuilder::new("id", ColumnType::Int4).primary_key());
    ///
    /// println!("Configuration summary: {}", table_builder.summary());
    /// ```
    fn summary(&self) -> String;
}

// Re-export commonly used traits
pub use CloneableBuilder as Cloneable;
pub use ConditionalBuilder as Conditional;
pub use InspectableBuilder as Inspectable;
pub use SchemaBuilder as Builder;
pub use ValidatableBuilder as Validatable;

/// Trait for column builders specifically
pub trait ColumnBuilderTrait: SchemaBuilder<Output = crate::schema::Column> {
    fn nullable(self) -> Self;
    fn not_null(self) -> Self;
    fn default(self, default: impl Into<String>) -> Self;
    fn primary_key(self) -> Self;
    fn unique(self) -> Self;
}