ignis-db 0.2.0

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

use anyhow::Result;
use ignis_db::{table, view};
use sqlx::{PgPool, Row};

// Define tables that our views will depend on
table! {
    test_users (id) {
        id -> Int4,
        name -> Varchar,
        email -> Varchar,
        status -> Text,
        created_at -> Timestamptz,
        score -> Numeric,
    }
}

table! {
    test_posts (id) {
        id -> Int4,
        user_id -> Int4,
        title -> Text,
        content -> Text,
        view_count -> Int4,
        like_count -> Int4,
        comment_count -> Int4,
        created_at -> Timestamptz,
    }
}

// Define views to test
view! {
    active_users (id) {
        id -> Int4,
        name -> Varchar,
        email -> Varchar,
        status -> Text,
    }
}

view! {
    user_post_stats (id) {
        id -> Int4,
        name -> Varchar,
        post_count -> Int4,
        total_views -> Int4,
        avg_score -> Numeric,
    }
}

async fn setup_database(pool: &PgPool) -> Result<()> {
    // Clean up any existing data first
    cleanup_database(pool).await?;

    // Create test tables
    sqlx::query(
        r#"
        CREATE TABLE test_users (
            id SERIAL PRIMARY KEY,
            name VARCHAR NOT NULL,
            email VARCHAR UNIQUE NOT NULL,
            status TEXT DEFAULT 'active',
            created_at TIMESTAMPTZ DEFAULT NOW(),
            score NUMERIC DEFAULT 0.0
        )
        "#,
    )
    .execute(pool)
    .await?;

    sqlx::query(
        r#"
        CREATE TABLE test_posts (
            id SERIAL PRIMARY KEY,
            user_id INTEGER NOT NULL REFERENCES test_users(id),
            title TEXT NOT NULL,
            content TEXT,
            view_count INTEGER DEFAULT 0,
            like_count INTEGER DEFAULT 0,
            comment_count INTEGER DEFAULT 0,
            created_at TIMESTAMPTZ DEFAULT NOW()
        )
        "#,
    )
    .execute(pool)
    .await?;

    // Insert test data
    sqlx::query("INSERT INTO test_users (name, email, score) VALUES ($1, $2, $3)")
        .bind("Alice Johnson")
        .bind("alice@example.com")
        .bind(85.5)
        .execute(pool)
        .await?;

    sqlx::query("INSERT INTO test_users (name, email, score) VALUES ($1, $2, $3)")
        .bind("Bob Smith")
        .bind("bob@example.com")
        .bind(92.3)
        .execute(pool)
        .await?;

    sqlx::query(
        "INSERT INTO test_posts (user_id, title, content, view_count, like_count, comment_count) VALUES ($1, $2, $3, $4, $5, $6)"
    )
    .bind(1)
    .bind("First Post")
    .bind("This is my first post")
    .bind(150)
    .bind(25)
    .bind(8)
    .execute(pool).await?;

    sqlx::query(
        "INSERT INTO test_posts (user_id, title, content, view_count, like_count, comment_count) VALUES ($1, $2, $3, $4, $5, $6)"
    )
    .bind(1)
    .bind("Second Post")
    .bind("Another interesting post")
    .bind(89)
    .bind(12)
    .bind(3)
    .execute(pool).await?;

    sqlx::query(
        "INSERT INTO test_posts (user_id, title, content, view_count, like_count, comment_count) VALUES ($1, $2, $3, $4, $5, $6)"
    )
    .bind(2)
    .bind("Bob's Post")
    .bind("Bob sharing his thoughts")
    .bind(200)
    .bind(45)
    .bind(15)
    .execute(pool).await?;

    Ok(())
}

async fn cleanup_database(pool: &PgPool) -> Result<()> {
    // Drop views first (they depend on tables)
    sqlx::query("DROP VIEW IF EXISTS test_active_users CASCADE")
        .execute(pool)
        .await?;
    sqlx::query("DROP VIEW IF EXISTS test_user_post_stats CASCADE")
        .execute(pool)
        .await?;
    sqlx::query("DROP VIEW IF EXISTS test_post_engagement CASCADE")
        .execute(pool)
        .await?;

    // Drop tables
    sqlx::query("DROP TABLE IF EXISTS test_posts CASCADE")
        .execute(pool)
        .await?;
    sqlx::query("DROP TABLE IF EXISTS test_users CASCADE")
        .execute(pool)
        .await?;

    Ok(())
}

#[tokio::test]
async fn test_view_creation_and_querying() -> Result<()> {
    let pool = PgPool::connect("postgresql://postgres:postgres@localhost:5433/postgres").await?;

    // Setup
    setup_database(&pool).await?;

    // Test 1: Create simple active_users view
    println!("Testing simple active_users view...");

    let active_users_ddl = r#"
        CREATE VIEW test_active_users AS 
        SELECT id, name, email, status 
        FROM test_users 
        WHERE status = 'active'
    "#;

    sqlx::query(active_users_ddl).execute(&pool).await?;

    // Verify view exists
    let view_exists = sqlx::query(
        "SELECT 1 FROM information_schema.views WHERE table_name = 'test_active_users'",
    )
    .fetch_optional(&pool)
    .await?
    .is_some();

    assert!(view_exists, "test_active_users view should exist");

    // Query the view
    let active_users = sqlx::query("SELECT * FROM test_active_users ORDER BY id")
        .fetch_all(&pool)
        .await?;

    assert_eq!(active_users.len(), 2, "Should have 2 active users");

    // Test 2: Create complex user_post_stats view with JOIN and aggregation
    println!("Testing complex user_post_stats view...");

    let user_stats_ddl = r#"
        CREATE VIEW test_user_post_stats AS 
        SELECT 
            u.id,
            u.name,
            COUNT(p.id) as post_count,
            SUM(p.view_count) as total_views,
            AVG(u.score) as avg_score
        FROM test_users u
        LEFT JOIN test_posts p ON u.id = p.user_id
        GROUP BY u.id, u.name
        ORDER BY u.id
    "#;

    sqlx::query(user_stats_ddl).execute(&pool).await?;

    // Verify complex view exists
    let view_exists = sqlx::query(
        "SELECT 1 FROM information_schema.views WHERE table_name = 'test_user_post_stats'",
    )
    .fetch_optional(&pool)
    .await?
    .is_some();

    assert!(view_exists, "test_user_post_stats view should exist");

    // Query the complex view
    let user_stats = sqlx::query("SELECT * FROM test_user_post_stats ORDER BY id")
        .fetch_all(&pool)
        .await?;

    assert_eq!(user_stats.len(), 2, "Should have stats for 2 users");

    // Verify Alice's stats (user_id = 1)
    let alice_stats = &user_stats[0];
    assert_eq!(alice_stats.get::<i32, _>("id"), 1);
    assert_eq!(alice_stats.get::<String, _>("name"), "Alice Johnson");
    assert_eq!(alice_stats.get::<i64, _>("post_count"), 2); // 2 posts
    assert_eq!(alice_stats.get::<i64, _>("total_views"), 239); // 150 + 89

    // Now we can read avg_score as rust_decimal::Decimal
    let avg_score: rust_decimal::Decimal = alice_stats.get("avg_score");
    assert_eq!(
        avg_score,
        rust_decimal::Decimal::new(855, 1),
        "Alice's avg_score should be 85.5"
    );

    // Verify Bob's stats (user_id = 2)
    let bob_stats = &user_stats[1];
    assert_eq!(bob_stats.get::<i32, _>("id"), 2);
    assert_eq!(bob_stats.get::<String, _>("name"), "Bob Smith");
    assert_eq!(bob_stats.get::<i64, _>("post_count"), 1); // 1 post
    assert_eq!(bob_stats.get::<i64, _>("total_views"), 200); // 200 views

    let avg_score: rust_decimal::Decimal = bob_stats.get("avg_score");
    assert_eq!(
        avg_score,
        rust_decimal::Decimal::new(923, 1),
        "Bob's avg_score should be 92.3"
    );

    // Test 3: Test view with CASE statement and complex calculations
    println!("Testing view with CASE statement...");

    let engagement_view_ddl = r#"
        CREATE VIEW test_post_engagement AS 
        SELECT 
            p.id,
            p.title,
            u.name as author_name,
            p.view_count,
            p.like_count,
            p.comment_count,
            CASE 
                WHEN p.view_count > 0 THEN 
                    ROUND(((p.like_count + p.comment_count)::numeric / p.view_count * 100), 2)
                ELSE 0
            END as engagement_rate
        FROM test_posts p
        JOIN test_users u ON p.user_id = u.id
        ORDER BY engagement_rate DESC
    "#;

    sqlx::query(engagement_view_ddl).execute(&pool).await?;

    // Query engagement view
    let engagement_data = sqlx::query("SELECT * FROM test_post_engagement ORDER BY id")
        .fetch_all(&pool)
        .await?;

    assert_eq!(engagement_data.len(), 3, "Should have 3 posts");

    // Verify engagement calculations
    let first_post = &engagement_data[0];
    let _view_count: i32 = first_post.get("view_count");
    let _like_count: i32 = first_post.get("like_count");
    let _comment_count: i32 = first_post.get("comment_count");

    // Now we can read engagement_rate as rust_decimal::Decimal
    let engagement_rate: rust_decimal::Decimal = first_post.get("engagement_rate");

    // Expected: (25 + 8) / 150 * 100 = 22.00
    let expected_rate = rust_decimal::Decimal::new(2200, 2);
    assert_eq!(
        engagement_rate, expected_rate,
        "Engagement rate calculation should be correct"
    );

    println!("✅ All view tests passed!");

    // Cleanup
    cleanup_database(&pool).await?;

    Ok(())
}

#[tokio::test]
async fn test_view_inventory_registration() -> Result<()> {
    let pool = PgPool::connect("postgresql://postgres:postgres@localhost:5433/postgres").await?;

    // Test that views are properly registered in the inventory system
    let registered: Vec<_> = ignis_db::iter_registered().collect();
    let view_count = registered.iter().filter(|obj| obj.0.kind == "view").count();

    assert!(view_count >= 2, "Should have at least 2 views registered");

    // Verify view objects have correct properties
    for obj in &registered {
        if obj.0.kind == "view" {
            assert!(!obj.0.name.is_empty(), "View name should not be empty");
            assert!(
                obj.0.ddl.contains("CREATE VIEW"),
                "View DDL should contain CREATE VIEW"
            );
            assert_eq!(obj.0.schema, None, "View schema should be None by default");
        }
    }

    println!("✅ View inventory registration test passed!");

    Ok(())
}