Skip to main content

ignis_db/migrate/
table_macro_generator.rs

1//! Migration generator that creates migrations from table! macro definitions
2
3use crate::code_parsing::{TableMacroParser, ParsedTable};
4use crate::database::PostgreSQL;
5use crate::migrate::Migration;
6use anyhow::{Context, Result};
7use std::path::Path;
8
9/// Generator for creating migrations from table! macro definitions
10pub struct TableMacroMigrationGenerator {
11    source_dir: String,
12    db: PostgreSQL,
13}
14
15impl TableMacroMigrationGenerator {
16    /// Create a new table macro migration generator
17    pub fn new(source_dir: impl Into<String>, db: PostgreSQL) -> Self {
18        Self {
19            source_dir: source_dir.into(),
20            db,
21        }
22    }
23
24    /// Generate migrations from all table! macro definitions in the source directory
25    pub fn generate_migrations(&self) -> Result<Vec<Migration>> {
26        let parser = TableMacroParser::new(&self.source_dir);
27        let parsed_tables = parser.parse_table_macros()
28            .context("Failed to parse table! macro definitions")?;
29
30        let mut migrations = Vec::new();
31
32        for parsed_table in parsed_tables {
33            let migration = self.create_migration_from_table(&parsed_table)?;
34            migrations.push(migration);
35        }
36
37        Ok(migrations)
38    }
39
40    /// Generate a single migration from a parsed table
41    pub fn generate_migration_from_table(&self, parsed_table: &ParsedTable) -> Result<Migration> {
42        // Convert parsed table to Table schema
43        let table = parsed_table.to_table()
44            .context("Failed to convert parsed table to Table schema")?;
45
46        // Generate SQL from table definition
47        let sql = self.db.create_table_sql(&table);
48
49        // Create migration
50        let migration_name = format!("create_{}_table", parsed_table.name);
51        let migration_description = format!("Create {} table from table! macro definition", parsed_table.name);
52        
53        let migration = Migration::new(
54            &migration_name,
55            &migration_description,
56            &sql
57        )
58        .with_down(&format!("DROP TABLE IF EXISTS \"{}\" CASCADE;", parsed_table.name));
59
60        Ok(migration)
61    }
62
63    /// Generate migration files to disk
64    pub fn generate_migration_files(&self, output_dir: &Path) -> Result<Vec<std::path::PathBuf>> {
65        let migrations = self.generate_migrations()?;
66        let mut generated_files = Vec::new();
67
68        // Ensure output directory exists
69        std::fs::create_dir_all(output_dir)
70            .context("Failed to create output directory")?;
71
72        for migration in migrations {
73            let file_path = self.write_migration_file(&migration, output_dir)?;
74            generated_files.push(file_path);
75        }
76
77        Ok(generated_files)
78    }
79
80    /// Write a single migration file to disk
81    fn write_migration_file(&self, migration: &Migration, output_dir: &Path) -> Result<std::path::PathBuf> {
82        use chrono::Utc;
83
84        // Generate timestamp for migration file
85        let timestamp = Utc::now().format("%Y%m%d_%H%M%S").to_string();
86        let filename = format!("{}_{}.sql", timestamp, migration.id);
87        let file_path = output_dir.join(filename);
88
89        // Generate migration file content
90        let content = self.generate_migration_file_content(migration);
91
92        // Write file
93        std::fs::write(&file_path, content)
94            .with_context(|| format!("Failed to write migration file: {}", file_path.display()))?;
95
96        Ok(file_path)
97    }
98
99    /// Generate the content for a migration file
100    fn generate_migration_file_content(&self, migration: &Migration) -> String {
101        let mut content = String::new();
102        
103        content.push_str(&format!("-- Migration: {}\n", migration.name));
104        content.push_str(&format!("-- Generated at: {}\n", chrono::Utc::now().format("%Y-%m-%d %H:%M:%S UTC")));
105        content.push_str("-- Generated from table! macro definition\n\n");
106        
107        content.push_str("-- UP\n");
108        content.push_str(&migration.up_sql);
109        content.push_str("\n\n");
110        
111        if let Some(down_sql) = &migration.down_sql {
112            content.push_str("-- DOWN\n");
113            content.push_str(down_sql);
114            content.push_str("\n");
115        }
116
117        content
118    }
119
120    /// Create a single migration from a parsed table (convenience method)
121    fn create_migration_from_table(&self, parsed_table: &ParsedTable) -> Result<Migration> {
122        self.generate_migration_from_table(parsed_table)
123    }
124}
125
126#[cfg(test)]
127mod tests {
128    use super::*;
129    use crate::database::PostgreSQL;
130
131    #[test]
132    fn test_migration_generator_creation() {
133        let db = PostgreSQL::new("test");
134        let generator = TableMacroMigrationGenerator::new("./src", db);
135        assert_eq!(generator.source_dir, "./src");
136    }
137
138    #[test]
139    fn test_migration_file_content_generation() {
140        let db = PostgreSQL::new("test");
141        let generator = TableMacroMigrationGenerator::new("./src", db);
142        
143        let migration = Migration::new(
144            "create_users_table",
145            "Create users table",
146            "CREATE TABLE users (id SERIAL PRIMARY KEY, name TEXT);"
147        )
148        .with_down("DROP TABLE users;");
149
150        let content = generator.generate_migration_file_content(&migration);
151        
152        assert!(content.contains("-- Migration: create_users_table"));
153        assert!(content.contains("CREATE TABLE users"));
154        assert!(content.contains("DROP TABLE users"));
155        assert!(content.contains("-- UP"));
156        assert!(content.contains("-- DOWN"));
157    }
158}