ignis-db 0.2.0

A comprehensive PostgreSQL ORM with macro-driven schema management
Documentation
//! Ignis: A comprehensive PostgreSQL ORM with macro-driven schema management
//!
//! This crate provides compile-time type safety with sqlx execution,
//! comprehensive macro system, and sophisticated migration management.

pub mod builders;
pub mod code_parsing;
pub mod codegen;
pub mod common;
pub mod config;
pub mod connection;
pub mod database;
pub mod dsl;
pub mod exec;
pub mod introspection;
pub mod macros;
pub mod migrate;
pub mod schema;

// Re-export commonly used items
pub use connection::{ConnectionManager, PoolStats};
pub use database::{Database, DatabaseConfig, DatabaseType, MySQL, PostgreSQL};
pub use dsl::{
    call_function, call_procedure, Column as DslColumn, CompositeField, CompositeFieldBuilder,
    CompositeFieldRef, FunctionCall, ProcedureCall, Query, Source,
};
pub use exec::transaction::{
    execute_transaction, IsolationLevel, TransactionConfig, TransactionManager,
};
pub use schema::{
    Column, ColumnType, CompositeField as SchemaCompositeField, CompositeType, IndexMeta,
    IndexType, StoredFunction, StoredProcedure, Table, TableMeta, Trigger, TriggerEvent,
    TriggerOrientation, TriggerTiming,
};

// Re-export derive macros
pub use ignis_derive::*;

// Note: table! macro is automatically exported due to #[macro_export]

// Re-export common types for derive macros
pub use anyhow::{anyhow, Result};

/// Core trait that all Ignis objects must implement
pub trait IgnisObject: Send + Sync {
    /// Get the name of this object
    fn name(&self) -> &str;

    /// Get the schema this object belongs to (if any)
    fn schema(&self) -> Option<&str>;

    /// Get the DDL for creating this object
    fn ddl(&self) -> &str;

    /// Get the type of this object
    fn object_type(&self) -> &str;
}

/// Schema object that can be registered in the inventory system
#[derive(Debug, Clone)]
pub struct SchemaObject {
    pub kind: &'static str,
    pub name: &'static str,
    pub ddl: &'static str,
    pub schema: Option<&'static str>,
}

impl IgnisObject for SchemaObject {
    #[inline]
    fn name(&self) -> &str {
        self.name
    }

    #[inline]
    fn schema(&self) -> Option<&str> {
        self.schema
    }

    #[inline]
    fn ddl(&self) -> &str {
        self.ddl
    }

    #[inline]
    fn object_type(&self) -> &str {
        self.kind
    }
}

/// Wrapper type for inventory registration
pub struct RegisteredObject(pub SchemaObject);

// Automatic registration via inventory
inventory::collect!(RegisteredObject);

/// Type alias for registered objects in the inventory
pub type RegisteredObjectRef = &'static RegisteredObject;

/// Get an iterator over all registered schema objects
pub fn iter_registered() -> impl Iterator<Item = &'static RegisteredObject> {
    inventory::iter::<RegisteredObject>()
}

/// Get all registered objects of a specific type
pub fn get_registered_by_type(
    object_type: &str,
) -> impl Iterator<Item = &'static RegisteredObject> + '_ {
    iter_registered().filter(move |obj| obj.0.object_type() == object_type)
}

/// Get all registered tables
pub fn get_registered_tables() -> impl Iterator<Item = &'static RegisteredObject> {
    get_registered_by_type("table")
}

/// Get all registered views
pub fn get_registered_views() -> impl Iterator<Item = &'static RegisteredObject> {
    get_registered_by_type("view")
}

/// Get all registered procedures
pub fn get_registered_procedures() -> impl Iterator<Item = &'static RegisteredObject> {
    get_registered_by_type("procedure")
}

/// Get all registered functions
pub fn get_registered_functions() -> impl Iterator<Item = &'static RegisteredObject> {
    get_registered_by_type("function")
}

/// Get all registered triggers
pub fn get_registered_triggers() -> impl Iterator<Item = &'static RegisteredObject> {
    get_registered_by_type("trigger")
}

/// Get all registered events
pub fn get_registered_events() -> impl Iterator<Item = &'static RegisteredObject> {
    get_registered_by_type("event")
}

// Model traits for CRUD operations
pub trait IgnisModel {
    const TABLE: &'static str;
    const PK: &'static str; // For single PK or comma-separated list for composite
    const SCHEMA: Option<&'static str>;
    const FULL_TABLE_NAME: &'static str;

    fn get_primary_key_value(&self) -> anyhow::Result<BindValue>;
    fn get_composite_key_values(&self) -> anyhow::Result<Vec<(&'static str, BindValue)>> {
        // Default implementation for single primary key
        Ok(vec![(Self::PK, self.get_primary_key_value()?)])
    }
}

pub trait Insertable {
    fn insert<'e, E>(
        &self,
        executor: E,
    ) -> impl std::future::Future<Output = sqlx::Result<u64>> + Send
    where
        E: sqlx::Executor<'e, Database = sqlx::Postgres>;
}

pub trait Updatable {
    fn update<'e, E>(
        &self,
        executor: E,
    ) -> impl std::future::Future<Output = sqlx::Result<u64>> + Send
    where
        E: sqlx::Executor<'e, Database = sqlx::Postgres>;
}

pub trait Deletable {
    fn delete<'e, E>(
        &self,
        executor: E,
    ) -> impl std::future::Future<Output = sqlx::Result<u64>> + Send
    where
        E: sqlx::Executor<'e, Database = sqlx::Postgres>;
}

// BindValue enum for type-safe parameter binding
// Re-export the consolidated BindValue from parameter_binding module
pub use macros::parameter_binding::BindValue;

// From implementations are now in the consolidated BindValue in parameter_binding module

#[cfg(test)]
mod tests {
    use super::*;

    // Test table definition
    crate::table! {
        users (id) {
            id -> Int4,
            email -> Varchar,
            created_at -> Timestamptz,
        }
    }

    #[test]
    fn test_table_macro() {
        // Test that the table module was created
        let table = users::table();
        assert_eq!(table.name, "users");
        assert_eq!(table.primary_key, Some("id".to_string()));
        assert_eq!(table.columns.len(), 3);

        // Test column accessors
        let id_col = users::id();
        assert_eq!(id_col.name, "id");

        let email_col = users::email();
        assert_eq!(email_col.name, "email");

        let created_at_col = users::created_at();
        assert_eq!(created_at_col.name, "created_at");
    }

    #[test]
    fn test_table_ddl_generation() {
        let table = users::table();
        let ddl = table.generate_ddl();

        // Verify the DDL contains expected elements
        assert!(ddl.contains("CREATE TABLE"));
        assert!(ddl.contains("\"users\""));
        assert!(ddl.contains("\"id\""));
        assert!(ddl.contains("\"email\""));
        assert!(ddl.contains("\"created_at\""));
        assert!(ddl.contains("PRIMARY KEY"));
        assert!(ddl.contains("INTEGER"));
        assert!(ddl.contains("VARCHAR"));
        assert!(ddl.contains("TIMESTAMPTZ"));
    }

    #[test]
    fn test_registered_tables() {
        // Test that tables are registered in the inventory
        let tables: Vec<_> = get_registered_tables().collect();
        assert!(!tables.is_empty());

        // Find our users table
        let users_table = tables.iter().find(|t| t.0.name == "users");
        assert!(users_table.is_some());

        if let Some(table) = users_table {
            assert_eq!(table.0.object_type(), "table");
            assert!(table.0.ddl.contains("CREATE TABLE"));
        }
    }
}