fraiseql-core 2.10.0

Core execution engine for FraiseQL v2 - Compiled GraphQL over SQL
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
//! Multi-database integration tests for FraiseQL adapters.
#![allow(clippy::unwrap_used, clippy::print_stdout, clippy::print_stderr)] // Reason: CLI / test / example / bench code prints to stdout/stderr by design
//! These tests validate that each database adapter works correctly against
//! real database instances. Tests are gated by feature flags and require
//! Docker containers to be running.
//!
//! # Running Tests
//!
//! ```bash
//! # Start test databases
//! docker compose -f docker-compose.test.yml up -d
//!
//! # Wait for databases to be ready
//! sleep 10
//!
//! # Run MySQL integration tests
//! cargo test -p fraiseql-core --features test-mysql --test multi_database_integration
//!
//! # Run SQLite tests (no Docker needed)
//! cargo test -p fraiseql-core --features sqlite --test multi_database_integration
//!
//! # Run SQL Server integration tests
//! cargo test -p fraiseql-core --features test-sqlserver --test multi_database_integration
//! ```

// Database adapters (conditionally compiled based on features)
#[cfg(any(feature = "mysql", feature = "sqlite", feature = "sqlserver"))]
use std::sync::Arc;

#[cfg(feature = "mysql")]
#[allow(unused_imports)]
// Reason: imported by conditional feature gate; used when test-mysql is enabled
use fraiseql_core::db::mysql::MySqlAdapter;
#[cfg(feature = "sqlite")]
#[allow(unused_imports)]
// Reason: imported by conditional feature gate; used when test-sqlite is enabled
use fraiseql_core::db::sqlite::SqliteAdapter;
#[cfg(feature = "sqlserver")]
#[allow(unused_imports)]
// Reason: imported by conditional feature gate; used when test-sqlserver is enabled
use fraiseql_core::db::sqlserver::SqlServerAdapter;
#[cfg(any(feature = "mysql", feature = "sqlite", feature = "sqlserver"))]
use fraiseql_core::db::traits::DatabaseAdapter;
#[cfg(any(feature = "mysql", feature = "sqlite", feature = "sqlserver"))]
use fraiseql_core::db::types::DatabaseType;
// Note: WhereClause and WhereOperator available for future WHERE tests
#[cfg(any(feature = "mysql", feature = "sqlite", feature = "sqlserver"))]
#[allow(unused_imports)]
// Reason: WhereClause/WhereOperator reserved for future WHERE-clause tests; feature-gated
use fraiseql_core::db::where_clause::{WhereClause, WhereOperator};

// ============================================================================
// MySQL Integration Tests
// ============================================================================

#[cfg(feature = "test-mysql")]
mod mysql_tests {
    use super::*;

    fn mysql_url() -> String {
        std::env::var("MYSQL_URL")
            .expect("MYSQL_URL must be set (e.g. via `dagger call test-integration --suite=mysql`)")
    }

    #[tokio::test]
    async fn test_mysql_adapter_creation() {
        let adapter =
            MySqlAdapter::new(&mysql_url()).await.expect("Failed to create MySQL adapter");

        assert_eq!(adapter.database_type(), DatabaseType::MySQL);

        let metrics = adapter.pool_metrics();
        assert!(metrics.total_connections > 0, "Pool should have connections");
    }

    #[tokio::test]
    async fn test_mysql_health_check() {
        let adapter =
            MySqlAdapter::new(&mysql_url()).await.expect("Failed to create MySQL adapter");

        adapter.health_check().await.expect("Health check should pass");
    }

    #[tokio::test]
    async fn test_mysql_execute_raw_query() {
        let adapter =
            MySqlAdapter::new(&mysql_url()).await.expect("Failed to create MySQL adapter");

        let results = adapter
            .execute_raw_query("SELECT 1 as value")
            .await
            .expect("Query should succeed");

        assert_eq!(results.len(), 1);
        assert!(results[0].contains_key("value"));
    }

    #[tokio::test]
    async fn test_mysql_query_v_user_view() {
        let adapter =
            MySqlAdapter::new(&mysql_url()).await.expect("Failed to create MySQL adapter");

        let results = adapter
            .execute_where_query("v_user", None, Some(10), None, None)
            .await
            .expect("Query should succeed");

        assert!(!results.is_empty(), "v_user view should have test data");

        // Verify JSON structure
        let first = results[0].as_value();
        assert!(first.get("id").is_some(), "Should have id field");
        assert!(first.get("name").is_some(), "Should have name field");
        assert!(first.get("email").is_some(), "Should have email field");
    }

    #[tokio::test]
    async fn test_mysql_query_with_limit() {
        let adapter =
            MySqlAdapter::new(&mysql_url()).await.expect("Failed to create MySQL adapter");

        let results = adapter
            .execute_where_query("v_user", None, Some(2), None, None)
            .await
            .expect("Query should succeed");

        assert!(results.len() <= 2, "Should respect LIMIT clause");
    }

    #[tokio::test]
    async fn test_mysql_query_with_offset() {
        let adapter =
            MySqlAdapter::new(&mysql_url()).await.expect("Failed to create MySQL adapter");

        // Get all users first
        let all_results = adapter
            .execute_where_query("v_user", None, Some(10), None, None)
            .await
            .expect("Query should succeed");

        // Get users with offset
        let offset_results = adapter
            .execute_where_query("v_user", None, Some(10), Some(1), None)
            .await
            .expect("Query should succeed");

        if all_results.len() > 1 {
            assert_eq!(offset_results.len(), all_results.len() - 1, "Offset should skip first row");
        }
    }

    #[tokio::test]
    async fn test_mysql_query_v_post_with_nested_author() {
        let adapter =
            MySqlAdapter::new(&mysql_url()).await.expect("Failed to create MySQL adapter");

        let results = adapter
            .execute_where_query("v_post", None, Some(5), None, None)
            .await
            .expect("Query should succeed");

        assert!(!results.is_empty(), "v_post view should have test data");

        // Verify nested author object
        let first = results[0].as_value();
        assert!(first.get("id").is_some(), "Should have id field");
        assert!(first.get("title").is_some(), "Should have title field");
        assert!(first.get("author").is_some(), "Should have nested author object");

        let author = first.get("author").unwrap();
        assert!(author.get("id").is_some(), "Author should have id");
        assert!(author.get("name").is_some(), "Author should have name");
    }

    #[tokio::test]
    async fn test_mysql_pool_metrics() {
        let adapter =
            MySqlAdapter::new(&mysql_url()).await.expect("Failed to create MySQL adapter");

        let metrics = adapter.pool_metrics();

        assert!(metrics.total_connections > 0, "Should have total connections");
        assert!(
            metrics.idle_connections <= metrics.total_connections,
            "Idle should not exceed total"
        );
    }

    #[tokio::test]
    async fn test_mysql_concurrent_queries() {
        let adapter = Arc::new(
            MySqlAdapter::new(&mysql_url()).await.expect("Failed to create MySQL adapter"),
        );

        let mut handles = Vec::new();

        for _ in 0..10 {
            let adapter_clone = Arc::clone(&adapter);
            let handle = tokio::spawn(async move {
                adapter_clone.execute_where_query("v_user", None, Some(5), None, None).await
            });
            handles.push(handle);
        }

        let results: Vec<_> = futures::future::join_all(handles).await.into_iter().collect();

        for result in results {
            assert!(result.is_ok(), "Task should complete");
            assert!(result.unwrap().is_ok(), "Query should succeed");
        }
    }
}

// ============================================================================
// SQLite Integration Tests
// ============================================================================

#[cfg(feature = "sqlite")]
mod sqlite_tests {
    use super::*;

    #[tokio::test]
    async fn test_sqlite_in_memory_adapter_creation() {
        let adapter = SqliteAdapter::in_memory().await.expect("Failed to create SQLite adapter");

        assert_eq!(adapter.database_type(), DatabaseType::SQLite);

        let metrics = adapter.pool_metrics();
        assert!(metrics.total_connections > 0, "Pool should have connections");
    }

    #[tokio::test]
    async fn test_sqlite_health_check() {
        let adapter = SqliteAdapter::in_memory().await.expect("Failed to create SQLite adapter");

        adapter.health_check().await.expect("Health check should pass");
    }

    #[tokio::test]
    async fn test_sqlite_execute_raw_query() {
        let adapter = SqliteAdapter::in_memory().await.expect("Failed to create SQLite adapter");

        let results = adapter
            .execute_raw_query("SELECT 1 as value")
            .await
            .expect("Query should succeed");

        assert_eq!(results.len(), 1);
        assert!(results[0].contains_key("value"));
    }

    #[tokio::test]
    async fn test_sqlite_insert_mutation_via_executor() {
        use fraiseql_core::{
            runtime::Executor,
            schema::{
                ArgumentDefinition, CompiledSchema, FieldType, MutationDefinition,
                MutationOperation,
            },
        };

        let adapter =
            Arc::new(SqliteAdapter::in_memory().await.expect("Failed to create SQLite adapter"));
        adapter
            .execute_raw_query(
                "CREATE TABLE users (pk_user INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, \
                 email TEXT)",
            )
            .await
            .expect("create table");

        let scalar = |name: &str| ArgumentDefinition {
            name:          name.to_string(),
            arg_type:      FieldType::String,
            nullable:      false,
            default_value: None,
            description:   None,
            deprecation:   None,
        };
        let mut schema = CompiledSchema::new();
        schema.mutations.push(MutationDefinition {
            arguments: vec![scalar("name"), scalar("email")],
            operation: MutationOperation::Insert {
                table: "users".to_string(),
            },
            ..MutationDefinition::new("createUser", "User")
        });

        let executor = Executor::new(schema, Arc::clone(&adapter));
        let result = executor
            .execute(
                "mutation { createUser(name: \"Alice\", email: \"alice@example.com\") \
                 { name email } }",
                None,
            )
            .await;
        assert!(result.is_ok(), "SQLite insert mutation should succeed: {result:?}");

        // The row must have actually landed in the table.
        let rows = adapter
            .execute_raw_query("SELECT name FROM users WHERE email = 'alice@example.com'")
            .await
            .expect("select");
        assert_eq!(rows.len(), 1, "exactly one row inserted");
        assert_eq!(rows[0].get("name").and_then(serde_json::Value::as_str), Some("Alice"));
    }

    #[tokio::test]
    async fn test_sqlite_delete_mutation_via_executor() {
        use fraiseql_core::{
            runtime::Executor,
            schema::{
                ArgumentDefinition, CompiledSchema, FieldType, MutationDefinition,
                MutationOperation,
            },
        };

        let adapter =
            Arc::new(SqliteAdapter::in_memory().await.expect("Failed to create SQLite adapter"));
        adapter
            .execute_raw_query(
                "CREATE TABLE users (pk_user INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, \
                 email TEXT)",
            )
            .await
            .expect("create table");
        adapter
            .execute_raw_query("INSERT INTO users (name, email) VALUES ('Bob', 'bob@example.com')")
            .await
            .expect("seed");

        let mut schema = CompiledSchema::new();
        schema.mutations.push(MutationDefinition {
            arguments: vec![ArgumentDefinition {
                name:          "pk_user".to_string(),
                arg_type:      FieldType::Int,
                nullable:      false,
                default_value: None,
                description:   None,
                deprecation:   None,
            }],
            operation: MutationOperation::Delete {
                table: "users".to_string(),
            },
            ..MutationDefinition::new("deleteUser", "User")
        });

        let executor = Executor::new(schema, Arc::clone(&adapter));
        let result = executor.execute("mutation { deleteUser(pk_user: 1) { name } }", None).await;
        assert!(result.is_ok(), "SQLite delete mutation should succeed: {result:?}");

        let rows = adapter.execute_raw_query("SELECT name FROM users").await.expect("select");
        assert!(rows.is_empty(), "row should be deleted");
    }

    #[tokio::test]
    async fn test_sqlite_create_and_query_view() {
        let adapter = SqliteAdapter::in_memory().await.expect("Failed to create SQLite adapter");

        // Create test table
        adapter
            .execute_raw_query("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, email TEXT)")
            .await
            .expect("Create table should succeed");

        // Insert test data
        adapter
            .execute_raw_query(
                "INSERT INTO users (name, email) VALUES ('Alice', 'alice@example.com')",
            )
            .await
            .expect("Insert should succeed");

        adapter
            .execute_raw_query("INSERT INTO users (name, email) VALUES ('Bob', 'bob@example.com')")
            .await
            .expect("Insert should succeed");

        // Create view returning JSON
        adapter
            .execute_raw_query(
                r"CREATE VIEW v_user AS
                   SELECT id, json_object('id', id, 'name', name, 'email', email) AS data
                   FROM users",
            )
            .await
            .expect("Create view should succeed");

        // Query the view
        let results = adapter
            .execute_where_query("v_user", None, Some(10), None, None)
            .await
            .expect("Query should succeed");

        assert_eq!(results.len(), 2, "Should have 2 users");

        let first = results[0].as_value();
        assert!(first.get("id").is_some(), "Should have id field");
        assert!(first.get("name").is_some(), "Should have name field");
        assert!(first.get("email").is_some(), "Should have email field");
    }

    #[tokio::test]
    async fn test_sqlite_query_with_limit() {
        let adapter = SqliteAdapter::in_memory().await.expect("Failed to create SQLite adapter");

        // Setup test data
        adapter
            .execute_raw_query("CREATE TABLE items (id INTEGER PRIMARY KEY, data TEXT)")
            .await
            .expect("Create table should succeed");

        for i in 1..=5 {
            adapter
                .execute_raw_query(&format!(
                    "INSERT INTO items (data) VALUES ('{}')",
                    serde_json::json!({"value": i})
                ))
                .await
                .expect("Insert should succeed");
        }

        adapter
            .execute_raw_query("CREATE VIEW v_items AS SELECT id, data FROM items")
            .await
            .expect("Create view should succeed");

        // Query with limit
        let results = adapter
            .execute_where_query("v_items", None, Some(2), None, None)
            .await
            .expect("Query should succeed");

        assert_eq!(results.len(), 2, "Should respect LIMIT clause");
    }

    #[tokio::test]
    async fn test_sqlite_query_with_offset() {
        let adapter = SqliteAdapter::in_memory().await.expect("Failed to create SQLite adapter");

        // Setup test data
        adapter
            .execute_raw_query("CREATE TABLE items (id INTEGER PRIMARY KEY, data TEXT)")
            .await
            .expect("Create table should succeed");

        for i in 1..=5 {
            adapter
                .execute_raw_query(&format!(
                    "INSERT INTO items (data) VALUES ('{}')",
                    serde_json::json!({"value": i})
                ))
                .await
                .expect("Insert should succeed");
        }

        adapter
            .execute_raw_query("CREATE VIEW v_items AS SELECT id, data FROM items")
            .await
            .expect("Create view should succeed");

        // Query with offset
        let results = adapter
            .execute_where_query("v_items", None, Some(10), Some(2), None)
            .await
            .expect("Query should succeed");

        assert_eq!(results.len(), 3, "Should skip first 2 rows");
    }

    #[tokio::test]
    async fn test_sqlite_pool_metrics() {
        let adapter = SqliteAdapter::in_memory().await.expect("Failed to create SQLite adapter");

        let metrics = adapter.pool_metrics();

        assert!(metrics.total_connections > 0, "Should have total connections");
        assert!(
            metrics.idle_connections <= metrics.total_connections,
            "Idle should not exceed total"
        );
    }

    #[tokio::test]
    async fn test_sqlite_nested_json_view() {
        let adapter = SqliteAdapter::in_memory().await.expect("Failed to create SQLite adapter");

        // Create tables
        adapter
            .execute_raw_query("CREATE TABLE authors (id INTEGER PRIMARY KEY, name TEXT)")
            .await
            .expect("Create authors table should succeed");

        adapter
            .execute_raw_query(
                "CREATE TABLE posts (id INTEGER PRIMARY KEY, title TEXT, author_id INTEGER REFERENCES authors(id))",
            )
            .await
            .expect("Create posts table should succeed");

        // Insert test data
        adapter
            .execute_raw_query("INSERT INTO authors (id, name) VALUES (1, 'Alice')")
            .await
            .expect("Insert author should succeed");

        adapter
            .execute_raw_query("INSERT INTO posts (title, author_id) VALUES ('Hello World', 1)")
            .await
            .expect("Insert post should succeed");

        // Create view with nested JSON
        adapter
            .execute_raw_query(
                r"CREATE VIEW v_post AS
                   SELECT p.id,
                          json_object(
                              'id', p.id,
                              'title', p.title,
                              'author', json_object('id', a.id, 'name', a.name)
                          ) AS data
                   FROM posts p
                   JOIN authors a ON p.author_id = a.id",
            )
            .await
            .expect("Create view should succeed");

        // Query the view
        let results = adapter
            .execute_where_query("v_post", None, Some(10), None, None)
            .await
            .expect("Query should succeed");

        assert_eq!(results.len(), 1, "Should have 1 post");

        let post = results[0].as_value();
        assert!(post.get("id").is_some(), "Should have id field");
        assert!(post.get("title").is_some(), "Should have title field");
        assert!(post.get("author").is_some(), "Should have nested author");

        let author = post.get("author").unwrap();
        assert!(author.get("id").is_some(), "Author should have id");
        assert!(author.get("name").is_some(), "Author should have name");
    }

    #[tokio::test]
    async fn test_sqlite_concurrent_queries() {
        let adapter =
            Arc::new(SqliteAdapter::in_memory().await.expect("Failed to create SQLite adapter"));

        // Setup test data
        adapter
            .execute_raw_query("CREATE TABLE test (id INTEGER PRIMARY KEY, data TEXT)")
            .await
            .expect("Create table should succeed");

        adapter
            .execute_raw_query(
                "CREATE VIEW v_test AS SELECT id, json_object('id', id) AS data FROM test",
            )
            .await
            .expect("Create view should succeed");

        for i in 1..=10 {
            adapter
                .execute_raw_query(&format!("INSERT INTO test (data) VALUES ('data{i}')"))
                .await
                .expect("Insert should succeed");
        }

        let mut handles = Vec::new();

        for _ in 0..10 {
            let adapter_clone = Arc::clone(&adapter);
            let handle = tokio::spawn(async move {
                adapter_clone.execute_where_query("v_test", None, Some(5), None, None).await
            });
            handles.push(handle);
        }

        let results: Vec<_> = futures::future::join_all(handles).await.into_iter().collect();

        for result in results {
            assert!(result.is_ok(), "Task should complete");
            assert!(result.unwrap().is_ok(), "Query should succeed");
        }
    }
}

// ============================================================================
// SQL Server Integration Tests
// ============================================================================

/// Build a SQL Server connection string for `database` from the harness-provided
/// server. `SQLSERVER_URL` holds `server=…;user=…;password=…;TrustServerCertificate=true`
/// (no database); each test appends the database it needs. Returns `None` only when
/// `SQLSERVER_URL` is unset.
#[cfg(feature = "test-sqlserver")]
async fn sqlserver_conn(database: &str) -> Option<String> {
    let svc = fraiseql_test_support::sqlserver().await?;
    Some(format!("{};database={database}", svc.url().trim_end_matches(';')))
}

#[cfg(feature = "test-sqlserver")]
mod sqlserver_tests {
    use super::*;

    /// Adapter against the `master` database (server-level tests).
    async fn master_adapter() -> SqlServerAdapter {
        let url = sqlserver_conn("master").await.expect(
            "SQLSERVER_URL must be set (e.g. via `dagger call test-integration --suite=sqlserver`)",
        );
        SqlServerAdapter::new(&url).await.expect("Failed to create SQL Server adapter")
    }

    #[tokio::test]
    async fn test_sqlserver_adapter_creation() {
        let adapter = master_adapter().await;

        assert_eq!(adapter.database_type(), DatabaseType::SQLServer);

        let metrics = adapter.pool_metrics();
        assert!(metrics.total_connections > 0, "Pool should have connections");
    }

    #[tokio::test]
    async fn test_sqlserver_health_check() {
        let adapter = master_adapter().await;

        adapter.health_check().await.expect("Health check should pass");
    }

    #[tokio::test]
    async fn test_sqlserver_execute_raw_query() {
        let adapter = master_adapter().await;

        let results = adapter
            .execute_raw_query("SELECT 1 as value")
            .await
            .expect("Query should succeed");

        assert_eq!(results.len(), 1);
        assert!(results[0].contains_key("value"));
    }

    #[tokio::test]
    async fn test_sqlserver_query_v_user_view() {
        let Some(url) = sqlserver_conn("fraiseql_test").await else {
            eprintln!("Skipping test_sqlserver_query_v_user_view: SQLSERVER_URL not set");
            return;
        };
        let adapter = SqlServerAdapter::new(&url)
            .await
            .expect("Failed to connect to SQL Server (fraiseql_test)");

        let results = adapter
            .execute_where_query("v_user", None, Some(10), None, None)
            .await
            .expect("Query should succeed");

        assert!(!results.is_empty(), "v_user view should have test data");

        // Verify JSON structure
        let first = results[0].as_value();
        assert!(first.get("id").is_some(), "Should have id field");
        assert!(first.get("name").is_some(), "Should have name field");
        assert!(first.get("email").is_some(), "Should have email field");
    }

    #[tokio::test]
    async fn test_sqlserver_pool_metrics() {
        let adapter = master_adapter().await;

        let metrics = adapter.pool_metrics();

        assert!(metrics.total_connections > 0, "Should have total connections");
        assert!(
            metrics.idle_connections <= metrics.total_connections,
            "Idle should not exceed total"
        );
    }

    #[tokio::test]
    async fn test_sqlserver_concurrent_queries() {
        let adapter = Arc::new(master_adapter().await);

        let mut handles = Vec::new();

        for _ in 0..5 {
            let adapter_clone = Arc::clone(&adapter);
            let handle =
                tokio::spawn(
                    async move { adapter_clone.execute_raw_query("SELECT 1 as value").await },
                );
            handles.push(handle);
        }

        let results: Vec<_> = futures::future::join_all(handles).await.into_iter().collect();

        for result in results {
            assert!(result.is_ok(), "Task should complete");
            assert!(result.unwrap().is_ok(), "Query should succeed");
        }
    }
}

// ============================================================================
// SQL Server Relay Pagination Integration Tests
// ============================================================================

#[cfg(feature = "test-sqlserver")]
mod sqlserver_relay_tests {
    use fraiseql_core::{
        db::{
            sqlserver::SqlServerAdapter,
            traits::{CursorValue, RelayDatabaseAdapter},
            where_clause::{WhereClause, WhereOperator},
        },
        error::FraiseQLError,
    };

    // UUID ids for v_relay_item rows (in ascending SQL Server UNIQUEIDENTIFIER order).
    // These UUIDs are of the form 00000000-0000-0000-0000-00000000000N where N is 1–a.
    // SQL Server compares bytes 10–15 first; for these UUIDs those bytes are
    // 000000000001 … 00000000000a, giving standard ascending order.
    const UUID_3: &str = "00000000-0000-0000-0000-000000000003";
    const UUID_5: &str = "00000000-0000-0000-0000-000000000005";
    const UUID_8: &str = "00000000-0000-0000-0000-000000000008";
    const UUID_10: &str = "00000000-0000-0000-0000-00000000000a";

    async fn adapter() -> SqlServerAdapter {
        let url = super::sqlserver_conn("fraiseql_test").await.expect(
            "SQLSERVER_URL must be set (e.g. via `dagger call test-integration --suite=sqlserver`)",
        );
        SqlServerAdapter::new(&url).await.expect("Failed to connect to SQL Server")
    }

    fn extract_label(row: &fraiseql_core::db::types::JsonbValue) -> String {
        row.as_value()
            .get("label")
            .and_then(|v| v.as_str())
            .expect("row must have 'label' field")
            .to_string()
    }

    fn extract_score(row: &fraiseql_core::db::types::JsonbValue) -> i64 {
        row.as_value()
            .get("score")
            .and_then(|v| v.as_i64())
            .expect("row must have 'score' field")
    }

    #[tokio::test]
    async fn test_sqlserver_relay_forward_first_page() {
        let a = adapter().await;
        let result = a
            .execute_relay_page("v_relay_item", "id", None, None, 3, true, None, None, false)
            .await
            .expect("forward first page");
        assert_eq!(result.rows().len(), 3);
        let labels: Vec<String> = result.rows().iter().map(extract_label).collect();
        assert_eq!(labels, vec!["item-1", "item-2", "item-3"]);
        assert_eq!(result.total_count(), None);
    }

    #[tokio::test]
    async fn test_sqlserver_relay_forward_with_after_cursor() {
        let a = adapter().await;
        let result = a
            .execute_relay_page(
                "v_relay_item",
                "id",
                Some(CursorValue::Uuid(UUID_3.to_string())),
                None,
                3,
                true,
                None,
                None,
                false,
            )
            .await
            .expect("forward with after cursor");
        let labels: Vec<String> = result.rows().iter().map(extract_label).collect();
        assert_eq!(labels, vec!["item-4", "item-5", "item-6"]);
    }

    #[tokio::test]
    async fn test_sqlserver_relay_forward_exhausted() {
        let a = adapter().await;
        let result = a
            .execute_relay_page(
                "v_relay_item",
                "id",
                Some(CursorValue::Uuid(UUID_8.to_string())),
                None,
                10,
                true,
                None,
                None,
                false,
            )
            .await
            .expect("forward exhausted");
        let labels: Vec<String> = result.rows().iter().map(extract_label).collect();
        assert_eq!(labels, vec!["item-9", "item-10"]);
    }

    #[tokio::test]
    async fn test_sqlserver_relay_backward_with_before_cursor() {
        let a = adapter().await;
        let result = a
            .execute_relay_page(
                "v_relay_item",
                "id",
                None,
                Some(CursorValue::Uuid(UUID_5.to_string())),
                3,
                false,
                None,
                None,
                false,
            )
            .await
            .expect("backward with before cursor");
        // Rows before UUID-5 (exclusive), last 3, re-sorted ASC → items 2,3,4
        let labels: Vec<String> = result.rows().iter().map(extract_label).collect();
        assert_eq!(labels, vec!["item-2", "item-3", "item-4"]);
    }

    #[tokio::test]
    async fn test_sqlserver_relay_backward_first_page_no_cursor() {
        let a = adapter().await;
        let result = a
            .execute_relay_page("v_relay_item", "id", None, None, 3, false, None, None, false)
            .await
            .expect("backward first page no cursor");
        // Last 3 rows in ascending cursor order → items 8,9,10
        let labels: Vec<String> = result.rows().iter().map(extract_label).collect();
        assert_eq!(labels, vec!["item-8", "item-9", "item-10"]);
    }

    #[tokio::test]
    async fn test_sqlserver_relay_total_count_is_10() {
        let a = adapter().await;
        let result = a
            .execute_relay_page("v_relay_item", "id", None, None, 3, true, None, None, true)
            .await
            .expect("total count");
        assert_eq!(result.total_count(), Some(10));
    }

    #[tokio::test]
    async fn test_sqlserver_relay_total_count_ignores_cursor() {
        let a = adapter().await;
        let result = a
            .execute_relay_page(
                "v_relay_item",
                "id",
                Some(CursorValue::Uuid(UUID_5.to_string())),
                None,
                3,
                true,
                None,
                None,
                true,
            )
            .await
            .expect("total count ignores cursor");
        // totalCount counts all matching rows, not just those after the cursor.
        assert_eq!(result.total_count(), Some(10));
    }

    #[tokio::test]
    async fn test_sqlserver_relay_total_count_absent_when_not_requested() {
        let a = adapter().await;
        let result = a
            .execute_relay_page("v_relay_item", "id", None, None, 3, true, None, None, false)
            .await
            .expect("no total count");
        assert_eq!(result.total_count(), None);
    }

    #[tokio::test]
    async fn test_sqlserver_relay_forward_with_where_clause() {
        let a = adapter().await;
        let clause = WhereClause::Field {
            path:     vec!["score".to_string()],
            operator: WhereOperator::Gte,
            value:    serde_json::json!(50),
        };
        let result = a
            .execute_relay_page(
                "v_relay_item",
                "id",
                None,
                None,
                10,
                true,
                Some(&clause),
                None,
                false,
            )
            .await
            .expect("forward with where clause");
        // Scores ≥ 50: items 1(50), 3(70), 5(90), 7(60), 9(80) → 5 rows
        assert_eq!(result.rows().len(), 5);
        for row in result.rows() {
            let score = extract_score(row);
            assert!(score >= 50, "All rows must have score >= 50, got {score}");
        }
    }

    #[tokio::test]
    async fn test_sqlserver_relay_backward_custom_order_by_score_asc() {
        use fraiseql_core::compiler::aggregation::{OrderByClause, OrderDirection};

        let a = adapter().await;
        let order_by = vec![OrderByClause::new("score".to_string(), OrderDirection::Asc)];

        // before = UUID-5 (score=90), limit=3, forward=false, order_by score ASC.
        // Rows with UUID < UUID-5: item-1(50), item-2(30), item-3(70), item-4(10).
        // Sorted by score ASC: [10, 30, 50, 70]. Last 3 = [30, 50, 70].
        // After backward flip (inner DESC, outer ASC): returned in score ASC order.
        let result = a
            .execute_relay_page(
                "v_relay_item",
                "id",
                None,
                Some(CursorValue::Uuid(UUID_5.to_string())),
                3,
                false,
                None,
                Some(&order_by),
                false,
            )
            .await
            .expect("backward custom order_by score asc");

        assert_eq!(result.rows().len(), 3, "Should return exactly 3 rows");

        // Verify scores are in ascending order (proves backward direction flip is correct).
        let scores: Vec<i64> = result.rows().iter().map(extract_score).collect();
        assert_eq!(scores, vec![30, 50, 70], "Rows must be in score ASC order");
    }

    #[tokio::test]
    async fn test_sqlserver_relay_forward_empty_result() {
        let a = adapter().await;
        let result = a
            .execute_relay_page(
                "v_relay_item",
                "id",
                Some(CursorValue::Uuid(UUID_10.to_string())),
                None,
                10,
                true,
                None,
                None,
                false,
            )
            .await
            .expect("forward empty result");
        assert!(result.rows().is_empty(), "Should return 0 rows after the last UUID");
    }

    #[tokio::test]
    async fn test_sqlserver_relay_missing_view_returns_error() {
        // Validates count query robustness: a missing view must surface as
        // FraiseQLError::Database, NOT as Ok(total_count: 0).
        let a = adapter().await;
        let err = a
            .execute_relay_page("v_nonexistent", "id", None, None, 3, true, None, None, true)
            .await
            .expect_err("missing view must return Err");
        assert!(
            matches!(err, FraiseQLError::Database { .. }),
            "Expected Database error, got {err:?}"
        );
    }

    #[tokio::test]
    async fn test_sqlserver_relay_uuid_cursor_invalid_format_returns_validation_error() {
        // Validates UUID validation: malformed UUID must return Validation error before
        // reaching SQL Server, rather than an opaque type-conversion database error.
        let a = adapter().await;
        let err = a
            .execute_relay_page(
                "v_relay_item",
                "id",
                Some(CursorValue::Uuid("not-a-uuid".to_string())),
                None,
                3,
                true,
                None,
                None,
                false,
            )
            .await
            .expect_err("malformed UUID cursor must return Err");
        assert!(
            matches!(err, FraiseQLError::Validation { .. }),
            "Expected Validation error, got {err:?}"
        );
    }
}

// ============================================================================
// MySQL Relay Pagination Tests
// ============================================================================

#[cfg(feature = "test-mysql")]
mod mysql_relay_tests {
    use fraiseql_core::db::{
        mysql::MySqlAdapter,
        traits::{CursorValue, RelayDatabaseAdapter},
        where_clause::{WhereClause, WhereOperator},
    };

    fn mysql_url() -> String {
        std::env::var("MYSQL_URL")
            .expect("MYSQL_URL must be set (e.g. via `dagger call test-integration --suite=mysql`)")
    }

    async fn adapter() -> MySqlAdapter {
        MySqlAdapter::new(&mysql_url()).await.expect("Failed to connect to MySQL")
    }

    fn extract_label(row: &fraiseql_core::db::types::JsonbValue) -> String {
        row.as_value()
            .get("label")
            .and_then(|v| v.as_str())
            .expect("row must have 'label' field")
            .to_string()
    }

    /// Forward pagination returns the first page.
    #[tokio::test]
    async fn test_mysql_relay_forward_first_page() {
        let a = adapter().await;
        let result = a
            .execute_relay_page("v_relay_item", "id", None, None, 3, true, None, None, false)
            .await
            .expect("forward first page");
        assert_eq!(result.rows().len(), 3);
        // First page has no previous entries (cursor starts at beginning)
        assert!(!result.rows().is_empty(), "first page must return rows");
    }

    /// Forward pagination with an `after` cursor skips earlier rows.
    #[tokio::test]
    async fn test_mysql_relay_forward_with_after_cursor() {
        let a = adapter().await;
        // Fetch first page to get a cursor
        let first = a
            .execute_relay_page("v_relay_item", "id", None, None, 3, true, None, None, false)
            .await
            .expect("first page");
        assert_eq!(first.rows().len(), 3);

        // Extract cursor from the last row's id field (MySQL relay_item uses CHAR(36) UUIDs)
        let last_id = first
            .rows
            .last()
            .and_then(|row| row.as_value().get("id"))
            .and_then(|v| v.as_str())
            .expect("last row must have string id for cursor");
        let cursor_val = CursorValue::Uuid(last_id.to_string());
        let second = a
            .execute_relay_page(
                "v_relay_item",
                "id",
                Some(cursor_val),
                None,
                3,
                true,
                None,
                None,
                false,
            )
            .await
            .expect("second page");
        assert!(!second.rows().is_empty(), "second page must have rows after cursor");
    }

    /// Requesting more rows than exist returns no further pages.
    #[tokio::test]
    async fn test_mysql_relay_forward_exhausted() {
        let a = adapter().await;
        let result = a
            .execute_relay_page("v_relay_item", "id", None, None, 100, true, None, None, false)
            .await
            .expect("over-limit page");
        assert_eq!(result.rows().len(), 10, "all 10 rows returned");
        // Requesting more than total rows means no further pages
        assert!(result.rows().len() <= 100, "rows must not exceed requested limit");
    }

    /// Backward pagination returns the last page.
    #[tokio::test]
    async fn test_mysql_relay_backward_last_page() {
        let a = adapter().await;
        let result = a
            .execute_relay_page("v_relay_item", "id", None, None, 3, false, None, None, false)
            .await
            .expect("backward last page");
        assert_eq!(result.rows().len(), 3);
        // Backward page of 3 from 10 rows returns exactly 3 rows
        assert!(result.rows().len() <= 3, "must not exceed requested limit");
    }

    /// Total count is returned when requested.
    #[tokio::test]
    async fn test_mysql_relay_total_count() {
        let a = adapter().await;
        let result = a
            .execute_relay_page("v_relay_item", "id", None, None, 3, true, None, None, true)
            .await
            .expect("total count query");
        assert_eq!(result.total_count(), Some(10), "must count all 10 rows");
    }

    /// WHERE filter reduces the result set.
    #[tokio::test]
    async fn test_mysql_relay_forward_with_where_clause() {
        use serde_json::json;
        let a = adapter().await;
        // Filter: only items whose label is "item-1"
        let where_clause = WhereClause::Field {
            path:     vec!["label".to_string()],
            operator: WhereOperator::Eq,
            value:    json!("item-1"),
        };
        let result = a
            .execute_relay_page(
                "v_relay_item",
                "id",
                None,
                None,
                10,
                true,
                Some(&where_clause),
                None,
                true,
            )
            .await
            .expect("filtered relay page");
        assert_eq!(result.total_count(), Some(1), "only item-1 matches");
        assert_eq!(result.rows().len(), 1);
        assert_eq!(extract_label(&result.rows()[0]), "item-1");
    }

    /// Querying a non-existent view returns a database error.
    #[tokio::test]
    async fn test_mysql_relay_missing_view_returns_error() {
        use fraiseql_core::error::FraiseQLError;
        let a = adapter().await;
        let err = a
            .execute_relay_page("v_nonexistent_view", "id", None, None, 3, true, None, None, false)
            .await
            .expect_err("missing view must return Err");
        assert!(
            matches!(err, FraiseQLError::Database { .. }),
            "Expected Database error, got {err:?}"
        );
    }
}

// ============================================================================
// MySQL Advanced Query Tests (window functions, CTEs, aggregations)
// ============================================================================

#[cfg(feature = "test-mysql")]
mod mysql_advanced_tests {
    use fraiseql_core::db::mysql::MySqlAdapter;
    use fraiseql_db::DatabaseAdapter;

    fn mysql_url() -> String {
        std::env::var("MYSQL_URL")
            .expect("MYSQL_URL must be set (e.g. via `dagger call test-integration --suite=mysql`)")
    }

    async fn adapter() -> MySqlAdapter {
        MySqlAdapter::new(&mysql_url()).await.expect("Failed to connect to MySQL")
    }

    /// MySQL 8+ `RANK()` window function partitioned by category.
    #[tokio::test]
    async fn test_mysql_window_function_rank() {
        let a = adapter().await;
        let results = a
            .execute_raw_query(
                "SELECT category, score, label,
                        RANK() OVER (PARTITION BY category ORDER BY score DESC) AS rnk
                 FROM v_score
                 ORDER BY category, rnk",
            )
            .await
            .expect("RANK() window function must succeed on MySQL 8+");
        // 8 rows in tb_score
        assert_eq!(results.len(), 8, "all 8 scored rows returned");
        let first = &results[0];
        assert!(first.contains_key("rnk"), "must include rank column");
        // Category A: alpha(95), beta(80), gamma(80) — alpha has rank 1
        let cat = first.get("category").and_then(|v| v.as_str()).unwrap_or("");
        assert_eq!(cat, "A");
        let rnk = first.get("rnk").and_then(|v| v.as_u64()).unwrap_or(0);
        assert_eq!(rnk, 1, "highest score in category A must have rank 1");
    }

    /// MySQL 8+ `ROW_NUMBER()` window function.
    #[tokio::test]
    async fn test_mysql_window_function_row_number() {
        let a = adapter().await;
        let results = a
            .execute_raw_query(
                "SELECT id, label,
                        ROW_NUMBER() OVER (ORDER BY score DESC) AS row_num
                 FROM v_score",
            )
            .await
            .expect("ROW_NUMBER() must succeed on MySQL 8+");
        assert_eq!(results.len(), 8);
        // Each row has a unique row_num
        let row_nums_count = results
            .iter()
            .filter(|r| r.get("row_num").and_then(|v| v.as_u64()).is_some())
            .count();
        assert_eq!(row_nums_count, 8, "all rows must have row_num");
    }

    /// CTE (WITH clause) is supported on MySQL 8+.
    #[tokio::test]
    async fn test_mysql_cte_basic() {
        let a = adapter().await;
        let results = a
            .execute_raw_query(
                "WITH top_scores AS (
                     SELECT id, label, score FROM v_score WHERE score >= 80
                 )
                 SELECT * FROM top_scores ORDER BY score DESC",
            )
            .await
            .expect("CTE must be supported on MySQL 8+");
        // Scores >= 80: alpha(95), beta(80), gamma(80), zeta(90) → 4 rows
        assert_eq!(results.len(), 4, "four rows have score >= 80");
    }

    /// Recursive CTE returns expected depth.
    #[tokio::test]
    async fn test_mysql_cte_recursive() {
        let a = adapter().await;
        let results = a
            .execute_raw_query(
                "WITH RECURSIVE counter(n) AS (
                     SELECT 1
                     UNION ALL
                     SELECT n + 1 FROM counter WHERE n < 5
                 )
                 SELECT n FROM counter",
            )
            .await
            .expect("recursive CTE must succeed");
        assert_eq!(results.len(), 5, "recursive CTE must return 5 rows");
    }

    /// COUNT, SUM, AVG, MIN, MAX aggregations.
    #[tokio::test]
    async fn test_mysql_aggregations() {
        let a = adapter().await;
        let results = a
            .execute_raw_query(
                "SELECT
                     COUNT(*) AS cnt,
                     SUM(score) AS total,
                     AVG(score) AS avg_score,
                     MIN(score) AS min_score,
                     MAX(score) AS max_score
                 FROM v_score",
            )
            .await
            .expect("aggregations must succeed");
        assert_eq!(results.len(), 1, "aggregation returns one row");
        let row = &results[0];
        let cnt = row.get("cnt").and_then(|v| v.as_u64()).unwrap_or(0);
        assert_eq!(cnt, 8, "8 score rows");
        let max = row.get("max_score").and_then(|v| v.as_u64()).unwrap_or(0);
        assert_eq!(max, 95, "max score is 95 (alpha)");
        let min = row.get("min_score").and_then(|v| v.as_u64()).unwrap_or(999);
        assert_eq!(min, 50, "min score is 50 (eta)");
    }

    /// GROUP BY aggregation per category.
    #[tokio::test]
    async fn test_mysql_group_by_aggregation() {
        let a = adapter().await;
        let results = a
            .execute_raw_query(
                "SELECT category, COUNT(*) AS cnt, MAX(score) AS max_score
                 FROM v_score
                 GROUP BY category
                 ORDER BY category",
            )
            .await
            .expect("GROUP BY must succeed");
        // 3 categories: A(3 rows), B(3 rows), C(2 rows)
        assert_eq!(results.len(), 3, "3 distinct categories");
        let first = &results[0];
        let cat = first.get("category").and_then(|v| v.as_str()).unwrap_or("");
        assert_eq!(cat, "A");
        let cnt = first.get("cnt").and_then(|v| v.as_u64()).unwrap_or(0);
        assert_eq!(cnt, 3, "category A has 3 rows");
    }
}

// ============================================================================
// MySQL Mutation Tests
// ============================================================================

#[cfg(feature = "test-mysql")]
mod mysql_mutation_tests {
    use fraiseql_core::db::mysql::MySqlAdapter;
    use fraiseql_db::DatabaseAdapter;

    fn mysql_url() -> String {
        std::env::var("MYSQL_URL")
            .expect("MYSQL_URL must be set (e.g. via `dagger call test-integration --suite=mysql`)")
    }

    /// MySQL mutation via stored procedure: insert returns the new row.
    #[tokio::test]
    async fn test_mysql_mutation_insert_via_procedure() {
        let a = MySqlAdapter::new(&mysql_url()).await.expect("connect");
        let result = a
            .execute_function_call("fn_create_tag", &[serde_json::json!("test-tag-plan03")])
            .await
            .expect("stored procedure call must succeed");
        // Procedure returns one row with id and name
        assert!(!result.is_empty(), "INSERT must return the new row");
        let row = &result[0];
        assert!(row.contains_key("id"), "returned row must have id");
        let name = row.get("name").and_then(|v| v.as_str()).unwrap_or("");
        assert_eq!(name, "test-tag-plan03");
    }

    /// Calling a non-existent procedure returns a database error.
    #[tokio::test]
    async fn test_mysql_mutation_nonexistent_procedure_returns_error() {
        use fraiseql_core::error::FraiseQLError;
        let a = MySqlAdapter::new(&mysql_url()).await.expect("connect");
        let err = a
            .execute_function_call("fn_does_not_exist", &[])
            .await
            .expect_err("non-existent procedure must return Err");
        assert!(
            matches!(err, FraiseQLError::Database { .. }),
            "Expected Database error, got {err:?}"
        );
    }

    /// C1 regression (CRITICAL SQL injection): a stored-procedure argument that
    /// looks like an injection payload — backslash-quote breakout + statement
    /// terminator + comment — must be **bound as a literal string**, not parsed
    /// as SQL. The procedure echoes its argument back via a SELECT, so the value
    /// must round-trip byte-for-byte. Under the pre-fix inline text-protocol
    /// escaping (which doubled `'` only and left `\` alone), MySQL's default
    /// backslash mode let `\'` close the quote and the trailing `; …` execute as
    /// raw SQL, so the call errored or stored a mangled value; the parameterized
    /// CALL binds the exact bytes.
    #[tokio::test]
    async fn test_mysql_function_call_arg_is_not_sql_injectable() {
        let a = MySqlAdapter::new(&mysql_url()).await.expect("connect");
        let payload = r"\', SELECT 1; -- injected";
        let result = a
            .execute_function_call("fn_create_tag", &[serde_json::json!(payload)])
            .await
            .expect("parameterized CALL must succeed even with an injection-shaped argument");
        assert!(!result.is_empty(), "procedure must return the inserted row");
        let name = result[0].get("name").and_then(|v| v.as_str()).unwrap_or_default();
        assert_eq!(
            name, payload,
            "argument must round-trip as a literal string, proving it was bound, not executed"
        );
    }
}

// ============================================================================
// MySQL Error Path Tests
// ============================================================================

#[cfg(feature = "test-mysql")]
mod mysql_error_tests {
    use fraiseql_core::{db::mysql::MySqlAdapter, error::FraiseQLError};
    use fraiseql_db::DatabaseAdapter;

    /// A completely bad connection URL returns a database error.
    #[tokio::test]
    async fn test_mysql_connection_failure_returns_database_error() {
        // Port 1 is almost certainly closed; connection attempt must fail.
        let result =
            MySqlAdapter::new("mysql://bad_user:bad_pass@127.0.0.1:1/nonexistent_db").await;
        assert!(result.is_err(), "connection to bad URL must fail");
        if let Err(err) = result {
            assert!(
                matches!(
                    err,
                    FraiseQLError::Database { .. } | FraiseQLError::ConnectionPool { .. }
                ),
                "Expected Database or ConnectionPool error on bad connection, got {err:?}"
            );
        }
    }

    /// Querying a non-existent view returns a database error.
    #[tokio::test]
    async fn test_mysql_missing_view_returns_database_error() {
        let url = std::env::var("MYSQL_URL").expect(
            "MYSQL_URL must be set (e.g. via `dagger call test-integration --suite=mysql`)",
        );
        let a = MySqlAdapter::new(&url).await.expect("connect");
        let err = a
            .execute_where_query("v_view_that_does_not_exist", None, Some(1), None, None)
            .await
            .expect_err("non-existent view must return Err");
        assert!(
            matches!(err, FraiseQLError::Database { .. }),
            "Expected Database error for missing view, got {err:?}"
        );
    }
}

// ============================================================================
// MySQL Change-Spine Outbox Tests
// ============================================================================

/// Behavioural proof of the Change Spine transactional outbox on MySQL: the
/// MySQL adapter's `execute_function_call_with_changelog` runs the mutation
/// procedure and writes exactly one `tb_entity_change_log` row **in the same
/// transaction**, atomically, and only for an effective change. The portable
/// path (no PG `MATERIALIZED` CTE): CALL the proc, parse its `mutation_response`
/// row in Rust, then INSERT the outbox row before commit. `duration_ms` /
/// `started_at` are legitimately NULL (no request-scoped DB clock on MySQL).
///
/// Self-provisions the contract table + procedures at runtime (mirrors the PG
/// `changelog_outbox_test.rs::provision`); each test isolates on a unique
/// `object_type`. Run with `--test-threads=1` (the file's contract).
#[cfg(feature = "test-mysql")]
mod mysql_outbox_tests {
    use fraiseql_core::db::mysql::MySqlAdapter;
    use fraiseql_db::{ChangeLogWrite, DatabaseAdapter};
    use serde_json::json;
    use sqlx::{MySqlPool, Row};

    fn mysql_url() -> String {
        std::env::var("MYSQL_URL")
            .expect("MYSQL_URL must be set (e.g. via `dagger call test-integration --suite=mysql`)")
    }

    /// A raw sqlx pool (provisioning + assertions) plus the adapter under test.
    async fn connect() -> (MySqlPool, MySqlAdapter) {
        let url = mysql_url();
        let pool = MySqlPool::connect(&url).await.expect("raw sqlx pool");
        let adapter = MySqlAdapter::new(&url).await.expect("Failed to create MySQL adapter");
        (pool, adapter)
    }

    /// DROP+CREATE the MySQL change-log contract table (the `09_*` DDL shape,
    /// trimmed to the columns these tests assert). `id` carries `DEFAULT (UUID())`
    /// — the portable INSERT omits it, exactly as on PG/MSSQL.
    async fn provision(pool: &MySqlPool) {
        sqlx::raw_sql("DROP TABLE IF EXISTS tb_entity_change_log")
            .execute(pool)
            .await
            .expect("drop contract table");
        sqlx::raw_sql(
            "CREATE TABLE tb_entity_change_log (
                 pk_entity_change_log BIGINT AUTO_INCREMENT PRIMARY KEY,
                 object_type       VARCHAR(255) NOT NULL,
                 modification_type VARCHAR(50)  NOT NULL,
                 id                CHAR(36)     NOT NULL DEFAULT (UUID()),
                 created_at        TIMESTAMP(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
                 tenant_id         CHAR(36)     NULL,
                 object_id         CHAR(36)     NULL,
                 object_data       JSON         NULL,
                 updated_fields    JSON         NULL,
                 `cascade`         JSON         NULL,
                 duration_ms       INT          NULL,
                 started_at        TIMESTAMP(6) NULL,
                 trace_id          VARCHAR(64)  NULL,
                 schema_version    VARCHAR(64)  NULL,
                 trace_context     JSON         NULL,
                 actor_type        VARCHAR(50)  NULL,
                 acting_for        CHAR(36)     NULL,
                 commit_time       TIMESTAMP(6) NULL,
                 seq               BIGINT       NULL)",
        )
        .execute(pool)
        .await
        .expect("create contract table");
    }

    /// (Re)create a stored procedure returning a `mutation_response`-shaped row.
    async fn create_proc(pool: &MySqlPool, name: &str, create_sql: &str) {
        sqlx::raw_sql(&format!("DROP PROCEDURE IF EXISTS {name}"))
            .execute(pool)
            .await
            .expect("drop proc");
        // A lone CREATE PROCEDURE statement via COM_QUERY needs no DELIMITER.
        sqlx::raw_sql(create_sql).execute(pool).await.expect("create proc");
    }

    async fn count_rows(pool: &MySqlPool, object_type: &str) -> i64 {
        sqlx::query("SELECT COUNT(*) AS c FROM tb_entity_change_log WHERE object_type = ?")
            .bind(object_type)
            .fetch_one(pool)
            .await
            .expect("count")
            .get::<i64, _>("c")
    }

    #[tokio::test]
    async fn mysql_executor_writes_changelog_in_txn() {
        let (pool, adapter) = connect().await;
        provision(&pool).await;
        let obj_type = "MyOutboxUser";

        create_proc(
            &pool,
            "fn_my_outbox_create",
            "CREATE PROCEDURE fn_my_outbox_create(IN p_id CHAR(36))
             BEGIN
               SELECT TRUE AS succeeded, TRUE AS state_changed,
                      p_id AS entity_id, 'MyOutboxUser' AS entity_type,
                      JSON_OBJECT('id', p_id, 'name', 'Ada') AS entity,
                      JSON_ARRAY('name') AS updated_fields,
                      NULL AS `cascade`;
             END",
        )
        .await;

        let id = uuid::Uuid::new_v4().to_string();
        let changelog = ChangeLogWrite::new(obj_type, "INSERT");
        let rows = adapter
            .execute_function_call_with_changelog(
                "fn_my_outbox_create",
                &[json!(id)],
                &[],
                Some(&changelog),
            )
            .await
            .expect("mutation + outbox write");

        // The procedure's row is still returned to the caller, unchanged.
        assert_eq!(rows.len(), 1, "procedure row returned to the caller");

        // Exactly one outbox row, with the mutation's identity + payload.
        let row = sqlx::query(
            "SELECT object_type, modification_type, object_id, object_data, updated_fields, \
             duration_ms FROM tb_entity_change_log WHERE object_id = ?",
        )
        .bind(&id)
        .fetch_one(&pool)
        .await
        .expect("exactly one outbox row");
        assert_eq!(row.get::<String, _>("object_type"), obj_type);
        assert_eq!(row.get::<String, _>("modification_type"), "INSERT");
        assert_eq!(row.get::<String, _>("object_id"), id);
        let data: serde_json::Value = row.get("object_data");
        assert_eq!(data["name"], json!("Ada"), "object_data is the entity payload");
        let updated: serde_json::Value = row.get("updated_fields");
        assert_eq!(updated, json!(["name"]), "updated_fields carried through");
        // duration_ms is legitimately NULL on the portable path (no DB-clock GUC).
        assert!(
            row.get::<Option<i32>, _>("duration_ms").is_none(),
            "duration_ms NULL on MySQL (no request-scoped clock)"
        );
    }

    #[tokio::test]
    async fn mysql_changelog_row_atomic_with_mutation() {
        let (pool, adapter) = connect().await;
        provision(&pool).await;
        let obj_type = "MyOutboxAtomic";

        // The procedure raises — the whole txn (incl. any outbox INSERT) rolls back.
        create_proc(
            &pool,
            "fn_my_outbox_boom",
            "CREATE PROCEDURE fn_my_outbox_boom()
             BEGIN
               SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'boom';
             END",
        )
        .await;

        let changelog = ChangeLogWrite::new(obj_type, "INSERT");
        let result = adapter
            .execute_function_call_with_changelog("fn_my_outbox_boom", &[], &[], Some(&changelog))
            .await;

        assert!(result.is_err(), "raising procedure surfaces an error");
        assert_eq!(count_rows(&pool, obj_type).await, 0, "no outbox row after rollback");
    }

    #[tokio::test]
    async fn mysql_noop_and_failed_mutations_write_no_changelog_row() {
        let (pool, adapter) = connect().await;
        provision(&pool).await;

        // succeeded=true but state_changed=false (a no-op) → no spine event.
        create_proc(
            &pool,
            "fn_my_outbox_noop",
            "CREATE PROCEDURE fn_my_outbox_noop()
             BEGIN
               SELECT TRUE AS succeeded, FALSE AS state_changed,
                      NULL AS entity_id, 'MyOutboxNoop' AS entity_type,
                      NULL AS entity, NULL AS updated_fields, NULL AS `cascade`;
             END",
        )
        .await;
        // succeeded=false (a business-logic failure that still commits) → no event.
        create_proc(
            &pool,
            "fn_my_outbox_fail",
            "CREATE PROCEDURE fn_my_outbox_fail()
             BEGIN
               SELECT FALSE AS succeeded, FALSE AS state_changed,
                      NULL AS entity_id, 'MyOutboxFail' AS entity_type,
                      NULL AS entity, NULL AS updated_fields, NULL AS `cascade`;
             END",
        )
        .await;

        adapter
            .execute_function_call_with_changelog(
                "fn_my_outbox_noop",
                &[],
                &[],
                Some(&ChangeLogWrite::new("MyOutboxNoop", "UPDATE")),
            )
            .await
            .unwrap();
        adapter
            .execute_function_call_with_changelog(
                "fn_my_outbox_fail",
                &[],
                &[],
                Some(&ChangeLogWrite::new("MyOutboxFail", "INSERT")),
            )
            .await
            .unwrap();

        assert_eq!(count_rows(&pool, "MyOutboxNoop").await, 0, "no-op writes no spine event");
        assert_eq!(count_rows(&pool, "MyOutboxFail").await, 0, "failure writes no spine event");
    }

    #[tokio::test]
    async fn mysql_object_type_falls_back_to_return_type_when_entity_type_is_null() {
        let (pool, adapter) = connect().await;
        provision(&pool).await;
        let obj_type = "MyOutboxFallback";

        // A state-changing mutation that returns NO entity_type — the NOT-NULL
        // object_type must fall back to the threaded value (the GraphQL return type).
        create_proc(
            &pool,
            "fn_my_outbox_noetype",
            "CREATE PROCEDURE fn_my_outbox_noetype(IN p_id CHAR(36))
             BEGIN
               SELECT TRUE AS succeeded, TRUE AS state_changed,
                      p_id AS entity_id, NULL AS entity_type,
                      NULL AS entity, NULL AS updated_fields, NULL AS `cascade`;
             END",
        )
        .await;

        let id = uuid::Uuid::new_v4().to_string();
        adapter
            .execute_function_call_with_changelog(
                "fn_my_outbox_noetype",
                &[json!(id)],
                &[],
                Some(&ChangeLogWrite::new(obj_type, "DELETE")),
            )
            .await
            .unwrap();

        let object_type: String =
            sqlx::query("SELECT object_type FROM tb_entity_change_log WHERE object_id = ?")
                .bind(&id)
                .fetch_one(&pool)
                .await
                .unwrap()
                .get("object_type");
        assert_eq!(object_type, obj_type, "object_type falls back to the return type");
    }

    #[tokio::test]
    async fn mysql_outbox_atomic_with_procedure_dml() {
        async fn probe_count(pool: &MySqlPool, id: &str) -> i64 {
            sqlx::query("SELECT COUNT(*) AS c FROM tb_my_probe WHERE id = ?")
                .bind(id)
                .fetch_one(pool)
                .await
                .unwrap()
                .get::<i64, _>("c")
        }

        let (pool, adapter) = connect().await;
        provision(&pool).await;
        // A probe table the procedure writes to: proves the procedure's OWN DML and
        // the outbox row commit (or roll back) together, and that a procedure doing
        // DML-then-SELECT does not desync the connection before the outbox INSERT.
        sqlx::raw_sql("DROP TABLE IF EXISTS tb_my_probe").execute(&pool).await.unwrap();
        sqlx::raw_sql("CREATE TABLE tb_my_probe (id CHAR(36) PRIMARY KEY, note VARCHAR(50))")
            .execute(&pool)
            .await
            .unwrap();

        // Commit path: the procedure INSERTs a probe row, then returns an effective
        // change → BOTH the probe row and the outbox row persist.
        create_proc(
            &pool,
            "fn_my_dml_ok",
            "CREATE PROCEDURE fn_my_dml_ok(IN p_id CHAR(36))
             BEGIN
               INSERT INTO tb_my_probe (id, note) VALUES (p_id, 'ok');
               SELECT TRUE AS succeeded, TRUE AS state_changed, p_id AS entity_id,
                      'MyDml' AS entity_type, NULL AS entity, NULL AS updated_fields,
                      NULL AS `cascade`;
             END",
        )
        .await;
        let ok_id = uuid::Uuid::new_v4().to_string();
        adapter
            .execute_function_call_with_changelog(
                "fn_my_dml_ok",
                &[json!(ok_id)],
                &[],
                Some(&ChangeLogWrite::new("MyDml", "INSERT")),
            )
            .await
            .unwrap();
        assert_eq!(probe_count(&pool, &ok_id).await, 1, "procedure DML committed");
        assert_eq!(
            count_rows(&pool, "MyDml").await,
            1,
            "outbox row committed atomically with the procedure DML"
        );

        // Rollback path: the procedure INSERTs a probe row, then RAISES → neither the
        // probe row nor the outbox row survives.
        create_proc(
            &pool,
            "fn_my_dml_boom",
            "CREATE PROCEDURE fn_my_dml_boom(IN p_id CHAR(36))
             BEGIN
               INSERT INTO tb_my_probe (id, note) VALUES (p_id, 'boom');
               SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'boom';
             END",
        )
        .await;
        let boom_id = uuid::Uuid::new_v4().to_string();
        let res = adapter
            .execute_function_call_with_changelog(
                "fn_my_dml_boom",
                &[json!(boom_id)],
                &[],
                Some(&ChangeLogWrite::new("MyDmlBoom", "INSERT")),
            )
            .await;
        assert!(res.is_err(), "raising procedure surfaces an error");
        assert_eq!(probe_count(&pool, &boom_id).await, 0, "procedure DML rolled back");
        assert_eq!(count_rows(&pool, "MyDmlBoom").await, 0, "no outbox row after rollback");
    }

    #[tokio::test]
    async fn mysql_tenant_id_stamped_and_null_paths() {
        let (pool, adapter) = connect().await;
        provision(&pool).await;
        let obj_type = "MyOutboxTenant";

        create_proc(
            &pool,
            "fn_my_outbox_tenant",
            "CREATE PROCEDURE fn_my_outbox_tenant(IN p_id CHAR(36))
             BEGIN
               SELECT TRUE AS succeeded, TRUE AS state_changed,
                      p_id AS entity_id, 'MyOutboxTenant' AS entity_type,
                      NULL AS entity, NULL AS updated_fields, NULL AS `cascade`;
             END",
        )
        .await;

        // Stamped explicitly from the envelope (NOT reconstructed from any session).
        let tenant = uuid::Uuid::new_v4().to_string();
        let stamped_id = uuid::Uuid::new_v4().to_string();
        adapter
            .execute_function_call_with_changelog(
                "fn_my_outbox_tenant",
                &[json!(stamped_id)],
                &[],
                Some(
                    &ChangeLogWrite::new(obj_type, "INSERT")
                        .with_tenant_id(Some(tenant.parse().unwrap())),
                ),
            )
            .await
            .unwrap();
        let got: String =
            sqlx::query("SELECT tenant_id FROM tb_entity_change_log WHERE object_id = ?")
                .bind(&stamped_id)
                .fetch_one(&pool)
                .await
                .unwrap()
                .get("tenant_id");
        assert_eq!(got, tenant, "tenant_id stamped verbatim from the envelope");

        // No tenant on the envelope → the column is NULL (never a lossy cast).
        let null_id = uuid::Uuid::new_v4().to_string();
        adapter
            .execute_function_call_with_changelog(
                "fn_my_outbox_tenant",
                &[json!(null_id)],
                &[],
                Some(&ChangeLogWrite::new(obj_type, "INSERT")),
            )
            .await
            .unwrap();
        let got: Option<String> =
            sqlx::query("SELECT tenant_id FROM tb_entity_change_log WHERE object_id = ?")
                .bind(&null_id)
                .fetch_one(&pool)
                .await
                .unwrap()
                .get("tenant_id");
        assert_eq!(got, None, "tenant_id is NULL when the envelope carries none");
    }
}

// ============================================================================
// SQL Server Advanced Query Tests (window functions, CTEs, aggregations)
// ============================================================================

#[cfg(feature = "test-sqlserver")]
mod sqlserver_advanced_tests {
    use fraiseql_core::db::sqlserver::SqlServerAdapter;
    use fraiseql_db::DatabaseAdapter;

    async fn adapter() -> SqlServerAdapter {
        let url = super::sqlserver_conn("fraiseql_test").await.expect(
            "SQLSERVER_URL must be set (e.g. via `dagger call test-integration --suite=sqlserver`)",
        );
        SqlServerAdapter::new(&url).await.expect("Failed to connect to SQL Server")
    }

    /// SQL Server `RANK()` window function partitioned by category.
    #[tokio::test]
    async fn test_sqlserver_window_function_rank() {
        let a = adapter().await;
        let results = a
            .execute_raw_query(
                "SELECT category, score, label,
                        RANK() OVER (PARTITION BY category ORDER BY score DESC) AS rnk
                 FROM v_score
                 ORDER BY category, rnk",
            )
            .await
            .expect("RANK() must succeed on SQL Server 2012+");
        assert_eq!(results.len(), 8, "all 8 scored rows returned");
        let first = &results[0];
        assert!(first.contains_key("rnk"), "must include rank column");
    }

    /// SQL Server `ROW_NUMBER()` window function.
    #[tokio::test]
    async fn test_sqlserver_window_function_row_number() {
        let a = adapter().await;
        let results = a
            .execute_raw_query(
                "SELECT id, label,
                        ROW_NUMBER() OVER (ORDER BY score DESC) AS row_num
                 FROM v_score",
            )
            .await
            .expect("ROW_NUMBER() must succeed");
        assert_eq!(results.len(), 8);
    }

    /// CTE (WITH clause) is fully supported on SQL Server.
    #[tokio::test]
    async fn test_sqlserver_cte_basic() {
        let a = adapter().await;
        let results = a
            .execute_raw_query(
                "WITH top_scores AS (
                     SELECT id, label, score FROM v_score WHERE score >= 80
                 )
                 SELECT * FROM top_scores ORDER BY score DESC",
            )
            .await
            .expect("CTE must succeed on SQL Server");
        assert_eq!(results.len(), 4, "four rows have score >= 80");
    }

    /// Recursive CTE on SQL Server.
    #[tokio::test]
    async fn test_sqlserver_cte_recursive() {
        let a = adapter().await;
        let results = a
            .execute_raw_query(
                "WITH counter(n) AS (
                     SELECT 1
                     UNION ALL
                     SELECT n + 1 FROM counter WHERE n < 5
                 )
                 SELECT n FROM counter",
            )
            .await
            .expect("recursive CTE must succeed on SQL Server");
        assert_eq!(results.len(), 5, "recursive CTE must return 5 rows");
    }

    /// COUNT, SUM, AVG, MIN, MAX aggregations on SQL Server.
    #[tokio::test]
    async fn test_sqlserver_aggregations() {
        let a = adapter().await;
        let results = a
            .execute_raw_query(
                "SELECT
                     COUNT(*) AS cnt,
                     SUM(score) AS total,
                     AVG(CAST(score AS FLOAT)) AS avg_score,
                     MIN(score) AS min_score,
                     MAX(score) AS max_score
                 FROM v_score",
            )
            .await
            .expect("aggregations must succeed");
        assert_eq!(results.len(), 1);
        let row = &results[0];
        let cnt = row.get("cnt").and_then(|v| v.as_u64()).unwrap_or(0);
        assert_eq!(cnt, 8);
        let max = row.get("max_score").and_then(|v| v.as_u64()).unwrap_or(0);
        assert_eq!(max, 95, "max score is 95 (alpha)");
    }
}

// ============================================================================
// SQL Server Mutation Tests
// ============================================================================

#[cfg(feature = "test-sqlserver")]
mod sqlserver_mutation_tests {
    use fraiseql_core::db::sqlserver::SqlServerAdapter;
    use fraiseql_db::DatabaseAdapter;

    async fn adapter() -> SqlServerAdapter {
        let url = super::sqlserver_conn("fraiseql_test").await.expect(
            "SQLSERVER_URL must be set (e.g. via `dagger call test-integration --suite=sqlserver`)",
        );
        SqlServerAdapter::new(&url).await.expect("connect")
    }

    /// SQL Server mutation via stored procedure using OUTPUT INSERTED.*.
    #[tokio::test]
    async fn test_sqlserver_mutation_insert_via_procedure() {
        let a = adapter().await;
        let result = a
            .execute_function_call("fn_create_tag", &[serde_json::json!("test-tag-sqlserver")])
            .await
            .expect("stored procedure call must succeed");
        assert!(!result.is_empty(), "INSERT must return the new row");
        let row = &result[0];
        assert!(row.contains_key("id"), "returned row must have id");
        let name = row.get("name").and_then(|v| v.as_str()).unwrap_or("");
        assert_eq!(name, "test-tag-sqlserver");
    }

    /// Calling a non-existent procedure returns a database error.
    #[tokio::test]
    async fn test_sqlserver_mutation_nonexistent_procedure_returns_error() {
        use fraiseql_core::error::FraiseQLError;
        let a = adapter().await;
        let err = a
            .execute_function_call("fn_does_not_exist", &[])
            .await
            .expect_err("non-existent procedure must return Err");
        assert!(
            matches!(err, FraiseQLError::Database { .. }),
            "Expected Database error, got {err:?}"
        );
    }
}

// ============================================================================
// SQL Server Change-Spine Outbox Tests
// ============================================================================

/// Behavioural proof of the Change Spine transactional outbox on SQL Server: the
/// tiberius adapter's `execute_function_call_with_changelog` runs the mutation
/// procedure and writes exactly one `core.tb_entity_change_log` row **in the same
/// transaction** (`SET XACT_ABORT ON; BEGIN TRAN … COMMIT`), atomically, and only
/// for an effective change. `duration_ms`/`started_at` are legitimately NULL (no
/// request-scoped DB clock on SQL Server).
///
/// Self-provisions the contract table + procedures at runtime; each test isolates
/// on a unique `object_type`. Run with `--test-threads=1`.
#[cfg(feature = "test-sqlserver")]
mod sqlserver_outbox_tests {
    use fraiseql_core::db::sqlserver::SqlServerAdapter;
    use fraiseql_db::{ChangeLogWrite, DatabaseAdapter};
    use serde_json::json;

    async fn adapter() -> SqlServerAdapter {
        let url = super::sqlserver_conn("fraiseql_test").await.expect(
            "SQLSERVER_URL must be set (e.g. via `dagger call test-integration --suite=sqlserver`)",
        );
        SqlServerAdapter::new(&url).await.expect("Failed to connect to SQL Server")
    }

    /// DROP+CREATE the SQL Server change-log contract table (the `10_*` DDL shape,
    /// trimmed to the columns these tests assert). `id`/`seq` carry defaults; the
    /// portable INSERT omits them. `[cascade]` is bracket-quoted (reserved word).
    async fn provision(a: &SqlServerAdapter) {
        a.execute_raw_query("IF SCHEMA_ID('core') IS NULL EXEC('CREATE SCHEMA core')")
            .await
            .expect("create core schema");
        a.execute_raw_query(
            "IF OBJECT_ID('core.tb_entity_change_log','U') IS NOT NULL \
                 DROP TABLE core.tb_entity_change_log",
        )
        .await
        .expect("drop contract table");
        a.execute_raw_query(
            "IF OBJECT_ID('core.seq_entity_change_log') IS NOT NULL \
                 DROP SEQUENCE core.seq_entity_change_log",
        )
        .await
        .expect("drop sequence");
        a.execute_raw_query(
            "CREATE SEQUENCE core.seq_entity_change_log AS BIGINT START WITH 1 INCREMENT BY 1",
        )
        .await
        .expect("create sequence");
        a.execute_raw_query(
            "CREATE TABLE core.tb_entity_change_log (
                 pk_entity_change_log BIGINT IDENTITY(1,1) PRIMARY KEY,
                 object_type       NVARCHAR(255) NOT NULL,
                 modification_type NVARCHAR(50)  NOT NULL,
                 id                UNIQUEIDENTIFIER NOT NULL DEFAULT NEWID(),
                 created_at        DATETIME2     NOT NULL DEFAULT SYSUTCDATETIME(),
                 tenant_id         UNIQUEIDENTIFIER NULL,
                 object_id         UNIQUEIDENTIFIER NULL,
                 object_data       NVARCHAR(MAX) NULL,
                 updated_fields    NVARCHAR(MAX) NULL,
                 [cascade]         NVARCHAR(MAX) NULL,
                 duration_ms       INT           NULL,
                 started_at        DATETIME2     NULL,
                 trace_id          NVARCHAR(64)  NULL,
                 schema_version    NVARCHAR(64)  NULL,
                 trace_context     NVARCHAR(MAX) NULL,
                 actor_type        NVARCHAR(50)  NULL,
                 acting_for        UNIQUEIDENTIFIER NULL,
                 commit_time       DATETIME2     NULL,
                 seq               BIGINT NOT NULL DEFAULT (NEXT VALUE FOR core.seq_entity_change_log))",
        )
        .await
        .expect("create contract table");
    }

    async fn create_proc(a: &SqlServerAdapter, body: &str) {
        a.execute_raw_query(body).await.expect("create proc");
    }

    async fn count_rows(a: &SqlServerAdapter, object_type: &str) -> i64 {
        let rows = a
            .execute_raw_query(&format!(
                "SELECT COUNT(*) AS c FROM core.tb_entity_change_log WHERE object_type = '{object_type}'"
            ))
            .await
            .expect("count");
        rows[0].get("c").and_then(serde_json::Value::as_i64).expect("count value")
    }

    #[tokio::test]
    async fn sqlserver_executor_writes_changelog_in_txn() {
        let a = adapter().await;
        provision(&a).await;
        let obj_type = "SsOutboxUser";
        create_proc(
            &a,
            "CREATE OR ALTER PROCEDURE dbo.fn_ss_outbox_create @p_id NVARCHAR(36) AS
             BEGIN
               SET NOCOUNT ON;
               SELECT CAST(1 AS BIT) AS succeeded, CAST(1 AS BIT) AS state_changed,
                      @p_id AS entity_id, 'SsOutboxUser' AS entity_type,
                      '{\"name\":\"Ada\"}' AS entity, '[\"name\"]' AS updated_fields,
                      NULL AS [cascade];
             END",
        )
        .await;

        let id = uuid::Uuid::new_v4().to_string();
        let rows = a
            .execute_function_call_with_changelog(
                "fn_ss_outbox_create",
                &[json!(id)],
                &[],
                Some(&ChangeLogWrite::new(obj_type, "INSERT")),
            )
            .await
            .expect("mutation + outbox write");
        assert_eq!(rows.len(), 1, "procedure row returned to the caller");

        let got = a
            .execute_raw_query(&format!(
                "SELECT object_type, modification_type, CONVERT(NVARCHAR(36), object_id) AS object_id, \
                 object_data, updated_fields, duration_ms \
                 FROM core.tb_entity_change_log WHERE object_id = '{id}'"
            ))
            .await
            .expect("read outbox row");
        assert_eq!(got.len(), 1, "exactly one outbox row");
        let row = &got[0];
        assert_eq!(row.get("object_type"), Some(&json!(obj_type)));
        assert_eq!(row.get("modification_type"), Some(&json!("INSERT")));
        // SQL Server canonicalises UNIQUEIDENTIFIER to uppercase → compare case-insensitively.
        assert_eq!(
            row.get("object_id").and_then(serde_json::Value::as_str).map(str::to_lowercase),
            Some(id.clone()),
            "object_id round-trips through the UNIQUEIDENTIFIER column"
        );
        assert_eq!(row["object_data"]["name"], json!("Ada"), "object_data is the entity payload");
        assert_eq!(row.get("updated_fields"), Some(&json!(["name"])), "updated_fields carried");
        // duration_ms is legitimately NULL on the portable path (no DB-clock GUC).
        assert!(
            row.get("duration_ms").is_none_or(serde_json::Value::is_null),
            "duration_ms NULL on SQL Server (no request-scoped clock)"
        );
    }

    #[tokio::test]
    async fn sqlserver_changelog_row_atomic_with_mutation() {
        let a = adapter().await;
        provision(&a).await;
        let obj_type = "SsOutboxAtomic";
        // The procedure raises — XACT_ABORT rolls back the whole transaction.
        create_proc(
            &a,
            "CREATE OR ALTER PROCEDURE dbo.fn_ss_outbox_boom AS
             BEGIN
               SET NOCOUNT ON;
               THROW 50000, 'boom', 1;
             END",
        )
        .await;
        let result = a
            .execute_function_call_with_changelog(
                "fn_ss_outbox_boom",
                &[],
                &[],
                Some(&ChangeLogWrite::new(obj_type, "INSERT")),
            )
            .await;
        assert!(result.is_err(), "raising procedure surfaces an error");
        assert_eq!(count_rows(&a, obj_type).await, 0, "no outbox row after rollback");
    }

    #[tokio::test]
    async fn sqlserver_noop_and_failed_mutations_write_no_changelog_row() {
        let a = adapter().await;
        provision(&a).await;
        create_proc(
            &a,
            "CREATE OR ALTER PROCEDURE dbo.fn_ss_outbox_noop AS
             BEGIN
               SET NOCOUNT ON;
               SELECT CAST(1 AS BIT) AS succeeded, CAST(0 AS BIT) AS state_changed,
                      NULL AS entity_id, 'SsOutboxNoop' AS entity_type,
                      NULL AS entity, NULL AS updated_fields, NULL AS [cascade];
             END",
        )
        .await;
        create_proc(
            &a,
            "CREATE OR ALTER PROCEDURE dbo.fn_ss_outbox_fail AS
             BEGIN
               SET NOCOUNT ON;
               SELECT CAST(0 AS BIT) AS succeeded, CAST(0 AS BIT) AS state_changed,
                      NULL AS entity_id, 'SsOutboxFail' AS entity_type,
                      NULL AS entity, NULL AS updated_fields, NULL AS [cascade];
             END",
        )
        .await;
        a.execute_function_call_with_changelog(
            "fn_ss_outbox_noop",
            &[],
            &[],
            Some(&ChangeLogWrite::new("SsOutboxNoop", "UPDATE")),
        )
        .await
        .unwrap();
        a.execute_function_call_with_changelog(
            "fn_ss_outbox_fail",
            &[],
            &[],
            Some(&ChangeLogWrite::new("SsOutboxFail", "INSERT")),
        )
        .await
        .unwrap();
        assert_eq!(count_rows(&a, "SsOutboxNoop").await, 0, "no-op writes no spine event");
        assert_eq!(count_rows(&a, "SsOutboxFail").await, 0, "failure writes no spine event");
    }

    #[tokio::test]
    async fn sqlserver_object_type_falls_back_to_return_type_when_entity_type_is_null() {
        let a = adapter().await;
        provision(&a).await;
        let obj_type = "SsOutboxFallback";
        create_proc(
            &a,
            "CREATE OR ALTER PROCEDURE dbo.fn_ss_outbox_noetype @p_id NVARCHAR(36) AS
             BEGIN
               SET NOCOUNT ON;
               SELECT CAST(1 AS BIT) AS succeeded, CAST(1 AS BIT) AS state_changed,
                      @p_id AS entity_id, NULL AS entity_type,
                      NULL AS entity, NULL AS updated_fields, NULL AS [cascade];
             END",
        )
        .await;
        let id = uuid::Uuid::new_v4().to_string();
        a.execute_function_call_with_changelog(
            "fn_ss_outbox_noetype",
            &[json!(id)],
            &[],
            Some(&ChangeLogWrite::new(obj_type, "DELETE")),
        )
        .await
        .unwrap();
        let got = a
            .execute_raw_query(&format!(
                "SELECT object_type FROM core.tb_entity_change_log WHERE object_id = '{id}'"
            ))
            .await
            .unwrap();
        assert_eq!(got[0].get("object_type"), Some(&json!(obj_type)), "object_type falls back");
    }

    #[tokio::test]
    async fn sqlserver_outbox_atomic_with_procedure_dml() {
        async fn probe_count(a: &SqlServerAdapter, id: &str) -> i64 {
            let rows = a
                .execute_raw_query(&format!(
                    "SELECT COUNT(*) AS c FROM dbo.tb_ss_probe WHERE id = '{id}'"
                ))
                .await
                .unwrap();
            rows[0].get("c").and_then(serde_json::Value::as_i64).unwrap()
        }

        let a = adapter().await;
        provision(&a).await;
        // A probe table the procedure writes to: proves the procedure's OWN DML and
        // the outbox row commit (or roll back) together.
        a.execute_raw_query(
            "IF OBJECT_ID('dbo.tb_ss_probe','U') IS NOT NULL DROP TABLE dbo.tb_ss_probe",
        )
        .await
        .unwrap();
        a.execute_raw_query(
            "CREATE TABLE dbo.tb_ss_probe (id NVARCHAR(36) PRIMARY KEY, note NVARCHAR(50))",
        )
        .await
        .unwrap();

        // Commit path: procedure INSERTs a probe row + returns an effective change.
        create_proc(
            &a,
            "CREATE OR ALTER PROCEDURE dbo.fn_ss_dml_ok @p_id NVARCHAR(36) AS
             BEGIN
               SET NOCOUNT ON;
               INSERT INTO dbo.tb_ss_probe (id, note) VALUES (@p_id, 'ok');
               SELECT CAST(1 AS BIT) AS succeeded, CAST(1 AS BIT) AS state_changed,
                      @p_id AS entity_id, 'SsDml' AS entity_type,
                      NULL AS entity, NULL AS updated_fields, NULL AS [cascade];
             END",
        )
        .await;
        let ok_id = uuid::Uuid::new_v4().to_string();
        a.execute_function_call_with_changelog(
            "fn_ss_dml_ok",
            &[json!(ok_id)],
            &[],
            Some(&ChangeLogWrite::new("SsDml", "INSERT")),
        )
        .await
        .unwrap();
        assert_eq!(probe_count(&a, &ok_id).await, 1, "procedure DML committed");
        assert_eq!(count_rows(&a, "SsDml").await, 1, "outbox row committed atomically");

        // Rollback path: procedure INSERTs then THROWs → neither survives.
        create_proc(
            &a,
            "CREATE OR ALTER PROCEDURE dbo.fn_ss_dml_boom @p_id NVARCHAR(36) AS
             BEGIN
               SET NOCOUNT ON;
               INSERT INTO dbo.tb_ss_probe (id, note) VALUES (@p_id, 'boom');
               THROW 50000, 'boom', 1;
             END",
        )
        .await;
        let boom_id = uuid::Uuid::new_v4().to_string();
        let res = a
            .execute_function_call_with_changelog(
                "fn_ss_dml_boom",
                &[json!(boom_id)],
                &[],
                Some(&ChangeLogWrite::new("SsDmlBoom", "INSERT")),
            )
            .await;
        assert!(res.is_err(), "raising procedure surfaces an error");
        assert_eq!(probe_count(&a, &boom_id).await, 0, "procedure DML rolled back");
        assert_eq!(count_rows(&a, "SsDmlBoom").await, 0, "no outbox row after rollback");
    }

    #[tokio::test]
    async fn sqlserver_tenant_id_stamped_and_null_paths() {
        let a = adapter().await;
        provision(&a).await;
        let obj_type = "SsOutboxTenant";
        create_proc(
            &a,
            "CREATE OR ALTER PROCEDURE dbo.fn_ss_outbox_tenant @p_id NVARCHAR(36) AS
             BEGIN
               SET NOCOUNT ON;
               SELECT CAST(1 AS BIT) AS succeeded, CAST(1 AS BIT) AS state_changed,
                      @p_id AS entity_id, 'SsOutboxTenant' AS entity_type,
                      NULL AS entity, NULL AS updated_fields, NULL AS [cascade];
             END",
        )
        .await;

        // Stamped explicitly from the envelope.
        let tenant = uuid::Uuid::new_v4().to_string();
        let stamped_id = uuid::Uuid::new_v4().to_string();
        a.execute_function_call_with_changelog(
            "fn_ss_outbox_tenant",
            &[json!(stamped_id)],
            &[],
            Some(
                &ChangeLogWrite::new(obj_type, "INSERT")
                    .with_tenant_id(Some(tenant.parse().unwrap())),
            ),
        )
        .await
        .unwrap();
        let got = a
            .execute_raw_query(&format!(
                "SELECT CONVERT(NVARCHAR(36), tenant_id) AS tenant_id \
                 FROM core.tb_entity_change_log WHERE object_id = '{stamped_id}'"
            ))
            .await
            .unwrap();
        // MSSQL upper-cases UNIQUEIDENTIFIER → compare case-insensitively.
        assert_eq!(
            got[0]
                .get("tenant_id")
                .and_then(serde_json::Value::as_str)
                .map(str::to_lowercase),
            Some(tenant.clone()),
            "tenant_id stamped verbatim from the envelope"
        );

        // No tenant on the envelope → the column is NULL.
        let null_id = uuid::Uuid::new_v4().to_string();
        a.execute_function_call_with_changelog(
            "fn_ss_outbox_tenant",
            &[json!(null_id)],
            &[],
            Some(&ChangeLogWrite::new(obj_type, "INSERT")),
        )
        .await
        .unwrap();
        let got = a
            .execute_raw_query(&format!(
                "SELECT CONVERT(NVARCHAR(36), tenant_id) AS tenant_id \
                 FROM core.tb_entity_change_log WHERE object_id = '{null_id}'"
            ))
            .await
            .unwrap();
        assert!(
            got[0].get("tenant_id").is_none_or(serde_json::Value::is_null),
            "tenant_id is NULL when the envelope carries none"
        );
    }
}

// ============================================================================
// DialectCapabilityGuard Error Path Tests
// ============================================================================

#[cfg(any(feature = "mysql", feature = "sqlserver"))]
mod dialect_guard_error_tests {
    use fraiseql_db::{DialectCapabilityGuard, Feature, types::DatabaseType};
    use fraiseql_error::FraiseQLError;

    /// JSONB path ops are unsupported on MySQL — guard returns Unsupported.
    #[cfg(feature = "mysql")]
    #[test]
    fn test_mysql_jsonb_returns_unsupported() {
        let result = DialectCapabilityGuard::check(DatabaseType::MySQL, Feature::JsonbPathOps);
        assert!(
            matches!(result, Err(FraiseQLError::Unsupported { .. })),
            "JSONB ops on MySQL must return Unsupported, got {result:?}"
        );
    }

    /// Subscriptions are unsupported on MySQL — guard returns Unsupported.
    #[cfg(feature = "mysql")]
    #[test]
    fn test_mysql_subscriptions_returns_unsupported() {
        let result = DialectCapabilityGuard::check(DatabaseType::MySQL, Feature::Subscriptions);
        assert!(
            matches!(result, Err(FraiseQLError::Unsupported { .. })),
            "Subscriptions on MySQL must return Unsupported"
        );
    }

    /// JSONB path ops are unsupported on SQL Server — guard returns Unsupported.
    #[cfg(feature = "sqlserver")]
    #[test]
    fn test_sqlserver_jsonb_returns_unsupported() {
        let result = DialectCapabilityGuard::check(DatabaseType::SQLServer, Feature::JsonbPathOps);
        assert!(
            matches!(result, Err(FraiseQLError::Unsupported { .. })),
            "JSONB ops on SQL Server must return Unsupported"
        );
    }

    /// Mutations are supported on both MySQL and SQL Server — guard returns Ok.
    #[cfg(feature = "mysql")]
    #[test]
    fn test_mysql_mutations_are_supported() {
        assert!(
            DialectCapabilityGuard::check(DatabaseType::MySQL, Feature::Mutations).is_ok(),
            "Mutations must be supported on MySQL"
        );
    }

    /// Window functions are supported on both MySQL 8+ and SQL Server 2012+.
    #[cfg(feature = "mysql")]
    #[test]
    fn test_mysql_window_functions_are_supported() {
        assert!(
            DialectCapabilityGuard::check(DatabaseType::MySQL, Feature::WindowFunctions).is_ok(),
            "Window functions must be supported on MySQL 8+"
        );
    }
}

// ============================================================================
// Cross-Database Tests (Database-Agnostic)
// ============================================================================

/// Trait for database-agnostic test execution
#[cfg(any(feature = "mysql", feature = "sqlite", feature = "sqlserver"))]
#[allow(dead_code)] // Reason: called by subset of multi-database tests; Clippy false-positive (multi-binary)
async fn run_basic_health_check<A: DatabaseAdapter>(adapter: &A) -> bool {
    adapter.health_check().await.is_ok()
}

#[cfg(any(feature = "mysql", feature = "sqlite", feature = "sqlserver"))]
#[allow(dead_code)] // Reason: called by subset of multi-database tests; Clippy false-positive (multi-binary)
async fn verify_pool_metrics<A: DatabaseAdapter>(adapter: &A) -> bool {
    let metrics = adapter.pool_metrics();
    metrics.total_connections > 0 && metrics.idle_connections <= metrics.total_connections
}

// Helper to run queries and verify JSON structure
#[cfg(any(feature = "mysql", feature = "sqlite", feature = "sqlserver"))]
#[allow(dead_code)] // Reason: called by subset of multi-database tests; Clippy false-positive (multi-binary)
async fn verify_view_returns_json<A: DatabaseAdapter>(
    adapter: &A,
    view_name: &str,
    expected_fields: &[&str],
) -> bool {
    let results = adapter.execute_where_query(view_name, None, Some(1), None, None).await;

    if let Ok(rows) = results {
        if rows.is_empty() {
            return false;
        }

        let value = rows[0].as_value();
        expected_fields.iter().all(|field| value.get(*field).is_some())
    } else {
        false
    }
}