reinhardt-db 0.1.0

Django-style database layer for Reinhardt framework
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
//! Schema diff detection
//!
//! Detects differences between current database schema and model definitions:
//! - Table additions/removals
//! - Column modifications
//! - Index changes
//! - Constraint changes

use super::ColumnDefinition;
use super::introspection;
use super::operations::Operation;
use std::collections::BTreeMap;

/// Schema difference detector
pub struct SchemaDiff {
	/// Current database schema
	current_schema: DatabaseSchema,
	/// Target schema from models
	target_schema: DatabaseSchema,
}

/// Database schema representation
#[derive(Debug, Clone, Default)]
pub struct DatabaseSchema {
	/// Table definitions (BTreeMap for deterministic iteration order)
	pub tables: BTreeMap<String, TableSchema>,
}

impl From<introspection::DatabaseSchema> for DatabaseSchema {
	fn from(intro_schema: introspection::DatabaseSchema) -> Self {
		let mut tables = BTreeMap::new();

		for (table_name, intro_table) in intro_schema.tables {
			let mut columns = BTreeMap::new();
			for (col_name, intro_col) in intro_table.columns {
				// Simplified conversion
				columns.insert(
					col_name.clone(),
					ColumnSchema {
						name: intro_col.name,
						data_type: intro_col.column_type,
						nullable: intro_col.nullable,
						default: intro_col.default,
						primary_key: intro_table.primary_key.contains(&col_name), // Check if column is in primary_key list
						auto_increment: intro_col.auto_increment,
					},
				);
			}

			let indexes: Vec<IndexSchema> = intro_table
				.indexes
				.values()
				.map(|idx| IndexSchema {
					name: idx.name.clone(),
					columns: idx.columns.clone(),
					unique: idx.unique,
				})
				.collect();

			let mut constraints: Vec<ConstraintSchema> = intro_table
				.unique_constraints
				.iter()
				.map(|uc| ConstraintSchema {
					name: uc.name.clone(),
					constraint_type: "UNIQUE".to_string(),
					definition: format!(
						"CONSTRAINT {} UNIQUE ({})",
						uc.name,
						uc.columns.join(", ")
					),
					foreign_key_info: None,
				})
				.collect();

			// Process foreign keys with structured information
			for fk in &intro_table.foreign_keys {
				let on_delete = fk
					.on_delete
					.clone()
					.unwrap_or_else(|| "NO ACTION".to_string());
				let on_update = fk
					.on_update
					.clone()
					.unwrap_or_else(|| "NO ACTION".to_string());

				let mut definition = format!(
					"CONSTRAINT {} FOREIGN KEY ({}) REFERENCES {}({})",
					fk.name,
					fk.columns.join(", "),
					fk.referenced_table,
					fk.referenced_columns.join(", ")
				);

				if on_delete != "NO ACTION" {
					definition.push_str(&format!(" ON DELETE {}", on_delete));
				}

				if on_update != "NO ACTION" {
					definition.push_str(&format!(" ON UPDATE {}", on_update));
				}

				constraints.push(ConstraintSchema {
					name: fk.name.clone(),
					constraint_type: "FOREIGN KEY".to_string(),
					definition,
					foreign_key_info: Some(ForeignKeySchemaInfo {
						columns: fk.columns.clone(),
						referenced_table: fk.referenced_table.clone(),
						referenced_columns: fk.referenced_columns.clone(),
						on_delete,
						on_update,
					}),
				});
			}

			tables.insert(
				table_name,
				TableSchema {
					name: intro_table.name,
					columns,
					indexes,
					constraints,
				},
			);
		}

		DatabaseSchema { tables }
	}
}

impl DatabaseSchema {
	/// Filter tables by app_label prefix
	///
	/// This method filters tables based on the Django-style naming convention
	/// where table names are prefixed with the app label (e.g., "users_user", "todos_todo").
	///
	/// # Examples
	///
	/// ```rust,ignore
	/// use reinhardt_db::migrations::schema_diff::DatabaseSchema;
	///
	/// let schema = DatabaseSchema::default();
	/// let filtered = schema.filter_by_app("users");
	/// // filtered contains only tables starting with "users_"
	/// ```
	pub fn filter_by_app(&self, app_label: &str) -> DatabaseSchema {
		let mut filtered_tables = BTreeMap::new();
		let prefix = format!("{}_", app_label);

		for (table_name, table_schema) in &self.tables {
			if table_name.starts_with(&prefix) {
				filtered_tables.insert(table_name.clone(), table_schema.clone());
			}
		}

		DatabaseSchema {
			tables: filtered_tables,
		}
	}
}

/// Table schema
#[derive(Debug, Clone)]
pub struct TableSchema {
	/// Table name
	pub name: String,
	/// Column definitions (BTreeMap for deterministic iteration order)
	pub columns: BTreeMap<String, ColumnSchema>,
	/// Indexes
	pub indexes: Vec<IndexSchema>,
	/// Constraints
	pub constraints: Vec<ConstraintSchema>,
}

/// Column schema
#[derive(Debug, Clone, PartialEq)]
pub struct ColumnSchema {
	/// Column name
	pub name: String,
	/// Data type
	pub data_type: super::FieldType,
	/// Nullable
	pub nullable: bool,
	/// Default value
	pub default: Option<String>,
	/// Primary key
	pub primary_key: bool,
	/// Auto increment
	pub auto_increment: bool,
}

/// Index schema
#[derive(Debug, Clone, PartialEq)]
pub struct IndexSchema {
	/// Index name
	pub name: String,
	/// Columns
	pub columns: Vec<String>,
	/// Unique index
	pub unique: bool,
}

/// Constraint schema
#[derive(Debug, Clone, PartialEq)]
pub struct ConstraintSchema {
	/// Constraint name
	pub name: String,
	/// Constraint type (UNIQUE, FOREIGN KEY, CHECK, etc.)
	pub constraint_type: String,
	/// Definition (columns for UNIQUE, expression for CHECK, etc.)
	pub definition: String,
	/// Foreign key specific information (only for FOREIGN KEY / ONE_TO_ONE types)
	pub foreign_key_info: Option<ForeignKeySchemaInfo>,
}

/// Foreign key constraint information for schema diff
///
/// This struct holds structured information about foreign key constraints,
/// enabling proper constraint extraction and comparison.
#[derive(Debug, Clone, PartialEq)]
pub struct ForeignKeySchemaInfo {
	/// Source columns in the referencing table
	pub columns: Vec<String>,
	/// Referenced table name
	pub referenced_table: String,
	/// Referenced columns in the target table
	pub referenced_columns: Vec<String>,
	/// ON DELETE action (CASCADE, SET NULL, SET DEFAULT, RESTRICT, NO ACTION)
	pub on_delete: String,
	/// ON UPDATE action (CASCADE, SET NULL, SET DEFAULT, RESTRICT, NO ACTION)
	pub on_update: String,
}

/// Schema diff result
#[derive(Debug, Clone)]
pub struct SchemaDiffResult {
	/// Tables to add
	pub tables_to_add: Vec<String>,
	/// Tables to remove
	pub tables_to_remove: Vec<String>,
	/// Columns to add (table_name, column_name)
	pub columns_to_add: Vec<(String, String)>,
	/// Columns to remove (table_name, column_name)
	pub columns_to_remove: Vec<(String, String)>,
	/// Columns to modify (table_name, column_name, old, new)
	pub columns_to_modify: Vec<(String, String, ColumnSchema, ColumnSchema)>,
	/// Indexes to add
	pub indexes_to_add: Vec<(String, IndexSchema)>,
	/// Indexes to remove
	pub indexes_to_remove: Vec<(String, IndexSchema)>,
	/// Constraints to add (table_name, constraint)
	pub constraints_to_add: Vec<(String, ConstraintSchema)>,
	/// Constraints to remove (table_name, constraint)
	pub constraints_to_remove: Vec<(String, ConstraintSchema)>,
}

impl SchemaDiff {
	/// Create a new schema diff detector
	pub fn new(current_schema: DatabaseSchema, target_schema: DatabaseSchema) -> Self {
		Self {
			current_schema,
			target_schema,
		}
	}

	/// Detect differences between schemas
	pub fn detect(&self) -> SchemaDiffResult {
		let mut result = SchemaDiffResult {
			tables_to_add: Vec::new(),
			tables_to_remove: Vec::new(),
			columns_to_add: Vec::new(),
			columns_to_remove: Vec::new(),
			columns_to_modify: Vec::new(),
			indexes_to_add: Vec::new(),
			indexes_to_remove: Vec::new(),
			constraints_to_add: Vec::new(),
			constraints_to_remove: Vec::new(),
		};

		// System tables to exclude from migration generation
		let system_tables = ["reinhardt_migrations"];

		// Detect table additions
		for table_name in self.target_schema.tables.keys() {
			if !self.current_schema.tables.contains_key(table_name) {
				result.tables_to_add.push(table_name.clone());
			}
		}

		// Detect table removals (skip system tables)
		for table_name in self.current_schema.tables.keys() {
			if system_tables.contains(&table_name.as_str()) {
				continue; // Skip system tables
			}
			if !self.target_schema.tables.contains_key(table_name) {
				result.tables_to_remove.push(table_name.clone());
			}
		}

		// Detect column changes for existing tables
		for (table_name, target_table) in &self.target_schema.tables {
			if let Some(current_table) = self.current_schema.tables.get(table_name) {
				// Clone table_name once for reuse across all change types
				let table_name_owned = table_name.clone();

				// Column additions
				for col_name in target_table.columns.keys() {
					if !current_table.columns.contains_key(col_name) {
						result
							.columns_to_add
							.push((table_name_owned.clone(), col_name.clone()));
					}
				}

				// Column removals
				for col_name in current_table.columns.keys() {
					if !target_table.columns.contains_key(col_name) {
						result
							.columns_to_remove
							.push((table_name_owned.clone(), col_name.clone()));
					}
				}

				// Column modifications
				for (col_name, target_col) in &target_table.columns {
					if let Some(current_col) = current_table.columns.get(col_name)
						&& current_col != target_col
					{
						result.columns_to_modify.push((
							table_name_owned.clone(),
							col_name.clone(),
							current_col.clone(),
							target_col.clone(),
						));
					}
				}

				// Index changes
				for target_index in &target_table.indexes {
					if !current_table.indexes.contains(target_index) {
						result
							.indexes_to_add
							.push((table_name_owned.clone(), target_index.clone()));
					}
				}

				for current_index in &current_table.indexes {
					if !target_table.indexes.contains(current_index) {
						result
							.indexes_to_remove
							.push((table_name_owned.clone(), current_index.clone()));
					}
				}

				// Constraint additions
				for target_constraint in &target_table.constraints {
					if !current_table.constraints.contains(target_constraint) {
						result
							.constraints_to_add
							.push((table_name_owned.clone(), target_constraint.clone()));
					}
				}

				// Constraint removals
				for current_constraint in &current_table.constraints {
					if !target_table.constraints.contains(current_constraint) {
						result
							.constraints_to_remove
							.push((table_name_owned.clone(), current_constraint.clone()));
					}
				}
			}
		}

		result
	}

	/// Generate migration operations from diff
	pub fn generate_operations(&self) -> Vec<Operation> {
		let diff = self.detect();
		let mut operations = Vec::new();

		// Add tables
		for table_name in &diff.tables_to_add {
			if let Some(table_schema) = self.target_schema.tables.get(table_name) {
				// Map columns to ColumnDefinition
				let columns: Vec<_> = table_schema
					.columns
					.iter()
					.map(|(name, col)| {
						let unique = self.extract_column_constraints(table_name, name);
						let auto_increment = Self::is_auto_increment(col);

						ColumnDefinition {
							name: name.clone(),
							type_definition: col.data_type.clone(),
							not_null: !col.nullable,
							default: col.default.as_ref().cloned(),
							unique,
							primary_key: col.primary_key,
							auto_increment,
						}
					})
					.collect();

				// Extract table-level constraints
				let constraints = self.extract_constraints(table_name);

				operations.push(Operation::CreateTable {
					name: table_name.clone(),
					columns,
					constraints,
					without_rowid: None,
					interleave_in_parent: None,
					partition: None,
				});

				// Generate CreateIndex for indexes on new tables
				// (detect() only compares indexes on existing tables)
				for index in &table_schema.indexes {
					operations.push(Operation::CreateIndex {
						table: table_name.clone(),
						columns: index.columns.clone(),
						unique: index.unique,
						index_type: None,
						where_clause: None,
						concurrently: false,
						expressions: None,
						mysql_options: None,
						operator_class: None,
					});
				}
			}
		}

		// Remove tables
		for table_name in &diff.tables_to_remove {
			operations.push(Operation::DropTable {
				name: table_name.clone(),
			});
		}

		// Add columns
		for (table_name, col_name) in &diff.columns_to_add {
			if let Some(table_schema) = self.target_schema.tables.get(table_name)
				&& let Some(col_schema) = table_schema.columns.get(col_name)
			{
				let unique = self.extract_column_constraints(table_name, col_name);
				let auto_increment = Self::is_auto_increment(col_schema);

				operations.push(Operation::AddColumn {
					table: table_name.clone(),
					column: ColumnDefinition {
						name: col_name.clone(),
						type_definition: col_schema.data_type.clone(),
						not_null: !col_schema.nullable,
						default: col_schema.default.as_ref().cloned(),
						unique,
						primary_key: col_schema.primary_key,
						auto_increment,
					},
					mysql_options: None,
				});
			}
		}

		// Remove columns
		for (table_name, col_name) in &diff.columns_to_remove {
			operations.push(Operation::DropColumn {
				table: table_name.clone(),
				column: col_name.clone(),
			});
		}

		// Alter columns (type changes, nullability changes, etc.)
		for (table_name, col_name, old_col, new_col) in &diff.columns_to_modify {
			let old_unique = Self::column_has_unique(&self.current_schema, table_name, col_name);
			let new_unique = Self::column_has_unique(&self.target_schema, table_name, col_name);

			operations.push(Operation::AlterColumn {
				table: table_name.clone(),
				column: col_name.clone(),
				old_definition: Some(ColumnDefinition {
					name: col_name.clone(),
					type_definition: old_col.data_type.clone(),
					not_null: !old_col.nullable,
					default: old_col.default.as_ref().cloned(),
					unique: old_unique,
					primary_key: old_col.primary_key,
					auto_increment: Self::is_auto_increment(old_col),
				}),
				new_definition: ColumnDefinition {
					name: col_name.clone(),
					type_definition: new_col.data_type.clone(),
					not_null: !new_col.nullable,
					default: new_col.default.as_ref().cloned(),
					unique: new_unique,
					primary_key: new_col.primary_key,
					auto_increment: Self::is_auto_increment(new_col),
				},
				mysql_options: None,
			});
		}

		// Add indexes
		for (table_name, index) in &diff.indexes_to_add {
			operations.push(Operation::CreateIndex {
				table: table_name.clone(),
				columns: index.columns.clone(),
				unique: index.unique,
				index_type: None,
				where_clause: None,
				concurrently: false,
				expressions: None,
				mysql_options: None,
				operator_class: None,
			});
		}

		// Remove indexes
		for (table_name, index) in &diff.indexes_to_remove {
			operations.push(Operation::DropIndex {
				table: table_name.clone(),
				columns: index.columns.clone(),
			});
		}

		// Add constraints
		for (table_name, constraint) in &diff.constraints_to_add {
			let constraint_sql = Self::constraint_schema_to_sql(constraint);
			operations.push(Operation::AddConstraint {
				table: table_name.clone(),
				constraint_sql,
			});
		}

		// Remove constraints
		for (table_name, constraint) in &diff.constraints_to_remove {
			operations.push(Operation::DropConstraint {
				table: table_name.clone(),
				constraint_name: constraint.name.clone(),
			});
		}

		operations
	}

	/// Check if diff has destructive changes
	pub fn has_destructive_changes(&self) -> bool {
		let diff = self.detect();
		!diff.tables_to_remove.is_empty()
			|| !diff.columns_to_remove.is_empty()
			|| !diff.columns_to_modify.is_empty()
			|| !diff.indexes_to_remove.is_empty()
			|| !diff.constraints_to_remove.is_empty()
	}

	/// Check if a column has a unique constraint or index in a given schema
	fn column_has_unique(schema: &DatabaseSchema, table_name: &str, column_name: &str) -> bool {
		let table_schema = match schema.tables.get(table_name) {
			Some(t) => t,
			None => return false,
		};

		let has_unique_constraint = table_schema.constraints.iter().any(|constraint| {
			constraint.constraint_type.to_uppercase() == "UNIQUE"
				&& constraint.definition.contains(column_name)
		});

		let has_unique_index = table_schema.indexes.iter().any(|index| {
			index.unique && index.columns.len() == 1 && index.columns[0] == column_name
		});

		has_unique_constraint || has_unique_index
	}

	/// Convert a ConstraintSchema to a SQL definition string for AddConstraint
	fn constraint_schema_to_sql(constraint: &ConstraintSchema) -> String {
		match constraint.constraint_type.to_uppercase().as_str() {
			"UNIQUE" => {
				format!(
					"CONSTRAINT {} UNIQUE ({})",
					constraint.name, constraint.definition
				)
			}
			"CHECK" => {
				format!(
					"CONSTRAINT {} CHECK ({})",
					constraint.name, constraint.definition
				)
			}
			"FOREIGN KEY" | "FOREIGN_KEY" => {
				if let Some(ref fk) = constraint.foreign_key_info {
					format!(
						"CONSTRAINT {} FOREIGN KEY ({}) REFERENCES {} ({}) ON DELETE {} ON UPDATE {}",
						constraint.name,
						fk.columns.join(", "),
						fk.referenced_table,
						fk.referenced_columns.join(", "),
						fk.on_delete,
						fk.on_update,
					)
				} else {
					format!(
						"CONSTRAINT {} FOREIGN KEY ({})",
						constraint.name, constraint.definition
					)
				}
			}
			"ONE_TO_ONE" => {
				if let Some(ref fk) = constraint.foreign_key_info {
					format!(
						"CONSTRAINT {} FOREIGN KEY ({}) REFERENCES {} ({}) ON DELETE {} ON UPDATE {}",
						constraint.name,
						fk.columns.join(", "),
						fk.referenced_table,
						fk.referenced_columns.join(", "),
						fk.on_delete,
						fk.on_update,
					)
				} else {
					format!(
						"CONSTRAINT {} UNIQUE ({})",
						constraint.name, constraint.definition
					)
				}
			}
			_ => {
				format!(
					"CONSTRAINT {} {} ({})",
					constraint.name, constraint.constraint_type, constraint.definition
				)
			}
		}
	}

	/// Extract column-level constraints from table constraints and indexes
	fn extract_column_constraints(&self, table_name: &str, column_name: &str) -> bool {
		Self::column_has_unique(&self.target_schema, table_name, column_name)
	}

	/// Detect if column is auto-increment based on column properties and data type
	fn is_auto_increment(column: &ColumnSchema) -> bool {
		// If already marked as auto_increment, trust it
		if column.auto_increment {
			return true;
		}

		let upper_type = column.data_type.to_sql_string().to_uppercase();

		// PostgreSQL SERIAL types (SMALLSERIAL, SERIAL, BIGSERIAL)
		if upper_type.contains("SERIAL") {
			return true;
		}

		// MySQL AUTO_INCREMENT (typically in extra metadata, but check data type comments)
		if upper_type.contains("AUTO_INCREMENT") {
			return true;
		}

		// SQLite: INTEGER PRIMARY KEY is auto-increment by default
		if column.primary_key && (upper_type == "INTEGER" || upper_type == "INT") {
			return true;
		}

		false
	}

	/// Extract table-level constraint definitions
	fn extract_constraints(&self, table_name: &str) -> Vec<super::Constraint> {
		let table_schema = match self.target_schema.tables.get(table_name) {
			Some(t) => t,
			None => return Vec::new(),
		};

		let mut constraints = Vec::new();

		// Extract PRIMARY KEY constraint as Unique constraint (composite keys only)
		let pk_columns: Vec<String> = table_schema
			.columns
			.iter()
			.filter_map(|(name, col)| {
				if col.primary_key {
					Some(name.clone())
				} else {
					None
				}
			})
			.collect();

		if pk_columns.len() > 1 {
			// Composite primary key represented as Unique constraint
			constraints.push(super::Constraint::Unique {
				name: format!("{}_pkey", table_name),
				columns: pk_columns,
			});
		}

		// Extract UNIQUE constraints from indexes (multi-column unique indexes)
		for index in &table_schema.indexes {
			if index.unique && index.columns.len() > 1 {
				constraints.push(super::Constraint::Unique {
					name: index.name.clone(),
					columns: index.columns.clone(),
				});
			}
		}

		// Extract constraints from table_schema.constraints (from model definitions)
		for constraint_schema in &table_schema.constraints {
			match constraint_schema.constraint_type.to_uppercase().as_str() {
				"UNIQUE" => {
					constraints.push(super::Constraint::Unique {
						name: constraint_schema.name.clone(),
						columns: constraint_schema
							.definition
							.split(", ")
							.map(String::from)
							.collect(),
					});
				}
				"FOREIGN KEY" | "FOREIGN_KEY" => {
					// Use structured FK info if available
					if let Some(ref fk_info) = constraint_schema.foreign_key_info {
						constraints.push(super::Constraint::ForeignKey {
							name: constraint_schema.name.clone(),
							columns: fk_info.columns.clone(),
							referenced_table: fk_info.referenced_table.clone(),
							referenced_columns: fk_info.referenced_columns.clone(),
							on_delete: Self::parse_fk_action(&fk_info.on_delete),
							on_update: Self::parse_fk_action(&fk_info.on_update),
							deferrable: None,
						});
					}
				}
				"ONE_TO_ONE" => {
					// OneToOne is similar to ForeignKey but typically single-column
					if let Some(ref fk_info) = constraint_schema.foreign_key_info {
						constraints.push(super::Constraint::OneToOne {
							name: constraint_schema.name.clone(),
							column: fk_info.columns.first().cloned().unwrap_or_default(),
							referenced_table: fk_info.referenced_table.clone(),
							referenced_column: fk_info
								.referenced_columns
								.first()
								.cloned()
								.unwrap_or_else(|| "id".to_string()),
							on_delete: Self::parse_fk_action(&fk_info.on_delete),
							on_update: Self::parse_fk_action(&fk_info.on_update),
							deferrable: None,
						});
					}
				}
				"CHECK" => {
					constraints.push(super::Constraint::Check {
						name: constraint_schema.name.clone(),
						expression: constraint_schema.definition.clone(),
					});
				}
				_ => {}
			}
		}

		constraints
	}

	/// Parse FK action string to ForeignKeyAction enum
	fn parse_fk_action(action: &str) -> super::ForeignKeyAction {
		match action.to_uppercase().as_str() {
			"CASCADE" => super::ForeignKeyAction::Cascade,
			"SET NULL" => super::ForeignKeyAction::SetNull,
			"SET DEFAULT" => super::ForeignKeyAction::SetDefault,
			"RESTRICT" => super::ForeignKeyAction::Restrict,
			// "NO ACTION" is the default FK action in SQL, treat unknown actions as NoAction
			_ => super::ForeignKeyAction::NoAction,
		}
	}
}

#[cfg(test)]
mod tests {
	use super::*;
	use crate::migrations::FieldType;

	#[test]
	fn test_detect_table_addition() {
		let current = DatabaseSchema::default();
		let mut target = DatabaseSchema::default();
		target.tables.insert(
			"users".to_string(),
			TableSchema {
				name: "users".to_string(),
				columns: BTreeMap::new(),
				indexes: Vec::new(),
				constraints: Vec::new(),
			},
		);

		let diff = SchemaDiff::new(current, target);
		let result = diff.detect();

		assert_eq!(result.tables_to_add.len(), 1);
		assert_eq!(result.tables_to_add[0], "users");
	}

	#[test]
	fn test_detect_column_addition() {
		let mut current = DatabaseSchema::default();
		current.tables.insert(
			"users".to_string(),
			TableSchema {
				name: "users".to_string(),
				columns: BTreeMap::new(),
				indexes: Vec::new(),
				constraints: Vec::new(),
			},
		);

		let mut target = DatabaseSchema::default();
		let mut target_table = TableSchema {
			name: "users".to_string(),
			columns: BTreeMap::new(),
			indexes: Vec::new(),
			constraints: Vec::new(),
		};
		target_table.columns.insert(
			"email".to_string(),
			ColumnSchema {
				name: "email".to_string(),
				data_type: FieldType::VarChar(255),
				nullable: false,
				default: None,
				primary_key: false,
				auto_increment: false,
			},
		);
		target.tables.insert("users".to_string(), target_table);

		let diff = SchemaDiff::new(current, target);
		let result = diff.detect();

		assert_eq!(result.columns_to_add.len(), 1);
		assert_eq!(
			result.columns_to_add[0],
			("users".to_string(), "email".to_string())
		);
	}

	#[test]
	fn test_destructive_changes_detection() {
		let mut current = DatabaseSchema::default();
		current.tables.insert(
			"users".to_string(),
			TableSchema {
				name: "users".to_string(),
				columns: BTreeMap::new(),
				indexes: Vec::new(),
				constraints: Vec::new(),
			},
		);

		let target = DatabaseSchema::default();

		let diff = SchemaDiff::new(current, target);
		assert!(diff.has_destructive_changes());
	}

	// ================================================================
	// generate_operations() tests (issue #3198 related)
	// ================================================================

	/// Helper to create a simple column schema
	fn col(name: &str, data_type: FieldType, nullable: bool) -> ColumnSchema {
		ColumnSchema {
			name: name.to_string(),
			data_type,
			nullable,
			default: None,
			primary_key: false,
			auto_increment: false,
		}
	}

	/// Helper to create a primary key column
	fn pk_col(name: &str) -> ColumnSchema {
		ColumnSchema {
			name: name.to_string(),
			data_type: FieldType::Integer,
			nullable: false,
			default: None,
			primary_key: true,
			auto_increment: true,
		}
	}

	/// Helper to create a table with given columns
	fn table_with_cols(name: &str, cols: Vec<(&str, ColumnSchema)>) -> TableSchema {
		let mut columns = BTreeMap::new();
		for (col_name, col_schema) in cols {
			columns.insert(col_name.to_string(), col_schema);
		}
		TableSchema {
			name: name.to_string(),
			columns,
			indexes: Vec::new(),
			constraints: Vec::new(),
		}
	}

	#[test]
	fn test_generate_operations_create_table() {
		// Arrange
		let current = DatabaseSchema::default();
		let mut target = DatabaseSchema::default();
		target.tables.insert(
			"users".to_string(),
			table_with_cols(
				"users",
				vec![
					("id", pk_col("id")),
					("name", col("name", FieldType::VarChar(100), false)),
				],
			),
		);

		// Act
		let diff = SchemaDiff::new(current, target);
		let ops = diff.generate_operations();

		// Assert
		assert_eq!(ops.len(), 1);
		assert!(
			matches!(&ops[0], Operation::CreateTable { name, .. } if name == "users"),
			"Should generate CreateTable for 'users'"
		);
	}

	#[test]
	fn test_generate_operations_drop_table() {
		// Arrange
		let mut current = DatabaseSchema::default();
		current.tables.insert(
			"old_table".to_string(),
			table_with_cols("old_table", vec![("id", pk_col("id"))]),
		);
		let target = DatabaseSchema::default();

		// Act
		let diff = SchemaDiff::new(current, target);
		let ops = diff.generate_operations();

		// Assert
		assert_eq!(ops.len(), 1);
		assert!(
			matches!(&ops[0], Operation::DropTable { name } if name == "old_table"),
			"Should generate DropTable for 'old_table'"
		);
	}

	#[test]
	fn test_generate_operations_add_column() {
		// Arrange
		let mut current = DatabaseSchema::default();
		current.tables.insert(
			"users".to_string(),
			table_with_cols("users", vec![("id", pk_col("id"))]),
		);
		let mut target = DatabaseSchema::default();
		target.tables.insert(
			"users".to_string(),
			table_with_cols(
				"users",
				vec![
					("id", pk_col("id")),
					("email", col("email", FieldType::VarChar(255), false)),
				],
			),
		);

		// Act
		let diff = SchemaDiff::new(current, target);
		let ops = diff.generate_operations();

		// Assert
		assert_eq!(ops.len(), 1);
		assert!(
			matches!(&ops[0], Operation::AddColumn { table, column, .. }
				if table == "users" && column.name == "email"),
			"Should generate AddColumn for 'email' on 'users'"
		);
	}

	#[test]
	fn test_generate_operations_drop_column() {
		// Arrange
		let mut current = DatabaseSchema::default();
		current.tables.insert(
			"users".to_string(),
			table_with_cols(
				"users",
				vec![
					("id", pk_col("id")),
					("bio", col("bio", FieldType::Text, true)),
				],
			),
		);
		let mut target = DatabaseSchema::default();
		target.tables.insert(
			"users".to_string(),
			table_with_cols("users", vec![("id", pk_col("id"))]),
		);

		// Act
		let diff = SchemaDiff::new(current, target);
		let ops = diff.generate_operations();

		// Assert
		assert_eq!(ops.len(), 1);
		assert!(
			matches!(&ops[0], Operation::DropColumn { table, column }
				if table == "users" && column == "bio"),
			"Should generate DropColumn for 'bio' on 'users'"
		);
	}

	#[test]
	fn test_generate_operations_alter_column_type_change() {
		// Arrange: change 'price' from Integer to Float
		let mut current = DatabaseSchema::default();
		current.tables.insert(
			"items".to_string(),
			table_with_cols(
				"items",
				vec![
					("id", pk_col("id")),
					("price", col("price", FieldType::Integer, false)),
				],
			),
		);
		let mut target = DatabaseSchema::default();
		target.tables.insert(
			"items".to_string(),
			table_with_cols(
				"items",
				vec![
					("id", pk_col("id")),
					("price", col("price", FieldType::Float, false)),
				],
			),
		);

		// Act
		let diff = SchemaDiff::new(current, target);
		let ops = diff.generate_operations();

		// Assert
		assert_eq!(ops.len(), 1, "Should generate exactly one operation");
		match &ops[0] {
			Operation::AlterColumn {
				table,
				column,
				old_definition,
				new_definition,
				..
			} => {
				assert_eq!(table, "items");
				assert_eq!(column, "price");
				assert_eq!(
					old_definition.as_ref().unwrap().type_definition,
					FieldType::Integer,
					"Old definition should be Integer"
				);
				assert_eq!(
					new_definition.type_definition,
					FieldType::Float,
					"New definition should be Float"
				);
			}
			other => panic!("Expected AlterColumn, got {:?}", other),
		}
	}

	#[test]
	fn test_generate_operations_alter_column_nullability_change() {
		// Arrange: change 'email' from nullable to non-nullable
		let mut current = DatabaseSchema::default();
		current.tables.insert(
			"users".to_string(),
			table_with_cols(
				"users",
				vec![
					("id", pk_col("id")),
					("email", col("email", FieldType::VarChar(255), true)),
				],
			),
		);
		let mut target = DatabaseSchema::default();
		target.tables.insert(
			"users".to_string(),
			table_with_cols(
				"users",
				vec![
					("id", pk_col("id")),
					("email", col("email", FieldType::VarChar(255), false)),
				],
			),
		);

		// Act
		let diff = SchemaDiff::new(current, target);
		let ops = diff.generate_operations();

		// Assert
		assert_eq!(ops.len(), 1);
		match &ops[0] {
			Operation::AlterColumn {
				table,
				column,
				old_definition,
				new_definition,
				..
			} => {
				assert_eq!(table, "users");
				assert_eq!(column, "email");
				assert!(
					!old_definition.as_ref().unwrap().not_null,
					"Old should be nullable (not_null=false)"
				);
				assert!(
					new_definition.not_null,
					"New should be non-nullable (not_null=true)"
				);
			}
			other => panic!("Expected AlterColumn, got {:?}", other),
		}
	}

	#[test]
	fn test_generate_operations_add_index() {
		// Arrange
		let mut current = DatabaseSchema::default();
		current.tables.insert(
			"users".to_string(),
			table_with_cols(
				"users",
				vec![
					("id", pk_col("id")),
					("email", col("email", FieldType::VarChar(255), false)),
				],
			),
		);
		let mut target = DatabaseSchema::default();
		let mut target_table = table_with_cols(
			"users",
			vec![
				("id", pk_col("id")),
				("email", col("email", FieldType::VarChar(255), false)),
			],
		);
		target_table.indexes.push(IndexSchema {
			name: "idx_users_email".to_string(),
			columns: vec!["email".to_string()],
			unique: true,
		});
		target.tables.insert("users".to_string(), target_table);

		// Act
		let diff = SchemaDiff::new(current, target);
		let ops = diff.generate_operations();

		// Assert
		assert_eq!(ops.len(), 1, "Should generate exactly one operation");
		match &ops[0] {
			Operation::CreateIndex {
				table,
				columns,
				unique,
				..
			} => {
				assert_eq!(table, "users");
				assert_eq!(columns, &vec!["email".to_string()]);
				assert!(unique, "Should be a unique index");
			}
			other => panic!("Expected CreateIndex, got {:?}", other),
		}
	}

	#[test]
	fn test_generate_operations_drop_index() {
		// Arrange
		let mut current = DatabaseSchema::default();
		let mut current_table = table_with_cols(
			"users",
			vec![
				("id", pk_col("id")),
				("email", col("email", FieldType::VarChar(255), false)),
			],
		);
		current_table.indexes.push(IndexSchema {
			name: "idx_users_email".to_string(),
			columns: vec!["email".to_string()],
			unique: false,
		});
		current.tables.insert("users".to_string(), current_table);

		let mut target = DatabaseSchema::default();
		target.tables.insert(
			"users".to_string(),
			table_with_cols(
				"users",
				vec![
					("id", pk_col("id")),
					("email", col("email", FieldType::VarChar(255), false)),
				],
			),
		);

		// Act
		let diff = SchemaDiff::new(current, target);
		let ops = diff.generate_operations();

		// Assert
		assert_eq!(ops.len(), 1);
		match &ops[0] {
			Operation::DropIndex { table, columns } => {
				assert_eq!(table, "users");
				assert_eq!(columns, &vec!["email".to_string()]);
			}
			other => panic!("Expected DropIndex, got {:?}", other),
		}
	}

	#[test]
	fn test_generate_operations_no_changes_returns_empty() {
		// Arrange: identical schemas
		let mut schema = DatabaseSchema::default();
		schema.tables.insert(
			"users".to_string(),
			table_with_cols("users", vec![("id", pk_col("id"))]),
		);

		// Act
		let diff = SchemaDiff::new(schema.clone(), schema);
		let ops = diff.generate_operations();

		// Assert
		assert!(
			ops.is_empty(),
			"Identical schemas should produce no operations"
		);
	}

	#[test]
	fn test_has_destructive_changes_index_drop() {
		// Arrange: dropping an index is destructive
		let mut current = DatabaseSchema::default();
		let mut current_table = table_with_cols("users", vec![("id", pk_col("id"))]);
		current_table.indexes.push(IndexSchema {
			name: "idx_email".to_string(),
			columns: vec!["email".to_string()],
			unique: false,
		});
		current.tables.insert("users".to_string(), current_table);

		let mut target = DatabaseSchema::default();
		target.tables.insert(
			"users".to_string(),
			table_with_cols("users", vec![("id", pk_col("id"))]),
		);

		// Act & Assert
		let diff = SchemaDiff::new(current, target);
		assert!(
			diff.has_destructive_changes(),
			"Index removal should be flagged as destructive"
		);
	}

	#[test]
	fn test_has_destructive_changes_column_modify() {
		// Arrange: modifying a column type is destructive
		let mut current = DatabaseSchema::default();
		current.tables.insert(
			"items".to_string(),
			table_with_cols(
				"items",
				vec![
					("id", pk_col("id")),
					("price", col("price", FieldType::Integer, false)),
				],
			),
		);
		let mut target = DatabaseSchema::default();
		target.tables.insert(
			"items".to_string(),
			table_with_cols(
				"items",
				vec![
					("id", pk_col("id")),
					("price", col("price", FieldType::Float, false)),
				],
			),
		);

		// Act & Assert
		let diff = SchemaDiff::new(current, target);
		assert!(
			diff.has_destructive_changes(),
			"Column type modification should be flagged as destructive"
		);
	}

	#[test]
	fn test_generate_operations_new_table_with_indexes() {
		// Arrange: new table with an index should generate both CreateTable and CreateIndex
		let current = DatabaseSchema::default();
		let mut target = DatabaseSchema::default();
		let mut table = table_with_cols(
			"users",
			vec![
				("id", pk_col("id")),
				("email", col("email", FieldType::VarChar(255), false)),
			],
		);
		table.indexes.push(IndexSchema {
			name: "idx_users_email".to_string(),
			columns: vec!["email".to_string()],
			unique: true,
		});
		target.tables.insert("users".to_string(), table);

		// Act
		let diff = SchemaDiff::new(current, target);
		let ops = diff.generate_operations();

		// Assert: should have CreateTable + CreateIndex
		assert_eq!(ops.len(), 2, "Should generate 2 operations, got {:?}", ops);
		assert!(
			matches!(&ops[0], Operation::CreateTable { name, .. } if name == "users"),
			"First operation should be CreateTable"
		);
		assert!(
			matches!(&ops[1], Operation::CreateIndex { table, unique, .. }
				if table == "users" && *unique),
			"Second operation should be CreateIndex"
		);
	}

	// ================================================================
	// Constraint detection and generation tests (issue #3203)
	// ================================================================

	/// Helper to create a ConstraintSchema
	fn unique_constraint(name: &str, columns: &str) -> ConstraintSchema {
		ConstraintSchema {
			name: name.to_string(),
			constraint_type: "UNIQUE".to_string(),
			definition: columns.to_string(),
			foreign_key_info: None,
		}
	}

	fn check_constraint(name: &str, expression: &str) -> ConstraintSchema {
		ConstraintSchema {
			name: name.to_string(),
			constraint_type: "CHECK".to_string(),
			definition: expression.to_string(),
			foreign_key_info: None,
		}
	}

	fn fk_constraint(name: &str, col: &str, ref_table: &str, ref_col: &str) -> ConstraintSchema {
		ConstraintSchema {
			name: name.to_string(),
			constraint_type: "FOREIGN KEY".to_string(),
			definition: col.to_string(),
			foreign_key_info: Some(ForeignKeySchemaInfo {
				columns: vec![col.to_string()],
				referenced_table: ref_table.to_string(),
				referenced_columns: vec![ref_col.to_string()],
				on_delete: "CASCADE".to_string(),
				on_update: "NO ACTION".to_string(),
			}),
		}
	}

	#[test]
	fn test_detect_constraint_addition() {
		// Arrange
		let mut current = DatabaseSchema::default();
		current.tables.insert(
			"orders".to_string(),
			table_with_cols(
				"orders",
				vec![
					("id", pk_col("id")),
					("amount", col("amount", FieldType::Integer, false)),
				],
			),
		);

		let mut target = DatabaseSchema::default();
		let mut target_table = table_with_cols(
			"orders",
			vec![
				("id", pk_col("id")),
				("amount", col("amount", FieldType::Integer, false)),
			],
		);
		target_table
			.constraints
			.push(check_constraint("ck_amount_positive", "amount > 0"));
		target.tables.insert("orders".to_string(), target_table);

		// Act
		let diff = SchemaDiff::new(current, target);
		let result = diff.detect();

		// Assert
		assert_eq!(result.constraints_to_add.len(), 1);
		assert_eq!(result.constraints_to_add[0].0, "orders");
		assert_eq!(result.constraints_to_add[0].1.name, "ck_amount_positive");
		assert!(result.constraints_to_remove.is_empty());
	}

	#[test]
	fn test_detect_constraint_removal() {
		// Arrange
		let mut current = DatabaseSchema::default();
		let mut current_table = table_with_cols(
			"orders",
			vec![
				("id", pk_col("id")),
				("amount", col("amount", FieldType::Integer, false)),
			],
		);
		current_table
			.constraints
			.push(check_constraint("ck_amount_positive", "amount > 0"));
		current.tables.insert("orders".to_string(), current_table);

		let mut target = DatabaseSchema::default();
		target.tables.insert(
			"orders".to_string(),
			table_with_cols(
				"orders",
				vec![
					("id", pk_col("id")),
					("amount", col("amount", FieldType::Integer, false)),
				],
			),
		);

		// Act
		let diff = SchemaDiff::new(current, target);
		let result = diff.detect();

		// Assert
		assert!(result.constraints_to_add.is_empty());
		assert_eq!(result.constraints_to_remove.len(), 1);
		assert_eq!(result.constraints_to_remove[0].1.name, "ck_amount_positive");
	}

	#[test]
	fn test_detect_constraint_modification() {
		// Arrange: changing CHECK expression is detected as remove old + add new
		let mut current = DatabaseSchema::default();
		let mut current_table = table_with_cols(
			"orders",
			vec![
				("id", pk_col("id")),
				("amount", col("amount", FieldType::Integer, false)),
			],
		);
		current_table
			.constraints
			.push(check_constraint("ck_amount", "amount > 0"));
		current.tables.insert("orders".to_string(), current_table);

		let mut target = DatabaseSchema::default();
		let mut target_table = table_with_cols(
			"orders",
			vec![
				("id", pk_col("id")),
				("amount", col("amount", FieldType::Integer, false)),
			],
		);
		target_table
			.constraints
			.push(check_constraint("ck_amount", "amount >= 0"));
		target.tables.insert("orders".to_string(), target_table);

		// Act
		let diff = SchemaDiff::new(current, target);
		let result = diff.detect();

		// Assert: old constraint removed, new added (same name, different definition)
		assert_eq!(result.constraints_to_remove.len(), 1);
		assert_eq!(result.constraints_to_add.len(), 1);
		assert_eq!(result.constraints_to_remove[0].1.definition, "amount > 0");
		assert_eq!(result.constraints_to_add[0].1.definition, "amount >= 0");
	}

	#[test]
	fn test_generate_operations_add_constraint() {
		// Arrange
		let mut current = DatabaseSchema::default();
		current.tables.insert(
			"orders".to_string(),
			table_with_cols(
				"orders",
				vec![
					("id", pk_col("id")),
					("amount", col("amount", FieldType::Integer, false)),
				],
			),
		);

		let mut target = DatabaseSchema::default();
		let mut target_table = table_with_cols(
			"orders",
			vec![
				("id", pk_col("id")),
				("amount", col("amount", FieldType::Integer, false)),
			],
		);
		target_table
			.constraints
			.push(check_constraint("ck_amount_positive", "amount > 0"));
		target.tables.insert("orders".to_string(), target_table);

		// Act
		let diff = SchemaDiff::new(current, target);
		let ops = diff.generate_operations();

		// Assert
		assert_eq!(ops.len(), 1);
		match &ops[0] {
			Operation::AddConstraint {
				table,
				constraint_sql,
			} => {
				assert_eq!(table, "orders");
				assert!(
					constraint_sql.contains("ck_amount_positive"),
					"SQL should contain constraint name, got '{}'",
					constraint_sql
				);
				assert!(
					constraint_sql.contains("CHECK"),
					"SQL should contain CHECK keyword, got '{}'",
					constraint_sql
				);
				assert!(
					constraint_sql.contains("amount > 0"),
					"SQL should contain expression, got '{}'",
					constraint_sql
				);
			}
			other => panic!("Expected AddConstraint, got {:?}", other),
		}
	}

	#[test]
	fn test_generate_operations_drop_constraint() {
		// Arrange
		let mut current = DatabaseSchema::default();
		let mut current_table = table_with_cols(
			"orders",
			vec![
				("id", pk_col("id")),
				("amount", col("amount", FieldType::Integer, false)),
			],
		);
		current_table
			.constraints
			.push(unique_constraint("uq_orders_amount", "amount"));
		current.tables.insert("orders".to_string(), current_table);

		let mut target = DatabaseSchema::default();
		target.tables.insert(
			"orders".to_string(),
			table_with_cols(
				"orders",
				vec![
					("id", pk_col("id")),
					("amount", col("amount", FieldType::Integer, false)),
				],
			),
		);

		// Act
		let diff = SchemaDiff::new(current, target);
		let ops = diff.generate_operations();

		// Assert
		assert_eq!(ops.len(), 1);
		match &ops[0] {
			Operation::DropConstraint {
				table,
				constraint_name,
			} => {
				assert_eq!(table, "orders");
				assert_eq!(constraint_name, "uq_orders_amount");
			}
			other => panic!("Expected DropConstraint, got {:?}", other),
		}
	}

	#[test]
	fn test_generate_operations_add_unique_constraint() {
		// Arrange
		let mut current = DatabaseSchema::default();
		current.tables.insert(
			"users".to_string(),
			table_with_cols(
				"users",
				vec![
					("id", pk_col("id")),
					("email", col("email", FieldType::VarChar(255), false)),
				],
			),
		);

		let mut target = DatabaseSchema::default();
		let mut target_table = table_with_cols(
			"users",
			vec![
				("id", pk_col("id")),
				("email", col("email", FieldType::VarChar(255), false)),
			],
		);
		target_table
			.constraints
			.push(unique_constraint("uq_users_email", "email"));
		target.tables.insert("users".to_string(), target_table);

		// Act
		let diff = SchemaDiff::new(current, target);
		let ops = diff.generate_operations();

		// Assert
		assert_eq!(ops.len(), 1);
		match &ops[0] {
			Operation::AddConstraint {
				table,
				constraint_sql,
			} => {
				assert_eq!(table, "users");
				assert!(constraint_sql.contains("UNIQUE"));
				assert!(constraint_sql.contains("email"));
			}
			other => panic!("Expected AddConstraint, got {:?}", other),
		}
	}

	#[test]
	fn test_generate_operations_add_foreign_key_constraint() {
		// Arrange
		let mut current = DatabaseSchema::default();
		current.tables.insert(
			"orders".to_string(),
			table_with_cols(
				"orders",
				vec![
					("id", pk_col("id")),
					("user_id", col("user_id", FieldType::Integer, false)),
				],
			),
		);

		let mut target = DatabaseSchema::default();
		let mut target_table = table_with_cols(
			"orders",
			vec![
				("id", pk_col("id")),
				("user_id", col("user_id", FieldType::Integer, false)),
			],
		);
		target_table
			.constraints
			.push(fk_constraint("fk_orders_user", "user_id", "users", "id"));
		target.tables.insert("orders".to_string(), target_table);

		// Act
		let diff = SchemaDiff::new(current, target);
		let ops = diff.generate_operations();

		// Assert
		assert_eq!(ops.len(), 1);
		match &ops[0] {
			Operation::AddConstraint {
				table,
				constraint_sql,
			} => {
				assert_eq!(table, "orders");
				assert!(
					constraint_sql.contains("FOREIGN KEY"),
					"Should contain FOREIGN KEY, got '{}'",
					constraint_sql
				);
				assert!(constraint_sql.contains("REFERENCES users"));
				assert!(constraint_sql.contains("CASCADE"));
			}
			other => panic!("Expected AddConstraint, got {:?}", other),
		}
	}

	#[test]
	fn test_has_destructive_changes_constraint_drop() {
		// Arrange
		let mut current = DatabaseSchema::default();
		let mut current_table = table_with_cols("orders", vec![("id", pk_col("id"))]);
		current_table
			.constraints
			.push(check_constraint("ck_test", "id > 0"));
		current.tables.insert("orders".to_string(), current_table);

		let mut target = DatabaseSchema::default();
		target.tables.insert(
			"orders".to_string(),
			table_with_cols("orders", vec![("id", pk_col("id"))]),
		);

		// Act & Assert
		let diff = SchemaDiff::new(current, target);
		assert!(
			diff.has_destructive_changes(),
			"Constraint removal should be flagged as destructive"
		);
	}

	#[test]
	fn test_unchanged_constraints_produce_no_operations() {
		// Arrange: same constraint on both sides
		let constraint = check_constraint("ck_amount", "amount > 0");

		let mut current = DatabaseSchema::default();
		let mut current_table = table_with_cols("orders", vec![("id", pk_col("id"))]);
		current_table.constraints.push(constraint.clone());
		current.tables.insert("orders".to_string(), current_table);

		let mut target = DatabaseSchema::default();
		let mut target_table = table_with_cols("orders", vec![("id", pk_col("id"))]);
		target_table.constraints.push(constraint);
		target.tables.insert("orders".to_string(), target_table);

		// Act
		let diff = SchemaDiff::new(current, target);
		let result = diff.detect();
		let ops = diff.generate_operations();

		// Assert
		assert!(result.constraints_to_add.is_empty());
		assert!(result.constraints_to_remove.is_empty());
		assert!(ops.is_empty());
	}

	#[test]
	fn test_no_destructive_changes_for_additions_only() {
		// Arrange: only adding tables/columns/indexes is NOT destructive
		let current = DatabaseSchema::default();
		let mut target = DatabaseSchema::default();
		let mut table = table_with_cols("users", vec![("id", pk_col("id"))]);
		table.indexes.push(IndexSchema {
			name: "idx_id".to_string(),
			columns: vec!["id".to_string()],
			unique: false,
		});
		target.tables.insert("users".to_string(), table);

		// Act & Assert
		let diff = SchemaDiff::new(current, target);
		assert!(
			!diff.has_destructive_changes(),
			"Additions only should NOT be flagged as destructive"
		);
	}
}