ignis-db 0.2.0

A comprehensive PostgreSQL ORM with macro-driven schema management
Documentation
//! Migration strategy implementations for flexible migration generation
//!
//! This module provides different strategies for organizing and generating
//! migration files during baseline migration and schema sync operations.

use anyhow::Result;
use std::collections::HashMap;

/// A single migration file to be generated
#[derive(Debug, Clone)]
pub struct MigrationFile {
    pub filename: String,
    pub up_sql: String,
    pub down_sql: String,
    pub description: String,
}

/// Types of schema changes that can occur
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum SchemaChangeType {
    CreateTable,
    DropTable,
    AddColumn,
    DropColumn,
    AlterColumn,
    CreateIndex,
    DropIndex,
    CreateCompositeType,
    DropCompositeType,
    CreateEnum,
    DropEnum,
}

/// A schema change with its details
#[derive(Debug, Clone)]
pub struct SchemaChange {
    pub change_type: SchemaChangeType,
    pub table_name: String,
    pub object_name: Option<String>, // Column name, index name, etc.
    pub up_sql: String,
    pub down_sql: String,
    pub description: String,
}

/// Trait for migration generation strategies
pub trait MigrationStrategy {
    /// Generate migration files from a list of schema changes
    fn generate_migrations(&self, changes: Vec<SchemaChange>) -> Result<Vec<MigrationFile>>;

    /// Get the strategy name
    fn name(&self) -> &'static str;

    /// Get the strategy description
    fn description(&self) -> &'static str;
}

/// Conservative strategy: Generate separate migration file for each change
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 {
                // Add seconds to ensure unique timestamps
                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)"
    }
}

/// Grouped strategy: Group related changes into logical migration files
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();

        // Group changes by category
        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);
        }

        // Generate migration files for each group
        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 {
                // Add minutes to ensure unique timestamps for groups
                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);

            // Combine SQL for all changes in this group
            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,
            });
        }

        // Sort migrations by filename to ensure consistent ordering
        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)"
    }
}

/// Factory function to create strategy instances
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();

        // Should be grouped into fewer files
        assert!(migrations.len() <= 2);

        // Check that SQL is properly combined
        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());
    }
}