floz-orm 0.1.7

A lightweight, typesafe Rust ORM — unifying DAO and DSL from a single schema
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
# floz — Design Document

> A lightweight, typesafe SQL library for Rust.
> Fast to compile. Explicit by design. Zero black-box magic.

---

## 1. Philosophy

**"Familiarity meets Rust's performance."**

Rust developers shouldn't have to learn a convoluted trait system just to query a database.
`floz` takes the beloved paradigms of Django ORM and Kotlin Exposed and adapts them to Rust's
strict memory model — with idiomatic Rust syntax throughout.

Today's Rust SQL ecosystem forces you to choose: raw SQL (SQLx), type-heavy DSL (Diesel),
or async ORM (SeaORM). None offers both a query builder AND an ORM from a single schema definition
with **proven zero-cost overhead** (routinely matching raw SQLx execution speeds under load).

`floz` uses a **single `#[model]` proc macro** per struct to generate everything:

- **One centralized schema** — generates both a plain-data DAO object and a typesafe DSL query builder
- **Builder-chain syntax**`integer("id").auto_increment().primary()` reads like natural Rust
- **Explicit state tracking** — zero-allocation dirty checking via bitmasks
- **Beautiful compile errors**`syn`-powered parsing catches typos with helpful messages
- **Single invocation** — the proc macro runs once for the entire schema, not per-struct
- **Pragmatic runtime metadata** — where it makes syntax cleaner, we use it

### Non-Goals (for now)

- Being a database engine
- Supporting every SQL dialect edge case
- Replacing raw SQL for ultra-complex analytics queries

### Explicit Trade-offs

- **No compile-time SQL verification.** Unlike `sqlx::query!()` which validates SQL against
  a live database at compile time, `floz` generates SQL at runtime via composable builders.
  You trade compile-time schema validation for composability, dynamic query construction,
  and freedom from requiring a database connection during compilation. The type system still
  prevents column typos and type mismatches — you just won't catch schema drift until runtime.

### Future Goals (not in v1)

- Migration engine with schema diffing (`floz::schema::sync`)
- Reverse-engineer schema from existing database tables (CLI)
- CLI tool for code generation

---

## 2. Quick Start — What It Looks Like

```rust
use floz::prelude::*;

const NAME_LENGTH: i32 = 100;
const TITLE_LENGTH: i32 = 255;
const LABEL_LENGTH: i32 = 50;

// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// Step 1: Define your schema ONCE
// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

```rust
#[model("users")]
pub struct User {
    #[col(key, auto)]
    pub id: i32,
    #[col(max_length = 100)]
    pub name: String,
    #[col]
    pub age: i16,
    #[col(max_length = 100)]
    pub email: Option<String>,
    #[col]
    pub bio: Option<String>,
    #[col(default = "true")]
    pub is_active: bool,
    #[col(auto_now_add)]
    pub created_at: chrono::DateTime<chrono::Utc>,
    #[col(auto_now)]
    pub updated_at: chrono::DateTime<chrono::Utc>,
}

#[model("posts")]
pub struct Post {
    #[col(key, auto)]
    pub id: i32,
    #[col(max_length = 255)]
    pub title: String,
    #[col]
    pub body: String,
    #[col(references("users", "id"))]
    pub author_id: i32,
    #[col(auto_now_add)]
    pub created_at: chrono::DateTime<chrono::Utc>,
}

#[model("tags")]
pub struct Tag {
    #[col(key, auto)]
    pub id: i32,
    #[col(unique, max_length = 50)]
    pub label: String,
}

#[model("post_tags", pks("post_id", "tag_id"))]
pub struct PostTag {
    #[col(references("posts", "id"))]
    pub post_id: i32,
    #[col(references("tags", "id"))]
    pub tag_id: i32,
}
```


// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// Step 2: DAO Mode (Active Record Style)
// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

// Create
let alice = User::create()
.name("Alice")
.age(30)
.email(Some("alice@example.com".into()))
.execute( & db)
.await?;

// Read (by primary key)
let mut user = User::get(1, & db).await?;

// Update (explicit setters track state via bitmask)
user.set_name("Alice Updated");
user.set_age(31);
user.save( & db).await?;
// → UPDATE users SET name = $1, age = $2 WHERE id = $3

// Delete
user.delete( & db).await?;

// Find / filter
let admins = User::find(UserTable::name.eq("admin"), & db).await?;
let admin = User::find_one(UserTable::name.eq("admin"), & db).await?;
let everyone = User::all( & db).await?;

// Utility
let exists = User::exists(UserTable::email.eq("x@y.com"), & db).await?;
let count = User::count(UserTable::age.gt(25), & db).await?;

// Relationships (auto-generated from `array(User, "author_id")`)
let user = User::get(1, & db).await?;
let posts: Vec<Post> = user.fetch_posts( & db).await?;


// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// Step 3: DSL Mode (Exposed Style)
// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

// Simple select
let young_users: Vec<User> = UserTable::select()
.where_(UserTable::age.gt(25))
.order_by(UserTable::name.asc())
.limit(10)
.execute( & db)
.await?;

// Select specific columns (returns tuples)
let names: Vec<(String, i16) > = UserTable::select_cols((
UserTable::name,
UserTable::age,
))
.where_(UserTable::age.between(18, 65))
.execute( & db)
.await?;

// Complex filter
let results: Vec<User> = UserTable::select()
.where_(
UserTable::age.between(18, 65)
.and(UserTable::email.is_not_null())
.or(UserTable::name.eq("admin"))
)
.execute( & db)
.await?;

// Joins
let user_posts: Vec<(String, String) > = UserTable::select_cols((
UserTable::name,
PostTable::title,
))
.join(PostTable::author_id.eq(UserTable::id))
.where_(UserTable::age.gt(20))
.execute( & db)
.await?;

// Aggregates
let stats = UserTable::select_cols((
UserTable::name,
UserTable::age.avg().alias("avg_age"),
UserTable::id.count().alias("total"),
))
.group_by(UserTable::name)
.having(UserTable::age.avg().gt(30.0))
.execute( & db)
.await?;

// Insert via DSL
UserTable::insert()
.set(UserTable::name, "Alice")
.set(UserTable::age, 30i16)
.execute( & db)
.await?;

// Bulk insert
UserTable::insert_many( & [
user_row! { name: "Alice", age: 30i16 },
user_row! { name: "Bob",   age: 25i16 },
])
.execute( & db)
.await?;

// Update via DSL
UserTable::update()
.set(UserTable::age, 32i16)
.where_(UserTable::name.eq("Alice"))
.execute( & db)
.await?;

// Delete via DSL
UserTable::delete()
.where_(UserTable::id.eq(1))
.execute( & db)
.await?;


// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// Step 4: Relationships
// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

let user = User::get(1, & db).await?;

// Auto-generated from array(User, "author_id") on Post
let posts: Vec<Post> = user.fetch_posts( & db).await?;

// Reverse: Post → User
let post = Post::get(1, & db).await?;
let author: User = post.fetch_user( & db).await?;

// Many-to-many via junction table
let post = Post::get(1, & db).await?;
let tags: Vec<Tag> = post.fetch_tags( & db).await?;


// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// Step 5: Transactions
// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

floz::transaction( & db, | tx| async move {
let user = User::get(1, &tx).await ?;

Post::create()
.title("New Post")
.author_id(user.id)
.execute( & tx)
.await ?;

user.delete( & tx).await ?;

Ok(())
}).await?;


// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// Step 5: Schema Management
// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

floz::schema::create::<User>( & db).await?;
floz::schema::drop::<User>( & db).await?;
let sql = floz::schema::create_sql::<User>();
```

---

## 3. Macro Strategy: Thin Proc Macro

### Why not `macro_rules!`

Declarative macros hit walls with this level of code generation:

- **Recursion limits** — schemas with many tables blow past default limits
- **Terrible error messages** — typos produce cryptic "no rules expected this token" errors
- **Complex parsing** — builder chains like `.auto_increment().primary()` are hard to parse

### Why not per-struct `#[derive]`

Spins up the proc macro engine per-struct, scatters schema across the codebase,
and can't cross-reference models for relationship generation.

### The thin proc macro approach

A **single attribute proc macro** — `#[model("table_name")]`:

- **One pass** — invoked once per struct
- **Beautiful errors**`syn` catches typos with underlined, helpful compiler errors
- **Identical DX** — the user writes idiomatic Rust-style struct fields with `#[col]` attributes

---

## 4. The `#[model]` Macro — Single Source of Truth

### 4.1 Syntax

```rust
#[model("table_name")]
pub struct ModelName {
    #[col(col_modifier, ...)]
    pub field_name: FieldType,
}
```

Key: **Rust field name** is exactly as declared. Type mapping is inferred by the `FieldType`.

### 4.2 What It Generates

For each `#[model]` declaration:

```
┌──────────────────────────────────────────────────────────────┐
│          #[model("users")] pub struct User { ... }           │
├──────────────────────────────────────────────────────────────┤
│                                                              │
│  1. struct User { id, name, age, email, ... }                │
│     → DAO entity struct with derives                         │
│     → Hidden _dirty_flags: u64                               │
│                                                              │
│  2. impl User { ... }                                        │
│     → set_name(), set_age(), ... (dirty-tracking setters)    │
│     → create() → UserBuilder                                 │
│     → get(), find(), find_one(), all(), save(), delete()     │
│     → exists(), count(), count_all()                         │
│     → fetch_posts() (from array declarations)                │
│                                                              │
│  3. struct UserTable;                                        │
│     → DSL namespace with typed Column constants              │
│     → UserTable::id, UserTable::name, UserTable::age, ...    │
│     → UserTable::select(), insert(), update(), delete()      │
│                                                              │
│  4. user_row! { name: "x", age: 1 }                         │
│     → Shorthand for bulk inserts                             │
│     → Expands to Vec<(AnyColumn, Value)>                     │
│                                                              │
│  5. static USER_TABLE_META: &[ColumnMeta]                    │
│     → Column metadata for schema generation                  │
│                                                              │
└──────────────────────────────────────────────────────────────┘
```

### 4.3 Generated Struct (DAO Entity)

```rust
#[derive(Debug, Clone, Serialize, Deserialize, sqlx::FromRow)]
pub struct User {
    pub id: i32,
    pub name: String,
    pub age: i16,
    pub email: Option<String>,
    pub bio: Option<String>,
    pub is_active: bool,
    pub created_at: chrono::DateTime<chrono::Utc>,
    pub updated_at: chrono::DateTime<chrono::Utc>,

    #[serde(skip)]
    #[sqlx(default)]  // Initializes to 0 when fetched from DB (column doesn't exist)
    #[doc(hidden)]
    pub _dirty_flags: u64,
}
```

### 4.4 Generated DSL Namespace

```rust
pub struct UserTable;

impl UserTable {
    pub const TABLE_NAME: &'static str = "users";

    pub const id: Column<i32> = Column::new("id", "users");
    pub const name: Column<String> = Column::new("name", "users");
    pub const age: Column<i16> = Column::new("age", "users");
    pub const email: Column<Option<String>> = Column::new("email", "users");
    pub const bio: Column<Option<String>> = Column::new("bio", "users");
    pub const is_active: Column<bool> = Column::new("is_active", "users");
    pub const created_at: Column<chrono::DateTime<chrono::Utc>> = Column::new("created_at", "users");
    pub const updated_at: Column<chrono::DateTime<chrono::Utc>> = Column::new("updated_at", "users");

    pub fn select() -> SelectQuery<User> { ... }
    pub fn select_cols<C: ColumnSet>(cols: C) -> SelectColsQuery<C::Output> { ... }
    pub fn insert() -> InsertQuery { ... }
    pub fn insert_many(rows: &[PartialRow]) -> InsertManyQuery { ... }
    pub fn update() -> UpdateQuery { ... }
    pub fn delete() -> DeleteQuery { ... }
}
```

---

## 5. Type System

### 5.1 Column Type Functions

Each column is defined with a type function. The first argument is always the **DB column name**.

> **Hard limit: 64 columns per model.** Dirty tracking uses a single `u64` bitmask — zero
> allocations, always. If a model exceeds 64 columns, the proc macro emits a compile error:
>
> ```
> error: `users` has 65 fields, exceeding the 64-column limit.
>    = help: Normalize your schema by splitting into related tables.
> ```
>
> This is a deliberate design constraint that enforces good database normalization.

#### Numeric

```rust
integer("col")                          // i32    → INTEGER
short("col")                            // i16    → SMALLINT
bigint("col")                           // i64    → BIGINT
real("col")                             // f32    → REAL
double("col")                           // f64    → DOUBLE PRECISION
decimal("col", precision, scale)        // BigDecimal → NUMERIC(p, s)
```

#### String

```rust
varchar("col", max_length)              // String → VARCHAR(N)
text("col")                             // String → TEXT
```

#### Boolean

```rust
bool("col")                             // bool   → BOOLEAN
```

#### Date & Time

Everything is **naive by default**. `.tz()` upgrades to timezone-aware.

```rust
date("col")                             // NaiveDate     → DATE
time("col")                             // NaiveTime     → TIME
time("col").tz()                        // (tz time)     → TIMETZ  (rare)
datetime("col")                         // NaiveDateTime → TIMESTAMP
datetime("col").tz()                    // DateTime<Utc> → TIMESTAMPTZ
```

#### Identity & Binary

```rust
uuid("col")                             // Uuid    → UUID
binary("col")                           // Vec<u8> → BYTEA
```

#### Generic Column (escape hatch)

For types without a dedicated function, or PostgreSQL-specific types:

```rust
col(Uuid, "col")                        // Uuid       → UUID
col(String, "col")                      // String     → TEXT
col(serde_json::Value, "col")           // Value      → JSONB (future)
```

#### Relationships

```rust
array(Model, "fk_column")              // has_many relationship
```

`array(Post, "author_id")` on User means "User has many Posts linked via `posts.author_id`".
Generates `user.fetch_posts(&db)` and `post.fetch_user(&db)`.

> **`array()` is for relationships only.** For PostgreSQL native array columns (`TEXT[]`,
> `INT[]`, etc.), use the dedicated array type functions below.

#### PostgreSQL Native Array Columns

```rust
text_array("col")                       // Vec<String>  → TEXT[]
int_array("col")                        // Vec<i32>     → INTEGER[]
bigint_array("col")                     // Vec<i64>     → BIGINT[]
uuid_array("col")                       // Vec<Uuid>    → UUID[]
bool_array("col")                       // Vec<bool>    → BOOLEAN[]
real_array("col")                       // Vec<f32>     → REAL[]
double_array("col")                     // Vec<f64>     → DOUBLE PRECISION[]
```

These generate **actual database columns** in the struct, unlike `array(Model, "fk")`
which generates relationship methods only.

#### Future Types

```rust
json("col")                             // serde_json::Value → JSON
jsonb("col")                            // serde_json::Value → JSONB
blob("col")                             // Vec<u8>           → BYTEA (large)
enumeration("col", EnumType)            // Rust enum          → PostgreSQL ENUM
ltree("col")                            // String            → LTREE (extension)
varchar_array("col")                    // Vec<String>        → VARCHAR[]
short_array("col")                      // Vec<i16>           → SMALLINT[]
```

### 5.2 Complete Type Mapping Table

| floz                    | Rust Type        | PostgreSQL         | Notes                    |
|------------------------|------------------|--------------------|--------------------------|
| `integer("col")`       | `i32`            | `INTEGER`          |                          |
| `short("col")`         | `i16`            | `SMALLINT`         |                          |
| `bigint("col")`        | `i64`            | `BIGINT`           |                          |
| `real("col")`          | `f32`            | `REAL`             |                          |
| `double("col")`        | `f64`            | `DOUBLE PRECISION` |                          |
| `decimal("col", p, s)` | `BigDecimal`     | `NUMERIC(p,s)`     |                          |
| `varchar("col", N)`    | `String`         | `VARCHAR(N)`       |                          |
| `text("col")`          | `String`         | `TEXT`             |                          |
| `bool("col")`          | `bool`           | `BOOLEAN`          |                          |
| `date("col")`          | `NaiveDate`      | `DATE`             |                          |
| `time("col")`          | `NaiveTime`      | `TIME`             |                          |
| `time("col").tz()`     | *(tz time)*      | `TIMETZ`           | Rare                     |
| `datetime("col")`      | `NaiveDateTime`  | `TIMESTAMP`        | Naive                    |
| `datetime("col").tz()` | `DateTime<Utc>`  | `TIMESTAMPTZ`      | With timezone            |
| `uuid("col")`          | `Uuid`           | `UUID`             |                          |
| `binary("col")`        | `Vec<u8>`        | `BYTEA`            |                          |
| `col(T, "col")`        | `T`              | *(inferred)*       | Generic escape hatch     |
| `text_array("col")`    | `Vec<String>`    | `TEXT[]`           | Native PG array          |
| `int_array("col")`     | `Vec<i32>`       | `INTEGER[]`        | Native PG array          |
| `bigint_array("col")`  | `Vec<i64>`       | `BIGINT[]`         | Native PG array          |
| `uuid_array("col")`    | `Vec<Uuid>`      | `UUID[]`           | Native PG array          |
| `array(Model, "fk")`   | *(relationship)* | *(no column)*      | Generates fetch_ methods |

### 5.3 Modifiers (Chained)

```rust
.primary()                // PRIMARY KEY
.auto_increment()         // SERIAL / BIGSERIAL (based on integer type)
.nullable()               // Wraps Rust type in Option<T>, allows NULL
.unique()                 // UNIQUE constraint
.default (value)           // DEFAULT <value>
.default ("sql_expr")      // DEFAULT <sql expression>
.now()                    // DEFAULT now()  — shorthand for datetime
.tz()                     // WITH TIME ZONE — for datetime/time
.index()                  // CREATE INDEX on this column
```

#### Modifier examples

```rust
id:         integer("id").auto_increment().primary(),
name:       varchar("name", 100),
email:      varchar("email", 255).nullable().unique(),
is_active:  bool("is_active").default (true),
score:      integer("score").default (0),
bio:        text("bio_column").nullable(),
created_at: datetime("created_at").tz().now(),
```

### 5.4 Table-Level Constraints

```rust
@primary_key(post_id, tag_id)    // Composite primary key
@ unique(col_a, col_b)            // Composite unique constraint
@ index(col_a)                    // Index on column
@ index(col_a, col_b)             // Composite index
```

### 5.5 Full Schema Example

```rust
const NAME_LEN: i32 = 100;
const TITLE_LEN: i32 = 255;
const LABEL_LEN: i32 = 50;
const RATING_DIGITS: i32 = 5;
const RATING_DECIMAL: i32 = 2;

floz::schema! {
    model User("users") {
        id:         integer("id").auto_increment().primary(),
        name:       varchar("name", NAME_LEN),
        bio:        text("bio").nullable(),
        age:        short("age"),
        email:      varchar("email", NAME_LEN).nullable().unique(),
        is_active:  bool("is_active").default(true),
        rating:     decimal("rating", RATING_DIGITS, RATING_DECIMAL),
        avatar_id:  col(Uuid, "avatar_id").nullable(),
        start_date: date("start_date"),
        start_time: time("start_time"),
        created_at: datetime("created_at").tz().now(),
        updated_at: datetime("updated_at").tz().now(),
    }

    model Post("posts") {
        id:         integer("id").auto_increment().primary(),
        title:      varchar("title", TITLE_LEN),
        body:       text("body"),
        author_id:  integer("author_id"),
        published:  bool("published").default(false),
        created_at: datetime("created_at").tz().now(),
        authors:    array(User, "author_id"),
    }

    model Tag("tags") {
        id:    integer("id").auto_increment().primary(),
        label: varchar("label", LABEL_LEN).unique(),
    }

    model PostTag("post_tags") {
        post_id: integer("post_id"),
        tag_id:  integer("tag_id"),
        posts:   array(Post, "post_id"),
        tags:    array(Tag, "tag_id"),

        @primary_key(post_id, tag_id),
    }
}
```

---

## 6. DAO API — Active Record Style

### 6.1 Create

```rust
let alice = User::create()
.name("Alice")
.age(30)
.email(Some("alice@example.com".into()))
.execute( & db)
.await?;
// alice.id is now populated from the DB

let new_id: i32 = User::create()
.name("Bob")
.age(25)
.execute_returning(UserTable::id, & db)
.await?;
```

**Builder Internals: Option\<T\> for Default Handling**

The generated `UserBuilder` stores every field as `Option<T>` internally. When `.execute()`
is called, only explicitly-set fields appear in the INSERT statement. This lets PostgreSQL
apply its native `DEFAULT` values (e.g., `now()`, `true`) for omitted columns:

```rust
// Internally generated:
struct UserBuilder {
    name: Option<String>,    // None until .name() is called
    age: Option<i16>,
    email: Option<Option<String>>,  // Option<Option<T>> for nullable fields
    is_active: Option<bool>,
    // ...
}

// User::create().name("Alice").age(30).execute(&db)
// → INSERT INTO users (name, age) VALUES ($1, $2) RETURNING *
// PostgreSQL handles is_active DEFAULT true, created_at DEFAULT now()
```

### 6.2 Read

```rust
let user = User::get(1, & db).await?;                              // by PK (errors if not found)
let maybe = User::get_optional(999, & db).await?;                  // by PK (returns Option)

// Composite primary keys: macro generates multi-arg get()
let pt = PostTag::get(post_id, tag_id, & db).await?;               // composite PK
let pt = PostTag::get_optional(post_id, tag_id, & db).await?;      // composite PK (Option)

let young = User::find(UserTable::age.lt(25), & db).await?;        // all matching
let admin = User::find_one(UserTable::name.eq("admin"), & db).await?; // first matching
let everyone = User::all( & db).await?;                              // all records

// Paginated
let page = User::paginate( & db)
.page(3)
.per_page(20)
.order_by(UserTable::created_at.desc())
.execute()
.await?;
// page.items, page.total, page.pages, page.has_next
```

### 6.3 Update (Dirty Tracking via Bitmask)

```rust
let mut user = User::get(1, & db).await?;

user.set_name("Alice Updated");
user.set_age(31);

user.save( & db).await?;
// → UPDATE users SET name = $1, age = $2 WHERE id = $3
// Only dirty fields. If nothing changed, save() is a no-op.

// Fields are pub for reading:
println!("Name: {}", user.name);
```

**Bitmask internals:**

```rust
impl User {
    pub fn set_name(&mut self, val: impl Into<String>) {
        self.name = val.into();
        self._dirty_flags |= 1 << 1;  // Bit 1 = name
    }

    pub fn set_age(&mut self, val: i16) {
        self.age = val;
        self._dirty_flags |= 1 << 2;  // Bit 2 = age
    }

    pub async fn save(&mut self, db: &Db) -> Result<(), FlozError> {
        // Guard: prevent accidental UPDATE WHERE id = 0
        if self.id == 0 {
            return Err(FlozError::UnsavedEntity);
            // Use User::create() for new records instead.
        }
        if self._dirty_flags == 0 { return Ok(()); }
        // Build UPDATE with only flagged columns, execute, reset
        self._dirty_flags = 0;
        Ok(())
    }
}
```

> **Hard limit: 64 columns per model.** The proc macro enforces this at compile time.
> Tables exceeding 64 columns produce a compile error — normalize your schema instead.
> This guarantee means every entity uses a single `u64` — zero heap allocations, ever.

### 6.4 Testing & Struct Instantiation

The hidden `_dirty_flags` field creates friction for unit tests. The macro addresses this:

```rust
// 1. _dirty_flags is public but hidden from docs
#[doc(hidden)]
pub _dirty_flags: u64,

// 2. Default is auto-generated for all models
impl Default for User {
    fn default() -> Self {
        User {
            id: 0,
            name: String::new(),
            age: 0,
            email: None,
            bio: None,
            is_active: true,   // uses declared default
            created_at: Utc::now(),
            updated_at: Utc::now(),
            _dirty_flags: 0,
        }
    }
}

// 3. Users can construct test instances freely:
let test_user = User {
id: 1,
name: "Test".into(),
age: 25,
..User::default ()
};

// 4. The create() builder allows .id() for test seeding:
let seeded = User::create()
.id(99)         // Normally auto-increment, but allowed for testing
.name("Seed")
.age(30)
.execute( & db)
.await?;
```

### 6.5 Soft Delete & Hard Delete

If your model schema contains a `deleted_at: datetime("deleted_at").nullable()` field, the macro engine automatically enables **Soft Deletes**. Calling `user.delete(&db)` will update `deleted_at` with the current time instead of wiping the record. All queries (`User::all()`, `User::find()`) are seamlessly scoped to ignore soft-deleted items unless explicitly bypassed.

```rust
let user = User::get(1, & db).await?;

// SOFT DELETE (if deleted_at exists) or HARD DELETE
user.delete( & db).await?;

// Bulk delete without loading
User::destroy(UserTable::age.lt(18), & db).await?;
```

### 6.6 Utility

```rust
let count  = User::count(UserTable::age.gt(25), & db).await?;
let total  = User::count_all( & db).await?;
let exists = User::exists(UserTable::email.eq("x@y.com"), & db).await?;
```

---

## 7. DSL API — Typesafe Query Builder

### 7.1 SELECT

```rust
// Full row
let users: Vec<User> = UserTable::select()
.where_(UserTable::age.gt(25))
.execute( & db).await?;

// Single row
let user: User = UserTable::select()
.where_(UserTable::id.eq(1))
.execute_one( & db).await?;

// Optional
let user: Option<User> = UserTable::select()
.where_(UserTable::id.eq(1))
.execute_optional( & db).await?;

// Specific columns (tuple return — max 16 columns)
let names: Vec<(String, i16) > = UserTable::select_cols((
UserTable::name, UserTable::age,
))
.where_(UserTable::age.gt(25))
.execute( & db).await?;

// Single column
let emails: Vec<String> = UserTable::select_cols(UserTable::email)
.where_(UserTable::email.is_not_null())
.execute( & db).await?;

// Distinct / Pagination / Count / Exists
UserTable::select_cols(UserTable::name).distinct().execute( & db).await?;
UserTable::select().order_by(UserTable::created_at.desc()).limit(20).offset(40).execute( & db).await?;
UserTable::select().where_(UserTable::age.gt(25)).count( & db).await?;
UserTable::select().where_(UserTable::email.eq("x@y.com")).exists( & db).await?;

// NOTE: select_cols supports tuples up to 16 elements.
// This mirrors sqlx's FromRow tuple implementation limit.
// The ColumnSet trait is implemented via macro for (A,) through (A,...,P).
// For wider selections, use select() to fetch the full struct, or use raw SQL.
```

### 7.2 Filters & Operators

```rust
// Comparison
UserTable::age.eq(25)             UserTable::age.ne(25)
UserTable::age.gt(25)             UserTable::age.gte(25)
UserTable::age.lt(25)             UserTable::age.lte(25)

// Range
UserTable::age.between(18, 65)
UserTable::id.in_list(vec![1, 2, 3])
UserTable::id.not_in(vec![4, 5])

// String (on varchar/text columns only)
UserTable::name.like("A%")       UserTable::name.ilike("a%")
UserTable::name.starts_with("A") UserTable::name.ends_with("z")
UserTable::name.contains("foo")

// Null (on nullable columns only)
UserTable::email.is_null()        UserTable::email.is_not_null()

// Logical
UserTable::age.gt(25).and(UserTable::name.eq("Alice"))
UserTable::age.lt(18).or(UserTable::age.gt(65))
UserTable::email.is_null().not()

// Nesting (automatic parentheses)
UserTable::age.gt(25).and(
UserTable::name.eq("Alice").or(UserTable::name.eq("Bob"))
)
// → age > 25 AND (name = 'Alice' OR name = 'Bob')

// Ordering
UserTable::name.asc()             UserTable::name.desc()
UserTable::name.asc_nulls_last()
```

### 7.3 Aggregates & Grouping

```rust
UserTable::age.avg()   UserTable::age.sum()   UserTable::age.min()   UserTable::age.max()
UserTable::id.count()  UserTable::id.count_distinct()
UserTable::age.avg().alias("avg_age")
UserTable::age.plus(1)  UserTable::age.minus(1)

let stats = UserTable::select_cols((
UserTable::name,
UserTable::age.avg().alias("avg_age"),
UserTable::id.count().alias("total"),
))
.group_by(UserTable::name)
.having(UserTable::age.avg().gt(30.0))
.execute( & db).await?;
```

### 7.4 INSERT

```rust
UserTable::insert()
.set(UserTable::name, "Alice")
.set(UserTable::age, 30i16)
.execute( & db).await?;

// Returning
let new_user: User = UserTable::insert()
.set(UserTable::name, "Alice").set(UserTable::age, 30i16)
.returning().execute( & db).await?;

let new_id: i32 = UserTable::insert()
.set(UserTable::name, "Alice").set(UserTable::age, 30i16)
.returning_col(UserTable::id).execute( & db).await?;

// Returning multiple columns (mirrors select_cols tuple logic)
let (new_id, created): (i32, DateTime<Utc>) = UserTable::insert()
.set(UserTable::name, "Alice").set(UserTable::age, 30i16)
.returning_cols((UserTable::id, UserTable::created_at))
.execute( & db).await?;

// Bulk
UserTable::insert_many( & [
user_row! { name: "Alice", age: 30i16 },
user_row! { name: "Bob",   age: 25i16 },
]).execute( & db).await?;

// user_row! expands to a fixed-size ARRAY (zero heap allocation per row):
// user_row! { name: "Alice", age: 30i16 }
// → [
//     (UserTable::name.into_any(), Value::String("Alice".into())),
//     (UserTable::age.into_any(), Value::Short(30)),
// ]
// Type: [(AnyColumn, Value); 2] — size known at compile time.
// insert_many takes &[&[(AnyColumn, Value)]] — zero allocations for row structures.

// Upsert
UserTable::insert()
.set(UserTable::name, "Alice").set(UserTable::age, 31i16)
.on_conflict(UserTable::name)
.do_update(UserTable::age, 31i16)
.execute( & db).await?;
```

### 7.5 UPDATE

```rust
let affected: u64 = UserTable::update()
.set(UserTable::name, "Updated")
.set(UserTable::age, 31i16)
.where_(UserTable::id.eq(1))
.execute( & db).await?;

// Increment
UserTable::update()
.set(UserTable::age, UserTable::age.plus(1))
.where_(UserTable::age.lt(18))
.execute( & db).await?;

// Returning
let updated: User = UserTable::update()
.set(UserTable::age, UserTable::age.plus(1))
.where_(UserTable::id.eq(1))
.returning().execute( & db).await?;
```

### 7.6 DELETE

```rust
let affected: u64 = UserTable::delete()
.where_(UserTable::id.eq(1))
.execute( & db).await?;

let deleted: User = UserTable::delete()
.where_(UserTable::id.eq(1))
.returning().execute( & db).await?;

// Safety guard for delete-all
UserTable::delete().all().execute( & db).await?;
```

### 7.7 JOINs

```rust
// Inner
let rows: Vec<(String, String) > = UserTable::select_cols((
UserTable::name, PostTable::title,
))
.join(PostTable::author_id.eq(UserTable::id))
.execute( & db).await?;

// Left
let rows: Vec<(String, Option<String>) > = UserTable::select_cols((
UserTable::name, PostTable::title,
))
.left_join(PostTable::author_id.eq(UserTable::id))
.execute( & db).await?;

// Multiple joins + filters
UserTable::select_cols((UserTable::name, PostTable::title, CommentTable::body))
.join(PostTable::author_id.eq(UserTable::id))
.join(CommentTable::post_id.eq(PostTable::id))
.where_(UserTable::age.gt(25))
.execute( & db).await?;
```

### 7.8 Subqueries & Raw SQL

```rust
// Subquery
UserTable::select()
.where_(UserTable::id.in_subquery(
PostTable::select_cols(PostTable::author_id)
.where_(PostTable::title.contains("Rust"))
))
.execute( & db).await?;

// Raw SQL escape hatch
let users: Vec<User> = floz::raw(
"SELECT * FROM users WHERE age > $1 AND name ILIKE $2",
& [ & 25, & "%alice%"],
).execute( & db).await?;

// Raw expression inside DSL
UserTable::select()
.where_(floz::expr("age + 5 > $1", & [ & 30]))
.execute( & db).await?;
```

---

## 8. Relationships

### 8.1 Declaration

Relationships are declared via `array(Model, "fk_column")` in the schema:

```rust
model Post("posts") {
author_id: integer("author_id"),
authors: array(User, "author_id"),  // Post.author_id → User.id
}
```

The proc macro inspects all `array` declarations and auto-generates `fetch_` methods.

### 8.2 Generated Methods

From `authors: array(User, "author_id")` on Post:

**On Post (the "many" side):**

```rust
impl Post {
    pub async fn fetch_user(&self, db: &Db) -> Result<User, FlozError> {
        User::get(self.author_id, db).await
    }
}
```

**On User (the "one" side) — reverse lookup:**

```rust
impl User {
    pub async fn fetch_posts(&self, db: &Db) -> Result<Vec<Post>, FlozError> {
        Post::find(PostTable::author_id.eq(self.id), db).await
    }
}
```

> **⚠ N+1 Warning:** `fetch_` methods are **lazy** — they execute one query per call.
> Do NOT use them in a loop over multiple entities. For batch loading, use eager loading
> (Phase 4) or the DSL join API:
>
> ```rust
> // ❌ Bad: N+1 queries
> for user in users {
>     let posts = user.fetch_posts(&db).await?; // 1 query per user!
> }
>
> // ✅ Good: Single query via DSL join
> let results = UserTable::select_cols((UserTable::name, PostTable::title))
>     .join(PostTable::author_id.eq(UserTable::id))
>     .execute(&db).await?;
>
> // ✅ Future: Eager loading (Phase 4)
> let users = UserTable::select().with(PostTable).execute(&db).await?;
> ```

### 8.3 Many-to-Many (Junction Tables)

```rust
model PostTag("post_tags") {
post_id: integer("post_id"),
tag_id: integer("tag_id"),
posts: array(Post, "post_id"),
tags: array(Tag, "tag_id"),
@ primary_key(post_id, tag_id),
}
```

Generates:

```rust
impl Post {
    pub async fn fetch_tags(&self, db: &Db) -> Result<Vec<Tag>, FlozError> { ... }
}
impl Tag {
    pub async fn fetch_posts(&self, db: &Db) -> Result<Vec<Post>, FlozError> { ... }
}
```

### 8.4 Relationship Write Methods

Alongside `fetch_` (read), the macro generates write methods for linking/unlinking:

**One-to-Many:**

```rust
// Set the author on a post (updates post.author_id and saves)
let mut post = Post::get(1, & db).await?;
post.set_author( & user, & db).await?;
// → UPDATE posts SET author_id = $1 WHERE id = $2
```

**Many-to-Many (junction table handled automatically):**

```rust
let post = Post::get(1, & db).await?;
let tag = Tag::get(5, & db).await?;

// Link: inserts into junction table
post.add_tag( & tag, & db).await?;
// → INSERT INTO post_tags (post_id, tag_id) VALUES ($1, $2)

// Unlink: removes from junction table
post.remove_tag( & tag, & db).await?;
// → DELETE FROM post_tags WHERE post_id = $1 AND tag_id = $2

// Replace all: clear + re-link
post.set_tags( & [tag1, tag2, tag3], & db).await?;
// → DELETE FROM post_tags WHERE post_id = $1
// → INSERT INTO post_tags (post_id, tag_id) VALUES ...
```

> **Transaction Safety:** Multi-statement relationship writes (`set_tags`, which does
> DELETE + INSERT) automatically wrap in a transaction if the executor is a pool.
> If already inside a `Tx`, they execute directly on the existing transaction.
> This prevents orphaned data from partial failures.

---

## 9. Transactions

The **primary API** uses explicit transaction boundaries. This avoids the notorious
Higher-Rank Trait Bound (HRTB) lifetime issues that plague closure-based async transaction
APIs in Rust.

### 9.1 Explicit Boundaries (Primary API)

```rust
// Begin → execute → commit/rollback
let mut tx = db.begin().await?;

User::create()
.name("Alice")
.age(30)
.execute( & mut tx)
.await?;

Post::create()
.title("New Post")
.author_id(1)
.execute( & mut tx)
.await?;

tx.commit().await?;
// If tx is dropped without commit(), it auto-rolls back.
```

### 9.2 Nested Savepoints

```rust
let mut tx = db.begin().await?;

User::create().name("Outer").age(25).execute( & mut tx).await?;

// Nested — uses SAVEPOINT internally
let mut sp = tx.savepoint().await?;
User::create().name("Inner").age(30).execute( & mut sp).await?;
sp.commit().await?;

tx.commit().await?;
```

### 9.3 Closure API (Convenience, may require nightly or boxing)

If Rust's async closure lifetime story stabilizes, we'll also offer:

```rust
// Sugar — auto-commits on Ok, rolls back on Err
floz::transaction( & db, | tx| async move {
let user = User::get(1, &tx).await ?;
user.delete(& tx).await ?;
Ok(())
}).await?;
```

> **Note:** This may require `Box::pin` internally on stable Rust due to HRTB limitations.
> The explicit `begin/commit` API always works without any boxing or lifetime gymnastics.

All DAO and DSL methods accept `&Db`, `&mut Tx`, or `&mut Savepoint` via the `Executor` trait.

---

## 10. Schema Management

```rust
floz::schema::create::<User>( & db).await?;          // CREATE TABLE IF NOT EXISTS
floz::schema::drop::<User>( & db).await?;             // DROP TABLE
let exists = floz::schema::exists::<User>( & db).await?;
let sql = floz::schema::create_sql::<User>();        // Dry-run review

// Future: auto-sync
floz::schema::sync( & db).await?;
```

---

## 11. Connection / Pool

```rust
use floz::Db;

let db = Db::connect("postgres://user:pass@localhost/mydb").await?;
let db = Db::from_pool(existing_sqlx_pool);         // Interop
let pool: & sqlx::PgPool = db.pool();                 // Escape hatch
```

### 11.1 Executor Trait (Mockable)

The `Executor` trait is the backbone — all floz methods accept any implementor:

```rust
pub trait Executor {
    async fn execute_raw(&self, sql: &str, params: Vec<Value>) -> Result<u64, FlozError>;

    async fn fetch_raw<T>(&self, sql: &str, params: Vec<Value>) -> Result<Vec<T>, FlozError>
    where
        T: Send + Unpin + for<'r> sqlx::FromRow<'r, sqlx::postgres::PgRow>;

    async fn fetch_one_raw<T>(&self, sql: &str, params: Vec<Value>) -> Result<T, FlozError>
    where
        T: Send + Unpin + for<'r> sqlx::FromRow<'r, sqlx::postgres::PgRow>;
}

// Implemented for:
impl Executor for Db { ... }        // Live connection pool
impl Executor for &mut Tx { ... }   // Transaction
impl Executor for &mut Sp { ... }   // Savepoint
```

#### Implementation Note: Value → sqlx Binding

The `params: &[Value]` signature hides a critical translation layer. Because `sqlx`
requires concrete types for `.bind()` (via `Encode<'q, Postgres>`), the `Executor`
implementation must pattern-match each `Value` variant and bind it explicitly:

```rust
// Inside Executor::fetch_raw() implementation
let mut query = sqlx::query(sql);
for param in params {
match param {
// Non-nullable types
Value::Int(v) => { query = query.bind(v); }
Value::Short(v) => { query = query.bind(v); }
Value::BigInt(v) => { query = query.bind(v); }
Value::Real(v) => { query = query.bind(v); }
Value::Double(v) => { query = query.bind(v); }
Value::String(v) => { query = query.bind(v); }
Value::Bool(v) => { query = query.bind(v); }
Value::Uuid(v) => { query = query.bind(v); }
Value::DateTime(v) => { query = query.bind(v); }
Value::NaiveDateTime(v) => { query = query.bind(v); }
Value::NaiveDate(v) => { query = query.bind(v); }
Value::NaiveTime(v) => { query = query.bind(v); }
Value::Bytes(v) => { query = query.bind(v); }

// Nullable types — preserves PostgreSQL type OID even for NULL
// (PostgreSQL rejects untyped NULLs with: "could not determine data type")
Value::OptionInt(v) => { query = query.bind(v); }
Value::OptionShort(v) => { query = query.bind(v); }
Value::OptionBigInt(v) => { query = query.bind(v); }
Value::OptionReal(v) => { query = query.bind(v); }
Value::OptionDouble(v) => { query = query.bind(v); }
Value::OptionString(v) => { query = query.bind(v); }
Value::OptionBool(v) => { query = query.bind(v); }
Value::OptionUuid(v) => { query = query.bind(v); }
Value::OptionDateTime(v) => { query = query.bind(v); }
Value::OptionNaiveDateTime(v) => { query = query.bind(v); }
Value::OptionNaiveDate(v) => { query = query.bind(v); }
Value::OptionNaiveTime(v) => { query = query.bind(v); }
Value::OptionBytes(v) => { query = query.bind(v); }
}
}
let rows = query.fetch_all(pool).await?;
```

> **Why typed nulls?** A generic `Value::Null` variant causes PostgreSQL to reject queries
> with `could not determine data type of parameter $N`. Each `Option*` variant preserves
> the PostgreSQL type OID so `.bind(None::<i32>)` sends INT4 and `.bind(None::<String>)`
> sends TEXT.

This is verbose but correct. No generic `Null` variant exists — every value carries its
PostgreSQL type information. The match is exhaustive and compile-time checked.

#### Lifetime Note: Owned Values

The `Executor` trait takes `params: Vec<Value>` (**owned**, not `&[Value]`). This is
deliberate: `sqlx` requires bound values to live for the duration of query execution `'q`.
If `Value` held references, the borrow checker would fight us across async boundaries.
Owned data ensures the values survive through the `.await` without lifetime gymnastics.

For testing, users can implement `Executor` on a mock struct or use the `Db::from_pool()`
interop to pass a test database. The `fetch_posts()` and other DAO methods only require
`&impl Executor`, so they work with any backend:

```rust
// Unit test with a test database
let test_db = Db::connect("postgres://localhost/test_db").await?;
let user = User::get(1, & test_db).await?;
let posts = user.fetch_posts( & test_db).await?;
```

---

## 12. Error Handling

```rust
#[derive(Debug, thiserror::Error)]
pub enum FlozError {
    #[error("Record not found")]
    NotFound,

    #[error("Unique constraint violated: {0}")]
    UniqueViolation(String),

    #[error("Foreign key constraint violated: {0}")]
    ForeignKeyViolation(String),

    #[error("Database error: {0}")]
    Database(#[from] sqlx::Error),

    #[error("Serialization error: {0}")]
    Serialization(String),

    #[error("Cannot save — entity has no primary key (use create() for new records)")]
    UnsavedEntity,

    #[error("Nothing to save — no fields were modified")]
    NothingToSave,
}
```

---

## 13. Architecture

`floz` is a **standalone Rust workspace** with two crates:

```
floz/                          ← workspace root
├── Cargo.toml                ← workspace manifest
│
├── floz/                      ← main crate (runtime library)
│   ├── Cargo.toml
│   └── src/
│       ├── lib.rs            ← public API, prelude, re-exports
│       ├── column.rs         ← Column<T>, typed operators
│       ├── expr.rs           ← Expression tree (Eq, Gt, And, Or, etc.)
│       ├── value.rs          ← Value enum for dynamic SQL params
│       ├── query/
│       │   ├── mod.rs
│       │   ├── select.rs     ← SelectQuery, SelectColsQuery
│       │   ├── insert.rs     ← InsertQuery, InsertManyQuery
│       │   ├── update.rs     ← UpdateQuery
│       │   └── delete.rs     ← DeleteQuery
│       ├── dao.rs            ← Entity trait, save/delete base logic
│       ├── db.rs             ← Db, Tx, Executor trait, transaction()
│       ├── schema.rs         ← create/drop/exists/sync
│       ├── error.rs          ← FlozError
│       └── prelude.rs        ← use floz::prelude::*
│
├── floz-macros/               ← proc macro crate (thin parser + codegen)
│   ├── Cargo.toml
│   └── src/
│       ├── lib.rs            ← proc_macro entry point
│       ├── parse.rs          ← Parse schema! DSL → internal AST
│       ├── ast.rs            ← ModelDef, FieldDef, TypeInfo, Modifier
│       ├── gen_struct.rs     ← Generate DAO struct + set_ + save/delete
│       ├── gen_table.rs      ← Generate Table namespace + Column constants
│       ├── gen_builder.rs    ← Generate create() builder + _row! macro
│       ├── gen_relations.rs  ← Generate fetch_ methods from array()
│       └── gen_schema.rs     ← Generate CREATE TABLE SQL metadata
│
└── tests/                    ← integration tests
    ├── test_schema.rs
    ├── test_dao.rs
    ├── test_dsl.rs
    ├── test_joins.rs
    └── test_transactions.rs
```

### Dependencies

```toml
# floz/Cargo.toml
[dependencies]
floz-macros = { path = "../floz-macros" }
sqlx = { version = "0.8", features = ["runtime-tokio", "postgres"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
thiserror = "2"
chrono = { version = "0.4", features = ["serde"] }
uuid = { version = "1", features = ["v4", "serde"] }

# floz-macros/Cargo.toml
[dependencies]
syn = { version = "2", features = ["full"] }
quote = "1"
proc-macro2 = "1"
```

### What Lives Where

| Concern                             | Crate        | Rationale                |
|-------------------------------------|--------------|--------------------------|
| Parsing `schema!` DSL               | `floz-macros` | Needs proc macro API     |
| Code generation (structs, impls)    | `floz-macros` | Compile-time expansion   |
| `Column<T>`, expressions, operators | `floz`        | Runtime types            |
| Query builders                      | `floz`        | Runtime SQL construction |
| SQL rendering, param binding        | `floz`        | Runtime execution        |
| `Db`, `Tx`, `Executor`              | `floz`        | Runtime connection       |
| `FlozError`                          | `floz`        | Runtime errors           |

---

## 14. Proc Macro Error Examples

```
error: unknown modifier `primry_key`
  --> src/schema.rs:5:32
   |
5  |         id: integer("id").primry_key(),
   |                            ^^^^^^^^^^
   |
   = help: did you mean `primary()`?


error: `varchar` requires a max_length argument
  --> src/schema.rs:6:15
   |
6  |         name: varchar("name"),
   |               ^^^^^^^^^^^^^^^
   |
   = help: use `varchar("name", 100)`


error: unknown type function `intgr`
  --> src/schema.rs:4:13
   |
4  |         id: intgr("id"),
   |             ^^^^^
   |
   = help: available types: integer, short, bigint, varchar, text, bool,
           date, time, datetime, uuid, decimal, real, double, binary, col, array
```

---

## 15. DAO vs DSL — When to Use Which

| Scenario                  | Use                                              | Why              |
|---------------------------|--------------------------------------------------|------------------|
| Create a single record    | `User::create().name("x").execute()` (DAO)       | Builder-driven   |
| Load → modify → save      | `user.set_name("y"); user.save()` (DAO)          | Dirty tracking   |
| Complex SELECT with joins | `UserTable::select_cols(...)` (DSL)              | Full control     |
| Bulk UPDATE by condition  | `UserTable::update().set(...).where_(...)` (DSL) | No loading       |
| Delete by condition       | `UserTable::delete().where_(...)` (DSL)          | No loading       |
| Simple find by filter     | `User::find(filter)` (DAO)                       | Returns entities |

Both APIs work on the same schema. Mix freely.

---

## 16. Implementation Phases

Build order: **floz core first** (testable without a database), then **floz-macros**.
Each phase is small, self-contained, and includes its own tests.

---

### Phase 1 — Workspace + Skeleton

**Goal:** Compiles, does nothing useful yet.

- [✓] Create workspace `Cargo.toml`
- [✓] Create `floz/Cargo.toml` + `floz/src/lib.rs` (empty, re-exports)
- [✓] Create `floz-macros/Cargo.toml` + `floz-macros/src/lib.rs` (empty proc macro stub)
- [✓] Create `floz/src/prelude.rs`
- [✓] Verify `cargo build` passes

**Tests:** `cargo build` compiles cleanly.

---

### Phase 2 — Value Enum + FlozError

**Goal:** Core data types needed by everything else.

- [✓] `floz/src/value.rs``Value` enum with all variants (Int, Short, BigInt, String, Bool, etc.) + all `Option*`
  variants for typed nulls
- [✓] `floz/src/error.rs``FlozError` enum (NotFound, UniqueViolation, UnsavedEntity, MismatchedBulkInsertColumns, etc.)
- [✓] `impl From<T>` conversions for `Value` (e.g., `From<i32>`, `From<String>`, `From<Option<i32>>`)

**Tests:**

```rust
#[test]
fn value_from_i32() { assert!(matches!(Value::from(42), Value::Int(42))); }
#[test]
fn value_from_none_string() { assert!(matches!(Value::from(None::<String>), Value::OptionString(None))); }
#[test]
fn value_from_some_string() { assert!(matches!(Value::from(Some("hi".into())), Value::OptionString(Some(_)))); }
```

---

### Phase 3 — Column + Expression Tree

**Goal:** Typed columns and composable filter expressions. No SQL yet.

- [✓] `floz/src/column.rs``Column<T>` struct with `name()`, `table()`, `into_any()`
- [✓] `floz/src/column.rs` — Comparison methods: `.eq()`, `.ne()`, `.gt()`, `.gte()`, `.lt()`, `.lte()`
- [✓] `floz/src/column.rs` — Range methods: `.between()`, `.in_list()`, `.not_in()`
- [✓] `floz/src/column.rs` — String methods: `.like()`, `.ilike()`, `.contains()`, `.starts_with()`, `.ends_with()`
- [✓] `floz/src/column.rs` — Null methods: `.is_null()`, `.is_not_null()`
- [✓] `floz/src/column.rs` — Order methods: `.asc()`, `.desc()`, `.asc_nulls_last()`
- [✓] `floz/src/expr.rs``Expr` enum (Eq, Gt, And, Or, Not, InList, Between, Like, IsNull, etc.)
- [✓] `floz/src/expr.rs``.and()`, `.or()`, `.not()` combinators on `Expr`
- [✓] `AnyColumn` type-erased column for dynamic use

**Tests:**

```rust
#[test]
fn column_eq_creates_expr() {
    let col: Column<i32> = Column::new("age", "users");
    let expr = col.eq(25);
    assert!(matches!(expr, Expr::Eq(_, _)));
}
#[test]
fn expr_and_combines() {
    let e = col_age.eq(25).and(col_name.eq("Alice"));
    assert!(matches!(e, Expr::And(_, _)));
}
```

---

### Phase 4 — SQL Rendering (No DB)

**Goal:** Expression tree → SQL string + params. Tested via string assertions.

- [✓] `floz/src/expr.rs``Expr::to_sql(&self, sql, params, &mut idx)` renderer
- [✓] Handle: `$1, $2, $3` parameter numbering via shared counter
- [✓] Handle: empty `in_list``1=0`, empty `not_in``1=1`
- [✓] Handle: nested `And`/`Or` with automatic parentheses
- [✓] Handle: `BETWEEN $1 AND $2`
- [✓] Handle: `IS NULL`, `IS NOT NULL`
- [✓] Handle: `LIKE`, `ILIKE`

**Tests:**

```rust
#[test]
fn render_eq() {
    let (sql, params) = render(col_age.eq(25));
    assert_eq!(sql, "age = $1");
    assert_eq!(params, vec![Value::Int(25)]);
}
#[test]
fn render_and_or() {
    let (sql, _) = render(col_age.gt(18).and(col_name.eq("A").or(col_name.eq("B"))));
    assert_eq!(sql, "(age > $1 AND (name = $2 OR name = $3))");
}
#[test]
fn render_empty_in_list() {
    let (sql, params) = render(col_id.in_list(vec![]));
    assert_eq!(sql, "1=0");
    assert!(params.is_empty());
}
#[test]
fn render_between() {
    let (sql, _) = render(col_age.between(18, 65));
    assert_eq!(sql, "age BETWEEN $1 AND $2");
}
```

---

### Phase 5 — Query Builders + SQL Generation (No DB)

**Goal:** SelectQuery, InsertQuery, UpdateQuery, DeleteQuery → full SQL strings.

- [✓] `floz/src/query/select.rs``SelectQuery` with `.where_()`, `.order_by()`, `.limit()`, `.offset()`, `.distinct()`
- [✓] `floz/src/query/select.rs``SelectColsQuery` for column-specific selects
- [✓] `floz/src/query/insert.rs``InsertQuery` with `.set()`, `.returning()`, `.returning_col()`, `.returning_cols()`
- [✓] `floz/src/query/insert.rs``InsertManyQuery` with ragged-row validation
- [✓] `floz/src/query/insert.rs` — Upsert: `.on_conflict()`, `.do_update()`
- [✓] `floz/src/query/update.rs``UpdateQuery` with `.set()`, `.where_()`, `.returning()`
- [✓] `floz/src/query/delete.rs``DeleteQuery` with `.where_()`, `.all()`, `.returning()`
- [✓] Table name quoting for PostgreSQL schemas (`"auth"."users"`)

**Tests:**

```rust
#[test]
fn select_basic() {
    let (sql, _) = SelectQuery::new("users").where_(col_age.gt(25)).to_sql();
    assert_eq!(sql, "SELECT * FROM users WHERE age > $1");
}
#[test]
fn select_order_limit() {
    let (sql, _) = SelectQuery::new("users")
        .order_by(col_name.asc()).limit(10).to_sql();
    assert_eq!(sql, "SELECT * FROM users ORDER BY name ASC LIMIT 10");
}
#[test]
fn insert_basic() {
    let (sql, _) = InsertQuery::new("users")
        .set_raw("name", Value::String("Alice".into()))
        .set_raw("age", Value::Short(30))
        .to_sql();
    assert_eq!(sql, "INSERT INTO users (name, age) VALUES ($1, $2)");
}
#[test]
fn insert_returning() {
    let (sql, _) = InsertQuery::new("users")
        .set_raw("name", Value::String("A".into()))
        .returning_all().to_sql();
    assert!(sql.ends_with("RETURNING *"));
}
#[test]
fn update_basic() {
    let (sql, _) = UpdateQuery::new("users")
        .set_raw("age", Value::Short(31))
        .where_(col_id.eq(1)).to_sql();
    assert_eq!(sql, "UPDATE users SET age = $1 WHERE id = $2");
}
#[test]
fn delete_with_guard() {
    // delete without .where_() or .all() should error
    let result = DeleteQuery::new("users").to_sql();
    assert!(result.is_err());
}
#[test]
fn schema_qualified_table() {
    let (sql, _) = SelectQuery::new("auth.users").to_sql();
    assert_eq!(sql, r#"SELECT * FROM "auth"."users""#);
}
```

---

### Phase 6 — Db + Executor + Transactions (Requires PostgreSQL)

**Goal:** Connect to real PostgreSQL, execute raw SQL.

- [✓] `floz/src/db.rs``Db` struct wrapping `sqlx::PgPool`
- [✓] `floz/src/db.rs``Db::connect()`, `Db::from_pool()`, `Db::pool()`
- [✓] `floz/src/db.rs``Tx` struct wrapping `sqlx::Transaction`
- [✓] `floz/src/db.rs``Executor` trait with `for<'r>` bounds
- [✓] `floz/src/db.rs``impl Executor for Db` with Value → `.bind()` pattern-match loop
- [✓] `floz/src/db.rs``impl Executor for &mut Tx` with `&&mut` reborrow
- [✓] `floz/src/db.rs``db.begin()`, `tx.commit()`, `tx.savepoint()`

**Tests:** (integration, requires running PostgreSQL)

```rust
#[tokio::test]
async fn connect_and_execute() {
    let db = Db::connect(&test_url()).await.unwrap();
    let result = db.execute_raw("SELECT 1", vec![]).await;
    assert!(result.is_ok());
}
#[tokio::test]
async fn transaction_commit() {
    let db = Db::connect(&test_url()).await.unwrap();
    let mut tx = db.begin().await.unwrap();
    tx.execute_raw("CREATE TEMP TABLE test_tx (id INT)", vec![]).await.unwrap();
    tx.commit().await.unwrap();
}
#[tokio::test]
async fn transaction_rollback_on_drop() {
    let db = Db::connect(&test_url()).await.unwrap();
    {
        let mut tx = db.begin().await.unwrap();
        tx.execute_raw("CREATE TEMP TABLE test_drop (id INT)", vec![]).await.unwrap();
        // tx dropped here — should rollback
    }
    // table should not exist
}
```

---

### Phase 7 — Proc Macro: Schema Parsing

**Goal:** `schema!` macro parses the DSL into an internal AST. No code generation yet.

- [✓] `floz-macros/src/ast.rs``ModelDef`, `FieldDef`, `RelDef`, `TypeInfo`, `Modifier` structs
- [✓] `floz-macros/src/parse.rs` — Parse `model Name("table") { ... }` blocks
- [✓] `floz-macros/src/parse.rs` — Parse type functions: `integer("col")`, `varchar("col", N)`, etc.
- [✓] `floz-macros/src/parse.rs` — Parse modifier chains: `.auto_increment().primary().nullable()`
- [✓] `floz-macros/src/parse.rs` — Parse `array(Model, "fk")``RelDef` (separate bucket)
- [✓] `floz-macros/src/parse.rs` — Parse `@primary_key(a, b)`, `@unique(a, b)`, `@index(a)`
- [✓] `floz-macros/src/parse.rs` — Validate: unknown type → error, missing `max_length` for varchar → error
- [✓] `floz-macros/src/parse.rs` — Validate: >64 columns → compile error
- [✓] Split fields into `db_columns` vs `relationships`

**Tests:** (proc macro unit tests via `syn::parse_str`)

```rust
#[test]
fn parse_simple_model() {
    let ast = parse_schema("model User(\"users\") { id: integer(\"id\").auto_increment().primary() }");
    assert_eq!(ast.models[0].name, "User");
    assert_eq!(ast.models[0].table_name, "users");
    assert_eq!(ast.models[0].db_columns.len(), 1);
}
#[test]
fn parse_relationship_excluded_from_columns() {
    let ast = parse_schema("model Post(\"posts\") { id: integer(\"id\"), authors: array(User, \"author_id\") }");
    assert_eq!(ast.models[0].db_columns.len(), 1); // only id
    assert_eq!(ast.models[0].relationships.len(), 1); // authors
}
#[test]
fn parse_rejects_65_columns() {
    // Generate 65 fields, assert compile error
}
#[test]
fn parse_varchar_requires_length() {
    let result = try_parse("model X(\"x\") { name: varchar(\"name\") }");
    assert!(result.is_err());
}
```

---

### Phase 8 — Proc Macro: Code Generation (Struct + Table)

**Goal:** `schema!` generates the struct, Table namespace, and Column constants.

- [✓] `floz-macros/src/gen_struct.rs` — Generate `pub struct User { ... }` with derives
- [✓] `floz-macros/src/gen_struct.rs` — Generate `#[sqlx(default)] pub _dirty_flags: u64`
- [✓] `floz-macros/src/gen_struct.rs` — Generate `impl Default for User`
- [✓] `floz-macros/src/gen_table.rs` — Generate `pub struct UserTable;`
- [✓] `floz-macros/src/gen_table.rs` — Generate `UserTable::id`, `UserTable::name` Column constants
- [✓] `floz-macros/src/gen_table.rs` — Generate `UserTable::select()`, `insert()`, `update()`, `delete()`
- [✓] `floz-macros/src/lib.rs` — Wire it all together in `#[proc_macro] pub fn schema`
- [✓] Re-export `schema!` from `floz/src/lib.rs`

**Tests:** (compile-test + `cargo expand`)

```rust
floz::schema! {
    model User("users") {
        id:   integer("id").auto_increment().primary(),
        name: varchar("name", 100),
        age:  short("age"),
    }
}

#[test]
fn generated_struct_has_fields() {
    let u = User { id: 1, name: "A".into(), age: 20, _dirty_flags: 0 };
    assert_eq!(u.name, "A");
}
#[test]
fn generated_table_has_columns() {
    assert_eq!(UserTable::TABLE_NAME, "users");
    assert_eq!(UserTable::id.name(), "id");
    assert_eq!(UserTable::name.name(), "name");
}
#[test]
fn generated_default_works() {
    let u = User::default();
    assert_eq!(u.id, 0);
    assert_eq!(u._dirty_flags, 0);
}
#[test]
fn struct_literal_with_default() {
    let u = User { id: 99, name: "Test".into(), ..User::default() };
    assert_eq!(u.id, 99);
}
```

---

### Phase 9 — Proc Macro: DAO Methods

**Goal:** Generate `set_`, `save()`, `get()`, `create()`, CRUD on entities.

- [✓] `floz-macros/src/gen_struct.rs` — Generate `set_name()`, `set_age()` with bitmask
- [✓] `floz-macros/src/gen_struct.rs` — Generate `save(&mut self, db)` — dirty-only UPDATE + UnsavedEntity guard
- [✓] `floz-macros/src/gen_struct.rs` — Generate `delete(&self, db)`
- [✓] `floz-macros/src/gen_struct.rs` — Generate `get(id, db)`, `get_optional(id, db)`
- [✓] `floz-macros/src/gen_struct.rs` — Generate `find(filter, db)`, `find_one(filter, db)`, `all(db)`
- [✓] `floz-macros/src/gen_struct.rs` — Generate `exists(filter, db)`, `count(filter, db)`, `count_all(db)`
- [✓] `floz-macros/src/gen_struct.rs` — Generate `destroy(filter, db)` — bulk delete
- [✓] `floz-macros/src/gen_builder.rs` — Generate `User::create()` builder with `Option<T>` internals
- [✓] `floz-macros/src/gen_builder.rs` — Generate `user_row!` macro (fixed-size array)
- [✓] Handle composite PKs: `PostTag::get(post_id, tag_id, db)`
- [✓] Handle PK-less models: skip `get/save/delete/set_`

**Tests:** (integration, requires PostgreSQL)

```rust
#[tokio::test]
async fn create_and_get() {
    let db = test_db().await;
    let user = User::create().name("Alice").age(30).execute(&db).await.unwrap();
    assert!(user.id > 0);
    let fetched = User::get(user.id, &db).await.unwrap();
    assert_eq!(fetched.name, "Alice");
}
#[tokio::test]
async fn dirty_tracking() {
    let db = test_db().await;
    let mut user = User::get(1, &db).await.unwrap();
    user.set_name("Updated");
    assert!(user._dirty_flags != 0);
    user.save(&db).await.unwrap();
    assert_eq!(user._dirty_flags, 0);
}
#[tokio::test]
async fn save_unsaved_entity_errors() {
    let db = test_db().await;
    let mut user = User::default();
    user.set_name("Ghost");
    let result = user.save(&db).await;
    assert!(matches!(result, Err(FlozError::UnsavedEntity)));
}
#[tokio::test]
async fn save_noop_when_clean() {
    let db = test_db().await;
    let mut user = User::get(1, &db).await.unwrap();
    // No changes — save should be a no-op
    user.save(&db).await.unwrap();
}
```

---

### Phase 10 — Advanced DSL + Relationships

**Goal:** Joins, aggregates, relationships, upsert.

- [✓] JOINs: `.join()`, `.left_join()` on SelectQuery
- [✓] Aggregates: `.avg()`, `.sum()`, `.count()`, `.min()`, `.max()` on Column
- [✓] `.alias()` for aggregate expressions
- [✓] `.group_by()`, `.having()` on SelectQuery
- [✓] Subqueries: `.in_subquery()` on Column
- [✓] UPSERT: `.on_conflict()`, `.do_update()` on InsertQuery
- [✓] `floz-macros/src/gen_relations.rs` — Generate `fetch_` methods from `array()`
- [✓] `floz-macros/src/gen_relations.rs` — Generate `add_`, `remove_`, `set_` for M2M
- [✓] Auto-transaction wrapping for multi-statement relationship writes

**Tests:**

```rust
#[test]
fn join_sql_rendering() {
    let (sql, _) = SelectQuery::new("users")
        .cols(&["users.name", "posts.title"])
        .join("posts", col_author_id.eq(col_user_id))
        .to_sql();
    assert!(sql.contains("INNER JOIN posts ON"));
}
#[tokio::test]
async fn fetch_relationship() {
    let db = test_db().await;
    let user = User::get(1, &db).await.unwrap();
    let posts = user.fetch_posts(&db).await.unwrap();
    assert!(!posts.is_empty());
}
#[tokio::test]
async fn add_remove_m2m() {
    let db = test_db().await;
    let post = Post::get(1, &db).await.unwrap();
    let tag = Tag::get(1, &db).await.unwrap();
    post.add_tag(&tag, &db).await.unwrap();
    let tags = post.fetch_tags(&db).await.unwrap();
    assert!(tags.iter().any(|t| t.id == tag.id));
    post.remove_tag(&tag, &db).await.unwrap();
}
```

---

### Phase 11, 12, 13, 14

- [✓] Eager loading: `.with(PostTable)`
- [✓] Hooks (before_save, after_create)
- [✓] Pagination: `User::paginate().page(3).per_page(20)`
- [✓] Additional types: `json()`, `jsonb()`, `enumeration()`, `ltree()`

### Future Phases

- [ ] Schema management: `create::<User>()`, `drop`, `exists`, `create_sql()`
- [ ] Migration engine
- [ ] Reverse-engineer models from DB (CLI)
- [ ] MySQL / SQLite backends

---

## 17. Implementation Traps (Reference During Build)

These are known technical traps to keep in mind during implementation.

### Trap 1: Bulk Insert Ragged Rows

`insert_many` generates `INSERT INTO users (name, age) VALUES ($1, $2), ($3, $4)`.
Every row **must** supply the same columns. If rows have mismatched columns:

```rust
UserTable::insert_many( & [
user_row! { name: "Alice", age: 30 },
user_row! { name: "Bob" }, // Missing age!
])
```

**Fix:** Grab the column list from the first row. For subsequent rows, if a column is
missing, return `FlozError::MismatchedBulkInsertColumns`. Fail fast — don't silently pad
with nulls. Add this error variant:

```rust
#[error("Bulk insert rows have mismatched columns: row {row} is missing `{column}`")]
MismatchedBulkInsertColumns { row: usize, column: String },
```

### Trap 2: Parameter Counter Across AST Nodes

PostgreSQL uses numbered params: `$1, $2, $3`. When rendering a nested expression tree
like `(age > $1 AND name = $2) OR (id = $3)`, the counter must be shared.

**Fix:** Thread a `&mut usize` counter through all `to_sql()` render methods:

```rust
impl Expr {
    fn to_sql(&self, sql: &mut String, params: &mut Vec<Value>, idx: &mut usize) {
        match self {
            Expr::Eq(col, val) => {
                *idx += 1;
                write!(sql, "{} = ${}", col.name(), idx).unwrap();
                params.push(val.clone());
            }
            Expr::And(left, right) => {
                sql.push('(');
                left.to_sql(sql, params, idx);
                sql.push_str(" AND ");
                right.to_sql(sql, params, idx);
                sql.push(')');
            }
            // ...
        }
    }
}
```

### Trap 3: Relationship Fields Must NOT Enter the Struct

In the schema, `array()` declarations sit alongside real columns:

```rust
model Post("posts") {
title: varchar("title", 255),       // Real column
authors: array(User, "author_id"),    // Relationship — NOT a column
}
```

If the proc macro accidentally puts `pub authors: Vec<User>` in `struct Post`,
`sqlx::FromRow` will panic at runtime because there's no `authors` column in PostgreSQL.

**Fix:** In `floz-macros/src/parse.rs`, split parsed fields into two buckets:

```rust
struct ModelDef {
    name: Ident,
    table_name: String,
    db_columns: Vec<FieldDef>,      // → go into struct + Column constants
    relationships: Vec<RelDef>,     // → only generate fetch_/add_/remove_ methods
}
```

Only `db_columns` participate in struct generation, `FromRow`, dirty flags, and
`UserTable` Column constants. `relationships` only produce impl methods.

### Trap 4: Empty `IN ()` Clause

`UserTable::id.in_list(vec![1, 2, 3])` renders `id IN ($1, $2, $3)`.
But if the user passes an empty vec dynamically, a naive renderer produces
`id IN ()` — which PostgreSQL **rejects** with a syntax error.

**Fix:** Short-circuit to `1=0` (always false, which is logically correct):

```rust
Expr::InList(col, values) => {
if values.is_empty() {
sql.push_str("1=0"); // Empty IN is logically impossible
} else {
write ! (sql, "{} IN (", col.name()).unwrap();
for (i, val) in values.iter().enumerate() {
if i > 0 { sql.push_str(", "); }
* idx += 1;
write ! (sql, "${}", idx).unwrap();
params.push(val.clone());
}
sql.push(')');
}
}
```

Similarly, `not_in` with an empty list should render `1=1` (always true — nothing is excluded).

*Working name: `floz`*
*License: To be decided.*

---

## Appendix: Additional Implementation Notes

### Note A: Models Without Primary Keys

Append-only tables (audit logs, metrics) may intentionally lack a primary key.
When `floz-macros` detects no `.primary()` modifier and no `@primary_key(...)` constraint,
it must:

- **Skip generating:** `get()`, `get_optional()`, `save()`, `delete()`, `set_` methods, `_dirty_flags`
- **Still generate:** `create()`, `find()`, `find_one()`, `all()`, `count()`, `exists()`
- **Still generate:** full `ModelTable` DSL (select, insert, update, delete)

This is not an error — it's a valid use case. No compile error needed.

### Note B: FromRow Trait Bound

The `Executor` trait uses `for<'r> sqlx::FromRow<'r, PgRow>` for generic fetch methods.
This Higher-Rank Trait Bound (HRTB) tells Rust that `T` can be constructed from a row
with *any* lifetime, which is required for sqlx's stream-based row fetching.
All generated structs automatically satisfy this via `#[derive(sqlx::FromRow)]`.

### Note C: user_row! Zero-Allocation Design

`user_row!` expands to a **fixed-size array** `[(AnyColumn, Value); N]` instead of `Vec`.
For 10,000-row bulk inserts, this avoids 10,000 small heap allocations.
`insert_many` accepts `&[&[(AnyColumn, Value)]]` — a slice of slices, all stack-allocated.

### Note D: Executor `&&mut Tx` Reborrow

Because `sqlx::query().execute()` requires `&mut PgConnection`, but the `Executor` trait
takes `&self`, implementing `Executor` for `&mut Tx` means `self` resolves to `&&mut Tx`.
Inside the implementation, you'll need a double-deref reborrow:

```rust
impl Executor for &mut Tx {
    async fn execute_raw(&self, sql: &str, params: Vec<Value>) -> Result<u64, FlozError> {
        let conn: &mut PgConnection = &mut **self; // double-deref reborrow
        // ... bind and execute on conn
    }
}
```

This is standard Rust — don't let the compiler error confuse you.