ignis-db 0.2.0

A comprehensive PostgreSQL ORM with macro-driven schema management
Documentation
//! Migration generator that creates migrations from table! macro definitions

use crate::code_parsing::{TableMacroParser, ParsedTable};
use crate::database::PostgreSQL;
use crate::migrate::Migration;
use anyhow::{Context, Result};
use std::path::Path;

/// Generator for creating migrations from table! macro definitions
pub struct TableMacroMigrationGenerator {
    source_dir: String,
    db: PostgreSQL,
}

impl TableMacroMigrationGenerator {
    /// Create a new table macro migration generator
    pub fn new(source_dir: impl Into<String>, db: PostgreSQL) -> Self {
        Self {
            source_dir: source_dir.into(),
            db,
        }
    }

    /// Generate migrations from all table! macro definitions in the source directory
    pub fn generate_migrations(&self) -> Result<Vec<Migration>> {
        let parser = TableMacroParser::new(&self.source_dir);
        let parsed_tables = parser.parse_table_macros()
            .context("Failed to parse table! macro definitions")?;

        let mut migrations = Vec::new();

        for parsed_table in parsed_tables {
            let migration = self.create_migration_from_table(&parsed_table)?;
            migrations.push(migration);
        }

        Ok(migrations)
    }

    /// Generate a single migration from a parsed table
    pub fn generate_migration_from_table(&self, parsed_table: &ParsedTable) -> Result<Migration> {
        // Convert parsed table to Table schema
        let table = parsed_table.to_table()
            .context("Failed to convert parsed table to Table schema")?;

        // Generate SQL from table definition
        let sql = self.db.create_table_sql(&table);

        // Create migration
        let migration_name = format!("create_{}_table", parsed_table.name);
        let migration_description = format!("Create {} table from table! macro definition", parsed_table.name);
        
        let migration = Migration::new(
            &migration_name,
            &migration_description,
            &sql
        )
        .with_down(&format!("DROP TABLE IF EXISTS \"{}\" CASCADE;", parsed_table.name));

        Ok(migration)
    }

    /// Generate migration files to disk
    pub fn generate_migration_files(&self, output_dir: &Path) -> Result<Vec<std::path::PathBuf>> {
        let migrations = self.generate_migrations()?;
        let mut generated_files = Vec::new();

        // Ensure output directory exists
        std::fs::create_dir_all(output_dir)
            .context("Failed to create output directory")?;

        for migration in migrations {
            let file_path = self.write_migration_file(&migration, output_dir)?;
            generated_files.push(file_path);
        }

        Ok(generated_files)
    }

    /// Write a single migration file to disk
    fn write_migration_file(&self, migration: &Migration, output_dir: &Path) -> Result<std::path::PathBuf> {
        use chrono::Utc;

        // Generate timestamp for migration file
        let timestamp = Utc::now().format("%Y%m%d_%H%M%S").to_string();
        let filename = format!("{}_{}.sql", timestamp, migration.id);
        let file_path = output_dir.join(filename);

        // Generate migration file content
        let content = self.generate_migration_file_content(migration);

        // Write file
        std::fs::write(&file_path, content)
            .with_context(|| format!("Failed to write migration file: {}", file_path.display()))?;

        Ok(file_path)
    }

    /// Generate the content for a migration file
    fn generate_migration_file_content(&self, migration: &Migration) -> String {
        let mut content = String::new();
        
        content.push_str(&format!("-- Migration: {}\n", migration.name));
        content.push_str(&format!("-- Generated at: {}\n", chrono::Utc::now().format("%Y-%m-%d %H:%M:%S UTC")));
        content.push_str("-- Generated from table! macro definition\n\n");
        
        content.push_str("-- UP\n");
        content.push_str(&migration.up_sql);
        content.push_str("\n\n");
        
        if let Some(down_sql) = &migration.down_sql {
            content.push_str("-- DOWN\n");
            content.push_str(down_sql);
            content.push_str("\n");
        }

        content
    }

    /// Create a single migration from a parsed table (convenience method)
    fn create_migration_from_table(&self, parsed_table: &ParsedTable) -> Result<Migration> {
        self.generate_migration_from_table(parsed_table)
    }
}

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

    #[test]
    fn test_migration_generator_creation() {
        let db = PostgreSQL::new("test");
        let generator = TableMacroMigrationGenerator::new("./src", db);
        assert_eq!(generator.source_dir, "./src");
    }

    #[test]
    fn test_migration_file_content_generation() {
        let db = PostgreSQL::new("test");
        let generator = TableMacroMigrationGenerator::new("./src", db);
        
        let migration = Migration::new(
            "create_users_table",
            "Create users table",
            "CREATE TABLE users (id SERIAL PRIMARY KEY, name TEXT);"
        )
        .with_down("DROP TABLE users;");

        let content = generator.generate_migration_file_content(&migration);
        
        assert!(content.contains("-- Migration: create_users_table"));
        assert!(content.contains("CREATE TABLE users"));
        assert!(content.contains("DROP TABLE users"));
        assert!(content.contains("-- UP"));
        assert!(content.contains("-- DOWN"));
    }
}