tideorm 0.4.5

A developer-friendly ORM for Rust with clean, expressive syntax
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
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
//! Database migration system
//!
//! This module provides a schema migration system for TideORM.
//!
//! ## Features
//!
//! - Create, alter, and drop tables
//! - Add, modify, and remove columns
//! - Create and drop indexes
//! - Track applied migrations in the database
//! - Rollback support
//!
//! ## Example
//!
//! ```rust,ignore
//! use tideorm::prelude::*;
//! use tideorm::migration::*;
//!
//! // Define a migration
//! struct CreateUsersTable;
//!
//! #[async_trait]
//! impl Migration for CreateUsersTable {
//!     fn version(&self) -> &str { "20260106_001" }
//!     fn name(&self) -> &str { "create_users_table" }
//!
//!     async fn up(&self, schema: &mut Schema) -> Result<()> {
//!         schema.create_table("users", |t| {
//!             t.id();
//!             t.string("email").unique();
//!             t.string("name");
//!             t.boolean("active").default(true);
//!             t.timestamps();
//!         }).await
//!     }
//!
//!     async fn down(&self, schema: &mut Schema) -> Result<()> {
//!         schema.drop_table("users").await
//!     }
//! }
//!
//! // Run migrations
//! #[tokio::main]
//! async fn main() -> Result<()> {
//!     TideConfig::init()
//!         .database("postgres://localhost/myapp")
//!         .connect()
//!         .await?;
//!
//!     Migrator::new()
//!         .add(CreateUsersTable)
//!         .run()
//!         .await?;
//!
//!     Ok(())
//! }
//! ```

use std::fmt;

use crate::config::DatabaseType;
use crate::database::{db, Database};
use crate::error::{Error, Result};
use crate::internal::ConnectionTrait;

// Re-export async_trait for users
pub use async_trait::async_trait;

// ============================================================================
// MIGRATION TRAIT
// ============================================================================

/// Trait for defining database migrations
///
/// Implement this trait to create a migration. Each migration must have:
/// - A unique version string (typically a timestamp)
/// - A descriptive name
/// - An `up` method that applies the migration
/// - A `down` method that reverts the migration
///
/// # Example
///
/// ```rust,ignore
/// struct AddEmailVerifiedToUsers;
///
/// #[async_trait]
/// impl Migration for AddEmailVerifiedToUsers {
///     fn version(&self) -> &str { "20260106_002" }
///     fn name(&self) -> &str { "add_email_verified_to_users" }
///
///     async fn up(&self, schema: &mut Schema) -> Result<()> {
///         schema.alter_table("users", |t| {
///             t.add_column("email_verified", ColumnType::Boolean)
///                 .default(false)
///                 .not_null();
///         }).await
///     }
///
///     async fn down(&self, schema: &mut Schema) -> Result<()> {
///         schema.alter_table("users", |t| {
///             t.drop_column("email_verified");
///         }).await
///     }
/// }
/// ```
#[async_trait]
pub trait Migration: Send + Sync {
    /// Unique version identifier for this migration
    ///
    /// Format: `YYYYMMDD_NNN` (e.g., "20260106_001")
    /// Migrations are run in lexicographical order by version.
    fn version(&self) -> &str;

    /// Human-readable name for this migration
    fn name(&self) -> &str;

    /// Apply the migration
    async fn up(&self, schema: &mut Schema) -> Result<()>;

    /// Revert the migration
    async fn down(&self, schema: &mut Schema) -> Result<()>;
}

// ============================================================================
// SCHEMA OPERATIONS
// ============================================================================

/// Schema manipulation context for migrations
///
/// Provides methods to create, alter, and drop database objects.
pub struct Schema {
    database_type: DatabaseType,
    statements: Vec<String>,
}

impl Schema {
    /// Create a new schema context
    pub fn new(database_type: DatabaseType) -> Self {
        Self {
            database_type,
            statements: Vec::new(),
        }
    }

    /// Create a new table
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// schema.create_table("users", |t| {
    ///     t.id();
    ///     t.string("email").unique();
    ///     t.string("name").not_null();
    ///     t.timestamps();
    /// }).await?;
    /// ```
    pub async fn create_table<F>(&mut self, name: &str, f: F) -> Result<()>
    where
        F: FnOnce(&mut TableBuilder),
    {
        let mut builder = TableBuilder::new(name, self.database_type);
        f(&mut builder);
        let sql = builder.build_create();
        self.execute(&sql).await?;

        // Create indexes
        for index_sql in builder.build_indexes() {
            self.execute(&index_sql).await?;
        }

        Ok(())
    }

    /// Create a table if it doesn't exist
    pub async fn create_table_if_not_exists<F>(&mut self, name: &str, f: F) -> Result<()>
    where
        F: FnOnce(&mut TableBuilder),
    {
        let mut builder = TableBuilder::new(name, self.database_type);
        f(&mut builder);
        let sql = builder.build_create_if_not_exists();
        self.execute(&sql).await?;

        // Create indexes (with IF NOT EXISTS)
        for index_sql in builder.build_indexes_if_not_exists() {
            self.execute(&index_sql).await?;
        }

        Ok(())
    }

    /// Alter an existing table
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// schema.alter_table("users", |t| {
    ///     t.add_column("phone", ColumnType::String);
    ///     t.rename_column("name", "full_name");
    ///     t.drop_column("legacy_field");
    /// }).await?;
    /// ```
    pub async fn alter_table<F>(&mut self, name: &str, f: F) -> Result<()>
    where
        F: FnOnce(&mut AlterTableBuilder),
    {
        let mut builder = AlterTableBuilder::new(name, self.database_type);
        f(&mut builder);

        for sql in builder.build() {
            self.execute(&sql).await?;
        }

        Ok(())
    }

    /// Drop a table
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// schema.drop_table("users").await?;
    /// ```
    pub async fn drop_table(&mut self, name: &str) -> Result<()> {
        let sql = format!(
            "DROP TABLE {}",
            self.quote_identifier(name)
        );
        self.execute(&sql).await
    }

    /// Drop a table if it exists
    pub async fn drop_table_if_exists(&mut self, name: &str) -> Result<()> {
        let sql = format!(
            "DROP TABLE IF EXISTS {}",
            self.quote_identifier(name)
        );
        self.execute(&sql).await
    }

    /// Rename a table
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// schema.rename_table("users", "accounts").await?;
    /// ```
    pub async fn rename_table(&mut self, from: &str, to: &str) -> Result<()> {
        let sql = match self.database_type {
            DatabaseType::MySQL => format!(
                "RENAME TABLE {} TO {}",
                self.quote_identifier(from),
                self.quote_identifier(to)
            ),
            _ => format!(
                "ALTER TABLE {} RENAME TO {}",
                self.quote_identifier(from),
                self.quote_identifier(to)
            ),
        };
        self.execute(&sql).await
    }

    /// Create an index
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// schema.create_index("users", "idx_users_email", &["email"], false).await?;
    /// ```
    pub async fn create_index(
        &mut self,
        table: &str,
        name: &str,
        columns: &[&str],
        unique: bool,
    ) -> Result<()> {
        let index_type = if unique { "UNIQUE INDEX" } else { "INDEX" };
        let cols: Vec<String> = columns.iter().map(|c| self.quote_identifier(c)).collect();

        let sql = format!(
            "CREATE {} {} ON {} ({})",
            index_type,
            self.quote_identifier(name),
            self.quote_identifier(table),
            cols.join(", ")
        );
        self.execute(&sql).await
    }

    /// Drop an index
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// schema.drop_index("idx_users_email").await?;
    /// ```
    pub async fn drop_index(&mut self, table: &str, name: &str) -> Result<()> {
        let sql = match self.database_type {
            DatabaseType::MySQL => format!(
                "DROP INDEX {} ON {}",
                self.quote_identifier(name),
                self.quote_identifier(table)
            ),
            _ => format!(
                "DROP INDEX {}",
                self.quote_identifier(name)
            ),
        };
        self.execute(&sql).await
    }

    /// Execute raw SQL
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// schema.raw("CREATE EXTENSION IF NOT EXISTS \"uuid-ossp\"").await?;
    /// ```
    pub async fn raw(&mut self, sql: &str) -> Result<()> {
        self.execute(sql).await
    }

    /// Execute a SQL statement
    async fn execute(&mut self, sql: &str) -> Result<()> {
        log_migration_sql(sql);
        self.statements.push(sql.to_string());

        let db = db();
        db.__internal_connection()
            .execute_unprepared(sql)
            .await
            .map_err(|e| Error::query_with_context(
                e.to_string(),
                crate::error::ErrorContext::new().query(sql.to_string()),
            ))?;

        Ok(())
    }

    /// Quote an identifier for the current database type
    fn quote_identifier(&self, name: &str) -> String {
        match self.database_type {
            DatabaseType::Postgres | DatabaseType::SQLite => format!("\"{}\"", name),
            DatabaseType::MySQL => format!("`{}`", name),
        }
    }

    /// Get the database type
    pub fn database_type(&self) -> DatabaseType {
        self.database_type
    }
}

// ============================================================================
// TABLE BUILDER
// ============================================================================

/// Definition of a composite unique constraint
#[derive(Debug, Clone)]
pub struct UniqueConstraint {
    /// Optional name for the constraint
    pub name: Option<String>,
    /// Columns that form the unique constraint
    pub columns: Vec<String>,
}

/// Definition of a composite primary key
#[derive(Debug, Clone)]
pub struct CompositePrimaryKey {
    /// Columns that form the composite primary key
    pub columns: Vec<String>,
}

/// Builder for creating tables
pub struct TableBuilder {
    name: String,
    database_type: DatabaseType,
    columns: Vec<ColumnDefinition>,
    indexes: Vec<IndexBuilder>,
    primary_key: Option<String>,
    /// Multi-column unique constraints
    unique_constraints: Vec<UniqueConstraint>,
    /// Composite primary key support
    composite_primary_key: Option<CompositePrimaryKey>,
}

impl TableBuilder {
    /// Create a new table builder
    pub fn new(name: &str, database_type: DatabaseType) -> Self {
        Self {
            name: name.to_string(),
            database_type,
            columns: Vec::new(),
            indexes: Vec::new(),
            primary_key: None,
            unique_constraints: Vec::new(),
            composite_primary_key: None,
        }
    }

    /// Add an auto-incrementing primary key column named "id"
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// t.id();  // Creates: id BIGSERIAL PRIMARY KEY
    /// ```
    pub fn id(&mut self) -> &mut Self {
        self.big_increments("id")
    }

    /// Add an auto-incrementing big integer column
    pub fn big_increments(&mut self, name: &str) -> &mut Self {
        let col = ColumnDefinition {
            name: name.to_string(),
            column_type: ColumnType::BigInteger,
            nullable: false,
            default: None,
            primary_key: true,
            auto_increment: true,
            unique: false,
            check: None,
            extra: None,
        };
        self.columns.push(col);
        self.primary_key = Some(name.to_string());
        self
    }

    /// Add an auto-incrementing integer column
    pub fn increments(&mut self, name: &str) -> &mut Self {
        let col = ColumnDefinition {
            name: name.to_string(),
            column_type: ColumnType::Integer,
            nullable: false,
            default: None,
            primary_key: true,
            auto_increment: true,
            unique: false,
            check: None,
            extra: None,
        };
        self.columns.push(col);
        self.primary_key = Some(name.to_string());
        self
    }

    /// Add a string column (VARCHAR/TEXT)
    pub fn string(&mut self, name: &str) -> ColumnBuilder<'_> {
        self.column(name, ColumnType::String)
    }

    /// Add a text column (TEXT)
    pub fn text(&mut self, name: &str) -> ColumnBuilder<'_> {
        self.column(name, ColumnType::Text)
    }

    /// Add an integer column
    pub fn integer(&mut self, name: &str) -> ColumnBuilder<'_> {
        self.column(name, ColumnType::Integer)
    }

    /// Add a big integer column
    pub fn big_integer(&mut self, name: &str) -> ColumnBuilder<'_> {
        self.column(name, ColumnType::BigInteger)
    }

    /// Add a small integer column
    pub fn small_integer(&mut self, name: &str) -> ColumnBuilder<'_> {
        self.column(name, ColumnType::SmallInteger)
    }

    /// Add a decimal column
    pub fn decimal(&mut self, name: &str) -> ColumnBuilder<'_> {
        self.column(name, ColumnType::Decimal { precision: 10, scale: 2 })
    }

    /// Add a decimal column with precision and scale
    pub fn decimal_with(&mut self, name: &str, precision: u32, scale: u32) -> ColumnBuilder<'_> {
        self.column(name, ColumnType::Decimal { precision, scale })
    }

    /// Add a float column
    pub fn float(&mut self, name: &str) -> ColumnBuilder<'_> {
        self.column(name, ColumnType::Float)
    }

    /// Add a double column
    pub fn double(&mut self, name: &str) -> ColumnBuilder<'_> {
        self.column(name, ColumnType::Double)
    }

    /// Add a boolean column
    pub fn boolean(&mut self, name: &str) -> ColumnBuilder<'_> {
        self.column(name, ColumnType::Boolean)
    }

    /// Add a date column
    pub fn date(&mut self, name: &str) -> ColumnBuilder<'_> {
        self.column(name, ColumnType::Date)
    }

    /// Add a time column
    pub fn time(&mut self, name: &str) -> ColumnBuilder<'_> {
        self.column(name, ColumnType::Time)
    }

    /// Add a datetime/timestamp column
    pub fn datetime(&mut self, name: &str) -> ColumnBuilder<'_> {
        self.column(name, ColumnType::DateTime)
    }

    /// Add a timestamp column (without time zone)
    /// 
    /// Use this for `chrono::NaiveDateTime` fields.
    pub fn timestamp(&mut self, name: &str) -> ColumnBuilder<'_> {
        self.column(name, ColumnType::Timestamp)
    }

    /// Add a timestamp with time zone column (TIMESTAMPTZ)
    /// 
    /// Use this for `chrono::DateTime<Utc>` fields in PostgreSQL.
    /// For MySQL, this falls back to TIMESTAMP.
    /// 
    /// # Example
    ///
    /// ```rust,ignore
    /// t.timestamptz("expires_at").not_null();
    /// t.timestamptz("created_at").default_now();
    /// ```
    pub fn timestamptz(&mut self, name: &str) -> ColumnBuilder<'_> {
        self.column(name, ColumnType::TimestampTz)
    }

    /// Add created_at and updated_at timestamp columns with time zone
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// t.timestamps();  // Adds created_at and updated_at columns (TIMESTAMPTZ for PostgreSQL)
    /// ```
    pub fn timestamps(&mut self) -> &mut Self {
        self.column("created_at", ColumnType::TimestampTz)
            .default_now()
            .not_null();
        self.column("updated_at", ColumnType::TimestampTz)
            .default_now()
            .not_null();
        self
    }

    /// Add created_at and updated_at timestamp columns (without time zone)
    /// 
    /// Use this for `chrono::NaiveDateTime` fields.
    pub fn timestamps_naive(&mut self) -> &mut Self {
        self.column("created_at", ColumnType::Timestamp)
            .default_now()
            .not_null();
        self.column("updated_at", ColumnType::Timestamp)
            .default_now()
            .not_null();
        self
    }

    /// Add a soft delete column (deleted_at)
    pub fn soft_deletes(&mut self) -> &mut Self {
        self.column("deleted_at", ColumnType::TimestampTz).nullable();
        self
    }

    /// Add a UUID column
    pub fn uuid(&mut self, name: &str) -> ColumnBuilder<'_> {
        self.column(name, ColumnType::Uuid)
    }

    /// Add a JSON column
    pub fn json(&mut self, name: &str) -> ColumnBuilder<'_> {
        self.column(name, ColumnType::Json)
    }

    /// Add a JSONB column (PostgreSQL)
    pub fn jsonb(&mut self, name: &str) -> ColumnBuilder<'_> {
        self.column(name, ColumnType::Jsonb)
    }

    /// Add a binary/blob column
    pub fn binary(&mut self, name: &str) -> ColumnBuilder<'_> {
        self.column(name, ColumnType::Binary)
    }

    /// Add an integer array column (PostgreSQL)
    pub fn integer_array(&mut self, name: &str) -> ColumnBuilder<'_> {
        self.column(name, ColumnType::IntegerArray)
    }

    /// Add a text array column (PostgreSQL)
    pub fn text_array(&mut self, name: &str) -> ColumnBuilder<'_> {
        self.column(name, ColumnType::TextArray)
    }

    /// Add a generic column with a specific type
    pub fn column(&mut self, name: &str, column_type: ColumnType) -> ColumnBuilder<'_> {
        ColumnBuilder {
            table: self,
            definition: ColumnDefinition {
                name: name.to_string(),
                column_type,
                nullable: true,
                default: None,
                primary_key: false,
                auto_increment: false,
                unique: false,
                check: None,
                extra: None,
            },
        }
    }

    /// Add a foreign key column (bigint)
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// t.foreign_id("user_id");  // Creates: user_id BIGINT
    /// ```
    pub fn foreign_id(&mut self, name: &str) -> ColumnBuilder<'_> {
        self.column(name, ColumnType::BigInteger)
    }

    /// Add an index on one or more columns
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// t.index(&["email"]);
    /// t.index(&["first_name", "last_name"]);
    /// ```
    pub fn index(&mut self, columns: &[&str]) -> &mut Self {
        let idx = IndexBuilder {
            name: format!("idx_{}_{}", self.name, columns.join("_")),
            columns: columns.iter().map(|s| s.to_string()).collect(),
            unique: false,
        };
        self.indexes.push(idx);
        self
    }

    /// Add a unique index on one or more columns
    pub fn unique_index(&mut self, columns: &[&str]) -> &mut Self {
        let idx = IndexBuilder {
            name: format!("idx_{}_{}_unique", self.name, columns.join("_")),
            columns: columns.iter().map(|s| s.to_string()).collect(),
            unique: true,
        };
        self.indexes.push(idx);
        self
    }

    /// Add a multi-column unique constraint
    ///
    /// Unlike `unique_index`, this creates an inline UNIQUE constraint in the
    /// CREATE TABLE statement rather than a separate CREATE UNIQUE INDEX.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// t.unique(&["email", "tenant_id"]);
    /// // Generates: UNIQUE ("email", "tenant_id")
    /// ```
    pub fn unique(&mut self, columns: &[&str]) -> &mut Self {
        self.unique_constraints.push(UniqueConstraint {
            name: None,
            columns: columns.iter().map(|s| s.to_string()).collect(),
        });
        self
    }

    /// Add a named multi-column unique constraint 
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// t.unique_named("uq_user_email_tenant", &["email", "tenant_id"]);
    /// // Generates: CONSTRAINT "uq_user_email_tenant" UNIQUE ("email", "tenant_id")
    /// ```
    pub fn unique_named(&mut self, name: &str, columns: &[&str]) -> &mut Self {
        self.unique_constraints.push(UniqueConstraint {
            name: Some(name.to_string()),
            columns: columns.iter().map(|s| s.to_string()).collect(),
        });
        self
    }

    /// Set a composite primary key on multiple columns 
    ///
    /// This is useful for junction tables or tables with natural composite keys.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// t.primary_key(&["user_id", "role_id"]);
    /// // Generates: PRIMARY KEY ("user_id", "role_id")
    /// ```
    pub fn primary_key(&mut self, columns: &[&str]) -> &mut Self {
        self.composite_primary_key = Some(CompositePrimaryKey {
            columns: columns.iter().map(|s| s.to_string()).collect(),
        });
        self
    }

    /// Add a named index
    pub fn index_named(&mut self, name: &str, columns: &[&str]) -> &mut Self {
        let idx = IndexBuilder {
            name: name.to_string(),
            columns: columns.iter().map(|s| s.to_string()).collect(),
            unique: false,
        };
        self.indexes.push(idx);
        self
    }

    /// Build the CREATE TABLE SQL statement
    fn build_create(&self) -> String {
        self.build_create_internal(false)
    }

    /// Build the CREATE TABLE IF NOT EXISTS SQL statement
    fn build_create_if_not_exists(&self) -> String {
        self.build_create_internal(true)
    }

    fn build_create_internal(&self, if_not_exists: bool) -> String {
        let exists_clause = if if_not_exists { "IF NOT EXISTS " } else { "" };
        let mut sql = format!(
            "CREATE TABLE {}{} (\n",
            exists_clause,
            self.quote_identifier(&self.name)
        );

        let column_defs: Vec<String> = self
            .columns
            .iter()
            .map(|col| self.build_column_def(col))
            .collect();

        sql.push_str(&column_defs.join(",\n"));

        // Add primary key constraint if specified (single column)
        if let Some(ref pk) = self.primary_key {
            sql.push_str(",\n");
            sql.push_str(&format!(
                "    PRIMARY KEY ({})",
                self.quote_identifier(pk)
            ));
        }

        // Add composite primary key if specified 
        if let Some(ref cpk) = self.composite_primary_key {
            sql.push_str(",\n");
            let cols: Vec<String> = cpk
                .columns
                .iter()
                .map(|c| self.quote_identifier(c))
                .collect();
            sql.push_str(&format!("    PRIMARY KEY ({})", cols.join(", ")));
        }

        // Add unique constraints
        for uc in &self.unique_constraints {
            sql.push_str(",\n");
            let cols: Vec<String> = uc
                .columns
                .iter()
                .map(|c| self.quote_identifier(c))
                .collect();
            if let Some(ref name) = uc.name {
                sql.push_str(&format!(
                    "    CONSTRAINT {} UNIQUE ({})",
                    self.quote_identifier(name),
                    cols.join(", ")
                ));
            } else {
                sql.push_str(&format!("    UNIQUE ({})", cols.join(", ")));
            }
        }

        sql.push_str("\n)");
        sql
    }

    /// Build column definition SQL
    fn build_column_def(&self, col: &ColumnDefinition) -> String {
        let mut def = format!(
            "    {} {}",
            self.quote_identifier(&col.name),
            self.type_to_sql(&col.column_type)
        );

        // Handle auto-increment
        if col.auto_increment {
            match self.database_type {
                DatabaseType::Postgres => {
                    // Replace type with SERIAL/BIGSERIAL
                    def = match col.column_type {
                        ColumnType::Integer => format!(
                            "    {} SERIAL",
                            self.quote_identifier(&col.name)
                        ),
                        _ => format!(
                            "    {} BIGSERIAL",
                            self.quote_identifier(&col.name)
                        ),
                    };
                }
                DatabaseType::MySQL => {
                    def.push_str(" AUTO_INCREMENT");
                }
                DatabaseType::SQLite => {
                    // SQLite auto-increments INTEGER PRIMARY KEY automatically
                }
            }
        }

        // NOT NULL
        if !col.nullable && !col.primary_key {
            def.push_str(" NOT NULL");
        }

        // DEFAULT
        if let Some(ref default) = col.default {
            def.push_str(&format!(" DEFAULT {}", default));
        }

        // UNIQUE (handled separately from indexes)
        if col.unique && !col.primary_key {
            def.push_str(" UNIQUE");
        }
        
        // CHECK constraint
        if let Some(ref check_expr) = col.check {
            def.push_str(&format!(" CHECK ({})", check_expr));
        }
        
        // Extra SQL
        if let Some(ref extra_sql) = col.extra {
            def.push_str(&format!(" {}", extra_sql));
        }

        def
    }

    /// Build CREATE INDEX statements
    fn build_indexes(&self) -> Vec<String> {
        self.build_indexes_internal(false)
    }

    /// Build CREATE INDEX IF NOT EXISTS statements
    fn build_indexes_if_not_exists(&self) -> Vec<String> {
        self.build_indexes_internal(true)
    }

    fn build_indexes_internal(&self, if_not_exists: bool) -> Vec<String> {
        let exists_clause = if if_not_exists { "IF NOT EXISTS " } else { "" };
        self.indexes
            .iter()
            .map(|idx| {
                let index_type = if idx.unique { "UNIQUE INDEX" } else { "INDEX" };
                let cols: Vec<String> = idx
                    .columns
                    .iter()
                    .map(|c| self.quote_identifier(c))
                    .collect();

                format!(
                    "CREATE {} {}{} ON {} ({})",
                    index_type,
                    exists_clause,
                    self.quote_identifier(&idx.name),
                    self.quote_identifier(&self.name),
                    cols.join(", ")
                )
            })
            .collect()
    }

    /// Convert column type to SQL type string
    fn type_to_sql(&self, column_type: &ColumnType) -> String {
        match self.database_type {
            DatabaseType::Postgres => column_type.to_postgres_sql(),
            DatabaseType::MySQL => column_type.to_mysql_sql(),
            DatabaseType::SQLite => column_type.to_sqlite_sql(),
        }
    }

    /// Quote an identifier
    fn quote_identifier(&self, name: &str) -> String {
        match self.database_type {
            DatabaseType::Postgres | DatabaseType::SQLite => format!("\"{}\"", name),
            DatabaseType::MySQL => format!("`{}`", name),
        }
    }
}

// ============================================================================
// COLUMN BUILDER
// ============================================================================

/// Builder for column definitions (fluent API)
pub struct ColumnBuilder<'a> {
    table: &'a mut TableBuilder,
    definition: ColumnDefinition,
}

impl<'a> ColumnBuilder<'a> {
    /// Mark the column as NOT NULL
    pub fn not_null(mut self) -> Self {
        self.definition.nullable = false;
        self
    }

    /// Mark the column as nullable
    pub fn nullable(mut self) -> Self {
        self.definition.nullable = true;
        self
    }

    /// Set a default value
    pub fn default(mut self, value: impl Into<DefaultValue>) -> Self {
        self.definition.default = Some(value.into().to_sql());
        self
    }

    /// Set default to current timestamp
    pub fn default_now(mut self) -> Self {
        self.definition.default = Some("CURRENT_TIMESTAMP".to_string());
        self
    }

    /// Mark the column as unique
    pub fn unique(mut self) -> Self {
        self.definition.unique = true;
        self
    }

    /// Mark as primary key
    pub fn primary_key(mut self) -> Self {
        self.definition.primary_key = true;
        self.definition.nullable = false;
        self.table.primary_key = Some(self.definition.name.clone());
        self
    }
    
    /// Add a CHECK constraint to the column
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// t.integer("price").check("price > 0");
    /// t.integer("quantity").check("quantity >= 0 AND quantity <= 1000");
    /// t.string("status", 50).check("status IN ('active', 'pending', 'inactive')");
    /// ```
    pub fn check(mut self, expression: &str) -> Self {
        self.definition.check = Some(expression.to_string());
        self
    }
    
    /// Add extra SQL to the column definition
    ///
    /// This allows adding arbitrary SQL after the column definition.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// t.integer("version").extra("GENERATED ALWAYS AS IDENTITY");
    /// t.string("code", 10).extra("COLLATE utf8mb4_unicode_ci");
    /// ```
    pub fn extra(mut self, sql: &str) -> Self {
        self.definition.extra = Some(sql.to_string());
        self
    }
}

impl<'a> Drop for ColumnBuilder<'a> {
    fn drop(&mut self) {
        // Move the definition to the table
        let def = std::mem::replace(
            &mut self.definition,
            ColumnDefinition {
                name: String::new(),
                column_type: ColumnType::String,
                nullable: true,
                default: None,
                primary_key: false,
                auto_increment: false,
                unique: false,
                check: None,
                extra: None,
            },
        );
        if !def.name.is_empty() {
            self.table.columns.push(def);
        }
    }
}

// ============================================================================
// ALTER TABLE BUILDER
// ============================================================================

/// Builder for ALTER TABLE operations
pub struct AlterTableBuilder {
    name: String,
    database_type: DatabaseType,
    operations: Vec<AlterOperation>,
}

impl AlterTableBuilder {
    /// Create a new alter table builder
    pub fn new(name: &str, database_type: DatabaseType) -> Self {
        Self {
            name: name.to_string(),
            database_type,
            operations: Vec::new(),
        }
    }

    /// Add a new column
    pub fn add_column(&mut self, name: &str, column_type: ColumnType) -> AlterColumnBuilder<'_> {
        AlterColumnBuilder {
            builder: self,
            definition: ColumnDefinition {
                name: name.to_string(),
                column_type,
                nullable: true,
                default: None,
                primary_key: false,
                auto_increment: false,
                unique: false,
                check: None,
                extra: None,
            },
        }
    }

    /// Drop a column
    pub fn drop_column(&mut self, name: &str) -> &mut Self {
        self.operations.push(AlterOperation::DropColumn(name.to_string()));
        self
    }

    /// Rename a column
    pub fn rename_column(&mut self, from: &str, to: &str) -> &mut Self {
        self.operations.push(AlterOperation::RenameColumn(
            from.to_string(),
            to.to_string(),
        ));
        self
    }

    /// Change column type
    pub fn change_column(&mut self, name: &str, column_type: ColumnType) -> &mut Self {
        self.operations.push(AlterOperation::ChangeColumnType(
            name.to_string(),
            column_type,
        ));
        self
    }

    /// Add an index
    pub fn add_index(&mut self, name: &str, columns: &[&str], unique: bool) -> &mut Self {
        self.operations.push(AlterOperation::AddIndex(IndexBuilder {
            name: name.to_string(),
            columns: columns.iter().map(|s| s.to_string()).collect(),
            unique,
        }));
        self
    }

    /// Drop an index
    pub fn drop_index(&mut self, name: &str) -> &mut Self {
        self.operations.push(AlterOperation::DropIndex(name.to_string()));
        self
    }

    /// Build the ALTER TABLE SQL statements
    fn build(&self) -> Vec<String> {
        self.operations
            .iter()
            .map(|op| self.build_operation(op))
            .collect()
    }

    fn build_operation(&self, op: &AlterOperation) -> String {
        match op {
            AlterOperation::AddColumn(col) => {
                let col_def = self.build_column_def(col);
                format!(
                    "ALTER TABLE {} ADD COLUMN {}",
                    self.quote_identifier(&self.name),
                    col_def.trim()
                )
            }
            AlterOperation::DropColumn(name) => {
                format!(
                    "ALTER TABLE {} DROP COLUMN {}",
                    self.quote_identifier(&self.name),
                    self.quote_identifier(name)
                )
            }
            AlterOperation::RenameColumn(from, to) => match self.database_type {
                DatabaseType::Postgres | DatabaseType::SQLite => {
                    format!(
                        "ALTER TABLE {} RENAME COLUMN {} TO {}",
                        self.quote_identifier(&self.name),
                        self.quote_identifier(from),
                        self.quote_identifier(to)
                    )
                }
                DatabaseType::MySQL => {
                    // MySQL requires the column type in CHANGE
                    format!(
                        "ALTER TABLE {} RENAME COLUMN {} TO {}",
                        self.quote_identifier(&self.name),
                        self.quote_identifier(from),
                        self.quote_identifier(to)
                    )
                }
            },
            AlterOperation::ChangeColumnType(name, column_type) => {
                let type_sql = self.type_to_sql(column_type);
                match self.database_type {
                    DatabaseType::Postgres => {
                        format!(
                            "ALTER TABLE {} ALTER COLUMN {} TYPE {}",
                            self.quote_identifier(&self.name),
                            self.quote_identifier(name),
                            type_sql
                        )
                    }
                    DatabaseType::MySQL => {
                        format!(
                            "ALTER TABLE {} MODIFY COLUMN {} {}",
                            self.quote_identifier(&self.name),
                            self.quote_identifier(name),
                            type_sql
                        )
                    }
                    DatabaseType::SQLite => {
                        // SQLite doesn't support ALTER COLUMN TYPE directly
                        // Would need to recreate the table
                        format!(
                            "-- SQLite does not support ALTER COLUMN TYPE; table recreation needed for {}",
                            name
                        )
                    }
                }
            }
            AlterOperation::AddIndex(idx) => {
                let index_type = if idx.unique { "UNIQUE INDEX" } else { "INDEX" };
                let cols: Vec<String> = idx
                    .columns
                    .iter()
                    .map(|c| self.quote_identifier(c))
                    .collect();

                format!(
                    "CREATE {} {} ON {} ({})",
                    index_type,
                    self.quote_identifier(&idx.name),
                    self.quote_identifier(&self.name),
                    cols.join(", ")
                )
            }
            AlterOperation::DropIndex(name) => match self.database_type {
                DatabaseType::MySQL => {
                    format!(
                        "DROP INDEX {} ON {}",
                        self.quote_identifier(name),
                        self.quote_identifier(&self.name)
                    )
                }
                _ => {
                    format!("DROP INDEX {}", self.quote_identifier(name))
                }
            },
        }
    }

    fn build_column_def(&self, col: &ColumnDefinition) -> String {
        let mut def = format!(
            "{} {}",
            self.quote_identifier(&col.name),
            self.type_to_sql(&col.column_type)
        );

        if !col.nullable {
            def.push_str(" NOT NULL");
        }

        if let Some(ref default) = col.default {
            def.push_str(&format!(" DEFAULT {}", default));
        }

        if col.unique {
            def.push_str(" UNIQUE");
        }

        def
    }

    fn type_to_sql(&self, column_type: &ColumnType) -> String {
        match self.database_type {
            DatabaseType::Postgres => column_type.to_postgres_sql(),
            DatabaseType::MySQL => column_type.to_mysql_sql(),
            DatabaseType::SQLite => column_type.to_sqlite_sql(),
        }
    }

    fn quote_identifier(&self, name: &str) -> String {
        match self.database_type {
            DatabaseType::Postgres | DatabaseType::SQLite => format!("\"{}\"", name),
            DatabaseType::MySQL => format!("`{}`", name),
        }
    }
}

/// Builder for adding columns in ALTER TABLE
pub struct AlterColumnBuilder<'a> {
    builder: &'a mut AlterTableBuilder,
    definition: ColumnDefinition,
}

impl<'a> AlterColumnBuilder<'a> {
    /// Mark as NOT NULL
    pub fn not_null(mut self) -> Self {
        self.definition.nullable = false;
        self
    }

    /// Mark as nullable
    pub fn nullable(mut self) -> Self {
        self.definition.nullable = true;
        self
    }

    /// Set default value
    pub fn default(mut self, value: impl Into<DefaultValue>) -> Self {
        self.definition.default = Some(value.into().to_sql());
        self
    }

    /// Set default to current timestamp
    pub fn default_now(mut self) -> Self {
        self.definition.default = Some("CURRENT_TIMESTAMP".to_string());
        self
    }

    /// Mark as unique
    pub fn unique(mut self) -> Self {
        self.definition.unique = true;
        self
    }
}

impl<'a> Drop for AlterColumnBuilder<'a> {
    fn drop(&mut self) {
        let def = std::mem::replace(
            &mut self.definition,
            ColumnDefinition {
                name: String::new(),
                column_type: ColumnType::String,
                nullable: true,
                default: None,
                primary_key: false,
                auto_increment: false,
                unique: false,
                check: None,
                extra: None,
            },
        );
        if !def.name.is_empty() {
            self.builder.operations.push(AlterOperation::AddColumn(def));
        }
    }
}

// ============================================================================
// COLUMN TYPES
// ============================================================================

/// Supported column types for migrations
#[derive(Debug, Clone)]
pub enum ColumnType {
    /// Small integer (2 bytes)
    SmallInteger,
    /// Integer (4 bytes)
    Integer,
    /// Big integer (8 bytes)
    BigInteger,
    /// Single precision float
    Float,
    /// Double precision float
    Double,
    /// Decimal with precision and scale
    Decimal {
        /// Total number of digits
        precision: u32,
        /// Number of digits after decimal point
        scale: u32,
    },
    /// Variable length string
    String,
    /// Text (unlimited length)
    Text,
    /// Boolean
    Boolean,
    /// Date
    Date,
    /// Time
    Time,
    /// DateTime
    DateTime,
    /// Timestamp (without time zone)
    Timestamp,
    /// Timestamp with time zone (PostgreSQL: TIMESTAMPTZ)
    /// Use this for `chrono::DateTime<Utc>` fields
    TimestampTz,
    /// UUID
    Uuid,
    /// JSON
    Json,
    /// JSONB (PostgreSQL)
    Jsonb,
    /// Binary/Blob
    Binary,
    /// Integer array (PostgreSQL)
    IntegerArray,
    /// Text array (PostgreSQL)
    TextArray,
    /// Custom SQL type
    Custom(String),
}

impl ColumnType {
    /// Convert to PostgreSQL SQL type
    pub fn to_postgres_sql(&self) -> String {
        match self {
            ColumnType::SmallInteger => "SMALLINT".to_string(),
            ColumnType::Integer => "INTEGER".to_string(),
            ColumnType::BigInteger => "BIGINT".to_string(),
            ColumnType::Float => "REAL".to_string(),
            ColumnType::Double => "DOUBLE PRECISION".to_string(),
            ColumnType::Decimal { precision, scale } => {
                format!("DECIMAL({}, {})", precision, scale)
            }
            ColumnType::String => "VARCHAR(255)".to_string(),
            ColumnType::Text => "TEXT".to_string(),
            ColumnType::Boolean => "BOOLEAN".to_string(),
            ColumnType::Date => "DATE".to_string(),
            ColumnType::Time => "TIME".to_string(),
            ColumnType::DateTime => "TIMESTAMP".to_string(),
            ColumnType::Timestamp => "TIMESTAMP".to_string(),
            ColumnType::TimestampTz => "TIMESTAMPTZ".to_string(),
            ColumnType::Uuid => "UUID".to_string(),
            ColumnType::Json => "JSON".to_string(),
            ColumnType::Jsonb => "JSONB".to_string(),
            ColumnType::Binary => "BYTEA".to_string(),
            ColumnType::IntegerArray => "INTEGER[]".to_string(),
            ColumnType::TextArray => "TEXT[]".to_string(),
            ColumnType::Custom(s) => s.clone(),
        }
    }

    /// Convert to MySQL SQL type
    pub fn to_mysql_sql(&self) -> String {
        match self {
            ColumnType::SmallInteger => "SMALLINT".to_string(),
            ColumnType::Integer => "INT".to_string(),
            ColumnType::BigInteger => "BIGINT".to_string(),
            ColumnType::Float => "FLOAT".to_string(),
            ColumnType::Double => "DOUBLE".to_string(),
            ColumnType::Decimal { precision, scale } => {
                format!("DECIMAL({}, {})", precision, scale)
            }
            ColumnType::String => "VARCHAR(255)".to_string(),
            ColumnType::Text => "TEXT".to_string(),
            ColumnType::Boolean => "TINYINT(1)".to_string(),
            ColumnType::Date => "DATE".to_string(),
            ColumnType::Time => "TIME".to_string(),
            ColumnType::DateTime => "DATETIME".to_string(),
            ColumnType::Timestamp | ColumnType::TimestampTz => "TIMESTAMP".to_string(), // MySQL doesn't have TIMESTAMPTZ
            ColumnType::Uuid => "CHAR(36)".to_string(),
            ColumnType::Json | ColumnType::Jsonb => "JSON".to_string(),
            ColumnType::Binary => "BLOB".to_string(),
            ColumnType::IntegerArray | ColumnType::TextArray => "JSON".to_string(), // MySQL uses JSON for arrays
            ColumnType::Custom(s) => s.clone(),
        }
    }

    /// Convert to SQLite SQL type
    pub fn to_sqlite_sql(&self) -> String {
        match self {
            ColumnType::SmallInteger
            | ColumnType::Integer
            | ColumnType::BigInteger
            | ColumnType::Boolean => "INTEGER".to_string(),
            ColumnType::Float | ColumnType::Double | ColumnType::Decimal { .. } => {
                "REAL".to_string()
            }
            ColumnType::String
            | ColumnType::Text
            | ColumnType::Uuid
            | ColumnType::Date
            | ColumnType::Time
            | ColumnType::DateTime
            | ColumnType::Timestamp
            | ColumnType::TimestampTz
            | ColumnType::Json
            | ColumnType::Jsonb
            | ColumnType::IntegerArray
            | ColumnType::TextArray => "TEXT".to_string(),
            ColumnType::Binary => "BLOB".to_string(),
            ColumnType::Custom(s) => s.clone(),
        }
    }
}

// ============================================================================
// DEFAULT VALUES
// ============================================================================

/// Default value for columns
#[derive(Debug, Clone)]
pub enum DefaultValue {
    /// String value
    String(String),
    /// Integer value
    Integer(i64),
    /// Float value
    Float(f64),
    /// Boolean value
    Boolean(bool),
    /// Raw SQL expression
    Raw(String),
    /// NULL
    Null,
}

impl DefaultValue {
    /// Convert to SQL representation
    pub fn to_sql(&self) -> String {
        match self {
            DefaultValue::String(s) => format!("'{}'", s.replace('\'', "''")),
            DefaultValue::Integer(i) => i.to_string(),
            DefaultValue::Float(f) => f.to_string(),
            DefaultValue::Boolean(b) => {
                if *b {
                    "TRUE".to_string()
                } else {
                    "FALSE".to_string()
                }
            }
            DefaultValue::Raw(s) => s.clone(),
            DefaultValue::Null => "NULL".to_string(),
        }
    }
}

impl From<&str> for DefaultValue {
    fn from(s: &str) -> Self {
        DefaultValue::String(s.to_string())
    }
}

impl From<String> for DefaultValue {
    fn from(s: String) -> Self {
        DefaultValue::String(s)
    }
}

impl From<i32> for DefaultValue {
    fn from(i: i32) -> Self {
        DefaultValue::Integer(i as i64)
    }
}

impl From<i64> for DefaultValue {
    fn from(i: i64) -> Self {
        DefaultValue::Integer(i)
    }
}

impl From<f64> for DefaultValue {
    fn from(f: f64) -> Self {
        DefaultValue::Float(f)
    }
}

impl From<bool> for DefaultValue {
    fn from(b: bool) -> Self {
        DefaultValue::Boolean(b)
    }
}

// ============================================================================
// INTERNAL TYPES
// ============================================================================

/// Internal column definition
#[derive(Debug, Clone)]
struct ColumnDefinition {
    name: String,
    column_type: ColumnType,
    nullable: bool,
    default: Option<String>,
    primary_key: bool,
    auto_increment: bool,
    unique: bool,
    /// CHECK constraint expression
    check: Option<String>,
    /// Extra SQL to append
    extra: Option<String>,
}

/// Internal index definition
#[derive(Debug, Clone)]
struct IndexBuilder {
    name: String,
    columns: Vec<String>,
    unique: bool,
}

/// ALTER TABLE operations
#[derive(Debug, Clone)]
enum AlterOperation {
    AddColumn(ColumnDefinition),
    DropColumn(String),
    RenameColumn(String, String),
    ChangeColumnType(String, ColumnType),
    AddIndex(IndexBuilder),
    DropIndex(String),
}

// ============================================================================
// MIGRATOR
// ============================================================================

/// Migration runner
///
/// Manages and executes database migrations.
///
/// # Example
///
/// ```rust,ignore
/// Migrator::new()
///     .add(CreateUsersTable)
///     .add(CreatePostsTable)
///     .add(AddEmailVerifiedToUsers)
///     .run()
///     .await?;
/// ```
pub struct Migrator {
    migrations: Vec<Box<dyn Migration>>,
}

impl Migrator {
    /// Create a new migrator
    pub fn new() -> Self {
        Self {
            migrations: Vec::new(),
        }
    }

    /// Add a migration
    pub fn add<M: Migration + 'static>(mut self, migration: M) -> Self {
        self.migrations.push(Box::new(migration));
        self
    }
    
    /// Add a boxed migration (used internally by TideConfig)
    #[doc(hidden)]
    pub fn add_boxed(mut self, migration: Box<dyn Migration>) -> Self {
        self.migrations.push(migration);
        self
    }

    /// Run all pending migrations
    pub async fn run(&self) -> Result<MigrationResult> {
        self.ensure_migrations_table().await?;

        let applied = self.get_applied_migrations().await?;
        let mut result = MigrationResult::new();

        let db = db();
        let db_type = detect_database_type(db);

        // Sort migrations by version
        let mut migrations: Vec<_> = self.migrations.iter().collect();
        migrations.sort_by_key(|m| m.version());

        for migration in migrations {
            let version = migration.version();

            if applied.contains(&version.to_string()) {
                result.skipped.push(MigrationInfo {
                    version: version.to_string(),
                    name: migration.name().to_string(),
                });
                continue;
            }

            log_migration_start(version, migration.name());

            let mut schema = Schema::new(db_type);
            migration.up(&mut schema).await?;

            // Record migration
            self.record_migration(version, migration.name()).await?;

            result.applied.push(MigrationInfo {
                version: version.to_string(),
                name: migration.name().to_string(),
            });

            log_migration_complete(version, migration.name());
        }

        Ok(result)
    }

    /// Rollback the last migration
    pub async fn rollback(&self) -> Result<MigrationResult> {
        self.ensure_migrations_table().await?;

        let applied = self.get_applied_migrations().await?;
        let mut result = MigrationResult::new();

        if applied.is_empty() {
            return Ok(result);
        }

        // Get the last applied migration version
        let last_version = applied.last().unwrap();

        let db = db();
        let db_type = detect_database_type(db);

        // Find the migration
        for migration in &self.migrations {
            if migration.version() == last_version {
                log_migration_rollback(last_version, migration.name());

                let mut schema = Schema::new(db_type);
                migration.down(&mut schema).await?;

                // Remove migration record
                self.remove_migration_record(last_version).await?;

                result.rolled_back.push(MigrationInfo {
                    version: migration.version().to_string(),
                    name: migration.name().to_string(),
                });

                break;
            }
        }

        Ok(result)
    }

    /// Rollback multiple migrations
    pub async fn rollback_steps(&self, steps: usize) -> Result<MigrationResult> {
        let mut result = MigrationResult::new();

        for _ in 0..steps {
            let step_result = self.rollback().await?;
            if step_result.rolled_back.is_empty() {
                break;
            }
            result.rolled_back.extend(step_result.rolled_back);
        }

        Ok(result)
    }

    /// Reset all migrations (rollback all)
    pub async fn reset(&self) -> Result<MigrationResult> {
        let applied = self.get_applied_migrations().await?;
        self.rollback_steps(applied.len()).await
    }

    /// Refresh migrations (reset + run)
    pub async fn refresh(&self) -> Result<MigrationResult> {
        let reset_result = self.reset().await?;
        let run_result = self.run().await?;

        Ok(MigrationResult {
            applied: run_result.applied,
            skipped: run_result.skipped,
            rolled_back: reset_result.rolled_back,
        })
    }

    /// Get migration status
    pub async fn status(&self) -> Result<Vec<MigrationStatus>> {
        self.ensure_migrations_table().await?;

        let applied = self.get_applied_migrations().await?;
        let mut status = Vec::new();

        let mut migrations: Vec<_> = self.migrations.iter().collect();
        migrations.sort_by_key(|m| m.version());

        for migration in migrations {
            let is_applied = applied.contains(&migration.version().to_string());
            status.push(MigrationStatus {
                version: migration.version().to_string(),
                name: migration.name().to_string(),
                applied: is_applied,
            });
        }

        Ok(status)
    }

    // =========================================================================
    // MIGRATIONS TABLE MANAGEMENT
    // =========================================================================

    /// Ensure the migrations table exists
    async fn ensure_migrations_table(&self) -> Result<()> {
        let db = db();
        let db_type = detect_database_type(db);

        let sql = match db_type {
            DatabaseType::Postgres => {
                r#"
                CREATE TABLE IF NOT EXISTS "_migrations" (
                    "id" SERIAL PRIMARY KEY,
                    "version" VARCHAR(255) NOT NULL UNIQUE,
                    "name" VARCHAR(255) NOT NULL,
                    "applied_at" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
                )
                "#
            }
            DatabaseType::MySQL => {
                r#"
                CREATE TABLE IF NOT EXISTS `_migrations` (
                    `id` INT AUTO_INCREMENT PRIMARY KEY,
                    `version` VARCHAR(255) NOT NULL UNIQUE,
                    `name` VARCHAR(255) NOT NULL,
                    `applied_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
                )
                "#
            }
            DatabaseType::SQLite => {
                r#"
                CREATE TABLE IF NOT EXISTS "_migrations" (
                    "id" INTEGER PRIMARY KEY AUTOINCREMENT,
                    "version" TEXT NOT NULL UNIQUE,
                    "name" TEXT NOT NULL,
                    "applied_at" TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
                )
                "#
            }
        };

        db.__internal_connection()
            .execute_unprepared(sql)
            .await
            .map_err(|e| Error::query(e.to_string()))?;

        Ok(())
    }

    /// Get list of applied migration versions
    async fn get_applied_migrations(&self) -> Result<Vec<String>> {
        let db = db();

        use crate::internal::Statement;

        let backend = db.__internal_connection().get_database_backend();
        let sql = r#"SELECT "version" FROM "_migrations" ORDER BY "version" ASC"#;
        let stmt = Statement::from_string(backend, sql.to_string());

        let results = db
            .__internal_connection()
            .query_all_raw(stmt)
            .await
            .map_err(|e| Error::query(e.to_string()))?;

        // Get the list of registered migration versions for filtering
        let registered_versions: std::collections::HashSet<_> = 
            self.migrations.iter().map(|m| m.version().to_string()).collect();

        let mut versions = Vec::new();
        for row in results {
            let version: String = row
                .try_get("", "version")
                .map_err(|e| Error::query(e.to_string()))?;
            // Only include versions that are registered in this migrator
            if registered_versions.contains(&version) {
                versions.push(version);
            }
        }

        Ok(versions)
    }

    /// Record a migration as applied
    async fn record_migration(&self, version: &str, name: &str) -> Result<()> {
        let db = db();

        let sql = format!(
            r#"INSERT INTO "_migrations" ("version", "name") VALUES ('{}', '{}')"#,
            version.replace('\'', "''"),
            name.replace('\'', "''")
        );

        db.__internal_connection()
            .execute_unprepared(&sql)
            .await
            .map_err(|e| Error::query(e.to_string()))?;

        Ok(())
    }

    /// Remove a migration record
    async fn remove_migration_record(&self, version: &str) -> Result<()> {
        let db = db();

        let sql = format!(
            r#"DELETE FROM "_migrations" WHERE "version" = '{}'"#,
            version.replace('\'', "''")
        );

        db.__internal_connection()
            .execute_unprepared(&sql)
            .await
            .map_err(|e| Error::query(e.to_string()))?;

        Ok(())
    }
}

impl Default for Migrator {
    fn default() -> Self {
        Self::new()
    }
}

// ============================================================================
// RESULT TYPES
// ============================================================================

/// Result of migration operations
#[derive(Debug, Clone)]
pub struct MigrationResult {
    /// Successfully applied migrations
    pub applied: Vec<MigrationInfo>,
    /// Skipped (already applied) migrations
    pub skipped: Vec<MigrationInfo>,
    /// Rolled back migrations
    pub rolled_back: Vec<MigrationInfo>,
}

impl MigrationResult {
    fn new() -> Self {
        Self {
            applied: Vec::new(),
            skipped: Vec::new(),
            rolled_back: Vec::new(),
        }
    }

    /// Check if any migrations were applied
    pub fn has_applied(&self) -> bool {
        !self.applied.is_empty()
    }

    /// Check if any migrations were rolled back
    pub fn has_rolled_back(&self) -> bool {
        !self.rolled_back.is_empty()
    }
}

impl fmt::Display for MigrationResult {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if !self.applied.is_empty() {
            writeln!(f, "Applied migrations:")?;
            for m in &self.applied {
                writeln!(f, "  ✓ {} - {}", m.version, m.name)?;
            }
        }

        if !self.skipped.is_empty() {
            writeln!(f, "Skipped migrations (already applied):")?;
            for m in &self.skipped {
                writeln!(f, "  - {} - {}", m.version, m.name)?;
            }
        }

        if !self.rolled_back.is_empty() {
            writeln!(f, "Rolled back migrations:")?;
            for m in &self.rolled_back {
                writeln!(f, "  ↩ {} - {}", m.version, m.name)?;
            }
        }

        Ok(())
    }
}

/// Information about a single migration
#[derive(Debug, Clone)]
pub struct MigrationInfo {
    /// Migration version
    pub version: String,
    /// Migration name
    pub name: String,
}

/// Status of a single migration
#[derive(Debug, Clone)]
pub struct MigrationStatus {
    /// Migration version
    pub version: String,
    /// Migration name
    pub name: String,
    /// Whether the migration has been applied
    pub applied: bool,
}

impl fmt::Display for MigrationStatus {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let status = if self.applied { "✓" } else { "○" };
        write!(f, "[{}] {} - {}", status, self.version, self.name)
    }
}

// ============================================================================
// HELPER FUNCTIONS
// ============================================================================

/// Detect database type from connection
fn detect_database_type(db: &Database) -> DatabaseType {
    use crate::internal::DbBackend;

    match db.__internal_connection().get_database_backend() {
        DbBackend::Postgres => DatabaseType::Postgres,
        DbBackend::MySql => DatabaseType::MySQL,
        DbBackend::Sqlite => DatabaseType::SQLite,
        _ => DatabaseType::Postgres, // Default to Postgres for unknown backends
    }
}

/// Log migration SQL (respects TIDE_LOG_QUERIES)
fn log_migration_sql(sql: &str) {
    if std::env::var("TIDE_LOG_QUERIES").is_ok() {
        eprintln!("[Migration SQL] {}", sql);
    }
}

/// Log migration start
fn log_migration_start(version: &str, name: &str) {
    eprintln!("Running migration: {} - {}", version, name);
}

/// Log migration complete
fn log_migration_complete(version: &str, name: &str) {
    eprintln!("Completed migration: {} - {}", version, name);
}

/// Log migration rollback
fn log_migration_rollback(version: &str, name: &str) {
    eprintln!("Rolling back migration: {} - {}", version, name);
}

// ============================================================================
// TESTS
// ============================================================================

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

    #[test]
    fn test_column_type_postgres() {
        assert_eq!(ColumnType::Integer.to_postgres_sql(), "INTEGER");
        assert_eq!(ColumnType::BigInteger.to_postgres_sql(), "BIGINT");
        assert_eq!(ColumnType::String.to_postgres_sql(), "VARCHAR(255)");
        assert_eq!(ColumnType::Text.to_postgres_sql(), "TEXT");
        assert_eq!(ColumnType::Boolean.to_postgres_sql(), "BOOLEAN");
        assert_eq!(ColumnType::Jsonb.to_postgres_sql(), "JSONB");
        assert_eq!(ColumnType::IntegerArray.to_postgres_sql(), "INTEGER[]");
        assert_eq!(ColumnType::Timestamp.to_postgres_sql(), "TIMESTAMP");
        assert_eq!(ColumnType::TimestampTz.to_postgres_sql(), "TIMESTAMPTZ");
        assert_eq!(ColumnType::Date.to_postgres_sql(), "DATE");
        assert_eq!(ColumnType::Time.to_postgres_sql(), "TIME");
    }

    #[test]
    fn test_column_type_mysql() {
        assert_eq!(ColumnType::Integer.to_mysql_sql(), "INT");
        assert_eq!(ColumnType::BigInteger.to_mysql_sql(), "BIGINT");
        assert_eq!(ColumnType::Boolean.to_mysql_sql(), "TINYINT(1)");
        assert_eq!(ColumnType::Jsonb.to_mysql_sql(), "JSON");
        assert_eq!(ColumnType::Timestamp.to_mysql_sql(), "TIMESTAMP");
        assert_eq!(ColumnType::TimestampTz.to_mysql_sql(), "TIMESTAMP"); // MySQL doesn't have TIMESTAMPTZ
        assert_eq!(ColumnType::Date.to_mysql_sql(), "DATE");
        assert_eq!(ColumnType::Time.to_mysql_sql(), "TIME");
    }

    #[test]
    fn test_column_type_sqlite() {
        assert_eq!(ColumnType::Integer.to_sqlite_sql(), "INTEGER");
        assert_eq!(ColumnType::BigInteger.to_sqlite_sql(), "INTEGER");
        assert_eq!(ColumnType::String.to_sqlite_sql(), "TEXT");
        assert_eq!(ColumnType::Boolean.to_sqlite_sql(), "INTEGER");
        assert_eq!(ColumnType::Timestamp.to_sqlite_sql(), "TEXT");
        assert_eq!(ColumnType::TimestampTz.to_sqlite_sql(), "TEXT");
        assert_eq!(ColumnType::Date.to_sqlite_sql(), "TEXT");
        assert_eq!(ColumnType::Time.to_sqlite_sql(), "TEXT");
    }

    #[test]
    fn test_default_value() {
        assert_eq!(DefaultValue::String("test".to_string()).to_sql(), "'test'");
        assert_eq!(DefaultValue::Integer(42).to_sql(), "42");
        assert_eq!(DefaultValue::Boolean(true).to_sql(), "TRUE");
        assert_eq!(DefaultValue::Boolean(false).to_sql(), "FALSE");
        assert_eq!(DefaultValue::Null.to_sql(), "NULL");
    }

    #[test]
    fn test_table_builder_create() {
        let mut builder = TableBuilder::new("users", DatabaseType::Postgres);
        builder.id();
        builder.string("email").unique().not_null();
        builder.string("name").not_null();
        builder.boolean("active").default(true);
        builder.timestamps();

        let sql = builder.build_create();
        assert!(sql.contains("CREATE TABLE"));
        assert!(sql.contains("\"users\""));
        assert!(sql.contains("\"id\" BIGSERIAL"));
        assert!(sql.contains("\"email\""));
        assert!(sql.contains("\"name\""));
        assert!(sql.contains("\"active\""));
        assert!(sql.contains("\"created_at\""));
        assert!(sql.contains("\"updated_at\""));
    }

    #[test]
    fn test_timestamps_feature() {
        // Test PostgreSQL timestamps - now uses TIMESTAMPTZ by default
        let mut builder = TableBuilder::new("posts", DatabaseType::Postgres);
        builder.id();
        builder.string("title").not_null();
        builder.timestamps();

        let sql = builder.build_create();
        // Verify timestamps use TIMESTAMPTZ with NOT NULL and DEFAULT CURRENT_TIMESTAMP
        assert!(sql.contains("\"created_at\" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP"), 
            "PostgreSQL should have created_at with TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP. Got: {}", sql);
        assert!(sql.contains("\"updated_at\" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP"),
            "PostgreSQL should have updated_at with TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP. Got: {}", sql);

        // Test MySQL timestamps - TIMESTAMPTZ falls back to TIMESTAMP
        let mut builder = TableBuilder::new("posts", DatabaseType::MySQL);
        builder.id();
        builder.string("title").not_null();
        builder.timestamps();

        let sql = builder.build_create();
        assert!(sql.contains("`created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP"),
            "MySQL should have created_at with TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP. Got: {}", sql);
        assert!(sql.contains("`updated_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP"),
            "MySQL should have updated_at with TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP. Got: {}", sql);

        // Test SQLite timestamps
        let mut builder = TableBuilder::new("posts", DatabaseType::SQLite);
        builder.id();
        builder.string("title").not_null();
        builder.timestamps();

        let sql = builder.build_create();
        assert!(sql.contains("\"created_at\" TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP"),
            "SQLite should have created_at with TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP. Got: {}", sql);
        assert!(sql.contains("\"updated_at\" TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP"),
            "SQLite should have updated_at with TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP. Got: {}", sql);
    }

    #[test]
    fn test_timestamps_naive_feature() {
        // Test timestamps_naive() which uses TIMESTAMP (without timezone)
        let mut builder = TableBuilder::new("logs", DatabaseType::Postgres);
        builder.id();
        builder.text("message").not_null();
        builder.timestamps_naive();

        let sql = builder.build_create();
        // Verify naive timestamps use TIMESTAMP (not TIMESTAMPTZ)
        assert!(sql.contains("\"created_at\" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP"), 
            "PostgreSQL timestamps_naive should use TIMESTAMP. Got: {}", sql);
        assert!(sql.contains("\"updated_at\" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP"),
            "PostgreSQL timestamps_naive should use TIMESTAMP. Got: {}", sql);
    }

    #[test]
    fn test_timestamptz_column() {
        // Test individual timestamptz column
        let mut builder = TableBuilder::new("sessions", DatabaseType::Postgres);
        builder.id();
        builder.string("token").not_null();
        builder.timestamptz("expires_at").not_null();
        builder.timestamptz("last_activity").nullable();

        let sql = builder.build_create();
        assert!(sql.contains("\"expires_at\" TIMESTAMPTZ NOT NULL"),
            "Should have expires_at as TIMESTAMPTZ NOT NULL. Got: {}", sql);
        assert!(sql.contains("\"last_activity\" TIMESTAMPTZ"),
            "Should have last_activity as TIMESTAMPTZ. Got: {}", sql);
        // last_activity should be nullable (no NOT NULL)
        assert!(!sql.contains("\"last_activity\" TIMESTAMPTZ NOT NULL"),
            "last_activity should be nullable. Got: {}", sql);
    }

    #[test]
    fn test_timestamp_vs_timestamptz() {
        // Test that timestamp() and timestamptz() produce different SQL in PostgreSQL
        let mut builder = TableBuilder::new("events", DatabaseType::Postgres);
        builder.id();
        builder.timestamp("local_time");      // TIMESTAMP (no timezone)
        builder.timestamptz("utc_time");      // TIMESTAMPTZ (with timezone)

        let sql = builder.build_create();
        assert!(sql.contains("\"local_time\" TIMESTAMP"),
            "timestamp() should produce TIMESTAMP. Got: {}", sql);
        assert!(sql.contains("\"utc_time\" TIMESTAMPTZ"),
            "timestamptz() should produce TIMESTAMPTZ. Got: {}", sql);
    }

    #[test]
    fn test_date_time_columns() {
        // Test all date/time column types
        let mut builder = TableBuilder::new("schedules", DatabaseType::Postgres);
        builder.id();
        builder.date("event_date");
        builder.time("start_time");
        builder.datetime("local_datetime");
        builder.timestamp("naive_timestamp");
        builder.timestamptz("utc_timestamp");

        let sql = builder.build_create();
        assert!(sql.contains("\"event_date\" DATE"), "Should have DATE column. Got: {}", sql);
        assert!(sql.contains("\"start_time\" TIME"), "Should have TIME column. Got: {}", sql);
        assert!(sql.contains("\"local_datetime\" TIMESTAMP"), "Should have TIMESTAMP for datetime. Got: {}", sql);
        assert!(sql.contains("\"naive_timestamp\" TIMESTAMP"), "Should have TIMESTAMP. Got: {}", sql);
        assert!(sql.contains("\"utc_timestamp\" TIMESTAMPTZ"), "Should have TIMESTAMPTZ. Got: {}", sql);
    }

    #[test]
    fn test_soft_deletes_feature() {
        // soft_deletes now uses TIMESTAMPTZ
        let mut builder = TableBuilder::new("posts", DatabaseType::Postgres);
        builder.id();
        builder.soft_deletes();

        let sql = builder.build_create();
        // soft_deletes should be nullable TIMESTAMPTZ
        assert!(sql.contains("\"deleted_at\" TIMESTAMPTZ"),
            "Should have deleted_at TIMESTAMPTZ column. Got: {}", sql);
        assert!(!sql.contains("\"deleted_at\" TIMESTAMPTZ NOT NULL"),
            "deleted_at should be nullable (no NOT NULL). Got: {}", sql);
    }

    #[test]
    fn test_alter_table_builder() {
        let mut builder = AlterTableBuilder::new("users", DatabaseType::Postgres);
        builder.add_column("phone", ColumnType::String).nullable();
        builder.drop_column("legacy");
        builder.rename_column("name", "full_name");

        let statements = builder.build();
        assert_eq!(statements.len(), 3);
        assert!(statements[0].contains("ADD COLUMN"));
        assert!(statements[1].contains("DROP COLUMN"));
        assert!(statements[2].contains("RENAME COLUMN"));
    }

    #[test]
    fn test_multi_column_unique_constraint() {
        // Test unnamed unique constraint
        let mut builder = TableBuilder::new("user_roles", DatabaseType::Postgres);
        builder.big_integer("user_id").not_null();
        builder.big_integer("role_id").not_null();
        builder.unique(&["user_id", "role_id"]);

        let sql = builder.build_create();
        assert!(sql.contains("UNIQUE (\"user_id\", \"role_id\")"),
            "Should have multi-column unique constraint. Got: {}", sql);

        // Test named unique constraint
        let mut builder = TableBuilder::new("users", DatabaseType::Postgres);
        builder.id();
        builder.string("email").not_null();
        builder.big_integer("tenant_id").not_null();
        builder.unique_named("uq_user_email_tenant", &["email", "tenant_id"]);

        let sql = builder.build_create();
        assert!(sql.contains("CONSTRAINT \"uq_user_email_tenant\" UNIQUE (\"email\", \"tenant_id\")"),
            "Should have named unique constraint. Got: {}", sql);
    }

    #[test]
    fn test_composite_primary_key() {
        // Test composite primary key for junction table
        let mut builder = TableBuilder::new("user_roles", DatabaseType::Postgres);
        builder.big_integer("user_id").not_null();
        builder.big_integer("role_id").not_null();
        builder.timestamps();
        builder.primary_key(&["user_id", "role_id"]);

        let sql = builder.build_create();
        assert!(sql.contains("PRIMARY KEY (\"user_id\", \"role_id\")"),
            "Should have composite primary key. Got: {}", sql);
        // Should NOT have individual primary keys
        assert!(!sql.contains("BIGINT PRIMARY KEY"),
            "Individual columns should not be marked as primary key. Got: {}", sql);
    }

    #[test]
    fn test_check_constraint() {
        let mut builder = TableBuilder::new("products", DatabaseType::Postgres);
        builder.id();
        builder.decimal("price").check("price >= 0");
        builder.integer("quantity").check("quantity >= 0");

        let sql = builder.build_create();
        assert!(sql.contains("CHECK (price >= 0)"),
            "Should have CHECK constraint on price. Got: {}", sql);
        assert!(sql.contains("CHECK (quantity >= 0)"),
            "Should have CHECK constraint on quantity. Got: {}", sql);
    }

    #[test]
    fn test_extra_sql_attribute() {
        let mut builder = TableBuilder::new("logs", DatabaseType::MySQL);
        builder.id();
        builder.text("message").extra("COLLATE utf8mb4_unicode_ci");

        let sql = builder.build_create();
        assert!(sql.contains("COLLATE utf8mb4_unicode_ci"),
            "Should include extra SQL. Got: {}", sql);
    }
}