ignis-db 0.2.0

A comprehensive PostgreSQL ORM with macro-driven schema management
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
//! Migration system for Ignis

use crate::schema::{
    Column, CompositeType, IndexMeta, StoredFunction, StoredProcedure, Table, View,
};
use anyhow::Result;
use sqlx::Row;
use std::collections::HashMap;
use std::path::Path;

pub mod baseline;
pub mod ddl_validator;
pub mod schema_diff;
pub mod strategy;
pub mod table_macro_generator;
// Multi-platform migration support integrated into main migration system

// Re-export for easy access
pub use baseline::{BaselineMigration, BaselineMigrationManager, SchemaStatistics};
pub use ddl_validator::{validate_ddl, DdlValidationContext, DdlValidationResult};
pub use strategy::{
    create_strategy, ConservativeStrategy, GroupedStrategy, MigrationFile, MigrationStrategy,
    SchemaChange, SchemaChangeType,
};
pub use table_macro_generator::TableMacroMigrationGenerator;
// Multi-platform migration support is integrated into the main migration system

// Migration management types are defined below

use schema_diff::{MigrationGenerator, SchemaDiffEngine};

/// Represents a database migration
#[derive(Debug, Clone)]
pub struct Migration {
    pub id: String,
    pub name: String,
    pub up_sql: String,
    pub down_sql: Option<String>,
    pub checksum: String,
}

impl Migration {
    /// Create a new migration
    pub fn new(id: impl Into<String>, name: impl Into<String>, up_sql: impl Into<String>) -> Self {
        let up_sql = up_sql.into();
        let checksum = Self::calculate_checksum(&up_sql, None);

        Self {
            id: id.into(),
            name: name.into(),
            up_sql,
            down_sql: None,
            checksum,
        }
    }

    /// Set the down migration SQL
    pub fn with_down(mut self, down_sql: impl Into<String>) -> Self {
        self.down_sql = Some(down_sql.into());
        self.checksum = Self::calculate_checksum(&self.up_sql, self.down_sql.as_deref());
        self
    }

    /// Calculate checksum for the migration
    fn calculate_checksum(up_sql: &str, down_sql: Option<&str>) -> String {
        use std::collections::hash_map::DefaultHasher;
        use std::hash::{Hash, Hasher};

        let mut hasher = DefaultHasher::new();
        up_sql.hash(&mut hasher);
        if let Some(down) = down_sql {
            down.hash(&mut hasher);
        }

        format!("{:x}", hasher.finish())
    }

    /// Optional: Validate DDL before execution
    pub fn validate(&self) -> DdlValidationResult {
        validate_ddl(&self.up_sql)
    }

    /// Optional: Execute with transaction safety
    pub async fn execute_with_transaction<'e, E>(&self, executor: E) -> sqlx::Result<u64>
    where
        E: sqlx::Executor<'e, Database = sqlx::Postgres>,
    {
        // use crate::exec::transaction::execute_transaction;

        // For now, execute directly - transaction wrapping can be added later
        sqlx::query(&self.up_sql)
            .execute(executor)
            .await
            .map(|r| r.rows_affected())
    }
}

/// Index-specific migration operations
pub struct IndexMigration;

impl IndexMigration {
    /// Create a migration for adding an index
    pub fn create_index(index: &IndexMeta) -> Migration {
        let up_sql = index.generate_ddl();
        let down_sql = format!("DROP INDEX IF EXISTS \"{}\" CASCADE;", index.name);

        Migration::new(
            format!("add_index_{}", index.name),
            format!("Add index {} on table {}", index.name, index.table),
            up_sql,
        )
        .with_down(down_sql)
    }

    /// Create a migration for dropping an index
    pub fn drop_index(index: &IndexMeta) -> Migration {
        let up_sql = format!("DROP INDEX IF EXISTS \"{}\" CASCADE;", index.name);
        let down_sql = index.generate_ddl();

        Migration::new(
            format!("drop_index_{}", index.name),
            format!("Drop index {} from table {}", index.name, index.table),
            up_sql,
        )
        .with_down(down_sql)
    }

    /// Create a migration for modifying an index
    pub fn modify_index(old_index: &IndexMeta, new_index: &IndexMeta) -> Migration {
        let up_sql = format!(
            "-- Drop old index and create new one\n\
             DROP INDEX IF EXISTS \"{}\" CASCADE;\n\
             {}",
            old_index.name,
            new_index.generate_ddl()
        );

        let down_sql = format!(
            "-- Revert to old index\n\
             DROP INDEX IF EXISTS \"{}\" CASCADE;\n\
             {}",
            new_index.name,
            old_index.generate_ddl()
        );

        Migration::new(
            format!("modify_index_{}", old_index.name),
            format!(
                "Modify index {} on table {}",
                old_index.name, old_index.table
            ),
            up_sql,
        )
        .with_down(down_sql)
    }

    /// Create a batch migration for multiple index operations
    pub fn batch_index_operations(operations: Vec<IndexOperation>) -> Migration {
        let mut up_sql = String::new();
        let mut down_sql = String::new();

        for op in &operations {
            match op {
                IndexOperation::Create(index) => {
                    up_sql.push_str(&index.generate_ddl());
                    up_sql.push('\n');
                    down_sql.push_str(&format!(
                        "DROP INDEX IF EXISTS \"{}\" CASCADE;\n",
                        index.name
                    ));
                }
                IndexOperation::Drop(index) => {
                    up_sql.push_str(&format!(
                        "DROP INDEX IF EXISTS \"{}\" CASCADE;\n",
                        index.name
                    ));
                    down_sql.push_str(&index.generate_ddl());
                    down_sql.push('\n');
                }
                IndexOperation::Modify { old, new } => {
                    up_sql.push_str(&format!("DROP INDEX IF EXISTS \"{}\" CASCADE;\n", old.name));
                    up_sql.push_str(&new.generate_ddl());
                    up_sql.push('\n');
                    down_sql.push_str(&format!("DROP INDEX IF EXISTS \"{}\" CASCADE;\n", new.name));
                    down_sql.push_str(&old.generate_ddl());
                    down_sql.push('\n');
                }
            }
        }

        Migration::new(
            "batch_index_operations".to_string(),
            "Batch index operations".to_string(),
            up_sql,
        )
        .with_down(down_sql)
    }
}

/// Event-specific migration operations
pub struct EventMigration;

impl EventMigration {
    /// Create a migration for adding an event
    pub fn create_event(event: &crate::schema::Event) -> Migration {
        let up_sql = event.generate_ddl();
        let down_sql = event.generate_drop_ddl();

        Migration::new(
            format!("add_event_{}", event.name),
            format!("Add event {} with schedule {}", event.name, event.schedule),
            up_sql,
        )
        .with_down(down_sql)
    }

    /// Create a migration for dropping an event
    pub fn drop_event(event: &crate::schema::Event) -> Migration {
        let up_sql = event.generate_drop_ddl();
        let down_sql = event.generate_ddl();

        Migration::new(
            format!("drop_event_{}", event.name),
            format!("Drop event {} with schedule {}", event.name, event.schedule),
            up_sql,
        )
        .with_down(down_sql)
    }

    /// Create a migration for modifying an event
    pub fn modify_event(
        old_event: &crate::schema::Event,
        new_event: &crate::schema::Event,
    ) -> Migration {
        let up_sql = format!(
            "-- Modify event {}\n{}\n",
            new_event.name,
            new_event.generate_ddl()
        );
        let down_sql = format!(
            "-- Revert event {}\n{}\n",
            old_event.name,
            old_event.generate_ddl()
        );

        Migration::new(
            format!("modify_event_{}", new_event.name),
            format!(
                "Modify event {} schedule from {} to {}",
                new_event.name, old_event.schedule, new_event.schedule
            ),
            up_sql,
        )
        .with_down(down_sql)
    }
}

/// Composite type-specific migration operations
pub struct CompositeTypeMigration;

impl CompositeTypeMigration {
    /// Create a migration for adding a composite type
    pub fn create_composite_type(composite_type: &CompositeType) -> Migration {
        let up_sql = composite_type.generate_create_ddl();
        let down_sql = composite_type.generate_drop_ddl();

        Migration::new(
            format!("add_composite_type_{}", composite_type.name),
            format!("Add composite type {}", composite_type.full_name()),
            up_sql,
        )
        .with_down(down_sql)
    }

    /// Create a migration for dropping a composite type
    pub fn drop_composite_type(composite_type: &CompositeType) -> Migration {
        let up_sql = composite_type.generate_drop_ddl();
        let down_sql = composite_type.generate_create_ddl();

        Migration::new(
            format!("drop_composite_type_{}", composite_type.name),
            format!("Drop composite type {}", composite_type.full_name()),
            up_sql,
        )
        .with_down(down_sql)
    }

    /// Create a migration for modifying a composite type
    pub fn modify_composite_type(old_type: &CompositeType, new_type: &CompositeType) -> Migration {
        let up_sql = format!(
            "-- Modify composite type {}\n{}\n{}",
            new_type.full_name(),
            old_type.generate_drop_ddl(),
            new_type.generate_create_ddl()
        );
        let down_sql = format!(
            "-- Revert composite type {}\n{}\n{}",
            old_type.full_name(),
            new_type.generate_drop_ddl(),
            old_type.generate_create_ddl()
        );

        Migration::new(
            format!("modify_composite_type_{}", new_type.name),
            format!("Modify composite type {}", new_type.full_name()),
            up_sql,
        )
        .with_down(down_sql)
    }

    /// Create a batch migration for multiple composite type operations
    pub fn batch_composite_operations(operations: Vec<CompositeTypeOperation>) -> Migration {
        let mut up_sql = String::new();
        let mut down_sql = String::new();

        for op in &operations {
            match op {
                CompositeTypeOperation::Create(composite_type) => {
                    up_sql.push_str(&composite_type.generate_create_ddl());
                    up_sql.push('\n');
                    down_sql.push_str(&composite_type.generate_drop_ddl());
                    down_sql.push('\n');
                }
                CompositeTypeOperation::Drop(composite_type) => {
                    up_sql.push_str(&composite_type.generate_drop_ddl());
                    up_sql.push('\n');
                    down_sql.push_str(&composite_type.generate_create_ddl());
                    down_sql.push('\n');
                }
                CompositeTypeOperation::Modify { old, new } => {
                    up_sql.push_str(&old.generate_drop_ddl());
                    up_sql.push('\n');
                    up_sql.push_str(&new.generate_create_ddl());
                    up_sql.push('\n');
                    down_sql.push_str(&new.generate_drop_ddl());
                    down_sql.push('\n');
                    down_sql.push_str(&old.generate_create_ddl());
                    down_sql.push('\n');
                }
            }
        }

        Migration::new(
            "batch_composite_type_operations".to_string(),
            "Batch composite type operations".to_string(),
            up_sql,
        )
        .with_down(down_sql)
    }
}

/// Represents different composite type operations for batch processing
#[derive(Debug, Clone)]
pub enum CompositeTypeOperation {
    Create(CompositeType),
    Drop(CompositeType),
    Modify {
        old: CompositeType,
        new: CompositeType,
    },
}

/// Stored procedure-specific migration operations
pub struct ProcedureMigration;

impl ProcedureMigration {
    /// Create a migration for adding a stored function
    pub fn create_function(function: &StoredFunction) -> Migration {
        let up_sql = function.generate_create_ddl();
        let down_sql = function.generate_drop_ddl();

        Migration::new(
            format!("add_function_{}", function.name),
            format!("Add function {}", function.full_name()),
            up_sql,
        )
        .with_down(down_sql)
    }

    /// Create a migration for dropping a stored function
    pub fn drop_function(function: &StoredFunction) -> Migration {
        let up_sql = function.generate_drop_ddl();
        let down_sql = function.generate_create_ddl();

        Migration::new(
            format!("drop_function_{}", function.name),
            format!("Drop function {}", function.full_name()),
            up_sql,
        )
        .with_down(down_sql)
    }

    /// Create a migration for modifying a stored function
    pub fn modify_function(
        old_function: &StoredFunction,
        new_function: &StoredFunction,
    ) -> Migration {
        let up_sql = format!(
            "-- Modify function {}\n{}\n{}",
            new_function.full_name(),
            old_function.generate_drop_ddl(),
            new_function.generate_create_ddl()
        );
        let down_sql = format!(
            "-- Revert function {}\n{}\n{}",
            old_function.full_name(),
            new_function.generate_drop_ddl(),
            old_function.generate_create_ddl()
        );

        Migration::new(
            format!("modify_function_{}", new_function.name),
            format!("Modify function {}", new_function.full_name()),
            up_sql,
        )
        .with_down(down_sql)
    }

    /// Create a migration for adding a stored procedure
    pub fn create_procedure(procedure: &StoredProcedure) -> Migration {
        let up_sql = procedure.generate_create_ddl();
        let down_sql = procedure.generate_drop_ddl();

        Migration::new(
            format!("add_procedure_{}", procedure.name),
            format!("Add procedure {}", procedure.full_name()),
            up_sql,
        )
        .with_down(down_sql)
    }

    /// Create a migration for dropping a stored procedure
    pub fn drop_procedure(procedure: &StoredProcedure) -> Migration {
        let up_sql = procedure.generate_drop_ddl();
        let down_sql = procedure.generate_create_ddl();

        Migration::new(
            format!("drop_procedure_{}", procedure.name),
            format!("Drop procedure {}", procedure.full_name()),
            up_sql,
        )
        .with_down(down_sql)
    }

    /// Create a migration for modifying a stored procedure
    pub fn modify_procedure(
        old_procedure: &StoredProcedure,
        new_procedure: &StoredProcedure,
    ) -> Migration {
        let up_sql = format!(
            "-- Modify procedure {}\n{}\n{}",
            new_procedure.full_name(),
            old_procedure.generate_drop_ddl(),
            new_procedure.generate_create_ddl()
        );
        let down_sql = format!(
            "-- Revert procedure {}\n{}\n{}",
            old_procedure.full_name(),
            new_procedure.generate_drop_ddl(),
            old_procedure.generate_create_ddl()
        );

        Migration::new(
            format!("modify_procedure_{}", new_procedure.name),
            format!("Modify procedure {}", new_procedure.full_name()),
            up_sql,
        )
        .with_down(down_sql)
    }

    /// Create a batch migration for multiple procedure operations
    pub fn batch_procedure_operations(operations: Vec<ProcedureOperation>) -> Migration {
        let mut up_sql = String::new();
        let mut down_sql = String::new();

        for op in &operations {
            match op {
                ProcedureOperation::CreateFunction(function) => {
                    up_sql.push_str(&function.generate_create_ddl());
                    up_sql.push('\n');
                    down_sql.push_str(&function.generate_drop_ddl());
                    down_sql.push('\n');
                }
                ProcedureOperation::DropFunction(function) => {
                    up_sql.push_str(&function.generate_drop_ddl());
                    up_sql.push('\n');
                    down_sql.push_str(&function.generate_create_ddl());
                    down_sql.push('\n');
                }
                ProcedureOperation::ModifyFunction { old, new } => {
                    up_sql.push_str(&old.generate_drop_ddl());
                    up_sql.push('\n');
                    up_sql.push_str(&new.generate_create_ddl());
                    up_sql.push('\n');
                    down_sql.push_str(&new.generate_drop_ddl());
                    down_sql.push('\n');
                    down_sql.push_str(&old.generate_create_ddl());
                    down_sql.push('\n');
                }
                ProcedureOperation::CreateProcedure(procedure) => {
                    up_sql.push_str(&procedure.generate_create_ddl());
                    up_sql.push('\n');
                    down_sql.push_str(&procedure.generate_drop_ddl());
                    down_sql.push('\n');
                }
                ProcedureOperation::DropProcedure(procedure) => {
                    up_sql.push_str(&procedure.generate_drop_ddl());
                    up_sql.push('\n');
                    down_sql.push_str(&procedure.generate_create_ddl());
                    down_sql.push('\n');
                }
                ProcedureOperation::ModifyProcedure { old, new } => {
                    up_sql.push_str(&old.generate_drop_ddl());
                    up_sql.push('\n');
                    up_sql.push_str(&new.generate_create_ddl());
                    up_sql.push('\n');
                    down_sql.push_str(&new.generate_drop_ddl());
                    down_sql.push('\n');
                    down_sql.push_str(&old.generate_create_ddl());
                    down_sql.push('\n');
                }
            }
        }

        Migration::new(
            "batch_procedure_operations".to_string(),
            "Batch procedure operations".to_string(),
            up_sql,
        )
        .with_down(down_sql)
    }
}

/// Represents different procedure operations for batch processing
#[derive(Debug, Clone)]
pub enum ProcedureOperation {
    CreateFunction(StoredFunction),
    DropFunction(StoredFunction),
    ModifyFunction {
        old: StoredFunction,
        new: StoredFunction,
    },
    CreateProcedure(StoredProcedure),
    DropProcedure(StoredProcedure),
    ModifyProcedure {
        old: StoredProcedure,
        new: StoredProcedure,
    },
}

/// Role-specific migration operations
pub struct RoleMigration;

impl RoleMigration {
    /// Create a migration for adding a role
    pub fn create_role(role: &crate::schema::Role) -> Migration {
        let up_sql = role.generate_create_ddl();
        let down_sql = role.generate_drop_ddl();

        Migration::new(
            format!("add_role_{}", role.name),
            format!("Add role {}", role.name),
            up_sql,
        )
        .with_down(down_sql)
    }

    /// Create a migration for dropping a role
    pub fn drop_role(role: &crate::schema::Role) -> Migration {
        let up_sql = role.generate_drop_ddl();
        let down_sql = role.generate_create_ddl();

        Migration::new(
            format!("drop_role_{}", role.name),
            format!("Drop role {}", role.name),
            up_sql,
        )
        .with_down(down_sql)
    }

    /// Create a migration for modifying a role
    pub fn modify_role(
        old_role: &crate::schema::Role,
        new_role: &crate::schema::Role,
    ) -> Migration {
        let up_sql = format!(
            "-- Modify role {}\n{}",
            new_role.name,
            new_role.generate_alter_ddl(old_role)
        );
        let down_sql = format!(
            "-- Revert role {}\n{}",
            old_role.name,
            old_role.generate_alter_ddl(new_role)
        );

        Migration::new(
            format!("modify_role_{}", new_role.name),
            format!("Modify role {}", new_role.name),
            up_sql,
        )
        .with_down(down_sql)
    }
}

/// Grant-specific migration operations
pub struct GrantMigration;

impl GrantMigration {
    /// Create a migration for adding a grant
    pub fn create_grant(grant: &crate::schema::Grant) -> Migration {
        let up_sql = grant.generate_grant_ddl();
        let down_sql = grant.generate_revoke_ddl();

        Migration::new(
            format!("add_grant_{}", grant.generate_name()),
            format!("Grant {} to {}", grant.privilege_name(), grant.grantee),
            up_sql,
        )
        .with_down(down_sql)
    }

    /// Create a migration for revoking a grant
    pub fn revoke_grant(grant: &crate::schema::Grant) -> Migration {
        let up_sql = grant.generate_revoke_ddl();
        let down_sql = grant.generate_grant_ddl();

        Migration::new(
            format!("revoke_grant_{}", grant.generate_name()),
            format!("Revoke {} from {}", grant.privilege_name(), grant.grantee),
            up_sql,
        )
        .with_down(down_sql)
    }

    /// Create a migration for modifying a grant
    pub fn modify_grant(
        old_grant: &crate::schema::Grant,
        new_grant: &crate::schema::Grant,
    ) -> Migration {
        let up_sql = format!(
            "-- Modify grant {}\n{}\n{}",
            new_grant.generate_name(),
            old_grant.generate_revoke_ddl(),
            new_grant.generate_grant_ddl()
        );
        let down_sql = format!(
            "-- Revert grant {}\n{}\n{}",
            old_grant.generate_name(),
            new_grant.generate_revoke_ddl(),
            old_grant.generate_grant_ddl()
        );

        Migration::new(
            format!("modify_grant_{}", new_grant.generate_name()),
            format!("Modify grant {}", new_grant.generate_name()),
            up_sql,
        )
        .with_down(down_sql)
    }
}

/// Represents an index operation for batch migrations
#[derive(Debug, Clone)]
pub enum IndexOperation {
    Create(IndexMeta),
    Drop(IndexMeta),
    Modify { old: IndexMeta, new: IndexMeta },
}

/// Migration runner for applying migrations
pub struct MigrationRunner {
    migrations: Vec<Migration>,
}

impl MigrationRunner {
    /// Create a new migration runner
    pub fn new() -> Self {
        Self {
            migrations: Vec::new(),
        }
    }

    /// Add a migration to the runner
    pub fn add_migration(mut self, migration: Migration) -> Self {
        self.migrations.push(migration);
        self
    }

    /// Get all migrations
    pub fn migrations(&self) -> &[Migration] {
        &self.migrations
    }

    /// Generate migration files in the given directory
    pub fn generate_files(&self, dir: &Path) -> Result<()> {
        use std::fs;

        for migration in &self.migrations {
            let migration_dir = dir.join(&migration.id);
            fs::create_dir_all(&migration_dir)?;

            // Write up.sql
            fs::write(migration_dir.join("up.sql"), &migration.up_sql)?;

            // Write down.sql if it exists
            if let Some(ref down_sql) = migration.down_sql {
                fs::write(migration_dir.join("down.sql"), down_sql)?;
            }
        }

        Ok(())
    }
}

/// Schema migration manager for handling table and view changes
pub struct SchemaMigrationManager {
    old_tables: HashMap<String, Table>,
    new_tables: HashMap<String, Table>,
    old_views: HashMap<String, crate::schema::View>,
    new_views: HashMap<String, crate::schema::View>,
    old_functions: HashMap<String, crate::schema::StoredFunction>,
    new_functions: HashMap<String, crate::schema::StoredFunction>,
    old_procedures: HashMap<String, crate::schema::StoredProcedure>,
    new_procedures: HashMap<String, crate::schema::StoredProcedure>,
    old_triggers: HashMap<String, crate::schema::Trigger>,
    new_triggers: HashMap<String, crate::schema::Trigger>,
    old_composite_types: HashMap<String, crate::schema::CompositeType>,
    new_composite_types: HashMap<String, crate::schema::CompositeType>,
}

impl SchemaMigrationManager {
    /// Create a new schema migration manager
    pub fn new() -> Self {
        Self {
            old_tables: HashMap::new(),
            new_tables: HashMap::new(),
            old_views: HashMap::new(),
            new_views: HashMap::new(),
            old_functions: HashMap::new(),
            new_functions: HashMap::new(),
            old_procedures: HashMap::new(),
            new_procedures: HashMap::new(),
            old_triggers: HashMap::new(),
            new_triggers: HashMap::new(),
            old_composite_types: HashMap::new(),
            new_composite_types: HashMap::new(),
        }
    }

    /// Set the old schema state
    pub fn set_old_schema(mut self, tables: HashMap<String, Table>) -> Self {
        self.old_tables = tables;
        self
    }

    /// Set the new schema state
    pub fn set_new_schema(mut self, tables: HashMap<String, Table>) -> Self {
        self.new_tables = tables;
        self
    }

    /// Set the old view schema state
    pub fn set_old_views(mut self, views: HashMap<String, crate::schema::View>) -> Self {
        self.old_views = views;
        self
    }

    /// Set the new view schema state
    pub fn set_new_views(mut self, views: HashMap<String, crate::schema::View>) -> Self {
        self.new_views = views;
        self
    }

    /// Set the old functions
    pub fn set_old_functions(
        mut self,
        functions: HashMap<String, crate::schema::StoredFunction>,
    ) -> Self {
        self.old_functions = functions;
        self
    }

    /// Set the new functions
    pub fn set_new_functions(
        mut self,
        functions: HashMap<String, crate::schema::StoredFunction>,
    ) -> Self {
        self.new_functions = functions;
        self
    }

    /// Set the old procedures
    pub fn set_old_procedures(
        mut self,
        procedures: HashMap<String, crate::schema::StoredProcedure>,
    ) -> Self {
        self.old_procedures = procedures;
        self
    }

    /// Set the new procedures
    pub fn set_new_procedures(
        mut self,
        procedures: HashMap<String, crate::schema::StoredProcedure>,
    ) -> Self {
        self.new_procedures = procedures;
        self
    }

    /// Set the old triggers
    pub fn set_old_triggers(mut self, triggers: HashMap<String, crate::schema::Trigger>) -> Self {
        self.old_triggers = triggers;
        self
    }

    /// Set the new triggers
    pub fn set_new_triggers(mut self, triggers: HashMap<String, crate::schema::Trigger>) -> Self {
        self.new_triggers = triggers;
        self
    }

    /// Set the old composite types
    pub fn set_old_composite_types(
        mut self,
        composite_types: HashMap<String, crate::schema::CompositeType>,
    ) -> Self {
        self.old_composite_types = composite_types;
        self
    }

    /// Set the new composite types
    pub fn set_new_composite_types(
        mut self,
        composite_types: HashMap<String, crate::schema::CompositeType>,
    ) -> Self {
        self.new_composite_types = composite_types;
        self
    }

    /// Generate a migration from the schema differences
    pub fn generate_migration(&self, name: &str) -> Result<Migration> {
        // Detect schema differences for all object types
        let table_diffs = SchemaDiffEngine::compare_tables(&self.old_tables, &self.new_tables);
        let view_diffs = SchemaDiffEngine::compare_views(&self.old_views, &self.new_views);
        let function_diffs =
            SchemaDiffEngine::compare_functions(&self.old_functions, &self.new_functions);
        let procedure_diffs =
            SchemaDiffEngine::compare_procedures(&self.old_procedures, &self.new_procedures);
        let trigger_diffs =
            SchemaDiffEngine::compare_triggers(&self.old_triggers, &self.new_triggers);
        let composite_type_diffs = SchemaDiffEngine::compare_composite_types(
            &self.old_composite_types,
            &self.new_composite_types,
        );

        // Check if any changes were detected
        if table_diffs.is_empty()
            && view_diffs.is_empty()
            && function_diffs.is_empty()
            && procedure_diffs.is_empty()
            && trigger_diffs.is_empty()
            && composite_type_diffs.is_empty()
        {
            return Err(anyhow::anyhow!("No schema changes detected"));
        }

        // Generate the migration SQL for tables
        let table_up_sql = if table_diffs.is_empty() {
            String::new()
        } else {
            MigrationGenerator::generate_table_migration(&table_diffs)
        };

        // Generate the migration SQL for views
        let view_up_sql = if view_diffs.is_empty() {
            String::new()
        } else {
            MigrationGenerator::generate_view_migration(&view_diffs)
        };

        // Generate the migration SQL for functions
        let function_up_sql = if function_diffs.is_empty() {
            String::new()
        } else {
            MigrationGenerator::generate_migration(&function_diffs)
        };

        // Generate the migration SQL for procedures
        let procedure_up_sql = if procedure_diffs.is_empty() {
            String::new()
        } else {
            MigrationGenerator::generate_migration(&procedure_diffs)
        };

        // Generate the migration SQL for triggers
        let trigger_up_sql = if trigger_diffs.is_empty() {
            String::new()
        } else {
            MigrationGenerator::generate_migration(&trigger_diffs)
        };

        // Generate the migration SQL for composite types
        let composite_type_up_sql = if composite_type_diffs.is_empty() {
            String::new()
        } else {
            MigrationGenerator::generate_migration(&composite_type_diffs)
        };

        // Combine all migration SQL sections
        let mut up_sql_parts = Vec::new();

        if !table_up_sql.is_empty() {
            up_sql_parts.push(format!("-- Table Changes\n{}", table_up_sql));
        }
        if !view_up_sql.is_empty() {
            up_sql_parts.push(format!("-- View Changes\n{}", view_up_sql));
        }
        if !function_up_sql.is_empty() {
            up_sql_parts.push(format!("-- Function Changes\n{}", function_up_sql));
        }
        if !procedure_up_sql.is_empty() {
            up_sql_parts.push(format!("-- Procedure Changes\n{}", procedure_up_sql));
        }
        if !trigger_up_sql.is_empty() {
            up_sql_parts.push(format!("-- Trigger Changes\n{}", trigger_up_sql));
        }
        if !composite_type_up_sql.is_empty() {
            up_sql_parts.push(format!(
                "-- Composite Type Changes\n{}",
                composite_type_up_sql
            ));
        }

        let up_sql = up_sql_parts.join("\n\n");

        // Generate down migration (reverse operations)
        let down_sql = self.generate_down_migration(
            &table_diffs,
            &view_diffs,
            &function_diffs,
            &procedure_diffs,
            &trigger_diffs,
            &composite_type_diffs,
        );

        // Create migration ID (timestamp-based)
        let id = chrono::Utc::now().format("%Y%m%d_%H%M%S").to_string();

        Ok(Migration::new(id, name, up_sql).with_down(down_sql))
    }

    /// Generate the down migration (reverse operations)
    fn generate_down_migration(
        &self,
        table_diffs: &[schema_diff::SchemaDiff],
        view_diffs: &[schema_diff::SchemaDiff],
        function_diffs: &[schema_diff::SchemaDiff],
        procedure_diffs: &[schema_diff::SchemaDiff],
        trigger_diffs: &[schema_diff::SchemaDiff],
        composite_type_diffs: &[schema_diff::SchemaDiff],
    ) -> String {
        let mut down_sql = String::new();

        // Process table diffs in reverse order
        for diff in table_diffs.iter().rev() {
            match diff {
                schema_diff::SchemaDiff::TableAdded { name, .. } => {
                    down_sql.push_str(&format!("-- Drop table {}\n", name));
                    down_sql.push_str(&format!("DROP TABLE IF EXISTS \"{}\" CASCADE;\n\n", name));
                }
                schema_diff::SchemaDiff::TableDropped { name, table } => {
                    down_sql.push_str(&format!("-- Recreate table {}\n", name));
                    down_sql.push_str(&table.generate_ddl());
                    down_sql.push_str("\n\n");
                }
                schema_diff::SchemaDiff::TableModified {
                    name,
                    old_table,
                    new_table,
                } => {
                    down_sql.push_str(&format!("-- Modify table {}\n", name));
                    // Generate reverse operations for table modifications
                    let reverse_changes =
                        self.generate_reverse_table_change_sql(name, old_table, new_table);
                    down_sql.push_str(&reverse_changes);
                    down_sql.push_str("\n");
                }
                _ => {} // Ignore other diffs in table processing
            }
        }

        // Process view diffs in reverse order
        for diff in view_diffs.iter().rev() {
            match diff {
                schema_diff::SchemaDiff::ViewAdded { name, .. } => {
                    down_sql.push_str(&format!("-- Drop view {}\n", name));
                    down_sql.push_str(&format!("DROP VIEW IF EXISTS \"{}\" CASCADE;\n\n", name));
                }
                schema_diff::SchemaDiff::ViewDropped { name, view } => {
                    down_sql.push_str(&format!("-- Recreate view {}\n", name));
                    down_sql.push_str(&view.generate_ddl());
                    down_sql.push_str("\n\n");
                }
                schema_diff::SchemaDiff::ViewModified {
                    name,
                    old_view,
                    new_view,
                } => {
                    down_sql.push_str(&format!("-- Modify view {}\n", name));
                    // Generate reverse operations for view modifications
                    let reverse_changes =
                        self.generate_reverse_view_change_sql(name, old_view, new_view);
                    down_sql.push_str(&reverse_changes);
                    down_sql.push_str("\n");
                }
                _ => {} // Ignore table diffs in view processing
            }
        }

        // Process function diffs in reverse order
        for diff in function_diffs.iter().rev() {
            match diff {
                schema_diff::SchemaDiff::FunctionAdded { name, .. } => {
                    down_sql.push_str(&format!("-- Drop function {}\n", name));
                    down_sql.push_str(&format!(
                        "DROP FUNCTION IF EXISTS \"{}\" CASCADE;\n\n",
                        name
                    ));
                }
                schema_diff::SchemaDiff::FunctionDropped { name, function } => {
                    down_sql.push_str(&format!("-- Recreate function {}\n", name));
                    down_sql.push_str(&function.generate_create_ddl());
                    down_sql.push_str("\n\n");
                }
                schema_diff::SchemaDiff::FunctionModified {
                    name,
                    old_function,
                    new_function: _,
                } => {
                    down_sql.push_str(&format!("-- Rollback function modification {}\n", name));
                    down_sql.push_str(&format!("DROP FUNCTION IF EXISTS \"{}\" CASCADE;\n", name));
                    down_sql.push_str(&old_function.generate_create_ddl());
                    down_sql.push_str("\n");
                }
                _ => {} // Ignore other diffs in function processing
            }
        }

        // Process procedure diffs in reverse order
        for diff in procedure_diffs.iter().rev() {
            match diff {
                schema_diff::SchemaDiff::ProcedureAdded { name, .. } => {
                    down_sql.push_str(&format!("-- Drop procedure {}\n", name));
                    down_sql.push_str(&format!(
                        "DROP PROCEDURE IF EXISTS \"{}\" CASCADE;\n\n",
                        name
                    ));
                }
                schema_diff::SchemaDiff::ProcedureDropped { name, procedure } => {
                    down_sql.push_str(&format!("-- Recreate procedure {}\n", name));
                    down_sql.push_str(&procedure.generate_create_ddl());
                    down_sql.push_str("\n\n");
                }
                schema_diff::SchemaDiff::ProcedureModified {
                    name,
                    old_procedure,
                    new_procedure: _,
                } => {
                    down_sql.push_str(&format!("-- Rollback procedure modification {}\n", name));
                    down_sql.push_str(&format!("DROP PROCEDURE IF EXISTS \"{}\" CASCADE;\n", name));
                    down_sql.push_str(&old_procedure.generate_create_ddl());
                    down_sql.push_str("\n");
                }
                _ => {} // Ignore other diffs in procedure processing
            }
        }

        // Process trigger diffs in reverse order
        for diff in trigger_diffs.iter().rev() {
            match diff {
                schema_diff::SchemaDiff::TriggerAdded { name, .. } => {
                    down_sql.push_str(&format!("-- Drop trigger {}\n", name));
                    down_sql.push_str(&format!("DROP TRIGGER IF EXISTS \"{}\" CASCADE;\n\n", name));
                }
                schema_diff::SchemaDiff::TriggerDropped { name, trigger } => {
                    down_sql.push_str(&format!("-- Recreate trigger {}\n", name));
                    down_sql.push_str(&trigger.generate_create_ddl());
                    down_sql.push_str("\n\n");
                }
                schema_diff::SchemaDiff::TriggerModified {
                    name,
                    old_trigger,
                    new_trigger: _,
                } => {
                    down_sql.push_str(&format!("-- Rollback trigger modification {}\n", name));
                    down_sql.push_str(&format!("DROP TRIGGER IF EXISTS \"{}\" CASCADE;\n", name));
                    down_sql.push_str(&old_trigger.generate_create_ddl());
                    down_sql.push_str("\n");
                }
                _ => {} // Ignore other diffs in trigger processing
            }
        }

        // Process composite type diffs in reverse order
        for diff in composite_type_diffs.iter().rev() {
            match diff {
                schema_diff::SchemaDiff::CompositeTypeAdded { name, .. } => {
                    down_sql.push_str(&format!("-- Drop composite type {}\n", name));
                    down_sql.push_str(&format!("DROP TYPE IF EXISTS \"{}\" CASCADE;\n\n", name));
                }
                schema_diff::SchemaDiff::CompositeTypeDropped {
                    name,
                    composite_type,
                } => {
                    down_sql.push_str(&format!("-- Recreate composite type {}\n", name));
                    down_sql.push_str(&composite_type.generate_create_ddl());
                    down_sql.push_str("\n\n");
                }
                schema_diff::SchemaDiff::CompositeTypeModified {
                    name,
                    old_composite_type,
                    new_composite_type: _,
                } => {
                    down_sql.push_str(&format!(
                        "-- Rollback composite type modification {}\n",
                        name
                    ));
                    down_sql.push_str(&format!("DROP TYPE IF EXISTS \"{}\" CASCADE;\n", name));
                    down_sql.push_str(&old_composite_type.generate_create_ddl());
                    down_sql.push_str("\n");
                }
                _ => {} // Ignore other diffs in composite type processing
            }
        }

        down_sql
    }

    /// Generate reverse SQL for table modifications (for down migrations)
    fn generate_reverse_table_change_sql(
        &self,
        table_name: &str,
        old_table: &Table,
        new_table: &Table,
    ) -> String {
        let mut reverse_sql = String::new();

        // Create column maps for easy comparison
        let old_columns: HashMap<&String, &Column> =
            old_table.columns.iter().map(|c| (&c.name, c)).collect();
        let new_columns: HashMap<&String, &Column> =
            new_table.columns.iter().map(|c| (&c.name, c)).collect();

        // Find added columns (in new but not in old) - reverse is DROP COLUMN
        for column in &new_table.columns {
            if !old_columns.contains_key(&column.name) {
                reverse_sql.push_str(&format!(
                    "ALTER TABLE \"{}\" DROP COLUMN \"{}\" CASCADE;\n",
                    table_name, column.name
                ));
            }
        }

        // Find dropped columns (in old but not in new) - reverse is ADD COLUMN
        for column in &old_table.columns {
            if !new_columns.contains_key(&column.name) {
                reverse_sql.push_str(&format!(
                    "ALTER TABLE \"{}\" ADD COLUMN {};\n",
                    table_name,
                    column.to_sql().trim_start_matches("    ")
                ));
            }
        }

        // Find modified columns - reverse is DROP new column and ADD old column
        for new_column in &new_table.columns {
            if let Some(old_column) = old_columns.get(&new_column.name) {
                if !self.columns_equal(old_column, new_column) {
                    reverse_sql.push_str(&format!(
                        "ALTER TABLE \"{}\" DROP COLUMN \"{}\" CASCADE;\n",
                        table_name, new_column.name
                    ));
                    reverse_sql.push_str(&format!(
                        "ALTER TABLE \"{}\" ADD COLUMN {};\n",
                        table_name,
                        old_column.to_sql().trim_start_matches("    ")
                    ));
                }
            }
        }

        // Handle primary key changes
        if old_table.primary_key != new_table.primary_key {
            if let Some(_new_pk) = &new_table.primary_key {
                reverse_sql.push_str(&format!(
                    "ALTER TABLE \"{}\" DROP CONSTRAINT IF EXISTS \"{}_pkey\" CASCADE;\n",
                    table_name, table_name
                ));
            }
            if let Some(old_pk) = &old_table.primary_key {
                reverse_sql.push_str(&format!(
                    "ALTER TABLE \"{}\" ADD PRIMARY KEY (\"{}\");\n",
                    table_name, old_pk
                ));
            }
        }

        reverse_sql
    }

    /// Generate reverse SQL for view modifications (for down migrations)
    fn generate_reverse_view_change_sql(
        &self,
        view_name: &str,
        old_view: &View,
        new_view: &View,
    ) -> String {
        let mut reverse_sql = String::new();

        reverse_sql.push_str(&format!("-- Revert changes to view {}\n", view_name));

        // Handle materialized status changes
        if old_view.materialized != new_view.materialized {
            if new_view.materialized && !old_view.materialized {
                // Convert back from materialized to regular view
                reverse_sql.push_str(&format!(
                    "-- Convert view {} back to regular view\n",
                    view_name
                ));
                reverse_sql.push_str(&format!(
                    "DROP MATERIALIZED VIEW IF EXISTS \"{}\" CASCADE;\n",
                    view_name
                ));
                reverse_sql.push_str(&old_view.generate_ddl());
                reverse_sql.push_str("\n");
            } else if !new_view.materialized && old_view.materialized {
                // Convert back from regular to materialized view
                reverse_sql.push_str(&format!(
                    "-- Convert view {} back to materialized view\n",
                    view_name
                ));
                reverse_sql.push_str(&format!("DROP VIEW IF EXISTS \"{}\" CASCADE;\n", view_name));
                reverse_sql.push_str(&old_view.generate_ddl());
                reverse_sql.push_str("\n");
            }
        }

        // Handle dependency changes
        if old_view.dependencies != new_view.dependencies {
            let added: Vec<_> = new_view
                .dependencies
                .iter()
                .filter(|d| !old_view.dependencies.contains(d))
                .collect();
            let removed: Vec<_> = old_view
                .dependencies
                .iter()
                .filter(|d| !new_view.dependencies.contains(d))
                .collect();

            if !added.is_empty() {
                let added_names: Vec<String> = added.iter().map(|&s| s.clone()).collect();
                reverse_sql.push_str(&format!(
                    "-- View {} no longer depends on: {}\n",
                    view_name,
                    added_names.join(", ")
                ));
            }
            if !removed.is_empty() {
                let removed_names: Vec<String> = removed.iter().map(|&s| s.clone()).collect();
                reverse_sql.push_str(&format!(
                    "-- View {} now depends on: {}\n",
                    view_name,
                    removed_names.join(", ")
                ));
            }
        }

        // Handle index changes
        if old_view.indexes != new_view.indexes {
            let added: Vec<_> = new_view
                .indexes
                .iter()
                .filter(|i| !old_view.indexes.contains(i))
                .collect();
            let removed: Vec<_> = old_view
                .indexes
                .iter()
                .filter(|i| !new_view.indexes.contains(i))
                .collect();

            for added_index in added {
                reverse_sql.push_str(&format!(
                    "DROP INDEX IF EXISTS \"{}\" CASCADE;\n",
                    added_index.name
                ));
            }
            for removed_index in removed {
                reverse_sql.push_str(&removed_index.to_sql());
                reverse_sql.push_str("\n");
            }
        }

        // Handle column changes
        let old_columns: HashMap<&String, &Column> =
            old_view.columns.iter().map(|c| (&c.name, c)).collect();
        let new_columns: HashMap<&String, &Column> =
            new_view.columns.iter().map(|c| (&c.name, c)).collect();

        // Find added columns (in new but not in old) - reverse is DROP COLUMN
        for column in &new_view.columns {
            if !old_columns.contains_key(&column.name) {
                reverse_sql.push_str(&format!(
                    "-- Remove column {} from view {}\n",
                    column.name, view_name
                ));
            }
        }

        // Find dropped columns (in old but not in new) - reverse is ADD COLUMN
        for column in &old_view.columns {
            if !new_columns.contains_key(&column.name) {
                reverse_sql.push_str(&format!(
                    "-- Add column {} back to view {}\n",
                    column.name, view_name
                ));
            }
        }

        reverse_sql
    }

    /// Compare two columns for equality
    fn columns_equal(&self, old_column: &Column, new_column: &Column) -> bool {
        old_column.name == new_column.name
            && old_column.column_type == new_column.column_type
            && old_column.nullable == new_column.nullable
            && old_column.default == new_column.default
            && old_column.unique == new_column.unique
            && old_column.references == new_column.references
    }

    /// Generate reverse SQL for a table change (legacy method)
    #[allow(dead_code)]
    fn generate_reverse_table_change_sql_legacy(
        &self,
        table_name: &str,
        change: &schema_diff::TableChange,
    ) -> String {
        match change {
            schema_diff::TableChange::ColumnAdded { name, .. } => {
                format!(
                    "ALTER TABLE \"{}\" DROP COLUMN \"{}\" CASCADE;\n",
                    table_name, name
                )
            }
            schema_diff::TableChange::ColumnDropped {
                name: _name,
                column,
            } => {
                format!(
                    "ALTER TABLE \"{}\" ADD COLUMN {};\n",
                    table_name,
                    column.to_sql().trim_start_matches("    ")
                )
            }
            schema_diff::TableChange::ColumnModified {
                name, old_column, ..
            } => {
                let mut sql = String::new();

                // Drop the new column and add the old one back
                sql.push_str(&format!(
                    "ALTER TABLE \"{}\" DROP COLUMN \"{}\" CASCADE;\n",
                    table_name, name
                ));
                sql.push_str(&format!(
                    "ALTER TABLE \"{}\" ADD COLUMN {};\n",
                    table_name,
                    old_column.to_sql().trim_start_matches("    ")
                ));

                sql
            }
            schema_diff::TableChange::PrimaryKeyChanged { old_pk, new_pk } => {
                let mut sql = String::new();

                // Drop new primary key if it exists
                if let Some(_new_pk) = new_pk {
                    sql.push_str(&format!(
                        "ALTER TABLE \"{}\" DROP CONSTRAINT IF EXISTS \"{}_pkey\" CASCADE;\n",
                        table_name, table_name
                    ));
                }

                // Add old primary key back if it existed
                if let Some(old_pk) = old_pk {
                    sql.push_str(&format!(
                        "ALTER TABLE \"{}\" ADD PRIMARY KEY (\"{}\");\n",
                        table_name, old_pk
                    ));
                }

                sql
            }
            schema_diff::TableChange::IndexesChanged {
                old_indexes,
                new_indexes,
            } => {
                let mut sql = String::new();
                for old_index in old_indexes {
                    sql.push_str(&format!(
                        "DROP INDEX IF EXISTS \"{}\" CASCADE;\n",
                        old_index.name
                    ));
                }
                for new_index in new_indexes {
                    sql.push_str(&new_index.generate_ddl());
                    sql.push_str("\n");
                }
                sql
            }
        }
    }

    /// Generate reverse SQL for a view change (legacy method)
    #[allow(dead_code)]
    fn generate_reverse_view_change_sql_legacy(
        &self,
        view_name: &str,
        change: &schema_diff::ViewChange,
    ) -> String {
        match change {
            schema_diff::ViewChange::ColumnAdded { name, .. } => {
                format!(
                    "ALTER VIEW \"{}\" DROP COLUMN \"{}\" CASCADE;\n",
                    view_name, name
                )
            }
            schema_diff::ViewChange::ColumnDropped {
                name: _name,
                column,
            } => {
                format!(
                    "ALTER VIEW \"{}\" ADD COLUMN {};\n",
                    view_name,
                    column.to_sql().trim_start_matches("    ")
                )
            }
            schema_diff::ViewChange::ColumnModified {
                name, old_column, ..
            } => {
                let mut sql = String::new();

                // Drop the new column and add the old one back
                sql.push_str(&format!(
                    "ALTER VIEW \"{}\" DROP COLUMN \"{}\" CASCADE;\n",
                    view_name, name
                ));
                sql.push_str(&format!(
                    "ALTER VIEW \"{}\" ADD COLUMN {};\n",
                    view_name,
                    old_column.to_sql().trim_start_matches("    ")
                ));

                sql
            }
            schema_diff::ViewChange::PrimaryKeyChanged { old_pk, new_pk } => {
                let mut sql = String::new();

                // Drop new primary key if it exists
                if let Some(_new_pk) = new_pk {
                    sql.push_str(&format!(
                        "ALTER VIEW \"{}\" DROP CONSTRAINT IF EXISTS \"{}_pkey\" CASCADE;\n",
                        view_name, view_name
                    ));
                }

                // Add old primary key back if it existed
                if let Some(old_pk) = old_pk {
                    sql.push_str(&format!(
                        "ALTER VIEW \"{}\" ADD PRIMARY KEY (\"{}\");\n",
                        view_name, old_pk
                    ));
                }

                sql
            }
            schema_diff::ViewChange::MaterializedChanged {
                was_materialized,
                is_materialized,
            } => {
                if *was_materialized && !*is_materialized {
                    // Convert back to materialized view
                    format!("-- Convert view {} back to materialized view\n", view_name)
                } else if !*was_materialized && *is_materialized {
                    // Convert back to regular view
                    format!("-- Convert view {} back to regular view\n", view_name)
                } else {
                    String::new()
                }
            }
            schema_diff::ViewChange::DependenciesChanged { old_deps, new_deps } => {
                let mut sql = String::new();
                let added: Vec<_> = new_deps.iter().filter(|d| !old_deps.contains(d)).collect();
                let removed: Vec<_> = old_deps.iter().filter(|d| !new_deps.contains(d)).collect();

                if !added.is_empty() {
                    let added_names: Vec<String> = added.iter().map(|s| (*s).clone()).collect();
                    sql.push_str(&format!(
                        "-- Remove dependencies from view {}: {}\n",
                        view_name,
                        added_names.join(", ")
                    ));
                }
                if !removed.is_empty() {
                    let removed_names: Vec<String> = removed.iter().map(|s| (*s).clone()).collect();
                    sql.push_str(&format!(
                        "-- Restore dependencies to view {}: {}\n",
                        view_name,
                        removed_names.join(", ")
                    ));
                }
                sql
            }
            schema_diff::ViewChange::IndexesChanged {
                old_indexes,
                new_indexes,
            } => {
                let mut sql = String::new();
                let added: Vec<_> = new_indexes
                    .iter()
                    .filter(|i| !old_indexes.contains(i))
                    .collect();
                let removed: Vec<_> = old_indexes
                    .iter()
                    .filter(|i| !new_indexes.contains(i))
                    .collect();

                if !added.is_empty() {
                    let added_names: Vec<String> = added.iter().map(|i| i.name.clone()).collect();
                    sql.push_str(&format!(
                        "-- Drop indexes from view {}: {}\n",
                        view_name,
                        added_names.join(", ")
                    ));
                }
                if !removed.is_empty() {
                    let removed_names: Vec<String> =
                        removed.iter().map(|i| i.name.clone()).collect();
                    sql.push_str(&format!(
                        "-- Restore indexes to view {}: {}\n",
                        view_name,
                        removed_names.join(", ")
                    ));
                }
                sql
            }
        }
    }
}

/// Execute SQL that may contain multiple statements
async fn execute_multi_statement_sql(
    sql: &str,
    executor: &mut sqlx::PgConnection,
) -> sqlx::Result<()> {
    // Split SQL by semicolons and process each statement
    let raw_statements: Vec<&str> = sql.split(';').collect();
    let mut statements = Vec::new();

    for raw_stmt in raw_statements {
        // Clean up the statement - remove comments and empty lines
        let cleaned_lines: Vec<&str> = raw_stmt
            .lines()
            .map(|line| line.trim())
            .filter(|line| !line.is_empty() && !line.starts_with("--"))
            .collect();

        let cleaned_stmt = cleaned_lines.join("\n").trim().to_string();

        if !cleaned_stmt.is_empty() {
            statements.push(cleaned_stmt);
        }
    }

    for statement in statements {
        if !statement.trim().is_empty() {
            sqlx::query(&statement).execute(&mut *executor).await?;
        }
    }

    Ok(())
}

/// Simple migration manager for CLI operations
pub struct MigrationManager {
    pool: sqlx::PgPool,
    migrations_dir: std::path::PathBuf,
    database_type: Option<crate::database::DatabaseType>,
}

impl MigrationManager {
    /// Create a new migration manager
    pub fn new(pool: sqlx::PgPool, migrations_dir: std::path::PathBuf) -> Self {
        Self {
            pool,
            migrations_dir,
            database_type: Some(crate::database::DatabaseType::PostgreSQL), // Default to PostgreSQL
        }
    }

    /// Create a new multi-platform migration manager
    pub fn new_multi_platform(
        pool: sqlx::PgPool,
        migrations_dir: std::path::PathBuf,
        database_type: crate::database::DatabaseType,
    ) -> Self {
        Self {
            pool,
            migrations_dir,
            database_type: Some(database_type),
        }
    }

    /// Ensure the migration tracking table exists
    pub async fn ensure_migration_table(&self) -> sqlx::Result<()> {
        let create_table_sql = match self.database_type {
            Some(crate::database::DatabaseType::PostgreSQL) => {
                r#"
                CREATE TABLE IF NOT EXISTS __ignis_migrations (
                    id SERIAL PRIMARY KEY,
                    name VARCHAR(255) NOT NULL UNIQUE,
                    checksum VARCHAR(64) NOT NULL,
                    applied_at TIMESTAMPTZ DEFAULT NOW(),
                    is_baseline BOOLEAN DEFAULT false
                );
                "#
            }
            Some(crate::database::DatabaseType::MySQL) => {
                r#"
                CREATE TABLE IF NOT EXISTS __ignis_migrations (
                    id INT AUTO_INCREMENT PRIMARY KEY,
                    name VARCHAR(255) NOT NULL UNIQUE,
                    checksum VARCHAR(64) NOT NULL,
                    applied_at DATETIME DEFAULT CURRENT_TIMESTAMP,
                    is_baseline BOOLEAN DEFAULT false
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
                "#
            }
            _ => {
                // Default to PostgreSQL syntax for unsupported databases
                r#"
                CREATE TABLE IF NOT EXISTS __ignis_migrations (
                    id SERIAL PRIMARY KEY,
                    name VARCHAR(255) NOT NULL UNIQUE,
                    checksum VARCHAR(64) NOT NULL,
                    applied_at TIMESTAMPTZ DEFAULT NOW(),
                    is_baseline BOOLEAN DEFAULT false
                );
                "#
            }
        };

        sqlx::query(create_table_sql).execute(&self.pool).await?;

        Ok(())
    }

    /// Get all applied migrations from the database
    pub async fn get_applied_migrations(&self) -> sqlx::Result<Vec<AppliedMigration>> {
        let query = r#"
            SELECT name, checksum, applied_at, COALESCE(is_baseline, false) as is_baseline
            FROM __ignis_migrations
            ORDER BY applied_at ASC
        "#;

        let rows = sqlx::query(query).fetch_all(&self.pool).await?;

        let mut migrations = Vec::new();
        for row in rows {
            let name: String = row.get("name");
            let checksum: String = row.get("checksum");
            let applied_at: chrono::DateTime<chrono::Utc> = row.get("applied_at");
            let is_baseline: bool = row.get("is_baseline");

            migrations.push(AppliedMigration {
                name,
                checksum,
                applied_at,
                is_baseline,
            });
        }

        Ok(migrations)
    }

    /// Apply a migration
    pub async fn apply_migration(&self, name: &str, up_sql: &str) -> sqlx::Result<()> {
        // Calculate checksum
        let checksum = calculate_migration_checksum(up_sql);

        // Execute the migration in a transaction
        let mut tx = self.pool.begin().await?;

        // Run the migration SQL (split into individual statements for proper execution)
        execute_multi_statement_sql(up_sql, &mut *tx).await?;

        // Record the migration
        let record_sql = r#"
            INSERT INTO __ignis_migrations (name, checksum, is_baseline)
            VALUES ($1, $2, false)
        "#;

        sqlx::query(record_sql)
            .bind(name)
            .bind(&checksum)
            .execute(&mut *tx)
            .await?;

        tx.commit().await?;

        Ok(())
    }

    /// Rollback a migration
    pub async fn rollback_migration(&self, name: &str, down_sql: &str) -> sqlx::Result<()> {
        // Execute the rollback in a transaction
        let mut tx = self.pool.begin().await?;

        // Run the rollback SQL
        sqlx::query(down_sql).execute(&mut *tx).await?;

        // Remove the migration record
        let delete_sql = r#"
            DELETE FROM __ignis_migrations
            WHERE name = $1
        "#;

        sqlx::query(delete_sql).bind(name).execute(&mut *tx).await?;

        tx.commit().await?;

        Ok(())
    }

    /// Get the migrations directory path
    pub fn migrations_dir(&self) -> &std::path::Path {
        &self.migrations_dir
    }

    /// Get the database type
    pub fn database_type(&self) -> Option<&crate::database::DatabaseType> {
        self.database_type.as_ref()
    }
}

/// Represents an applied migration
#[derive(Debug, Clone)]
pub struct AppliedMigration {
    pub name: String,
    pub checksum: String,
    pub applied_at: chrono::DateTime<chrono::Utc>,
    pub is_baseline: bool,
}

/// Calculate a checksum for migration content
fn calculate_migration_checksum(sql: &str) -> String {
    use std::collections::hash_map::DefaultHasher;
    use std::hash::{Hash, Hasher};

    let mut hasher = DefaultHasher::new();
    sql.hash(&mut hasher);
    format!("{:x}", hasher.finish())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::schema::{Column, ColumnType, Table, View};

    #[test]
    fn test_migration_generation() {
        let mut old_tables = HashMap::new();
        let mut new_tables = HashMap::new();

        // Old schema: users table with just id
        let old_users = Table::new("users")
            .add_column(Column::new("id", ColumnType::Int4))
            .set_primary_key("id");

        // New schema: users table with id and email
        let new_users = Table::new("users")
            .add_column(Column::new("id", ColumnType::Int4))
            .add_column(Column::new("email", ColumnType::Varchar(None)))
            .set_primary_key("id");

        old_tables.insert("users".to_string(), old_users);
        new_tables.insert("users".to_string(), new_users);

        let manager = SchemaMigrationManager::new()
            .set_old_schema(old_tables)
            .set_new_schema(new_tables);

        let migration = manager.generate_migration("add_email_to_users").unwrap();

        // Debug output
        println!("Generated migration:");
        println!("Up SQL: {}", migration.up_sql);
        println!("Down SQL: {}", migration.down_sql.as_ref().unwrap());

        // Verify up migration contains ALTER TABLE ADD COLUMN
        assert!(migration.up_sql.contains("ALTER TABLE"));
        assert!(migration.up_sql.contains("ADD COLUMN"));
        assert!(migration.up_sql.contains("email"));

        // Verify down migration contains ALTER TABLE DROP COLUMN
        assert!(migration.down_sql.as_ref().unwrap().contains("DROP COLUMN"));
        assert!(migration.down_sql.as_ref().unwrap().contains("email"));
    }

    #[test]
    fn test_view_migration_generation() {
        let mut old_views = HashMap::new();
        let mut new_views = HashMap::new();

        // Old schema: simple view
        let old_view = View::new("user_summary")
            .add_column(Column::new("id", ColumnType::Int4))
            .add_column(Column::new("name", ColumnType::Varchar(None)));

        // New schema: materialized view with indexes
        let new_view = View::new("user_summary")
            .add_column(Column::new("id", ColumnType::Int4))
            .add_column(Column::new("name", ColumnType::Varchar(None)))
            .add_column(Column::new("post_count", ColumnType::Int4))
            .set_materialized(true)
            .add_index("idx_user_summary_id", vec!["id".to_string()])
            .add_dependency("users")
            .add_dependency("posts")
            .clone();

        old_views.insert("user_summary".to_string(), old_view);
        new_views.insert("user_summary".to_string(), new_view);

        let manager = SchemaMigrationManager::new()
            .set_old_views(old_views)
            .set_new_views(new_views);

        let migration = manager
            .generate_migration("enhance_user_summary_view")
            .unwrap();

        // Debug output
        println!("Generated migration:");
        println!("Up SQL: {}", migration.up_sql);
        println!("Down SQL: {}", migration.down_sql.as_ref().unwrap());

        // Verify up migration contains view changes
        assert!(migration.up_sql.contains("View Changes"));
        assert!(migration.up_sql.contains("user_summary"));

        // Verify down migration contains view change reversals
        assert!(migration
            .down_sql
            .as_ref()
            .unwrap()
            .contains("Revert changes to view"));
        assert!(migration
            .down_sql
            .as_ref()
            .unwrap()
            .contains("user_summary"));
    }
}