sqlmodel-schema 0.2.2

Schema definition and migration support for SQLModel Rust
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
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
//! Database introspection.
//!
//! This module provides comprehensive schema introspection for SQLite, PostgreSQL, and MySQL.
//! It extracts metadata about tables, columns, constraints, and indexes.

use asupersync::{Cx, Outcome};
use sqlmodel_core::{Connection, Error};
use std::collections::HashMap;

#[cfg(test)]
use sqlmodel_core::sanitize_identifier;

// ============================================================================
// Schema Types
// ============================================================================

/// Complete representation of a database schema.
#[derive(Debug, Clone, Default)]
pub struct DatabaseSchema {
    /// All tables in the schema, keyed by table name
    pub tables: HashMap<String, TableInfo>,
    /// Database dialect
    pub dialect: Dialect,
}

impl DatabaseSchema {
    /// Create a new empty schema for the given dialect.
    pub fn new(dialect: Dialect) -> Self {
        Self {
            tables: HashMap::new(),
            dialect,
        }
    }

    /// Get a table by name.
    pub fn table(&self, name: &str) -> Option<&TableInfo> {
        self.tables.get(name)
    }

    /// Get all table names.
    pub fn table_names(&self) -> Vec<&str> {
        self.tables.keys().map(|s| s.as_str()).collect()
    }
}

/// Parsed SQL type with extracted metadata.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ParsedSqlType {
    /// Base type name (e.g., VARCHAR, INTEGER, DECIMAL)
    pub base_type: String,
    /// Length for character types (e.g., VARCHAR(255) -> 255)
    pub length: Option<u32>,
    /// Precision for numeric types (e.g., DECIMAL(10,2) -> 10)
    pub precision: Option<u32>,
    /// Scale for numeric types (e.g., DECIMAL(10,2) -> 2)
    pub scale: Option<u32>,
    /// Whether the type is unsigned (MySQL)
    pub unsigned: bool,
    /// Whether this is an array type (PostgreSQL)
    pub array: bool,
}

impl ParsedSqlType {
    /// Parse a SQL type string into structured metadata.
    ///
    /// # Examples
    /// - `VARCHAR(255)` -> base_type: "VARCHAR", length: 255
    /// - `DECIMAL(10,2)` -> base_type: "DECIMAL", precision: 10, scale: 2
    /// - `INT UNSIGNED` -> base_type: "INT", unsigned: true
    /// - `TEXT[]` -> base_type: "TEXT", array: true
    pub fn parse(type_str: &str) -> Self {
        let type_str = type_str.trim().to_uppercase();

        // Check for array suffix (PostgreSQL)
        let (type_str, array) = if type_str.ends_with("[]") {
            (type_str.trim_end_matches("[]"), true)
        } else {
            (type_str.as_str(), false)
        };

        // Check for UNSIGNED suffix (MySQL)
        let (type_str, unsigned) = if type_str.ends_with(" UNSIGNED") {
            (type_str.trim_end_matches(" UNSIGNED"), true)
        } else {
            (type_str, false)
        };

        // Parse base type and parameters
        if let Some(paren_start) = type_str.find('(') {
            let base_type = type_str[..paren_start].trim().to_string();
            let params = &type_str[paren_start + 1..type_str.len() - 1]; // Remove ()

            // Check if it's precision,scale or just length
            if params.contains(',') {
                let parts: Vec<&str> = params.split(',').collect();
                let precision = parts.first().and_then(|s| s.trim().parse().ok());
                let scale = parts.get(1).and_then(|s| s.trim().parse().ok());
                Self {
                    base_type,
                    length: None,
                    precision,
                    scale,
                    unsigned,
                    array,
                }
            } else {
                let length = params.trim().parse().ok();
                Self {
                    base_type,
                    length,
                    precision: None,
                    scale: None,
                    unsigned,
                    array,
                }
            }
        } else {
            Self {
                base_type: type_str.to_string(),
                length: None,
                precision: None,
                scale: None,
                unsigned,
                array,
            }
        }
    }

    /// Check if this is a text/string type.
    pub fn is_text(&self) -> bool {
        matches!(
            self.base_type.as_str(),
            "VARCHAR" | "CHAR" | "TEXT" | "CLOB" | "NVARCHAR" | "NCHAR" | "NTEXT"
        )
    }

    /// Check if this is a numeric type.
    pub fn is_numeric(&self) -> bool {
        matches!(
            self.base_type.as_str(),
            "INT"
                | "INTEGER"
                | "BIGINT"
                | "SMALLINT"
                | "TINYINT"
                | "MEDIUMINT"
                | "DECIMAL"
                | "NUMERIC"
                | "FLOAT"
                | "DOUBLE"
                | "REAL"
                | "DOUBLE PRECISION"
        )
    }

    /// Check if this is a date/time type.
    pub fn is_datetime(&self) -> bool {
        matches!(
            self.base_type.as_str(),
            "DATE" | "TIME" | "DATETIME" | "TIMESTAMP" | "TIMESTAMPTZ" | "TIMETZ"
        )
    }
}

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

/// Check constraint information.
#[derive(Debug, Clone)]
pub struct CheckConstraintInfo {
    /// Constraint name
    pub name: Option<String>,
    /// Check expression
    pub expression: String,
}

/// Information about a database table.
#[derive(Debug, Clone)]
pub struct TableInfo {
    /// Table name
    pub name: String,
    /// Columns in the table
    pub columns: Vec<ColumnInfo>,
    /// Primary key column names
    pub primary_key: Vec<String>,
    /// Foreign key constraints
    pub foreign_keys: Vec<ForeignKeyInfo>,
    /// Unique constraints
    pub unique_constraints: Vec<UniqueConstraintInfo>,
    /// Check constraints
    pub check_constraints: Vec<CheckConstraintInfo>,
    /// Indexes on the table
    pub indexes: Vec<IndexInfo>,
    /// Table comment (if any)
    pub comment: Option<String>,
}

impl TableInfo {
    /// Get a column by name.
    pub fn column(&self, name: &str) -> Option<&ColumnInfo> {
        self.columns.iter().find(|c| c.name == name)
    }

    /// Check if this table has a single-column auto-increment primary key.
    pub fn has_auto_pk(&self) -> bool {
        self.primary_key.len() == 1
            && self
                .column(&self.primary_key[0])
                .is_some_and(|c| c.auto_increment)
    }
}

/// Information about a table column.
#[derive(Debug, Clone)]
pub struct ColumnInfo {
    /// Column name
    pub name: String,
    /// SQL type as raw string
    pub sql_type: String,
    /// Parsed SQL type with extracted metadata
    pub parsed_type: ParsedSqlType,
    /// Whether the column is nullable
    pub nullable: bool,
    /// Default value expression
    pub default: Option<String>,
    /// Whether this is part of the primary key
    pub primary_key: bool,
    /// Whether this column auto-increments
    pub auto_increment: bool,
    /// Column comment (if any)
    pub comment: Option<String>,
}

/// Information about a foreign key constraint.
#[derive(Debug, Clone)]
pub struct ForeignKeyInfo {
    /// Constraint name
    pub name: Option<String>,
    /// Local column name
    pub column: String,
    /// Referenced table
    pub foreign_table: String,
    /// Referenced column
    pub foreign_column: String,
    /// ON DELETE action
    pub on_delete: Option<String>,
    /// ON UPDATE action
    pub on_update: Option<String>,
}

/// Information about an index.
#[derive(Debug, Clone)]
pub struct IndexInfo {
    /// Index name
    pub name: String,
    /// Columns in the index
    pub columns: Vec<String>,
    /// Whether this is a unique index
    pub unique: bool,
    /// Index type (BTREE, HASH, GIN, GIST, etc.)
    pub index_type: Option<String>,
    /// Whether this is a primary key index
    pub primary: bool,
}

#[derive(Default)]
struct MySqlIndexAccumulator {
    columns: Vec<(i64, String)>,
    unique: bool,
    index_type: Option<String>,
    primary: bool,
}

/// Database introspector.
pub struct Introspector {
    /// Database type for dialect-specific queries
    dialect: Dialect,
}

/// Supported database dialects.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum Dialect {
    /// SQLite
    #[default]
    Sqlite,
    /// PostgreSQL
    Postgres,
    /// MySQL/MariaDB
    Mysql,
}

impl Introspector {
    /// Create a new introspector for the given dialect.
    pub fn new(dialect: Dialect) -> Self {
        Self { dialect }
    }

    /// List all table names in the database.
    pub async fn table_names<C: Connection>(
        &self,
        cx: &Cx,
        conn: &C,
    ) -> Outcome<Vec<String>, Error> {
        let sql = match self.dialect {
            Dialect::Sqlite => {
                "SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'"
            }
            Dialect::Postgres => {
                "SELECT table_name
                                   FROM information_schema.tables
                                   WHERE table_schema = current_schema()
                                     AND table_type = 'BASE TABLE'"
            }
            Dialect::Mysql => "SHOW TABLES",
        };

        let rows = match conn.query(cx, sql, &[]).await {
            Outcome::Ok(rows) => rows,
            Outcome::Err(e) => return Outcome::Err(e),
            Outcome::Cancelled(r) => return Outcome::Cancelled(r),
            Outcome::Panicked(p) => return Outcome::Panicked(p),
        };

        let names: Vec<String> = rows
            .iter()
            .filter_map(|row| row.get(0).and_then(|v| v.as_str().map(String::from)))
            .collect();

        Outcome::Ok(names)
    }

    /// Get detailed information about a table.
    pub async fn table_info<C: Connection>(
        &self,
        cx: &Cx,
        conn: &C,
        table_name: &str,
    ) -> Outcome<TableInfo, Error> {
        let columns = match self.columns(cx, conn, table_name).await {
            Outcome::Ok(cols) => cols,
            Outcome::Err(e) => return Outcome::Err(e),
            Outcome::Cancelled(r) => return Outcome::Cancelled(r),
            Outcome::Panicked(p) => return Outcome::Panicked(p),
        };

        let primary_key: Vec<String> = columns
            .iter()
            .filter(|c| c.primary_key)
            .map(|c| c.name.clone())
            .collect();

        let foreign_keys = match self.foreign_keys(cx, conn, table_name).await {
            Outcome::Ok(fks) => fks,
            Outcome::Err(e) => return Outcome::Err(e),
            Outcome::Cancelled(r) => return Outcome::Cancelled(r),
            Outcome::Panicked(p) => return Outcome::Panicked(p),
        };

        let indexes = match self.indexes(cx, conn, table_name).await {
            Outcome::Ok(idxs) => idxs,
            Outcome::Err(e) => return Outcome::Err(e),
            Outcome::Cancelled(r) => return Outcome::Cancelled(r),
            Outcome::Panicked(p) => return Outcome::Panicked(p),
        };

        let unique_constraints = match self.dialect {
            Dialect::Postgres => match self.postgres_unique_constraints(cx, conn, table_name).await
            {
                Outcome::Ok(uks) => uks,
                Outcome::Err(e) => return Outcome::Err(e),
                Outcome::Cancelled(r) => return Outcome::Cancelled(r),
                Outcome::Panicked(p) => return Outcome::Panicked(p),
            },
            Dialect::Sqlite | Dialect::Mysql => {
                // For SQLite/MySQL, UNIQUE constraints are represented by UNIQUE indexes.
                // We normalize them into `unique_constraints` and remove them from `indexes`
                // so the diff engine does not try to DROP/CREATE constraint-backed indexes.
                Vec::new()
            }
        };

        // SQLite/MySQL: derive unique_constraints from indexes (unique && !primary).
        // PostgreSQL: unique_constraints already queried from pg_constraint; indexes already
        // exclude constraint-backed indexes (see postgres_indexes()).
        let (unique_constraints, indexes) = match self.dialect {
            Dialect::Sqlite | Dialect::Mysql => {
                let mut uks = Vec::new();
                let mut idxs = Vec::new();
                for idx in indexes {
                    if idx.unique && !idx.primary {
                        uks.push(UniqueConstraintInfo {
                            name: Some(idx.name.clone()),
                            columns: idx.columns.clone(),
                        });
                    } else {
                        idxs.push(idx);
                    }
                }
                (uks, idxs)
            }
            Dialect::Postgres => (unique_constraints, indexes),
        };

        let check_constraints = match self.check_constraints(cx, conn, table_name).await {
            Outcome::Ok(checks) => checks,
            Outcome::Err(e) => return Outcome::Err(e),
            Outcome::Cancelled(r) => return Outcome::Cancelled(r),
            Outcome::Panicked(p) => return Outcome::Panicked(p),
        };

        let comment = match self.table_comment(cx, conn, table_name).await {
            Outcome::Ok(comment) => comment,
            Outcome::Err(e) => return Outcome::Err(e),
            Outcome::Cancelled(r) => return Outcome::Cancelled(r),
            Outcome::Panicked(p) => return Outcome::Panicked(p),
        };

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

    async fn postgres_unique_constraints<C: Connection>(
        &self,
        cx: &Cx,
        conn: &C,
        table_name: &str,
    ) -> Outcome<Vec<UniqueConstraintInfo>, Error> {
        debug_assert!(self.dialect == Dialect::Postgres);

        let sql = "SELECT
                       c.conname AS constraint_name,
                       a.attname AS column_name,
                       u.ord AS ordinal
                   FROM pg_constraint c
                   JOIN pg_class t ON t.oid = c.conrelid
                   JOIN pg_namespace n ON n.oid = t.relnamespace
                   JOIN LATERAL unnest(c.conkey) WITH ORDINALITY AS u(attnum, ord) ON true
                   JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = u.attnum
                   WHERE t.relname = $1
                     AND n.nspname = current_schema()
                     AND c.contype = 'u'
                   ORDER BY c.conname, u.ord";

        let rows = match conn
            .query(
                cx,
                sql,
                &[sqlmodel_core::Value::Text(table_name.to_string())],
            )
            .await
        {
            Outcome::Ok(rows) => rows,
            Outcome::Err(e) => return Outcome::Err(e),
            Outcome::Cancelled(r) => return Outcome::Cancelled(r),
            Outcome::Panicked(p) => return Outcome::Panicked(p),
        };

        let mut map: HashMap<String, Vec<(i64, String)>> = HashMap::new();
        for row in &rows {
            let Ok(name) = row.get_named::<String>("constraint_name") else {
                continue;
            };
            let Ok(col) = row.get_named::<String>("column_name") else {
                continue;
            };
            let ord = row.get_named::<i64>("ordinal").ok().unwrap_or(0);
            map.entry(name.clone())
                .and_modify(|cols| cols.push((ord, col.clone())))
                .or_insert_with(|| vec![(ord, col)]);
        }

        let mut out = Vec::new();
        for (name, mut cols) in map {
            cols.sort_by_key(|(ord, _)| *ord);
            out.push(UniqueConstraintInfo {
                name: Some(name),
                columns: cols.into_iter().map(|(_, c)| c).collect(),
            });
        }
        out.sort_by(|a, b| a.name.cmp(&b.name));

        Outcome::Ok(out)
    }

    /// Introspect the entire database schema.
    pub async fn introspect_all<C: Connection>(
        &self,
        cx: &Cx,
        conn: &C,
    ) -> Outcome<DatabaseSchema, Error> {
        let table_names = match self.table_names(cx, conn).await {
            Outcome::Ok(names) => names,
            Outcome::Err(e) => return Outcome::Err(e),
            Outcome::Cancelled(r) => return Outcome::Cancelled(r),
            Outcome::Panicked(p) => return Outcome::Panicked(p),
        };

        let mut schema = DatabaseSchema::new(self.dialect);

        for name in table_names {
            let info = match self.table_info(cx, conn, &name).await {
                Outcome::Ok(info) => info,
                Outcome::Err(e) => return Outcome::Err(e),
                Outcome::Cancelled(r) => return Outcome::Cancelled(r),
                Outcome::Panicked(p) => return Outcome::Panicked(p),
            };
            schema.tables.insert(name, info);
        }

        Outcome::Ok(schema)
    }

    /// Get column information for a table.
    async fn columns<C: Connection>(
        &self,
        cx: &Cx,
        conn: &C,
        table_name: &str,
    ) -> Outcome<Vec<ColumnInfo>, Error> {
        match self.dialect {
            Dialect::Sqlite => self.sqlite_columns(cx, conn, table_name).await,
            Dialect::Postgres => self.postgres_columns(cx, conn, table_name).await,
            Dialect::Mysql => self.mysql_columns(cx, conn, table_name).await,
        }
    }

    async fn sqlite_columns<C: Connection>(
        &self,
        cx: &Cx,
        conn: &C,
        table_name: &str,
    ) -> Outcome<Vec<ColumnInfo>, Error> {
        let sql = format!("PRAGMA table_info({})", quote_sqlite_identifier(table_name));
        let rows = match conn.query(cx, &sql, &[]).await {
            Outcome::Ok(rows) => rows,
            Outcome::Err(e) => return Outcome::Err(e),
            Outcome::Cancelled(r) => return Outcome::Cancelled(r),
            Outcome::Panicked(p) => return Outcome::Panicked(p),
        };

        let columns: Vec<ColumnInfo> = rows
            .iter()
            .filter_map(|row| {
                let name = row.get_named::<String>("name").ok()?;
                let sql_type = row.get_named::<String>("type").ok()?;
                let notnull = row.get_named::<i64>("notnull").ok().unwrap_or(0);
                let dflt_value = row.get_named::<String>("dflt_value").ok();
                let pk = row.get_named::<i64>("pk").ok().unwrap_or(0);
                let parsed_type = ParsedSqlType::parse(&sql_type);

                Some(ColumnInfo {
                    name,
                    sql_type,
                    parsed_type,
                    nullable: notnull == 0,
                    default: dflt_value,
                    primary_key: pk > 0,
                    auto_increment: false, // SQLite doesn't report this via PRAGMA
                    comment: None,         // SQLite doesn't support column comments
                })
            })
            .collect();

        Outcome::Ok(columns)
    }

    async fn postgres_columns<C: Connection>(
        &self,
        cx: &Cx,
        conn: &C,
        table_name: &str,
    ) -> Outcome<Vec<ColumnInfo>, Error> {
        // Use a more comprehensive query to get full type info
        let sql = "SELECT
                       c.column_name,
                       c.data_type,
                       c.udt_name,
                       c.character_maximum_length,
                       c.numeric_precision,
                       c.numeric_scale,
                       c.is_nullable,
                       c.column_default,
                       COALESCE(d.description, '') as column_comment
                   FROM information_schema.columns c
                   LEFT JOIN pg_catalog.pg_statio_all_tables st
                       ON c.table_schema = st.schemaname AND c.table_name = st.relname
                   LEFT JOIN pg_catalog.pg_description d
                       ON d.objoid = st.relid AND d.objsubid = c.ordinal_position
                   WHERE c.table_name = $1 AND c.table_schema = current_schema()
                   ORDER BY c.ordinal_position";

        let rows = match conn
            .query(
                cx,
                sql,
                &[sqlmodel_core::Value::Text(table_name.to_string())],
            )
            .await
        {
            Outcome::Ok(rows) => rows,
            Outcome::Err(e) => return Outcome::Err(e),
            Outcome::Cancelled(r) => return Outcome::Cancelled(r),
            Outcome::Panicked(p) => return Outcome::Panicked(p),
        };

        let columns: Vec<ColumnInfo> = rows
            .iter()
            .filter_map(|row| {
                let name = row.get_named::<String>("column_name").ok()?;
                let data_type = row.get_named::<String>("data_type").ok()?;
                let udt_name = row.get_named::<String>("udt_name").ok().unwrap_or_default();
                let char_len = row.get_named::<i64>("character_maximum_length").ok();
                let precision = row.get_named::<i64>("numeric_precision").ok();
                let scale = row.get_named::<i64>("numeric_scale").ok();
                let nullable_str = row.get_named::<String>("is_nullable").ok()?;
                let default = row.get_named::<String>("column_default").ok();
                let comment = row.get_named::<String>("column_comment").ok();

                // Build a complete SQL type string
                let sql_type =
                    build_postgres_type(&data_type, &udt_name, char_len, precision, scale);
                let parsed_type = ParsedSqlType::parse(&sql_type);

                // Check if auto-increment by looking at default (nextval)
                let auto_increment = default.as_ref().is_some_and(|d| d.starts_with("nextval("));

                Some(ColumnInfo {
                    name,
                    sql_type,
                    parsed_type,
                    nullable: nullable_str == "YES",
                    default,
                    primary_key: false, // Determined via separate index query
                    auto_increment,
                    comment: comment.filter(|s| !s.is_empty()),
                })
            })
            .collect();

        Outcome::Ok(columns)
    }

    async fn mysql_columns<C: Connection>(
        &self,
        cx: &Cx,
        conn: &C,
        table_name: &str,
    ) -> Outcome<Vec<ColumnInfo>, Error> {
        // Use SHOW FULL COLUMNS to get comments
        let sql = format!(
            "SHOW FULL COLUMNS FROM {}",
            quote_mysql_identifier(table_name)
        );
        let rows = match conn.query(cx, &sql, &[]).await {
            Outcome::Ok(rows) => rows,
            Outcome::Err(e) => return Outcome::Err(e),
            Outcome::Cancelled(r) => return Outcome::Cancelled(r),
            Outcome::Panicked(p) => return Outcome::Panicked(p),
        };

        let columns: Vec<ColumnInfo> = rows
            .iter()
            .filter_map(|row| {
                let name = row.get_named::<String>("Field").ok()?;
                let sql_type = row.get_named::<String>("Type").ok()?;
                let null = row.get_named::<String>("Null").ok()?;
                let key = row.get_named::<String>("Key").ok()?;
                let default = row.get_named::<String>("Default").ok();
                let extra = row.get_named::<String>("Extra").ok().unwrap_or_default();
                let comment = row.get_named::<String>("Comment").ok();
                let parsed_type = ParsedSqlType::parse(&sql_type);

                Some(ColumnInfo {
                    name,
                    sql_type,
                    parsed_type,
                    nullable: null == "YES",
                    default,
                    primary_key: key == "PRI",
                    auto_increment: extra.contains("auto_increment"),
                    comment: comment.filter(|s| !s.is_empty()),
                })
            })
            .collect();

        Outcome::Ok(columns)
    }

    // ========================================================================
    // Foreign Key Introspection
    // ========================================================================

    async fn check_constraints<C: Connection>(
        &self,
        cx: &Cx,
        conn: &C,
        table_name: &str,
    ) -> Outcome<Vec<CheckConstraintInfo>, Error> {
        match self.dialect {
            Dialect::Sqlite => self.sqlite_check_constraints(cx, conn, table_name).await,
            Dialect::Postgres => self.postgres_check_constraints(cx, conn, table_name).await,
            Dialect::Mysql => self.mysql_check_constraints(cx, conn, table_name).await,
        }
    }

    async fn sqlite_check_constraints<C: Connection>(
        &self,
        cx: &Cx,
        conn: &C,
        table_name: &str,
    ) -> Outcome<Vec<CheckConstraintInfo>, Error> {
        let sql = "SELECT sql FROM sqlite_master WHERE type='table' AND name=?1";
        let rows = match conn
            .query(
                cx,
                sql,
                &[sqlmodel_core::Value::Text(table_name.to_string())],
            )
            .await
        {
            Outcome::Ok(rows) => rows,
            Outcome::Err(e) => return Outcome::Err(e),
            Outcome::Cancelled(r) => return Outcome::Cancelled(r),
            Outcome::Panicked(p) => return Outcome::Panicked(p),
        };

        let create_sql = rows.iter().find_map(|row| {
            row.get_named::<String>("sql").ok().or_else(|| {
                row.get(0)
                    .and_then(|value| value.as_str().map(ToString::to_string))
            })
        });

        match create_sql {
            Some(sql) => Outcome::Ok(extract_sqlite_check_constraints(&sql)),
            None => Outcome::Ok(Vec::new()),
        }
    }

    async fn postgres_check_constraints<C: Connection>(
        &self,
        cx: &Cx,
        conn: &C,
        table_name: &str,
    ) -> Outcome<Vec<CheckConstraintInfo>, Error> {
        let sql = "SELECT
                       c.conname AS constraint_name,
                       pg_get_constraintdef(c.oid, true) AS constraint_definition
                   FROM pg_constraint c
                   JOIN pg_class t ON t.oid = c.conrelid
                   JOIN pg_namespace n ON n.oid = t.relnamespace
                   WHERE t.relname = $1
                     AND n.nspname = current_schema()
                     AND c.contype = 'c'
                   ORDER BY c.conname";

        let rows = match conn
            .query(
                cx,
                sql,
                &[sqlmodel_core::Value::Text(table_name.to_string())],
            )
            .await
        {
            Outcome::Ok(rows) => rows,
            Outcome::Err(e) => return Outcome::Err(e),
            Outcome::Cancelled(r) => return Outcome::Cancelled(r),
            Outcome::Panicked(p) => return Outcome::Panicked(p),
        };

        let checks = rows
            .iter()
            .filter_map(|row| {
                let definition = row.get_named::<String>("constraint_definition").ok()?;
                let expression = normalize_check_expression(&definition);
                if expression.is_empty() {
                    return None;
                }
                Some(CheckConstraintInfo {
                    name: row
                        .get_named::<String>("constraint_name")
                        .ok()
                        .filter(|s| !s.is_empty()),
                    expression,
                })
            })
            .collect();

        Outcome::Ok(checks)
    }

    async fn mysql_check_constraints<C: Connection>(
        &self,
        cx: &Cx,
        conn: &C,
        table_name: &str,
    ) -> Outcome<Vec<CheckConstraintInfo>, Error> {
        let sql = "SELECT
                 tc.CONSTRAINT_NAME AS constraint_name,
                 cc.CHECK_CLAUSE AS check_clause
             FROM information_schema.TABLE_CONSTRAINTS tc
             JOIN information_schema.CHECK_CONSTRAINTS cc
               ON tc.CONSTRAINT_SCHEMA = cc.CONSTRAINT_SCHEMA
              AND tc.CONSTRAINT_NAME = cc.CONSTRAINT_NAME
             WHERE tc.CONSTRAINT_TYPE = 'CHECK'
               AND tc.TABLE_SCHEMA = DATABASE()
               AND tc.TABLE_NAME = ?
             ORDER BY tc.CONSTRAINT_NAME";

        let rows = match conn
            .query(
                cx,
                sql,
                &[sqlmodel_core::Value::Text(table_name.to_string())],
            )
            .await
        {
            Outcome::Ok(rows) => rows,
            Outcome::Err(e) => return Outcome::Err(e),
            Outcome::Cancelled(r) => return Outcome::Cancelled(r),
            Outcome::Panicked(p) => return Outcome::Panicked(p),
        };

        let checks = rows
            .iter()
            .filter_map(|row| {
                let definition = row.get_named::<String>("check_clause").ok()?;
                let expression = normalize_check_expression(&definition);
                if expression.is_empty() {
                    return None;
                }
                Some(CheckConstraintInfo {
                    name: row
                        .get_named::<String>("constraint_name")
                        .ok()
                        .filter(|s| !s.is_empty()),
                    expression,
                })
            })
            .collect();

        Outcome::Ok(checks)
    }

    async fn table_comment<C: Connection>(
        &self,
        cx: &Cx,
        conn: &C,
        table_name: &str,
    ) -> Outcome<Option<String>, Error> {
        match self.dialect {
            Dialect::Sqlite => Outcome::Ok(None),
            Dialect::Postgres => self.postgres_table_comment(cx, conn, table_name).await,
            Dialect::Mysql => self.mysql_table_comment(cx, conn, table_name).await,
        }
    }

    async fn postgres_table_comment<C: Connection>(
        &self,
        cx: &Cx,
        conn: &C,
        table_name: &str,
    ) -> Outcome<Option<String>, Error> {
        let sql = "SELECT
                       COALESCE(obj_description(c.oid, 'pg_class'), '') AS table_comment
                   FROM pg_class c
                   JOIN pg_namespace n ON n.oid = c.relnamespace
                   WHERE c.relname = $1
                     AND n.nspname = current_schema()
                   LIMIT 1";

        let rows = match conn
            .query(
                cx,
                sql,
                &[sqlmodel_core::Value::Text(table_name.to_string())],
            )
            .await
        {
            Outcome::Ok(rows) => rows,
            Outcome::Err(e) => return Outcome::Err(e),
            Outcome::Cancelled(r) => return Outcome::Cancelled(r),
            Outcome::Panicked(p) => return Outcome::Panicked(p),
        };

        let comment = rows.iter().find_map(|row| {
            row.get_named::<String>("table_comment")
                .ok()
                .filter(|s| !s.is_empty())
        });
        Outcome::Ok(comment)
    }

    async fn mysql_table_comment<C: Connection>(
        &self,
        cx: &Cx,
        conn: &C,
        table_name: &str,
    ) -> Outcome<Option<String>, Error> {
        let sql = "SELECT TABLE_COMMENT AS table_comment
             FROM information_schema.TABLES
             WHERE TABLE_SCHEMA = DATABASE()
               AND TABLE_NAME = ?
             LIMIT 1";

        let rows = match conn
            .query(
                cx,
                sql,
                &[sqlmodel_core::Value::Text(table_name.to_string())],
            )
            .await
        {
            Outcome::Ok(rows) => rows,
            Outcome::Err(e) => return Outcome::Err(e),
            Outcome::Cancelled(r) => return Outcome::Cancelled(r),
            Outcome::Panicked(p) => return Outcome::Panicked(p),
        };

        let comment = rows.iter().find_map(|row| {
            row.get_named::<String>("table_comment")
                .ok()
                .filter(|s| !s.is_empty())
        });
        Outcome::Ok(comment)
    }

    /// Get foreign key constraints for a table.
    async fn foreign_keys<C: Connection>(
        &self,
        cx: &Cx,
        conn: &C,
        table_name: &str,
    ) -> Outcome<Vec<ForeignKeyInfo>, Error> {
        match self.dialect {
            Dialect::Sqlite => self.sqlite_foreign_keys(cx, conn, table_name).await,
            Dialect::Postgres => self.postgres_foreign_keys(cx, conn, table_name).await,
            Dialect::Mysql => self.mysql_foreign_keys(cx, conn, table_name).await,
        }
    }

    async fn sqlite_foreign_keys<C: Connection>(
        &self,
        cx: &Cx,
        conn: &C,
        table_name: &str,
    ) -> Outcome<Vec<ForeignKeyInfo>, Error> {
        let sql = format!(
            "PRAGMA foreign_key_list({})",
            quote_sqlite_identifier(table_name)
        );
        let rows = match conn.query(cx, &sql, &[]).await {
            Outcome::Ok(rows) => rows,
            Outcome::Err(e) => return Outcome::Err(e),
            Outcome::Cancelled(r) => return Outcome::Cancelled(r),
            Outcome::Panicked(p) => return Outcome::Panicked(p),
        };

        let fks: Vec<ForeignKeyInfo> = rows
            .iter()
            .filter_map(|row| {
                let table = row.get_named::<String>("table").ok()?;
                let from = row.get_named::<String>("from").ok()?;
                let to = row.get_named::<String>("to").ok()?;
                let on_update = row.get_named::<String>("on_update").ok();
                let on_delete = row.get_named::<String>("on_delete").ok();

                Some(ForeignKeyInfo {
                    name: None, // SQLite doesn't name FK constraints in PRAGMA output
                    column: from,
                    foreign_table: table,
                    foreign_column: to,
                    on_delete: on_delete.filter(|s| s != "NO ACTION"),
                    on_update: on_update.filter(|s| s != "NO ACTION"),
                })
            })
            .collect();

        Outcome::Ok(fks)
    }

    async fn postgres_foreign_keys<C: Connection>(
        &self,
        cx: &Cx,
        conn: &C,
        table_name: &str,
    ) -> Outcome<Vec<ForeignKeyInfo>, Error> {
        let sql = "SELECT
                       tc.constraint_name,
                       kcu.column_name,
                       ccu.table_name AS foreign_table_name,
                       ccu.column_name AS foreign_column_name,
                       rc.delete_rule,
                       rc.update_rule
                   FROM information_schema.table_constraints AS tc
                   JOIN information_schema.key_column_usage AS kcu
                       ON tc.constraint_name = kcu.constraint_name
                       AND tc.table_schema = kcu.table_schema
                   JOIN information_schema.constraint_column_usage AS ccu
                       ON ccu.constraint_name = tc.constraint_name
                       AND ccu.table_schema = tc.table_schema
                   JOIN information_schema.referential_constraints AS rc
                       ON rc.constraint_name = tc.constraint_name
                       AND rc.constraint_schema = tc.table_schema
                   WHERE tc.constraint_type = 'FOREIGN KEY'
                       AND tc.table_name = $1
                       AND tc.table_schema = current_schema()";

        let rows = match conn
            .query(
                cx,
                sql,
                &[sqlmodel_core::Value::Text(table_name.to_string())],
            )
            .await
        {
            Outcome::Ok(rows) => rows,
            Outcome::Err(e) => return Outcome::Err(e),
            Outcome::Cancelled(r) => return Outcome::Cancelled(r),
            Outcome::Panicked(p) => return Outcome::Panicked(p),
        };

        let fks: Vec<ForeignKeyInfo> = rows
            .iter()
            .filter_map(|row| {
                let name = row.get_named::<String>("constraint_name").ok();
                let column = row.get_named::<String>("column_name").ok()?;
                let foreign_table = row.get_named::<String>("foreign_table_name").ok()?;
                let foreign_column = row.get_named::<String>("foreign_column_name").ok()?;
                let on_delete = row.get_named::<String>("delete_rule").ok();
                let on_update = row.get_named::<String>("update_rule").ok();

                Some(ForeignKeyInfo {
                    name,
                    column,
                    foreign_table,
                    foreign_column,
                    on_delete: on_delete.filter(|s| s != "NO ACTION"),
                    on_update: on_update.filter(|s| s != "NO ACTION"),
                })
            })
            .collect();

        Outcome::Ok(fks)
    }

    async fn mysql_foreign_keys<C: Connection>(
        &self,
        cx: &Cx,
        conn: &C,
        table_name: &str,
    ) -> Outcome<Vec<ForeignKeyInfo>, Error> {
        let sql = "SELECT
                       kcu.constraint_name,
                       kcu.column_name,
                       kcu.referenced_table_name,
                       kcu.referenced_column_name,
                       rc.delete_rule,
                       rc.update_rule
                   FROM information_schema.key_column_usage AS kcu
                   JOIN information_schema.referential_constraints AS rc
                       ON rc.constraint_name = kcu.constraint_name
                       AND rc.constraint_schema = kcu.constraint_schema
                   WHERE kcu.table_schema = DATABASE()
                       AND kcu.table_name = ?
                       AND kcu.referenced_table_name IS NOT NULL";

        let rows = match conn
            .query(
                cx,
                sql,
                &[sqlmodel_core::Value::Text(table_name.to_string())],
            )
            .await
        {
            Outcome::Ok(rows) => rows,
            Outcome::Err(e) => return Outcome::Err(e),
            Outcome::Cancelled(r) => return Outcome::Cancelled(r),
            Outcome::Panicked(p) => return Outcome::Panicked(p),
        };

        let fks: Vec<ForeignKeyInfo> = rows
            .iter()
            .filter_map(|row| {
                let name = row.get_named::<String>("constraint_name").ok();
                let column = row.get_named::<String>("column_name").ok()?;
                let foreign_table = row.get_named::<String>("referenced_table_name").ok()?;
                let foreign_column = row.get_named::<String>("referenced_column_name").ok()?;
                let on_delete = row.get_named::<String>("delete_rule").ok();
                let on_update = row.get_named::<String>("update_rule").ok();

                Some(ForeignKeyInfo {
                    name,
                    column,
                    foreign_table,
                    foreign_column,
                    on_delete: on_delete.filter(|s| s != "NO ACTION"),
                    on_update: on_update.filter(|s| s != "NO ACTION"),
                })
            })
            .collect();

        Outcome::Ok(fks)
    }

    // ========================================================================
    // Index Introspection
    // ========================================================================

    /// Get indexes for a table.
    async fn indexes<C: Connection>(
        &self,
        cx: &Cx,
        conn: &C,
        table_name: &str,
    ) -> Outcome<Vec<IndexInfo>, Error> {
        match self.dialect {
            Dialect::Sqlite => self.sqlite_indexes(cx, conn, table_name).await,
            Dialect::Postgres => self.postgres_indexes(cx, conn, table_name).await,
            Dialect::Mysql => self.mysql_indexes(cx, conn, table_name).await,
        }
    }

    async fn sqlite_indexes<C: Connection>(
        &self,
        cx: &Cx,
        conn: &C,
        table_name: &str,
    ) -> Outcome<Vec<IndexInfo>, Error> {
        let sql = format!("PRAGMA index_list({})", quote_sqlite_identifier(table_name));
        let rows = match conn.query(cx, &sql, &[]).await {
            Outcome::Ok(rows) => rows,
            Outcome::Err(e) => return Outcome::Err(e),
            Outcome::Cancelled(r) => return Outcome::Cancelled(r),
            Outcome::Panicked(p) => return Outcome::Panicked(p),
        };

        let mut indexes = Vec::new();

        for row in &rows {
            let Ok(name) = row.get_named::<String>("name") else {
                continue;
            };
            let unique = row.get_named::<i64>("unique").ok().unwrap_or(0) == 1;
            let origin = row.get_named::<String>("origin").ok().unwrap_or_default();
            let primary = origin == "pk";

            // Get column info for this index
            let info_sql = format!("PRAGMA index_info({})", quote_sqlite_identifier(&name));
            let info_rows = match conn.query(cx, &info_sql, &[]).await {
                Outcome::Ok(r) => r,
                Outcome::Err(_) => continue,
                Outcome::Cancelled(r) => return Outcome::Cancelled(r),
                Outcome::Panicked(p) => return Outcome::Panicked(p),
            };

            let columns: Vec<String> = info_rows
                .iter()
                .filter_map(|r| r.get_named::<String>("name").ok())
                .collect();

            indexes.push(IndexInfo {
                name,
                columns,
                unique,
                index_type: None, // SQLite doesn't expose index type
                primary,
            });
        }

        Outcome::Ok(indexes)
    }

    async fn postgres_indexes<C: Connection>(
        &self,
        cx: &Cx,
        conn: &C,
        table_name: &str,
    ) -> Outcome<Vec<IndexInfo>, Error> {
        // Exclude indexes backing PRIMARY KEY / UNIQUE constraints; those are represented
        // via TableInfo.primary_key and TableInfo.unique_constraints so the diff engine
        // doesn't try to DROP/CREATE constraint-backed indexes.
        let sql = "SELECT
                       i.relname AS index_name,
                       a.attname AS column_name,
                       k.ord AS column_ord,
                       ix.indisunique AS is_unique,
                       ix.indisprimary AS is_primary,
                       am.amname AS index_type
                   FROM pg_class t
                   JOIN pg_namespace n ON n.oid = t.relnamespace
                   JOIN pg_index ix ON t.oid = ix.indrelid
                   JOIN LATERAL unnest(ix.indkey) WITH ORDINALITY AS k(attnum, ord) ON true
                   JOIN pg_class i ON i.oid = ix.indexrelid
                   JOIN pg_am am ON i.relam = am.oid
                   JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = k.attnum
                   WHERE t.relname = $1
                       AND n.nspname = current_schema()
                       AND t.relkind = 'r'
                       AND NOT EXISTS (
                           SELECT 1
                           FROM pg_constraint c
                           WHERE c.conrelid = t.oid
                             AND c.conindid = i.oid
                             AND c.contype IN ('p', 'u')
                       )
                   ORDER BY i.relname, k.ord";

        let rows = match conn
            .query(
                cx,
                sql,
                &[sqlmodel_core::Value::Text(table_name.to_string())],
            )
            .await
        {
            Outcome::Ok(rows) => rows,
            Outcome::Err(e) => return Outcome::Err(e),
            Outcome::Cancelled(r) => return Outcome::Cancelled(r),
            Outcome::Panicked(p) => return Outcome::Panicked(p),
        };

        // Group by index name
        let mut index_map: HashMap<String, IndexInfo> = HashMap::new();

        for row in &rows {
            let Ok(name) = row.get_named::<String>("index_name") else {
                continue;
            };
            let Ok(column) = row.get_named::<String>("column_name") else {
                continue;
            };
            let unique = row.get_named::<bool>("is_unique").ok().unwrap_or(false);
            let primary = row.get_named::<bool>("is_primary").ok().unwrap_or(false);
            let index_type = row.get_named::<String>("index_type").ok();

            index_map
                .entry(name.clone())
                .and_modify(|idx| idx.columns.push(column.clone()))
                .or_insert_with(|| IndexInfo {
                    name,
                    columns: vec![column],
                    unique,
                    index_type,
                    primary,
                });
        }

        Outcome::Ok(index_map.into_values().collect())
    }

    async fn mysql_indexes<C: Connection>(
        &self,
        cx: &Cx,
        conn: &C,
        table_name: &str,
    ) -> Outcome<Vec<IndexInfo>, Error> {
        let sql = format!("SHOW INDEX FROM {}", quote_mysql_identifier(table_name));
        let rows = match conn.query(cx, &sql, &[]).await {
            Outcome::Ok(rows) => rows,
            Outcome::Err(e) => return Outcome::Err(e),
            Outcome::Cancelled(r) => return Outcome::Cancelled(r),
            Outcome::Panicked(p) => return Outcome::Panicked(p),
        };

        // Group by index name, preserving declared key order via Seq_in_index.
        let mut index_map: HashMap<String, MySqlIndexAccumulator> = HashMap::new();

        for row in &rows {
            let Ok(name) = row.get_named::<String>("Key_name") else {
                continue;
            };
            let Ok(column) = row.get_named::<String>("Column_name") else {
                continue;
            };
            let seq_in_index = row
                .get_named::<i64>("Seq_in_index")
                .ok()
                .unwrap_or(i64::MAX);
            let non_unique = row.get_named::<i64>("Non_unique").ok().unwrap_or(1);
            let index_type = row.get_named::<String>("Index_type").ok();
            let primary = name == "PRIMARY";

            index_map
                .entry(name.clone())
                .and_modify(|idx| idx.columns.push((seq_in_index, column.clone())))
                .or_insert_with(|| MySqlIndexAccumulator {
                    columns: vec![(seq_in_index, column)],
                    unique: non_unique == 0,
                    index_type: index_type.clone(),
                    primary,
                });
        }

        let indexes = index_map
            .into_iter()
            .map(|(name, mut acc)| {
                acc.columns.sort_by_key(|(seq, _)| *seq);
                IndexInfo {
                    name,
                    columns: acc.columns.into_iter().map(|(_, col)| col).collect(),
                    unique: acc.unique,
                    index_type: acc.index_type,
                    primary: acc.primary,
                }
            })
            .collect();

        Outcome::Ok(indexes)
    }
}

// ============================================================================
// Helper Functions
// ============================================================================

fn quote_sqlite_identifier(name: &str) -> String {
    let escaped = name.replace('"', "\"\"");
    format!("\"{escaped}\"")
}

fn quote_mysql_identifier(name: &str) -> String {
    let escaped = name.replace('`', "``");
    format!("`{escaped}`")
}

/// Build a complete PostgreSQL type string from information_schema data.
fn build_postgres_type(
    data_type: &str,
    udt_name: &str,
    char_len: Option<i64>,
    precision: Option<i64>,
    scale: Option<i64>,
) -> String {
    // Handle array types
    if data_type == "ARRAY" {
        return format!("{}[]", udt_name.trim_start_matches('_'));
    }

    // For character types with length
    if let Some(len) = char_len {
        return format!("{}({})", data_type.to_uppercase(), len);
    }

    // For numeric types with precision/scale
    if let (Some(p), Some(s)) = (precision, scale) {
        if data_type == "numeric" {
            return format!("NUMERIC({},{})", p, s);
        }
    }

    // Default: just return the data type
    data_type.to_uppercase()
}

fn normalize_check_expression(definition: &str) -> String {
    let trimmed = definition.trim();
    let check_positions = keyword_positions_outside_quotes(trimmed, "CHECK");
    if let Some(check_pos) = check_positions.first().copied() {
        let mut cursor = check_pos + "CHECK".len();
        while cursor < trimmed.len() && trimmed.as_bytes()[cursor].is_ascii_whitespace() {
            cursor += 1;
        }
        if cursor < trimmed.len()
            && trimmed.as_bytes()[cursor] == b'('
            && let Some((expr, _)) = extract_parenthesized(trimmed, cursor)
        {
            return expr;
        }
    }
    trimmed.to_string()
}

fn extract_sqlite_check_constraints(create_table_sql: &str) -> Vec<CheckConstraintInfo> {
    let Some(definitions) = sqlite_table_definitions(create_table_sql) else {
        return Vec::new();
    };

    let mut checks = Vec::new();
    for definition in split_sqlite_definitions(definitions) {
        let constraint_positions = keyword_positions_outside_quotes(definition, "CONSTRAINT");
        let check_positions = keyword_positions_outside_quotes(definition, "CHECK");

        for check_pos in check_positions {
            let mut cursor = check_pos + "CHECK".len();
            while cursor < definition.len() && definition.as_bytes()[cursor].is_ascii_whitespace() {
                cursor += 1;
            }

            if cursor >= definition.len() || definition.as_bytes()[cursor] != b'(' {
                continue;
            }

            let Some((expression, _end_pos)) = extract_parenthesized(definition, cursor) else {
                continue;
            };

            checks.push(CheckConstraintInfo {
                name: sqlite_constraint_name_for_check(
                    definition,
                    check_pos,
                    &constraint_positions,
                ),
                expression,
            });
        }
    }

    checks
}

fn sqlite_table_definitions(create_table_sql: &str) -> Option<&str> {
    let mut start = None;
    let mut depth = 0usize;

    for (idx, byte) in create_table_sql.as_bytes().iter().copied().enumerate() {
        match byte {
            b'(' => {
                if start.is_none() {
                    start = Some(idx + 1);
                }
                depth += 1;
            }
            b')' if depth > 0 => {
                depth -= 1;
                if depth == 0 {
                    return start.map(|s| &create_table_sql[s..idx]);
                }
            }
            _ => {}
        }
    }

    None
}

fn split_sqlite_definitions(definitions: &str) -> Vec<&str> {
    let mut parts = Vec::new();
    let bytes = definitions.as_bytes();
    let mut depth = 0usize;
    let mut start = 0usize;
    let mut i = 0usize;
    let mut single_quote = false;
    let mut double_quote = false;
    let mut backtick_quote = false;
    let mut bracket_quote = false;

    while i < bytes.len() {
        let b = bytes[i];
        if single_quote {
            if b == b'\'' {
                if i + 1 < bytes.len() && bytes[i + 1] == b'\'' {
                    i += 2;
                    continue;
                }
                single_quote = false;
            }
            i += 1;
            continue;
        }
        if double_quote {
            if b == b'"' {
                double_quote = false;
            }
            i += 1;
            continue;
        }
        if backtick_quote {
            if b == b'`' {
                backtick_quote = false;
            }
            i += 1;
            continue;
        }
        if bracket_quote {
            if b == b']' {
                bracket_quote = false;
            }
            i += 1;
            continue;
        }

        match b {
            b'\'' => single_quote = true,
            b'"' => double_quote = true,
            b'`' => backtick_quote = true,
            b'[' => bracket_quote = true,
            b'(' => depth += 1,
            b')' if depth > 0 => depth -= 1,
            b',' if depth == 0 => {
                let part = definitions[start..i].trim();
                if !part.is_empty() {
                    parts.push(part);
                }
                start = i + 1;
            }
            _ => {}
        }

        i += 1;
    }

    let tail = definitions[start..].trim();
    if !tail.is_empty() {
        parts.push(tail);
    }

    parts
}

fn keyword_positions_outside_quotes(input: &str, keyword: &str) -> Vec<usize> {
    if keyword.is_empty() || input.len() < keyword.len() {
        return Vec::new();
    }

    let bytes = input.as_bytes();
    let keyword_bytes = keyword.as_bytes();
    let mut positions = Vec::new();
    let mut i = 0usize;
    let mut single_quote = false;
    let mut double_quote = false;
    let mut backtick_quote = false;
    let mut bracket_quote = false;

    while i < bytes.len() {
        let b = bytes[i];
        if single_quote {
            if b == b'\'' {
                if i + 1 < bytes.len() && bytes[i + 1] == b'\'' {
                    i += 2;
                    continue;
                }
                single_quote = false;
            }
            i += 1;
            continue;
        }
        if double_quote {
            if b == b'"' {
                double_quote = false;
            }
            i += 1;
            continue;
        }
        if backtick_quote {
            if b == b'`' {
                backtick_quote = false;
            }
            i += 1;
            continue;
        }
        if bracket_quote {
            if b == b']' {
                bracket_quote = false;
            }
            i += 1;
            continue;
        }

        match b {
            b'\'' => {
                single_quote = true;
                i += 1;
                continue;
            }
            b'"' => {
                double_quote = true;
                i += 1;
                continue;
            }
            b'`' => {
                backtick_quote = true;
                i += 1;
                continue;
            }
            b'[' => {
                bracket_quote = true;
                i += 1;
                continue;
            }
            _ => {}
        }

        if i + keyword_bytes.len() <= bytes.len()
            && bytes[i..i + keyword_bytes.len()].eq_ignore_ascii_case(keyword_bytes)
            && (i == 0 || !is_identifier_byte(bytes[i - 1]))
            && (i + keyword_bytes.len() == bytes.len()
                || !is_identifier_byte(bytes[i + keyword_bytes.len()]))
        {
            positions.push(i);
            i += keyword_bytes.len();
            continue;
        }

        i += 1;
    }

    positions
}

fn sqlite_constraint_name_for_check(
    definition: &str,
    check_pos: usize,
    constraint_positions: &[usize],
) -> Option<String> {
    let constraint_pos = constraint_positions
        .iter()
        .copied()
        .rfind(|pos| *pos < check_pos)?;

    let mut cursor = constraint_pos + "CONSTRAINT".len();
    while cursor < definition.len() && definition.as_bytes()[cursor].is_ascii_whitespace() {
        cursor += 1;
    }
    if cursor >= definition.len() {
        return None;
    }

    let (name, _next) = parse_sqlite_identifier_token(definition, cursor)?;
    Some(name)
}

fn parse_sqlite_identifier_token(input: &str, start: usize) -> Option<(String, usize)> {
    let bytes = input.as_bytes();
    let first = *bytes.get(start)?;
    match first {
        b'"' => {
            let mut i = start + 1;
            while i < bytes.len() {
                if bytes[i] == b'"' {
                    if i + 1 < bytes.len() && bytes[i + 1] == b'"' {
                        i += 2;
                        continue;
                    }
                    let name = input[start + 1..i].replace("\"\"", "\"");
                    return Some((name, i + 1));
                }
                i += 1;
            }
            None
        }
        b'`' => {
            let mut i = start + 1;
            while i < bytes.len() {
                if bytes[i] == b'`' {
                    if i + 1 < bytes.len() && bytes[i + 1] == b'`' {
                        i += 2;
                        continue;
                    }
                    let name = input[start + 1..i].replace("``", "`");
                    return Some((name, i + 1));
                }
                i += 1;
            }
            None
        }
        b'[' => {
            let mut i = start + 1;
            while i < bytes.len() {
                if bytes[i] == b']' {
                    let name = input[start + 1..i].to_string();
                    return Some((name, i + 1));
                }
                i += 1;
            }
            None
        }
        _ => {
            let mut i = start;
            while i < bytes.len() && !bytes[i].is_ascii_whitespace() {
                i += 1;
            }
            if i == start {
                None
            } else {
                Some((input[start..i].to_string(), i))
            }
        }
    }
}

fn extract_parenthesized(input: &str, open_paren_pos: usize) -> Option<(String, usize)> {
    let bytes = input.as_bytes();
    if bytes.get(open_paren_pos).copied() != Some(b'(') {
        return None;
    }

    let mut depth = 0usize;
    let mut i = open_paren_pos;
    let mut single_quote = false;
    let mut double_quote = false;
    let mut backtick_quote = false;
    let mut bracket_quote = false;

    while i < bytes.len() {
        let b = bytes[i];
        if single_quote {
            if b == b'\'' {
                if i + 1 < bytes.len() && bytes[i + 1] == b'\'' {
                    i += 2;
                    continue;
                }
                single_quote = false;
            }
            i += 1;
            continue;
        }
        if double_quote {
            if b == b'"' {
                double_quote = false;
            }
            i += 1;
            continue;
        }
        if backtick_quote {
            if b == b'`' {
                backtick_quote = false;
            }
            i += 1;
            continue;
        }
        if bracket_quote {
            if b == b']' {
                bracket_quote = false;
            }
            i += 1;
            continue;
        }

        match b {
            b'\'' => single_quote = true,
            b'"' => double_quote = true,
            b'`' => backtick_quote = true,
            b'[' => bracket_quote = true,
            b'(' => depth += 1,
            b')' => {
                if depth == 0 {
                    return None;
                }
                depth -= 1;
                if depth == 0 {
                    let expression = input[open_paren_pos + 1..i].trim().to_string();
                    return Some((expression, i));
                }
            }
            _ => {}
        }
        i += 1;
    }

    None
}

fn is_identifier_byte(b: u8) -> bool {
    b.is_ascii_alphanumeric() || b == b'_'
}

// ============================================================================
// Unit Tests
// ============================================================================

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

    #[test]
    fn test_parsed_sql_type_varchar() {
        let t = ParsedSqlType::parse("VARCHAR(255)");
        assert_eq!(t.base_type, "VARCHAR");
        assert_eq!(t.length, Some(255));
        assert_eq!(t.precision, None);
        assert_eq!(t.scale, None);
        assert!(!t.unsigned);
        assert!(!t.array);
    }

    #[test]
    fn test_parsed_sql_type_decimal() {
        let t = ParsedSqlType::parse("DECIMAL(10,2)");
        assert_eq!(t.base_type, "DECIMAL");
        assert_eq!(t.length, None);
        assert_eq!(t.precision, Some(10));
        assert_eq!(t.scale, Some(2));
    }

    #[test]
    fn test_parsed_sql_type_unsigned() {
        let t = ParsedSqlType::parse("INT UNSIGNED");
        assert_eq!(t.base_type, "INT");
        assert!(t.unsigned);
    }

    #[test]
    fn test_parsed_sql_type_array() {
        let t = ParsedSqlType::parse("TEXT[]");
        assert_eq!(t.base_type, "TEXT");
        assert!(t.array);
    }

    #[test]
    fn test_parsed_sql_type_simple() {
        let t = ParsedSqlType::parse("INTEGER");
        assert_eq!(t.base_type, "INTEGER");
        assert_eq!(t.length, None);
        assert!(!t.unsigned);
        assert!(!t.array);
    }

    #[test]
    fn test_parsed_sql_type_is_text() {
        assert!(ParsedSqlType::parse("VARCHAR(100)").is_text());
        assert!(ParsedSqlType::parse("TEXT").is_text());
        assert!(ParsedSqlType::parse("CHAR(1)").is_text());
        assert!(!ParsedSqlType::parse("INTEGER").is_text());
    }

    #[test]
    fn test_parsed_sql_type_is_numeric() {
        assert!(ParsedSqlType::parse("INTEGER").is_numeric());
        assert!(ParsedSqlType::parse("BIGINT").is_numeric());
        assert!(ParsedSqlType::parse("DECIMAL(10,2)").is_numeric());
        assert!(!ParsedSqlType::parse("TEXT").is_numeric());
    }

    #[test]
    fn test_parsed_sql_type_is_datetime() {
        assert!(ParsedSqlType::parse("DATE").is_datetime());
        assert!(ParsedSqlType::parse("TIMESTAMP").is_datetime());
        assert!(ParsedSqlType::parse("TIMESTAMPTZ").is_datetime());
        assert!(!ParsedSqlType::parse("TEXT").is_datetime());
    }

    #[test]
    fn test_database_schema_new() {
        let schema = DatabaseSchema::new(Dialect::Postgres);
        assert_eq!(schema.dialect, Dialect::Postgres);
        assert!(schema.tables.is_empty());
    }

    #[test]
    fn test_table_info_column() {
        let table = TableInfo {
            name: "test".to_string(),
            columns: vec![ColumnInfo {
                name: "id".to_string(),
                sql_type: "INTEGER".to_string(),
                parsed_type: ParsedSqlType::parse("INTEGER"),
                nullable: false,
                default: None,
                primary_key: true,
                auto_increment: true,
                comment: None,
            }],
            primary_key: vec!["id".to_string()],
            foreign_keys: Vec::new(),
            unique_constraints: Vec::new(),
            check_constraints: Vec::new(),
            indexes: Vec::new(),
            comment: None,
        };

        assert!(table.column("id").is_some());
        assert!(table.column("nonexistent").is_none());
        assert!(table.has_auto_pk());
    }

    #[test]
    fn test_build_postgres_type_array() {
        let result = build_postgres_type("ARRAY", "_text", None, None, None);
        assert_eq!(result, "text[]");
    }

    #[test]
    fn test_build_postgres_type_varchar() {
        let result = build_postgres_type("character varying", "", Some(100), None, None);
        assert_eq!(result, "CHARACTER VARYING(100)");
    }

    #[test]
    fn test_build_postgres_type_numeric() {
        let result = build_postgres_type("numeric", "", None, Some(10), Some(2));
        assert_eq!(result, "NUMERIC(10,2)");
    }

    #[test]
    fn test_sanitize_identifier_normal() {
        assert_eq!(sanitize_identifier("users"), "users");
        assert_eq!(sanitize_identifier("my_table"), "my_table");
        assert_eq!(sanitize_identifier("Table123"), "Table123");
    }

    #[test]
    fn test_sanitize_identifier_sql_injection() {
        // SQL injection attempts should be sanitized
        assert_eq!(sanitize_identifier("users; DROP TABLE--"), "usersDROPTABLE");
        assert_eq!(sanitize_identifier("table`; malicious"), "tablemalicious");
        assert_eq!(sanitize_identifier("users'--"), "users");
        assert_eq!(
            sanitize_identifier("table\"); DROP TABLE users;--"),
            "tableDROPTABLEusers"
        );
    }

    #[test]
    fn test_sanitize_identifier_special_chars() {
        // Various special characters should be stripped
        assert_eq!(sanitize_identifier("table-name"), "tablename");
        assert_eq!(sanitize_identifier("table.name"), "tablename");
        assert_eq!(sanitize_identifier("table name"), "tablename");
        assert_eq!(sanitize_identifier("table\nname"), "tablename");
    }

    #[test]
    fn test_quote_sqlite_identifier_preserves_special_chars() {
        assert_eq!(quote_sqlite_identifier("my table"), "\"my table\"");
        assert_eq!(quote_sqlite_identifier("my\"table"), "\"my\"\"table\"");
    }

    #[test]
    fn test_quote_mysql_identifier_preserves_special_chars() {
        assert_eq!(quote_mysql_identifier("my-table"), "`my-table`");
        assert_eq!(quote_mysql_identifier("my`table"), "`my``table`");
    }

    #[test]
    fn test_normalize_check_expression_wrapped_check() {
        assert_eq!(
            normalize_check_expression("CHECK ((age >= 0) AND (age <= 150))"),
            "(age >= 0) AND (age <= 150)"
        );
    }

    #[test]
    fn test_normalize_check_expression_raw_clause() {
        assert_eq!(normalize_check_expression("(score > 0)"), "(score > 0)");
    }

    #[test]
    fn test_normalize_check_expression_with_quoted_commas() {
        assert_eq!(
            normalize_check_expression("CHECK (kind IN ('A,B', 'C'))"),
            "kind IN ('A,B', 'C')"
        );
    }

    #[test]
    fn test_extract_sqlite_check_constraints_named_and_unnamed() {
        let sql = r"
            CREATE TABLE heroes (
                id INTEGER PRIMARY KEY,
                age INTEGER,
                CONSTRAINT age_non_negative CHECK (age >= 0),
                CHECK (age <= 150)
            )
        ";

        let checks = extract_sqlite_check_constraints(sql);
        assert_eq!(checks.len(), 2);
        assert_eq!(checks[0].name.as_deref(), Some("age_non_negative"));
        assert_eq!(checks[0].expression, "age >= 0");
        assert_eq!(checks[1].name, None);
        assert_eq!(checks[1].expression, "age <= 150");
    }

    #[test]
    fn test_extract_sqlite_check_constraints_column_level_and_nested() {
        let sql = r"
            CREATE TABLE heroes (
                age INTEGER CONSTRAINT age_positive CHECK (age > 0),
                score INTEGER CHECK ((score >= 0) AND (score <= 100)),
                level INTEGER CHECK (level > 0) CHECK (level < 10)
            )
        ";

        let checks = extract_sqlite_check_constraints(sql);
        assert_eq!(checks.len(), 4);
        assert_eq!(checks[0].name.as_deref(), Some("age_positive"));
        assert_eq!(checks[0].expression, "age > 0");
        assert_eq!(checks[1].name, None);
        assert_eq!(checks[1].expression, "(score >= 0) AND (score <= 100)");
        assert_eq!(checks[2].expression, "level > 0");
        assert_eq!(checks[3].expression, "level < 10");
    }

    #[test]
    fn test_extract_sqlite_check_constraints_handles_quoted_commas() {
        let sql = r"
            CREATE TABLE heroes (
                kind TEXT CHECK (kind IN ('A,B', 'C')),
                note TEXT
            )
        ";

        let checks = extract_sqlite_check_constraints(sql);
        assert_eq!(checks.len(), 1);
        assert_eq!(checks[0].expression, "kind IN ('A,B', 'C')");
    }
}