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
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
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
//! Database schema introspection
//!
//! This module provides functionality to read the current database schema
//! and extract table definitions, column metadata, indexes, and constraints.

use async_trait::async_trait;
use std::collections::HashMap;

use super::{MigrationError, Result};

/// Schema information extracted from a database
#[derive(Debug, Clone, PartialEq)]
pub struct DatabaseSchema {
	/// All tables in the schema
	pub tables: HashMap<String, TableInfo>,
}

/// Table metadata
#[derive(Debug, Clone, PartialEq)]
pub struct TableInfo {
	/// Table name
	pub name: String,
	/// Columns in the table
	pub columns: HashMap<String, ColumnInfo>,
	/// Indexes on the table
	pub indexes: HashMap<String, IndexInfo>,
	/// Primary key columns
	pub primary_key: Vec<String>,
	/// Foreign key constraints
	pub foreign_keys: Vec<ForeignKeyInfo>,
	/// Unique constraints (excluding unique indexes)
	pub unique_constraints: Vec<UniqueConstraintInfo>,
	/// CHECK constraints
	pub check_constraints: Vec<CheckConstraintInfo>,
}

/// Column metadata
#[derive(Debug, Clone, PartialEq)]
pub struct ColumnInfo {
	/// Column name
	pub name: String,
	/// Column type
	pub column_type: super::FieldType,
	/// Whether the column is nullable
	pub nullable: bool,
	/// Default value expression
	pub default: Option<String>,
	/// Whether this is an auto-increment column
	pub auto_increment: bool,
}

/// Index metadata
#[derive(Debug, Clone, PartialEq)]
pub struct IndexInfo {
	/// Index name
	pub name: String,
	/// Columns in the index (in order)
	pub columns: Vec<String>,
	/// Whether the index is unique
	pub unique: bool,
	/// Index type (e.g., BTREE, HASH)
	pub index_type: Option<String>,
}

/// Foreign key constraint
#[derive(Debug, Clone, PartialEq)]
pub struct ForeignKeyInfo {
	/// Constraint name
	pub name: String,
	/// Columns in this table
	pub columns: Vec<String>,
	/// Referenced table
	pub referenced_table: String,
	/// Referenced columns
	pub referenced_columns: Vec<String>,
	/// ON DELETE action
	pub on_delete: Option<String>,
	/// ON UPDATE action
	pub on_update: Option<String>,
}

/// Unique constraint
#[derive(Debug, Clone, PartialEq)]
pub struct UniqueConstraintInfo {
	/// Constraint name
	pub name: String,
	/// Columns in the constraint
	pub columns: Vec<String>,
}

/// CHECK constraint
#[derive(Debug, Clone, PartialEq)]
pub struct CheckConstraintInfo {
	/// Constraint name (None for anonymous CHECK constraints)
	pub name: Option<String>,
	/// CHECK expression (without the CHECK keyword and outer parentheses)
	pub expression: String,
}

/// Trait for database-specific schema introspection
#[async_trait]
pub trait DatabaseIntrospector: Send + Sync {
	/// Read the complete database schema
	async fn read_schema(&self) -> Result<DatabaseSchema>;

	/// Read a specific table schema
	async fn read_table(&self, table_name: &str) -> Result<Option<TableInfo>>;
}

/// PostgreSQL schema introspector
#[cfg(feature = "postgres")]
pub struct PostgresIntrospector {
	pool: sqlx::PgPool,
}

#[cfg(feature = "postgres")]
impl PostgresIntrospector {
	/// Creates a new instance.
	pub fn new(pool: sqlx::PgPool) -> Self {
		Self { pool }
	}

	/// Maps PostgreSQL udt_name/data_type to FieldType
	fn parse_pg_type(
		udt_name: &str,
		data_type: &str,
		char_max_length: Option<i32>,
		numeric_precision: Option<i32>,
		numeric_scale: Option<i32>,
		enum_values: Option<Vec<String>>,
	) -> super::FieldType {
		use super::FieldType;
		match udt_name {
			// Integer types
			"int4" | "serial" => FieldType::Integer,
			"int8" | "bigserial" => FieldType::BigInteger,
			"int2" | "smallserial" => FieldType::SmallInteger,

			// String types
			"varchar" => FieldType::VarChar(char_max_length.unwrap_or(255) as u32),
			"bpchar" => FieldType::Char(char_max_length.unwrap_or(1) as u32),
			"text" => FieldType::Text,

			// Boolean
			"bool" => FieldType::Boolean,

			// Floating point
			"float4" => FieldType::Real,
			"float8" => FieldType::Double,

			// Numeric/Decimal
			"numeric" => FieldType::Decimal {
				precision: numeric_precision.unwrap_or(10) as u32,
				scale: numeric_scale.unwrap_or(2) as u32,
			},

			// Date/Time types
			"timestamp" => FieldType::DateTime,
			"timestamptz" => FieldType::TimestampTz,
			"date" => FieldType::Date,
			"time" | "timetz" => FieldType::Time,

			// Binary
			"bytea" => FieldType::Bytea,

			// JSON
			"json" => FieldType::Json,
			"jsonb" => FieldType::JsonBinary,

			// UUID
			"uuid" => FieldType::Uuid,

			// Text search
			"tsvector" => FieldType::TsVector,
			"tsquery" => FieldType::TsQuery,

			// Range types
			"int4range" => FieldType::Int4Range,
			"int8range" => FieldType::Int8Range,
			"numrange" => FieldType::NumRange,
			"tsrange" => FieldType::TsRange,
			"tstzrange" => FieldType::TsTzRange,
			"daterange" => FieldType::DateRange,

			// Array types (udt_name starts with _)
			name if name.starts_with('_') => {
				let inner = Self::parse_pg_type(
					&name[1..],
					data_type,
					char_max_length,
					numeric_precision,
					numeric_scale,
					None,
				);
				FieldType::Array(Box::new(inner))
			}

			// Geometric types
			"point" => FieldType::Custom("POINT".to_string()),
			"line" => FieldType::Custom("LINE".to_string()),
			"lseg" => FieldType::Custom("LSEG".to_string()),
			"box" => FieldType::Custom("BOX".to_string()),
			"path" => FieldType::Custom("PATH".to_string()),
			"polygon" => FieldType::Custom("POLYGON".to_string()),
			"circle" => FieldType::Custom("CIRCLE".to_string()),

			// Network address types
			"cidr" => FieldType::Custom("CIDR".to_string()),
			"inet" => FieldType::Custom("INET".to_string()),
			"macaddr" => FieldType::Custom("MACADDR".to_string()),
			"macaddr8" => FieldType::Custom("MACADDR8".to_string()),

			// Bit string types
			"bit" => FieldType::Custom("BIT".to_string()),
			"varbit" => FieldType::Custom("VARBIT".to_string()),

			// XML
			"xml" => FieldType::Custom("XML".to_string()),

			// Money
			"money" => FieldType::Custom("MONEY".to_string()),

			// Interval
			"interval" => FieldType::Custom("INTERVAL".to_string()),

			// PG_LSN
			"pg_lsn" => FieldType::Custom("PG_LSN".to_string()),

			// User-defined types (enums)
			_ if data_type == "USER-DEFINED" => {
				if let Some(values) = enum_values {
					FieldType::Enum { values }
				} else {
					FieldType::Custom(udt_name.to_string())
				}
			}

			// Fallback
			_ => FieldType::Custom(udt_name.to_string()),
		}
	}

	/// Fetches enum label values for a given PostgreSQL enum type name
	async fn fetch_enum_values(&self, type_name: &str) -> Result<Vec<String>> {
		use sqlx::Row;
		let query = r#"
			SELECT e.enumlabel
			FROM pg_enum e
			JOIN pg_type t ON e.enumtypid = t.oid
			JOIN pg_namespace n ON t.typnamespace = n.oid
			WHERE t.typname = $1 AND n.nspname = 'public'
			ORDER BY e.enumsortorder
		"#;
		let rows = sqlx::query(query)
			.bind(type_name)
			.fetch_all(&self.pool)
			.await
			.map_err(|e| {
				MigrationError::IntrospectionError(format!(
					"Failed to fetch enum values for {}: {}",
					type_name, e
				))
			})?;
		Ok(rows
			.iter()
			.map(|r| r.try_get::<String, _>("enumlabel").unwrap_or_default())
			.collect())
	}

	/// Introspects a single table using direct SQL queries against
	/// information_schema and pg_catalog
	async fn introspect_table(&self, table_name: &str) -> Result<TableInfo> {
		use sqlx::Row;

		// Fetch columns
		let col_query = r#"
			SELECT column_name, udt_name, data_type, is_nullable, column_default,
			       character_maximum_length, numeric_precision, numeric_scale,
			       is_identity, identity_generation
			FROM information_schema.columns
			WHERE table_schema = 'public' AND table_name = $1
			ORDER BY ordinal_position
		"#;
		let col_rows = sqlx::query(col_query)
			.bind(table_name)
			.fetch_all(&self.pool)
			.await
			.map_err(|e| {
				MigrationError::IntrospectionError(format!(
					"Failed to fetch columns for table {}: {}",
					table_name, e
				))
			})?;

		let mut columns = HashMap::new();
		for row in &col_rows {
			let column_name: String = row.try_get("column_name").map_err(|e| {
				MigrationError::IntrospectionError(format!("Failed to get column_name: {}", e))
			})?;
			let udt_name: String = row.try_get("udt_name").map_err(|e| {
				MigrationError::IntrospectionError(format!("Failed to get udt_name: {}", e))
			})?;
			let data_type: String = row.try_get("data_type").map_err(|e| {
				MigrationError::IntrospectionError(format!("Failed to get data_type: {}", e))
			})?;
			let is_nullable: String = row.try_get("is_nullable").map_err(|e| {
				MigrationError::IntrospectionError(format!("Failed to get is_nullable: {}", e))
			})?;
			let column_default: Option<String> = row.try_get("column_default").map_err(|e| {
				MigrationError::IntrospectionError(format!("Failed to get column_default: {}", e))
			})?;
			let char_max_length: Option<i32> =
				row.try_get("character_maximum_length").map_err(|e| {
					MigrationError::IntrospectionError(format!(
						"Failed to get character_maximum_length: {}",
						e
					))
				})?;
			let numeric_precision: Option<i32> = row.try_get("numeric_precision").map_err(|e| {
				MigrationError::IntrospectionError(format!(
					"Failed to get numeric_precision: {}",
					e
				))
			})?;
			let numeric_scale: Option<i32> = row.try_get("numeric_scale").map_err(|e| {
				MigrationError::IntrospectionError(format!("Failed to get numeric_scale: {}", e))
			})?;
			let is_identity: String = row.try_get("is_identity").map_err(|e| {
				MigrationError::IntrospectionError(format!("Failed to get is_identity: {}", e))
			})?;

			// Detect auto-increment: nextval() in default or identity column
			let is_auto = column_default
				.as_ref()
				.is_some_and(|d| d.starts_with("nextval("))
				|| is_identity == "YES";

			// Detect serial types (auto-increment integer)
			let is_serial = matches!(udt_name.as_str(), "int4" | "int8" | "int2")
				&& column_default
					.as_ref()
					.is_some_and(|d| d.starts_with("nextval("));

			// Fetch enum values for USER-DEFINED types
			let enum_values = if data_type == "USER-DEFINED" {
				let values = self.fetch_enum_values(&udt_name).await?;
				if values.is_empty() {
					None
				} else {
					Some(values)
				}
			} else {
				None
			};

			let field_type = Self::parse_pg_type(
				&udt_name,
				&data_type,
				char_max_length,
				numeric_precision,
				numeric_scale,
				enum_values,
			);

			columns.insert(
				column_name.clone(),
				ColumnInfo {
					name: column_name,
					column_type: field_type,
					nullable: is_nullable == "YES",
					default: column_default,
					auto_increment: is_auto || is_serial,
				},
			);
		}

		// Fetch primary key
		let pk_query = r#"
			SELECT kcu.column_name
			FROM information_schema.table_constraints tc
			JOIN information_schema.key_column_usage kcu
			    ON tc.constraint_name = kcu.constraint_name
			    AND tc.table_schema = kcu.table_schema
			WHERE tc.table_schema = 'public' AND tc.table_name = $1
			    AND tc.constraint_type = 'PRIMARY KEY'
			ORDER BY kcu.ordinal_position
		"#;
		let pk_rows = sqlx::query(pk_query)
			.bind(table_name)
			.fetch_all(&self.pool)
			.await
			.map_err(|e| {
				MigrationError::IntrospectionError(format!(
					"Failed to fetch primary key for table {}: {}",
					table_name, e
				))
			})?;
		let primary_key: Vec<String> = pk_rows
			.iter()
			.map(|r| r.try_get::<String, _>("column_name").unwrap_or_default())
			.collect();

		// Fetch foreign keys
		let fk_query = r#"
			SELECT tc.constraint_name, kcu.column_name,
			       ccu.table_name AS referenced_table, ccu.column_name AS referenced_column,
			       rc.update_rule, rc.delete_rule
			FROM information_schema.table_constraints tc
			JOIN information_schema.key_column_usage kcu
			    ON tc.constraint_name = kcu.constraint_name
			    AND tc.table_schema = kcu.table_schema
			JOIN information_schema.constraint_column_usage ccu
			    ON tc.constraint_name = ccu.constraint_name
			    AND tc.table_schema = ccu.table_schema
			JOIN information_schema.referential_constraints rc
			    ON tc.constraint_name = rc.constraint_name
			    AND tc.table_schema = rc.constraint_schema
			WHERE tc.table_schema = 'public' AND tc.table_name = $1
			    AND tc.constraint_type = 'FOREIGN KEY'
			ORDER BY tc.constraint_name, kcu.ordinal_position
		"#;
		let fk_rows = sqlx::query(fk_query)
			.bind(table_name)
			.fetch_all(&self.pool)
			.await
			.map_err(|e| {
				MigrationError::IntrospectionError(format!(
					"Failed to fetch foreign keys for table {}: {}",
					table_name, e
				))
			})?;

		// Group FK rows by constraint name
		let mut fk_map: HashMap<String, ForeignKeyInfo> = HashMap::new();
		for row in &fk_rows {
			let constraint_name: String = row.try_get("constraint_name").unwrap_or_default();
			let column_name: String = row.try_get("column_name").unwrap_or_default();
			let ref_table: String = row.try_get("referenced_table").unwrap_or_default();
			let ref_column: String = row.try_get("referenced_column").unwrap_or_default();
			let update_rule: String = row.try_get("update_rule").unwrap_or_default();
			let delete_rule: String = row.try_get("delete_rule").unwrap_or_default();

			let entry = fk_map
				.entry(constraint_name.clone())
				.or_insert_with(|| ForeignKeyInfo {
					name: constraint_name,
					columns: Vec::new(),
					referenced_table: ref_table,
					referenced_columns: Vec::new(),
					on_delete: if delete_rule == "NO ACTION" {
						None
					} else {
						Some(delete_rule)
					},
					on_update: if update_rule == "NO ACTION" {
						None
					} else {
						Some(update_rule)
					},
				});
			if !entry.columns.contains(&column_name) {
				entry.columns.push(column_name);
			}
			if !entry.referenced_columns.contains(&ref_column) {
				entry.referenced_columns.push(ref_column);
			}
		}

		let foreign_keys: Vec<ForeignKeyInfo> = fk_map.into_values().collect();

		// Fetch unique constraints
		let uq_query = r#"
			SELECT tc.constraint_name, kcu.column_name
			FROM information_schema.table_constraints tc
			JOIN information_schema.key_column_usage kcu
			    ON tc.constraint_name = kcu.constraint_name
			    AND tc.table_schema = kcu.table_schema
			WHERE tc.table_schema = 'public' AND tc.table_name = $1
			    AND tc.constraint_type = 'UNIQUE'
			ORDER BY tc.constraint_name, kcu.ordinal_position
		"#;
		let uq_rows = sqlx::query(uq_query)
			.bind(table_name)
			.fetch_all(&self.pool)
			.await
			.map_err(|e| {
				MigrationError::IntrospectionError(format!(
					"Failed to fetch unique constraints for table {}: {}",
					table_name, e
				))
			})?;

		let mut uq_map: HashMap<String, Vec<String>> = HashMap::new();
		for row in &uq_rows {
			let constraint_name: String = row.try_get("constraint_name").unwrap_or_default();
			let column_name: String = row.try_get("column_name").unwrap_or_default();
			uq_map.entry(constraint_name).or_default().push(column_name);
		}
		let unique_constraints: Vec<UniqueConstraintInfo> = uq_map
			.into_iter()
			.map(|(name, columns)| UniqueConstraintInfo { name, columns })
			.collect();

		// Fetch indexes (reuse existing method)
		let indexes = self.fetch_table_indexes(table_name).await?;

		// CHECK constraints not yet implemented
		let check_constraints: Vec<CheckConstraintInfo> = Vec::new();

		Ok(TableInfo {
			name: table_name.to_string(),
			columns,
			indexes,
			primary_key,
			foreign_keys,
			unique_constraints,
			check_constraints,
		})
	}

	/// Fetch index information for a specific table from PostgreSQL system catalogs
	async fn fetch_table_indexes(&self, table_name: &str) -> Result<HashMap<String, IndexInfo>> {
		use sqlx::Row;

		// Query PostgreSQL system catalogs to get index information
		// Excludes primary key indexes as they are handled separately
		let query = r#"
			SELECT
				i.relname AS index_name,
				array_agg(a.attname ORDER BY array_position(ix.indkey, a.attnum)) AS column_names,
				ix.indisunique AS is_unique,
				am.amname AS index_type
			FROM
				pg_class t,
				pg_class i,
				pg_index ix,
				pg_attribute a,
				pg_am am,
				pg_namespace n
			WHERE
				t.oid = ix.indrelid
				AND i.oid = ix.indexrelid
				AND a.attrelid = t.oid
				AND a.attnum = ANY(ix.indkey)
				AND t.relkind = 'r'
				AND t.relname = $1
				AND i.relam = am.oid
				AND NOT ix.indisprimary
				AND n.oid = t.relnamespace
				AND n.nspname = 'public'
			GROUP BY i.relname, ix.indisunique, am.amname
			ORDER BY i.relname
		"#;

		let rows = sqlx::query(query)
			.bind(table_name)
			.fetch_all(&self.pool)
			.await
			.map_err(|e| {
				MigrationError::IntrospectionError(format!(
					"Failed to fetch indexes for table {}: {}",
					table_name, e
				))
			})?;

		let mut indexes = HashMap::new();
		for row in rows {
			let index_name: String = row.try_get("index_name").map_err(|e| {
				MigrationError::IntrospectionError(format!("Failed to get index_name: {}", e))
			})?;
			let column_names: Vec<String> = row.try_get("column_names").map_err(|e| {
				MigrationError::IntrospectionError(format!("Failed to get column_names: {}", e))
			})?;
			let is_unique: bool = row.try_get("is_unique").map_err(|e| {
				MigrationError::IntrospectionError(format!("Failed to get is_unique: {}", e))
			})?;
			let index_type: String = row.try_get("index_type").map_err(|e| {
				MigrationError::IntrospectionError(format!("Failed to get index_type: {}", e))
			})?;

			indexes.insert(
				index_name.clone(),
				IndexInfo {
					name: index_name,
					columns: column_names,
					unique: is_unique,
					index_type: Some(index_type),
				},
			);
		}

		Ok(indexes)
	}
}

#[cfg(feature = "postgres")]
#[async_trait]
impl DatabaseIntrospector for PostgresIntrospector {
	async fn read_schema(&self) -> Result<DatabaseSchema> {
		use sqlx::Row;

		let table_query = r#"
			SELECT table_name FROM information_schema.tables
			WHERE table_schema = 'public' AND table_type = 'BASE TABLE'
		"#;
		let table_rows = sqlx::query(table_query)
			.fetch_all(&self.pool)
			.await
			.map_err(|e| {
				MigrationError::IntrospectionError(format!("Failed to fetch table list: {}", e))
			})?;

		let mut tables = HashMap::new();
		for row in &table_rows {
			let table_name: String = row.try_get("table_name").unwrap_or_default();
			let table_info = self.introspect_table(&table_name).await?;
			tables.insert(table_name, table_info);
		}

		Ok(DatabaseSchema { tables })
	}

	async fn read_table(&self, table_name: &str) -> Result<Option<TableInfo>> {
		// Check if table exists
		let exists_query = r#"
			SELECT table_name FROM information_schema.tables
			WHERE table_schema = 'public' AND table_type = 'BASE TABLE' AND table_name = $1
		"#;
		let exists = sqlx::query(exists_query)
			.bind(table_name)
			.fetch_optional(&self.pool)
			.await
			.map_err(|e| {
				MigrationError::IntrospectionError(format!(
					"Failed to check table existence: {}",
					e
				))
			})?;

		if exists.is_some() {
			Ok(Some(self.introspect_table(table_name).await?))
		} else {
			Ok(None)
		}
	}
}

/// MySQL schema introspector
#[cfg(feature = "mysql")]
pub struct MySQLIntrospector {
	pool: sqlx::MySqlPool,
}

#[cfg(feature = "mysql")]
impl MySQLIntrospector {
	/// Creates a new MySQL introspector with the given pool.
	pub fn new(pool: sqlx::MySqlPool) -> Self {
		Self { pool }
	}

	fn parse_mysql_type(
		data_type: &str,
		column_type: &str,
		char_max_length: Option<i64>,
		numeric_precision: Option<i64>,
		numeric_scale: Option<i64>,
	) -> super::FieldType {
		use super::FieldType;
		let data_type_lower = data_type.to_lowercase();
		match data_type_lower.as_str() {
			"tinyint" => {
				// MySQL uses tinyint(1) for boolean
				if column_type.to_lowercase().starts_with("tinyint(1)") {
					FieldType::Boolean
				} else {
					FieldType::TinyInt
				}
			}
			"smallint" => FieldType::SmallInteger,
			"mediumint" => FieldType::MediumInt,
			"int" | "integer" => FieldType::Integer,
			"bigint" => FieldType::BigInteger,

			"varchar" => FieldType::VarChar(char_max_length.unwrap_or(255) as u32),
			"char" => FieldType::Char(char_max_length.unwrap_or(1) as u32),
			"text" => FieldType::Text,
			"tinytext" => FieldType::TinyText,
			"mediumtext" => FieldType::MediumText,
			"longtext" => FieldType::LongText,

			"decimal" | "numeric" => FieldType::Decimal {
				precision: numeric_precision.unwrap_or(10) as u32,
				scale: numeric_scale.unwrap_or(2) as u32,
			},
			"float" => FieldType::Float,
			"double" => FieldType::Double,

			"date" => FieldType::Date,
			"time" => FieldType::Time,
			"datetime" => FieldType::DateTime,
			"timestamp" => FieldType::DateTime,
			"year" => FieldType::Year,

			"binary" | "varbinary" => FieldType::Binary,
			"blob" => FieldType::Blob,
			"tinyblob" => FieldType::TinyBlob,
			"mediumblob" => FieldType::MediumBlob,
			"longblob" => FieldType::LongBlob,

			"json" => FieldType::Json,
			"bit" => FieldType::Boolean,

			"enum" => {
				// Parse enum values from column_type: enum('a','b','c')
				let values = Self::parse_enum_or_set_values(column_type);
				FieldType::Enum { values }
			}
			"set" => {
				// Parse set values from column_type: set('a','b','c')
				let values = Self::parse_enum_or_set_values(column_type);
				FieldType::Set { values }
			}

			_ => FieldType::Custom(data_type.to_string()),
		}
	}

	/// Parse enum or set values from MySQL column_type string.
	/// Input format: "enum('val1','val2','val3')" or "set('val1','val2')"
	fn parse_enum_or_set_values(column_type: &str) -> Vec<String> {
		// Find the opening parenthesis
		if let Some(start) = column_type.find('(')
			&& let Some(end) = column_type.rfind(')')
		{
			let inner = &column_type[start + 1..end];
			return inner
				.split(',')
				.map(|s| s.trim().trim_matches('\'').to_string())
				.collect();
		}
		Vec::new()
	}

	/// Introspects a single table using direct SQL queries against information_schema
	async fn introspect_table(&self, table_name: &str) -> Result<TableInfo> {
		use sqlx::Row;

		// Fetch columns from information_schema
		let col_query = r#"
			SELECT column_name, data_type, column_type, is_nullable, column_default,
			       column_key, extra, character_maximum_length, numeric_precision, numeric_scale
			FROM information_schema.columns
			WHERE table_schema = DATABASE() AND table_name = ?
			ORDER BY ordinal_position
		"#;
		let col_rows = sqlx::query(col_query)
			.bind(table_name)
			.fetch_all(&self.pool)
			.await
			.map_err(|e| {
				MigrationError::IntrospectionError(format!(
					"Failed to fetch columns for table {}: {}",
					table_name, e
				))
			})?;

		let mut columns = HashMap::new();
		let mut primary_key = Vec::new();

		for row in &col_rows {
			let column_name: String = row.try_get("column_name").map_err(|e| {
				MigrationError::IntrospectionError(format!("Failed to get column_name: {}", e))
			})?;
			let data_type: String = row.try_get("data_type").map_err(|e| {
				MigrationError::IntrospectionError(format!("Failed to get data_type: {}", e))
			})?;
			let column_type_str: String = row.try_get("column_type").map_err(|e| {
				MigrationError::IntrospectionError(format!("Failed to get column_type: {}", e))
			})?;
			let is_nullable: String = row.try_get("is_nullable").map_err(|e| {
				MigrationError::IntrospectionError(format!("Failed to get is_nullable: {}", e))
			})?;
			let column_default: Option<String> = row.try_get("column_default").map_err(|e| {
				MigrationError::IntrospectionError(format!("Failed to get column_default: {}", e))
			})?;
			let column_key: String = row.try_get("column_key").map_err(|e| {
				MigrationError::IntrospectionError(format!("Failed to get column_key: {}", e))
			})?;
			let extra: String = row.try_get("extra").map_err(|e| {
				MigrationError::IntrospectionError(format!("Failed to get extra: {}", e))
			})?;
			let char_max_length: Option<i64> =
				row.try_get("character_maximum_length").map_err(|e| {
					MigrationError::IntrospectionError(format!(
						"Failed to get character_maximum_length: {}",
						e
					))
				})?;
			let numeric_precision: Option<i64> = row.try_get("numeric_precision").map_err(|e| {
				MigrationError::IntrospectionError(format!(
					"Failed to get numeric_precision: {}",
					e
				))
			})?;
			let numeric_scale: Option<i64> = row.try_get("numeric_scale").map_err(|e| {
				MigrationError::IntrospectionError(format!("Failed to get numeric_scale: {}", e))
			})?;

			// Primary key detection
			if column_key == "PRI" {
				primary_key.push(column_name.clone());
			}

			// Auto-increment detection
			let is_auto = extra.to_lowercase().contains("auto_increment");

			let field_type = Self::parse_mysql_type(
				&data_type,
				&column_type_str,
				char_max_length,
				numeric_precision,
				numeric_scale,
			);

			columns.insert(
				column_name.clone(),
				ColumnInfo {
					name: column_name,
					column_type: field_type,
					nullable: is_nullable == "YES",
					default: column_default,
					auto_increment: is_auto,
				},
			);
		}

		// Fetch indexes from information_schema.statistics
		let idx_query = r#"
			SELECT index_name, column_name, non_unique, index_type
			FROM information_schema.statistics
			WHERE table_schema = DATABASE() AND table_name = ?
			ORDER BY index_name, seq_in_index
		"#;
		let idx_rows = sqlx::query(idx_query)
			.bind(table_name)
			.fetch_all(&self.pool)
			.await
			.map_err(|e| {
				MigrationError::IntrospectionError(format!(
					"Failed to fetch indexes for table {}: {}",
					table_name, e
				))
			})?;

		let mut idx_map: HashMap<String, (Vec<String>, bool, String)> = HashMap::new();
		for row in &idx_rows {
			let index_name: String = row.try_get("index_name").unwrap_or_default();
			let column_name: String = row.try_get("column_name").unwrap_or_default();
			let non_unique: i64 = row.try_get("non_unique").unwrap_or(1);
			let index_type: String = row.try_get("index_type").unwrap_or_default();

			let entry = idx_map
				.entry(index_name)
				.or_insert_with(|| (Vec::new(), non_unique == 0, index_type.clone()));
			entry.0.push(column_name);
		}

		let mut indexes = HashMap::new();
		let mut unique_constraints = Vec::new();
		for (name, (cols, is_unique, idx_type)) in &idx_map {
			// Skip PRIMARY key index - already handled
			if name == "PRIMARY" {
				continue;
			}

			indexes.insert(
				name.clone(),
				IndexInfo {
					name: name.clone(),
					columns: cols.clone(),
					unique: *is_unique,
					index_type: Some(idx_type.clone()),
				},
			);

			if *is_unique {
				unique_constraints.push(UniqueConstraintInfo {
					name: name.clone(),
					columns: cols.clone(),
				});
			}
		}

		// Fetch foreign keys
		let fk_query = r#"
			SELECT rc.constraint_name, kcu.column_name,
			       kcu.referenced_table_name, kcu.referenced_column_name,
			       rc.update_rule, rc.delete_rule
			FROM information_schema.referential_constraints rc
			JOIN information_schema.key_column_usage kcu
			    ON rc.constraint_name = kcu.constraint_name
			    AND rc.constraint_schema = kcu.constraint_schema
			WHERE rc.constraint_schema = DATABASE() AND kcu.table_name = ?
			    AND kcu.referenced_table_name IS NOT NULL
			ORDER BY rc.constraint_name, kcu.ordinal_position
		"#;
		let fk_rows = sqlx::query(fk_query)
			.bind(table_name)
			.fetch_all(&self.pool)
			.await
			.map_err(|e| {
				MigrationError::IntrospectionError(format!(
					"Failed to fetch foreign keys for table {}: {}",
					table_name, e
				))
			})?;

		let mut fk_map: HashMap<String, ForeignKeyInfo> = HashMap::new();
		for row in &fk_rows {
			let constraint_name: String = row.try_get("constraint_name").unwrap_or_default();
			let column_name: String = row.try_get("column_name").unwrap_or_default();
			let ref_table: String = row.try_get("referenced_table_name").unwrap_or_default();
			let ref_column: String = row.try_get("referenced_column_name").unwrap_or_default();
			let update_rule: String = row.try_get("update_rule").unwrap_or_default();
			let delete_rule: String = row.try_get("delete_rule").unwrap_or_default();

			let entry = fk_map
				.entry(constraint_name.clone())
				.or_insert_with(|| ForeignKeyInfo {
					name: constraint_name,
					columns: Vec::new(),
					referenced_table: ref_table,
					referenced_columns: Vec::new(),
					on_delete: Some(delete_rule),
					on_update: Some(update_rule),
				});
			if !entry.columns.contains(&column_name) {
				entry.columns.push(column_name);
			}
			if !entry.referenced_columns.contains(&ref_column) {
				entry.referenced_columns.push(ref_column);
			}
		}

		let foreign_keys: Vec<ForeignKeyInfo> = fk_map.into_values().collect();

		// MySQL CHECK constraints not yet implemented
		let check_constraints: Vec<CheckConstraintInfo> = Vec::new();

		Ok(TableInfo {
			name: table_name.to_string(),
			columns,
			indexes,
			primary_key,
			foreign_keys,
			unique_constraints,
			check_constraints,
		})
	}
}

#[cfg(feature = "mysql")]
#[async_trait]
impl DatabaseIntrospector for MySQLIntrospector {
	async fn read_schema(&self) -> Result<DatabaseSchema> {
		use sqlx::Row;

		let table_query = r#"
			SELECT table_name FROM information_schema.tables
			WHERE table_schema = DATABASE() AND table_type = 'BASE TABLE'
		"#;
		let table_rows = sqlx::query(table_query)
			.fetch_all(&self.pool)
			.await
			.map_err(|e| {
				MigrationError::IntrospectionError(format!("Failed to fetch table list: {}", e))
			})?;

		let mut tables = HashMap::new();
		for row in &table_rows {
			let table_name: String = row.try_get("table_name").unwrap_or_default();
			let table_info = self.introspect_table(&table_name).await?;
			tables.insert(table_name, table_info);
		}

		Ok(DatabaseSchema { tables })
	}

	async fn read_table(&self, table_name: &str) -> Result<Option<TableInfo>> {
		let exists_query = r#"
			SELECT table_name FROM information_schema.tables
			WHERE table_schema = DATABASE() AND table_type = 'BASE TABLE' AND table_name = ?
		"#;
		let exists = sqlx::query(exists_query)
			.bind(table_name)
			.fetch_optional(&self.pool)
			.await
			.map_err(|e| {
				MigrationError::IntrospectionError(format!(
					"Failed to check table existence: {}",
					e
				))
			})?;

		if exists.is_some() {
			Ok(Some(self.introspect_table(table_name).await?))
		} else {
			Ok(None)
		}
	}
}

/// SQLite schema introspector
#[cfg(feature = "sqlite")]
pub struct SQLiteIntrospector {
	pool: sqlx::SqlitePool,
}

#[cfg(feature = "sqlite")]
impl SQLiteIntrospector {
	/// Creates a new SQLite introspector with the given pool.
	pub fn new(pool: sqlx::SqlitePool) -> Self {
		Self { pool }
	}

	pub(crate) fn parse_sqlite_type(type_str: &str) -> super::FieldType {
		use super::FieldType;
		let upper = type_str.to_uppercase();
		let upper = upper.trim();
		match upper {
			"INTEGER" | "INT" => FieldType::Integer,
			"BIGINT" => FieldType::BigInteger,
			"SMALLINT" => FieldType::SmallInteger,
			"TINYINT" => FieldType::TinyInt,
			"TEXT" => FieldType::Text,
			"REAL" => FieldType::Real,
			"FLOAT" => FieldType::Float,
			"DOUBLE" | "DOUBLE PRECISION" => FieldType::Double,
			"BLOB" => FieldType::Blob,
			"BOOLEAN" => FieldType::Boolean,
			"DATE" => FieldType::Date,
			"TIME" => FieldType::Time,
			"DATETIME" => FieldType::DateTime,
			"TIMESTAMP" => FieldType::DateTime,
			"JSON" => FieldType::Json,
			"JSONB" => FieldType::JsonBinary,
			"UUID" => FieldType::Uuid,
			"NUMERIC" => FieldType::Decimal {
				precision: 10,
				scale: 2,
			},
			_ => {
				// Handle parameterized types: VARCHAR(n), CHAR(n), DECIMAL(p,s), etc.
				if let Some(rest) = upper.strip_prefix("VARCHAR(") {
					if let Some(len_str) = rest.strip_suffix(')')
						&& let Ok(len) = len_str.trim().parse::<u32>()
					{
						return FieldType::VarChar(len);
					}
					return FieldType::VarChar(255);
				}
				if let Some(rest) = upper.strip_prefix("CHAR(") {
					if let Some(len_str) = rest.strip_suffix(')')
						&& let Ok(len) = len_str.trim().parse::<u32>()
					{
						return FieldType::Char(len);
					}
					return FieldType::Char(1);
				}
				if let Some(rest) = upper.strip_prefix("DECIMAL(") {
					if let Some(params_str) = rest.strip_suffix(')') {
						let parts: Vec<&str> = params_str.split(',').collect();
						if parts.len() == 2
							&& let (Ok(p), Ok(s)) = (
								parts[0].trim().parse::<u32>(),
								parts[1].trim().parse::<u32>(),
							) {
							return FieldType::Decimal {
								precision: p,
								scale: s,
							};
						}
					}
					return FieldType::Decimal {
						precision: 10,
						scale: 2,
					};
				}
				if let Some(rest) = upper.strip_prefix("NUMERIC(") {
					if let Some(params_str) = rest.strip_suffix(')') {
						let parts: Vec<&str> = params_str.split(',').collect();
						if parts.len() == 2
							&& let (Ok(p), Ok(s)) = (
								parts[0].trim().parse::<u32>(),
								parts[1].trim().parse::<u32>(),
							) {
							return FieldType::Decimal {
								precision: p,
								scale: s,
							};
						}
					}
					return FieldType::Decimal {
						precision: 10,
						scale: 2,
					};
				}
				// Default fallback for unknown types
				FieldType::Custom(type_str.to_string())
			}
		}
	}

	/// Extracts foreign key information from SQLite using PRAGMA foreign_key_list.
	///
	/// SQLite's PRAGMA foreign_key_list returns:
	/// - id: FK constraint ID (for multi-column FKs, same ID for all columns)
	/// - seq: Column sequence in the FK
	/// - table: Referenced table name
	/// - from: Source column name
	/// - to: Referenced column name
	/// - on_update: ON UPDATE action
	/// - on_delete: ON DELETE action
	/// - match: MATCH clause (usually 'NONE')
	///
	/// This method also extracts actual constraint names from CREATE TABLE SQL
	/// when available (for named FK constraints like `CONSTRAINT fk_name FOREIGN KEY...`).
	async fn extract_foreign_keys(
		pool: &sqlx::SqlitePool,
		table_name: &str,
	) -> Result<Vec<ForeignKeyInfo>> {
		#[derive(sqlx::FromRow)]
		struct ForeignKeyRow {
			id: i64,
			seq: i64,
			table: String,
			from: String,
			to: String,
			on_update: String,
			on_delete: String,
			// Allow dead_code: field required for SQLite PRAGMA row deserialization
			#[allow(dead_code)]
			r#match: String,
		}

		// Get CREATE TABLE SQL to extract actual constraint names
		let create_sql = Self::get_create_table_sql(pool, table_name).await?;
		let named_fks = create_sql
			.as_ref()
			.map(|sql| Self::parse_fk_constraint_names(sql))
			.unwrap_or_default();

		// SQLite PRAGMA arguments cannot be passed via parameter binding, so
		// the identifier is interpolated through `quote_pragma_identifier`
		// (single-quoted, embedded quotes doubled). The `table_name` here
		// always originates from an internal `Operation` enum payload — never
		// from user-supplied input — so this is not a SQL-injection sink.
		// See issue #4454 for context.
		// nosemgrep: rust.actix.sql.sqlx-taint.sqlx-taint
		let query = format!(
			"PRAGMA foreign_key_list({})",
			super::sqlite_pragma::quote_pragma_identifier(table_name)
		);
		let rows: Vec<ForeignKeyRow> = sqlx::query_as(&query)
			.fetch_all(pool)
			.await
			.map_err(|e| MigrationError::IntrospectionError(e.to_string()))?;

		// Group by FK ID to handle multi-column foreign keys
		let mut fk_map: HashMap<i64, Vec<ForeignKeyRow>> = HashMap::new();
		for row in rows {
			fk_map.entry(row.id).or_default().push(row);
		}

		// Convert to ForeignKeyInfo
		let mut foreign_keys = Vec::new();
		for (fk_id, mut fk_rows) in fk_map {
			// Sort by sequence to maintain column order
			fk_rows.sort_by_key(|r| r.seq);

			let referenced_table = fk_rows[0].table.clone();
			let on_update = fk_rows[0].on_update.clone();
			let on_delete = fk_rows[0].on_delete.clone();

			let columns: Vec<String> = fk_rows.iter().map(|r| r.from.clone()).collect();
			let referenced_columns: Vec<String> = fk_rows.iter().map(|r| r.to.clone()).collect();

			// Try to find actual constraint name from CREATE TABLE SQL
			// If not found, fall back to generated name
			let signature = (columns.clone(), referenced_table.clone());
			let name = named_fks
				.get(&signature)
				.cloned()
				.unwrap_or_else(|| format!("fk_{}_{}", table_name, fk_id));

			foreign_keys.push(ForeignKeyInfo {
				name,
				columns,
				referenced_table,
				referenced_columns,
				on_delete: if on_delete == "NO ACTION" {
					None
				} else {
					Some(on_delete)
				},
				on_update: if on_update == "NO ACTION" {
					None
				} else {
					Some(on_update)
				},
			});
		}

		Ok(foreign_keys)
	}

	/// Extracts index information from SQLite using PRAGMA index_list and PRAGMA index_info.
	async fn extract_indexes(
		pool: &sqlx::SqlitePool,
		table_name: &str,
	) -> Result<HashMap<String, IndexInfo>> {
		#[derive(sqlx::FromRow)]
		struct IndexListRow {
			// Allow dead_code: field required for SQLite PRAGMA row deserialization
			#[allow(dead_code)]
			seq: i64,
			name: String,
			unique: i64,
			// Allow dead_code: field required for SQLite PRAGMA row deserialization
			#[allow(dead_code)]
			origin: String,
			// Allow dead_code: field required for SQLite PRAGMA row deserialization
			#[allow(dead_code)]
			partial: i64,
		}

		#[derive(sqlx::FromRow)]
		struct IndexInfoRow {
			// Allow dead_code: field required for SQLite PRAGMA row deserialization
			#[allow(dead_code)]
			seqno: i64,
			// Allow dead_code: field required for SQLite PRAGMA row deserialization
			#[allow(dead_code)]
			cid: i64,
			name: Option<String>,
		}

		let mut indexes = HashMap::new();

		// Get list of indexes for the table
		// SQLite PRAGMA: identifier interpolation via shared helper. Inputs
		// originate from internal migration operations; see issue #4454.
		// nosemgrep: rust.actix.sql.sqlx-taint.sqlx-taint
		let query = format!(
			"PRAGMA index_list({})",
			super::sqlite_pragma::quote_pragma_identifier(table_name)
		);
		let index_list: Vec<IndexListRow> = sqlx::query_as(&query)
			.fetch_all(pool)
			.await
			.map_err(|e| MigrationError::IntrospectionError(e.to_string()))?;

		for index_row in index_list {
			// Get columns for this index.
			// nosemgrep: rust.actix.sql.sqlx-taint.sqlx-taint
			let info_query = format!(
				"PRAGMA index_info({})",
				super::sqlite_pragma::quote_pragma_identifier(&index_row.name)
			);
			let index_info: Vec<IndexInfoRow> =
				sqlx::query_as(&info_query)
					.fetch_all(pool)
					.await
					.map_err(|e| MigrationError::IntrospectionError(e.to_string()))?;

			let columns: Vec<String> = index_info
				.into_iter()
				.filter_map(|info| info.name)
				.collect();

			indexes.insert(
				index_row.name.clone(),
				IndexInfo {
					name: index_row.name,
					columns,
					unique: index_row.unique != 0,
					index_type: None,
				},
			);
		}

		Ok(indexes)
	}

	/// Gets the CREATE TABLE SQL statement from sqlite_master.
	async fn get_create_table_sql(
		pool: &sqlx::SqlitePool,
		table_name: &str,
	) -> Result<Option<String>> {
		#[derive(sqlx::FromRow)]
		struct SqlRow {
			sql: Option<String>,
		}

		let query = "SELECT sql FROM sqlite_master WHERE type='table' AND name=?";
		let result: Option<SqlRow> = sqlx::query_as(query)
			.bind(table_name)
			.fetch_optional(pool)
			.await
			.map_err(|e| MigrationError::IntrospectionError(e.to_string()))?;

		Ok(result.and_then(|r| r.sql))
	}

	/// Extracts CHECK constraints from the CREATE TABLE SQL statement.
	///
	/// SQLite doesn't have a PRAGMA for CHECK constraints, so we parse them
	/// from the CREATE TABLE statement stored in sqlite_master.
	///
	/// Handles both:
	/// - Named CHECK: `CONSTRAINT check_name CHECK(expression)`
	/// - Anonymous CHECK: `CHECK(expression)`
	async fn extract_check_constraints(
		pool: &sqlx::SqlitePool,
		table_name: &str,
	) -> Result<Vec<CheckConstraintInfo>> {
		let create_sql = match Self::get_create_table_sql(pool, table_name).await? {
			Some(sql) => sql,
			None => return Ok(Vec::new()),
		};

		Self::parse_check_constraints(&create_sql)
	}

	/// Parses CHECK constraints from a CREATE TABLE SQL statement.
	pub(crate) fn parse_check_constraints(create_sql: &str) -> Result<Vec<CheckConstraintInfo>> {
		let mut constraints = Vec::new();

		// Named CHECK constraint pattern: CONSTRAINT name CHECK(...)
		// We need to handle nested parentheses in the expression
		let named_pattern = regex::Regex::new(r#"(?i)CONSTRAINT\s+["'`]?(\w+)["'`]?\s+CHECK\s*\("#)
			.map_err(|e| MigrationError::IntrospectionError(e.to_string()))?;

		// Anonymous CHECK pattern: CHECK(...) not preceded by CONSTRAINT
		let anon_pattern = regex::Regex::new(r#"(?i)CHECK\s*\("#)
			.map_err(|e| MigrationError::IntrospectionError(e.to_string()))?;

		// Pattern to check for CONSTRAINT name before CHECK
		let constraint_pattern =
			regex::Regex::new(r#"(?i)CONSTRAINT\s+["'`]?\w+["'`]?\s*$"#).unwrap();

		// Find named CHECK constraints
		for cap in named_pattern.captures_iter(create_sql) {
			let name = cap.get(1).map(|m| m.as_str().to_string());
			let match_end = cap.get(0).unwrap().end();

			// Extract expression by counting parentheses
			if let Some(expr) = Self::extract_parenthesized_expression(create_sql, match_end - 1) {
				constraints.push(CheckConstraintInfo {
					name,
					expression: expr,
				});
			}
		}

		// Find anonymous CHECK constraints
		// We need to exclude the named ones we already found
		for m in anon_pattern.find_iter(create_sql) {
			let start = m.start();

			// Check if this is preceded by CONSTRAINT (skip if so)
			let before = &create_sql[..start];
			if before.to_uppercase().trim_end().ends_with("CONSTRAINT") {
				continue;
			}

			// Also check for CONSTRAINT name pattern before CHECK
			if constraint_pattern.is_match(before.trim_end()) {
				continue;
			}

			let match_end = m.end();
			if let Some(expr) = Self::extract_parenthesized_expression(create_sql, match_end - 1) {
				constraints.push(CheckConstraintInfo {
					name: None,
					expression: expr,
				});
			}
		}

		Ok(constraints)
	}

	/// Extracts the content inside parentheses, handling nested parentheses.
	/// `start_pos` should be the position of the opening parenthesis.
	fn extract_parenthesized_expression(sql: &str, start_pos: usize) -> Option<String> {
		let chars: Vec<char> = sql.chars().collect();
		if start_pos >= chars.len() || chars[start_pos] != '(' {
			return None;
		}

		let mut depth = 0;
		let expr_start = start_pos + 1;
		let mut expr_end = start_pos + 1;

		for (i, &c) in chars.iter().enumerate().skip(start_pos) {
			match c {
				'(' => depth += 1,
				')' => {
					depth -= 1;
					if depth == 0 {
						expr_end = i;
						break;
					}
				}
				_ => {}
			}
		}

		if depth == 0 && expr_end > expr_start {
			let expr: String = chars[expr_start..expr_end].iter().collect();
			Some(expr.trim().to_string())
		} else {
			None
		}
	}

	/// Parses FK constraint names from a CREATE TABLE SQL statement.
	///
	/// Returns a HashMap where:
	/// - Key: (source_columns, referenced_table) as a signature
	/// - Value: constraint name
	///
	/// This is used to match PRAGMA foreign_key_list results with actual constraint names.
	pub(crate) fn parse_fk_constraint_names(
		create_sql: &str,
	) -> HashMap<(Vec<String>, String), String> {
		let mut result = HashMap::new();

		// Pattern: CONSTRAINT name FOREIGN KEY (cols) REFERENCES table(cols)
		let fk_pattern = regex::Regex::new(
			r#"(?i)CONSTRAINT\s+["'`]?(\w+)["'`]?\s+FOREIGN\s+KEY\s*\(([^)]+)\)\s*REFERENCES\s+["'`]?(\w+)["'`]?"#,
		);

		if let Ok(re) = fk_pattern {
			for cap in re.captures_iter(create_sql) {
				if let (Some(name), Some(cols), Some(ref_table)) =
					(cap.get(1), cap.get(2), cap.get(3))
				{
					let constraint_name = name.as_str().to_string();
					let columns: Vec<String> = cols
						.as_str()
						.split(',')
						.map(|s| s.trim().trim_matches('"').trim_matches('\'').to_string())
						.collect();
					let referenced_table = ref_table.as_str().to_string();

					result.insert((columns, referenced_table), constraint_name);
				}
			}
		}

		result
	}

	/// Extracts unique constraints from PRAGMA index_list where origin = 'u'.
	async fn extract_unique_constraints(
		&self,
		table_name: &str,
	) -> Result<Vec<UniqueConstraintInfo>> {
		#[derive(sqlx::FromRow)]
		struct IndexListRow {
			// Allow dead_code: field required for SQLite PRAGMA row deserialization
			#[allow(dead_code)]
			// Column sequence number from PRAGMA index_list
			seq: i64,
			name: String,
			// Allow dead_code: field required for SQLite PRAGMA row deserialization
			#[allow(dead_code)]
			// Whether the index enforces uniqueness
			unique: i64,
			origin: String,
			// Allow dead_code: field required for SQLite PRAGMA row deserialization
			#[allow(dead_code)]
			// Whether this is a partial index
			partial: i64,
		}

		#[derive(sqlx::FromRow)]
		struct IndexInfoRow {
			// Allow dead_code: field required for SQLite PRAGMA row deserialization
			#[allow(dead_code)]
			// Column sequence number within the index
			seqno: i64,
			// Allow dead_code: field required for SQLite PRAGMA row deserialization
			#[allow(dead_code)]
			// Column ID in the table
			cid: i64,
			name: Option<String>,
		}

		// SQLite PRAGMA: identifier interpolation via shared helper. Inputs
		// originate from internal migration operations; see issue #4454.
		// nosemgrep: rust.actix.sql.sqlx-taint.sqlx-taint
		let query = format!(
			"PRAGMA index_list({})",
			super::sqlite_pragma::quote_pragma_identifier(table_name)
		);
		let index_list: Vec<IndexListRow> = sqlx::query_as(&query)
			.fetch_all(&self.pool)
			.await
			.map_err(|e| MigrationError::IntrospectionError(e.to_string()))?;

		let mut constraints = Vec::new();
		for index_row in index_list {
			if index_row.origin == "u" {
				// nosemgrep: rust.actix.sql.sqlx-taint.sqlx-taint
				let info_query = format!(
					"PRAGMA index_info({})",
					super::sqlite_pragma::quote_pragma_identifier(&index_row.name)
				);
				let index_info: Vec<IndexInfoRow> = sqlx::query_as(&info_query)
					.fetch_all(&self.pool)
					.await
					.map_err(|e| MigrationError::IntrospectionError(e.to_string()))?;

				let columns: Vec<String> = index_info
					.into_iter()
					.filter_map(|info| info.name)
					.collect();

				constraints.push(UniqueConstraintInfo {
					name: index_row.name,
					columns,
				});
			}
		}

		Ok(constraints)
	}

	/// Introspects a single table using PRAGMA queries.
	async fn introspect_table(&self, table_name: &str) -> Result<TableInfo> {
		#[derive(sqlx::FromRow)]
		struct TableInfoRow {
			// Allow dead_code: field required for SQLite PRAGMA row deserialization
			#[allow(dead_code)]
			// Column index from PRAGMA table_info
			cid: i64,
			name: String,
			r#type: String,
			notnull: i64,
			dflt_value: Option<String>,
			pk: i64,
		}

		// SQLite PRAGMA: identifier interpolation via shared helper. Inputs
		// originate from internal migration operations; see issue #4454.
		// nosemgrep: rust.actix.sql.sqlx-taint.sqlx-taint
		let query = format!(
			"PRAGMA table_info({})",
			super::sqlite_pragma::quote_pragma_identifier(table_name)
		);
		let rows: Vec<TableInfoRow> = sqlx::query_as(&query)
			.fetch_all(&self.pool)
			.await
			.map_err(|e| MigrationError::IntrospectionError(e.to_string()))?;

		// Check AUTOINCREMENT by inspecting CREATE TABLE SQL
		let create_sql = Self::get_create_table_sql(&self.pool, table_name).await?;
		let has_autoincrement = create_sql
			.as_ref()
			.map(|sql| sql.to_uppercase().contains("AUTOINCREMENT"))
			.unwrap_or(false);

		let mut columns = HashMap::new();

		// Build primary key ordered by pk field value
		let mut pk_entries: Vec<(i64, String)> = rows
			.iter()
			.filter(|r| r.pk > 0)
			.map(|r| (r.pk, r.name.clone()))
			.collect();
		pk_entries.sort_by_key(|(pk, _)| *pk);
		let primary_key: Vec<String> = pk_entries.into_iter().map(|(_, name)| name).collect();

		for row in &rows {
			let is_pk = row.pk > 0;

			// AUTOINCREMENT only applies to INTEGER PRIMARY KEY columns
			let is_auto = is_pk && has_autoincrement;

			// Primary key columns are implicitly NOT NULL in SQLite
			let nullable = if is_pk { false } else { row.notnull == 0 };

			// Preserve `dflt_value` verbatim as the raw SQL fragment (e.g.
			// `'pending'` including the surrounding quotes). Downstream DDL
			// emission paths in `operations.rs` round-trip this form
			// correctly:
			// - `format!("DEFAULT {}", default)` emits valid DDL
			//   (`DEFAULT 'pending'`, not the previously broken
			//   `DEFAULT pending`).
			// - `convert_default_value` already handles both quoted and
			//   plain forms.
			// See issue #4454 for context.
			let default = row
				.dflt_value
				.as_ref()
				.map(|v| super::sqlite_pragma::normalize_default_value(v));

			columns.insert(
				row.name.clone(),
				ColumnInfo {
					name: row.name.clone(),
					column_type: Self::parse_sqlite_type(&row.r#type),
					nullable,
					default,
					auto_increment: is_auto,
				},
			);
		}

		// Extract unique constraints from PRAGMA index_list where origin = 'u'
		let unique_constraints = self.extract_unique_constraints(table_name).await?;

		// Extract indexes using existing method
		let indexes = Self::extract_indexes(&self.pool, table_name).await?;

		// Extract foreign keys using existing method
		let foreign_keys = Self::extract_foreign_keys(&self.pool, table_name).await?;

		// Extract CHECK constraints using existing method
		let check_constraints = Self::extract_check_constraints(&self.pool, table_name).await?;

		Ok(TableInfo {
			name: table_name.to_string(),
			columns,
			indexes,
			primary_key,
			foreign_keys,
			unique_constraints,
			check_constraints,
		})
	}
}

#[cfg(feature = "sqlite")]
#[async_trait]
impl DatabaseIntrospector for SQLiteIntrospector {
	async fn read_schema(&self) -> Result<DatabaseSchema> {
		#[derive(sqlx::FromRow)]
		struct TableRow {
			name: String,
		}

		// Get all user tables (exclude SQLite internal tables)
		let query =
			"SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'";
		let table_rows: Vec<TableRow> = sqlx::query_as(query)
			.fetch_all(&self.pool)
			.await
			.map_err(|e| MigrationError::IntrospectionError(e.to_string()))?;

		let mut tables = HashMap::new();
		for table_row in table_rows {
			let table_info = self.introspect_table(&table_row.name).await?;
			tables.insert(table_info.name.clone(), table_info);
		}

		Ok(DatabaseSchema { tables })
	}

	async fn read_table(&self, table_name: &str) -> Result<Option<TableInfo>> {
		#[derive(sqlx::FromRow)]
		struct TableRow {
			// Allow dead_code: field required for SQLite PRAGMA row deserialization
			#[allow(dead_code)]
			// Table name from sqlite_master
			name: String,
		}

		// Check if the table exists
		let query = "SELECT name FROM sqlite_master WHERE type='table' AND name=?";
		let result: Option<TableRow> = sqlx::query_as(query)
			.bind(table_name)
			.fetch_optional(&self.pool)
			.await
			.map_err(|e| MigrationError::IntrospectionError(e.to_string()))?;

		match result {
			Some(_) => {
				let table_info = self.introspect_table(table_name).await?;
				Ok(Some(table_info))
			}
			None => Ok(None),
		}
	}
}

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

	#[cfg(feature = "sqlite")]
	#[tokio::test]
	async fn test_sqlite_introspector_read_schema() {
		use sqlx::SqlitePool;

		let pool = SqlitePool::connect("sqlite::memory:")
			.await
			.expect("Failed to create pool");

		// Create a test table
		sqlx::query(
			r#"
            CREATE TABLE users (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                name TEXT NOT NULL,
                email TEXT UNIQUE NOT NULL,
                age INTEGER
            )
            "#,
		)
		.execute(&pool)
		.await
		.expect("Failed to create table");

		let introspector = SQLiteIntrospector::new(pool);
		let schema = introspector
			.read_schema()
			.await
			.expect("Failed to read schema");

		assert!(schema.tables.contains_key("users"));
		let users_table = &schema.tables["users"];
		assert_eq!(users_table.name, "users");
		assert_eq!(users_table.columns.len(), 4);

		// Check id column
		let id_col = &users_table.columns["id"];
		assert_eq!(id_col.name, "id");
		assert_eq!(id_col.column_type, FieldType::Integer);
		assert!(id_col.auto_increment);
		assert!(!id_col.nullable);

		// Check name column
		let name_col = &users_table.columns["name"];
		assert_eq!(name_col.name, "name");
		assert_eq!(name_col.column_type, FieldType::Text);
		assert!(!name_col.nullable);
	}

	#[cfg(feature = "sqlite")]
	#[tokio::test]
	async fn test_sqlite_introspector_read_table() {
		use sqlx::SqlitePool;

		let pool = SqlitePool::connect("sqlite::memory:")
			.await
			.expect("Failed to create pool");

		// Create a test table
		sqlx::query(
			r#"
            CREATE TABLE posts (
                id INTEGER PRIMARY KEY,
                title TEXT NOT NULL,
                content TEXT
            )
            "#,
		)
		.execute(&pool)
		.await
		.expect("Failed to create table");

		let introspector = SQLiteIntrospector::new(pool);
		let table = introspector
			.read_table("posts")
			.await
			.expect("Failed to read table");

		let posts_table = table.unwrap();
		assert_eq!(posts_table.name, "posts");
		assert_eq!(posts_table.columns.len(), 3);

		// Check non-existent table
		let missing = introspector
			.read_table("non_existent")
			.await
			.expect("Failed to read table");
		assert!(missing.is_none());
	}

	#[cfg(feature = "sqlite")]
	#[tokio::test]
	async fn test_sqlite_introspector_with_indexes() {
		use sqlx::SqlitePool;

		let pool = SqlitePool::connect("sqlite::memory:")
			.await
			.expect("Failed to create pool");

		// Create table with indexes
		sqlx::query(
			r#"
            CREATE TABLE products (
                id INTEGER PRIMARY KEY,
                sku TEXT NOT NULL UNIQUE,
                name TEXT NOT NULL
            )
            "#,
		)
		.execute(&pool)
		.await
		.expect("Failed to create table");

		sqlx::query("CREATE INDEX idx_products_name ON products(name)")
			.execute(&pool)
			.await
			.expect("Failed to create index");

		let introspector = SQLiteIntrospector::new(pool);
		let schema = introspector
			.read_schema()
			.await
			.expect("Failed to read schema");

		let products_table = &schema.tables["products"];
		assert!(!products_table.indexes.is_empty());
	}

	#[cfg(feature = "sqlite")]
	#[tokio::test]
	async fn test_sqlite_introspector_foreign_keys_and_unique_constraints() {
		use sqlx::SqlitePool;

		let pool = SqlitePool::connect("sqlite::memory:")
			.await
			.expect("Failed to create pool");

		// Create tables with foreign keys and unique constraints
		sqlx::query(
			r#"
            CREATE TABLE users (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                email TEXT UNIQUE NOT NULL,
                username TEXT UNIQUE NOT NULL,
                name TEXT NOT NULL
            )
            "#,
		)
		.execute(&pool)
		.await
		.expect("Failed to create users table");

		sqlx::query(
			r#"
            CREATE TABLE posts (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                user_id INTEGER NOT NULL,
                title TEXT NOT NULL,
                FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE ON UPDATE CASCADE
            )
            "#,
		)
		.execute(&pool)
		.await
		.expect("Failed to create posts table");

		let introspector = SQLiteIntrospector::new(pool);
		let schema = introspector
			.read_schema()
			.await
			.expect("Failed to read schema");

		// Check users table
		assert!(schema.tables.contains_key("users"));
		let users_table = &schema.tables["users"];

		// Check unique constraints (email and username)
		assert!(
			!users_table.unique_constraints.is_empty(),
			"Users table should have unique constraints"
		);

		// Check posts table
		assert!(schema.tables.contains_key("posts"));
		let posts_table = &schema.tables["posts"];

		// Verify foreign key on posts table
		assert!(
			!posts_table.foreign_keys.is_empty(),
			"Posts table should have foreign key constraint"
		);

		let fk = &posts_table.foreign_keys[0];
		assert_eq!(
			fk.referenced_table, "users",
			"Foreign key should reference users table"
		);
		assert_eq!(
			fk.columns,
			vec!["user_id"],
			"Foreign key should be on user_id column"
		);
		assert_eq!(
			fk.referenced_columns,
			vec!["id"],
			"Foreign key should reference id column"
		);
		assert_eq!(
			fk.on_delete,
			Some("CASCADE".to_string()),
			"Foreign key should have CASCADE on delete"
		);
		assert_eq!(
			fk.on_update,
			Some("CASCADE".to_string()),
			"Foreign key should have CASCADE on update"
		);
	}
}