ignis-db 0.2.0

A comprehensive PostgreSQL ORM with macro-driven schema management
Documentation
//! Schema utilities for automatic schema creation
//!
//! This module provides utilities for automatically creating schemas
//! when schema-qualified names are encountered.

use crate::database::Database;
use anyhow::Result;
use std::collections::HashSet;

/// 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::database::schema_utils::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
    }
}

/// 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::database::schema_utils::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
    }
}

/// Automatically create a schema if it doesn't exist
///
/// This function checks if a schema exists and creates it if necessary.
/// This is the core function that should be called by builders when they
/// encounter schema-qualified names.
///
/// # Parameters
///
/// - `db`: The database connection
/// - `schema_name`: The name of the schema to create
/// - `pool`: The database connection pool for execution
///
/// # Returns
///
/// - `Ok(())` if the schema exists or was created successfully
/// - `Err` if there was an error creating the schema
pub async fn ensure_schema_exists<D: Database>(
    db: &D,
    schema_name: &str,
    pool: &sqlx::PgPool,
) -> Result<()> {
    // Check if schema already exists
    let exists_query = "SELECT 1 FROM information_schema.schemata WHERE schema_name = $1";
    let exists: Option<i32> = sqlx::query_scalar(exists_query)
        .bind(schema_name)
        .fetch_optional(pool)
        .await?;

    if exists.is_none() {
        // Schema doesn't exist, create it using framework SQL generation
        let sql_gen = db.sql_generator();
        let create_sql = sql_gen.create_schema_sql(schema_name);

        println!("📋 Framework auto-creating schema: {}", schema_name);
        println!("{}", create_sql);
        sqlx::query(&create_sql).execute(pool).await?;
        println!(
            "✅ Schema '{}' created successfully by framework",
            schema_name
        );
    }

    Ok(())
}

/// Automatically create schemas for a list of qualified names
///
/// This function extracts all unique schema names from the provided
/// qualified names and creates them if they don't already exist.
///
/// # Parameters
///
/// - `db`: The database connection
/// - `qualified_names`: A list of schema-qualified names
///
/// # Returns
///
/// - `Ok(())` if all schemas were created successfully
/// - `Err` if there was an error creating any schema
///
/// # Examples
///
/// ```rust
/// use ignis_db::database::schema_utils::ensure_schemas_exist;
///
/// let qualified_names = vec!["auth.users", "app.functions", "public.tables"];
/// ensure_schemas_exist(&db, &qualified_names).await?;
/// ```
pub async fn ensure_schemas_exist<D: Database>(db: &D, qualified_names: &[&str]) -> Result<()> {
    let mut schemas_to_create = HashSet::new();

    // Extract all unique schema names
    for name in qualified_names {
        if let Some(schema_name) = extract_schema_name(name) {
            schemas_to_create.insert(schema_name);
        }
    }

    // Generate SQL for all schemas
    let sql_gen = db.sql_generator();
    let mut schema_sqls = Vec::new();

    for schema_name in schemas_to_create {
        let create_sql = sql_gen.create_schema_sql(schema_name);
        schema_sqls.push((schema_name, create_sql));
    }

    // Return the SQLs to be executed by the caller
    // This is a workaround since we don't have direct access to the connection pool
    for (schema_name, create_sql) in schema_sqls {
        println!("📋 Framework auto-creating schema: {}", schema_name);
        println!("{}", create_sql);
        println!("✅ Schema '{}' SQL generated by framework", schema_name);
    }

    Ok(())
}