ignis-db 0.2.0

A comprehensive PostgreSQL ORM with macro-driven schema management
Documentation
//! PostgreSQL integration tests for Ignis

use ignis_db::{table, IgnisObject};
use sqlx::{PgPool, Row};
use std::env;

// Define test tables
table! {
    test_users (id) {
        id -> Int4,
        email -> Varchar,
        name -> Text,
        created_at -> Timestamptz,
        active -> Bool,
    }
}

table! {
    test_posts (id) {
        id -> Int4,
        user_id -> Int4,
        title -> Varchar,
        content -> Text,
        published -> Bool,
        created_at -> Timestamptz,
    }
}

async fn setup_database() -> Result<PgPool, Box<dyn std::error::Error>> {
    // Get database URL from environment or use default
    let database_url = env::var("DATABASE_URL")
        .unwrap_or_else(|_| "postgres://postgres:postgres@localhost:5433/postgres".to_string());

    let pool = PgPool::connect(&database_url).await?;

    Ok(pool)
}

async fn cleanup_database(pool: &PgPool) -> Result<(), Box<dyn std::error::Error>> {
    // Drop test tables
    sqlx::query("DROP TABLE IF EXISTS test_posts CASCADE")
        .execute(pool)
        .await
        .ok();
    sqlx::query("DROP TABLE IF EXISTS test_users CASCADE")
        .execute(pool)
        .await
        .ok();

    Ok(())
}

#[tokio::test]
async fn test_table_creation() -> Result<(), Box<dyn std::error::Error>> {
    let pool = setup_database().await?;

    // Clean up any existing tables
    cleanup_database(&pool).await?;

    // Get the DDL from our macro
    let users_table = test_users::table();
    let users_ddl = users_table.generate_ddl();

    let posts_table = test_posts::table();
    let posts_ddl = posts_table.generate_ddl();

    println!("Generated Users DDL:");
    println!("{}", users_ddl);
    println!();

    println!("Generated Posts DDL:");
    println!("{}", posts_ddl);
    println!();

    // Execute the DDL
    println!("Creating users table...");
    sqlx::query(&users_ddl).execute(&pool).await?;
    println!("Users table created successfully!");

    println!("Creating posts table...");
    sqlx::query(&posts_ddl).execute(&pool).await?;
    println!("Posts table created successfully!");

    // Verify tables exist
    let tables: Vec<String> = sqlx::query("SELECT table_name FROM information_schema.tables WHERE table_schema = 'public' AND table_name IN ('test_users', 'test_posts')")
        .fetch_all(&pool)
        .await?
        .into_iter()
        .map(|row| row.get("table_name"))
        .collect();

    assert!(tables.contains(&"test_users".to_string()));
    assert!(tables.contains(&"test_posts".to_string()));

    // Verify table structure
    let user_columns: Vec<String> = sqlx::query("SELECT column_name FROM information_schema.columns WHERE table_name = 'test_users' ORDER BY ordinal_position")
        .fetch_all(&pool)
        .await?
        .into_iter()
        .map(|row| row.get("column_name"))
        .collect();

    assert_eq!(
        user_columns,
        vec!["id", "email", "name", "created_at", "active"]
    );

    // Test inserting and querying data
    println!("Testing data insertion...");

    let insert_result = sqlx::query(
        "INSERT INTO test_users (id, email, name, created_at, active) VALUES ($1, $2, $3, $4, $5)",
    )
    .bind(1)
    .bind("test@example.com")
    .bind("Test User")
    .bind(chrono::Utc::now())
    .bind(true)
    .execute(&pool)
    .await?;

    assert_eq!(insert_result.rows_affected(), 1);

    // Query the data back
    let user = sqlx::query("SELECT * FROM test_users WHERE id = $1")
        .bind(1)
        .fetch_one(&pool)
        .await?;

    assert_eq!(user.get::<i32, _>("id"), 1);
    assert_eq!(user.get::<String, _>("email"), "test@example.com");
    assert_eq!(user.get::<String, _>("name"), "Test User");
    assert_eq!(user.get::<bool, _>("active"), true);

    println!("Data insertion and querying successful!");

    // Clean up
    cleanup_database(&pool).await?;

    Ok(())
}

#[tokio::test]
async fn test_inventory_registration() -> Result<(), Box<dyn std::error::Error>> {
    // Test that our tables are properly registered in the inventory
    let tables: Vec<_> = ignis_db::get_registered_tables().collect();

    // Find our test tables
    let test_users = tables.iter().find(|t| t.0.name == "test_users");
    let test_posts = tables.iter().find(|t| t.0.name == "test_posts");

    assert!(
        test_users.is_some(),
        "test_users table should be registered"
    );
    assert!(
        test_posts.is_some(),
        "test_posts table should be registered"
    );

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

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

    Ok(())
}