ignis-db 0.2.0

A comprehensive PostgreSQL ORM with macro-driven schema management
Documentation
//! Core database abstraction traits
//!
//! These traits define the interface for multi-platform database support.

use crate::migrate::Migration;
use crate::schema::{CompositeType, Grant, Index, Role, Table, View};
use anyhow::Result;
use std::collections::HashMap;

/// Core database abstraction trait
///
/// This trait defines the interface that all database implementations must provide.
/// It serves as the central point of abstraction for multi-platform support.
pub trait Database: Send + Sync {
    /// Get the database type
    fn database_type(&self) -> crate::database::DatabaseType;

    /// Get the database name
    fn name(&self) -> &str;

    /// Get the type mapping implementation
    fn type_mapping(&self) -> &dyn TypeMapping;

    /// Get the SQL generator implementation
    fn sql_generator(&self) -> &dyn SqlGenerator;

    /// Get the introspector implementation
    fn introspector(&self) -> &dyn Introspector;

    /// Get the connection manager implementation
    fn connection_manager(&self) -> &dyn ConnectionManager;

    /// Get the migration manager implementation
    fn migration_manager(&self) -> &dyn MigrationManager;
}

/// Type mapping trait for converting between Rust types and database-specific types
pub trait TypeMapping: Send + Sync {
    /// Convert a Rust type to a database-specific column type
    fn rust_to_sql_type(&self, rust_type: &str) -> String;

    /// Convert a database-specific type to a Rust type
    fn sql_to_rust_type(&self, sql_type: &str) -> String;

    /// Get the default value for a type
    fn default_value(&self, sql_type: &str) -> Option<String>;

    /// Check if a type supports auto-increment
    fn supports_auto_increment(&self, sql_type: &str) -> bool;

    /// Get the maximum length for a string type
    fn max_string_length(&self, sql_type: &str) -> Option<usize>;
}

/// SQL generator trait for creating database-specific SQL statements
pub trait SqlGenerator: Send + Sync {
    /// Generate CREATE TABLE SQL
    fn create_table_sql(&self, table: &Table) -> String;

    /// Generate CREATE VIEW SQL
    fn create_view_sql(&self, view: &View) -> String;

    /// Generate CREATE INDEX SQL
    fn create_index_sql(&self, index: &Index) -> String;

    /// Generate CREATE TYPE SQL (for composite types)
    fn create_type_sql(&self, composite_type: &CompositeType) -> String;

    /// Generate CREATE SCHEMA SQL
    fn create_schema_sql(&self, schema_name: &str) -> String;

    /// Generate ALTER TABLE SQL
    fn alter_table_sql(&self, table: &Table, changes: &[String]) -> String;

    /// Generate DROP TABLE SQL
    fn drop_table_sql(&self, table_name: &str) -> String;

    /// Generate DROP VIEW SQL
    fn drop_view_sql(&self, view_name: &str) -> String;

    /// Generate DROP INDEX SQL
    fn drop_index_sql(&self, index_name: &str) -> String;

    /// Generate INSERT SQL
    fn insert_sql(&self, table_name: &str, columns: &[String], values: &[String]) -> String;

    /// Generate UPDATE SQL
    fn update_sql(&self, table_name: &str, set_clause: &str, where_clause: &str) -> String;

    /// Generate DELETE SQL
    fn delete_sql(&self, table_name: &str, where_clause: &str) -> String;

    /// Generate SELECT SQL
    fn select_sql(
        &self,
        table_name: &str,
        columns: &[String],
        where_clause: Option<&str>,
    ) -> String;

    /// Quote an identifier (table name, column name, etc.)
    fn quote_identifier(&self, identifier: &str) -> String;

    /// Quote a string literal
    fn quote_string(&self, value: &str) -> String;

    /// Get the current timestamp function
    fn current_timestamp_function(&self) -> &str;

    /// Get the auto-increment keyword
    fn auto_increment_keyword(&self) -> &str;

    /// Create GUC setting SQL
    fn create_guc_sql(&self, guc: &crate::schema::GucSetting) -> String;

    /// Reset GUC setting SQL
    fn reset_guc_sql(&self, guc: &crate::schema::GucSetting) -> String;

    /// Get GUC setting value SQL
    fn get_guc_sql(&self, guc: &crate::schema::GucSetting) -> String;

    /// List all GUC settings SQL
    fn list_guc_settings_sql(&self) -> String;

    /// Set JWT context SQL
    fn set_jwt_context_sql(
        &self,
        user_id: &str,
        tenant_id: Option<&str>,
        role: Option<&str>,
    ) -> String;

    /// Clear JWT context SQL
    fn clear_jwt_context_sql(&self) -> String;
}

/// Introspector trait for querying database schema information
pub trait Introspector: Send + Sync {
    /// Get all tables in the database
    fn get_tables(&self) -> Result<Vec<Table>>;

    /// Get a specific table by name
    fn get_table(&self, table_name: &str) -> Result<Option<Table>>;

    /// Get all views in the database
    fn get_views(&self) -> Result<Vec<View>>;

    /// Get a specific view by name
    fn get_view(&self, view_name: &str) -> Result<Option<View>>;

    /// Get all indexes in the database
    fn get_indexes(&self) -> Result<Vec<Index>>;

    /// Get indexes for a specific table
    fn get_table_indexes(&self, table_name: &str) -> Result<Vec<Index>>;

    /// Get all composite types in the database
    fn get_composite_types(&self) -> Result<Vec<CompositeType>>;

    /// Get a specific composite type by name
    fn get_composite_type(&self, type_name: &str) -> Result<Option<CompositeType>>;

    /// Get all roles in the database
    fn get_roles(&self) -> Result<Vec<Role>>;

    /// Get all grants in the database
    fn get_grants(&self) -> Result<Vec<Grant>>;

    /// Get the database schema version
    fn get_schema_version(&self) -> Result<Option<String>>;

    /// Check if a table exists
    fn table_exists(&self, table_name: &str) -> Result<bool>;

    /// Check if a view exists
    fn view_exists(&self, view_name: &str) -> Result<bool>;

    /// Check if an index exists
    fn index_exists(&self, index_name: &str) -> Result<bool>;
}

/// Connection manager trait for handling database connections
pub trait ConnectionManager: Send + Sync {
    /// Create a new connection pool
    fn create_pool(
        &self,
        config: &crate::database::DatabaseConfig,
    ) -> Result<Box<dyn ConnectionPool>>;

    /// Test a database connection
    fn test_connection(&self, config: &crate::database::DatabaseConfig) -> Result<()>;

    /// Get the connection string for the database
    fn connection_string(&self, config: &crate::database::DatabaseConfig) -> String;

    /// Get the database-specific connection options
    fn connection_options(
        &self,
        config: &crate::database::DatabaseConfig,
    ) -> Result<Box<dyn std::fmt::Debug>>;
}

/// Connection pool trait for managing database connections
pub trait ConnectionPool: Send + Sync {
    /// Execute a query and return results
    fn execute_query(
        &self,
        sql: &str,
        params: &[&dyn std::fmt::Display],
    ) -> Result<Vec<HashMap<String, String>>>;

    /// Execute a command (INSERT, UPDATE, DELETE)
    fn execute_command(&self, sql: &str, params: &[&dyn std::fmt::Display]) -> Result<u64>;

    /// Begin a transaction
    fn begin_transaction(&self) -> Result<Box<dyn Transaction>>;

    /// Get the number of active connections
    fn active_connections(&self) -> u32;

    /// Get the maximum number of connections
    fn max_connections(&self) -> u32;
}

/// Transaction trait for managing database transactions
pub trait Transaction: Send + Sync {
    /// Execute a query within the transaction
    fn execute_query(
        &self,
        sql: &str,
        params: &[&dyn std::fmt::Display],
    ) -> Result<Vec<HashMap<String, String>>>;

    /// Execute a command within the transaction
    fn execute_command(&self, sql: &str, params: &[&dyn std::fmt::Display]) -> Result<u64>;

    /// Commit the transaction
    fn commit(self: Box<Self>) -> Result<()>;

    /// Rollback the transaction
    fn rollback(self: Box<Self>) -> Result<()>;
}

/// Migration manager trait for handling database migrations
pub trait MigrationManager: Send + Sync {
    /// Get all applied migrations
    fn get_applied_migrations(&self) -> Result<Vec<Migration>>;

    /// Apply a migration
    fn apply_migration(&self, migration: &Migration) -> Result<()>;

    /// Rollback a migration
    fn rollback_migration(&self, migration: &Migration) -> Result<()>;

    /// Check if a migration has been applied
    fn is_migration_applied(&self, migration_id: &str) -> Result<bool>;

    /// Create the migrations table if it doesn't exist
    fn create_migrations_table(&self) -> Result<()>;

    /// Get the current schema version
    fn get_current_version(&self) -> Result<Option<String>>;

    /// Set the schema version
    fn set_schema_version(&self, version: &str) -> Result<()>;
}