entity-derive 0.22.8

Derive macro for generating DTOs, repositories, and SQL from a single entity definition
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
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
// SPDX-FileCopyrightText: 2025-2026 RAprogramm <andrey.rozanov.vl@gmail.com>
// SPDX-License-Identifier: MIT

//! Generated SQL executed against a live Postgres server.
//!
//! The trybuild cases in `tests/cases` prove that the macro emits code
//! that compiles; nothing there proves that the emitted *SQL* is valid.
//! This target closes that gap: the generated DDL creates real tables
//! and the generated repository methods run real statements against
//! them.
//!
//! Each entity lives in its own module so that the repository traits —
//! all of which are implemented for `sqlx::PgPool` — never collide in
//! method resolution.
//!
//! See [`pg`] for how to point the suite at a server; without one every
//! case reports a skip and passes.

mod pg;

/// CRUD, bulk, keyset pagination, upsert, projections, filtering and
/// schema assertion over a single richly annotated entity.
mod articles {
    use chrono::{DateTime, Utc};
    use entity_derive::Entity;
    use uuid::Uuid;

    use crate::pg;

    #[derive(Debug, Clone, Entity)]
    #[entity(table = "articles", migrations, upsert(conflict = "slug"))]
    #[projection(Card: id, title, views)]
    pub struct Article {
        #[id]
        pub id: Uuid,

        #[field(create, update, response)]
        #[sort]
        #[filter(like)]
        pub title: String,

        #[field(create, response)]
        #[column(unique)]
        pub slug: String,

        #[field(create, response)]
        pub body: String,

        #[field(create, update, response)]
        #[sort]
        #[filter(range)]
        pub views: i64,

        /// Populated by the database: the generated INSERT skips
        /// `#[auto]` columns, so the DDL supplies the value.
        #[field(response)]
        #[auto]
        pub created_at: DateTime<Utc>
    }

    /// Build a create request with distinct values per call.
    fn draft(slug: &str, title: &str, views: i64) -> CreateArticleRequest {
        CreateArticleRequest {
            title: title.to_owned(),
            slug: slug.to_owned(),
            body: format!("body of {slug}"),
            views
        }
    }

    #[tokio::test]
    async fn crud_roundtrip() {
        let Some(db) = pg::provision("crud", &[Article::MIGRATION_UP]).await else {
            return;
        };
        let pool = db.pool();

        let created = pool
            .create(draft("hello", "Hello", 1))
            .await
            .expect("create failed");
        assert_eq!(created.title, "Hello");
        assert_eq!(created.views, 1);

        let found = pool
            .find_by_id(created.id)
            .await
            .expect("find_by_id failed")
            .expect("row missing right after create");
        assert_eq!(found.slug, "hello");
        assert_eq!(
            found.created_at, created.created_at,
            "the auto column must come back from the database, not from the DTO"
        );

        let updated = pool
            .update(
                created.id,
                UpdateArticleRequest {
                    title: Some("Hello again".to_owned()),
                    views: Some(7)
                }
            )
            .await
            .expect("update failed");
        assert_eq!(updated.title, "Hello again");
        assert_eq!(updated.views, 7);
        assert_eq!(updated.body, created.body, "update must not touch body");

        let listed = pool.list(10, 0).await.expect("list failed");
        assert_eq!(listed.len(), 1);

        assert!(pool.delete(created.id).await.expect("delete failed"));
        assert!(
            pool.find_by_id(created.id)
                .await
                .expect("find_by_id failed")
                .is_none()
        );

        db.teardown().await;
    }

    #[tokio::test]
    async fn bulk_and_keyset_pagination() {
        let Some(db) = pg::provision("bulk", &[Article::MIGRATION_UP]).await else {
            return;
        };
        let pool = db.pool();

        let created = pool
            .create_many(vec![
                draft("a", "A", 10),
                draft("b", "B", 20),
                draft("c", "C", 30),
            ])
            .await
            .expect("create_many failed");
        assert_eq!(created.len(), 3);

        let ids: Vec<Uuid> = created.iter().map(|a| a.id).collect();
        let fetched = pool
            .find_by_ids(ids.clone())
            .await
            .expect("find_by_ids failed");
        assert_eq!(fetched.len(), 3);

        let first_page = pool.list_after(None, 2).await.expect("list_after failed");
        assert_eq!(first_page.len(), 2);
        let cursor = first_page.last().map(|a| a.id);
        let second_page = pool
            .list_after(cursor, 2)
            .await
            .expect("list_after with cursor failed");
        assert_eq!(second_page.len(), 1);
        assert!(
            !second_page
                .iter()
                .any(|a| first_page.iter().any(|p| p.id == a.id)),
            "keyset pages must not overlap"
        );

        let removed = pool.delete_many(ids).await.expect("delete_many failed");
        assert_eq!(removed, 3);

        db.teardown().await;
    }

    #[tokio::test]
    async fn upsert_touches_only_update_columns() {
        let Some(db) = pg::provision("upsert", &[Article::MIGRATION_UP]).await else {
            return;
        };
        let pool = db.pool();

        let original = pool
            .upsert(draft("guide", "Guide", 5))
            .await
            .expect("first upsert failed");

        let mut conflicting = draft("guide", "Guide v2", 9);
        conflicting.body = "rewritten body".to_owned();
        let merged = pool
            .upsert(conflicting)
            .await
            .expect("second upsert failed");

        assert_eq!(
            merged.id, original.id,
            "conflict must reuse the existing row"
        );
        assert_eq!(merged.title, "Guide v2", "update-marked column must change");
        assert_eq!(merged.views, 9, "update-marked column must change");
        assert_eq!(
            merged.body, original.body,
            "column without #[field(update)] must survive the conflict"
        );

        db.teardown().await;
    }

    #[tokio::test]
    async fn query_filters_and_sorts() {
        let Some(db) = pg::provision("query", &[Article::MIGRATION_UP]).await else {
            return;
        };
        let pool = db.pool();

        pool.create_many(vec![
            draft("rust-1", "Rust patterns", 100),
            draft("rust-2", "Rust internals", 50),
            draft("go-1", "Go patterns", 300),
            draft("pct", "100% coverage", 1),
        ])
        .await
        .expect("create_many failed");

        let matched = pool
            .query(ArticleQuery {
                title: Some("rust".to_owned()),
                sort: Some(ArticleSortField::ViewsDesc),
                limit: Some(10),
                ..Default::default()
            })
            .await
            .expect("query failed");
        assert_eq!(matched.len(), 2, "ILIKE filter must exclude the Go article");
        assert_eq!(matched[0].views, 100, "sort must order by views descending");

        let literal = pool
            .query(ArticleQuery {
                title: Some("100%".to_owned()),
                ..Default::default()
            })
            .await
            .expect("query with a wildcard character failed");
        assert_eq!(
            literal.len(),
            1,
            "a % inside the filter value must match literally, not as a wildcard"
        );

        let ranged = pool
            .query(ArticleQuery {
                views_from: Some(60),
                ..Default::default()
            })
            .await
            .expect("range query failed");
        assert_eq!(ranged.len(), 2, "range filter must keep views >= 60");

        let windowed = pool
            .query(ArticleQuery {
                views_from: Some(40),
                views_to: Some(150),
                ..Default::default()
            })
            .await
            .expect("bounded range query failed");
        assert_eq!(windowed.len(), 2, "both range bounds must apply");

        db.teardown().await;
    }

    #[tokio::test]
    async fn projection_returns_subset() {
        let Some(db) = pg::provision("projection", &[Article::MIGRATION_UP]).await else {
            return;
        };
        let pool = db.pool();

        let created = pool
            .create(draft("card", "Card", 3))
            .await
            .expect("create failed");

        let card: ArticleCard = pool
            .find_by_id_card(created.id)
            .await
            .expect("find_by_id_card failed")
            .expect("projection row missing");
        assert_eq!(card.id, created.id);
        assert_eq!(card.title, "Card");
        assert_eq!(card.views, 3);

        db.teardown().await;
    }

    #[tokio::test]
    async fn schema_assertion_detects_drift() {
        let Some(db) = pg::provision("drift", &[Article::MIGRATION_UP]).await else {
            return;
        };
        let pool = db.pool();

        Article::assert_schema(pool)
            .await
            .expect("freshly migrated table must match the entity");

        db.run("ALTER TABLE articles DROP COLUMN body").await;
        let drift = Article::assert_schema(pool)
            .await
            .expect_err("dropping a column must be reported as drift");
        assert!(
            drift.to_string().contains("body"),
            "drift report must name the missing column, got: {drift}"
        );

        db.teardown().await;
    }

    #[tokio::test]
    async fn migration_down_reverses_up() {
        let Some(db) = pg::provision("migration", &[Article::MIGRATION_UP]).await else {
            return;
        };

        Article::assert_schema(db.pool())
            .await
            .expect("MIGRATION_UP must create the declared table");

        db.run(Article::MIGRATION_DOWN).await;
        Article::assert_schema(db.pool())
            .await
            .expect_err("MIGRATION_DOWN must remove the table");

        db.run(Article::MIGRATION_UP).await;
        Article::assert_schema(db.pool())
            .await
            .expect("MIGRATION_UP must be repeatable after a down migration");

        db.teardown().await;
    }
}

/// Unique and case-insensitive lookup methods.
mod accounts {
    use entity_derive::Entity;
    use uuid::Uuid;

    use crate::pg;

    #[derive(Debug, Clone, Entity)]
    #[entity(table = "accounts", migrations)]
    pub struct Account {
        #[id]
        pub id: Uuid,

        #[field(create, response)]
        #[column(unique, ci)]
        pub email: String,

        #[field(create, update, response)]
        pub name: String
    }

    #[tokio::test]
    async fn lookups_are_case_insensitive_when_declared() {
        let Some(db) = pg::provision("lookup", &[Account::MIGRATION_UP]).await else {
            return;
        };
        let pool = db.pool();

        let created = pool
            .create(CreateAccountRequest {
                email: "Ada@Example.COM".to_owned(),
                name:  "Ada".to_owned()
            })
            .await
            .expect("create failed");

        let exact = pool
            .find_by_email("Ada@Example.COM".to_owned())
            .await
            .expect("find_by_email failed")
            .expect("row missing for the exact spelling");
        assert_eq!(exact.id, created.id);

        let folded = pool
            .find_by_email("ada@example.com".to_owned())
            .await
            .expect("find_by_email failed")
            .expect("ci column must match a differently cased spelling");
        assert_eq!(folded.id, created.id);

        assert!(
            pool.exists_by_email("ADA@EXAMPLE.COM".to_owned())
                .await
                .expect("exists_by_email failed")
        );

        let duplicate = pool
            .create(CreateAccountRequest {
                email: "ADA@example.com".to_owned(),
                name:  "Impostor".to_owned()
            })
            .await;
        assert!(
            duplicate.is_err(),
            "the LOWER() unique index must reject a case variant"
        );

        db.teardown().await;
    }
}

/// Soft-delete lifecycle: hidden reads, restore, hard delete.
mod notes {
    use chrono::{DateTime, Utc};
    use entity_derive::Entity;
    use uuid::Uuid;

    use crate::pg;

    #[derive(Debug, Clone, Entity)]
    #[entity(table = "notes", soft_delete, migrations)]
    pub struct Note {
        #[id]
        pub id: Uuid,

        #[field(create, update, response)]
        pub title: String,

        #[field(skip)]
        pub deleted_at: Option<DateTime<Utc>>
    }

    #[tokio::test]
    async fn soft_delete_lifecycle() {
        let Some(db) = pg::provision("softdelete", &[Note::MIGRATION_UP]).await else {
            return;
        };
        let pool = db.pool();

        let note = pool
            .create(CreateNoteRequest {
                title: "Draft".to_owned()
            })
            .await
            .expect("create failed");

        assert!(pool.delete(note.id).await.expect("soft delete failed"));
        assert!(
            pool.find_by_id(note.id)
                .await
                .expect("find_by_id failed")
                .is_none(),
            "soft-deleted rows must be hidden from find_by_id"
        );
        assert!(
            pool.list(10, 0).await.expect("list failed").is_empty(),
            "soft-deleted rows must be hidden from list"
        );
        assert!(
            pool.find_by_id_with_deleted(note.id)
                .await
                .expect("find_by_id_with_deleted failed")
                .is_some(),
            "the row must still exist physically"
        );

        assert!(pool.restore(note.id).await.expect("restore failed"));
        assert!(
            pool.find_by_id(note.id)
                .await
                .expect("find_by_id failed")
                .is_some(),
            "restore must bring the row back"
        );

        assert!(pool.hard_delete(note.id).await.expect("hard_delete failed"));
        assert!(
            pool.find_by_id_with_deleted(note.id)
                .await
                .expect("find_by_id_with_deleted failed")
                .is_none(),
            "hard_delete must remove the row"
        );

        db.teardown().await;
    }

    #[tokio::test]
    async fn soft_deleted_rows_stay_out_of_every_read() {
        let Some(db) = pg::provision("softreads", &[Note::MIGRATION_UP]).await else {
            return;
        };
        let pool = db.pool();

        let kept = pool
            .create(CreateNoteRequest {
                title: "kept".to_owned()
            })
            .await
            .expect("create failed");
        let removed = pool
            .create(CreateNoteRequest {
                title: "removed".to_owned()
            })
            .await
            .expect("create failed");

        assert!(pool.delete(removed.id).await.expect("soft delete failed"));

        let visible = pool.list(10, 0).await.expect("list failed");
        assert_eq!(visible.len(), 1);
        assert_eq!(visible[0].id, kept.id);

        let everything = pool
            .list_with_deleted(10, 0)
            .await
            .expect("list_with_deleted failed");
        assert_eq!(
            everything.len(),
            2,
            "the deleted row must still be listable"
        );

        let by_ids = pool
            .find_by_ids(vec![kept.id, removed.id])
            .await
            .expect("find_by_ids failed");
        assert_eq!(
            by_ids.len(),
            1,
            "a bulk read must respect the soft delete as well"
        );

        let deleted_count = pool
            .delete_many(vec![kept.id])
            .await
            .expect("delete_many failed");
        assert_eq!(deleted_count, 1);
        assert!(
            pool.list(10, 0).await.expect("list failed").is_empty(),
            "the bulk delete must apply the soft delete too"
        );
        assert_eq!(
            pool.list_with_deleted(10, 0)
                .await
                .expect("list_with_deleted failed")
                .len(),
            2,
            "a soft bulk delete must not remove rows physically"
        );

        db.teardown().await;
    }
}

/// Optimistic locking via the `#[version]` column.
mod orders {
    use entity_derive::Entity;
    use uuid::Uuid;

    use crate::pg;

    #[derive(Debug, Clone, Entity)]
    #[entity(table = "orders", migrations)]
    pub struct Order {
        #[id]
        pub id: Uuid,

        #[field(create, update, response)]
        pub note: String,

        #[version]
        #[field(response)]
        #[auto]
        pub version: i32
    }

    #[tokio::test]
    async fn stale_version_is_rejected() {
        let Some(db) = pg::provision("version", &[Order::MIGRATION_UP]).await else {
            return;
        };
        let pool = db.pool();

        let order = pool
            .create(CreateOrderRequest {
                note: "first".to_owned()
            })
            .await
            .expect("create failed");
        assert_eq!(order.version, 0, "a fresh row starts at version 0");

        let bumped = pool
            .update(
                order.id,
                UpdateOrderRequest {
                    note:             Some("second".to_owned()),
                    expected_version: order.version
                }
            )
            .await
            .expect("update with the current version must succeed");
        assert_eq!(bumped.version, 1, "a successful update bumps the version");

        let stale = pool
            .update(
                order.id,
                UpdateOrderRequest {
                    note:             Some("third".to_owned()),
                    expected_version: order.version
                }
            )
            .await;
        assert!(
            stale.is_err(),
            "an update carrying a stale version must be rejected"
        );

        db.teardown().await;
    }
}

/// Relations: parent lookups, child lookups and the junction table
/// behind a many-to-many link.
mod relations {
    use entity_derive::Entity;
    use uuid::Uuid;

    use crate::pg;

    #[derive(Debug, Clone, Entity)]
    #[entity(table = "authors", migrations)]
    #[has_many(Book)]
    #[has_many(Genre, through = "author_genres")]
    pub struct Author {
        #[id]
        pub id: Uuid,

        #[field(create, update, response)]
        pub name: String
    }

    #[derive(Debug, Clone, Entity)]
    #[entity(table = "books", migrations)]
    pub struct Book {
        #[id]
        pub id: Uuid,

        #[belongs_to(Author)]
        #[field(create, response)]
        pub author_id: Uuid,

        #[field(create, update, response)]
        pub title: String
    }

    #[derive(Debug, Clone, Entity)]
    #[entity(table = "genres", migrations)]
    pub struct Genre {
        #[id]
        pub id: Uuid,

        #[field(create, update, response)]
        pub label: String
    }

    /// Every table plus the junction DDL the many-to-many link needs.
    fn migrations() -> Vec<&'static str> {
        let mut scripts = vec![
            Author::MIGRATION_UP,
            Genre::MIGRATION_UP,
            Book::MIGRATION_UP,
        ];
        scripts.extend_from_slice(Author::MIGRATION_JUNCTIONS);
        scripts
    }

    #[tokio::test]
    async fn parent_and_child_lookups() {
        let Some(db) = pg::provision("relations", &migrations()).await else {
            return;
        };
        let pool = db.pool();

        let author = AuthorRepository::create(
            pool,
            CreateAuthorRequest {
                name: "Ada".to_owned()
            }
        )
        .await
        .expect("create author failed");
        let book = BookRepository::create(
            pool,
            CreateBookRequest {
                author_id: author.id,
                title:     "Notes".to_owned()
            }
        )
        .await
        .expect("create book failed");

        let books = pool
            .find_books(author.id)
            .await
            .expect("has_many lookup failed");
        assert_eq!(books.len(), 1, "the author must own exactly one book");
        assert_eq!(books[0].id, book.id);

        let parent = pool
            .find_author(book.id)
            .await
            .expect("belongs_to lookup failed")
            .expect("the book must resolve its author");
        assert_eq!(parent.id, author.id);

        db.teardown().await;
    }

    #[tokio::test]
    async fn many_to_many_link_lifecycle() {
        let Some(db) = pg::provision("junction", &migrations()).await else {
            return;
        };
        let pool = db.pool();

        let author = AuthorRepository::create(
            pool,
            CreateAuthorRequest {
                name: "Grace".to_owned()
            }
        )
        .await
        .expect("create author failed");
        let genre = GenreRepository::create(
            pool,
            CreateGenreRequest {
                label: "essays".to_owned()
            }
        )
        .await
        .expect("create genre failed");

        assert!(
            !pool
                .has_genre(author.id, genre.id)
                .await
                .expect("has_ lookup failed"),
            "no link exists yet"
        );

        pool.add_genre(author.id, genre.id)
            .await
            .expect("add_ failed");
        assert!(
            pool.has_genre(author.id, genre.id)
                .await
                .expect("has_ lookup failed")
        );

        let linked = pool
            .find_genres(author.id)
            .await
            .expect("through lookup failed");
        assert_eq!(linked.len(), 1);
        assert_eq!(linked[0].id, genre.id);

        assert!(
            pool.remove_genre(author.id, genre.id)
                .await
                .expect("remove_ failed")
        );
        assert!(
            pool.find_genres(author.id)
                .await
                .expect("through lookup failed")
                .is_empty()
        );

        db.teardown().await;
    }
}

/// Ownership scoping: every scoped method must refuse rows owned by
/// somebody else.
mod scoping {
    use chrono::{DateTime, Utc};
    use entity_derive::Entity;
    use uuid::Uuid;

    use crate::pg;

    #[derive(Debug, Clone, Entity)]
    #[entity(table = "tickets", soft_delete, migrations)]
    pub struct Ticket {
        #[id]
        pub id: Uuid,

        #[owner]
        #[field(create, response)]
        pub owner_id: Uuid,

        #[field(create, update, response)]
        pub subject: String,

        #[field(skip)]
        pub deleted_at: Option<DateTime<Utc>>
    }

    #[tokio::test]
    async fn scoped_methods_refuse_another_owner() {
        let Some(db) = pg::provision("scoped", &[Ticket::MIGRATION_UP]).await else {
            return;
        };
        let pool = db.pool();

        let mine = Uuid::now_v7();
        let theirs = Uuid::now_v7();

        let ticket = pool
            .create(CreateTicketRequest {
                owner_id: mine,
                subject:  "printer".to_owned()
            })
            .await
            .expect("create failed");

        assert!(
            pool.find_by_id_scoped(ticket.id, mine)
                .await
                .expect("scoped read failed")
                .is_some()
        );
        assert!(
            pool.find_by_id_scoped(ticket.id, theirs)
                .await
                .expect("scoped read failed")
                .is_none(),
            "another owner must not see the row"
        );

        let mine_only = pool
            .list_by_owner(mine, 10, 0)
            .await
            .expect("list_by_owner failed");
        assert_eq!(mine_only.len(), 1);
        assert!(
            pool.list_by_owner(theirs, 10, 0)
                .await
                .expect("list_by_owner failed")
                .is_empty()
        );

        assert!(
            pool.update_scoped(
                ticket.id,
                theirs,
                UpdateTicketRequest {
                    subject: Some("hijacked".to_owned())
                }
            )
            .await
            .expect("scoped update failed")
            .is_none(),
            "another owner must not update the row"
        );
        let updated = pool
            .update_scoped(
                ticket.id,
                mine,
                UpdateTicketRequest {
                    subject: Some("scanner".to_owned())
                }
            )
            .await
            .expect("scoped update failed")
            .expect("the owner must update the row");
        assert_eq!(updated.subject, "scanner");

        assert!(
            !pool
                .delete_scoped(ticket.id, theirs)
                .await
                .expect("scoped delete failed"),
            "another owner must not delete the row"
        );
        assert!(
            pool.delete_scoped(ticket.id, mine)
                .await
                .expect("scoped delete failed")
        );
        assert!(
            pool.find_by_id(ticket.id)
                .await
                .expect("read failed")
                .is_none(),
            "the scoped delete must apply the soft delete"
        );

        db.teardown().await;
    }
}

/// The transaction adapter and the aggregate-root `save()`, including
/// what a rollback must undo.
mod transactional {
    use entity_derive::Entity;
    use uuid::Uuid;

    use crate::pg;

    #[derive(Debug, Clone, Entity)]
    #[entity(
        table = "wallets",
        migrations,
        transactions,
        aggregate_root,
        upsert(conflict = "holder")
    )]
    pub struct Wallet {
        #[id]
        pub id: Uuid,

        #[field(create, response)]
        #[column(unique)]
        pub holder: String,

        #[field(create, update, response)]
        pub balance: i64
    }

    #[tokio::test]
    async fn adapter_writes_inside_one_transaction() {
        let Some(db) = pg::provision("tx", &[Wallet::MIGRATION_UP]).await else {
            return;
        };
        let pool = db.pool();

        let mut tx = pool.begin().await.expect("begin failed");
        let mut repo = WalletTransactionRepo::new(&mut tx);
        let created = repo
            .create(CreateWalletRequest {
                holder:  "ada".to_owned(),
                balance: 100
            })
            .await
            .expect("transactional create failed");
        let updated = repo
            .update(
                created.id,
                UpdateWalletRequest {
                    balance: Some(250)
                }
            )
            .await
            .expect("transactional update failed");
        assert_eq!(updated.balance, 250);
        let merged = repo
            .upsert(CreateWalletRequest {
                holder:  "ada".to_owned(),
                balance: 400
            })
            .await
            .expect("transactional upsert failed");
        assert_eq!(merged.id, created.id, "the upsert must hit the same row");
        tx.commit().await.expect("commit failed");

        let stored = pool
            .find_by_id(created.id)
            .await
            .expect("read failed")
            .expect("the committed row must be visible");
        assert_eq!(stored.balance, 400);

        db.teardown().await;
    }

    #[tokio::test]
    async fn rollback_undoes_the_whole_unit() {
        let Some(db) = pg::provision("rollback", &[Wallet::MIGRATION_UP]).await else {
            return;
        };
        let pool = db.pool();

        let mut tx = pool.begin().await.expect("begin failed");
        let mut repo = WalletTransactionRepo::new(&mut tx);
        let created = repo
            .create(CreateWalletRequest {
                holder:  "grace".to_owned(),
                balance: 10
            })
            .await
            .expect("transactional create failed");
        tx.rollback().await.expect("rollback failed");

        assert!(
            pool.find_by_id(created.id)
                .await
                .expect("read failed")
                .is_none(),
            "a rolled back write must leave nothing behind"
        );

        db.teardown().await;
    }

    #[tokio::test]
    async fn row_lock_blocks_a_concurrent_writer() {
        let Some(db) = pg::provision("rowlock", &[Wallet::MIGRATION_UP]).await else {
            return;
        };
        let pool = db.pool();

        let wallet = pool
            .create(CreateWalletRequest {
                holder:  "linus".to_owned(),
                balance: 1
            })
            .await
            .expect("create failed");

        let mut holder = pool.begin().await.expect("begin failed");
        let mut repo = WalletTransactionRepo::new(&mut holder);
        let locked = repo
            .find_by_id_for_update(wallet.id)
            .await
            .expect("row lock failed")
            .expect("the row must be there to lock");
        assert_eq!(locked.id, wallet.id);

        let contender = pool.clone();
        let blocked = tokio::time::timeout(std::time::Duration::from_millis(300), async move {
            let mut tx = contender.begin().await.expect("begin failed");
            let mut repo = WalletTransactionRepo::new(&mut tx);
            repo.find_by_id_for_update(wallet.id).await
        })
        .await;
        assert!(
            blocked.is_err(),
            "a second FOR UPDATE must wait while the first transaction holds the row"
        );

        holder.rollback().await.expect("rollback failed");

        db.teardown().await;
    }

    #[tokio::test]
    async fn aggregate_root_save_persists() {
        let Some(db) = pg::provision("save", &[Wallet::MIGRATION_UP]).await else {
            return;
        };
        let pool = db.pool();

        let saved = pool
            .save(NewWallet {
                holder:  "hopper".to_owned(),
                balance: 7
            })
            .await
            .expect("save failed");

        let stored = pool
            .find_by_id(saved.id)
            .await
            .expect("read failed")
            .expect("save must persist the row");
        assert_eq!(stored.holder, "hopper");
        assert_eq!(stored.balance, 7);

        db.teardown().await;
    }
}

/// Migration extras: extensions, triggers, indexes, checks and foreign
/// keys have to survive contact with the server, not just string
/// assertions.
mod migration_extras {
    use chrono::{DateTime, Utc};
    use entity_derive::Entity;
    use uuid::Uuid;

    use crate::pg;

    #[derive(Debug, Clone, Entity)]
    #[entity(
        table = "posts",
        migrations(touch_updated_at, audit),
        unique_index(space_id, slug)
    )]
    pub struct Post {
        #[id]
        pub id: Uuid,

        #[field(create, response)]
        pub space_id: Uuid,

        #[field(create, response)]
        pub slug: String,

        #[field(create, update, response)]
        #[filter(search)]
        pub title: String,

        #[field(create, update, response)]
        #[column(check = "score >= 0")]
        pub score: i32,

        #[field(create, update, response)]
        #[column(index = "gin")]
        pub tags: Vec<String>,

        #[field(response)]
        #[auto]
        pub updated_at: DateTime<Utc>
    }

    /// Extensions, then enum types, then the table, then triggers — the
    /// order a migration runner has to apply them in.
    fn migrations() -> Vec<&'static str> {
        let mut scripts = Vec::new();
        scripts.extend_from_slice(Post::MIGRATION_EXTENSIONS);
        scripts.push(Post::MIGRATION_UP);
        scripts.extend_from_slice(Post::MIGRATION_TRIGGERS);
        scripts
    }

    fn draft(slug: &str, title: &str, score: i32) -> CreatePostRequest {
        CreatePostRequest {
            space_id: Uuid::nil(),
            slug: slug.to_owned(),
            title: title.to_owned(),
            score,
            tags: vec!["rust".to_owned()]
        }
    }

    #[tokio::test]
    async fn declared_ddl_applies_and_holds() {
        let Some(db) = pg::provision("ddl", &migrations()).await else {
            return;
        };
        let pool = db.pool();

        let post = pool
            .create(draft("first", "Postgres in anger", 3))
            .await
            .expect("create failed");

        assert!(
            pool.create(draft("first", "Duplicate slug", 1))
                .await
                .is_err(),
            "the composite unique index must reject the duplicate pair"
        );

        assert!(
            pool.create(draft("second", "Negative", -1)).await.is_err(),
            "the check constraint must reject a negative score"
        );

        let hits = pool
            .query(PostQuery {
                title: Some("anger".to_owned()),
                ..Default::default()
            })
            .await
            .expect("trigram search failed");
        assert_eq!(hits.len(), 1, "the search filter must find the substring");

        let before = post.updated_at;
        pool.update(
            post.id,
            UpdatePostRequest {
                title: Some("Postgres, calmly".to_owned()),
                score: Some(4),
                tags:  Some(vec!["rust".to_owned(), "sql".to_owned()])
            }
        )
        .await
        .expect("update failed");
        let after = pool
            .find_by_id(post.id)
            .await
            .expect("read failed")
            .expect("row missing")
            .updated_at;
        assert!(
            after > before,
            "the touch_updated_at trigger must move the timestamp: {before} -> {after}"
        );

        let audited: i64 =
            sqlx::query_scalar("SELECT count(*) FROM entity_audit_log WHERE table_name = 'posts'")
                .fetch_one(pool)
                .await
                .expect("audit table missing");
        assert!(
            audited >= 2,
            "the audit trigger must have recorded the insert and the update, got {audited}"
        );

        db.teardown().await;
    }
}

/// Typed constraint errors: a violation has to arrive as the declared
/// error type with the field named, not as an opaque database error.
mod typed_constraints {
    use entity_derive::{ConstraintError, Entity};
    use uuid::Uuid;

    use crate::pg;

    #[derive(Debug)]
    pub enum ShopError {
        Database(sqlx::Error),
        Constraint(ConstraintError)
    }

    impl std::fmt::Display for ShopError {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            match self {
                Self::Database(e) => write!(f, "database error: {e}"),
                Self::Constraint(e) => write!(f, "constraint violation: {e}")
            }
        }
    }

    impl std::error::Error for ShopError {}

    impl From<sqlx::Error> for ShopError {
        fn from(e: sqlx::Error) -> Self {
            Self::Database(e)
        }
    }

    impl From<ConstraintError> for ShopError {
        fn from(e: ConstraintError) -> Self {
            Self::Constraint(e)
        }
    }

    #[derive(Debug, Clone, Entity)]
    #[entity(
        table = "customers",
        migrations,
        typed_constraints,
        error = "ShopError"
    )]
    pub struct Customer {
        #[id]
        pub id: Uuid,

        #[field(create, response)]
        #[column(unique)]
        pub email: String,

        #[field(create, update, response)]
        pub name: String
    }

    #[tokio::test]
    async fn unique_violation_arrives_typed() {
        let Some(db) = pg::provision("constraints", &[Customer::MIGRATION_UP]).await else {
            return;
        };
        let pool = db.pool();

        pool.create(CreateCustomerRequest {
            email: "ada@example.com".to_owned(),
            name:  "Ada".to_owned()
        })
        .await
        .expect("create failed");

        let duplicate = pool
            .create(CreateCustomerRequest {
                email: "ada@example.com".to_owned(),
                name:  "Impostor".to_owned()
            })
            .await;

        match duplicate {
            Err(ShopError::Constraint(violation)) => {
                assert_eq!(
                    violation.field,
                    Some("email"),
                    "the violation must name the column that collided"
                );
            }
            Err(other) => panic!("expected a typed constraint violation, got {other}"),
            Ok(_) => panic!("the unique index must reject the duplicate")
        }

        db.teardown().await;
    }
}

/// Postgres enum columns and embedded value objects: both change what
/// the DDL and the row mapping look like.
mod column_shapes {
    use entity_derive::{Entity, ValueObject};
    use uuid::Uuid;

    use crate::pg;

    #[derive(
        ValueObject,
        Debug,
        Clone,
        PartialEq,
        Eq,
        utoipa::ToSchema,
        serde::Serialize,
        serde::Deserialize,
    )]
    #[value_object(pg_type = "shipment_status", sqlx)]
    pub enum ShipmentStatus {
        Pending,
        Shipped,
        Delivered
    }

    #[derive(Debug, Clone, PartialEq, utoipa::ToSchema, serde::Serialize, serde::Deserialize)]
    pub struct Money {
        pub amount_cents: i64,
        pub currency:     String
    }

    #[derive(Debug, Clone, Entity)]
    #[entity(table = "shipments", migrations)]
    pub struct Shipment {
        #[id]
        pub id: Uuid,

        #[field(create, update, response)]
        #[column(pg_enum = "shipment_status")]
        pub status: ShipmentStatus,

        #[field(create, update, response)]
        #[embed(prefix = "cost_", fields(amount_cents: i64, currency: String))]
        pub cost: Money
    }

    fn migrations() -> Vec<&'static str> {
        let mut scripts = Vec::new();
        scripts.extend_from_slice(Shipment::MIGRATION_TYPES);
        scripts.push(Shipment::MIGRATION_UP);
        scripts
    }

    #[tokio::test]
    async fn enum_and_embedded_columns_round_trip() {
        let Some(db) = pg::provision("shapes", &migrations()).await else {
            return;
        };
        let pool = db.pool();

        let created = pool
            .create(CreateShipmentRequest {
                status: ShipmentStatus::Pending,
                cost:   Money {
                    amount_cents: 1999,
                    currency:     "EUR".to_owned()
                }
            })
            .await
            .expect("create failed");
        assert_eq!(created.status, ShipmentStatus::Pending);
        assert_eq!(created.cost.amount_cents, 1999);

        let updated = pool
            .update(
                created.id,
                UpdateShipmentRequest {
                    status: Some(ShipmentStatus::Delivered),
                    cost:   Some(Money {
                        amount_cents: 2500,
                        currency:     "USD".to_owned()
                    })
                }
            )
            .await
            .expect("update failed");
        assert_eq!(updated.status, ShipmentStatus::Delivered);
        assert_eq!(updated.cost.currency, "USD");

        let stored = pool
            .find_by_id(created.id)
            .await
            .expect("read failed")
            .expect("row missing");
        assert_eq!(stored.status, ShipmentStatus::Delivered);
        assert_eq!(stored.cost.amount_cents, 2500);

        let native: String =
            sqlx::query_scalar("SELECT status::text FROM shipments WHERE id = $1")
                .bind(created.id)
                .fetch_one(pool)
                .await
                .expect("the column must be the declared enum type");
        assert_eq!(native, "delivered");

        db.teardown().await;
    }
}

/// The transactional outbox: a write and its outbox row must land in
/// the same transaction.
mod outbox {
    use entity_derive::Entity;
    use uuid::Uuid;

    use crate::pg;

    #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, Entity)]
    #[entity(table = "invoices", migrations, events(outbox))]
    pub struct Invoice {
        #[id]
        pub id: Uuid,

        #[field(create, update, response)]
        pub number: String
    }

    #[tokio::test]
    async fn writes_enqueue_their_event() {
        let Some(db) = pg::provision(
            "outbox",
            &[Invoice::MIGRATION_UP, Invoice::MIGRATION_OUTBOX]
        )
        .await
        else {
            return;
        };
        let pool = db.pool();

        let invoice = pool
            .create(CreateInvoiceRequest {
                number: "INV-1".to_owned()
            })
            .await
            .expect("create failed");

        let (kind, entity_id): (String, String) = sqlx::query_as(
            "SELECT kind, entity_id FROM entity_outbox WHERE entity = 'invoices' ORDER BY id"
        )
        .fetch_one(pool)
        .await
        .expect("the create must have enqueued an outbox row");
        assert_eq!(entity_id, invoice.id.to_string());
        assert_eq!(kind.to_lowercase(), "created");

        db.teardown().await;
    }

    /// Records what it was handed, and fails on demand.
    struct Recorder {
        seen: std::sync::Mutex<Vec<String>>,
        fail: bool
    }

    #[entity_derive::async_trait]
    impl entity_derive::outbox::OutboxHandler for Recorder {
        type Error = String;

        async fn handle(&self, row: &entity_derive::outbox::OutboxRow) -> Result<(), Self::Error> {
            self.seen
                .lock()
                .expect("the recorder lock is never poisoned")
                .push(row.entity_id.clone());
            if self.fail {
                Err("handler refused".to_owned())
            } else {
                Ok(())
            }
        }
    }

    #[tokio::test]
    async fn the_drainer_claims_delivers_and_retries() {
        let Some(db) = pg::provision(
            "drainer",
            &[Invoice::MIGRATION_UP, Invoice::MIGRATION_OUTBOX]
        )
        .await
        else {
            return;
        };
        let pool = db.pool();

        let invoice = pool
            .create(CreateInvoiceRequest {
                number: "INV-2".to_owned()
            })
            .await
            .expect("create failed");

        let failing = entity_derive::outbox::OutboxDrainer::new(
            pool.clone(),
            Recorder {
                seen: std::sync::Mutex::new(Vec::new()),
                fail: true
            }
        );
        let claimed = failing.drain_once().await.expect("drain failed");
        assert_eq!(claimed, 1, "the pending row must be claimed");

        let (attempts, processed): (i32, Option<chrono::DateTime<chrono::Utc>>) =
            sqlx::query_as("SELECT attempts, processed_at FROM entity_outbox")
                .fetch_one(pool)
                .await
                .expect("read failed");
        assert_eq!(attempts, 1, "a failed delivery must count an attempt");
        assert!(
            processed.is_none(),
            "a failed delivery must stay pending for the retry"
        );

        sqlx::query("UPDATE entity_outbox SET next_attempt_at = NOW()")
            .execute(pool)
            .await
            .expect("rescheduling for the test failed");

        let recorder = Recorder {
            seen: std::sync::Mutex::new(Vec::new()),
            fail: false
        };
        let succeeding = entity_derive::outbox::OutboxDrainer::new(pool.clone(), recorder);
        assert_eq!(
            succeeding.drain_once().await.expect("drain failed"),
            1,
            "the retry must claim the row again"
        );

        let processed: Option<chrono::DateTime<chrono::Utc>> =
            sqlx::query_scalar("SELECT processed_at FROM entity_outbox")
                .fetch_one(pool)
                .await
                .expect("read failed");
        assert!(
            processed.is_some(),
            "a successful delivery must mark the row processed"
        );

        assert_eq!(
            entity_derive::outbox::OutboxDrainer::new(
                pool.clone(),
                Recorder {
                    seen: std::sync::Mutex::new(Vec::new()),
                    fail: false
                }
            )
            .drain_once()
            .await
            .expect("drain failed"),
            0,
            "a processed row must not be claimed twice"
        );

        let _ = invoice;
        db.teardown().await;
    }
}

/// Streams: a write has to publish its event on the entity channel, in
/// the same transaction that wrote the row.
mod streams {
    use entity_derive::Entity;
    use sqlx::postgres::PgListener;
    use uuid::Uuid;

    use crate::pg;

    #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, Entity)]
    #[entity(table = "alerts", migrations, events, streams)]
    pub struct Alert {
        #[id]
        pub id: Uuid,

        #[field(create, update, response)]
        pub message: String
    }

    #[tokio::test]
    async fn writes_notify_the_channel() {
        let Some(db) = pg::provision("streams", &[Alert::MIGRATION_UP]).await else {
            return;
        };
        let pool = db.pool();

        let mut listener = PgListener::connect_with(pool)
            .await
            .expect("listener connect failed");
        listener
            .listen(Alert::CHANNEL)
            .await
            .expect("LISTEN failed");

        let alert = pool
            .create(CreateAlertRequest {
                message: "disk full".to_owned()
            })
            .await
            .expect("create failed");

        let notification =
            tokio::time::timeout(std::time::Duration::from_secs(5), listener.recv())
                .await
                .expect("no notification arrived within five seconds")
                .expect("listener failed");

        let event: AlertEvent = serde_json::from_str(notification.payload())
            .expect("the payload must deserialize into the generated event");
        match event {
            AlertEvent::Created(created) => assert_eq!(created.id, alert.id),
            other => panic!("expected a Created event, got {other:?}")
        }

        // The listener holds a pooled connection; teardown closes the
        // pool and would wait for it.
        drop(listener);
        db.teardown().await;
    }

    #[tokio::test]
    async fn the_generated_subscriber_receives_events() {
        let Some(db) = pg::provision("subscriber", &[Alert::MIGRATION_UP]).await else {
            return;
        };
        let pool = db.pool();

        let mut subscriber = AlertSubscriber::new(pool)
            .await
            .expect("subscriber connect failed");

        let alert = pool
            .create(CreateAlertRequest {
                message: "battery low".to_owned()
            })
            .await
            .expect("create failed");

        let event = tokio::time::timeout(std::time::Duration::from_secs(5), subscriber.recv())
            .await
            .expect("no event arrived within five seconds")
            .expect("the subscriber must decode the payload");
        match event {
            AlertEvent::Created(created) => assert_eq!(created.id, alert.id),
            other => panic!("expected a Created event, got {other:?}")
        }

        drop(subscriber);
        db.teardown().await;
    }
}

/// Returning modes decide what comes back from a write, and each mode
/// builds a different statement.
mod returning_modes {
    use entity_derive::Entity;
    use uuid::Uuid;

    use crate::pg;

    #[derive(Debug, Clone, Entity)]
    #[entity(table = "id_only", migrations, returning = "id")]
    pub struct IdOnly {
        #[id]
        pub id: Uuid,

        #[field(create, update, response)]
        pub label: String
    }

    #[derive(Debug, Clone, Entity)]
    #[entity(table = "no_returning", migrations, returning = "none")]
    pub struct NoReturning {
        #[id]
        pub id: Uuid,

        #[field(create, update, response)]
        pub label: String
    }

    #[tokio::test]
    async fn id_mode_returns_the_row_it_wrote() {
        let Some(db) = pg::provision("ret_id", &[IdOnly::MIGRATION_UP]).await else {
            return;
        };
        let pool = db.pool();

        let created = IdOnlyRepository::create(
            pool,
            CreateIdOnlyRequest {
                label: "alpha".to_owned()
            }
        )
        .await
        .expect("create failed");

        let stored = IdOnlyRepository::find_by_id(pool, created.id)
            .await
            .expect("read failed")
            .expect("the write must have landed");
        assert_eq!(stored.label, "alpha");

        db.teardown().await;
    }

    #[tokio::test]
    async fn none_mode_still_writes() {
        let Some(db) = pg::provision("ret_none", &[NoReturning::MIGRATION_UP]).await else {
            return;
        };
        let pool = db.pool();

        let created = NoReturningRepository::create(
            pool,
            CreateNoReturningRequest {
                label: "beta".to_owned()
            }
        )
        .await
        .expect("create failed");

        let stored = NoReturningRepository::find_by_id(pool, created.id)
            .await
            .expect("read failed")
            .expect("a write with no RETURNING must still persist the row");
        assert_eq!(stored.label, "beta");

        db.teardown().await;
    }
}

/// Joined read models: the generated `SELECT` spans several tables, so
/// a wrong alias or a missing column only shows up when it runs.
mod join_views {
    use entity_derive::Entity;
    use uuid::Uuid;

    use crate::pg;

    #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, Entity)]
    #[join(airports as origin, on = origin_iata = iata, fields(
        city as origin_city: String
    ))]
    #[join(airports as dest, on = destination_iata = iata, fields(
        city as destination_city: String
    ))]
    #[entity(table = "tickets", migrations)]
    pub struct Ticket {
        #[id]
        pub id: Uuid,

        #[field(create, response)]
        pub origin_iata: String,

        #[field(create, response)]
        pub destination_iata: String
    }

    /// The joined table is not an entity, so its DDL is written by hand
    /// exactly as a user would write it.
    const AIRPORTS: &str = "CREATE TABLE airports (iata TEXT PRIMARY KEY, city TEXT NOT NULL);\n\
                            INSERT INTO airports (iata, city) VALUES \
                            ('TLL', 'Tallinn'), ('HEL', 'Helsinki');";

    #[tokio::test]
    async fn view_joins_both_sides() {
        let Some(db) = pg::provision("joins", &[AIRPORTS, Ticket::MIGRATION_UP]).await else {
            return;
        };
        let pool = db.pool();

        let ticket = pool
            .create(CreateTicketRequest {
                origin_iata:      "TLL".to_owned(),
                destination_iata: "HEL".to_owned()
            })
            .await
            .expect("create failed");

        let view = TicketView::find_by_id(pool, ticket.id)
            .await
            .expect("the joined SELECT must execute")
            .expect("the row must resolve through both joins");
        assert_eq!(view.origin_city, "Tallinn");
        assert_eq!(view.destination_city, "Helsinki");
        assert_eq!(view.origin_iata, "TLL");

        let page = TicketView::list(pool, 10, 0)
            .await
            .expect("the joined list must execute");
        assert_eq!(page.len(), 1);
        assert_eq!(page[0].destination_city, "Helsinki");

        db.teardown().await;
    }

    #[tokio::test]
    async fn inner_join_drops_rows_without_a_match() {
        let Some(db) = pg::provision("joinmiss", &[AIRPORTS, Ticket::MIGRATION_UP]).await else {
            return;
        };
        let pool = db.pool();

        let orphan = pool
            .create(CreateTicketRequest {
                origin_iata:      "TLL".to_owned(),
                destination_iata: "XXX".to_owned()
            })
            .await
            .expect("create failed");

        assert!(
            TicketView::find_by_id(pool, orphan.id)
                .await
                .expect("the joined SELECT must execute")
                .is_none(),
            "an INNER JOIN must drop the row whose destination has no airport"
        );

        db.teardown().await;
    }
}

/// The policy wrapper is an authorization boundary: a denial has to
/// stop the write, not just be recorded.
mod policy {
    use entity_derive::{Entity, async_trait};
    use uuid::Uuid;

    use crate::pg;

    #[derive(Debug, Clone, Entity)]
    #[entity(table = "documents", migrations, policy)]
    pub struct Document {
        #[id]
        pub id: Uuid,

        #[field(create, response)]
        pub owner_id: Uuid,

        #[field(create, update, response)]
        pub title: String
    }

    /// Denies everything an admin is not allowed to do.
    struct OwnerOnly;

    /// Who is asking.
    struct Caller {
        user_id: Uuid
    }

    #[derive(Debug)]
    struct Denied;

    impl std::fmt::Display for Denied {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            f.write_str("not allowed")
        }
    }

    impl std::error::Error for Denied {}

    #[async_trait]
    impl DocumentPolicy for OwnerOnly {
        type Context = Caller;
        type Error = Denied;

        async fn can_create(
            &self,
            dto: &CreateDocumentRequest,
            ctx: &Self::Context
        ) -> Result<(), Self::Error> {
            if dto.owner_id == ctx.user_id {
                Ok(())
            } else {
                Err(Denied)
            }
        }

        async fn can_read(&self, _id: &Uuid, _ctx: &Self::Context) -> Result<(), Self::Error> {
            Ok(())
        }

        async fn can_update(
            &self,
            _id: &Uuid,
            _dto: &UpdateDocumentRequest,
            _ctx: &Self::Context
        ) -> Result<(), Self::Error> {
            Err(Denied)
        }

        async fn can_delete(&self, _id: &Uuid, _ctx: &Self::Context) -> Result<(), Self::Error> {
            Err(Denied)
        }

        async fn can_list(&self, _ctx: &Self::Context) -> Result<(), Self::Error> {
            Ok(())
        }
    }

    #[tokio::test]
    async fn denied_operations_never_reach_the_database() {
        let Some(db) = pg::provision("policy", &[Document::MIGRATION_UP]).await else {
            return;
        };
        let pool = db.pool();

        let owner = Uuid::now_v7();
        let guarded = DocumentPolicyRepository::new(pool.clone(), OwnerOnly);
        let ctx = Caller {
            user_id: owner
        };

        let refused = guarded
            .create(
                CreateDocumentRequest {
                    owner_id: Uuid::now_v7(),
                    title:    "somebody else's".to_owned()
                },
                &ctx
            )
            .await;
        assert!(refused.is_err(), "the policy must refuse the create");
        assert!(
            pool.list(10, 0).await.expect("list failed").is_empty(),
            "a refused create must not have written anything"
        );

        let allowed = guarded
            .create(
                CreateDocumentRequest {
                    owner_id: owner,
                    title:    "mine".to_owned()
                },
                &ctx
            )
            .await
            .expect("the policy must allow the owner's create");
        assert_eq!(pool.list(10, 0).await.expect("list failed").len(), 1);

        assert!(
            guarded
                .update(
                    allowed.id,
                    UpdateDocumentRequest {
                        title: Some("renamed".to_owned())
                    },
                    &ctx
                )
                .await
                .is_err(),
            "the policy must refuse the update"
        );
        let unchanged = pool
            .find_by_id(allowed.id)
            .await
            .expect("read failed")
            .expect("row missing");
        assert_eq!(
            unchanged.title, "mine",
            "a refused update must leave the row alone"
        );

        assert!(
            guarded.delete(allowed.id, &ctx).await.is_err(),
            "the policy must refuse the delete"
        );
        assert!(
            pool.find_by_id(allowed.id)
                .await
                .expect("read failed")
                .is_some(),
            "a refused delete must leave the row in place"
        );

        db.teardown().await;
    }
}

/// The generated HTTP layer, driven over the generated router with a
/// real repository behind it.
mod http {
    use std::sync::Arc;

    use axum::{
        body::Body,
        http::{Request, StatusCode}
    };
    use entity_derive::Entity;
    use tower::ServiceExt;
    use uuid::Uuid;

    use crate::pg;

    #[derive(Debug, Clone, Entity)]
    #[entity(table = "gadgets", migrations, api(tag = "Gadgets", handlers))]
    pub struct Gadget {
        #[id]
        pub id: Uuid,

        #[field(create, update, response)]
        pub name: String,

        #[field(create, update, response)]
        pub weight: i32
    }

    /// Send one request through the generated router and return the
    /// status together with the body.
    async fn call(pool: &sqlx::PgPool, request: Request<Body>) -> (StatusCode, serde_json::Value) {
        let app = gadget_router::<sqlx::PgPool>().with_state(Arc::new(pool.clone()));
        let response = app.oneshot(request).await.expect("the router must respond");
        let status = response.status();
        let bytes = axum::body::to_bytes(response.into_body(), 1 << 20)
            .await
            .expect("body read failed");
        let body = if bytes.is_empty() {
            serde_json::Value::Null
        } else {
            serde_json::from_slice(&bytes).expect("the response must be JSON")
        };
        (status, body)
    }

    fn json_request(method: &str, uri: &str, body: serde_json::Value) -> Request<Body> {
        Request::builder()
            .method(method)
            .uri(uri)
            .header("content-type", "application/json")
            .body(Body::from(body.to_string()))
            .expect("request build failed")
    }

    #[tokio::test]
    async fn crud_endpoints_answer_over_http() {
        let Some(db) = pg::provision("http", &[Gadget::MIGRATION_UP]).await else {
            return;
        };
        let pool = db.pool();

        let (status, created) = call(
            pool,
            json_request(
                "POST",
                "/gadgets",
                serde_json::json!({
                    "name": "spanner",
                    "weight": 3
                })
            )
        )
        .await;
        assert_eq!(status, StatusCode::CREATED, "a create must answer 201");
        assert_eq!(created["name"], "spanner");
        let id = created["id"].as_str().expect("the response carries the id");

        let (status, fetched) = call(
            pool,
            Request::builder()
                .uri(format!("/gadgets/{id}"))
                .body(Body::empty())
                .expect("request build failed")
        )
        .await;
        assert_eq!(status, StatusCode::OK);
        assert_eq!(fetched["weight"], 3);

        let (status, listed) = call(
            pool,
            Request::builder()
                .uri("/gadgets?limit=10&offset=0")
                .body(Body::empty())
                .expect("request build failed")
        )
        .await;
        assert_eq!(status, StatusCode::OK);
        assert_eq!(
            listed.as_array().map(Vec::len),
            Some(1),
            "the list endpoint must honour its pagination parameters"
        );

        let (status, updated) = call(
            pool,
            json_request(
                "PATCH",
                &format!("/gadgets/{id}"),
                serde_json::json!({ "weight": 5 })
            )
        )
        .await;
        assert_eq!(status, StatusCode::OK);
        assert_eq!(updated["weight"], 5);
        assert_eq!(
            updated["name"], "spanner",
            "a PATCH must leave the omitted field alone"
        );

        let (status, _) = call(
            pool,
            Request::builder()
                .method("DELETE")
                .uri(format!("/gadgets/{id}"))
                .body(Body::empty())
                .expect("request build failed")
        )
        .await;
        assert_eq!(status, StatusCode::NO_CONTENT, "a delete must answer 204");

        let (status, _) = call(
            pool,
            Request::builder()
                .uri(format!("/gadgets/{id}"))
                .body(Body::empty())
                .expect("request build failed")
        )
        .await;
        assert_eq!(
            status,
            StatusCode::NOT_FOUND,
            "reading a deleted row must answer 404"
        );

        db.teardown().await;
    }

    #[tokio::test]
    async fn unknown_id_answers_not_found() {
        let Some(db) = pg::provision("http404", &[Gadget::MIGRATION_UP]).await else {
            return;
        };
        let pool = db.pool();

        let (status, _) = call(
            pool,
            Request::builder()
                .uri(format!("/gadgets/{}", Uuid::now_v7()))
                .body(Body::empty())
                .expect("request build failed")
        )
        .await;
        assert_eq!(status, StatusCode::NOT_FOUND);

        db.teardown().await;
    }
}

/// Declarative state transitions: the guard is SQL plus a status check
/// under a row lock, so only a real run proves it.
mod transitions {
    use entity_derive::{Entity, ValueObject};
    use uuid::Uuid;

    use crate::pg;

    #[derive(
        ValueObject,
        Debug,
        Clone,
        Copy,
        PartialEq,
        Eq,
        utoipa::ToSchema,
        serde::Serialize,
        serde::Deserialize,
    )]
    #[value_object(pg_type = "parcel_status", sqlx)]
    pub enum ParcelStatus {
        Created,
        Accepted,
        Cancelled
    }

    /// The transition guard reports a typed failure, so the entity has
    /// to declare an error type that can carry it.
    #[derive(Debug)]
    pub enum ParcelError {
        Database(sqlx::Error),
        Transition(entity_derive::TransitionError)
    }

    impl std::fmt::Display for ParcelError {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            match self {
                Self::Database(e) => write!(f, "database error: {e}"),
                Self::Transition(e) => write!(f, "transition refused: {e}")
            }
        }
    }

    impl std::error::Error for ParcelError {}

    impl From<sqlx::Error> for ParcelError {
        fn from(e: sqlx::Error) -> Self {
            Self::Database(e)
        }
    }

    impl From<entity_derive::TransitionError> for ParcelError {
        fn from(e: entity_derive::TransitionError) -> Self {
            Self::Transition(e)
        }
    }

    #[derive(Debug, Clone, Entity)]
    #[entity(table = "parcels", migrations, transactions, error = "ParcelError")]
    #[transition(created -> accepted, sets(courier_id))]
    #[transition(created | accepted -> cancelled)]
    pub struct Parcel {
        #[id]
        pub id: Uuid,

        #[field(create, update, response)]
        #[column(pg_enum = "parcel_status")]
        pub status: ParcelStatus,

        #[field(create, update, response)]
        pub courier_id: Option<Uuid>
    }

    fn migrations() -> Vec<&'static str> {
        let mut scripts = Vec::new();
        scripts.extend_from_slice(Parcel::MIGRATION_TYPES);
        scripts.push(Parcel::MIGRATION_UP);
        scripts
    }

    #[tokio::test]
    async fn allowed_transition_patches_declared_columns() {
        let Some(db) = pg::provision("transition", &migrations()).await else {
            return;
        };
        let pool = db.pool();

        let parcel = pool
            .create(CreateParcelRequest {
                status:     ParcelStatus::Created,
                courier_id: None
            })
            .await
            .expect("create failed");

        let courier = Uuid::now_v7();
        let mut tx = pool.begin().await.expect("begin failed");
        let mut repo = ParcelTransactionRepo::new(&mut tx);
        let accepted = repo
            .transition_to_accepted(parcel.id, courier)
            .await
            .expect("the declared transition must be allowed")
            .expect("the row must exist");
        tx.commit().await.expect("commit failed");

        assert_eq!(accepted.status, ParcelStatus::Accepted);
        assert_eq!(
            accepted.courier_id,
            Some(courier),
            "the transition must patch the columns it declares"
        );

        db.teardown().await;
    }

    #[tokio::test]
    async fn disallowed_source_status_is_refused() {
        let Some(db) = pg::provision("transbad", &migrations()).await else {
            return;
        };
        let pool = db.pool();

        let parcel = pool
            .create(CreateParcelRequest {
                status:     ParcelStatus::Cancelled,
                courier_id: None
            })
            .await
            .expect("create failed");

        let mut tx = pool.begin().await.expect("begin failed");
        let mut repo = ParcelTransactionRepo::new(&mut tx);
        let refused = repo.transition_to_accepted(parcel.id, Uuid::now_v7()).await;
        assert!(
            refused.is_err(),
            "a cancelled parcel must not become accepted"
        );
        tx.rollback().await.expect("rollback failed");

        let unchanged = pool
            .find_by_id(parcel.id)
            .await
            .expect("read failed")
            .expect("row missing");
        assert_eq!(
            unchanged.status,
            ParcelStatus::Cancelled,
            "a refused transition must leave the status alone"
        );

        db.teardown().await;
    }

    #[tokio::test]
    async fn a_missing_row_is_not_an_error() {
        let Some(db) = pg::provision("transnone", &migrations()).await else {
            return;
        };
        let pool = db.pool();

        let mut tx = pool.begin().await.expect("begin failed");
        let mut repo = ParcelTransactionRepo::new(&mut tx);
        let outcome = repo
            .transition_to_cancelled(Uuid::now_v7())
            .await
            .expect("a missing row must not be reported as a transition failure");
        assert!(outcome.is_none());
        tx.rollback().await.expect("rollback failed");

        db.teardown().await;
    }
}

/// HTTP guards and the generated OpenAPI document.
mod http_guard {
    use std::sync::Arc;

    use axum::{
        body::Body,
        extract::FromRequestParts,
        http::{Request, StatusCode, request::Parts}
    };
    use entity_derive::Entity;
    use tower::ServiceExt;
    use uuid::Uuid;

    use crate::pg;

    /// Accepts a request only when it carries an authorization header.
    pub struct RequireAuth;

    impl<S> FromRequestParts<S> for RequireAuth
    where
        S: Send + Sync
    {
        type Rejection = StatusCode;

        fn from_request_parts(
            parts: &mut Parts,
            _state: &S
        ) -> impl Future<Output = Result<Self, Self::Rejection>> + Send {
            let authenticated = parts.headers.contains_key("authorization");
            async move {
                if authenticated {
                    Ok(Self)
                } else {
                    Err(StatusCode::UNAUTHORIZED)
                }
            }
        }
    }

    #[derive(Debug, Clone, Entity)]
    #[entity(
        table = "vaults",
        migrations,
        api(tag = "Vaults", handlers, guard = "RequireAuth", guard(list = "none"))
    )]
    pub struct Vault {
        #[id]
        pub id: Uuid,

        #[field(create, update, response)]
        pub label: String
    }

    async fn status_of(pool: &sqlx::PgPool, request: Request<Body>) -> StatusCode {
        let app = vault_router::<sqlx::PgPool>().with_state(Arc::new(pool.clone()));
        app.oneshot(request)
            .await
            .expect("the router must respond")
            .status()
    }

    #[tokio::test]
    async fn the_guard_rejects_and_the_exempt_route_stays_open() {
        let Some(db) = pg::provision("guard", &[Vault::MIGRATION_UP]).await else {
            return;
        };
        let pool = db.pool();

        let anonymous_create = Request::builder()
            .method("POST")
            .uri("/vaults")
            .header("content-type", "application/json")
            .body(Body::from(r#"{"label":"secrets"}"#))
            .expect("request build failed");
        assert_eq!(
            status_of(pool, anonymous_create).await,
            StatusCode::UNAUTHORIZED,
            "the guard must reject a request without credentials"
        );
        assert!(
            pool.list(10, 0).await.expect("list failed").is_empty(),
            "a rejected request must not have written anything"
        );

        let authenticated_create = Request::builder()
            .method("POST")
            .uri("/vaults")
            .header("content-type", "application/json")
            .header("authorization", "Bearer token")
            .body(Body::from(r#"{"label":"secrets"}"#))
            .expect("request build failed");
        assert_eq!(
            status_of(pool, authenticated_create).await,
            StatusCode::CREATED,
            "the guard must let an authenticated request through"
        );

        let anonymous_list = Request::builder()
            .uri("/vaults")
            .body(Body::empty())
            .expect("request build failed");
        assert_eq!(
            status_of(pool, anonymous_list).await,
            StatusCode::OK,
            "the route exempted with guard(list = \"none\") must stay open"
        );

        db.teardown().await;
    }

    #[test]
    fn the_openapi_document_describes_the_routes() {
        use utoipa::OpenApi;

        let document = VaultApi::openapi();
        let json = serde_json::to_value(&document).expect("the document must serialize");

        let paths = json["paths"]
            .as_object()
            .expect("the document must declare paths");
        assert!(
            paths.contains_key("/vaults"),
            "the collection path must be documented, got {:?}",
            paths.keys().collect::<Vec<_>>()
        );
        assert!(
            paths.contains_key("/vaults/{id}"),
            "the item path must be documented"
        );
        assert!(
            paths["/vaults"].get("post").is_some(),
            "the create operation must be documented"
        );

        let schemas = json["components"]["schemas"]
            .as_object()
            .expect("the document must declare schemas");
        for expected in ["VaultResponse", "CreateVaultRequest", "UpdateVaultRequest"] {
            assert!(
                schemas.contains_key(expected),
                "{expected} must be in the document, got {:?}",
                schemas.keys().collect::<Vec<_>>()
            );
        }
    }
}

/// CQRS commands: the dispatcher routes a variant to its handler, and
/// the generated route carries a command over HTTP.
mod commands {
    use std::sync::Arc;

    use axum::{
        body::Body,
        http::{Request, StatusCode}
    };
    use entity_derive::{Entity, async_trait};
    use tower::ServiceExt;
    use uuid::Uuid;

    use crate::pg;

    #[derive(Debug, Clone, Entity)]
    #[entity(
        table = "members",
        migrations,
        commands,
        api(tag = "Members", handlers)
    )]
    #[command(Register)]
    #[command(Rename: nickname, requires_id)]
    pub struct Member {
        #[id]
        pub id: Uuid,

        #[field(create, update, response)]
        pub nickname: String
    }

    /// Handles commands by writing through the generated repository.
    struct Handlers {
        pool: sqlx::PgPool
    }

    #[async_trait]
    impl MemberCommandHandler for Handlers {
        type Context = ();
        type Error = sqlx::Error;

        async fn handle_register(
            &self,
            cmd: RegisterMember,
            _ctx: &Self::Context
        ) -> Result<Member, Self::Error> {
            self.pool
                .create(CreateMemberRequest {
                    nickname: cmd.nickname
                })
                .await
        }

        async fn handle_rename(
            &self,
            cmd: RenameMember,
            _ctx: &Self::Context
        ) -> Result<Member, Self::Error> {
            self.pool
                .update(
                    cmd.id,
                    UpdateMemberRequest {
                        nickname: Some(cmd.nickname)
                    }
                )
                .await
        }
    }

    #[tokio::test]
    async fn the_dispatcher_routes_each_variant() {
        let Some(db) = pg::provision("commands", &[Member::MIGRATION_UP]).await else {
            return;
        };
        let pool = db.pool();
        let handlers = Handlers {
            pool: pool.clone()
        };

        let registered = handlers
            .handle(
                MemberCommand::Register(RegisterMember {
                    nickname: "ada".to_owned()
                }),
                &()
            )
            .await
            .expect("the dispatcher must route Register");
        let MemberCommandResult::Register(member) = registered else {
            panic!("the result variant must match the command")
        };
        assert_eq!(member.nickname, "ada");

        let renamed = handlers
            .handle(
                MemberCommand::Rename(RenameMember {
                    id:       member.id,
                    nickname: "grace".to_owned()
                }),
                &()
            )
            .await
            .expect("the dispatcher must route Rename");
        let MemberCommandResult::Rename(updated) = renamed else {
            panic!("the result variant must match the command")
        };
        assert_eq!(updated.nickname, "grace");

        let stored = pool
            .find_by_id(member.id)
            .await
            .expect("read failed")
            .expect("row missing");
        assert_eq!(
            stored.nickname, "grace",
            "the handler's write must have reached the database"
        );

        db.teardown().await;
    }

    #[tokio::test]
    async fn a_command_route_answers_over_http() {
        let Some(db) = pg::provision("cmdhttp", &[Member::MIGRATION_UP]).await else {
            return;
        };
        let pool = db.pool();

        // Command handlers take their dependency as an extension, not
        // as router state.
        let app =
            member_commands_router::<Handlers>().layer(axum::Extension(Arc::new(Handlers {
                pool: pool.clone()
            })));
        let response = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/members/register")
                    .header("content-type", "application/json")
                    .body(Body::from(r#"{"nickname":"hopper"}"#))
                    .expect("request build failed")
            )
            .await
            .expect("the router must respond");
        assert_eq!(response.status(), StatusCode::OK);

        assert_eq!(
            pool.list(10, 0).await.expect("list failed").len(),
            1,
            "the command handler must have written the row"
        );

        let body = axum::body::to_bytes(response.into_body(), 1 << 20)
            .await
            .expect("body read failed");
        let json: serde_json::Value =
            serde_json::from_slice(&body).expect("the response must be JSON");
        assert_eq!(
            json["nickname"], "hopper",
            "a command route answers with the response shape, not the raw entity"
        );

        db.teardown().await;
    }
}

/// Update-DTO setters have to produce the same patch a struct literal
/// does, including asking for NULL.
mod update_builders {
    use entity_derive::Entity;
    use uuid::Uuid;

    use crate::pg;

    #[derive(Debug, Clone, Entity)]
    #[entity(table = "shipments_b", migrations)]
    pub struct Shipment {
        #[id]
        pub id: Uuid,

        #[field(create, update, response)]
        pub status: String,

        #[field(create, update, response)]
        pub courier_id: Option<Uuid>
    }

    #[tokio::test]
    async fn setters_and_clear_reach_the_row() {
        let Some(db) = pg::provision("builders", &[Shipment::MIGRATION_UP]).await else {
            return;
        };
        let pool = db.pool();

        let courier = Uuid::now_v7();
        let shipment = pool
            .create(CreateShipmentRequest {
                status:     "created".to_owned(),
                courier_id: Some(courier)
            })
            .await
            .expect("create failed");

        let patched = pool
            .update(
                shipment.id,
                UpdateShipmentRequest::default().set_status("accepted".to_owned())
            )
            .await
            .expect("update failed");
        assert_eq!(patched.status, "accepted");
        assert_eq!(
            patched.courier_id,
            Some(courier),
            "an untouched field must keep its stored value"
        );

        let cleared = pool
            .update(
                shipment.id,
                UpdateShipmentRequest::default().clear_courier_id()
            )
            .await
            .expect("update failed");
        assert_eq!(
            cleared.courier_id, None,
            "clear_ must write NULL, not leave the column alone"
        );
        assert_eq!(
            cleared.status, "accepted",
            "clearing one column must not touch another"
        );

        let reassigned = pool
            .update(
                shipment.id,
                UpdateShipmentRequest::default().set_courier_id(courier)
            )
            .await
            .expect("update failed");
        assert_eq!(reassigned.courier_id, Some(courier));

        db.teardown().await;
    }
}

/// Participant scopes: one value matched against several roles, with
/// and without narrowing to a parent row.
mod scopes {
    use entity_derive::Entity;
    use uuid::Uuid;

    use crate::pg;

    #[derive(Debug, Clone, Entity)]
    #[entity(table = "disputes", migrations)]
    #[scope(involving: requester_id | subject_id)]
    #[scope(handled: requester_id | subject_id, within = parcel_id)]
    pub struct Dispute {
        #[id]
        pub id: Uuid,

        #[field(create, response)]
        pub parcel_id: Uuid,

        #[field(create, response)]
        pub requester_id: Uuid,

        #[field(create, response)]
        pub subject_id: Uuid
    }

    #[tokio::test]
    async fn a_scope_matches_every_declared_role() {
        let Some(db) = pg::provision("scopes", &[Dispute::MIGRATION_UP]).await else {
            return;
        };
        let pool = db.pool();

        let ada = Uuid::now_v7();
        let grace = Uuid::now_v7();
        let stranger = Uuid::now_v7();
        let parcel = Uuid::now_v7();
        let other_parcel = Uuid::now_v7();

        let requested = pool
            .create(CreateDisputeRequest {
                parcel_id:    parcel,
                requester_id: ada,
                subject_id:   grace
            })
            .await
            .expect("create failed");
        let subjected = pool
            .create(CreateDisputeRequest {
                parcel_id:    other_parcel,
                requester_id: grace,
                subject_id:   ada
            })
            .await
            .expect("create failed");
        pool.create(CreateDisputeRequest {
            parcel_id:    parcel,
            requester_id: grace,
            subject_id:   stranger
        })
        .await
        .expect("create failed");

        let ada_rows = pool
            .list_involving(ada, 10, 0)
            .await
            .expect("scope query failed");
        let ada_ids: Vec<Uuid> = ada_rows.iter().map(|d| d.id).collect();
        assert_eq!(ada_ids.len(), 2, "both roles must match the same principal");
        assert!(ada_ids.contains(&requested.id) && ada_ids.contains(&subjected.id));

        let narrowed = pool
            .list_handled(parcel, ada, 10, 0)
            .await
            .expect("narrowed scope query failed");
        assert_eq!(
            narrowed.len(),
            1,
            "narrowing must drop the row belonging to another parcel"
        );
        assert_eq!(narrowed[0].id, requested.id);

        assert!(
            pool.list_involving(Uuid::now_v7(), 10, 0)
                .await
                .expect("scope query failed")
                .is_empty(),
            "an uninvolved principal matches nothing"
        );

        let page = pool
            .list_involving(ada, 1, 0)
            .await
            .expect("scope query failed");
        assert_eq!(page.len(), 1, "the scope honours its pagination");

        db.teardown().await;
    }
}

/// Domain operations write named columns that the public patch DTO
/// deliberately does not carry.
mod domain_operations {
    use chrono::{DateTime, Utc};
    use entity_derive::Entity;
    use uuid::Uuid;

    use crate::pg;

    #[derive(Debug, Clone, Entity)]
    #[entity(table = "citizens", migrations, commands, transactions)]
    #[command(
        VerifyPassport,
        payload(passport_provider),
        sets(passport_verified = "true", passport_verified_at = "NOW()")
    )]
    pub struct Citizen {
        #[id]
        pub id: Uuid,

        #[field(create, update, response)]
        pub name: String,

        #[field(response)]
        #[column(default = "false")]
        pub passport_verified: bool,

        #[field(response)]
        pub passport_provider: Option<String>,

        #[field(response)]
        pub passport_verified_at: Option<DateTime<Utc>>
    }

    #[tokio::test]
    async fn the_operation_writes_exactly_its_columns() {
        let Some(db) = pg::provision("domainop", &[Citizen::MIGRATION_UP]).await else {
            return;
        };
        let pool = db.pool();

        let citizen = pool
            .create(CreateCitizenRequest {
                name: "Ada".to_owned()
            })
            .await
            .expect("create failed");
        assert!(!citizen.passport_verified);
        assert!(citizen.passport_verified_at.is_none());

        let verified = pool
            .verify_passport(VerifyPassportCitizen {
                id:                citizen.id,
                passport_provider: Some("gov".to_owned())
            })
            .await
            .expect("the domain operation must apply");

        assert!(
            verified.passport_verified,
            "the fixed expression must apply"
        );
        assert_eq!(
            verified.passport_provider.as_deref(),
            Some("gov"),
            "the payload column must be bound"
        );
        assert!(
            verified.passport_verified_at.is_some(),
            "the second fixed expression must apply too"
        );
        assert_eq!(
            verified.name, "Ada",
            "a column the operation does not name must stay untouched"
        );

        let missing = pool
            .verify_passport(VerifyPassportCitizen {
                id:                Uuid::now_v7(),
                passport_provider: None
            })
            .await;
        assert!(missing.is_err(), "an unknown id must not report success");

        db.teardown().await;
    }

    #[tokio::test]
    async fn the_operation_runs_inside_a_transaction() {
        let Some(db) = pg::provision("domainoptx", &[Citizen::MIGRATION_UP]).await else {
            return;
        };
        let pool = db.pool();

        let citizen = pool
            .create(CreateCitizenRequest {
                name: "Grace".to_owned()
            })
            .await
            .expect("create failed");

        let mut tx = pool.begin().await.expect("begin failed");
        let verified = CitizenTransactionRepo::new(&mut tx)
            .verify_passport(VerifyPassportCitizen {
                id:                citizen.id,
                passport_provider: Some("gov".to_owned())
            })
            .await
            .expect("the operation must apply")
            .expect("the row exists");
        assert!(verified.passport_verified);
        tx.rollback().await.expect("rollback failed");

        let after_rollback = pool
            .find_by_id(citizen.id)
            .await
            .expect("lookup failed")
            .expect("the row exists");
        assert!(
            !after_rollback.passport_verified,
            "the operation must take part in the transaction, not commit on its own"
        );

        let mut tx = pool.begin().await.expect("begin failed");
        let missing = CitizenTransactionRepo::new(&mut tx)
            .verify_passport(VerifyPassportCitizen {
                id:                Uuid::now_v7(),
                passport_provider: None
            })
            .await
            .expect("an unknown id is not an error here");
        assert!(missing.is_none(), "an unknown id must report no row");
        tx.commit().await.expect("commit failed");

        db.teardown().await;
    }
}

/// The hook-invoking wrapper: order of calls, and what a refusing
/// `before_*` must prevent.
mod hooks {
    use std::sync::{Arc, Mutex};

    use entity_derive::{Entity, async_trait};
    use uuid::Uuid;

    use crate::pg;

    #[derive(Debug, Clone, Entity)]
    #[entity(table = "accounts_h", migrations, soft_delete, hooks)]
    pub struct Account {
        #[id]
        pub id: Uuid,

        #[field(create, update, response)]
        pub label: String,

        #[field(skip)]
        pub deleted_at: Option<chrono::DateTime<chrono::Utc>>
    }

    /// Records the calls it receives, and can refuse one of them.
    #[derive(Clone)]
    struct Recorder {
        calls:  Arc<Mutex<Vec<&'static str>>>,
        refuse: Option<&'static str>
    }

    impl Recorder {
        fn new(refuse: Option<&'static str>) -> Self {
            Self {
                calls: Arc::new(Mutex::new(Vec::new())),
                refuse
            }
        }

        fn note(&self, call: &'static str) -> Result<(), sqlx::Error> {
            self.calls
                .lock()
                .expect("the recorder lock is never poisoned")
                .push(call);
            if self.refuse == Some(call) {
                return Err(sqlx::Error::RowNotFound);
            }
            Ok(())
        }

        fn calls(&self) -> Vec<&'static str> {
            self.calls
                .lock()
                .expect("the recorder lock is never poisoned")
                .clone()
        }
    }

    #[async_trait]
    impl AccountHooks for Recorder {
        type Error = sqlx::Error;

        async fn before_create(&self, dto: &mut CreateAccountRequest) -> Result<(), Self::Error> {
            let trimmed = dto.label.trim().to_owned();
            dto.label = trimmed;
            self.note("before_create")
        }

        async fn after_create(&self, _entity: &Account) -> Result<(), Self::Error> {
            self.note("after_create")
        }

        async fn before_update(
            &self,
            _id: &Uuid,
            _dto: &mut UpdateAccountRequest
        ) -> Result<(), Self::Error> {
            self.note("before_update")
        }

        async fn after_update(&self, _entity: &Account) -> Result<(), Self::Error> {
            self.note("after_update")
        }

        async fn before_delete(&self, _id: &Uuid) -> Result<(), Self::Error> {
            self.note("before_delete")
        }

        async fn after_delete(&self, _id: &Uuid) -> Result<(), Self::Error> {
            self.note("after_delete")
        }

        async fn before_restore(&self, _id: &Uuid) -> Result<(), Self::Error> {
            self.note("before_restore")
        }

        async fn after_restore(&self, _id: &Uuid) -> Result<(), Self::Error> {
            self.note("after_restore")
        }
    }

    #[tokio::test]
    async fn hooks_run_around_every_mutation() {
        let Some(db) = pg::provision("hooks", &[Account::MIGRATION_UP]).await else {
            return;
        };
        let pool = db.pool();

        let recorder = Recorder::new(None);
        let repo = AccountRepo::new(pool.clone(), recorder.clone());

        let created = repo
            .create(CreateAccountRequest {
                label: "  ledger  ".to_owned()
            })
            .await
            .expect("create failed");
        assert_eq!(
            created.label, "ledger",
            "before_create must be able to rewrite the DTO before the INSERT"
        );

        repo.update(
            created.id,
            UpdateAccountRequest {
                label: Some("cashbook".to_owned())
            }
        )
        .await
        .expect("update failed");

        assert!(repo.delete(created.id).await.expect("delete failed"));
        assert!(repo.restore(created.id).await.expect("restore failed"));

        assert_eq!(
            recorder.calls(),
            vec![
                "before_create",
                "after_create",
                "before_update",
                "after_update",
                "before_delete",
                "after_delete",
                "before_restore",
                "after_restore",
            ]
        );

        db.teardown().await;
    }

    #[tokio::test]
    async fn a_refusing_before_hook_writes_nothing() {
        let Some(db) = pg::provision("hooksrefuse", &[Account::MIGRATION_UP]).await else {
            return;
        };
        let pool = db.pool();

        let recorder = Recorder::new(Some("before_create"));
        let repo = AccountRepo::new(pool.clone(), recorder.clone());

        assert!(
            repo.create(CreateAccountRequest {
                label: "ledger".to_owned()
            })
            .await
            .is_err(),
            "a refusing before_create must fail the call"
        );
        assert!(
            pool.list(10, 0).await.expect("list failed").is_empty(),
            "a refused create must not have written a row"
        );
        assert_eq!(
            recorder.calls(),
            vec!["before_create"],
            "the after hook must not run when the before hook refused"
        );

        db.teardown().await;
    }

    #[tokio::test]
    async fn a_refusing_delete_hook_leaves_the_row() {
        let Some(db) = pg::provision("hooksdel", &[Account::MIGRATION_UP]).await else {
            return;
        };
        let pool = db.pool();

        let stored = pool
            .create(CreateAccountRequest {
                label: "ledger".to_owned()
            })
            .await
            .expect("create failed");

        let repo = AccountRepo::new(pool.clone(), Recorder::new(Some("before_delete")));
        assert!(repo.delete(stored.id).await.is_err());
        assert!(
            pool.find_by_id(stored.id)
                .await
                .expect("read failed")
                .is_some(),
            "a refused delete must leave the row in place"
        );

        db.teardown().await;
    }

    #[tokio::test]
    async fn reads_reach_the_pool_through_the_wrapper() {
        let Some(db) = pg::provision("hooksread", &[Account::MIGRATION_UP]).await else {
            return;
        };
        let pool = db.pool();

        let recorder = Recorder::new(None);
        let repo = AccountRepo::new(pool.clone(), recorder.clone());
        let created = repo
            .create(CreateAccountRequest {
                label: "ledger".to_owned()
            })
            .await
            .expect("create failed");

        let found = repo
            .find_by_id(created.id)
            .await
            .expect("read through the wrapper failed")
            .expect("row missing");
        assert_eq!(found.id, created.id);
        assert_eq!(
            recorder.calls(),
            vec!["before_create", "after_create"],
            "a read must not invoke any hook"
        );

        db.teardown().await;
    }
}