use anyhow::Result;
use std::collections::HashMap;
#[derive(Debug, Clone)]
pub struct MigrationFile {
pub filename: String,
pub up_sql: String,
pub down_sql: String,
pub description: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum SchemaChangeType {
CreateTable,
DropTable,
AddColumn,
DropColumn,
AlterColumn,
CreateIndex,
DropIndex,
CreateCompositeType,
DropCompositeType,
CreateEnum,
DropEnum,
}
#[derive(Debug, Clone)]
pub struct SchemaChange {
pub change_type: SchemaChangeType,
pub table_name: String,
pub object_name: Option<String>, pub up_sql: String,
pub down_sql: String,
pub description: String,
}
pub trait MigrationStrategy {
fn generate_migrations(&self, changes: Vec<SchemaChange>) -> Result<Vec<MigrationFile>>;
fn name(&self) -> &'static str;
fn description(&self) -> &'static str;
}
pub struct ConservativeStrategy;
impl MigrationStrategy for ConservativeStrategy {
fn generate_migrations(&self, changes: Vec<SchemaChange>) -> Result<Vec<MigrationFile>> {
let mut migrations = Vec::new();
let base_timestamp = chrono::Utc::now().format("%Y%m%d_%H%M%S");
for (index, change) in changes.into_iter().enumerate() {
let timestamp = if index == 0 {
base_timestamp.to_string()
} else {
let time_offset = chrono::Utc::now() + chrono::Duration::seconds(index as i64);
time_offset.format("%Y%m%d_%H%M%S").to_string()
};
let filename = match change.change_type {
SchemaChangeType::CreateTable => {
format!("{}_create_table_{}.sql", timestamp, change.table_name)
}
SchemaChangeType::DropTable => {
format!("{}_drop_table_{}.sql", timestamp, change.table_name)
}
SchemaChangeType::AddColumn => {
let column_name = change.object_name.as_deref().unwrap_or("unknown");
format!(
"{}_add_column_{}_{}.sql",
timestamp, change.table_name, column_name
)
}
SchemaChangeType::DropColumn => {
let column_name = change.object_name.as_deref().unwrap_or("unknown");
format!(
"{}_drop_column_{}_{}.sql",
timestamp, change.table_name, column_name
)
}
SchemaChangeType::AlterColumn => {
let column_name = change.object_name.as_deref().unwrap_or("unknown");
format!(
"{}_alter_column_{}_{}.sql",
timestamp, change.table_name, column_name
)
}
SchemaChangeType::CreateIndex => {
let index_name = change.object_name.as_deref().unwrap_or("unknown");
format!("{}_create_index_{}.sql", timestamp, index_name)
}
SchemaChangeType::DropIndex => {
let index_name = change.object_name.as_deref().unwrap_or("unknown");
format!("{}_drop_index_{}.sql", timestamp, index_name)
}
SchemaChangeType::CreateCompositeType => {
let type_name = change.object_name.as_deref().unwrap_or("unknown");
format!("{}_create_composite_{}.sql", timestamp, type_name)
}
SchemaChangeType::DropCompositeType => {
let type_name = change.object_name.as_deref().unwrap_or("unknown");
format!("{}_drop_composite_{}.sql", timestamp, type_name)
}
SchemaChangeType::CreateEnum => {
let enum_name = change.object_name.as_deref().unwrap_or("unknown");
format!("{}_create_enum_{}.sql", timestamp, enum_name)
}
SchemaChangeType::DropEnum => {
let enum_name = change.object_name.as_deref().unwrap_or("unknown");
format!("{}_drop_enum_{}.sql", timestamp, enum_name)
}
};
migrations.push(MigrationFile {
filename,
up_sql: change.up_sql,
down_sql: change.down_sql,
description: change.description,
});
}
Ok(migrations)
}
fn name(&self) -> &'static str {
"Conservative"
}
fn description(&self) -> &'static str {
"Generate separate migration files per change type (safer, more granular)"
}
}
pub struct GroupedStrategy;
impl MigrationStrategy for GroupedStrategy {
fn generate_migrations(&self, changes: Vec<SchemaChange>) -> Result<Vec<MigrationFile>> {
let mut grouped_changes: HashMap<String, Vec<SchemaChange>> = HashMap::new();
for change in changes {
let group_key = match change.change_type {
SchemaChangeType::CreateTable | SchemaChangeType::DropTable => {
"table_operations".to_string()
}
SchemaChangeType::AddColumn
| SchemaChangeType::DropColumn
| SchemaChangeType::AlterColumn => {
format!("column_changes_{}", change.table_name)
}
SchemaChangeType::CreateIndex | SchemaChangeType::DropIndex => {
format!("index_changes_{}", change.table_name)
}
SchemaChangeType::CreateCompositeType | SchemaChangeType::DropCompositeType => {
"composite_type_changes".to_string()
}
SchemaChangeType::CreateEnum | SchemaChangeType::DropEnum => {
"enum_changes".to_string()
}
};
grouped_changes
.entry(group_key)
.or_insert_with(Vec::new)
.push(change);
}
let mut migrations = Vec::new();
let base_timestamp = chrono::Utc::now().format("%Y%m%d_%H%M%S");
for (index, (group_key, group_changes)) in grouped_changes.into_iter().enumerate() {
let timestamp = if index == 0 {
base_timestamp.to_string()
} else {
let time_offset = chrono::Utc::now() + chrono::Duration::minutes(index as i64);
time_offset.format("%Y%m%d_%H%M%S").to_string()
};
let filename = format!("{}_{}.sql", timestamp, group_key);
let mut up_sql = String::new();
let mut down_sql = String::new();
let mut descriptions = Vec::new();
for change in &group_changes {
up_sql.push_str(&format!("-- {}\n", change.description));
up_sql.push_str(&change.up_sql);
up_sql.push_str("\n\n");
down_sql.push_str(&format!("-- Rollback: {}\n", change.description));
down_sql.push_str(&change.down_sql);
down_sql.push_str("\n\n");
descriptions.push(change.description.clone());
}
let description = if group_changes.len() == 1 {
descriptions[0].clone()
} else {
format!("Grouped changes: {}", descriptions.join(", "))
};
migrations.push(MigrationFile {
filename,
up_sql,
down_sql,
description,
});
}
migrations.sort_by(|a, b| a.filename.cmp(&b.filename));
Ok(migrations)
}
fn name(&self) -> &'static str {
"Grouped"
}
fn description(&self) -> &'static str {
"Group related changes into single migrations (fewer files, faster deployment)"
}
}
pub fn create_strategy(strategy_name: &str) -> Result<Box<dyn MigrationStrategy>> {
match strategy_name.to_lowercase().as_str() {
"conservative" => Ok(Box::new(ConservativeStrategy)),
"grouped" => Ok(Box::new(GroupedStrategy)),
_ => Err(anyhow::anyhow!(
"Unknown migration strategy: {}",
strategy_name
)),
}
}
#[cfg(test)]
mod tests {
use super::*;
fn create_sample_changes() -> Vec<SchemaChange> {
vec![
SchemaChange {
change_type: SchemaChangeType::CreateTable,
table_name: "users".to_string(),
object_name: None,
up_sql: "CREATE TABLE users (id SERIAL PRIMARY KEY);".to_string(),
down_sql: "DROP TABLE users;".to_string(),
description: "Create users table".to_string(),
},
SchemaChange {
change_type: SchemaChangeType::AddColumn,
table_name: "users".to_string(),
object_name: Some("email".to_string()),
up_sql: "ALTER TABLE users ADD COLUMN email VARCHAR(255);".to_string(),
down_sql: "ALTER TABLE users DROP COLUMN email;".to_string(),
description: "Add email column to users".to_string(),
},
]
}
#[test]
fn test_conservative_strategy() {
let strategy = ConservativeStrategy;
let changes = create_sample_changes();
let migrations = strategy.generate_migrations(changes).unwrap();
assert_eq!(migrations.len(), 2);
assert!(migrations[0].filename.contains("create_table_users"));
assert!(migrations[1].filename.contains("add_column_users_email"));
}
#[test]
fn test_grouped_strategy() {
let strategy = GroupedStrategy;
let changes = create_sample_changes();
let migrations = strategy.generate_migrations(changes).unwrap();
assert!(migrations.len() <= 2);
for migration in migrations {
assert!(!migration.up_sql.is_empty());
assert!(!migration.down_sql.is_empty());
}
}
#[test]
fn test_strategy_factory() {
let conservative = create_strategy("conservative").unwrap();
assert_eq!(conservative.name(), "Conservative");
let grouped = create_strategy("grouped").unwrap();
assert_eq!(grouped.name(), "Grouped");
assert!(create_strategy("unknown").is_err());
}
}