use crate::code_parsing::{TableMacroParser, ParsedTable};
use crate::database::PostgreSQL;
use crate::migrate::Migration;
use anyhow::{Context, Result};
use std::path::Path;
pub struct TableMacroMigrationGenerator {
source_dir: String,
db: PostgreSQL,
}
impl TableMacroMigrationGenerator {
pub fn new(source_dir: impl Into<String>, db: PostgreSQL) -> Self {
Self {
source_dir: source_dir.into(),
db,
}
}
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)
}
pub fn generate_migration_from_table(&self, parsed_table: &ParsedTable) -> Result<Migration> {
let table = parsed_table.to_table()
.context("Failed to convert parsed table to Table schema")?;
let sql = self.db.create_table_sql(&table);
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)
}
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();
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)
}
fn write_migration_file(&self, migration: &Migration, output_dir: &Path) -> Result<std::path::PathBuf> {
use chrono::Utc;
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);
let content = self.generate_migration_file_content(migration);
std::fs::write(&file_path, content)
.with_context(|| format!("Failed to write migration file: {}", file_path.display()))?;
Ok(file_path)
}
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
}
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"));
}
}