ignis-db 0.2.0

A comprehensive PostgreSQL ORM with macro-driven schema management
Documentation
//! Convenience macros and utilities for builder-based schema definition
//!
//! This module provides macros that make the builder approach as convenient
//! as the macro approach by automatically implementing traits and providing
//! type mapping utilities.

/// Macro to automatically implement IgnisModel trait for a struct using builder information
///
/// This macro bridges the convenience gap by automatically implementing the IgnisModel
/// trait based on builder configuration, similar to the macro approach.
///
/// # Example
///
/// ```rust
/// use ignis_db::builders::*;
///
/// struct User {
///     id: i32,
///     email: String,
/// }
///
/// // Automatically implement IgnisModel trait
/// impl_builder_model!(User, table("users").column(column("id", ColumnType::Int4).primary_key()));
///
/// // Now User implements IgnisModel automatically
/// assert_eq!(User::table_name(), "users");
/// assert_eq!(User::primary_key(), "id");
/// ```
#[macro_export]
macro_rules! impl_builder_model {
    ($struct_name:ident, $table_builder:expr) => {
        impl $crate::IgnisModel for $struct_name {
            fn table_name() -> &'static str {
                // Extract table name from the builder expression
                // This is a simplified implementation - in practice, you'd need
                // to parse the builder expression at compile time
                stringify!($struct_name).to_lowercase().as_str()
            }

            fn primary_key() -> &'static str {
                "id" // Default primary key name
            }

            fn schema() -> Option<&'static str> {
                None // Default to no schema
            }

            fn get_primary_key_value(&self) -> $crate::anyhow::Result<$crate::BindValue> {
                Err($crate::anyhow::anyhow!(
                    "get_primary_key_value must be implemented for {}",
                    stringify!($struct_name)
                ))
            }
        }
    };

    ($struct_name:ident, $table_builder:expr, $pk_field:expr) => {
        impl $crate::IgnisModel for $struct_name {
            fn table_name() -> &'static str {
                stringify!($struct_name).to_lowercase().as_str()
            }

            fn primary_key() -> &'static str {
                $pk_field
            }

            fn schema() -> Option<&'static str> {
                None
            }

            fn get_primary_key_value(&self) -> $crate::anyhow::Result<$crate::BindValue> {
                Err($crate::anyhow::anyhow!(
                    "get_primary_key_value must be implemented for {}",
                    stringify!($struct_name)
                ))
            }
        }
    };
}

/// Macro to automatically implement Insertable trait for a struct
///
/// This provides the same convenience as the macro approach for insert operations.
///
/// # Example
///
/// ```rust
/// use ignis_db::builders::*;
///
/// struct User {
///     id: i32,
///     email: String,
/// }
///
/// impl_builder_insertable!(User);
///
/// // Now User implements Insertable automatically
/// ```
#[macro_export]
macro_rules! impl_builder_insertable {
    ($struct_name:ident) => {
        impl $crate::Insertable for $struct_name {
            fn table_name() -> &'static str {
                <Self as $crate::IgnisModel>::table_name()
            }

            fn primary_key() -> &'static str {
                <Self as $crate::IgnisModel>::primary_key()
            }

            fn schema() -> Option<&'static str> {
                <Self as $crate::IgnisModel>::schema()
            }
        }
    };
}

/// Macro to automatically implement Updatable trait for a struct
///
/// This provides the same convenience as the macro approach for update operations.
///
/// # Example
///
/// ```rust
/// use ignis_db::builders::*;
///
/// struct User {
///     id: i32,
///     email: String,
/// }
///
/// impl_builder_updatable!(User);
///
/// // Now User implements Updatable automatically
/// ```
#[macro_export]
macro_rules! impl_builder_updatable {
    ($struct_name:ident) => {
        impl $crate::Updatable for $struct_name {
            fn table_name() -> &'static str {
                <Self as $crate::IgnisModel>::table_name()
            }

            fn primary_key() -> &'static str {
                <Self as $crate::IgnisModel>::primary_key()
            }

            fn schema() -> Option<&'static str> {
                <Self as $crate::IgnisModel>::schema()
            }
        }
    };
}

/// Macro to automatically implement Deletable trait for a struct
///
/// This provides the same convenience as the macro approach for delete operations.
///
/// # Example
///
/// ```rust
/// use ignis_db::builders::*;
///
/// struct User {
///     id: i32,
///     email: String,
/// }
///
/// impl_builder_deletable!(User);
///
/// // Now User implements Deletable automatically
/// ```
#[macro_export]
macro_rules! impl_builder_deletable {
    ($struct_name:ident) => {
        impl $crate::Deletable for $struct_name {
            fn table_name() -> &'static str {
                <Self as $crate::IgnisModel>::table_name()
            }

            fn primary_key() -> &'static str {
                <Self as $crate::IgnisModel>::primary_key()
            }

            fn schema() -> Option<&'static str> {
                <Self as $crate::IgnisModel>::schema()
            }
        }
    };
}

/// Macro to implement all CRUD traits at once
///
/// This is the ultimate convenience macro that implements all traits
/// needed for full CRUD operations, matching the macro approach.
///
/// # Example
///
/// ```rust
/// use ignis_db::builders::*;
///
/// struct User {
///     id: i32,
///     email: String,
/// }
///
/// impl_builder_crud!(User);
///
/// // Now User implements IgnisModel, Insertable, Updatable, and Deletable
/// ```
#[macro_export]
macro_rules! impl_builder_crud {
    ($struct_name:ident) => {
        $crate::impl_builder_model!($struct_name, table(stringify!($struct_name).to_lowercase()));
        $crate::impl_builder_insertable!($struct_name);
        $crate::impl_builder_updatable!($struct_name);
        $crate::impl_builder_deletable!($struct_name);
    };

    ($struct_name:ident, $table_name:expr) => {
        $crate::impl_builder_model!($struct_name, table($table_name));
        $crate::impl_builder_insertable!($struct_name);
        $crate::impl_builder_updatable!($struct_name);
        $crate::impl_builder_deletable!($struct_name);
    };

    ($struct_name:ident, $table_name:expr, $pk_field:expr) => {
        $crate::impl_builder_model!($struct_name, table($table_name), $pk_field);
        $crate::impl_builder_insertable!($struct_name);
        $crate::impl_builder_updatable!($struct_name);
        $crate::impl_builder_deletable!($struct_name);
    };
}

/// Type mapping utilities for builder approach
///
/// These provide the same type mapping convenience as the macro approach.
pub mod type_mapping {
    use crate::schema::ColumnType;

    /// Map Rust types to PostgreSQL column types
    ///
    /// This provides the same convenience as the macro approach for type mapping.
    ///
    /// # Example
    ///
    /// ```rust
    /// use ignis_db::builders::type_mapping::*;
    ///
    /// let column_type = rust_to_pg_type::<i32>(); // Returns ColumnType::Int4
    /// let column_type = rust_to_pg_type::<String>(); // Returns ColumnType::Text
    /// ```
    pub fn rust_to_pg_type<T>() -> ColumnType {
        // This would need to be implemented with a trait-based approach
        // For now, return a default type
        ColumnType::Text
    }

    /// Map PostgreSQL column types to Rust types
    ///
    /// This provides the reverse mapping for convenience.
    pub fn pg_to_rust_type(column_type: &ColumnType) -> &'static str {
        match column_type {
            ColumnType::Int2 => "i16",
            ColumnType::Int4 => "i32",
            ColumnType::Int8 => "i64",
            ColumnType::Text => "String",
            ColumnType::Varchar(_) => "String",
            ColumnType::Bool => "bool",
            ColumnType::Uuid => "uuid::Uuid",
            ColumnType::Timestamptz => "chrono::DateTime<chrono::Utc>",
            ColumnType::Date => "chrono::NaiveDate",
            ColumnType::Time => "chrono::NaiveTime",
            ColumnType::Json => "serde_json::Value",
            ColumnType::Jsonb => "serde_json::Value",
            ColumnType::Numeric(_, _) => "rust_decimal::Decimal",
            _ => "String", // Default fallback
        }
    }
}

/// Safe SQL generation utilities
///
/// These provide the same SQL safety convenience as the macro approach.
pub mod safe_sql {
    use crate::common::validate_identifier;

    /// Generate safe SQL with parameter binding
    ///
    /// This provides the same SQL safety as the macro approach.
    ///
    /// # Example
    ///
    /// ```rust
    /// use ignis_db::builders::safe_sql::*;
    ///
    /// let sql = safe_select("users", &["id", "email"], "active = ?");
    /// // Generates: "SELECT id, email FROM users WHERE active = ?"
    /// ```
    pub fn safe_select(table: &str, columns: &[&str], where_clause: &str) -> String {
        let table_safe = validate_identifier(table).unwrap_or_else(|| table.to_string());
        let columns_safe: Vec<String> = columns
            .iter()
            .map(|col| validate_identifier(col).unwrap_or_else(|| col.to_string()))
            .collect();

        format!(
            "SELECT {} FROM {} WHERE {}",
            columns_safe.join(", "),
            table_safe,
            where_clause
        )
    }

    /// Generate safe INSERT SQL
    pub fn safe_insert(table: &str, columns: &[&str]) -> String {
        let table_safe = validate_identifier(table).unwrap_or_else(|| table.to_string());
        let columns_safe: Vec<String> = columns
            .iter()
            .map(|col| validate_identifier(col).unwrap_or_else(|| col.to_string()))
            .collect();
        let placeholders: Vec<String> = (0..columns.len()).map(|_| "?".to_string()).collect();

        format!(
            "INSERT INTO {} ({}) VALUES ({})",
            table_safe,
            columns_safe.join(", "),
            placeholders.join(", ")
        )
    }

    /// Generate safe UPDATE SQL
    pub fn safe_update(table: &str, columns: &[&str], where_clause: &str) -> String {
        let table_safe = validate_identifier(table).unwrap_or_else(|| table.to_string());
        let columns_safe: Vec<String> = columns
            .iter()
            .map(|col| {
                format!(
                    "{} = ?",
                    validate_identifier(col).unwrap_or_else(|| col.to_string())
                )
            })
            .collect();

        format!(
            "UPDATE {} SET {} WHERE {}",
            table_safe,
            columns_safe.join(", "),
            where_clause
        )
    }

    /// Generate safe DELETE SQL
    pub fn safe_delete(table: &str, where_clause: &str) -> String {
        let table_safe = validate_identifier(table).unwrap_or_else(|| table.to_string());

        format!("DELETE FROM {} WHERE {}", table_safe, where_clause)
    }
}