Skip to main content

ignis_db/migrate/
mod.rs

1//! Migration system for Ignis
2
3use crate::schema::{
4    Column, CompositeType, IndexMeta, StoredFunction, StoredProcedure, Table, View,
5};
6use anyhow::Result;
7use sqlx::Row;
8use std::collections::HashMap;
9use std::path::Path;
10
11pub mod baseline;
12pub mod ddl_validator;
13pub mod schema_diff;
14pub mod strategy;
15pub mod table_macro_generator;
16// Multi-platform migration support integrated into main migration system
17
18// Re-export for easy access
19pub use baseline::{BaselineMigration, BaselineMigrationManager, SchemaStatistics};
20pub use ddl_validator::{validate_ddl, DdlValidationContext, DdlValidationResult};
21pub use strategy::{
22    create_strategy, ConservativeStrategy, GroupedStrategy, MigrationFile, MigrationStrategy,
23    SchemaChange, SchemaChangeType,
24};
25pub use table_macro_generator::TableMacroMigrationGenerator;
26// Multi-platform migration support is integrated into the main migration system
27
28// Migration management types are defined below
29
30use schema_diff::{MigrationGenerator, SchemaDiffEngine};
31
32/// Represents a database migration
33#[derive(Debug, Clone)]
34pub struct Migration {
35    pub id: String,
36    pub name: String,
37    pub up_sql: String,
38    pub down_sql: Option<String>,
39    pub checksum: String,
40}
41
42impl Migration {
43    /// Create a new migration
44    pub fn new(id: impl Into<String>, name: impl Into<String>, up_sql: impl Into<String>) -> Self {
45        let up_sql = up_sql.into();
46        let checksum = Self::calculate_checksum(&up_sql, None);
47
48        Self {
49            id: id.into(),
50            name: name.into(),
51            up_sql,
52            down_sql: None,
53            checksum,
54        }
55    }
56
57    /// Set the down migration SQL
58    pub fn with_down(mut self, down_sql: impl Into<String>) -> Self {
59        self.down_sql = Some(down_sql.into());
60        self.checksum = Self::calculate_checksum(&self.up_sql, self.down_sql.as_deref());
61        self
62    }
63
64    /// Calculate checksum for the migration
65    fn calculate_checksum(up_sql: &str, down_sql: Option<&str>) -> String {
66        use std::collections::hash_map::DefaultHasher;
67        use std::hash::{Hash, Hasher};
68
69        let mut hasher = DefaultHasher::new();
70        up_sql.hash(&mut hasher);
71        if let Some(down) = down_sql {
72            down.hash(&mut hasher);
73        }
74
75        format!("{:x}", hasher.finish())
76    }
77
78    /// Optional: Validate DDL before execution
79    pub fn validate(&self) -> DdlValidationResult {
80        validate_ddl(&self.up_sql)
81    }
82
83    /// Optional: Execute with transaction safety
84    pub async fn execute_with_transaction<'e, E>(&self, executor: E) -> sqlx::Result<u64>
85    where
86        E: sqlx::Executor<'e, Database = sqlx::Postgres>,
87    {
88        // use crate::exec::transaction::execute_transaction;
89
90        // For now, execute directly - transaction wrapping can be added later
91        sqlx::query(&self.up_sql)
92            .execute(executor)
93            .await
94            .map(|r| r.rows_affected())
95    }
96}
97
98/// Index-specific migration operations
99pub struct IndexMigration;
100
101impl IndexMigration {
102    /// Create a migration for adding an index
103    pub fn create_index(index: &IndexMeta) -> Migration {
104        let up_sql = index.generate_ddl();
105        let down_sql = format!("DROP INDEX IF EXISTS \"{}\" CASCADE;", index.name);
106
107        Migration::new(
108            format!("add_index_{}", index.name),
109            format!("Add index {} on table {}", index.name, index.table),
110            up_sql,
111        )
112        .with_down(down_sql)
113    }
114
115    /// Create a migration for dropping an index
116    pub fn drop_index(index: &IndexMeta) -> Migration {
117        let up_sql = format!("DROP INDEX IF EXISTS \"{}\" CASCADE;", index.name);
118        let down_sql = index.generate_ddl();
119
120        Migration::new(
121            format!("drop_index_{}", index.name),
122            format!("Drop index {} from table {}", index.name, index.table),
123            up_sql,
124        )
125        .with_down(down_sql)
126    }
127
128    /// Create a migration for modifying an index
129    pub fn modify_index(old_index: &IndexMeta, new_index: &IndexMeta) -> Migration {
130        let up_sql = format!(
131            "-- Drop old index and create new one\n\
132             DROP INDEX IF EXISTS \"{}\" CASCADE;\n\
133             {}",
134            old_index.name,
135            new_index.generate_ddl()
136        );
137
138        let down_sql = format!(
139            "-- Revert to old index\n\
140             DROP INDEX IF EXISTS \"{}\" CASCADE;\n\
141             {}",
142            new_index.name,
143            old_index.generate_ddl()
144        );
145
146        Migration::new(
147            format!("modify_index_{}", old_index.name),
148            format!(
149                "Modify index {} on table {}",
150                old_index.name, old_index.table
151            ),
152            up_sql,
153        )
154        .with_down(down_sql)
155    }
156
157    /// Create a batch migration for multiple index operations
158    pub fn batch_index_operations(operations: Vec<IndexOperation>) -> Migration {
159        let mut up_sql = String::new();
160        let mut down_sql = String::new();
161
162        for op in &operations {
163            match op {
164                IndexOperation::Create(index) => {
165                    up_sql.push_str(&index.generate_ddl());
166                    up_sql.push('\n');
167                    down_sql.push_str(&format!(
168                        "DROP INDEX IF EXISTS \"{}\" CASCADE;\n",
169                        index.name
170                    ));
171                }
172                IndexOperation::Drop(index) => {
173                    up_sql.push_str(&format!(
174                        "DROP INDEX IF EXISTS \"{}\" CASCADE;\n",
175                        index.name
176                    ));
177                    down_sql.push_str(&index.generate_ddl());
178                    down_sql.push('\n');
179                }
180                IndexOperation::Modify { old, new } => {
181                    up_sql.push_str(&format!("DROP INDEX IF EXISTS \"{}\" CASCADE;\n", old.name));
182                    up_sql.push_str(&new.generate_ddl());
183                    up_sql.push('\n');
184                    down_sql.push_str(&format!("DROP INDEX IF EXISTS \"{}\" CASCADE;\n", new.name));
185                    down_sql.push_str(&old.generate_ddl());
186                    down_sql.push('\n');
187                }
188            }
189        }
190
191        Migration::new(
192            "batch_index_operations".to_string(),
193            "Batch index operations".to_string(),
194            up_sql,
195        )
196        .with_down(down_sql)
197    }
198}
199
200/// Event-specific migration operations
201pub struct EventMigration;
202
203impl EventMigration {
204    /// Create a migration for adding an event
205    pub fn create_event(event: &crate::schema::Event) -> Migration {
206        let up_sql = event.generate_ddl();
207        let down_sql = event.generate_drop_ddl();
208
209        Migration::new(
210            format!("add_event_{}", event.name),
211            format!("Add event {} with schedule {}", event.name, event.schedule),
212            up_sql,
213        )
214        .with_down(down_sql)
215    }
216
217    /// Create a migration for dropping an event
218    pub fn drop_event(event: &crate::schema::Event) -> Migration {
219        let up_sql = event.generate_drop_ddl();
220        let down_sql = event.generate_ddl();
221
222        Migration::new(
223            format!("drop_event_{}", event.name),
224            format!("Drop event {} with schedule {}", event.name, event.schedule),
225            up_sql,
226        )
227        .with_down(down_sql)
228    }
229
230    /// Create a migration for modifying an event
231    pub fn modify_event(
232        old_event: &crate::schema::Event,
233        new_event: &crate::schema::Event,
234    ) -> Migration {
235        let up_sql = format!(
236            "-- Modify event {}\n{}\n",
237            new_event.name,
238            new_event.generate_ddl()
239        );
240        let down_sql = format!(
241            "-- Revert event {}\n{}\n",
242            old_event.name,
243            old_event.generate_ddl()
244        );
245
246        Migration::new(
247            format!("modify_event_{}", new_event.name),
248            format!(
249                "Modify event {} schedule from {} to {}",
250                new_event.name, old_event.schedule, new_event.schedule
251            ),
252            up_sql,
253        )
254        .with_down(down_sql)
255    }
256}
257
258/// Composite type-specific migration operations
259pub struct CompositeTypeMigration;
260
261impl CompositeTypeMigration {
262    /// Create a migration for adding a composite type
263    pub fn create_composite_type(composite_type: &CompositeType) -> Migration {
264        let up_sql = composite_type.generate_create_ddl();
265        let down_sql = composite_type.generate_drop_ddl();
266
267        Migration::new(
268            format!("add_composite_type_{}", composite_type.name),
269            format!("Add composite type {}", composite_type.full_name()),
270            up_sql,
271        )
272        .with_down(down_sql)
273    }
274
275    /// Create a migration for dropping a composite type
276    pub fn drop_composite_type(composite_type: &CompositeType) -> Migration {
277        let up_sql = composite_type.generate_drop_ddl();
278        let down_sql = composite_type.generate_create_ddl();
279
280        Migration::new(
281            format!("drop_composite_type_{}", composite_type.name),
282            format!("Drop composite type {}", composite_type.full_name()),
283            up_sql,
284        )
285        .with_down(down_sql)
286    }
287
288    /// Create a migration for modifying a composite type
289    pub fn modify_composite_type(old_type: &CompositeType, new_type: &CompositeType) -> Migration {
290        let up_sql = format!(
291            "-- Modify composite type {}\n{}\n{}",
292            new_type.full_name(),
293            old_type.generate_drop_ddl(),
294            new_type.generate_create_ddl()
295        );
296        let down_sql = format!(
297            "-- Revert composite type {}\n{}\n{}",
298            old_type.full_name(),
299            new_type.generate_drop_ddl(),
300            old_type.generate_create_ddl()
301        );
302
303        Migration::new(
304            format!("modify_composite_type_{}", new_type.name),
305            format!("Modify composite type {}", new_type.full_name()),
306            up_sql,
307        )
308        .with_down(down_sql)
309    }
310
311    /// Create a batch migration for multiple composite type operations
312    pub fn batch_composite_operations(operations: Vec<CompositeTypeOperation>) -> Migration {
313        let mut up_sql = String::new();
314        let mut down_sql = String::new();
315
316        for op in &operations {
317            match op {
318                CompositeTypeOperation::Create(composite_type) => {
319                    up_sql.push_str(&composite_type.generate_create_ddl());
320                    up_sql.push('\n');
321                    down_sql.push_str(&composite_type.generate_drop_ddl());
322                    down_sql.push('\n');
323                }
324                CompositeTypeOperation::Drop(composite_type) => {
325                    up_sql.push_str(&composite_type.generate_drop_ddl());
326                    up_sql.push('\n');
327                    down_sql.push_str(&composite_type.generate_create_ddl());
328                    down_sql.push('\n');
329                }
330                CompositeTypeOperation::Modify { old, new } => {
331                    up_sql.push_str(&old.generate_drop_ddl());
332                    up_sql.push('\n');
333                    up_sql.push_str(&new.generate_create_ddl());
334                    up_sql.push('\n');
335                    down_sql.push_str(&new.generate_drop_ddl());
336                    down_sql.push('\n');
337                    down_sql.push_str(&old.generate_create_ddl());
338                    down_sql.push('\n');
339                }
340            }
341        }
342
343        Migration::new(
344            "batch_composite_type_operations".to_string(),
345            "Batch composite type operations".to_string(),
346            up_sql,
347        )
348        .with_down(down_sql)
349    }
350}
351
352/// Represents different composite type operations for batch processing
353#[derive(Debug, Clone)]
354pub enum CompositeTypeOperation {
355    Create(CompositeType),
356    Drop(CompositeType),
357    Modify {
358        old: CompositeType,
359        new: CompositeType,
360    },
361}
362
363/// Stored procedure-specific migration operations
364pub struct ProcedureMigration;
365
366impl ProcedureMigration {
367    /// Create a migration for adding a stored function
368    pub fn create_function(function: &StoredFunction) -> Migration {
369        let up_sql = function.generate_create_ddl();
370        let down_sql = function.generate_drop_ddl();
371
372        Migration::new(
373            format!("add_function_{}", function.name),
374            format!("Add function {}", function.full_name()),
375            up_sql,
376        )
377        .with_down(down_sql)
378    }
379
380    /// Create a migration for dropping a stored function
381    pub fn drop_function(function: &StoredFunction) -> Migration {
382        let up_sql = function.generate_drop_ddl();
383        let down_sql = function.generate_create_ddl();
384
385        Migration::new(
386            format!("drop_function_{}", function.name),
387            format!("Drop function {}", function.full_name()),
388            up_sql,
389        )
390        .with_down(down_sql)
391    }
392
393    /// Create a migration for modifying a stored function
394    pub fn modify_function(
395        old_function: &StoredFunction,
396        new_function: &StoredFunction,
397    ) -> Migration {
398        let up_sql = format!(
399            "-- Modify function {}\n{}\n{}",
400            new_function.full_name(),
401            old_function.generate_drop_ddl(),
402            new_function.generate_create_ddl()
403        );
404        let down_sql = format!(
405            "-- Revert function {}\n{}\n{}",
406            old_function.full_name(),
407            new_function.generate_drop_ddl(),
408            old_function.generate_create_ddl()
409        );
410
411        Migration::new(
412            format!("modify_function_{}", new_function.name),
413            format!("Modify function {}", new_function.full_name()),
414            up_sql,
415        )
416        .with_down(down_sql)
417    }
418
419    /// Create a migration for adding a stored procedure
420    pub fn create_procedure(procedure: &StoredProcedure) -> Migration {
421        let up_sql = procedure.generate_create_ddl();
422        let down_sql = procedure.generate_drop_ddl();
423
424        Migration::new(
425            format!("add_procedure_{}", procedure.name),
426            format!("Add procedure {}", procedure.full_name()),
427            up_sql,
428        )
429        .with_down(down_sql)
430    }
431
432    /// Create a migration for dropping a stored procedure
433    pub fn drop_procedure(procedure: &StoredProcedure) -> Migration {
434        let up_sql = procedure.generate_drop_ddl();
435        let down_sql = procedure.generate_create_ddl();
436
437        Migration::new(
438            format!("drop_procedure_{}", procedure.name),
439            format!("Drop procedure {}", procedure.full_name()),
440            up_sql,
441        )
442        .with_down(down_sql)
443    }
444
445    /// Create a migration for modifying a stored procedure
446    pub fn modify_procedure(
447        old_procedure: &StoredProcedure,
448        new_procedure: &StoredProcedure,
449    ) -> Migration {
450        let up_sql = format!(
451            "-- Modify procedure {}\n{}\n{}",
452            new_procedure.full_name(),
453            old_procedure.generate_drop_ddl(),
454            new_procedure.generate_create_ddl()
455        );
456        let down_sql = format!(
457            "-- Revert procedure {}\n{}\n{}",
458            old_procedure.full_name(),
459            new_procedure.generate_drop_ddl(),
460            old_procedure.generate_create_ddl()
461        );
462
463        Migration::new(
464            format!("modify_procedure_{}", new_procedure.name),
465            format!("Modify procedure {}", new_procedure.full_name()),
466            up_sql,
467        )
468        .with_down(down_sql)
469    }
470
471    /// Create a batch migration for multiple procedure operations
472    pub fn batch_procedure_operations(operations: Vec<ProcedureOperation>) -> Migration {
473        let mut up_sql = String::new();
474        let mut down_sql = String::new();
475
476        for op in &operations {
477            match op {
478                ProcedureOperation::CreateFunction(function) => {
479                    up_sql.push_str(&function.generate_create_ddl());
480                    up_sql.push('\n');
481                    down_sql.push_str(&function.generate_drop_ddl());
482                    down_sql.push('\n');
483                }
484                ProcedureOperation::DropFunction(function) => {
485                    up_sql.push_str(&function.generate_drop_ddl());
486                    up_sql.push('\n');
487                    down_sql.push_str(&function.generate_create_ddl());
488                    down_sql.push('\n');
489                }
490                ProcedureOperation::ModifyFunction { old, new } => {
491                    up_sql.push_str(&old.generate_drop_ddl());
492                    up_sql.push('\n');
493                    up_sql.push_str(&new.generate_create_ddl());
494                    up_sql.push('\n');
495                    down_sql.push_str(&new.generate_drop_ddl());
496                    down_sql.push('\n');
497                    down_sql.push_str(&old.generate_create_ddl());
498                    down_sql.push('\n');
499                }
500                ProcedureOperation::CreateProcedure(procedure) => {
501                    up_sql.push_str(&procedure.generate_create_ddl());
502                    up_sql.push('\n');
503                    down_sql.push_str(&procedure.generate_drop_ddl());
504                    down_sql.push('\n');
505                }
506                ProcedureOperation::DropProcedure(procedure) => {
507                    up_sql.push_str(&procedure.generate_drop_ddl());
508                    up_sql.push('\n');
509                    down_sql.push_str(&procedure.generate_create_ddl());
510                    down_sql.push('\n');
511                }
512                ProcedureOperation::ModifyProcedure { old, new } => {
513                    up_sql.push_str(&old.generate_drop_ddl());
514                    up_sql.push('\n');
515                    up_sql.push_str(&new.generate_create_ddl());
516                    up_sql.push('\n');
517                    down_sql.push_str(&new.generate_drop_ddl());
518                    down_sql.push('\n');
519                    down_sql.push_str(&old.generate_create_ddl());
520                    down_sql.push('\n');
521                }
522            }
523        }
524
525        Migration::new(
526            "batch_procedure_operations".to_string(),
527            "Batch procedure operations".to_string(),
528            up_sql,
529        )
530        .with_down(down_sql)
531    }
532}
533
534/// Represents different procedure operations for batch processing
535#[derive(Debug, Clone)]
536pub enum ProcedureOperation {
537    CreateFunction(StoredFunction),
538    DropFunction(StoredFunction),
539    ModifyFunction {
540        old: StoredFunction,
541        new: StoredFunction,
542    },
543    CreateProcedure(StoredProcedure),
544    DropProcedure(StoredProcedure),
545    ModifyProcedure {
546        old: StoredProcedure,
547        new: StoredProcedure,
548    },
549}
550
551/// Role-specific migration operations
552pub struct RoleMigration;
553
554impl RoleMigration {
555    /// Create a migration for adding a role
556    pub fn create_role(role: &crate::schema::Role) -> Migration {
557        let up_sql = role.generate_create_ddl();
558        let down_sql = role.generate_drop_ddl();
559
560        Migration::new(
561            format!("add_role_{}", role.name),
562            format!("Add role {}", role.name),
563            up_sql,
564        )
565        .with_down(down_sql)
566    }
567
568    /// Create a migration for dropping a role
569    pub fn drop_role(role: &crate::schema::Role) -> Migration {
570        let up_sql = role.generate_drop_ddl();
571        let down_sql = role.generate_create_ddl();
572
573        Migration::new(
574            format!("drop_role_{}", role.name),
575            format!("Drop role {}", role.name),
576            up_sql,
577        )
578        .with_down(down_sql)
579    }
580
581    /// Create a migration for modifying a role
582    pub fn modify_role(
583        old_role: &crate::schema::Role,
584        new_role: &crate::schema::Role,
585    ) -> Migration {
586        let up_sql = format!(
587            "-- Modify role {}\n{}",
588            new_role.name,
589            new_role.generate_alter_ddl(old_role)
590        );
591        let down_sql = format!(
592            "-- Revert role {}\n{}",
593            old_role.name,
594            old_role.generate_alter_ddl(new_role)
595        );
596
597        Migration::new(
598            format!("modify_role_{}", new_role.name),
599            format!("Modify role {}", new_role.name),
600            up_sql,
601        )
602        .with_down(down_sql)
603    }
604}
605
606/// Grant-specific migration operations
607pub struct GrantMigration;
608
609impl GrantMigration {
610    /// Create a migration for adding a grant
611    pub fn create_grant(grant: &crate::schema::Grant) -> Migration {
612        let up_sql = grant.generate_grant_ddl();
613        let down_sql = grant.generate_revoke_ddl();
614
615        Migration::new(
616            format!("add_grant_{}", grant.generate_name()),
617            format!("Grant {} to {}", grant.privilege_name(), grant.grantee),
618            up_sql,
619        )
620        .with_down(down_sql)
621    }
622
623    /// Create a migration for revoking a grant
624    pub fn revoke_grant(grant: &crate::schema::Grant) -> Migration {
625        let up_sql = grant.generate_revoke_ddl();
626        let down_sql = grant.generate_grant_ddl();
627
628        Migration::new(
629            format!("revoke_grant_{}", grant.generate_name()),
630            format!("Revoke {} from {}", grant.privilege_name(), grant.grantee),
631            up_sql,
632        )
633        .with_down(down_sql)
634    }
635
636    /// Create a migration for modifying a grant
637    pub fn modify_grant(
638        old_grant: &crate::schema::Grant,
639        new_grant: &crate::schema::Grant,
640    ) -> Migration {
641        let up_sql = format!(
642            "-- Modify grant {}\n{}\n{}",
643            new_grant.generate_name(),
644            old_grant.generate_revoke_ddl(),
645            new_grant.generate_grant_ddl()
646        );
647        let down_sql = format!(
648            "-- Revert grant {}\n{}\n{}",
649            old_grant.generate_name(),
650            new_grant.generate_revoke_ddl(),
651            old_grant.generate_grant_ddl()
652        );
653
654        Migration::new(
655            format!("modify_grant_{}", new_grant.generate_name()),
656            format!("Modify grant {}", new_grant.generate_name()),
657            up_sql,
658        )
659        .with_down(down_sql)
660    }
661}
662
663/// Represents an index operation for batch migrations
664#[derive(Debug, Clone)]
665pub enum IndexOperation {
666    Create(IndexMeta),
667    Drop(IndexMeta),
668    Modify { old: IndexMeta, new: IndexMeta },
669}
670
671/// Migration runner for applying migrations
672pub struct MigrationRunner {
673    migrations: Vec<Migration>,
674}
675
676impl MigrationRunner {
677    /// Create a new migration runner
678    pub fn new() -> Self {
679        Self {
680            migrations: Vec::new(),
681        }
682    }
683
684    /// Add a migration to the runner
685    pub fn add_migration(mut self, migration: Migration) -> Self {
686        self.migrations.push(migration);
687        self
688    }
689
690    /// Get all migrations
691    pub fn migrations(&self) -> &[Migration] {
692        &self.migrations
693    }
694
695    /// Generate migration files in the given directory
696    pub fn generate_files(&self, dir: &Path) -> Result<()> {
697        use std::fs;
698
699        for migration in &self.migrations {
700            let migration_dir = dir.join(&migration.id);
701            fs::create_dir_all(&migration_dir)?;
702
703            // Write up.sql
704            fs::write(migration_dir.join("up.sql"), &migration.up_sql)?;
705
706            // Write down.sql if it exists
707            if let Some(ref down_sql) = migration.down_sql {
708                fs::write(migration_dir.join("down.sql"), down_sql)?;
709            }
710        }
711
712        Ok(())
713    }
714}
715
716/// Schema migration manager for handling table and view changes
717pub struct SchemaMigrationManager {
718    old_tables: HashMap<String, Table>,
719    new_tables: HashMap<String, Table>,
720    old_views: HashMap<String, crate::schema::View>,
721    new_views: HashMap<String, crate::schema::View>,
722    old_functions: HashMap<String, crate::schema::StoredFunction>,
723    new_functions: HashMap<String, crate::schema::StoredFunction>,
724    old_procedures: HashMap<String, crate::schema::StoredProcedure>,
725    new_procedures: HashMap<String, crate::schema::StoredProcedure>,
726    old_triggers: HashMap<String, crate::schema::Trigger>,
727    new_triggers: HashMap<String, crate::schema::Trigger>,
728    old_composite_types: HashMap<String, crate::schema::CompositeType>,
729    new_composite_types: HashMap<String, crate::schema::CompositeType>,
730}
731
732impl SchemaMigrationManager {
733    /// Create a new schema migration manager
734    pub fn new() -> Self {
735        Self {
736            old_tables: HashMap::new(),
737            new_tables: HashMap::new(),
738            old_views: HashMap::new(),
739            new_views: HashMap::new(),
740            old_functions: HashMap::new(),
741            new_functions: HashMap::new(),
742            old_procedures: HashMap::new(),
743            new_procedures: HashMap::new(),
744            old_triggers: HashMap::new(),
745            new_triggers: HashMap::new(),
746            old_composite_types: HashMap::new(),
747            new_composite_types: HashMap::new(),
748        }
749    }
750
751    /// Set the old schema state
752    pub fn set_old_schema(mut self, tables: HashMap<String, Table>) -> Self {
753        self.old_tables = tables;
754        self
755    }
756
757    /// Set the new schema state
758    pub fn set_new_schema(mut self, tables: HashMap<String, Table>) -> Self {
759        self.new_tables = tables;
760        self
761    }
762
763    /// Set the old view schema state
764    pub fn set_old_views(mut self, views: HashMap<String, crate::schema::View>) -> Self {
765        self.old_views = views;
766        self
767    }
768
769    /// Set the new view schema state
770    pub fn set_new_views(mut self, views: HashMap<String, crate::schema::View>) -> Self {
771        self.new_views = views;
772        self
773    }
774
775    /// Set the old functions
776    pub fn set_old_functions(
777        mut self,
778        functions: HashMap<String, crate::schema::StoredFunction>,
779    ) -> Self {
780        self.old_functions = functions;
781        self
782    }
783
784    /// Set the new functions
785    pub fn set_new_functions(
786        mut self,
787        functions: HashMap<String, crate::schema::StoredFunction>,
788    ) -> Self {
789        self.new_functions = functions;
790        self
791    }
792
793    /// Set the old procedures
794    pub fn set_old_procedures(
795        mut self,
796        procedures: HashMap<String, crate::schema::StoredProcedure>,
797    ) -> Self {
798        self.old_procedures = procedures;
799        self
800    }
801
802    /// Set the new procedures
803    pub fn set_new_procedures(
804        mut self,
805        procedures: HashMap<String, crate::schema::StoredProcedure>,
806    ) -> Self {
807        self.new_procedures = procedures;
808        self
809    }
810
811    /// Set the old triggers
812    pub fn set_old_triggers(mut self, triggers: HashMap<String, crate::schema::Trigger>) -> Self {
813        self.old_triggers = triggers;
814        self
815    }
816
817    /// Set the new triggers
818    pub fn set_new_triggers(mut self, triggers: HashMap<String, crate::schema::Trigger>) -> Self {
819        self.new_triggers = triggers;
820        self
821    }
822
823    /// Set the old composite types
824    pub fn set_old_composite_types(
825        mut self,
826        composite_types: HashMap<String, crate::schema::CompositeType>,
827    ) -> Self {
828        self.old_composite_types = composite_types;
829        self
830    }
831
832    /// Set the new composite types
833    pub fn set_new_composite_types(
834        mut self,
835        composite_types: HashMap<String, crate::schema::CompositeType>,
836    ) -> Self {
837        self.new_composite_types = composite_types;
838        self
839    }
840
841    /// Generate a migration from the schema differences
842    pub fn generate_migration(&self, name: &str) -> Result<Migration> {
843        // Detect schema differences for all object types
844        let table_diffs = SchemaDiffEngine::compare_tables(&self.old_tables, &self.new_tables);
845        let view_diffs = SchemaDiffEngine::compare_views(&self.old_views, &self.new_views);
846        let function_diffs =
847            SchemaDiffEngine::compare_functions(&self.old_functions, &self.new_functions);
848        let procedure_diffs =
849            SchemaDiffEngine::compare_procedures(&self.old_procedures, &self.new_procedures);
850        let trigger_diffs =
851            SchemaDiffEngine::compare_triggers(&self.old_triggers, &self.new_triggers);
852        let composite_type_diffs = SchemaDiffEngine::compare_composite_types(
853            &self.old_composite_types,
854            &self.new_composite_types,
855        );
856
857        // Check if any changes were detected
858        if table_diffs.is_empty()
859            && view_diffs.is_empty()
860            && function_diffs.is_empty()
861            && procedure_diffs.is_empty()
862            && trigger_diffs.is_empty()
863            && composite_type_diffs.is_empty()
864        {
865            return Err(anyhow::anyhow!("No schema changes detected"));
866        }
867
868        // Generate the migration SQL for tables
869        let table_up_sql = if table_diffs.is_empty() {
870            String::new()
871        } else {
872            MigrationGenerator::generate_table_migration(&table_diffs)
873        };
874
875        // Generate the migration SQL for views
876        let view_up_sql = if view_diffs.is_empty() {
877            String::new()
878        } else {
879            MigrationGenerator::generate_view_migration(&view_diffs)
880        };
881
882        // Generate the migration SQL for functions
883        let function_up_sql = if function_diffs.is_empty() {
884            String::new()
885        } else {
886            MigrationGenerator::generate_migration(&function_diffs)
887        };
888
889        // Generate the migration SQL for procedures
890        let procedure_up_sql = if procedure_diffs.is_empty() {
891            String::new()
892        } else {
893            MigrationGenerator::generate_migration(&procedure_diffs)
894        };
895
896        // Generate the migration SQL for triggers
897        let trigger_up_sql = if trigger_diffs.is_empty() {
898            String::new()
899        } else {
900            MigrationGenerator::generate_migration(&trigger_diffs)
901        };
902
903        // Generate the migration SQL for composite types
904        let composite_type_up_sql = if composite_type_diffs.is_empty() {
905            String::new()
906        } else {
907            MigrationGenerator::generate_migration(&composite_type_diffs)
908        };
909
910        // Combine all migration SQL sections
911        let mut up_sql_parts = Vec::new();
912
913        if !table_up_sql.is_empty() {
914            up_sql_parts.push(format!("-- Table Changes\n{}", table_up_sql));
915        }
916        if !view_up_sql.is_empty() {
917            up_sql_parts.push(format!("-- View Changes\n{}", view_up_sql));
918        }
919        if !function_up_sql.is_empty() {
920            up_sql_parts.push(format!("-- Function Changes\n{}", function_up_sql));
921        }
922        if !procedure_up_sql.is_empty() {
923            up_sql_parts.push(format!("-- Procedure Changes\n{}", procedure_up_sql));
924        }
925        if !trigger_up_sql.is_empty() {
926            up_sql_parts.push(format!("-- Trigger Changes\n{}", trigger_up_sql));
927        }
928        if !composite_type_up_sql.is_empty() {
929            up_sql_parts.push(format!(
930                "-- Composite Type Changes\n{}",
931                composite_type_up_sql
932            ));
933        }
934
935        let up_sql = up_sql_parts.join("\n\n");
936
937        // Generate down migration (reverse operations)
938        let down_sql = self.generate_down_migration(
939            &table_diffs,
940            &view_diffs,
941            &function_diffs,
942            &procedure_diffs,
943            &trigger_diffs,
944            &composite_type_diffs,
945        );
946
947        // Create migration ID (timestamp-based)
948        let id = chrono::Utc::now().format("%Y%m%d_%H%M%S").to_string();
949
950        Ok(Migration::new(id, name, up_sql).with_down(down_sql))
951    }
952
953    /// Generate the down migration (reverse operations)
954    fn generate_down_migration(
955        &self,
956        table_diffs: &[schema_diff::SchemaDiff],
957        view_diffs: &[schema_diff::SchemaDiff],
958        function_diffs: &[schema_diff::SchemaDiff],
959        procedure_diffs: &[schema_diff::SchemaDiff],
960        trigger_diffs: &[schema_diff::SchemaDiff],
961        composite_type_diffs: &[schema_diff::SchemaDiff],
962    ) -> String {
963        let mut down_sql = String::new();
964
965        // Process table diffs in reverse order
966        for diff in table_diffs.iter().rev() {
967            match diff {
968                schema_diff::SchemaDiff::TableAdded { name, .. } => {
969                    down_sql.push_str(&format!("-- Drop table {}\n", name));
970                    down_sql.push_str(&format!("DROP TABLE IF EXISTS \"{}\" CASCADE;\n\n", name));
971                }
972                schema_diff::SchemaDiff::TableDropped { name, table } => {
973                    down_sql.push_str(&format!("-- Recreate table {}\n", name));
974                    down_sql.push_str(&table.generate_ddl());
975                    down_sql.push_str("\n\n");
976                }
977                schema_diff::SchemaDiff::TableModified {
978                    name,
979                    old_table,
980                    new_table,
981                } => {
982                    down_sql.push_str(&format!("-- Modify table {}\n", name));
983                    // Generate reverse operations for table modifications
984                    let reverse_changes =
985                        self.generate_reverse_table_change_sql(name, old_table, new_table);
986                    down_sql.push_str(&reverse_changes);
987                    down_sql.push_str("\n");
988                }
989                _ => {} // Ignore other diffs in table processing
990            }
991        }
992
993        // Process view diffs in reverse order
994        for diff in view_diffs.iter().rev() {
995            match diff {
996                schema_diff::SchemaDiff::ViewAdded { name, .. } => {
997                    down_sql.push_str(&format!("-- Drop view {}\n", name));
998                    down_sql.push_str(&format!("DROP VIEW IF EXISTS \"{}\" CASCADE;\n\n", name));
999                }
1000                schema_diff::SchemaDiff::ViewDropped { name, view } => {
1001                    down_sql.push_str(&format!("-- Recreate view {}\n", name));
1002                    down_sql.push_str(&view.generate_ddl());
1003                    down_sql.push_str("\n\n");
1004                }
1005                schema_diff::SchemaDiff::ViewModified {
1006                    name,
1007                    old_view,
1008                    new_view,
1009                } => {
1010                    down_sql.push_str(&format!("-- Modify view {}\n", name));
1011                    // Generate reverse operations for view modifications
1012                    let reverse_changes =
1013                        self.generate_reverse_view_change_sql(name, old_view, new_view);
1014                    down_sql.push_str(&reverse_changes);
1015                    down_sql.push_str("\n");
1016                }
1017                _ => {} // Ignore table diffs in view processing
1018            }
1019        }
1020
1021        // Process function diffs in reverse order
1022        for diff in function_diffs.iter().rev() {
1023            match diff {
1024                schema_diff::SchemaDiff::FunctionAdded { name, .. } => {
1025                    down_sql.push_str(&format!("-- Drop function {}\n", name));
1026                    down_sql.push_str(&format!(
1027                        "DROP FUNCTION IF EXISTS \"{}\" CASCADE;\n\n",
1028                        name
1029                    ));
1030                }
1031                schema_diff::SchemaDiff::FunctionDropped { name, function } => {
1032                    down_sql.push_str(&format!("-- Recreate function {}\n", name));
1033                    down_sql.push_str(&function.generate_create_ddl());
1034                    down_sql.push_str("\n\n");
1035                }
1036                schema_diff::SchemaDiff::FunctionModified {
1037                    name,
1038                    old_function,
1039                    new_function: _,
1040                } => {
1041                    down_sql.push_str(&format!("-- Rollback function modification {}\n", name));
1042                    down_sql.push_str(&format!("DROP FUNCTION IF EXISTS \"{}\" CASCADE;\n", name));
1043                    down_sql.push_str(&old_function.generate_create_ddl());
1044                    down_sql.push_str("\n");
1045                }
1046                _ => {} // Ignore other diffs in function processing
1047            }
1048        }
1049
1050        // Process procedure diffs in reverse order
1051        for diff in procedure_diffs.iter().rev() {
1052            match diff {
1053                schema_diff::SchemaDiff::ProcedureAdded { name, .. } => {
1054                    down_sql.push_str(&format!("-- Drop procedure {}\n", name));
1055                    down_sql.push_str(&format!(
1056                        "DROP PROCEDURE IF EXISTS \"{}\" CASCADE;\n\n",
1057                        name
1058                    ));
1059                }
1060                schema_diff::SchemaDiff::ProcedureDropped { name, procedure } => {
1061                    down_sql.push_str(&format!("-- Recreate procedure {}\n", name));
1062                    down_sql.push_str(&procedure.generate_create_ddl());
1063                    down_sql.push_str("\n\n");
1064                }
1065                schema_diff::SchemaDiff::ProcedureModified {
1066                    name,
1067                    old_procedure,
1068                    new_procedure: _,
1069                } => {
1070                    down_sql.push_str(&format!("-- Rollback procedure modification {}\n", name));
1071                    down_sql.push_str(&format!("DROP PROCEDURE IF EXISTS \"{}\" CASCADE;\n", name));
1072                    down_sql.push_str(&old_procedure.generate_create_ddl());
1073                    down_sql.push_str("\n");
1074                }
1075                _ => {} // Ignore other diffs in procedure processing
1076            }
1077        }
1078
1079        // Process trigger diffs in reverse order
1080        for diff in trigger_diffs.iter().rev() {
1081            match diff {
1082                schema_diff::SchemaDiff::TriggerAdded { name, .. } => {
1083                    down_sql.push_str(&format!("-- Drop trigger {}\n", name));
1084                    down_sql.push_str(&format!("DROP TRIGGER IF EXISTS \"{}\" CASCADE;\n\n", name));
1085                }
1086                schema_diff::SchemaDiff::TriggerDropped { name, trigger } => {
1087                    down_sql.push_str(&format!("-- Recreate trigger {}\n", name));
1088                    down_sql.push_str(&trigger.generate_create_ddl());
1089                    down_sql.push_str("\n\n");
1090                }
1091                schema_diff::SchemaDiff::TriggerModified {
1092                    name,
1093                    old_trigger,
1094                    new_trigger: _,
1095                } => {
1096                    down_sql.push_str(&format!("-- Rollback trigger modification {}\n", name));
1097                    down_sql.push_str(&format!("DROP TRIGGER IF EXISTS \"{}\" CASCADE;\n", name));
1098                    down_sql.push_str(&old_trigger.generate_create_ddl());
1099                    down_sql.push_str("\n");
1100                }
1101                _ => {} // Ignore other diffs in trigger processing
1102            }
1103        }
1104
1105        // Process composite type diffs in reverse order
1106        for diff in composite_type_diffs.iter().rev() {
1107            match diff {
1108                schema_diff::SchemaDiff::CompositeTypeAdded { name, .. } => {
1109                    down_sql.push_str(&format!("-- Drop composite type {}\n", name));
1110                    down_sql.push_str(&format!("DROP TYPE IF EXISTS \"{}\" CASCADE;\n\n", name));
1111                }
1112                schema_diff::SchemaDiff::CompositeTypeDropped {
1113                    name,
1114                    composite_type,
1115                } => {
1116                    down_sql.push_str(&format!("-- Recreate composite type {}\n", name));
1117                    down_sql.push_str(&composite_type.generate_create_ddl());
1118                    down_sql.push_str("\n\n");
1119                }
1120                schema_diff::SchemaDiff::CompositeTypeModified {
1121                    name,
1122                    old_composite_type,
1123                    new_composite_type: _,
1124                } => {
1125                    down_sql.push_str(&format!(
1126                        "-- Rollback composite type modification {}\n",
1127                        name
1128                    ));
1129                    down_sql.push_str(&format!("DROP TYPE IF EXISTS \"{}\" CASCADE;\n", name));
1130                    down_sql.push_str(&old_composite_type.generate_create_ddl());
1131                    down_sql.push_str("\n");
1132                }
1133                _ => {} // Ignore other diffs in composite type processing
1134            }
1135        }
1136
1137        down_sql
1138    }
1139
1140    /// Generate reverse SQL for table modifications (for down migrations)
1141    fn generate_reverse_table_change_sql(
1142        &self,
1143        table_name: &str,
1144        old_table: &Table,
1145        new_table: &Table,
1146    ) -> String {
1147        let mut reverse_sql = String::new();
1148
1149        // Create column maps for easy comparison
1150        let old_columns: HashMap<&String, &Column> =
1151            old_table.columns.iter().map(|c| (&c.name, c)).collect();
1152        let new_columns: HashMap<&String, &Column> =
1153            new_table.columns.iter().map(|c| (&c.name, c)).collect();
1154
1155        // Find added columns (in new but not in old) - reverse is DROP COLUMN
1156        for column in &new_table.columns {
1157            if !old_columns.contains_key(&column.name) {
1158                reverse_sql.push_str(&format!(
1159                    "ALTER TABLE \"{}\" DROP COLUMN \"{}\" CASCADE;\n",
1160                    table_name, column.name
1161                ));
1162            }
1163        }
1164
1165        // Find dropped columns (in old but not in new) - reverse is ADD COLUMN
1166        for column in &old_table.columns {
1167            if !new_columns.contains_key(&column.name) {
1168                reverse_sql.push_str(&format!(
1169                    "ALTER TABLE \"{}\" ADD COLUMN {};\n",
1170                    table_name,
1171                    column.to_sql().trim_start_matches("    ")
1172                ));
1173            }
1174        }
1175
1176        // Find modified columns - reverse is DROP new column and ADD old column
1177        for new_column in &new_table.columns {
1178            if let Some(old_column) = old_columns.get(&new_column.name) {
1179                if !self.columns_equal(old_column, new_column) {
1180                    reverse_sql.push_str(&format!(
1181                        "ALTER TABLE \"{}\" DROP COLUMN \"{}\" CASCADE;\n",
1182                        table_name, new_column.name
1183                    ));
1184                    reverse_sql.push_str(&format!(
1185                        "ALTER TABLE \"{}\" ADD COLUMN {};\n",
1186                        table_name,
1187                        old_column.to_sql().trim_start_matches("    ")
1188                    ));
1189                }
1190            }
1191        }
1192
1193        // Handle primary key changes
1194        if old_table.primary_key != new_table.primary_key {
1195            if let Some(_new_pk) = &new_table.primary_key {
1196                reverse_sql.push_str(&format!(
1197                    "ALTER TABLE \"{}\" DROP CONSTRAINT IF EXISTS \"{}_pkey\" CASCADE;\n",
1198                    table_name, table_name
1199                ));
1200            }
1201            if let Some(old_pk) = &old_table.primary_key {
1202                reverse_sql.push_str(&format!(
1203                    "ALTER TABLE \"{}\" ADD PRIMARY KEY (\"{}\");\n",
1204                    table_name, old_pk
1205                ));
1206            }
1207        }
1208
1209        reverse_sql
1210    }
1211
1212    /// Generate reverse SQL for view modifications (for down migrations)
1213    fn generate_reverse_view_change_sql(
1214        &self,
1215        view_name: &str,
1216        old_view: &View,
1217        new_view: &View,
1218    ) -> String {
1219        let mut reverse_sql = String::new();
1220
1221        reverse_sql.push_str(&format!("-- Revert changes to view {}\n", view_name));
1222
1223        // Handle materialized status changes
1224        if old_view.materialized != new_view.materialized {
1225            if new_view.materialized && !old_view.materialized {
1226                // Convert back from materialized to regular view
1227                reverse_sql.push_str(&format!(
1228                    "-- Convert view {} back to regular view\n",
1229                    view_name
1230                ));
1231                reverse_sql.push_str(&format!(
1232                    "DROP MATERIALIZED VIEW IF EXISTS \"{}\" CASCADE;\n",
1233                    view_name
1234                ));
1235                reverse_sql.push_str(&old_view.generate_ddl());
1236                reverse_sql.push_str("\n");
1237            } else if !new_view.materialized && old_view.materialized {
1238                // Convert back from regular to materialized view
1239                reverse_sql.push_str(&format!(
1240                    "-- Convert view {} back to materialized view\n",
1241                    view_name
1242                ));
1243                reverse_sql.push_str(&format!("DROP VIEW IF EXISTS \"{}\" CASCADE;\n", view_name));
1244                reverse_sql.push_str(&old_view.generate_ddl());
1245                reverse_sql.push_str("\n");
1246            }
1247        }
1248
1249        // Handle dependency changes
1250        if old_view.dependencies != new_view.dependencies {
1251            let added: Vec<_> = new_view
1252                .dependencies
1253                .iter()
1254                .filter(|d| !old_view.dependencies.contains(d))
1255                .collect();
1256            let removed: Vec<_> = old_view
1257                .dependencies
1258                .iter()
1259                .filter(|d| !new_view.dependencies.contains(d))
1260                .collect();
1261
1262            if !added.is_empty() {
1263                let added_names: Vec<String> = added.iter().map(|&s| s.clone()).collect();
1264                reverse_sql.push_str(&format!(
1265                    "-- View {} no longer depends on: {}\n",
1266                    view_name,
1267                    added_names.join(", ")
1268                ));
1269            }
1270            if !removed.is_empty() {
1271                let removed_names: Vec<String> = removed.iter().map(|&s| s.clone()).collect();
1272                reverse_sql.push_str(&format!(
1273                    "-- View {} now depends on: {}\n",
1274                    view_name,
1275                    removed_names.join(", ")
1276                ));
1277            }
1278        }
1279
1280        // Handle index changes
1281        if old_view.indexes != new_view.indexes {
1282            let added: Vec<_> = new_view
1283                .indexes
1284                .iter()
1285                .filter(|i| !old_view.indexes.contains(i))
1286                .collect();
1287            let removed: Vec<_> = old_view
1288                .indexes
1289                .iter()
1290                .filter(|i| !new_view.indexes.contains(i))
1291                .collect();
1292
1293            for added_index in added {
1294                reverse_sql.push_str(&format!(
1295                    "DROP INDEX IF EXISTS \"{}\" CASCADE;\n",
1296                    added_index.name
1297                ));
1298            }
1299            for removed_index in removed {
1300                reverse_sql.push_str(&removed_index.to_sql());
1301                reverse_sql.push_str("\n");
1302            }
1303        }
1304
1305        // Handle column changes
1306        let old_columns: HashMap<&String, &Column> =
1307            old_view.columns.iter().map(|c| (&c.name, c)).collect();
1308        let new_columns: HashMap<&String, &Column> =
1309            new_view.columns.iter().map(|c| (&c.name, c)).collect();
1310
1311        // Find added columns (in new but not in old) - reverse is DROP COLUMN
1312        for column in &new_view.columns {
1313            if !old_columns.contains_key(&column.name) {
1314                reverse_sql.push_str(&format!(
1315                    "-- Remove column {} from view {}\n",
1316                    column.name, view_name
1317                ));
1318            }
1319        }
1320
1321        // Find dropped columns (in old but not in new) - reverse is ADD COLUMN
1322        for column in &old_view.columns {
1323            if !new_columns.contains_key(&column.name) {
1324                reverse_sql.push_str(&format!(
1325                    "-- Add column {} back to view {}\n",
1326                    column.name, view_name
1327                ));
1328            }
1329        }
1330
1331        reverse_sql
1332    }
1333
1334    /// Compare two columns for equality
1335    fn columns_equal(&self, old_column: &Column, new_column: &Column) -> bool {
1336        old_column.name == new_column.name
1337            && old_column.column_type == new_column.column_type
1338            && old_column.nullable == new_column.nullable
1339            && old_column.default == new_column.default
1340            && old_column.unique == new_column.unique
1341            && old_column.references == new_column.references
1342    }
1343
1344    /// Generate reverse SQL for a table change (legacy method)
1345    #[allow(dead_code)]
1346    fn generate_reverse_table_change_sql_legacy(
1347        &self,
1348        table_name: &str,
1349        change: &schema_diff::TableChange,
1350    ) -> String {
1351        match change {
1352            schema_diff::TableChange::ColumnAdded { name, .. } => {
1353                format!(
1354                    "ALTER TABLE \"{}\" DROP COLUMN \"{}\" CASCADE;\n",
1355                    table_name, name
1356                )
1357            }
1358            schema_diff::TableChange::ColumnDropped {
1359                name: _name,
1360                column,
1361            } => {
1362                format!(
1363                    "ALTER TABLE \"{}\" ADD COLUMN {};\n",
1364                    table_name,
1365                    column.to_sql().trim_start_matches("    ")
1366                )
1367            }
1368            schema_diff::TableChange::ColumnModified {
1369                name, old_column, ..
1370            } => {
1371                let mut sql = String::new();
1372
1373                // Drop the new column and add the old one back
1374                sql.push_str(&format!(
1375                    "ALTER TABLE \"{}\" DROP COLUMN \"{}\" CASCADE;\n",
1376                    table_name, name
1377                ));
1378                sql.push_str(&format!(
1379                    "ALTER TABLE \"{}\" ADD COLUMN {};\n",
1380                    table_name,
1381                    old_column.to_sql().trim_start_matches("    ")
1382                ));
1383
1384                sql
1385            }
1386            schema_diff::TableChange::PrimaryKeyChanged { old_pk, new_pk } => {
1387                let mut sql = String::new();
1388
1389                // Drop new primary key if it exists
1390                if let Some(_new_pk) = new_pk {
1391                    sql.push_str(&format!(
1392                        "ALTER TABLE \"{}\" DROP CONSTRAINT IF EXISTS \"{}_pkey\" CASCADE;\n",
1393                        table_name, table_name
1394                    ));
1395                }
1396
1397                // Add old primary key back if it existed
1398                if let Some(old_pk) = old_pk {
1399                    sql.push_str(&format!(
1400                        "ALTER TABLE \"{}\" ADD PRIMARY KEY (\"{}\");\n",
1401                        table_name, old_pk
1402                    ));
1403                }
1404
1405                sql
1406            }
1407            schema_diff::TableChange::IndexesChanged {
1408                old_indexes,
1409                new_indexes,
1410            } => {
1411                let mut sql = String::new();
1412                for old_index in old_indexes {
1413                    sql.push_str(&format!(
1414                        "DROP INDEX IF EXISTS \"{}\" CASCADE;\n",
1415                        old_index.name
1416                    ));
1417                }
1418                for new_index in new_indexes {
1419                    sql.push_str(&new_index.generate_ddl());
1420                    sql.push_str("\n");
1421                }
1422                sql
1423            }
1424        }
1425    }
1426
1427    /// Generate reverse SQL for a view change (legacy method)
1428    #[allow(dead_code)]
1429    fn generate_reverse_view_change_sql_legacy(
1430        &self,
1431        view_name: &str,
1432        change: &schema_diff::ViewChange,
1433    ) -> String {
1434        match change {
1435            schema_diff::ViewChange::ColumnAdded { name, .. } => {
1436                format!(
1437                    "ALTER VIEW \"{}\" DROP COLUMN \"{}\" CASCADE;\n",
1438                    view_name, name
1439                )
1440            }
1441            schema_diff::ViewChange::ColumnDropped {
1442                name: _name,
1443                column,
1444            } => {
1445                format!(
1446                    "ALTER VIEW \"{}\" ADD COLUMN {};\n",
1447                    view_name,
1448                    column.to_sql().trim_start_matches("    ")
1449                )
1450            }
1451            schema_diff::ViewChange::ColumnModified {
1452                name, old_column, ..
1453            } => {
1454                let mut sql = String::new();
1455
1456                // Drop the new column and add the old one back
1457                sql.push_str(&format!(
1458                    "ALTER VIEW \"{}\" DROP COLUMN \"{}\" CASCADE;\n",
1459                    view_name, name
1460                ));
1461                sql.push_str(&format!(
1462                    "ALTER VIEW \"{}\" ADD COLUMN {};\n",
1463                    view_name,
1464                    old_column.to_sql().trim_start_matches("    ")
1465                ));
1466
1467                sql
1468            }
1469            schema_diff::ViewChange::PrimaryKeyChanged { old_pk, new_pk } => {
1470                let mut sql = String::new();
1471
1472                // Drop new primary key if it exists
1473                if let Some(_new_pk) = new_pk {
1474                    sql.push_str(&format!(
1475                        "ALTER VIEW \"{}\" DROP CONSTRAINT IF EXISTS \"{}_pkey\" CASCADE;\n",
1476                        view_name, view_name
1477                    ));
1478                }
1479
1480                // Add old primary key back if it existed
1481                if let Some(old_pk) = old_pk {
1482                    sql.push_str(&format!(
1483                        "ALTER VIEW \"{}\" ADD PRIMARY KEY (\"{}\");\n",
1484                        view_name, old_pk
1485                    ));
1486                }
1487
1488                sql
1489            }
1490            schema_diff::ViewChange::MaterializedChanged {
1491                was_materialized,
1492                is_materialized,
1493            } => {
1494                if *was_materialized && !*is_materialized {
1495                    // Convert back to materialized view
1496                    format!("-- Convert view {} back to materialized view\n", view_name)
1497                } else if !*was_materialized && *is_materialized {
1498                    // Convert back to regular view
1499                    format!("-- Convert view {} back to regular view\n", view_name)
1500                } else {
1501                    String::new()
1502                }
1503            }
1504            schema_diff::ViewChange::DependenciesChanged { old_deps, new_deps } => {
1505                let mut sql = String::new();
1506                let added: Vec<_> = new_deps.iter().filter(|d| !old_deps.contains(d)).collect();
1507                let removed: Vec<_> = old_deps.iter().filter(|d| !new_deps.contains(d)).collect();
1508
1509                if !added.is_empty() {
1510                    let added_names: Vec<String> = added.iter().map(|s| (*s).clone()).collect();
1511                    sql.push_str(&format!(
1512                        "-- Remove dependencies from view {}: {}\n",
1513                        view_name,
1514                        added_names.join(", ")
1515                    ));
1516                }
1517                if !removed.is_empty() {
1518                    let removed_names: Vec<String> = removed.iter().map(|s| (*s).clone()).collect();
1519                    sql.push_str(&format!(
1520                        "-- Restore dependencies to view {}: {}\n",
1521                        view_name,
1522                        removed_names.join(", ")
1523                    ));
1524                }
1525                sql
1526            }
1527            schema_diff::ViewChange::IndexesChanged {
1528                old_indexes,
1529                new_indexes,
1530            } => {
1531                let mut sql = String::new();
1532                let added: Vec<_> = new_indexes
1533                    .iter()
1534                    .filter(|i| !old_indexes.contains(i))
1535                    .collect();
1536                let removed: Vec<_> = old_indexes
1537                    .iter()
1538                    .filter(|i| !new_indexes.contains(i))
1539                    .collect();
1540
1541                if !added.is_empty() {
1542                    let added_names: Vec<String> = added.iter().map(|i| i.name.clone()).collect();
1543                    sql.push_str(&format!(
1544                        "-- Drop indexes from view {}: {}\n",
1545                        view_name,
1546                        added_names.join(", ")
1547                    ));
1548                }
1549                if !removed.is_empty() {
1550                    let removed_names: Vec<String> =
1551                        removed.iter().map(|i| i.name.clone()).collect();
1552                    sql.push_str(&format!(
1553                        "-- Restore indexes to view {}: {}\n",
1554                        view_name,
1555                        removed_names.join(", ")
1556                    ));
1557                }
1558                sql
1559            }
1560        }
1561    }
1562}
1563
1564/// Execute SQL that may contain multiple statements
1565async fn execute_multi_statement_sql(
1566    sql: &str,
1567    executor: &mut sqlx::PgConnection,
1568) -> sqlx::Result<()> {
1569    // Split SQL by semicolons and process each statement
1570    let raw_statements: Vec<&str> = sql.split(';').collect();
1571    let mut statements = Vec::new();
1572
1573    for raw_stmt in raw_statements {
1574        // Clean up the statement - remove comments and empty lines
1575        let cleaned_lines: Vec<&str> = raw_stmt
1576            .lines()
1577            .map(|line| line.trim())
1578            .filter(|line| !line.is_empty() && !line.starts_with("--"))
1579            .collect();
1580
1581        let cleaned_stmt = cleaned_lines.join("\n").trim().to_string();
1582
1583        if !cleaned_stmt.is_empty() {
1584            statements.push(cleaned_stmt);
1585        }
1586    }
1587
1588    for statement in statements {
1589        if !statement.trim().is_empty() {
1590            sqlx::query(&statement).execute(&mut *executor).await?;
1591        }
1592    }
1593
1594    Ok(())
1595}
1596
1597/// Simple migration manager for CLI operations
1598pub struct MigrationManager {
1599    pool: sqlx::PgPool,
1600    migrations_dir: std::path::PathBuf,
1601    database_type: Option<crate::database::DatabaseType>,
1602}
1603
1604impl MigrationManager {
1605    /// Create a new migration manager
1606    pub fn new(pool: sqlx::PgPool, migrations_dir: std::path::PathBuf) -> Self {
1607        Self {
1608            pool,
1609            migrations_dir,
1610            database_type: Some(crate::database::DatabaseType::PostgreSQL), // Default to PostgreSQL
1611        }
1612    }
1613
1614    /// Create a new multi-platform migration manager
1615    pub fn new_multi_platform(
1616        pool: sqlx::PgPool,
1617        migrations_dir: std::path::PathBuf,
1618        database_type: crate::database::DatabaseType,
1619    ) -> Self {
1620        Self {
1621            pool,
1622            migrations_dir,
1623            database_type: Some(database_type),
1624        }
1625    }
1626
1627    /// Ensure the migration tracking table exists
1628    pub async fn ensure_migration_table(&self) -> sqlx::Result<()> {
1629        let create_table_sql = match self.database_type {
1630            Some(crate::database::DatabaseType::PostgreSQL) => {
1631                r#"
1632                CREATE TABLE IF NOT EXISTS __ignis_migrations (
1633                    id SERIAL PRIMARY KEY,
1634                    name VARCHAR(255) NOT NULL UNIQUE,
1635                    checksum VARCHAR(64) NOT NULL,
1636                    applied_at TIMESTAMPTZ DEFAULT NOW(),
1637                    is_baseline BOOLEAN DEFAULT false
1638                );
1639                "#
1640            }
1641            Some(crate::database::DatabaseType::MySQL) => {
1642                r#"
1643                CREATE TABLE IF NOT EXISTS __ignis_migrations (
1644                    id INT AUTO_INCREMENT PRIMARY KEY,
1645                    name VARCHAR(255) NOT NULL UNIQUE,
1646                    checksum VARCHAR(64) NOT NULL,
1647                    applied_at DATETIME DEFAULT CURRENT_TIMESTAMP,
1648                    is_baseline BOOLEAN DEFAULT false
1649                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
1650                "#
1651            }
1652            _ => {
1653                // Default to PostgreSQL syntax for unsupported databases
1654                r#"
1655                CREATE TABLE IF NOT EXISTS __ignis_migrations (
1656                    id SERIAL PRIMARY KEY,
1657                    name VARCHAR(255) NOT NULL UNIQUE,
1658                    checksum VARCHAR(64) NOT NULL,
1659                    applied_at TIMESTAMPTZ DEFAULT NOW(),
1660                    is_baseline BOOLEAN DEFAULT false
1661                );
1662                "#
1663            }
1664        };
1665
1666        sqlx::query(create_table_sql).execute(&self.pool).await?;
1667
1668        Ok(())
1669    }
1670
1671    /// Get all applied migrations from the database
1672    pub async fn get_applied_migrations(&self) -> sqlx::Result<Vec<AppliedMigration>> {
1673        let query = r#"
1674            SELECT name, checksum, applied_at, COALESCE(is_baseline, false) as is_baseline
1675            FROM __ignis_migrations
1676            ORDER BY applied_at ASC
1677        "#;
1678
1679        let rows = sqlx::query(query).fetch_all(&self.pool).await?;
1680
1681        let mut migrations = Vec::new();
1682        for row in rows {
1683            let name: String = row.get("name");
1684            let checksum: String = row.get("checksum");
1685            let applied_at: chrono::DateTime<chrono::Utc> = row.get("applied_at");
1686            let is_baseline: bool = row.get("is_baseline");
1687
1688            migrations.push(AppliedMigration {
1689                name,
1690                checksum,
1691                applied_at,
1692                is_baseline,
1693            });
1694        }
1695
1696        Ok(migrations)
1697    }
1698
1699    /// Apply a migration
1700    pub async fn apply_migration(&self, name: &str, up_sql: &str) -> sqlx::Result<()> {
1701        // Calculate checksum
1702        let checksum = calculate_migration_checksum(up_sql);
1703
1704        // Execute the migration in a transaction
1705        let mut tx = self.pool.begin().await?;
1706
1707        // Run the migration SQL (split into individual statements for proper execution)
1708        execute_multi_statement_sql(up_sql, &mut *tx).await?;
1709
1710        // Record the migration
1711        let record_sql = r#"
1712            INSERT INTO __ignis_migrations (name, checksum, is_baseline)
1713            VALUES ($1, $2, false)
1714        "#;
1715
1716        sqlx::query(record_sql)
1717            .bind(name)
1718            .bind(&checksum)
1719            .execute(&mut *tx)
1720            .await?;
1721
1722        tx.commit().await?;
1723
1724        Ok(())
1725    }
1726
1727    /// Rollback a migration
1728    pub async fn rollback_migration(&self, name: &str, down_sql: &str) -> sqlx::Result<()> {
1729        // Execute the rollback in a transaction
1730        let mut tx = self.pool.begin().await?;
1731
1732        // Run the rollback SQL
1733        sqlx::query(down_sql).execute(&mut *tx).await?;
1734
1735        // Remove the migration record
1736        let delete_sql = r#"
1737            DELETE FROM __ignis_migrations
1738            WHERE name = $1
1739        "#;
1740
1741        sqlx::query(delete_sql).bind(name).execute(&mut *tx).await?;
1742
1743        tx.commit().await?;
1744
1745        Ok(())
1746    }
1747
1748    /// Get the migrations directory path
1749    pub fn migrations_dir(&self) -> &std::path::Path {
1750        &self.migrations_dir
1751    }
1752
1753    /// Get the database type
1754    pub fn database_type(&self) -> Option<&crate::database::DatabaseType> {
1755        self.database_type.as_ref()
1756    }
1757}
1758
1759/// Represents an applied migration
1760#[derive(Debug, Clone)]
1761pub struct AppliedMigration {
1762    pub name: String,
1763    pub checksum: String,
1764    pub applied_at: chrono::DateTime<chrono::Utc>,
1765    pub is_baseline: bool,
1766}
1767
1768/// Calculate a checksum for migration content
1769fn calculate_migration_checksum(sql: &str) -> String {
1770    use std::collections::hash_map::DefaultHasher;
1771    use std::hash::{Hash, Hasher};
1772
1773    let mut hasher = DefaultHasher::new();
1774    sql.hash(&mut hasher);
1775    format!("{:x}", hasher.finish())
1776}
1777
1778#[cfg(test)]
1779mod tests {
1780    use super::*;
1781    use crate::schema::{Column, ColumnType, Table, View};
1782
1783    #[test]
1784    fn test_migration_generation() {
1785        let mut old_tables = HashMap::new();
1786        let mut new_tables = HashMap::new();
1787
1788        // Old schema: users table with just id
1789        let old_users = Table::new("users")
1790            .add_column(Column::new("id", ColumnType::Int4))
1791            .set_primary_key("id");
1792
1793        // New schema: users table with id and email
1794        let new_users = Table::new("users")
1795            .add_column(Column::new("id", ColumnType::Int4))
1796            .add_column(Column::new("email", ColumnType::Varchar(None)))
1797            .set_primary_key("id");
1798
1799        old_tables.insert("users".to_string(), old_users);
1800        new_tables.insert("users".to_string(), new_users);
1801
1802        let manager = SchemaMigrationManager::new()
1803            .set_old_schema(old_tables)
1804            .set_new_schema(new_tables);
1805
1806        let migration = manager.generate_migration("add_email_to_users").unwrap();
1807
1808        // Debug output
1809        println!("Generated migration:");
1810        println!("Up SQL: {}", migration.up_sql);
1811        println!("Down SQL: {}", migration.down_sql.as_ref().unwrap());
1812
1813        // Verify up migration contains ALTER TABLE ADD COLUMN
1814        assert!(migration.up_sql.contains("ALTER TABLE"));
1815        assert!(migration.up_sql.contains("ADD COLUMN"));
1816        assert!(migration.up_sql.contains("email"));
1817
1818        // Verify down migration contains ALTER TABLE DROP COLUMN
1819        assert!(migration.down_sql.as_ref().unwrap().contains("DROP COLUMN"));
1820        assert!(migration.down_sql.as_ref().unwrap().contains("email"));
1821    }
1822
1823    #[test]
1824    fn test_view_migration_generation() {
1825        let mut old_views = HashMap::new();
1826        let mut new_views = HashMap::new();
1827
1828        // Old schema: simple view
1829        let old_view = View::new("user_summary")
1830            .add_column(Column::new("id", ColumnType::Int4))
1831            .add_column(Column::new("name", ColumnType::Varchar(None)));
1832
1833        // New schema: materialized view with indexes
1834        let new_view = View::new("user_summary")
1835            .add_column(Column::new("id", ColumnType::Int4))
1836            .add_column(Column::new("name", ColumnType::Varchar(None)))
1837            .add_column(Column::new("post_count", ColumnType::Int4))
1838            .set_materialized(true)
1839            .add_index("idx_user_summary_id", vec!["id".to_string()])
1840            .add_dependency("users")
1841            .add_dependency("posts")
1842            .clone();
1843
1844        old_views.insert("user_summary".to_string(), old_view);
1845        new_views.insert("user_summary".to_string(), new_view);
1846
1847        let manager = SchemaMigrationManager::new()
1848            .set_old_views(old_views)
1849            .set_new_views(new_views);
1850
1851        let migration = manager
1852            .generate_migration("enhance_user_summary_view")
1853            .unwrap();
1854
1855        // Debug output
1856        println!("Generated migration:");
1857        println!("Up SQL: {}", migration.up_sql);
1858        println!("Down SQL: {}", migration.down_sql.as_ref().unwrap());
1859
1860        // Verify up migration contains view changes
1861        assert!(migration.up_sql.contains("View Changes"));
1862        assert!(migration.up_sql.contains("user_summary"));
1863
1864        // Verify down migration contains view change reversals
1865        assert!(migration
1866            .down_sql
1867            .as_ref()
1868            .unwrap()
1869            .contains("Revert changes to view"));
1870        assert!(migration
1871            .down_sql
1872            .as_ref()
1873            .unwrap()
1874            .contains("user_summary"));
1875    }
1876}