toasty-driver-integration-suite 0.5.0

Integration test suite for Toasty database drivers
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
use crate::prelude::*;

/// Tests that preloading a `HasOne<Option<_>>` correctly distinguishes between
/// "not loaded" and "loaded as None" when the relation does not exist.
#[driver_test(id(ID), scenario(crate::scenarios::has_one_optional_belongs_to))]
pub async fn preload_has_one_option_none_then_some(test: &mut Test) -> Result<()> {
    let mut db = setup(test).await;

    // Create a user WITHOUT a profile
    let user_no_profile = User::create().name("No Profile").exec(&mut db).await?;

    // Preload the profile — no profile exists, so it should be `None` (loaded)
    let user_no_profile = User::filter_by_id(user_no_profile.id)
        .include(User::fields().profile())
        .get(&mut db)
        .await?;

    // `.get()` must not panic — the relation was preloaded and is None
    assert!(user_no_profile.profile.get().is_none());

    // Create a user WITH a profile
    let user_with_profile = User::create()
        .name("Has Profile")
        .profile(Profile::create().bio("A bio"))
        .exec(&mut db)
        .await?;

    // Preload the profile — a profile exists, so it should be `Some`
    let user_with_profile = User::filter_by_id(user_with_profile.id)
        .include(User::fields().profile())
        .get(&mut db)
        .await?;

    let profile = user_with_profile.profile.get().as_ref().unwrap();
    assert_eq!("A bio", profile.bio);
    assert_eq!(user_with_profile.id, *profile.user_id.as_ref().unwrap());

    Ok(())
}

#[driver_test(id(ID), scenario(crate::scenarios::has_many_belongs_to))]
pub async fn basic_has_many_and_belongs_to_preload(test: &mut Test) -> Result<()> {
    let mut db = setup(test).await;

    // Create a user with a few todos
    let user = User::create()
        .name("Alice")
        .todo(Todo::create().title("todo 1"))
        .todo(Todo::create().title("todo 2"))
        .todo(Todo::create().title("todo 3"))
        .exec(&mut db)
        .await?;

    // Find the user, include TODOs
    let user = User::filter_by_id(user.id)
        .include(User::fields().todos())
        .get(&mut db)
        .await?;

    // This will panic
    assert_eq!(3, user.todos.get().len());

    let id = user.todos.get()[0].id;

    let todo = Todo::filter_by_id(id)
        .include(Todo::fields().user())
        .get(&mut db)
        .await?;

    assert_eq!(user.id, todo.user.get().id);
    assert_eq!(user.id, todo.user_id);
    Ok(())
}

#[driver_test(id(ID))]
pub async fn multiple_includes_same_model(test: &mut Test) -> Result<()> {
    #[derive(Debug, toasty::Model)]
    struct User {
        #[key]
        #[auto]
        id: ID,

        #[allow(dead_code)]
        name: String,

        #[has_many]
        posts: toasty::HasMany<Post>,

        #[has_many]
        comments: toasty::HasMany<Comment>,
    }

    #[derive(Debug, toasty::Model)]
    struct Post {
        #[key]
        #[auto]
        id: ID,

        #[allow(dead_code)]
        title: String,

        #[index]
        #[allow(dead_code)]
        user_id: ID,

        #[belongs_to(key = user_id, references = id)]
        user: toasty::BelongsTo<User>,
    }

    #[derive(Debug, toasty::Model)]
    struct Comment {
        #[key]
        #[auto]
        id: ID,

        #[allow(dead_code)]
        text: String,

        #[index]
        #[allow(dead_code)]
        user_id: ID,

        #[belongs_to(key = user_id, references = id)]
        user: toasty::BelongsTo<User>,
    }

    let mut db = test.setup_db(models!(User, Post, Comment)).await;

    // Create a user
    let user = User::create().name("Test User").exec(&mut db).await?;

    // Create posts associated with the user
    Post::create()
        .title("Post 1")
        .user(&user)
        .exec(&mut db)
        .await?;

    Post::create()
        .title("Post 2")
        .user(&user)
        .exec(&mut db)
        .await?;

    // Create comments associated with the user
    Comment::create()
        .text("Comment 1")
        .user(&user)
        .exec(&mut db)
        .await?;

    Comment::create()
        .text("Comment 2")
        .user(&user)
        .exec(&mut db)
        .await?;

    Comment::create()
        .text("Comment 3")
        .user(&user)
        .exec(&mut db)
        .await?;

    // Test individual includes work (baseline)
    let user_with_posts = User::filter_by_id(user.id)
        .include(User::fields().posts())
        .get(&mut db)
        .await?;
    assert_eq!(2, user_with_posts.posts.get().len());

    let user_with_comments = User::filter_by_id(user.id)
        .include(User::fields().comments())
        .get(&mut db)
        .await?;
    assert_eq!(3, user_with_comments.comments.get().len());

    // Test multiple includes in one query
    let loaded_user = User::filter_by_id(user.id)
        .include(User::fields().posts()) // First include
        .include(User::fields().comments()) // Second include
        .get(&mut db)
        .await?;

    assert_eq!(2, loaded_user.posts.get().len());
    assert_eq!(3, loaded_user.comments.get().len());
    Ok(())
}

#[driver_test(id(ID))]
pub async fn basic_has_one_and_belongs_to_preload(test: &mut Test) -> Result<()> {
    #[derive(Debug, toasty::Model)]
    struct User {
        #[key]
        #[auto]
        id: ID,

        name: String,

        #[has_one]
        profile: toasty::HasOne<Option<Profile>>,
    }

    #[derive(Debug, toasty::Model)]
    struct Profile {
        #[key]
        #[auto]
        id: ID,

        bio: String,

        #[unique]
        user_id: Option<ID>,

        #[belongs_to(key = user_id, references = id)]
        user: toasty::BelongsTo<Option<User>>,
    }

    let mut db = test.setup_db(models!(User, Profile)).await;

    // Create a user with a profile
    let user = User::create()
        .name("John Doe")
        .profile(Profile::create().bio("A person"))
        .exec(&mut db)
        .await?;

    // Find the user, include profile
    let user = User::filter_by_id(user.id)
        .include(User::fields().profile())
        .get(&mut db)
        .await?;

    // Verify the profile is preloaded
    let profile = user.profile.get().as_ref().unwrap();
    assert_eq!("A person", profile.bio);
    assert_eq!(user.id, *profile.user_id.as_ref().unwrap());

    let profile_id = profile.id;

    // Test the reciprocal belongs_to preload
    let profile = Profile::filter_by_id(profile_id)
        .include(Profile::fields().user())
        .get(&mut db)
        .await?;

    assert_eq!(user.id, profile.user.get().as_ref().unwrap().id);
    assert_eq!("John Doe", profile.user.get().as_ref().unwrap().name);
    Ok(())
}

#[driver_test(id(ID))]
pub async fn multiple_includes_with_has_one(test: &mut Test) -> Result<()> {
    #[derive(Debug, toasty::Model)]
    #[allow(dead_code)]
    struct User {
        #[key]
        #[auto]
        id: ID,

        name: String,

        #[has_one]
        profile: toasty::HasOne<Option<Profile>>,

        #[has_one]
        settings: toasty::HasOne<Option<Settings>>,
    }

    #[derive(Debug, toasty::Model)]
    #[allow(dead_code)]
    struct Profile {
        #[key]
        #[auto]
        id: ID,

        bio: String,

        #[unique]
        user_id: Option<ID>,

        #[belongs_to(key = user_id, references = id)]
        user: toasty::BelongsTo<Option<User>>,
    }

    #[derive(Debug, toasty::Model)]
    #[allow(dead_code)]
    struct Settings {
        #[key]
        #[auto]
        id: ID,

        theme: String,

        #[unique]
        user_id: Option<ID>,

        #[belongs_to(key = user_id, references = id)]
        user: toasty::BelongsTo<Option<User>>,
    }

    let mut db = test.setup_db(models!(User, Profile, Settings)).await;

    // Create a user with both profile and settings
    let user = User::create()
        .name("Jane Doe")
        .profile(Profile::create().bio("Software engineer"))
        .settings(Settings::create().theme("dark"))
        .exec(&mut db)
        .await?;

    // Test individual includes work (baseline)
    let user_with_profile = User::filter_by_id(user.id)
        .include(User::fields().profile())
        .get(&mut db)
        .await?;
    assert!(user_with_profile.profile.get().is_some());
    assert_eq!(
        "Software engineer",
        user_with_profile.profile.get().as_ref().unwrap().bio
    );

    let user_with_settings = User::filter_by_id(user.id)
        .include(User::fields().settings())
        .get(&mut db)
        .await?;
    assert!(user_with_settings.settings.get().is_some());
    assert_eq!(
        "dark",
        user_with_settings.settings.get().as_ref().unwrap().theme
    );

    // Test multiple includes in one query
    let loaded_user = User::filter_by_id(user.id)
        .include(User::fields().profile()) // First include
        .include(User::fields().settings()) // Second include
        .get(&mut db)
        .await?;

    assert!(loaded_user.profile.get().is_some());
    assert_eq!(
        "Software engineer",
        loaded_user.profile.get().as_ref().unwrap().bio
    );
    assert!(loaded_user.settings.get().is_some());
    assert_eq!("dark", loaded_user.settings.get().as_ref().unwrap().theme);
    Ok(())
}

#[driver_test(id(ID))]
pub async fn combined_has_many_and_has_one_preload(test: &mut Test) -> Result<()> {
    #[derive(Debug, toasty::Model)]
    #[allow(dead_code)]
    struct User {
        #[key]
        #[auto]
        id: ID,

        name: String,

        #[has_one]
        profile: toasty::HasOne<Option<Profile>>,

        #[has_many]
        todos: toasty::HasMany<Todo>,
    }

    #[derive(Debug, toasty::Model)]
    #[allow(dead_code)]
    struct Profile {
        #[key]
        #[auto]
        id: ID,

        bio: String,

        #[unique]
        user_id: Option<ID>,

        #[belongs_to(key = user_id, references = id)]
        user: toasty::BelongsTo<Option<User>>,
    }

    #[derive(Debug, toasty::Model)]
    #[allow(dead_code)]
    struct Todo {
        #[key]
        #[auto]
        id: ID,

        title: String,

        #[index]
        user_id: ID,

        #[belongs_to(key = user_id, references = id)]
        user: toasty::BelongsTo<User>,
    }

    let mut db = test.setup_db(models!(User, Profile, Todo)).await;

    // Create a user with a profile and multiple todos
    let user = User::create()
        .name("Bob Smith")
        .profile(Profile::create().bio("Developer"))
        .todo(Todo::create().title("Task 1"))
        .todo(Todo::create().title("Task 2"))
        .todo(Todo::create().title("Task 3"))
        .exec(&mut db)
        .await?;

    // Test combined has_one and has_many preload in a single query
    let loaded_user = User::filter_by_id(user.id)
        .include(User::fields().profile()) // has_one include
        .include(User::fields().todos()) // has_many include
        .get(&mut db)
        .await?;

    // Verify has_one association is preloaded
    assert!(loaded_user.profile.get().is_some());
    assert_eq!("Developer", loaded_user.profile.get().as_ref().unwrap().bio);

    // Verify has_many association is preloaded
    assert_eq!(3, loaded_user.todos.get().len());
    let todo_titles: Vec<&str> = loaded_user
        .todos
        .get()
        .iter()
        .map(|t| t.title.as_str())
        .collect();
    assert!(todo_titles.contains(&"Task 1"));
    assert!(todo_titles.contains(&"Task 2"));
    assert!(todo_titles.contains(&"Task 3"));
    Ok(())
}

#[driver_test(id(ID), requires(sql), scenario(crate::scenarios::has_many_belongs_to))]
pub async fn preload_on_empty_table(test: &mut Test) -> Result<()> {
    let mut db = setup(test).await;

    // Query with include on empty table - should return empty result, not SQL error
    let users: Vec<User> = User::all()
        .include(User::fields().todos())
        .exec(&mut db)
        .await?;

    assert_eq!(0, users.len());
    Ok(())
}

#[driver_test(id(ID))]
pub async fn preload_on_empty_query(test: &mut Test) -> Result<()> {
    #[derive(Debug, toasty::Model)]
    struct User {
        #[key]
        #[auto]
        id: ID,

        #[index]
        #[allow(dead_code)]
        name: String,

        #[has_many]
        #[allow(dead_code)]
        todos: toasty::HasMany<Todo>,
    }

    #[derive(Debug, toasty::Model)]
    struct Todo {
        #[key]
        #[auto]
        id: ID,

        #[index]
        #[allow(dead_code)]
        user_id: ID,

        #[belongs_to(key = user_id, references = id)]
        #[allow(dead_code)]
        user: toasty::BelongsTo<User>,
    }

    let mut db = test.setup_db(models!(User, Todo)).await;

    // Query with include on empty table - should return empty result, not SQL error
    let users: Vec<User> = User::filter_by_name("foo")
        .include(User::fields().todos())
        .exec(&mut db)
        .await?;

    assert_eq!(0, users.len());
    Ok(())
}

/// HasMany<T> + BelongsTo<Option<T>>: nullable FK allows children to exist
/// without a parent. Tests preloading from both directions.
#[driver_test(id(ID))]
pub async fn preload_has_many_with_optional_belongs_to(test: &mut Test) -> Result<()> {
    #[derive(Debug, toasty::Model)]
    struct User {
        #[key]
        #[auto]
        id: ID,

        name: String,

        #[has_many]
        todos: toasty::HasMany<Todo>,
    }

    #[derive(Debug, toasty::Model)]
    struct Todo {
        #[key]
        #[auto]
        id: ID,

        #[index]
        title: String,

        #[index]
        user_id: Option<ID>,

        #[belongs_to(key = user_id, references = id)]
        user: toasty::BelongsTo<Option<User>>,
    }

    let mut db = test.setup_db(models!(User, Todo)).await;

    // Create a user with linked todos
    let user = User::create()
        .name("Alice")
        .todo(Todo::create().title("Task 1"))
        .todo(Todo::create().title("Task 2"))
        .exec(&mut db)
        .await?;

    // Preload HasMany from parent side
    let user = User::filter_by_id(user.id)
        .include(User::fields().todos())
        .get(&mut db)
        .await?;

    assert_eq!(2, user.todos.get().len());

    let todo_id = user.todos.get()[0].id;

    // Preload BelongsTo<Option<User>> from child side — linked todo
    let todo = Todo::filter_by_id(todo_id)
        .include(Todo::fields().user())
        .get(&mut db)
        .await?;

    assert_eq!(user.id, todo.user.get().as_ref().unwrap().id);

    // Create an orphan todo (no user)
    let orphan = Todo::create().title("Orphan").exec(&mut db).await?;

    // Preload BelongsTo<Option<User>> on orphan — should be None
    let orphan = Todo::filter_by_id(orphan.id)
        .include(Todo::fields().user())
        .get(&mut db)
        .await?;

    assert!(orphan.user.get().is_none());

    Ok(())
}

/// HasOne<Option<T>> + BelongsTo<T> (required FK): the child always points to a
/// parent, but the parent may or may not have a child. Tests preloading from
/// both directions.
#[driver_test(id(ID))]
pub async fn preload_has_one_optional_with_required_belongs_to(test: &mut Test) -> Result<()> {
    #[derive(Debug, toasty::Model)]
    struct User {
        #[key]
        #[auto]
        id: ID,

        name: String,

        #[has_one]
        profile: toasty::HasOne<Option<Profile>>,
    }

    #[derive(Debug, toasty::Model)]
    struct Profile {
        #[key]
        #[auto]
        id: ID,

        bio: String,

        #[unique]
        user_id: ID,

        #[belongs_to(key = user_id, references = id)]
        user: toasty::BelongsTo<User>,
    }

    let mut db = test.setup_db(models!(User, Profile)).await;

    // Create a user WITH a profile
    let user_with = User::create()
        .name("Has Profile")
        .profile(Profile::create().bio("hello"))
        .exec(&mut db)
        .await?;

    // Create a user WITHOUT a profile
    let user_without = User::create().name("No Profile").exec(&mut db).await?;

    // Preload HasOne<Option<Profile>> — profile exists
    let loaded = User::filter_by_id(user_with.id)
        .include(User::fields().profile())
        .get(&mut db)
        .await?;

    let profile = loaded.profile.get().as_ref().unwrap();
    assert_eq!("hello", profile.bio);
    assert_eq!(user_with.id, profile.user_id);

    // Preload HasOne<Option<Profile>> — no profile
    let loaded = User::filter_by_id(user_without.id)
        .include(User::fields().profile())
        .get(&mut db)
        .await?;

    assert!(loaded.profile.get().is_none());

    // Preload BelongsTo<User> (required) from child side
    let profile = Profile::filter_by_user_id(user_with.id)
        .include(Profile::fields().user())
        .get(&mut db)
        .await?;

    assert_eq!(user_with.id, profile.user.get().id);
    assert_eq!("Has Profile", profile.user.get().name);

    Ok(())
}

/// HasOne<T> (required) + BelongsTo<Option<T>>: creating a parent requires
/// providing a child, but the child FK is nullable. Tests preloading from both
/// directions.
#[driver_test(id(ID))]
pub async fn preload_has_one_required_with_optional_belongs_to(test: &mut Test) -> Result<()> {
    #[derive(Debug, toasty::Model)]
    struct User {
        #[key]
        #[auto]
        id: ID,

        name: String,

        #[has_one]
        profile: toasty::HasOne<Profile>,
    }

    #[derive(Debug, toasty::Model)]
    struct Profile {
        #[key]
        #[auto]
        id: ID,

        bio: String,

        #[unique]
        user_id: Option<ID>,

        #[belongs_to(key = user_id, references = id)]
        user: toasty::BelongsTo<Option<User>>,
    }

    let mut db = test.setup_db(models!(User, Profile)).await;

    // Create a user (must provide a profile since HasOne<T> is required)
    let user = User::create()
        .name("Alice")
        .profile(Profile::create().bio("a bio"))
        .exec(&mut db)
        .await?;

    // Preload HasOne<Profile> (required) from parent side
    let loaded = User::filter_by_id(user.id)
        .include(User::fields().profile())
        .get(&mut db)
        .await?;

    let profile = loaded.profile.get();
    assert_eq!("a bio", profile.bio);
    assert_eq!(user.id, *profile.user_id.as_ref().unwrap());

    // Preload BelongsTo<Option<User>> from child side
    let profile = Profile::filter_by_id(profile.id)
        .include(Profile::fields().user())
        .get(&mut db)
        .await?;

    assert_eq!(user.id, profile.user.get().as_ref().unwrap().id);
    assert_eq!("Alice", profile.user.get().as_ref().unwrap().name);

    Ok(())
}

#[driver_test(id(ID))]
pub async fn nested_has_many_preload(test: &mut Test) {
    #[derive(Debug, toasty::Model)]
    #[allow(dead_code)]
    struct User {
        #[key]
        #[auto]
        id: ID,

        name: String,

        #[has_many]
        todos: toasty::HasMany<Todo>,
    }

    #[derive(Debug, toasty::Model)]
    #[allow(dead_code)]
    struct Todo {
        #[key]
        #[auto]
        id: ID,

        title: String,

        #[index]
        user_id: ID,

        #[belongs_to(key = user_id, references = id)]
        user: toasty::BelongsTo<User>,

        #[has_many]
        steps: toasty::HasMany<Step>,
    }

    #[derive(Debug, toasty::Model)]
    #[allow(dead_code)]
    struct Step {
        #[key]
        #[auto]
        id: ID,

        description: String,

        #[index]
        todo_id: ID,

        #[belongs_to(key = todo_id, references = id)]
        todo: toasty::BelongsTo<Todo>,
    }

    let mut db = test.setup_db(models!(User, Todo, Step)).await;

    // Create a user with todos, each with steps
    let user = User::create()
        .name("Alice")
        .todo(
            Todo::create()
                .title("Todo 1")
                .step(Step::create().description("Step 1a"))
                .step(Step::create().description("Step 1b")),
        )
        .todo(
            Todo::create()
                .title("Todo 2")
                .step(Step::create().description("Step 2a"))
                .step(Step::create().description("Step 2b"))
                .step(Step::create().description("Step 2c")),
        )
        .exec(&mut db)
        .await
        .unwrap();

    // Load user with nested include: todos AND their steps
    let user = User::filter_by_id(user.id)
        .include(User::fields().todos().steps())
        .get(&mut db)
        .await
        .unwrap();

    // Verify todos are loaded
    let todos = user.todos.get();
    assert_eq!(2, todos.len());

    // Verify steps are loaded on each todo
    let mut all_step_descriptions: Vec<&str> = Vec::new();
    for todo in todos {
        let steps = todo.steps.get();
        for step in steps {
            all_step_descriptions.push(&step.description);
        }
    }
    all_step_descriptions.sort();
    assert_eq!(
        all_step_descriptions,
        vec!["Step 1a", "Step 1b", "Step 2a", "Step 2b", "Step 2c"]
    );
}

// ===== HasMany -> HasOne<Option<T>> =====
// User has_many Posts, each Post has_one optional Detail
#[driver_test(id(ID))]
pub async fn nested_has_many_then_has_one_optional(test: &mut Test) -> Result<()> {
    #[derive(Debug, toasty::Model)]
    #[allow(dead_code)]
    struct User {
        #[key]
        #[auto]
        id: ID,

        name: String,

        #[has_many]
        posts: toasty::HasMany<Post>,
    }

    #[derive(Debug, toasty::Model)]
    #[allow(dead_code)]
    struct Post {
        #[key]
        #[auto]
        id: ID,

        title: String,

        #[index]
        user_id: ID,

        #[belongs_to(key = user_id, references = id)]
        user: toasty::BelongsTo<User>,

        #[has_one]
        detail: toasty::HasOne<Option<Detail>>,
    }

    #[derive(Debug, toasty::Model)]
    #[allow(dead_code)]
    struct Detail {
        #[key]
        #[auto]
        id: ID,

        body: String,

        #[unique]
        post_id: Option<ID>,

        #[belongs_to(key = post_id, references = id)]
        post: toasty::BelongsTo<Option<Post>>,
    }

    let mut db = test.setup_db(models!(User, Post, Detail)).await;

    let user = User::create()
        .name("Alice")
        .post(
            Post::create()
                .title("P1")
                .detail(Detail::create().body("D1")),
        )
        .post(Post::create().title("P2")) // no detail
        .exec(&mut db)
        .await?;

    let user = User::filter_by_id(user.id)
        .include(User::fields().posts().detail())
        .get(&mut db)
        .await?;

    let posts = user.posts.get();
    assert_eq!(2, posts.len());

    let mut with_detail = 0;
    let mut without_detail = 0;
    for post in posts {
        match post.detail.get() {
            Some(d) => {
                assert_eq!("D1", d.body);
                with_detail += 1;
            }
            None => without_detail += 1,
        }
    }
    assert_eq!(1, with_detail);
    assert_eq!(1, without_detail);

    Ok(())
}

// ===== HasMany -> HasOne<T> (required) =====
// User has_many Accounts, each Account has_one required Settings
#[driver_test(id(ID))]
pub async fn nested_has_many_then_has_one_required(test: &mut Test) -> Result<()> {
    #[derive(Debug, toasty::Model)]
    #[allow(dead_code)]
    struct User {
        #[key]
        #[auto]
        id: ID,

        name: String,

        #[has_many]
        accounts: toasty::HasMany<Account>,
    }

    #[derive(Debug, toasty::Model)]
    #[allow(dead_code)]
    struct Account {
        #[key]
        #[auto]
        id: ID,

        label: String,

        #[index]
        user_id: ID,

        #[belongs_to(key = user_id, references = id)]
        user: toasty::BelongsTo<User>,

        #[has_one]
        settings: toasty::HasOne<Settings>,
    }

    #[derive(Debug, toasty::Model)]
    #[allow(dead_code)]
    struct Settings {
        #[key]
        #[auto]
        id: ID,

        theme: String,

        #[unique]
        account_id: Option<ID>,

        #[belongs_to(key = account_id, references = id)]
        account: toasty::BelongsTo<Option<Account>>,
    }

    let mut db = test.setup_db(models!(User, Account, Settings)).await;

    let user = User::create()
        .name("Bob")
        .account(
            Account::create()
                .label("A1")
                .settings(Settings::create().theme("dark")),
        )
        .account(
            Account::create()
                .label("A2")
                .settings(Settings::create().theme("light")),
        )
        .exec(&mut db)
        .await?;

    let user = User::filter_by_id(user.id)
        .include(User::fields().accounts().settings())
        .get(&mut db)
        .await?;

    let accounts = user.accounts.get();
    assert_eq!(2, accounts.len());

    let mut themes: Vec<&str> = accounts
        .iter()
        .map(|a| a.settings.get().theme.as_str())
        .collect();
    themes.sort();
    assert_eq!(themes, vec!["dark", "light"]);

    Ok(())
}

// ===== HasMany -> BelongsTo<T> (required) =====
// Category has_many Items, each Item belongs_to a Brand
#[driver_test(id(ID))]
pub async fn nested_has_many_then_belongs_to_required(test: &mut Test) -> Result<()> {
    #[derive(Debug, toasty::Model)]
    #[allow(dead_code)]
    struct Category {
        #[key]
        #[auto]
        id: ID,

        name: String,

        #[has_many]
        items: toasty::HasMany<Item>,
    }

    #[derive(Debug, toasty::Model)]
    #[allow(dead_code)]
    struct Brand {
        #[key]
        #[auto]
        id: ID,

        name: String,
    }

    #[derive(Debug, toasty::Model)]
    #[allow(dead_code)]
    struct Item {
        #[key]
        #[auto]
        id: ID,

        title: String,

        #[index]
        category_id: ID,

        #[belongs_to(key = category_id, references = id)]
        category: toasty::BelongsTo<Category>,

        #[index]
        brand_id: ID,

        #[belongs_to(key = brand_id, references = id)]
        brand: toasty::BelongsTo<Brand>,
    }

    let mut db = test.setup_db(models!(Category, Brand, Item)).await;

    let brand_a = Brand::create().name("BrandA").exec(&mut db).await?;
    let brand_b = Brand::create().name("BrandB").exec(&mut db).await?;

    let cat = Category::create()
        .name("Electronics")
        .item(Item::create().title("Phone").brand(&brand_a))
        .item(Item::create().title("Laptop").brand(&brand_b))
        .exec(&mut db)
        .await?;

    let cat = Category::filter_by_id(cat.id)
        .include(Category::fields().items().brand())
        .get(&mut db)
        .await?;

    let items = cat.items.get();
    assert_eq!(2, items.len());

    let mut brand_names: Vec<&str> = items.iter().map(|i| i.brand.get().name.as_str()).collect();
    brand_names.sort();
    assert_eq!(brand_names, vec!["BrandA", "BrandB"]);

    Ok(())
}

// ===== HasMany -> BelongsTo<T> where multiple items share the same target =====
// Sibling rows with the same foreign key must not break the nested preload.
// Regression for #701: the DDB nested merge used to panic with
// "HashIndex: duplicate key detected" when two Items pointed at one Brand.
#[driver_test(id(ID))]
pub async fn nested_has_many_then_shared_belongs_to(test: &mut Test) -> Result<()> {
    #[derive(Debug, toasty::Model)]
    #[allow(dead_code)]
    struct Category {
        #[key]
        #[auto]
        id: ID,

        name: String,

        #[has_many]
        items: toasty::HasMany<Item>,
    }

    #[derive(Debug, toasty::Model)]
    #[allow(dead_code)]
    struct Brand {
        #[key]
        #[auto]
        id: ID,

        name: String,
    }

    #[derive(Debug, toasty::Model)]
    #[allow(dead_code)]
    struct Item {
        #[key]
        #[auto]
        id: ID,

        title: String,

        #[index]
        category_id: ID,

        #[belongs_to(key = category_id, references = id)]
        category: toasty::BelongsTo<Category>,

        #[index]
        brand_id: ID,

        #[belongs_to(key = brand_id, references = id)]
        brand: toasty::BelongsTo<Brand>,
    }

    let mut db = test.setup_db(models!(Category, Brand, Item)).await;

    let brand = Brand::create().name("BrandA").exec(&mut db).await?;
    let cat = Category::create()
        .name("Electronics")
        .item(Item::create().title("Phone").brand(&brand))
        .item(Item::create().title("Laptop").brand(&brand))
        .exec(&mut db)
        .await?;

    let cat = Category::filter_by_id(cat.id)
        .include(Category::fields().items().brand())
        .get(&mut db)
        .await?;

    let items = cat.items.get();
    assert_eq!(2, items.len());
    for item in items {
        assert_eq!("BrandA", item.brand.get().name);
    }

    Ok(())
}

// ===== HasMany -> BelongsTo<Option<T>> =====
// Team has_many Tasks, each Task optionally belongs_to an Assignee
#[driver_test(id(ID))]
pub async fn nested_has_many_then_belongs_to_optional(test: &mut Test) -> Result<()> {
    #[derive(Debug, toasty::Model)]
    #[allow(dead_code)]
    struct Team {
        #[key]
        #[auto]
        id: ID,

        name: String,

        #[has_many]
        tasks: toasty::HasMany<Task>,
    }

    #[derive(Debug, toasty::Model)]
    #[allow(dead_code)]
    struct Assignee {
        #[key]
        #[auto]
        id: ID,

        name: String,
    }

    #[derive(Debug, toasty::Model)]
    #[allow(dead_code)]
    struct Task {
        #[key]
        #[auto]
        id: ID,

        title: String,

        #[index]
        team_id: ID,

        #[belongs_to(key = team_id, references = id)]
        team: toasty::BelongsTo<Team>,

        #[index]
        assignee_id: Option<ID>,

        #[belongs_to(key = assignee_id, references = id)]
        assignee: toasty::BelongsTo<Option<Assignee>>,
    }

    let mut db = test.setup_db(models!(Team, Assignee, Task)).await;

    let person = Assignee::create().name("Alice").exec(&mut db).await?;

    let team = Team::create()
        .name("Engineering")
        .task(Task::create().title("Assigned").assignee(&person))
        .task(Task::create().title("Unassigned"))
        .exec(&mut db)
        .await?;

    let team = Team::filter_by_id(team.id)
        .include(Team::fields().tasks().assignee())
        .get(&mut db)
        .await?;

    let tasks = team.tasks.get();
    assert_eq!(2, tasks.len());

    let mut assigned = 0;
    let mut unassigned = 0;
    for task in tasks {
        match task.assignee.get() {
            Some(a) => {
                assert_eq!("Alice", a.name);
                assigned += 1;
            }
            None => unassigned += 1,
        }
    }
    assert_eq!(1, assigned);
    assert_eq!(1, unassigned);

    Ok(())
}

// ===== HasOne<Option<T>> -> HasMany =====
// User has_one optional Profile, Profile has_many Badges
#[driver_test(id(ID))]
pub async fn nested_has_one_optional_then_has_many(test: &mut Test) -> Result<()> {
    #[derive(Debug, toasty::Model)]
    #[allow(dead_code)]
    struct User {
        #[key]
        #[auto]
        id: ID,

        name: String,

        #[has_one]
        profile: toasty::HasOne<Option<Profile>>,
    }

    #[derive(Debug, toasty::Model)]
    #[allow(dead_code)]
    struct Profile {
        #[key]
        #[auto]
        id: ID,

        bio: String,

        #[unique]
        user_id: Option<ID>,

        #[belongs_to(key = user_id, references = id)]
        user: toasty::BelongsTo<Option<User>>,

        #[has_many]
        badges: toasty::HasMany<Badge>,
    }

    #[derive(Debug, toasty::Model)]
    #[allow(dead_code)]
    struct Badge {
        #[key]
        #[auto]
        id: ID,

        label: String,

        #[index]
        profile_id: ID,

        #[belongs_to(key = profile_id, references = id)]
        profile: toasty::BelongsTo<Profile>,
    }

    let mut db = test.setup_db(models!(User, Profile, Badge)).await;

    // User with profile and badges
    let user = User::create()
        .name("Alice")
        .profile(
            Profile::create()
                .bio("hi")
                .badge(Badge::create().label("Gold"))
                .badge(Badge::create().label("Silver")),
        )
        .exec(&mut db)
        .await?;

    let user = User::filter_by_id(user.id)
        .include(User::fields().profile().badges())
        .get(&mut db)
        .await?;

    let profile = user.profile.get().as_ref().unwrap();
    assert_eq!("hi", profile.bio);
    let mut labels: Vec<&str> = profile
        .badges
        .get()
        .iter()
        .map(|b| b.label.as_str())
        .collect();
    labels.sort();
    assert_eq!(labels, vec!["Gold", "Silver"]);

    // User without profile - nested preload should handle gracefully
    let user2 = User::create().name("Bob").exec(&mut db).await?;

    let user2 = User::filter_by_id(user2.id)
        .include(User::fields().profile().badges())
        .get(&mut db)
        .await?;

    assert!(user2.profile.get().is_none());

    Ok(())
}

// ===== HasOne<T> (required) -> HasMany =====
// Order has_one required Invoice, Invoice has_many LineItems
#[driver_test(id(ID))]
pub async fn nested_has_one_required_then_has_many(test: &mut Test) -> Result<()> {
    #[derive(Debug, toasty::Model)]
    #[allow(dead_code)]
    struct Order {
        #[key]
        #[auto]
        id: ID,

        label: String,

        #[has_one]
        invoice: toasty::HasOne<Invoice>,
    }

    #[derive(Debug, toasty::Model)]
    #[allow(dead_code)]
    struct Invoice {
        #[key]
        #[auto]
        id: ID,

        code: String,

        #[unique]
        order_id: Option<ID>,

        #[belongs_to(key = order_id, references = id)]
        order: toasty::BelongsTo<Option<Order>>,

        #[has_many]
        line_items: toasty::HasMany<LineItem>,
    }

    #[derive(Debug, toasty::Model)]
    #[allow(dead_code)]
    struct LineItem {
        #[key]
        #[auto]
        id: ID,

        description: String,

        #[index]
        invoice_id: ID,

        #[belongs_to(key = invoice_id, references = id)]
        invoice: toasty::BelongsTo<Invoice>,
    }

    let mut db = test.setup_db(models!(Order, Invoice, LineItem)).await;

    let order = Order::create()
        .label("Order1")
        .invoice(
            Invoice::create()
                .code("INV-001")
                .line_item(LineItem::create().description("Widget"))
                .line_item(LineItem::create().description("Gadget")),
        )
        .exec(&mut db)
        .await?;

    let order = Order::filter_by_id(order.id)
        .include(Order::fields().invoice().line_items())
        .get(&mut db)
        .await?;

    let invoice = order.invoice.get();
    assert_eq!("INV-001", invoice.code);
    let mut descs: Vec<&str> = invoice
        .line_items
        .get()
        .iter()
        .map(|li| li.description.as_str())
        .collect();
    descs.sort();
    assert_eq!(descs, vec!["Gadget", "Widget"]);

    Ok(())
}

// ===== HasOne<Option<T>> -> HasOne<Option<T>> =====
// User has_one optional Profile, Profile has_one optional Avatar
#[driver_test(id(ID))]
pub async fn nested_has_one_optional_then_has_one_optional(test: &mut Test) -> Result<()> {
    #[derive(Debug, toasty::Model)]
    #[allow(dead_code)]
    struct User {
        #[key]
        #[auto]
        id: ID,

        name: String,

        #[has_one]
        profile: toasty::HasOne<Option<Profile>>,
    }

    #[derive(Debug, toasty::Model)]
    #[allow(dead_code)]
    struct Profile {
        #[key]
        #[auto]
        id: ID,

        bio: String,

        #[unique]
        user_id: Option<ID>,

        #[belongs_to(key = user_id, references = id)]
        user: toasty::BelongsTo<Option<User>>,

        #[has_one]
        avatar: toasty::HasOne<Option<Avatar>>,
    }

    #[derive(Debug, toasty::Model)]
    #[allow(dead_code)]
    struct Avatar {
        #[key]
        #[auto]
        id: ID,

        url: String,

        #[unique]
        profile_id: Option<ID>,

        #[belongs_to(key = profile_id, references = id)]
        profile: toasty::BelongsTo<Option<Profile>>,
    }

    let mut db = test.setup_db(models!(User, Profile, Avatar)).await;

    // User -> Profile -> Avatar (all present)
    let user = User::create()
        .name("Alice")
        .profile(
            Profile::create()
                .bio("hi")
                .avatar(Avatar::create().url("pic.png")),
        )
        .exec(&mut db)
        .await?;

    let user = User::filter_by_id(user.id)
        .include(User::fields().profile().avatar())
        .get(&mut db)
        .await?;

    let profile = user.profile.get().as_ref().unwrap();
    assert_eq!("hi", profile.bio);
    let avatar = profile.avatar.get().as_ref().unwrap();
    assert_eq!("pic.png", avatar.url);

    // User -> Profile (present) -> Avatar (missing)
    let user2 = User::create()
        .name("Bob")
        .profile(Profile::create().bio("no pic"))
        .exec(&mut db)
        .await?;

    let user2 = User::filter_by_id(user2.id)
        .include(User::fields().profile().avatar())
        .get(&mut db)
        .await?;

    let profile2 = user2.profile.get().as_ref().unwrap();
    assert_eq!("no pic", profile2.bio);
    assert!(profile2.avatar.get().is_none());

    // User -> Profile (missing) - nested preload short-circuits
    let user3 = User::create().name("Carol").exec(&mut db).await?;

    let user3 = User::filter_by_id(user3.id)
        .include(User::fields().profile().avatar())
        .get(&mut db)
        .await?;

    assert!(user3.profile.get().is_none());

    Ok(())
}

// ===== HasOne<T> (required) -> HasOne<T> (required) =====
// User has_one required Profile, Profile has_one required Avatar
#[driver_test(id(ID))]
pub async fn nested_has_one_required_then_has_one_required(test: &mut Test) -> Result<()> {
    #[derive(Debug, toasty::Model)]
    #[allow(dead_code)]
    struct User {
        #[key]
        #[auto]
        id: ID,

        name: String,

        #[has_one]
        profile: toasty::HasOne<Profile>,
    }

    #[derive(Debug, toasty::Model)]
    #[allow(dead_code)]
    struct Profile {
        #[key]
        #[auto]
        id: ID,

        bio: String,

        #[unique]
        user_id: Option<ID>,

        #[belongs_to(key = user_id, references = id)]
        user: toasty::BelongsTo<Option<User>>,

        #[has_one]
        avatar: toasty::HasOne<Avatar>,
    }

    #[derive(Debug, toasty::Model)]
    #[allow(dead_code)]
    struct Avatar {
        #[key]
        #[auto]
        id: ID,

        url: String,

        #[unique]
        profile_id: Option<ID>,

        #[belongs_to(key = profile_id, references = id)]
        profile: toasty::BelongsTo<Option<Profile>>,
    }

    let mut db = test.setup_db(models!(User, Profile, Avatar)).await;

    let user = User::create()
        .name("Alice")
        .profile(
            Profile::create()
                .bio("engineer")
                .avatar(Avatar::create().url("alice.jpg")),
        )
        .exec(&mut db)
        .await?;

    let user = User::filter_by_id(user.id)
        .include(User::fields().profile().avatar())
        .get(&mut db)
        .await?;

    let profile = user.profile.get();
    assert_eq!("engineer", profile.bio);
    let avatar = profile.avatar.get();
    assert_eq!("alice.jpg", avatar.url);

    Ok(())
}

// ===== HasOne<Option<T>> -> BelongsTo<T> (required) =====
// User has_one optional Review, Review belongs_to a Product
#[driver_test(id(ID))]
pub async fn nested_has_one_optional_then_belongs_to_required(test: &mut Test) -> Result<()> {
    #[derive(Debug, toasty::Model)]
    #[allow(dead_code)]
    struct User {
        #[key]
        #[auto]
        id: ID,

        name: String,

        #[has_one]
        review: toasty::HasOne<Option<Review>>,
    }

    #[derive(Debug, toasty::Model)]
    #[allow(dead_code)]
    struct Product {
        #[key]
        #[auto]
        id: ID,

        name: String,
    }

    #[derive(Debug, toasty::Model)]
    #[allow(dead_code)]
    struct Review {
        #[key]
        #[auto]
        id: ID,

        body: String,

        #[unique]
        user_id: Option<ID>,

        #[belongs_to(key = user_id, references = id)]
        user: toasty::BelongsTo<Option<User>>,

        #[index]
        product_id: ID,

        #[belongs_to(key = product_id, references = id)]
        product: toasty::BelongsTo<Product>,
    }

    let mut db = test.setup_db(models!(User, Product, Review)).await;

    let product = Product::create().name("Widget").exec(&mut db).await?;

    let user = User::create()
        .name("Alice")
        .review(Review::create().body("Great!").product(&product))
        .exec(&mut db)
        .await?;

    // User with review -> preload nested product
    let user = User::filter_by_id(user.id)
        .include(User::fields().review().product())
        .get(&mut db)
        .await?;

    let review = user.review.get().as_ref().unwrap();
    assert_eq!("Great!", review.body);
    assert_eq!("Widget", review.product.get().name);

    // User without review
    let user2 = User::create().name("Bob").exec(&mut db).await?;

    let user2 = User::filter_by_id(user2.id)
        .include(User::fields().review().product())
        .get(&mut db)
        .await?;

    assert!(user2.review.get().is_none());

    Ok(())
}

// ===== BelongsTo<T> (required) -> HasMany =====
// Comment belongs_to a Post, Post has_many Tags
#[driver_test(id(ID))]
pub async fn nested_belongs_to_required_then_has_many(test: &mut Test) -> Result<()> {
    #[derive(Debug, toasty::Model)]
    #[allow(dead_code)]
    struct Post {
        #[key]
        #[auto]
        id: ID,

        title: String,

        #[has_many]
        tags: toasty::HasMany<Tag>,
    }

    #[derive(Debug, toasty::Model)]
    #[allow(dead_code)]
    struct Tag {
        #[key]
        #[auto]
        id: ID,

        label: String,

        #[index]
        post_id: ID,

        #[belongs_to(key = post_id, references = id)]
        post: toasty::BelongsTo<Post>,
    }

    #[derive(Debug, toasty::Model)]
    #[allow(dead_code)]
    struct Comment {
        #[key]
        #[auto]
        id: ID,

        body: String,

        #[index]
        post_id: ID,

        #[belongs_to(key = post_id, references = id)]
        post: toasty::BelongsTo<Post>,
    }

    let mut db = test.setup_db(models!(Post, Tag, Comment)).await;

    let post = Post::create()
        .title("Hello")
        .tag(Tag::create().label("rust"))
        .tag(Tag::create().label("orm"))
        .exec(&mut db)
        .await?;

    let comment = Comment::create()
        .body("Nice post")
        .post(&post)
        .exec(&mut db)
        .await?;

    // From comment, preload post's tags
    let comment = Comment::filter_by_id(comment.id)
        .include(Comment::fields().post().tags())
        .get(&mut db)
        .await?;

    assert_eq!("Hello", comment.post.get().title);
    let mut labels: Vec<&str> = comment
        .post
        .get()
        .tags
        .get()
        .iter()
        .map(|t| t.label.as_str())
        .collect();
    labels.sort();
    assert_eq!(labels, vec!["orm", "rust"]);

    Ok(())
}

// ===== BelongsTo<T> (required) -> HasOne<Option<T>> =====
// Todo belongs_to a User, User has_one optional Profile
#[driver_test(id(ID))]
pub async fn nested_belongs_to_required_then_has_one_optional(test: &mut Test) -> Result<()> {
    #[derive(Debug, toasty::Model)]
    #[allow(dead_code)]
    struct User {
        #[key]
        #[auto]
        id: ID,

        name: String,

        #[has_one]
        profile: toasty::HasOne<Option<Profile>>,

        #[has_many]
        todos: toasty::HasMany<Todo>,
    }

    #[derive(Debug, toasty::Model)]
    #[allow(dead_code)]
    struct Profile {
        #[key]
        #[auto]
        id: ID,

        bio: String,

        #[unique]
        user_id: Option<ID>,

        #[belongs_to(key = user_id, references = id)]
        user: toasty::BelongsTo<Option<User>>,
    }

    #[derive(Debug, toasty::Model)]
    #[allow(dead_code)]
    struct Todo {
        #[key]
        #[auto]
        id: ID,

        title: String,

        #[index]
        user_id: ID,

        #[belongs_to(key = user_id, references = id)]
        user: toasty::BelongsTo<User>,
    }

    let mut db = test.setup_db(models!(User, Profile, Todo)).await;

    // User with profile
    let user = User::create()
        .name("Alice")
        .profile(Profile::create().bio("developer"))
        .todo(Todo::create().title("Task 1"))
        .exec(&mut db)
        .await?;

    let todo_id = Todo::get_by_user_id(&mut db, user.id).await?.id;

    let todo = Todo::filter_by_id(todo_id)
        .include(Todo::fields().user().profile())
        .get(&mut db)
        .await?;

    assert_eq!("Alice", todo.user.get().name);
    let profile = todo.user.get().profile.get().as_ref().unwrap();
    assert_eq!("developer", profile.bio);

    // User without profile
    let user2 = User::create()
        .name("Bob")
        .todo(Todo::create().title("Task 2"))
        .exec(&mut db)
        .await?;

    let todo2_id = Todo::get_by_user_id(&mut db, user2.id).await?.id;

    let todo2 = Todo::filter_by_id(todo2_id)
        .include(Todo::fields().user().profile())
        .get(&mut db)
        .await?;

    assert_eq!("Bob", todo2.user.get().name);
    assert!(todo2.user.get().profile.get().is_none());

    Ok(())
}

// ===== BelongsTo<T> (required) -> BelongsTo<T> (required) =====
// Step belongs_to a Todo, Todo belongs_to a User (chain of belongs_to going up)
#[driver_test(id(ID))]
pub async fn nested_belongs_to_required_then_belongs_to_required(test: &mut Test) -> Result<()> {
    #[derive(Debug, toasty::Model)]
    #[allow(dead_code)]
    struct User {
        #[key]
        #[auto]
        id: ID,

        name: String,

        #[has_many]
        todos: toasty::HasMany<Todo>,
    }

    #[derive(Debug, toasty::Model)]
    #[allow(dead_code)]
    struct Todo {
        #[key]
        #[auto]
        id: ID,

        title: String,

        #[index]
        user_id: ID,

        #[belongs_to(key = user_id, references = id)]
        user: toasty::BelongsTo<User>,

        #[has_many]
        steps: toasty::HasMany<Step>,
    }

    #[derive(Debug, toasty::Model)]
    #[allow(dead_code)]
    struct Step {
        #[key]
        #[auto]
        id: ID,

        description: String,

        #[index]
        todo_id: ID,

        #[belongs_to(key = todo_id, references = id)]
        todo: toasty::BelongsTo<Todo>,
    }

    let mut db = test.setup_db(models!(User, Todo, Step)).await;

    let user = User::create()
        .name("Alice")
        .todo(
            Todo::create()
                .title("T1")
                .step(Step::create().description("S1")),
        )
        .exec(&mut db)
        .await?;

    let todo_id = Todo::get_by_user_id(&mut db, user.id).await?.id;
    let step_id = Step::get_by_todo_id(&mut db, todo_id).await?.id;

    // From step, preload todo and then todo's user
    let step = Step::filter_by_id(step_id)
        .include(Step::fields().todo().user())
        .get(&mut db)
        .await?;

    assert_eq!("T1", step.todo.get().title);
    assert_eq!("Alice", step.todo.get().user.get().name);

    Ok(())
}

// ===== BelongsTo<Option<T>> -> HasMany =====
// Task optionally belongs_to a Project, Project has_many Members
#[driver_test(id(ID))]
pub async fn nested_belongs_to_optional_then_has_many(test: &mut Test) -> Result<()> {
    #[derive(Debug, toasty::Model)]
    #[allow(dead_code)]
    struct Project {
        #[key]
        #[auto]
        id: ID,

        name: String,

        #[has_many]
        members: toasty::HasMany<Member>,
    }

    #[derive(Debug, toasty::Model)]
    #[allow(dead_code)]
    struct Member {
        #[key]
        #[auto]
        id: ID,

        name: String,

        #[index]
        project_id: ID,

        #[belongs_to(key = project_id, references = id)]
        project: toasty::BelongsTo<Project>,
    }

    #[derive(Debug, toasty::Model)]
    #[allow(dead_code)]
    struct Task {
        #[key]
        #[auto]
        id: ID,

        title: String,

        #[index]
        project_id: Option<ID>,

        #[belongs_to(key = project_id, references = id)]
        project: toasty::BelongsTo<Option<Project>>,
    }

    let mut db = test.setup_db(models!(Project, Member, Task)).await;

    let project = Project::create()
        .name("Proj1")
        .member(Member::create().name("Alice"))
        .member(Member::create().name("Bob"))
        .exec(&mut db)
        .await?;

    // Task with project
    let task = Task::create()
        .title("Linked")
        .project(&project)
        .exec(&mut db)
        .await?;

    let task = Task::filter_by_id(task.id)
        .include(Task::fields().project().members())
        .get(&mut db)
        .await?;

    let proj = task.project.get().as_ref().unwrap();
    assert_eq!("Proj1", proj.name);
    let mut names: Vec<&str> = proj.members.get().iter().map(|m| m.name.as_str()).collect();
    names.sort();
    assert_eq!(names, vec!["Alice", "Bob"]);

    // Task without project
    let orphan = Task::create().title("Orphan").exec(&mut db).await?;

    let orphan = Task::filter_by_id(orphan.id)
        .include(Task::fields().project().members())
        .get(&mut db)
        .await?;

    assert!(orphan.project.get().is_none());

    Ok(())
}

// ===== BelongsTo<Option<T>> -> BelongsTo<Option<T>> =====
// Comment optionally belongs_to a Post, Post optionally belongs_to a Category
#[driver_test(id(ID))]
pub async fn nested_belongs_to_optional_then_belongs_to_optional(test: &mut Test) -> Result<()> {
    #[derive(Debug, toasty::Model)]
    #[allow(dead_code)]
    struct Category {
        #[key]
        #[auto]
        id: ID,

        name: String,
    }

    #[derive(Debug, toasty::Model)]
    #[allow(dead_code)]
    struct Post {
        #[key]
        #[auto]
        id: ID,

        title: String,

        #[index]
        category_id: Option<ID>,

        #[belongs_to(key = category_id, references = id)]
        category: toasty::BelongsTo<Option<Category>>,
    }

    #[derive(Debug, toasty::Model)]
    #[allow(dead_code)]
    struct Comment {
        #[key]
        #[auto]
        id: ID,

        body: String,

        #[index]
        post_id: Option<ID>,

        #[belongs_to(key = post_id, references = id)]
        post: toasty::BelongsTo<Option<Post>>,
    }

    let mut db = test.setup_db(models!(Category, Post, Comment)).await;

    let cat = Category::create().name("Tech").exec(&mut db).await?;
    let post = Post::create()
        .title("Hello")
        .category(&cat)
        .exec(&mut db)
        .await?;

    // Comment -> Post (present) -> Category (present)
    let c1 = Comment::create()
        .body("Nice")
        .post(&post)
        .exec(&mut db)
        .await?;

    let c1 = Comment::filter_by_id(c1.id)
        .include(Comment::fields().post().category())
        .get(&mut db)
        .await?;

    let loaded_post = c1.post.get().as_ref().unwrap();
    assert_eq!("Hello", loaded_post.title);
    let loaded_cat = loaded_post.category.get().as_ref().unwrap();
    assert_eq!("Tech", loaded_cat.name);

    // Post without category
    let post2 = Post::create().title("Uncategorized").exec(&mut db).await?;
    let c2 = Comment::create()
        .body("Hmm")
        .post(&post2)
        .exec(&mut db)
        .await?;

    let c2 = Comment::filter_by_id(c2.id)
        .include(Comment::fields().post().category())
        .get(&mut db)
        .await?;

    let loaded_post2 = c2.post.get().as_ref().unwrap();
    assert_eq!("Uncategorized", loaded_post2.title);
    assert!(loaded_post2.category.get().is_none());

    // Comment without post
    let c3 = Comment::create().body("Orphan").exec(&mut db).await?;

    let c3 = Comment::filter_by_id(c3.id)
        .include(Comment::fields().post().category())
        .get(&mut db)
        .await?;

    assert!(c3.post.get().is_none());

    Ok(())
}

// ===== BelongsTo<T> -> HasOne<T> (required) =====
// Todo belongs_to a User, User has_one required Config
#[driver_test(id(ID))]
pub async fn nested_belongs_to_required_then_has_one_required(test: &mut Test) -> Result<()> {
    #[derive(Debug, toasty::Model)]
    #[allow(dead_code)]
    struct User {
        #[key]
        #[auto]
        id: ID,

        name: String,

        #[has_one]
        config: toasty::HasOne<Config>,

        #[has_many]
        todos: toasty::HasMany<Todo>,
    }

    #[derive(Debug, toasty::Model)]
    #[allow(dead_code)]
    struct Config {
        #[key]
        #[auto]
        id: ID,

        theme: String,

        #[unique]
        user_id: Option<ID>,

        #[belongs_to(key = user_id, references = id)]
        user: toasty::BelongsTo<Option<User>>,
    }

    #[derive(Debug, toasty::Model)]
    #[allow(dead_code)]
    struct Todo {
        #[key]
        #[auto]
        id: ID,

        title: String,

        #[index]
        user_id: ID,

        #[belongs_to(key = user_id, references = id)]
        user: toasty::BelongsTo<User>,
    }

    let mut db = test.setup_db(models!(User, Config, Todo)).await;

    let user = User::create()
        .name("Alice")
        .config(Config::create().theme("dark"))
        .todo(Todo::create().title("Task"))
        .exec(&mut db)
        .await?;

    let todo_id = Todo::get_by_user_id(&mut db, user.id).await?.id;

    let todo = Todo::filter_by_id(todo_id)
        .include(Todo::fields().user().config())
        .get(&mut db)
        .await?;

    assert_eq!("Alice", todo.user.get().name);
    assert_eq!("dark", todo.user.get().config.get().theme);

    Ok(())
}

// ===== HasMany -> HasMany (with empty nested collections) =====
// Ensures that when some parents have children and others don't, nested preload
// correctly assigns empty collections rather than panicking.
#[driver_test(id(ID))]
pub async fn nested_has_many_then_has_many_with_empty_leaves(test: &mut Test) {
    #[derive(Debug, toasty::Model)]
    #[allow(dead_code)]
    struct User {
        #[key]
        #[auto]
        id: ID,

        name: String,

        #[has_many]
        todos: toasty::HasMany<Todo>,
    }

    #[derive(Debug, toasty::Model)]
    #[allow(dead_code)]
    struct Todo {
        #[key]
        #[auto]
        id: ID,

        title: String,

        #[index]
        user_id: ID,

        #[belongs_to(key = user_id, references = id)]
        user: toasty::BelongsTo<User>,

        #[has_many]
        steps: toasty::HasMany<Step>,
    }

    #[derive(Debug, toasty::Model)]
    #[allow(dead_code)]
    struct Step {
        #[key]
        #[auto]
        id: ID,

        description: String,

        #[index]
        todo_id: ID,

        #[belongs_to(key = todo_id, references = id)]
        todo: toasty::BelongsTo<Todo>,
    }

    let mut db = test.setup_db(models!(User, Todo, Step)).await;

    let user = User::create()
        .name("Alice")
        .todo(
            Todo::create()
                .title("With Steps")
                .step(Step::create().description("S1")),
        )
        .todo(Todo::create().title("No Steps")) // empty nested
        .exec(&mut db)
        .await
        .unwrap();

    let user = User::filter_by_id(user.id)
        .include(User::fields().todos().steps())
        .get(&mut db)
        .await
        .unwrap();

    let todos = user.todos.get();
    assert_eq!(2, todos.len());

    let mut total_steps = 0;
    for todo in todos {
        let steps = todo.steps.get();
        if todo.title == "With Steps" {
            assert_eq!(1, steps.len());
            assert_eq!("S1", steps[0].description);
        } else {
            assert_eq!(0, steps.len());
        }
        total_steps += steps.len();
    }
    assert_eq!(1, total_steps);
}

// ===== Issue #691: multiple nested includes sharing a prefix =====
// When several `.include()` calls share a common prefix (e.g. `todos()`), each
// sibling nested include must be preserved — previously the second overwrote
// the first at the shared field slot.
#[driver_test(
    id(ID),
    requires(sql),
    scenario(crate::scenarios::has_many_multi_relation)
)]
pub async fn sibling_nested_includes_on_shared_prefix(test: &mut Test) -> Result<()> {
    let mut db = setup(test).await;

    let category = toasty::create!(Category { name: "Food" })
        .exec(&mut db)
        .await?;
    let user = toasty::create!(User {
        name: "Alice",
        todos: [
            { title: "T1", category: &category },
            { title: "T2", category: &category },
        ],
    })
    .exec(&mut db)
    .await?;

    // Two sibling nested includes under the `todos()` prefix. Both must be
    // preloaded — neither should be silently clobbered by the other.
    let loaded = User::filter_by_id(user.id)
        .include(User::fields().todos().user())
        .include(User::fields().todos().category())
        .get(&mut db)
        .await?;

    let todos = loaded.todos.get();
    assert_eq!(2, todos.len());
    for todo in todos {
        assert_eq!("Alice", todo.user.get().name);
        assert_eq!("Food", todo.category.get().name);
    }

    Ok(())
}

// Mirrors the exact pattern from issue #691: a bare top-level include plus
// two sibling nested includes sharing that same top-level prefix. All three
// paths must be honored.
#[driver_test(
    id(ID),
    requires(sql),
    scenario(crate::scenarios::has_many_multi_relation)
)]
pub async fn bare_and_nested_includes_on_shared_prefix(test: &mut Test) -> Result<()> {
    let mut db = setup(test).await;

    let category = toasty::create!(Category { name: "Food" })
        .exec(&mut db)
        .await?;
    let user = toasty::create!(User {
        name: "Alice",
        todos: [{ title: "T1", category: &category }],
    })
    .exec(&mut db)
    .await?;

    let loaded = User::filter_by_id(user.id)
        .include(User::fields().todos()) // bare
        .include(User::fields().todos().user()) // sibling 1
        .include(User::fields().todos().category()) // sibling 2
        .get(&mut db)
        .await?;

    let todos = loaded.todos.get();
    assert_eq!(1, todos.len());
    assert_eq!("Alice", todos[0].user.get().name);
    assert_eq!("Food", todos[0].category.get().name);

    Ok(())
}

// DDB-compatible variant of the issue #691 repro. Two sibling nested includes
// under `items()` — each item has a distinct brand and supplier so the
// per-item belongs_to batches stay unique (DDB's nested merge uses a HashIndex
// that requires unique keys).
#[driver_test(id(ID))]
pub async fn sibling_nested_includes_on_shared_prefix_non_sql(test: &mut Test) -> Result<()> {
    #[derive(Debug, toasty::Model)]
    #[allow(dead_code)]
    struct Category {
        #[key]
        #[auto]
        id: ID,

        name: String,

        #[has_many]
        items: toasty::HasMany<Item>,
    }

    #[derive(Debug, toasty::Model)]
    #[allow(dead_code)]
    struct Brand {
        #[key]
        #[auto]
        id: ID,

        name: String,
    }

    #[derive(Debug, toasty::Model)]
    #[allow(dead_code)]
    struct Supplier {
        #[key]
        #[auto]
        id: ID,

        name: String,
    }

    #[derive(Debug, toasty::Model)]
    #[allow(dead_code)]
    struct Item {
        #[key]
        #[auto]
        id: ID,

        title: String,

        #[index]
        category_id: ID,

        #[belongs_to(key = category_id, references = id)]
        category: toasty::BelongsTo<Category>,

        #[index]
        brand_id: ID,

        #[belongs_to(key = brand_id, references = id)]
        brand: toasty::BelongsTo<Brand>,

        #[index]
        supplier_id: ID,

        #[belongs_to(key = supplier_id, references = id)]
        supplier: toasty::BelongsTo<Supplier>,
    }

    let mut db = test
        .setup_db(models!(Category, Brand, Supplier, Item))
        .await;

    let brand_a = toasty::create!(Brand { name: "BrandA" })
        .exec(&mut db)
        .await?;
    let brand_b = toasty::create!(Brand { name: "BrandB" })
        .exec(&mut db)
        .await?;
    let sup_a = toasty::create!(Supplier { name: "SupA" })
        .exec(&mut db)
        .await?;
    let sup_b = toasty::create!(Supplier { name: "SupB" })
        .exec(&mut db)
        .await?;

    let cat = toasty::create!(Category {
        name: "Electronics",
        items: [
            { title: "Phone", brand: &brand_a, supplier: &sup_a },
            { title: "Laptop", brand: &brand_b, supplier: &sup_b },
        ],
    })
    .exec(&mut db)
    .await?;

    // Two sibling nested includes under the `items()` prefix. Without the
    // fix, the second would overwrite the first.
    let loaded = Category::filter_by_id(cat.id)
        .include(Category::fields().items().brand())
        .include(Category::fields().items().supplier())
        .get(&mut db)
        .await?;

    let items = loaded.items.get();
    assert_eq!(2, items.len());
    let mut pairs: Vec<(&str, &str)> = items
        .iter()
        .map(|i| (i.brand.get().name.as_str(), i.supplier.get().name.as_str()))
        .collect();
    pairs.sort();
    assert_eq!(pairs, vec![("BrandA", "SupA"), ("BrandB", "SupB")]);

    Ok(())
}