fraiseql-cli 2.17.1

CLI tools for FraiseQL v2 - Schema compilation and development utilities
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
#![allow(clippy::unwrap_used, clippy::panic)] // Reason: test code, panics acceptable
#![allow(clippy::wildcard_imports)] // Reason: test modules use wildcard imports for conciseness

mod database_validator_tests {
    use std::collections::HashMap;

    use fraiseql_core::{
        db::{
            DatabaseType,
            introspector::{DatabaseIntrospector, RelationInfo},
        },
        schema::{
            ArgumentDefinition, AutoParams, CompiledSchema, CursorType, FieldDefinition, FieldType,
            MutationDefinition, PaginationOrder, QueryDefinition, TypeDefinition,
        },
        validation::CustomTypeRegistry,
    };
    use indexmap::IndexMap;

    use super::super::{database_validator::*, mutation_contract::Severity};

    /// Mock introspector for unit tests.
    struct MockIntrospector {
        relations:    Vec<RelationInfo>,
        columns:      HashMap<String, Vec<(String, String, bool)>>,
        json_samples: HashMap<(String, String), Vec<serde_json::Value>>,
        functions:    std::collections::HashSet<String>,
        view_defs:    HashMap<String, String>,
        db_type:      DatabaseType,
    }

    impl MockIntrospector {
        fn new(db_type: DatabaseType) -> Self {
            Self {
                relations: Vec::new(),
                columns: HashMap::new(),
                json_samples: HashMap::new(),
                functions: std::collections::HashSet::new(),
                view_defs: HashMap::new(),
                db_type,
            }
        }

        /// Register a backing function (as the runtime would name it, e.g.
        /// `fn_create_user` or `app.fn_create_order`).
        fn with_function(mut self, name: &str) -> Self {
            self.functions.insert(name.to_string());
            self
        }

        fn with_relation(
            mut self,
            schema: &str,
            name: &str,
            kind: fraiseql_core::db::RelationKind,
        ) -> Self {
            self.relations.push(RelationInfo {
                schema: schema.to_string(),
                name: name.to_string(),
                kind,
            });
            self
        }

        fn with_columns(mut self, table: &str, cols: Vec<(&str, &str, bool)>) -> Self {
            self.columns.insert(
                table.to_string(),
                cols.into_iter()
                    .map(|(n, t, nullable)| (n.to_string(), t.to_string(), nullable))
                    .collect(),
            );
            self
        }

        /// Register a view body, as `pg_get_viewdef` would return it (#1303).
        fn with_view_definition(mut self, view: &str, body: &str) -> Self {
            self.view_defs.insert(view.to_string(), body.to_string());
            self
        }

        fn with_json_samples(
            mut self,
            table: &str,
            column: &str,
            samples: Vec<serde_json::Value>,
        ) -> Self {
            self.json_samples.insert((table.to_string(), column.to_string()), samples);
            self
        }
    }

    // Reason: `DatabaseIntrospector` is async because the real one queries the catalog;
    // a mock answering from a fixture still implements it.
    #[allow(unknown_lints, clippy::unused_async_trait_impl)]
    impl DatabaseIntrospector for MockIntrospector {
        async fn list_fact_tables(&self) -> fraiseql_core::Result<Vec<String>> {
            Ok(Vec::new())
        }

        async fn get_columns(
            &self,
            table_name: &str,
        ) -> fraiseql_core::Result<Vec<(String, String, bool)>> {
            Ok(self.columns.get(table_name).cloned().unwrap_or_default())
        }

        async fn get_indexed_columns(
            &self,
            _table_name: &str,
        ) -> fraiseql_core::Result<Vec<String>> {
            Ok(Vec::new())
        }

        fn database_type(&self) -> DatabaseType {
            self.db_type
        }

        async fn list_relations(&self) -> fraiseql_core::Result<Vec<RelationInfo>> {
            Ok(self.relations.clone())
        }

        async fn get_sample_json_rows(
            &self,
            table_name: &str,
            column_name: &str,
            _limit: usize,
        ) -> fraiseql_core::Result<Vec<serde_json::Value>> {
            Ok(self
                .json_samples
                .get(&(table_name.to_string(), column_name.to_string()))
                .cloned()
                .unwrap_or_default())
        }

        async fn function_exists(
            &self,
            schema: Option<&str>,
            name: &str,
        ) -> fraiseql_core::Result<Option<bool>> {
            let key = match schema {
                Some(s) => format!("{s}.{name}"),
                None => name.to_string(),
            };
            Ok(Some(self.functions.contains(&key)))
        }

        async fn get_view_definition(
            &self,
            relation: &str,
        ) -> fraiseql_core::Result<Option<String>> {
            Ok(self.view_defs.get(relation).cloned())
        }
    }

    fn make_query(name: &str, return_type: &str, sql_source: &str) -> QueryDefinition {
        QueryDefinition {
            function: None,

            requires_actor:      Vec::new(),
            returns_count:       false,
            name:                name.to_string(),
            return_type:         return_type.to_string(),
            returns_list:        true,
            nullable:            false,
            arguments:           vec![],
            sql_source:          Some(sql_source.to_string()),
            description:         None,
            auto_params:         AutoParams::default(),
            deprecation:         None,
            jsonb_column:        "data".to_string(),
            relay:               false,
            relay_cursor_column: None,
            relay_cursor_type:   CursorType::default(),
            inject_params:       IndexMap::default(),
            read_routing:        fraiseql_core::db::types::ReadRouting::default(),
            cache_ttl_seconds:   None,
            additional_views:    vec![],
            requires_role:       None,
            rest_path:           None,
            rest_method:         None,
            rest_stream:         false,
            native_columns:      HashMap::new(),
            pagination_order:    None,
        }
    }

    fn make_type(name: &str, fields: Vec<(&str, FieldType)>) -> TypeDefinition {
        TypeDefinition {
            name:                name.into(),
            fields:              fields
                .into_iter()
                .map(|(n, ft)| FieldDefinition::new(n, ft))
                .collect(),
            description:         None,
            sql_source:          "".into(),
            jsonb_column:        "data".to_string(),
            sql_projection_hint: None,
            implements:          vec![],
            requires_role:       None,
            is_error:            false,
            relay:               false,
            internal:            false,
            embedded:            false,
            relationships:       Vec::new(),
            inject_params:       indexmap::IndexMap::new(),
            subscription_policy: None,
        }
    }

    fn make_schema(types: Vec<TypeDefinition>, queries: Vec<QueryDefinition>) -> CompiledSchema {
        CompiledSchema {
            types,
            queries,
            enums: vec![],
            input_types: vec![],
            interfaces: vec![],
            unions: vec![],
            mutations: vec![],
            subscriptions: vec![],
            directives: vec![],
            observers: Vec::new(),
            fact_tables: HashMap::default(),
            federation: None,
            security: None,
            observers_config: None,
            subscriptions_config: None,
            validation_config: None,
            debug_config: None,
            mcp_config: None,
            schema_sdl: None,
            custom_scalars: CustomTypeRegistry::default(),
            ..Default::default()
        }
    }

    #[tokio::test]
    async fn test_valid_schema_no_warnings() {
        let introspector = MockIntrospector::new(DatabaseType::PostgreSQL)
            .with_relation("public", "v_user", fraiseql_core::db::RelationKind::View)
            .with_columns("v_user", vec![("data", "jsonb", false), ("pk_user", "bigint", false)])
            .with_json_samples(
                "v_user",
                "data",
                vec![serde_json::json!({"name": "Alice", "email": "alice@example.com"})],
            );

        let schema = make_schema(
            vec![make_type(
                "User",
                vec![("name", FieldType::String), ("email", FieldType::String)],
            )],
            vec![make_query("users", "User", "v_user")],
        );

        let report = validate_schema_against_database(&schema, &introspector).await.unwrap();
        assert!(
            report.warnings.is_empty(),
            "Expected no warnings, got: {:?}",
            report.warnings.len()
        );
    }

    #[tokio::test]
    async fn test_missing_relation() {
        let introspector = MockIntrospector::new(DatabaseType::PostgreSQL);
        let schema = make_schema(vec![], vec![make_query("users", "User", "v_user")]);

        let report = validate_schema_against_database(&schema, &introspector).await.unwrap();
        assert_eq!(report.warnings.len(), 1);
        assert!(
            matches!(&report.warnings[0], DatabaseWarning::MissingRelation { sql_source, .. } if sql_source == "v_user")
        );
    }

    // #653 (2.14 Phase 03): a `@fraiseql.type`'s declared `sql_source` view that is absent
    // from the DB warns (warn-grade, never fails) under `compile --database`. Synthesized
    // types (empty source) are skipped. The hard `FRAISEQL_VALIDATE_SQL_SOURCES` gate does
    // not probe type sources; this is the only check that surfaces phantom type sources.
    #[tokio::test]
    async fn missing_type_source_warns_and_skips_synthetic_types() {
        let introspector = MockIntrospector::new(DatabaseType::PostgreSQL).with_relation(
            "public",
            "v_order",
            fraiseql_core::db::RelationKind::View,
        );

        // Order is view-backed and its view exists → no warning.
        let order = TypeDefinition {
            sql_source: "v_order".into(),
            ..make_type("Order", vec![("id", FieldType::Id)])
        };
        // Money is an embedded value object the SDK synthesized `v_money` for → one warning.
        let money = TypeDefinition {
            sql_source: "v_money".into(),
            ..make_type("Money", vec![("amount", FieldType::Int)])
        };
        // A synthesized cascade payload (empty sql_source) must be skipped, not warned about.
        let synthetic =
            make_type("CreateOrderPayload", vec![("entity", FieldType::Object("Order".into()))]);

        let schema = make_schema(vec![order, money, synthetic], vec![]);
        let report = validate_schema_against_database(&schema, &introspector).await.unwrap();

        let type_warnings: Vec<_> = report
            .warnings
            .iter()
            .filter(|w| matches!(w, DatabaseWarning::MissingTypeSource { .. }))
            .collect();
        assert_eq!(
            type_warnings.len(),
            1,
            "only the phantom type source warns: {:?}",
            report.warnings
        );
        assert!(
            matches!(&type_warnings[0], DatabaseWarning::MissingTypeSource { type_name, sql_source }
                if type_name == "Money" && sql_source == "v_money")
        );
        assert!(
            type_warnings[0].to_string().contains("embedded value object"),
            "message points at the real fix: {}",
            type_warnings[0]
        );
    }

    /// The type-source existence check INCLUDES framework-`internal` projections — it
    /// INTENTIONALLY diverges from `is_queryable_entity` (the cascade classifier), which
    /// excludes them (#665). A change-log projection whose backing view is absent
    /// (`EntityChangeLog` → `v_entity_change_log`) is exactly #569's failure mode ("no
    /// install path; every mutation fails on a fresh stack"), so the validator MUST still
    /// flag it — surfacing that missing view is the whole point of this check.
    ///
    /// Pinned as a TRIPWIRE: a future DRY pass that "unifies" this predicate with the
    /// cascade classifier — adding `!ty.internal` here — deletes the #569 signal, and must
    /// fail this test instead of passing silently. Do NOT satisfy it by excluding internal
    /// types; the `internal` exemption belongs to cascade classification only.
    #[tokio::test]
    async fn validator_checks_internal_projection_view_existence() {
        // The database has the user entity's view but NOT the change-log view.
        let introspector = MockIntrospector::new(DatabaseType::PostgreSQL).with_relation(
            "public",
            "v_user",
            fraiseql_core::db::RelationKind::View,
        );

        let user = TypeDefinition {
            sql_source: "v_user".into(),
            ..make_type("User", vec![("id", FieldType::Id)])
        };
        // A framework-`internal` change-log projection whose view is absent from the DB.
        let change_log = TypeDefinition {
            sql_source: "v_entity_change_log".into(),
            internal: true,
            ..make_type("EntityChangeLog", vec![("id", FieldType::Id)])
        };

        let schema = make_schema(vec![user, change_log], vec![]);
        let report = validate_schema_against_database(&schema, &introspector).await.unwrap();

        let flagged = report
            .warnings
            .iter()
            .filter(|w| matches!(w, DatabaseWarning::MissingTypeSource { type_name, .. } if type_name == "EntityChangeLog"))
            .count();
        assert_eq!(
            flagged, 1,
            "the internal projection's missing view MUST still be flagged (#569): {:?}",
            report.warnings
        );
    }

    #[tokio::test]
    async fn test_missing_additional_view() {
        let introspector = MockIntrospector::new(DatabaseType::PostgreSQL)
            .with_relation("public", "v_user", fraiseql_core::db::RelationKind::View)
            .with_columns("v_user", vec![("data", "jsonb", false)]);

        let mut query = make_query("users", "User", "v_user");
        query.additional_views = vec!["v_missing".to_string()];

        let schema = make_schema(vec![], vec![query]);

        let report = validate_schema_against_database(&schema, &introspector).await.unwrap();
        assert_eq!(report.warnings.len(), 1);
        assert!(
            matches!(&report.warnings[0], DatabaseWarning::MissingAdditionalView { view_name, .. } if view_name == "v_missing")
        );
    }

    #[tokio::test]
    async fn test_missing_jsonb_column() {
        let introspector = MockIntrospector::new(DatabaseType::PostgreSQL)
            .with_relation("public", "v_user", fraiseql_core::db::RelationKind::View)
            .with_columns("v_user", vec![("pk_user", "bigint", false)]);

        let schema = make_schema(vec![], vec![make_query("users", "User", "v_user")]);

        let report = validate_schema_against_database(&schema, &introspector).await.unwrap();
        assert_eq!(report.warnings.len(), 1);
        assert!(
            matches!(&report.warnings[0], DatabaseWarning::MissingJsonColumn { column_name, .. } if column_name == "data")
        );
    }

    #[tokio::test]
    async fn test_wrong_json_column_type() {
        let introspector = MockIntrospector::new(DatabaseType::PostgreSQL)
            .with_relation("public", "v_user", fraiseql_core::db::RelationKind::View)
            .with_columns("v_user", vec![("data", "text", false)]);

        let schema = make_schema(vec![], vec![make_query("users", "User", "v_user")]);

        let report = validate_schema_against_database(&schema, &introspector).await.unwrap();
        assert_eq!(report.warnings.len(), 1);
        assert!(
            matches!(&report.warnings[0], DatabaseWarning::WrongJsonColumnType { actual_type, .. } if actual_type == "text")
        );
    }

    #[tokio::test]
    async fn test_missing_cursor_column() {
        let introspector = MockIntrospector::new(DatabaseType::PostgreSQL)
            .with_relation("public", "v_user", fraiseql_core::db::RelationKind::View)
            .with_columns("v_user", vec![("data", "jsonb", false)]);

        let mut query = make_query("users", "User", "v_user");
        query.relay = true;
        query.relay_cursor_column = Some("pk_user".to_string());

        let schema = make_schema(vec![], vec![query]);

        let report = validate_schema_against_database(&schema, &introspector).await.unwrap();
        assert!(report.warnings.iter().any(|w| matches!(w, DatabaseWarning::MissingCursorColumn { column_name, .. } if column_name == "pk_user")));
    }

    #[tokio::test]
    async fn test_missing_json_key() {
        let introspector = MockIntrospector::new(DatabaseType::PostgreSQL)
            .with_relation("public", "v_user", fraiseql_core::db::RelationKind::View)
            .with_columns("v_user", vec![("data", "jsonb", false)])
            .with_json_samples("v_user", "data", vec![serde_json::json!({"name": "Alice"})]);

        let schema = make_schema(
            vec![make_type(
                "User",
                vec![("name", FieldType::String), ("email", FieldType::String)],
            )],
            vec![make_query("users", "User", "v_user")],
        );

        let report = validate_schema_against_database(&schema, &introspector).await.unwrap();
        // The warning names the owning GraphQL type so the field is locatable (#384 Gap C).
        assert!(report.warnings.iter().any(|w| matches!(
            w,
            DatabaseWarning::MissingJsonKey { field_name, type_name, .. }
                if field_name == "email" && type_name == "User"
        )));
    }

    #[tokio::test]
    async fn test_arg_type_convertibility_warning() {
        // An `Int` argument that resolves to a `uuid` native column is flagged (#384 Gap B):
        // the runtime predicate `WHERE id = $1` would error / never match.
        let introspector = MockIntrospector::new(DatabaseType::PostgreSQL)
            .with_relation("public", "v_order", fraiseql_core::db::RelationKind::View)
            .with_columns("v_order", vec![("data", "jsonb", false), ("id", "uuid", false)])
            .with_json_samples("v_order", "data", vec![serde_json::json!({"total": 10})]);

        let mut query = make_query("orders", "Order", "v_order");
        query.arguments = vec![ArgumentDefinition::new("id", FieldType::Int)];
        let schema =
            make_schema(vec![make_type("Order", vec![("total", FieldType::Int)])], vec![query]);

        let report = validate_schema_against_database(&schema, &introspector).await.unwrap();
        assert!(report.warnings.iter().any(|w| matches!(
            w,
            DatabaseWarning::TypeConvertibility { arg_name, graphql_type, column_type, .. }
                if arg_name == "id" && graphql_type == "Int" && column_type == "uuid"
        )));
    }

    #[tokio::test]
    async fn test_id_arg_against_uuid_column_no_convertibility_warning() {
        // The common `id: ID` filtering a uuid column must NOT warn — `ID` is permissive.
        let introspector = MockIntrospector::new(DatabaseType::PostgreSQL)
            .with_relation("public", "v_order", fraiseql_core::db::RelationKind::View)
            .with_columns("v_order", vec![("data", "jsonb", false), ("id", "uuid", false)])
            .with_json_samples("v_order", "data", vec![serde_json::json!({"total": 10})]);

        let mut query = make_query("orders", "Order", "v_order");
        query.arguments = vec![ArgumentDefinition::new("id", FieldType::Id)];
        let schema =
            make_schema(vec![make_type("Order", vec![("total", FieldType::Int)])], vec![query]);

        let report = validate_schema_against_database(&schema, &introspector).await.unwrap();
        assert!(
            !report
                .warnings
                .iter()
                .any(|w| matches!(w, DatabaseWarning::TypeConvertibility { .. }))
        );
    }

    #[tokio::test]
    async fn test_empty_json_sample_no_l3_warnings() {
        let introspector = MockIntrospector::new(DatabaseType::PostgreSQL)
            .with_relation("public", "v_user", fraiseql_core::db::RelationKind::View)
            .with_columns("v_user", vec![("data", "jsonb", false)]);

        let schema = make_schema(
            vec![make_type("User", vec![("name", FieldType::String)])],
            vec![make_query("users", "User", "v_user")],
        );

        let report = validate_schema_against_database(&schema, &introspector).await.unwrap();
        // No L3 warnings because no sample data
        assert!(
            !report
                .warnings
                .iter()
                .any(|w| matches!(w, DatabaseWarning::MissingJsonKey { .. }))
        );
    }

    #[tokio::test]
    async fn test_schema_qualified_match() {
        let introspector = MockIntrospector::new(DatabaseType::PostgreSQL)
            .with_relation("etl_log", "v_foo", fraiseql_core::db::RelationKind::View)
            .with_columns("v_foo", vec![("data", "jsonb", false)]);

        let schema = make_schema(vec![], vec![make_query("foos", "Foo", "etl_log.v_foo")]);

        let report = validate_schema_against_database(&schema, &introspector).await.unwrap();
        // Should match
        assert!(
            !report
                .warnings
                .iter()
                .any(|w| matches!(w, DatabaseWarning::MissingRelation { .. }))
        );
    }

    #[tokio::test]
    async fn test_schema_qualified_wrong_schema() {
        let introspector = MockIntrospector::new(DatabaseType::PostgreSQL).with_relation(
            "public",
            "v_foo",
            fraiseql_core::db::RelationKind::View,
        );

        let schema = make_schema(vec![], vec![make_query("foos", "Foo", "etl_log.v_foo")]);

        let report = validate_schema_against_database(&schema, &introspector).await.unwrap();
        assert_eq!(report.warnings.len(), 1);
        assert!(
            matches!(&report.warnings[0], DatabaseWarning::MissingRelation { sql_source, .. } if sql_source == "etl_log.v_foo")
        );
    }

    #[tokio::test]
    async fn test_mutation_missing_function_reported_as_missing_function() {
        // A mutation's sql_source is a FUNCTION — a missing one is MissingFunction,
        // not MissingRelation (#485). The mock has no functions registered.
        let introspector = MockIntrospector::new(DatabaseType::PostgreSQL);

        let mut schema = make_schema(vec![], vec![]);
        schema.mutations.push(MutationDefinition {
            name: "createUser".to_string(),
            sql_source: Some("fn_create_user".to_string()),
            ..MutationDefinition::new("createUser", "User")
        });

        let report = validate_schema_against_database(&schema, &introspector).await.unwrap();
        assert_eq!(report.warnings.len(), 1);
        assert!(
            matches!(&report.warnings[0], DatabaseWarning::MissingFunction { sql_source, .. } if sql_source == "fn_create_user"),
            "got {:?}",
            report.warnings
        );
    }

    #[tokio::test]
    async fn test_mutation_function_not_probed_as_relation() {
        // The fix: a mutation backed by a real FUNCTION that is absent from the
        // relation catalog must NOT false-fail (the old bug probed it as a relation).
        let introspector =
            MockIntrospector::new(DatabaseType::PostgreSQL).with_function("fn_create_user");

        let mut schema = make_schema(vec![], vec![]);
        schema.mutations.push(MutationDefinition {
            name: "createUser".to_string(),
            sql_source: Some("fn_create_user".to_string()),
            ..MutationDefinition::new("createUser", "User")
        });

        let report = validate_schema_against_database(&schema, &introspector).await.unwrap();
        assert!(
            report.warnings.is_empty(),
            "backed function must be clean, got {:?}",
            report.warnings
        );
    }

    #[tokio::test]
    async fn test_query_no_sql_source_skipped() {
        let introspector = MockIntrospector::new(DatabaseType::PostgreSQL);

        let mut query = make_query("users", "User", "v_user");
        query.sql_source = None;

        let schema = make_schema(vec![], vec![query]);

        let report = validate_schema_against_database(&schema, &introspector).await.unwrap();
        assert!(report.warnings.is_empty());
    }

    #[tokio::test]
    async fn test_multiple_samples_merge_keys() {
        let introspector = MockIntrospector::new(DatabaseType::PostgreSQL)
            .with_relation("public", "v_user", fraiseql_core::db::RelationKind::View)
            .with_columns("v_user", vec![("data", "jsonb", false)])
            .with_json_samples(
                "v_user",
                "data",
                vec![
                    serde_json::json!({"name": "Alice", "email": "alice@example.com"}),
                    serde_json::json!({"email": "bob@example.com", "age": 30}),
                ],
            );

        let schema = make_schema(
            vec![make_type(
                "User",
                vec![
                    ("name", FieldType::String),
                    ("email", FieldType::String),
                    ("age", FieldType::Int),
                ],
            )],
            vec![make_query("users", "User", "v_user")],
        );

        let report = validate_schema_against_database(&schema, &introspector).await.unwrap();
        // All keys present across both samples
        assert!(
            !report
                .warnings
                .iter()
                .any(|w| matches!(w, DatabaseWarning::MissingJsonKey { .. }))
        );
    }

    /// #485 caser-drift fix: the L3 JSON-key check derives the expected key with
    /// the canonical acronym/digit-aware caser, so an acronym field (`httpResponse`
    /// → `http_response`) matches the stored key instead of crying wolf with the
    /// old uppercase-only `h_t_t_p_response`.
    #[tokio::test]
    async fn test_acronym_field_no_false_missing_json_key() {
        let introspector = MockIntrospector::new(DatabaseType::PostgreSQL)
            .with_relation("public", "v_log", fraiseql_core::db::RelationKind::View)
            .with_columns("v_log", vec![("data", "jsonb", false)])
            .with_json_samples(
                "v_log",
                "data",
                vec![serde_json::json!({"http_response": 200, "dns_1_id": "x"})],
            );

        let schema = make_schema(
            vec![make_type(
                "Log",
                vec![
                    ("httpResponse", FieldType::Int),
                    ("dns1Id", FieldType::String),
                ],
            )],
            vec![make_query("logs", "Log", "v_log")],
        );

        let report = validate_schema_against_database(&schema, &introspector).await.unwrap();
        assert!(
            !report
                .warnings
                .iter()
                .any(|w| matches!(w, DatabaseWarning::MissingJsonKey { .. })),
            "acronym/digit fields must not false-flag MissingJsonKey, got {:?}",
            report.warnings
        );
    }

    #[test]
    fn test_is_json_type_postgres() {
        assert!(is_json_type("jsonb", DatabaseType::PostgreSQL));
        assert!(is_json_type("json", DatabaseType::PostgreSQL));
        assert!(!is_json_type("text", DatabaseType::PostgreSQL));
    }

    #[test]
    fn test_display_warnings() {
        let warning = DatabaseWarning::MissingRelation {
            query_name: "users".to_string(),
            sql_source: "v_user".to_string(),
        };
        assert_eq!(
            warning.to_string(),
            "query `users`: sql_source `v_user` does not exist in database"
        );
    }

    // ── #1303 the --database sharpening ─────────────────────────────────────

    /// A `users` query over `v_user`, with the compiler's offline answer already on
    /// it — which is the state every paginating query reaches the validator in.
    fn paginating_query(order: Option<PaginationOrder>) -> QueryDefinition {
        let mut q = make_query("users", "User", "v_user");
        q.pagination_order = order;
        q
    }

    fn paginating_schema(order: Option<PaginationOrder>) -> CompiledSchema {
        make_schema(
            vec![make_type("User", vec![("name", FieldType::String)])],
            vec![paginating_query(order)],
        )
    }

    /// A relation exposing both: `pk_user` wins, because it is the cheaper of the
    /// two (1.7x against 4.2x) *and* the column relay already pages on.
    #[tokio::test]
    async fn a_derived_identity_is_sharpened_to_the_pk_column() {
        let introspector = MockIntrospector::new(DatabaseType::PostgreSQL)
            .with_relation("public", "v_user", fraiseql_core::db::RelationKind::View)
            .with_columns(
                "v_user",
                vec![
                    ("data", "jsonb", false),
                    ("id", "uuid", false),
                    ("pk_user", "bigint", false),
                ],
            )
            .with_json_samples("v_user", "data", vec![serde_json::json!({"name": "Alice"})]);

        let report = validate_schema_against_database(
            &paginating_schema(Some(PaginationOrder::Identity)),
            &introspector,
        )
        .await
        .unwrap();

        assert_eq!(
            report.pagination_orders.get("users"),
            Some(&PaginationOrder::Column("pk_user".into()))
        );
    }

    /// No `pk_user`, but the `id` column the derived identity reads (4.2x the unordered plan
    /// at a deep offset, against `pk_user`'s 1.7x).
    #[tokio::test]
    async fn a_relation_with_only_an_id_column_keeps_the_identity() {
        let introspector = MockIntrospector::new(DatabaseType::PostgreSQL)
            .with_relation("public", "v_user", fraiseql_core::db::RelationKind::View)
            .with_columns("v_user", vec![("data", "jsonb", false), ("id", "uuid", false)])
            .with_json_samples("v_user", "data", vec![serde_json::json!({"name": "Alice"})]);

        let report = validate_schema_against_database(
            &paginating_schema(Some(PaginationOrder::Identity)),
            &introspector,
        )
        .await
        .unwrap();

        // The derived identity already reads `id` (#1569): nothing to sharpen, nothing to say.
        assert!(report.pagination_orders.is_empty(), "{:?}", report.pagination_orders);
        assert!(
            !report
                .warnings
                .iter()
                .any(|w| matches!(w, DatabaseWarning::MissingIdentityColumn { .. })),
            "{:?}",
            report.warnings
        );
    }

    /// Neither column: the identity is never read out of the document (#1569), so the
    /// compiled `ORDER BY` would fail at the first paged read. A drift error.
    #[tokio::test]
    async fn a_relation_with_neither_identity_column_is_refused() {
        let introspector = MockIntrospector::new(DatabaseType::PostgreSQL)
            .with_relation("public", "v_user", fraiseql_core::db::RelationKind::View)
            .with_columns("v_user", vec![("data", "jsonb", false)])
            .with_json_samples("v_user", "data", vec![serde_json::json!({"name": "Alice"})]);

        let report = validate_schema_against_database(
            &paginating_schema(Some(PaginationOrder::Identity)),
            &introspector,
        )
        .await
        .unwrap();

        assert!(report.pagination_orders.is_empty(), "{:?}", report.pagination_orders);
        let finding = report
            .warnings
            .iter()
            .find(|w| matches!(w, DatabaseWarning::MissingIdentityColumn { .. }))
            .unwrap_or_else(|| {
                panic!("expected a missing-identity finding, got {:?}", report.warnings)
            });
        assert_eq!(finding.severity(), Severity::Error, "an ORDER BY that cannot run is drift");
        assert!(finding.to_string().contains("pk_user"), "{finding}");
    }

    /// An authored column is never replaced — only its existence is checked.
    #[tokio::test]
    async fn an_authored_column_is_checked_but_never_overridden() {
        let introspector = MockIntrospector::new(DatabaseType::PostgreSQL)
            .with_relation("public", "v_user", fraiseql_core::db::RelationKind::View)
            .with_columns(
                "v_user",
                vec![
                    ("data", "jsonb", false),
                    ("pk_user", "bigint", false),
                    ("email", "text", false),
                ],
            )
            .with_json_samples("v_user", "data", vec![serde_json::json!({"name": "Alice"})]);

        let report = validate_schema_against_database(
            &paginating_schema(Some(PaginationOrder::Column("email".into()))),
            &introspector,
        )
        .await
        .unwrap();

        assert!(
            report.pagination_orders.is_empty(),
            "a cheaper column exists on the relation, and the author's choice still stands: {:?}",
            report.pagination_orders
        );
        assert!(report.warnings.is_empty(), "{:?}", report.warnings);
    }

    /// A declared column the relation does not carry fails the compile, exactly as
    /// a missing relay cursor column does: it is rendered into ORDER BY.
    #[tokio::test]
    async fn a_declared_column_that_does_not_exist_is_a_drift_error() {
        let introspector = MockIntrospector::new(DatabaseType::PostgreSQL)
            .with_relation("public", "v_user", fraiseql_core::db::RelationKind::View)
            .with_columns("v_user", vec![("data", "jsonb", false)])
            .with_json_samples("v_user", "data", vec![serde_json::json!({"name": "Alice"})]);

        let report = validate_schema_against_database(
            &paginating_schema(Some(PaginationOrder::Column("pk_user".into()))),
            &introspector,
        )
        .await
        .unwrap();

        let finding = report
            .warnings
            .iter()
            .find(|w| matches!(w, DatabaseWarning::MissingPaginationColumn { .. }))
            .unwrap_or_else(|| {
                panic!("expected a missing-column finding, got {:?}", report.warnings)
            });
        assert_eq!(finding.severity(), Severity::Error);
        assert!(finding.to_string().contains("pk_user"), "{finding}");
    }

    /// A query that declared `none` gets no ordering back, and no advice about one.
    #[tokio::test]
    async fn a_query_that_opted_out_is_left_alone() {
        let introspector = MockIntrospector::new(DatabaseType::PostgreSQL)
            .with_relation("public", "v_user", fraiseql_core::db::RelationKind::View)
            .with_columns("v_user", vec![("data", "jsonb", false), ("pk_user", "bigint", false)])
            .with_view_definition("v_user", " SELECT data FROM tb_user ORDER BY data ->> 'name'")
            .with_json_samples("v_user", "data", vec![serde_json::json!({"name": "Alice"})]);

        let report = validate_schema_against_database(&paginating_schema(None), &introspector)
            .await
            .unwrap();

        assert!(report.pagination_orders.is_empty(), "{:?}", report.pagination_orders);
        assert!(
            report.warnings.is_empty(),
            "the author already answered the question this view raises: {:?}",
            report.warnings
        );
    }

    /// The one case the default ordering makes worse, reported at compile time
    /// rather than discovered as a reordered page.
    #[tokio::test]
    async fn a_self_ordering_view_asks_the_author_to_declare() {
        let introspector = MockIntrospector::new(DatabaseType::PostgreSQL)
            .with_relation("public", "v_user", fraiseql_core::db::RelationKind::View)
            .with_columns("v_user", vec![("data", "jsonb", false), ("pk_user", "bigint", false)])
            .with_view_definition(
                "v_user",
                " SELECT data FROM tb_user ORDER BY (data ->> 'created_at'::text)",
            )
            .with_json_samples("v_user", "data", vec![serde_json::json!({"name": "Alice"})]);

        let report = validate_schema_against_database(
            &paginating_schema(Some(PaginationOrder::Identity)),
            &introspector,
        )
        .await
        .unwrap();

        let finding = report
            .warnings
            .iter()
            .find(|w| matches!(w, DatabaseWarning::SelfOrderingView { .. }))
            .unwrap_or_else(|| {
                panic!("expected a self-ordering finding, got {:?}", report.warnings)
            });
        assert_eq!(finding.severity(), Severity::Warn);
        assert!(finding.to_string().contains("none"), "the remedy must be named: {finding}");
    }

    /// Every `DatabaseIntrospector` method is delegated by `AnyIntrospector`.
    ///
    /// `AnyIntrospector` is the enum the real `compile --database` runs through, and
    /// every method with a defaulted trait body it forgets to forward silently
    /// becomes that default — `Ok(None)` — for the whole compiler. The check that
    /// depends on it then reports nothing, forever, and looks exactly like a check
    /// over a database that has nothing to report. It has happened once already:
    /// `function_exists` carries a comment saying so.
    ///
    /// Read from source rather than exercised, because the alternative needs a live
    /// pool: `AnyIntrospector`'s only variant wraps one.
    #[test]
    fn any_introspector_forwards_every_trait_method() {
        let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .parent()
            .expect("crates/")
            .join("fraiseql-db/src/introspector.rs");
        let trait_src = std::fs::read_to_string(&root)
            .unwrap_or_else(|e| panic!("cannot read {}: {e}", root.display()));

        // The trait body is everything from its declaration to the file's last `}`.
        let trait_body = trait_src
            .split_once("pub trait DatabaseIntrospector")
            .expect("the trait moved; this gate reads it by name")
            .1;
        let methods: Vec<&str> = trait_body
            .lines()
            .filter_map(|l| {
                let l = l.trim_start();
                let rest = l.strip_prefix("async fn ").or_else(|| l.strip_prefix("fn "))?;
                rest.split(['(', '<']).next()
            })
            .collect();
        assert!(methods.len() >= 8, "only found {methods:?} — the parse broke, not the impl");

        let validator = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("src/schema/database_validator.rs");
        let impl_src = std::fs::read_to_string(&validator).expect("read database_validator.rs");
        let impl_body = impl_src
            .split_once("impl DatabaseIntrospector for AnyIntrospector")
            .expect("the impl moved; this gate reads it by name")
            .1;

        let missing: Vec<&&str> =
            methods.iter().filter(|m| !impl_body.contains(&format!("fn {m}("))).collect();
        assert!(
            missing.is_empty(),
            "AnyIntrospector does not forward {missing:?}. Each one silently inherits the \
             trait default for every `compile --database` run, which reads as a database \
             with nothing to report."
        );
    }

    /// A view with no ORDER BY raises nothing — the finding above discriminates on
    /// the body, not on the presence of a body.
    #[tokio::test]
    async fn a_plain_view_raises_no_self_ordering_finding() {
        let introspector = MockIntrospector::new(DatabaseType::PostgreSQL)
            .with_relation("public", "v_user", fraiseql_core::db::RelationKind::View)
            .with_columns("v_user", vec![("data", "jsonb", false), ("pk_user", "bigint", false)])
            .with_view_definition("v_user", " SELECT data FROM tb_user")
            .with_json_samples("v_user", "data", vec![serde_json::json!({"name": "Alice"})]);

        let report = validate_schema_against_database(
            &paginating_schema(Some(PaginationOrder::Identity)),
            &introspector,
        )
        .await
        .unwrap();

        assert!(
            !report
                .warnings
                .iter()
                .any(|w| matches!(w, DatabaseWarning::SelfOrderingView { .. })),
            "{:?}",
            report.warnings
        );
    }

    // ── #1571: a sorted or filtered temporal key read out of a TVIEW's document ──

    /// `events` over `tv_event`, returning `Event { occurredAt: <ty> }`, with `auto_params`
    /// and the relation's extra columns as given.
    async fn temporal_report(
        source: &str,
        ty: FieldType,
        auto_params: AutoParams,
        extra_columns: Vec<(&str, &str, bool)>,
        mapped_by_argument: bool,
    ) -> Vec<DatabaseWarning> {
        let mut columns = vec![("data", "jsonb", false), ("id", "uuid", false)];
        columns.extend(extra_columns);
        let introspector = MockIntrospector::new(DatabaseType::PostgreSQL)
            .with_relation("public", source, fraiseql_core::db::RelationKind::Table)
            .with_columns(source, columns)
            .with_json_samples(source, "data", vec![serde_json::json!({"occurredAt": "x"})]);
        let mut query = make_query("events", "Event", source);
        query.auto_params = auto_params;
        if mapped_by_argument {
            query.arguments.push(ArgumentDefinition::new("occurredAt", FieldType::DateTime));
        }
        let schema = make_schema(vec![make_type("Event", vec![("occurredAt", ty)])], vec![query]);
        validate_schema_against_database(&schema, &introspector).await.unwrap().warnings
    }

    fn sorting() -> AutoParams {
        AutoParams {
            has_order_by: true,
            ..AutoParams::default()
        }
    }

    fn temporal_advice(warnings: &[DatabaseWarning]) -> Vec<(&str, &str, &str, bool)> {
        warnings
            .iter()
            .filter_map(|w| match w {
                DatabaseWarning::TemporalKeyInDocument {
                    query_name,
                    field,
                    column,
                    column_exists,
                    ..
                } => Some((query_name.as_str(), field.as_str(), column.as_str(), *column_exists)),
                _ => None,
            })
            .collect()
    }

    #[tokio::test]
    async fn a_sorted_datetime_read_from_a_tview_document_is_advised() {
        let warnings =
            temporal_report("tv_event", FieldType::DateTime, sorting(), vec![], false).await;
        assert_eq!(
            temporal_advice(&warnings),
            vec![("events", "occurredAt", "occurred_at", false)]
        );
        let advice = warnings
            .iter()
            .find(|w| matches!(w, DatabaseWarning::TemporalKeyInDocument { .. }))
            .unwrap();
        assert_eq!(advice.severity(), Severity::Warn, "advice, never a failed compile");
    }

    #[tokio::test]
    async fn a_filtered_date_is_advised_too() {
        let filtering = AutoParams {
            has_where: true,
            ..AutoParams::default()
        };
        let warnings = temporal_report("tv_event", FieldType::Date, filtering, vec![], false).await;
        assert_eq!(
            temporal_advice(&warnings),
            vec![("events", "occurredAt", "occurred_at", false)]
        );
    }

    #[tokio::test]
    async fn a_column_the_query_does_not_map_yet_is_named_as_existing() {
        let column = vec![("occurred_at", "timestamp with time zone", false)];
        let warnings =
            temporal_report("tv_event", FieldType::DateTime, sorting(), column, false).await;
        assert_eq!(temporal_advice(&warnings), vec![("events", "occurredAt", "occurred_at", true)]);
    }

    #[tokio::test]
    async fn a_temporal_key_mapped_to_its_native_column_is_not_advised() {
        let column = vec![("occurred_at", "timestamp with time zone", false)];
        let warnings =
            temporal_report("tv_event", FieldType::DateTime, sorting(), column, true).await;
        assert!(temporal_advice(&warnings).is_empty(), "{warnings:?}");
    }

    #[tokio::test]
    async fn a_query_that_neither_sorts_nor_filters_is_not_advised() {
        let warnings =
            temporal_report("tv_event", FieldType::DateTime, AutoParams::default(), vec![], false)
                .await;
        assert!(temporal_advice(&warnings).is_empty(), "{warnings:?}");
    }

    #[tokio::test]
    async fn a_non_temporal_key_is_not_advised() {
        let warnings =
            temporal_report("tv_event", FieldType::String, sorting(), vec![], false).await;
        assert!(temporal_advice(&warnings).is_empty(), "{warnings:?}");
    }

    #[tokio::test]
    async fn a_relation_that_is_not_a_tview_is_not_advised() {
        let warnings =
            temporal_report("v_event", FieldType::DateTime, sorting(), vec![], false).await;
        assert!(temporal_advice(&warnings).is_empty(), "{warnings:?}");
    }
}

mod merger_tests {
    use std::fs;

    use tempfile::TempDir;

    use super::super::merger::*;

    #[test]
    fn test_merge_toml_only() {
        let toml_content = r#"
[schema]
name = "test"
version = "1.0.0"
database_target = "postgresql"

[database]
url = "postgresql://localhost/test"

[types.User]
sql_source = "v_user"

[types.User.fields.id]
type = "ID"

[types.User.fields.name]
type = "String"

[queries.users]
return_type = "User"
return_array = true
sql_source = "v_user"
"#;

        // Write temp file
        let tmp = tempfile::NamedTempFile::with_suffix(".toml").unwrap();
        std::fs::write(tmp.path(), toml_content).unwrap();

        // Merge
        let result = SchemaMerger::merge_toml_only(tmp.path().to_str().unwrap());
        result.unwrap_or_else(|e| panic!("expected Ok from merge_toml_only: {e}"));
    }

    #[test]
    fn test_merge_with_includes() -> anyhow::Result<()> {
        let temp_dir = TempDir::new()?;

        // Create schema files
        let user_types = serde_json::json!({
            "types": [{"name": "User", "fields": []}],
            "queries": [],
            "mutations": []
        });
        fs::write(temp_dir.path().join("user.json"), user_types.to_string())?;

        let post_types = serde_json::json!({
            "types": [{"name": "Post", "fields": []}],
            "queries": [],
            "mutations": []
        });
        fs::write(temp_dir.path().join("post.json"), post_types.to_string())?;

        // Create TOML with includes
        let toml_content = format!(
            r#"
[schema]
name = "test"
version = "1.0.0"
database_target = "postgresql"

[database]
url = "postgresql://localhost/test"

[includes]
types = ["{}/*.json"]
queries = []
mutations = []
"#,
            temp_dir.path().to_string_lossy()
        );

        let toml_path = temp_dir.path().join("fraiseql.toml");
        fs::write(&toml_path, toml_content)?;

        // Merge
        let result = SchemaMerger::merge_with_includes(toml_path.to_str().unwrap());
        let schema = result.unwrap_or_else(|e| panic!("expected Ok from merge_with_includes: {e}"));
        assert_eq!(schema.types.len(), 2);

        Ok(())
    }

    #[test]
    fn test_merge_with_includes_missing_files() -> anyhow::Result<()> {
        let temp_dir = TempDir::new()?;

        let toml_content = r#"
[schema]
name = "test"
version = "1.0.0"
database_target = "postgresql"

[database]
url = "postgresql://localhost/test"

[includes]
types = ["/nonexistent/path/*.json"]
queries = []
mutations = []
"#;

        let toml_path = temp_dir.path().join("fraiseql.toml");
        fs::write(&toml_path, toml_content)?;

        // A configured `[includes]` pattern that matches nothing must FAIL the compile.
        //
        // This test previously asserted the opposite — "Should succeed but with no files
        // loaded (glob matches nothing)" — which codified the #723 fail-open as the expected
        // result. Succeeding there means the user configured a schema source, the compile
        // reported success, and none of the types they were including are in the artifact.
        // An empty *list* of patterns is still fine (nothing configured); a pattern that
        // resolves to nothing is a typo or a build-ordering mistake, and it is now loud.
        let err = SchemaMerger::merge_with_includes(toml_path.to_str().unwrap())
            .expect_err("a configured include pattern matching no files must fail the compile");

        let msg = format!("{err:#}");
        assert!(
            msg.contains("/nonexistent/path/*.json"),
            "the error must name the pattern that matched nothing; got: {msg}"
        );

        Ok(())
    }

    #[test]
    fn test_merge_from_domains() -> anyhow::Result<()> {
        let temp_dir = TempDir::new()?;
        let schema_dir = temp_dir.path().join("schema");
        fs::create_dir(&schema_dir)?;

        // Create domain structure
        fs::create_dir(schema_dir.join("auth"))?;
        fs::create_dir(schema_dir.join("products"))?;

        let auth_types = serde_json::json!({
            "types": [{"name": "User", "fields": []}],
            "queries": [{"name": "getUser", "return_type": "User"}],
            "mutations": []
        });
        fs::write(schema_dir.join("auth/types.json"), auth_types.to_string())?;

        let product_types = serde_json::json!({
            "types": [{"name": "Product", "fields": []}],
            "queries": [{"name": "getProduct", "return_type": "Product"}],
            "mutations": []
        });
        fs::write(schema_dir.join("products/types.json"), product_types.to_string())?;

        // Create TOML with domain discovery (use absolute path)
        let schema_dir_str = schema_dir.to_string_lossy().to_string();
        let toml_content = format!(
            r#"
[schema]
name = "test"
version = "1.0.0"
database_target = "postgresql"

[database]
url = "postgresql://localhost/test"

[domain_discovery]
enabled = true
root_dir = "{schema_dir_str}"
"#
        );

        let toml_path = temp_dir.path().join("fraiseql.toml");
        fs::write(&toml_path, toml_content)?;

        // Merge
        let schema = SchemaMerger::merge_from_domains(toml_path.to_str().unwrap())
            .unwrap_or_else(|e| panic!("expected Ok from merge_from_domains: {e}"));

        // Should have 2 types (from both domains)
        assert_eq!(schema.types.len(), 2);
        // Should have 2 queries (from both domains)
        assert_eq!(schema.queries.len(), 2);

        Ok(())
    }

    #[test]
    fn test_merge_from_domains_alphabetical_order() -> anyhow::Result<()> {
        let temp_dir = TempDir::new()?;
        let schema_dir = temp_dir.path().join("schema");
        fs::create_dir(&schema_dir)?;

        // Create domains in non-alphabetical order
        fs::create_dir(schema_dir.join("zebra"))?;
        fs::create_dir(schema_dir.join("alpha"))?;
        fs::create_dir(schema_dir.join("middle"))?;

        for domain in &["zebra", "alpha", "middle"] {
            let types = serde_json::json!({
                "types": [{"name": domain.to_uppercase(), "fields": []}],
                "queries": [],
                "mutations": []
            });
            fs::write(schema_dir.join(format!("{domain}/types.json")), types.to_string())?;
        }

        let schema_dir_str = schema_dir.to_string_lossy().to_string();
        let toml_content = format!(
            r#"
[schema]
name = "test"
version = "1.0.0"
database_target = "postgresql"

[database]
url = "postgresql://localhost/test"

[domain_discovery]
enabled = true
root_dir = "{schema_dir_str}"
"#
        );

        let toml_path = temp_dir.path().join("fraiseql.toml");
        fs::write(&toml_path, toml_content)?;

        let schema = SchemaMerger::merge_from_domains(toml_path.to_str().unwrap())
            .unwrap_or_else(|e| panic!("expected Ok from merge_from_domains (alphabetical): {e}"));

        // Types should be loaded in alphabetical order: ALPHA, MIDDLE, ZEBRA
        let type_names: Vec<String> = schema.types.iter().map(|t| t.name.clone()).collect();

        assert_eq!(type_names[0], "ALPHA");
        assert_eq!(type_names[1], "MIDDLE");
        assert_eq!(type_names[2], "ZEBRA");

        Ok(())
    }

    #[test]
    fn test_merge_toml_only_with_validation_config() {
        let toml_content = r#"
[schema]
name = "test"
version = "1.0.0"
database_target = "postgresql"

[database]
url = "postgresql://localhost/test"

[types.User]
sql_source = "v_user"

[types.User.fields.id]
type = "ID"

[validation]
max_query_depth = 3
max_query_complexity = 25
max_page_size = 750
"#;

        let tmp = tempfile::NamedTempFile::with_suffix(".toml").unwrap();
        std::fs::write(tmp.path(), toml_content).unwrap();

        let schema = SchemaMerger::merge_toml_only(tmp.path().to_str().unwrap())
            .unwrap_or_else(|e| panic!("expected Ok from merge_toml_only (with validation): {e}"));

        // validation_config should be populated
        let vc = schema.validation_config.as_ref().expect("validation_config should be set");
        assert_eq!(vc.max_query_depth, Some(3));
        assert_eq!(vc.max_query_complexity, Some(25));
        // #421: the page-size ceiling flows TOML → compiled schema.
        assert_eq!(vc.max_page_size, Some(750));
    }

    #[test]
    fn test_merge_toml_only_without_validation_config() {
        let toml_content = r#"
[schema]
name = "test"
version = "1.0.0"
database_target = "postgresql"

[database]
url = "postgresql://localhost/test"

[types.User]
sql_source = "v_user"

[types.User.fields.id]
type = "ID"
"#;

        let tmp = tempfile::NamedTempFile::with_suffix(".toml").unwrap();
        std::fs::write(tmp.path(), toml_content).unwrap();

        let schema = SchemaMerger::merge_toml_only(tmp.path().to_str().unwrap())
            .unwrap_or_else(|e| panic!("expected Ok from merge_toml_only (no validation): {e}"));

        // validation_config should be None when no [validation] section
        assert!(schema.validation_config.is_none());
    }

    // ── CRUD naming config ─────────────────────────────────────────────────────

    #[test]
    fn pascal_to_snake_single_word() {
        assert_eq!(pascal_to_snake("User"), "user");
    }

    #[test]
    fn pascal_to_snake_compound_type() {
        assert_eq!(pascal_to_snake("UserProfile"), "user_profile");
    }

    #[test]
    fn pascal_to_snake_already_lower() {
        assert_eq!(pascal_to_snake("user"), "user");
    }

    #[test]
    fn pascal_to_snake_three_words() {
        assert_eq!(pascal_to_snake("DnsServerConfig"), "dns_server_config");
    }

    fn write_temp_toml(content: &str) -> tempfile::NamedTempFile {
        let tmp = tempfile::NamedTempFile::with_suffix(".toml").unwrap();
        std::fs::write(tmp.path(), content).unwrap();
        tmp
    }

    #[test]
    fn crud_trinity_resolves_create_mutation() {
        let toml = r#"
[schema]
name = "test"
version = "1.0.0"

[crud]
function_schema = "app"
function_naming = "trinity"

[types.User]
sql_source = "v_user"

[types.User.fields.id]
type = "ID"

[mutations.create_user]
return_type = "User"
operation = "CREATE"
"#;
        let tmp = write_temp_toml(toml);
        let schema = SchemaMerger::merge_toml_only(tmp.path().to_str().unwrap())
            .expect("should merge with crud naming");
        let mutation = schema.mutations.iter().find(|m| m.name == "create_user").unwrap();
        assert_eq!(mutation.sql_source.as_deref(), Some("app.create_user"));
    }

    #[test]
    fn crud_trinity_resolves_pascal_return_type() {
        let toml = r#"
[schema]
name = "test"
version = "1.0.0"

[crud]
function_naming = "trinity"

[types.UserProfile]
sql_source = "v_user_profile"

[types.UserProfile.fields.id]
type = "ID"

[mutations.create_user_profile]
return_type = "UserProfile"
operation = "CREATE"
"#;
        let tmp = write_temp_toml(toml);
        let schema =
            SchemaMerger::merge_toml_only(tmp.path().to_str().unwrap()).expect("should merge");
        let mutation = schema.mutations.iter().find(|m| m.name == "create_user_profile").unwrap();
        assert_eq!(mutation.sql_source.as_deref(), Some("create_user_profile"));
    }

    #[test]
    fn explicit_sql_source_wins_over_crud() {
        let toml = r#"
[schema]
name = "test"
version = "1.0.0"

[crud]
function_schema = "app"
function_naming = "trinity"

[types.User]
sql_source = "v_user"

[types.User.fields.id]
type = "ID"

[mutations.create_user]
return_type = "User"
operation = "CREATE"
sql_source = "custom_create_user_fn"
"#;
        let tmp = write_temp_toml(toml);
        let schema =
            SchemaMerger::merge_toml_only(tmp.path().to_str().unwrap()).expect("should merge");
        let mutation = schema.mutations.iter().find(|m| m.name == "create_user").unwrap();
        assert_eq!(mutation.sql_source.as_deref(), Some("custom_create_user_fn"));
    }

    #[test]
    fn no_sql_source_no_crud_errors_with_mutation_name() {
        let toml = r#"
[schema]
name = "test"
version = "1.0.0"

[types.User]
sql_source = "v_user"

[types.User.fields.id]
type = "ID"

[mutations.create_user]
return_type = "User"
operation = "CREATE"
"#;
        let tmp = write_temp_toml(toml);
        let err = SchemaMerger::merge_toml_only(tmp.path().to_str().unwrap())
            .expect_err("should fail without sql_source and no crud config");
        let msg = format!("{err}");
        assert!(msg.contains("create_user"), "error should name the mutation, got: {msg}");
        assert!(msg.contains("sql_source") || msg.contains("crud"), "got: {msg}");
    }

    #[test]
    fn crud_custom_template_resolved_in_merger() {
        let toml = r#"
[schema]
name = "test"
version = "1.0.0"

[crud]
function_schema = "app"
create_template = "insert_{entity}"

[types.Order]
sql_source = "v_order"

[types.Order.fields.id]
type = "ID"

[mutations.create_order]
return_type = "Order"
operation = "CREATE"
"#;
        let tmp = write_temp_toml(toml);
        let schema =
            SchemaMerger::merge_toml_only(tmp.path().to_str().unwrap()).expect("should merge");
        let mutation = schema.mutations.iter().find(|m| m.name == "create_order").unwrap();
        assert_eq!(mutation.sql_source.as_deref(), Some("app.insert_order"));
    }

    #[test]
    fn crud_update_and_delete_resolved() {
        let toml = r#"
[schema]
name = "test"
version = "1.0.0"

[crud]
function_schema = "app"
function_naming = "trinity"

[types.User]
sql_source = "v_user"

[types.User.fields.id]
type = "ID"

[mutations.update_user]
return_type = "User"
operation = "UPDATE"

[mutations.delete_user]
return_type = "User"
operation = "DELETE"
"#;
        let tmp = write_temp_toml(toml);
        let schema =
            SchemaMerger::merge_toml_only(tmp.path().to_str().unwrap()).expect("should merge");
        let update = schema.mutations.iter().find(|m| m.name == "update_user").unwrap();
        let delete = schema.mutations.iter().find(|m| m.name == "delete_user").unwrap();
        assert_eq!(update.sql_source.as_deref(), Some("app.update_user"));
        assert_eq!(delete.sql_source.as_deref(), Some("app.delete_user"));
    }

    #[test]
    fn toml_mutation_input_style_threads_to_intermediate() {
        use fraiseql_core::schema::InputStyle;
        let toml = r#"
[schema]
name = "test"
version = "1.0.0"

[types.Order]
sql_source = "v_order"

[types.Order.fields.id]
type = "ID"

[mutations.create_order]
return_type = "Order"
operation = "CREATE"
sql_source = "create_order"
input_style = "jsonb"

[mutations.touch_order]
return_type = "Order"
operation = "CREATE"
sql_source = "touch_order"
"#;
        let tmp = write_temp_toml(toml);
        let schema =
            SchemaMerger::merge_toml_only(tmp.path().to_str().unwrap()).expect("should merge");
        // Explicit input_style = "jsonb" threads through, orthogonal to the verb.
        let create = schema.mutations.iter().find(|m| m.name == "create_order").unwrap();
        assert_eq!(create.input_style, InputStyle::Jsonb);
        // Absent input_style defaults to flatten.
        let touch = schema.mutations.iter().find(|m| m.name == "touch_order").unwrap();
        assert_eq!(touch.input_style, InputStyle::Flatten);
    }

    #[test]
    fn toml_mutation_changelog_pre_image_threads_to_intermediate() {
        let toml = r#"
[schema]
name = "test"
version = "1.0.0"

[types.Price]
sql_source = "v_price"

[types.Price.fields.id]
type = "ID"

[mutations.update_price]
return_type = "Price"
operation = "UPDATE"
sql_source = "update_price"
changelog_pre_image = true

[mutations.touch_price]
return_type = "Price"
operation = "UPDATE"
sql_source = "touch_price"
"#;
        let tmp = write_temp_toml(toml);
        let schema =
            SchemaMerger::merge_toml_only(tmp.path().to_str().unwrap()).expect("should merge");
        // Explicit changelog_pre_image = true threads through.
        let update = schema.mutations.iter().find(|m| m.name == "update_price").unwrap();
        assert!(update.changelog_pre_image);
        // Absent changelog_pre_image defaults to false (after-image only).
        let touch = schema.mutations.iter().find(|m| m.name == "touch_price").unwrap();
        assert!(!touch.changelog_pre_image);
    }

    #[test]
    fn toml_mutation_cascade_threads_to_intermediate() {
        let toml = r#"
[schema]
name = "test"
version = "1.0.0"

[types.Post]
sql_source = "v_post"

[types.Post.fields.id]
type = "ID"

[mutations.create_post]
return_type = "Post"
operation = "CREATE"
sql_source = "create_post"
cascade = true

[mutations.touch_post]
return_type = "Post"
operation = "UPDATE"
sql_source = "touch_post"
"#;
        let tmp = write_temp_toml(toml);
        let schema =
            SchemaMerger::merge_toml_only(tmp.path().to_str().unwrap()).expect("should merge");
        // Explicit cascade = true threads through (was rejected by deny_unknown_fields
        // and silently dropped before the flag was wired — eval finding 4).
        let create = schema.mutations.iter().find(|m| m.name == "create_post").unwrap();
        assert!(create.cascade);
        // Absent cascade defaults to false (no cascade surface).
        let touch = schema.mutations.iter().find(|m| m.name == "touch_post").unwrap();
        assert!(!touch.cascade);
    }
}

mod multi_file_loader_tests {
    use std::fs;

    use serde_json::json;
    use tempfile::TempDir;

    use super::super::multi_file_loader::*;

    fn create_test_file(dir: &std::path::Path, name: &str, content: &str) -> anyhow::Result<()> {
        let path = dir.join(name);
        fs::write(path, content)?;
        Ok(())
    }

    #[test]
    fn test_load_single_type_file() -> anyhow::Result<()> {
        let temp_dir = TempDir::new()?;
        let schema = json!({
            "types": [
                {"name": "User", "fields": []}
            ],
            "queries": [],
            "mutations": []
        });
        create_test_file(temp_dir.path(), "types.json", &schema.to_string())?;

        let result = MultiFileLoader::load_from_directory(temp_dir.path().to_str().unwrap())?;

        assert_eq!(result["types"].as_array().unwrap().len(), 1);
        assert_eq!(result["types"][0]["name"], "User");
        assert_eq!(result["queries"].as_array().unwrap().len(), 0);
        assert_eq!(result["mutations"].as_array().unwrap().len(), 0);

        Ok(())
    }

    #[test]
    fn test_merge_multiple_type_files() -> anyhow::Result<()> {
        let temp_dir = TempDir::new()?;

        let user_schema = json!({
            "types": [
                {"name": "User", "fields": []}
            ],
            "queries": [],
            "mutations": []
        });
        create_test_file(temp_dir.path(), "user.json", &user_schema.to_string())?;

        let post_schema = json!({
            "types": [
                {"name": "Post", "fields": []}
            ],
            "queries": [],
            "mutations": []
        });
        create_test_file(temp_dir.path(), "post.json", &post_schema.to_string())?;

        let result = MultiFileLoader::load_from_directory(temp_dir.path().to_str().unwrap())?;

        assert_eq!(result["types"].as_array().unwrap().len(), 2);
        let type_names: Vec<&str> = result["types"]
            .as_array()
            .unwrap()
            .iter()
            .filter_map(|t| t["name"].as_str())
            .collect();
        assert!(type_names.contains(&"User"));
        assert!(type_names.contains(&"Post"));

        Ok(())
    }

    #[test]
    fn test_merge_respects_alphabetical_order() -> anyhow::Result<()> {
        let temp_dir = TempDir::new()?;

        let c_schema = json!({
            "types": [{"name": "C", "fields": []}],
            "queries": [],
            "mutations": []
        });
        create_test_file(temp_dir.path(), "c.json", &c_schema.to_string())?;

        let a_schema = json!({
            "types": [{"name": "A", "fields": []}],
            "queries": [],
            "mutations": []
        });
        create_test_file(temp_dir.path(), "a.json", &a_schema.to_string())?;

        let b_schema = json!({
            "types": [{"name": "B", "fields": []}],
            "queries": [],
            "mutations": []
        });
        create_test_file(temp_dir.path(), "b.json", &b_schema.to_string())?;

        let result = MultiFileLoader::load_from_directory(temp_dir.path().to_str().unwrap())?;

        let type_names: Vec<&str> = result["types"]
            .as_array()
            .unwrap()
            .iter()
            .filter_map(|t| t["name"].as_str())
            .collect();

        // Should be ordered by file load order (a.json, b.json, c.json alphabetically)
        assert_eq!(type_names[0], "A");
        assert_eq!(type_names[1], "B");
        assert_eq!(type_names[2], "C");

        Ok(())
    }

    #[test]
    fn test_merge_queries_and_mutations() -> anyhow::Result<()> {
        let temp_dir = TempDir::new()?;

        let schema = json!({
            "types": [
                {"name": "User", "fields": []}
            ],
            "queries": [
                {"name": "getUser", "return_type": "User"}
            ],
            "mutations": [
                {"name": "createUser", "return_type": "User"}
            ]
        });
        create_test_file(temp_dir.path(), "schema.json", &schema.to_string())?;

        let result = MultiFileLoader::load_from_directory(temp_dir.path().to_str().unwrap())?;

        assert_eq!(result["types"].as_array().unwrap().len(), 1);
        assert_eq!(result["queries"].as_array().unwrap().len(), 1);
        assert_eq!(result["queries"][0]["name"], "getUser");
        assert_eq!(result["mutations"].as_array().unwrap().len(), 1);
        assert_eq!(result["mutations"][0]["name"], "createUser");

        Ok(())
    }

    #[test]
    fn test_nested_directory_structure() -> anyhow::Result<()> {
        let temp_dir = TempDir::new()?;

        // Create nested structure
        fs::create_dir_all(temp_dir.path().join("types"))?;
        fs::create_dir_all(temp_dir.path().join("queries"))?;

        let user_type = json!({
            "types": [{"name": "User", "fields": []}],
            "queries": [],
            "mutations": []
        });
        create_test_file(
            temp_dir.path().join("types").as_path(),
            "user.json",
            &user_type.to_string(),
        )?;

        let post_type = json!({
            "types": [{"name": "Post", "fields": []}],
            "queries": [],
            "mutations": []
        });
        create_test_file(
            temp_dir.path().join("types").as_path(),
            "post.json",
            &post_type.to_string(),
        )?;

        let user_queries = json!({
            "types": [],
            "queries": [{"name": "getUser", "return_type": "User"}],
            "mutations": []
        });
        create_test_file(
            temp_dir.path().join("queries").as_path(),
            "user_queries.json",
            &user_queries.to_string(),
        )?;

        let result = MultiFileLoader::load_from_directory(temp_dir.path().to_str().unwrap())?;

        assert_eq!(result["types"].as_array().unwrap().len(), 2);
        assert_eq!(result["queries"].as_array().unwrap().len(), 1);

        Ok(())
    }

    #[test]
    fn test_duplicate_type_names_error() -> anyhow::Result<()> {
        let temp_dir = TempDir::new()?;

        let file1 = json!({
            "types": [{"name": "User", "fields": []}],
            "queries": [],
            "mutations": []
        });
        create_test_file(temp_dir.path(), "file1.json", &file1.to_string())?;

        let file2 = json!({
            "types": [{"name": "User", "fields": []}],
            "queries": [],
            "mutations": []
        });
        create_test_file(temp_dir.path(), "file2.json", &file2.to_string())?;

        let result = MultiFileLoader::load_from_directory(temp_dir.path().to_str().unwrap());

        assert!(result.is_err(), "expected Err, got: {result:?}");
        let err_msg = result.unwrap_err().to_string();
        assert!(err_msg.contains("Duplicate type 'User'"));
        assert!(err_msg.contains("file1.json"));
        assert!(err_msg.contains("file2.json"));

        Ok(())
    }

    #[test]
    fn test_duplicate_query_names_error() -> anyhow::Result<()> {
        let temp_dir = TempDir::new()?;

        let file1 = json!({
            "types": [],
            "queries": [{"name": "getUser", "return_type": "User"}],
            "mutations": []
        });
        create_test_file(temp_dir.path(), "file1.json", &file1.to_string())?;

        let file2 = json!({
            "types": [],
            "queries": [{"name": "getUser", "return_type": "User"}],
            "mutations": []
        });
        create_test_file(temp_dir.path(), "file2.json", &file2.to_string())?;

        let result = MultiFileLoader::load_from_directory(temp_dir.path().to_str().unwrap());

        assert!(result.is_err(), "expected Err, got: {result:?}");
        let err_msg = result.unwrap_err().to_string();
        assert!(err_msg.contains("Duplicate query 'getUser'"));

        Ok(())
    }

    #[test]
    fn test_empty_directory() -> anyhow::Result<()> {
        let temp_dir = TempDir::new()?;

        let result = MultiFileLoader::load_from_directory(temp_dir.path().to_str().unwrap())?;

        assert_eq!(result["types"].as_array().unwrap().len(), 0);
        assert_eq!(result["queries"].as_array().unwrap().len(), 0);
        assert_eq!(result["mutations"].as_array().unwrap().len(), 0);

        Ok(())
    }

    #[test]
    fn test_nonexistent_directory() {
        let result = MultiFileLoader::load_from_directory("/nonexistent/path/to/schema");
        assert!(result.is_err(), "expected Err for nonexistent directory, got: {result:?}");
    }

    #[test]
    fn test_load_from_paths() -> anyhow::Result<()> {
        let temp_dir = TempDir::new()?;

        let schema1 = json!({
            "types": [{"name": "User", "fields": []}],
            "queries": [],
            "mutations": []
        });
        create_test_file(temp_dir.path(), "schema1.json", &schema1.to_string())?;

        let schema2 = json!({
            "types": [{"name": "Post", "fields": []}],
            "queries": [],
            "mutations": []
        });
        create_test_file(temp_dir.path(), "schema2.json", &schema2.to_string())?;

        let paths = vec![
            temp_dir.path().join("schema1.json"),
            temp_dir.path().join("schema2.json"),
        ];

        let result = MultiFileLoader::load_from_paths(&paths)?;

        assert_eq!(result["types"].as_array().unwrap().len(), 2);

        Ok(())
    }

    /// Two explicitly-listed files declaring the same name is the same authoring mistake
    /// as two files in a directory declaring it, and must be reported the same way.
    ///
    /// `load_from_directory_with_tracking` detected duplicates across every named section;
    /// `load_from_paths` — the `--schema-file a.json --schema-file b.json` path, and the
    /// one the TOML merger calls — did not. Both definitions were silently concatenated,
    /// so which one the compiler used depended on argument order.
    #[test]
    fn load_from_paths_rejects_a_duplicate_name_across_files() -> anyhow::Result<()> {
        let temp_dir = TempDir::new()?;

        let schema1 = json!({"types": [{"name": "User", "fields": []}]});
        create_test_file(temp_dir.path(), "a.json", &schema1.to_string())?;
        let schema2 = json!({"types": [{"name": "User", "fields": []}]});
        create_test_file(temp_dir.path(), "b.json", &schema2.to_string())?;

        let paths = vec![
            temp_dir.path().join("a.json"),
            temp_dir.path().join("b.json"),
        ];
        let error = MultiFileLoader::load_from_paths(&paths)
            .expect_err("a duplicate type across two listed files must be refused");

        let message = error.to_string();
        assert!(message.contains("User"), "the diagnostic must name the duplicate: {message}");
        assert!(message.contains("a.json"), "the diagnostic must name both files: {message}");
        assert!(message.contains("b.json"), "the diagnostic must name both files: {message}");

        Ok(())
    }

    /// Detection covers every named section, not just `types` — the directory loader's
    /// behaviour, now shared.
    #[test]
    fn load_from_paths_rejects_a_duplicate_in_any_section() -> anyhow::Result<()> {
        let temp_dir = TempDir::new()?;

        let schema1 = json!({"enums": [{"name": "Status", "values": [{"name": "A"}]}]});
        create_test_file(temp_dir.path(), "a.json", &schema1.to_string())?;
        let schema2 = json!({"enums": [{"name": "Status", "values": [{"name": "B"}]}]});
        create_test_file(temp_dir.path(), "b.json", &schema2.to_string())?;

        let paths = vec![
            temp_dir.path().join("a.json"),
            temp_dir.path().join("b.json"),
        ];
        let error = MultiFileLoader::load_from_paths(&paths)
            .expect_err("a duplicate enum across two listed files must be refused");

        assert!(
            error.to_string().contains("enum 'Status'"),
            "the diagnostic must name the section and the duplicate: {error}"
        );

        Ok(())
    }

    /// The same name in the *same* file twice is still one file's problem, and distinct
    /// names across files still merge — the guard must not over-reject.
    #[test]
    fn load_from_paths_still_merges_distinct_names() -> anyhow::Result<()> {
        let temp_dir = TempDir::new()?;

        create_test_file(
            temp_dir.path(),
            "a.json",
            &json!({"types": [{"name": "User", "fields": []}]}).to_string(),
        )?;
        create_test_file(
            temp_dir.path(),
            "b.json",
            &json!({"types": [{"name": "Post", "fields": []}]}).to_string(),
        )?;

        let paths = vec![
            temp_dir.path().join("a.json"),
            temp_dir.path().join("b.json"),
        ];
        let merged = MultiFileLoader::load_from_paths(&paths)?;

        assert_eq!(merged["types"].as_array().expect("types is an array").len(), 2);

        Ok(())
    }

    #[test]
    fn test_directory_file_count_limit_exceeded() -> anyhow::Result<()> {
        let temp_dir = tempfile::tempdir()?;

        // Create MAX_SCHEMA_FILES + 1 JSON files — should trip the limit.
        let schema = json!({"types": [], "queries": [], "mutations": []});
        let content = schema.to_string();
        for i in 0..=MAX_SCHEMA_FILES {
            create_test_file(temp_dir.path(), &format!("schema_{i:04}.json"), &content)?;
        }

        let result =
            MultiFileLoader::load_from_directory_with_tracking(temp_dir.path().to_str().unwrap());
        assert!(result.is_err(), "expected error when file count exceeds limit");
        let msg = result.err().unwrap().to_string();
        assert!(msg.contains("more than"), "error should mention the limit: {msg}");
        Ok(())
    }
}

mod optimizer_tests {
    use std::collections::HashMap;

    use fraiseql_core::{
        db::types::DatabaseType,
        schema::{
            ArgumentDefinition, AutoParams, CompiledSchema, CursorType, FieldDefinition,
            FieldDenyPolicy, FieldType, QueryDefinition, TypeDefinition,
        },
        validation::CustomTypeRegistry,
    };
    use indexmap::IndexMap;

    use super::super::optimizer::*;

    #[test]
    fn test_optimize_empty_schema() {
        let mut schema = CompiledSchema {
            types: vec![],
            enums: vec![],
            input_types: vec![],
            interfaces: vec![],
            unions: vec![],
            queries: vec![],
            mutations: vec![],
            subscriptions: vec![],
            directives: vec![],
            observers: Vec::new(),
            fact_tables: HashMap::default(),
            federation: None,
            security: None,
            observers_config: None,
            subscriptions_config: None,
            validation_config: None,
            debug_config: None,
            mcp_config: None,
            schema_sdl: None,
            custom_scalars: CustomTypeRegistry::default(),
            ..Default::default()
        };

        let report = SchemaOptimizer::optimize(&mut schema).unwrap();
        assert_eq!(report.total_hints(), 0);
    }

    #[test]
    fn test_index_hint_for_list_query() {
        let mut schema = CompiledSchema {
            types: vec![],
            enums: vec![],
            input_types: vec![],
            interfaces: vec![],
            unions: vec![],
            queries: vec![QueryDefinition {
                function: None,

                requires_actor:      Vec::new(),
                returns_count:       false,
                name:                "users".to_string(),
                return_type:         "User".to_string(),
                returns_list:        true,
                nullable:            false,
                arguments:           vec![ArgumentDefinition {
                    name:          "status".to_string(),
                    arg_type:      FieldType::String,
                    nullable:      false,
                    default_value: None,
                    description:   None,
                    deprecation:   None,
                    localized:     false,
                }],
                sql_source:          Some("users".to_string()),
                description:         None,
                auto_params:         AutoParams::default(),
                deprecation:         None,
                jsonb_column:        "data".to_string(),
                relay:               false,
                relay_cursor_column: None,
                relay_cursor_type:   CursorType::default(),
                inject_params:       IndexMap::default(),
                read_routing:        fraiseql_core::db::types::ReadRouting::default(),
                cache_ttl_seconds:   None,
                additional_views:    vec![],
                requires_role:       None,
                rest_path:           None,
                rest_method:         None,
                rest_stream:         false,
                native_columns:      HashMap::new(),
                pagination_order:    None,
            }],
            mutations: vec![],
            subscriptions: vec![],
            directives: vec![],
            observers: Vec::new(),
            fact_tables: HashMap::default(),
            federation: None,
            security: None,
            observers_config: None,
            subscriptions_config: None,
            validation_config: None,
            debug_config: None,
            mcp_config: None,
            schema_sdl: None,
            custom_scalars: CustomTypeRegistry::default(),
            ..Default::default()
        };

        let report = SchemaOptimizer::optimize(&mut schema).unwrap();
        assert!(report.total_hints() > 0);
        assert!(!report.index_hints.is_empty());
        assert_eq!(report.index_hints[0].query_name, "users");
    }

    #[test]
    fn test_pagination_note() {
        let mut schema = CompiledSchema {
            types: vec![],
            enums: vec![],
            input_types: vec![],
            interfaces: vec![],
            unions: vec![],
            queries: vec![QueryDefinition {
                function: None,

                requires_actor:      Vec::new(),
                returns_count:       false,
                name:                "products".to_string(),
                return_type:         "Product".to_string(),
                returns_list:        true,
                nullable:            false,
                arguments:           vec![],
                sql_source:          Some("products".to_string()),
                description:         None,
                auto_params:         AutoParams {
                    has_where:    false,
                    has_order_by: false,
                    has_limit:    true,
                    has_offset:   true,
                },
                deprecation:         None,
                jsonb_column:        "data".to_string(),
                relay:               false,
                relay_cursor_column: None,
                relay_cursor_type:   CursorType::default(),
                inject_params:       IndexMap::default(),
                read_routing:        fraiseql_core::db::types::ReadRouting::default(),
                cache_ttl_seconds:   None,
                additional_views:    vec![],
                requires_role:       None,
                rest_path:           None,
                rest_method:         None,
                rest_stream:         false,
                native_columns:      HashMap::new(),
                pagination_order:    None,
            }],
            mutations: vec![],
            subscriptions: vec![],
            directives: vec![],
            observers: Vec::new(),
            fact_tables: HashMap::default(),
            federation: None,
            security: None,
            observers_config: None,
            subscriptions_config: None,
            validation_config: None,
            debug_config: None,
            mcp_config: None,
            schema_sdl: None,
            custom_scalars: CustomTypeRegistry::default(),
            ..Default::default()
        };

        let report = SchemaOptimizer::optimize(&mut schema).unwrap();
        assert!(report.optimization_notes.iter().any(|note| note.contains("pagination")));
    }

    #[test]
    fn test_large_type_warning() {
        let mut schema = CompiledSchema {
            types: vec![TypeDefinition {
                name:                "BigType".into(),
                sql_source:          String::new().into(),
                jsonb_column:        String::new(),
                fields:              (0..25)
                    .map(|i| FieldDefinition {
                        name:            format!("field{i}").into(),
                        field_type:      FieldType::String,
                        nullable:        false,
                        default_value:   None,
                        description:     None,
                        vector_config:   None,
                        vector_distance: None,
                        alias:           None,
                        deprecation:     None,
                        requires_scope:  None,
                        on_deny:         FieldDenyPolicy::default(),
                        authorize:       false,
                        encryption:      None,
                        hierarchy:       None,
                        unique:          false,
                        localized:       false,
                    })
                    .collect(),
                description:         None,
                sql_projection_hint: None,
                implements:          vec![],
                requires_role:       None,
                is_error:            false,
                relay:               false,
                internal:            false,
                embedded:            false,
                relationships:       Vec::new(),
                inject_params:       indexmap::IndexMap::new(),
                subscription_policy: None,
            }],
            enums: vec![],
            input_types: vec![],
            interfaces: vec![],
            unions: vec![],
            queries: vec![],
            mutations: vec![],
            subscriptions: vec![],
            directives: vec![],
            observers: Vec::new(),
            fact_tables: HashMap::default(),
            federation: None,
            security: None,
            observers_config: None,
            subscriptions_config: None,
            validation_config: None,
            debug_config: None,
            mcp_config: None,
            schema_sdl: None,
            custom_scalars: CustomTypeRegistry::default(),
            ..Default::default()
        };

        let report = SchemaOptimizer::optimize(&mut schema).unwrap();
        assert!(report.optimization_notes.iter().any(|note| note.contains("25 fields")));
    }

    #[test]
    fn test_projection_hint_for_large_type() {
        let mut schema = CompiledSchema {
            types: vec![TypeDefinition {
                name:                "User".into(),
                sql_source:          "users".into(),
                jsonb_column:        "data".to_string(),
                fields:              (0..15)
                    .map(|i| FieldDefinition {
                        name:            format!("field{i}").into(),
                        field_type:      FieldType::String,
                        nullable:        false,
                        default_value:   None,
                        description:     None,
                        vector_config:   None,
                        vector_distance: None,
                        alias:           None,
                        deprecation:     None,
                        requires_scope:  None,
                        on_deny:         FieldDenyPolicy::default(),
                        authorize:       false,
                        encryption:      None,
                        hierarchy:       None,
                        unique:          false,
                        localized:       false,
                    })
                    .collect(),
                description:         None,
                sql_projection_hint: None,
                implements:          vec![],
                requires_role:       None,
                is_error:            false,
                relay:               false,
                internal:            false,
                embedded:            false,
                relationships:       Vec::new(),
                inject_params:       indexmap::IndexMap::new(),
                subscription_policy: None,
            }],
            enums: vec![],
            input_types: vec![],
            interfaces: vec![],
            unions: vec![],
            queries: vec![],
            mutations: vec![],
            subscriptions: vec![],
            directives: vec![],
            observers: Vec::new(),
            fact_tables: HashMap::default(),
            federation: None,
            security: None,
            observers_config: None,
            subscriptions_config: None,
            validation_config: None,
            debug_config: None,
            mcp_config: None,
            schema_sdl: None,
            custom_scalars: CustomTypeRegistry::default(),
            ..Default::default()
        };

        let report = SchemaOptimizer::optimize(&mut schema).unwrap();

        // Type with 15 fields and JSONB column should get projection hint
        assert!(!report.projection_hints.is_empty());
        assert_eq!(report.projection_hints[0].type_name, "User");
        assert_eq!(report.projection_hints[0].field_count, 15);

        // Type should have sql_projection_hint set
        assert!(schema.types[0].has_sql_projection());
        let hint = schema.types[0].sql_projection_hint.as_ref().unwrap();
        assert_eq!(hint.database, DatabaseType::PostgreSQL);
        assert!(hint.estimated_reduction_percent > 0);
    }

    #[test]
    fn test_projection_not_applied_without_jsonb() {
        let mut schema = CompiledSchema {
            types: vec![TypeDefinition {
                name:                "SmallType".into(),
                sql_source:          "small_table".into(),
                jsonb_column:        String::new(), // No JSONB column
                fields:              (0..15)
                    .map(|i| FieldDefinition {
                        name:            format!("field{i}").into(),
                        field_type:      FieldType::String,
                        nullable:        false,
                        default_value:   None,
                        description:     None,
                        vector_config:   None,
                        vector_distance: None,
                        alias:           None,
                        deprecation:     None,
                        requires_scope:  None,
                        on_deny:         FieldDenyPolicy::default(),
                        authorize:       false,
                        encryption:      None,
                        hierarchy:       None,
                        unique:          false,
                        localized:       false,
                    })
                    .collect(),
                description:         None,
                sql_projection_hint: None,
                implements:          vec![],
                requires_role:       None,
                is_error:            false,
                relay:               false,
                internal:            false,
                embedded:            false,
                relationships:       Vec::new(),
                inject_params:       indexmap::IndexMap::new(),
                subscription_policy: None,
            }],
            enums: vec![],
            input_types: vec![],
            interfaces: vec![],
            unions: vec![],
            queries: vec![],
            mutations: vec![],
            subscriptions: vec![],
            directives: vec![],
            observers: Vec::new(),
            fact_tables: HashMap::default(),
            federation: None,
            security: None,
            observers_config: None,
            subscriptions_config: None,
            validation_config: None,
            debug_config: None,
            mcp_config: None,
            schema_sdl: None,
            custom_scalars: CustomTypeRegistry::default(),
            ..Default::default()
        };

        let report = SchemaOptimizer::optimize(&mut schema).unwrap();

        // Type without JSONB column should not get projection hint
        assert!(report.projection_hints.is_empty());
        assert!(!schema.types[0].has_sql_projection());
    }
}