mcp-server-sqlite 1.0.0

An MCP server for SQLite with fine-grained access control
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
//! Rule-based access control for the MCP SQLite server.
//!
//! This module implements the permission system that decides which SQL
//! operations the server may execute. Permissions are configured at startup
//! through the `--allow` and `--deny` CLI flags, each taking an *access control
//! selector* that identifies the operation — and optionally the exact resources
//! — the rule applies to.
//!
//! # Selector syntax
//!
//! Every SQLite authorization action (`Read`, `Insert`, `CreateTable`,
//! `DropIndex`, `Function`, etc.) has a corresponding selector type. A selector
//! is written as:
//!
//! - `Action` — matches **all** operations of that type (every field defaults
//!   to the wildcard `*`).
//! - `Action(value)` — pins the first field to a specific value; remaining
//!   fields stay as wildcards.
//! - `Action(value1.value2)` — pins both fields.
//! - `Action(*.value2)` — wildcard first field, pinned second field.
//!
//! For example, the `Read` selector has two fields (`table_name` and
//! `column_name`):
//!
//! | CLI flag                       | Meaning                        |
//! |--------------------------------|--------------------------------|
//! | `--allow Read`                 | allow all column reads         |
//! | `--deny  Read(Secrets)`        | deny reads on `Secrets`        |
//! | `--allow Read(Secrets.id)`     | allow reads on `Secrets.id`    |
//! | `--deny  Read(*.ssn)`          | deny reads on any `ssn` column |
//!
//! # Specificity
//!
//! Each selector has a *specificity* equal to the number of its fields that are
//! pinned to concrete values (i.e. not `*`). A bare `Read` has specificity 0,
//! `Read(Students)` has specificity 1, and `Read(Students.name)` has
//! specificity 2. More specific rules always outrank less specific ones.
//!
//! # Resolution algorithm
//!
//! When SQLite asks "is this operation allowed?", the [`AuthorizationResolver`]
//! evaluates rules as follows:
//!
//! 1. **Collect matching rules.** For each configured rule whose selector
//!    covers the requested operation (globs match anything, values must match
//!    exactly), note its specificity.
//!
//! 2. **Most specific wins.** Rules are evaluated from the highest specificity
//!    level to the lowest. The first level that contains at least one matching
//!    rule determines the outcome.
//!
//! 3. **Deny breaks ties.** If both allow *and* deny rules match at the same
//!    specificity level, the result is **deny** (fail-closed).
//!
//! 4. **Default fallback.** If no rule matches at any level, the per-action
//!    default is used. The default depends on how the resolver was constructed
//!    (e.g. [`AuthorizationResolver::new_allow_everything`] ).
//!
//! One sentence summary: **the most specific matching rule wins; ties go to
//! deny; no match defers to the default.**
//!
//! # Examples
//!
//! ## Read-only server with one table blocked
//!
//! ```text
//! --allow Read --deny Read(Secrets)
//! ```
//!
//! All column reads are allowed except anything touching the `Secrets` table.
//! `Read(Secrets)` has specificity 1 which beats the blanket `Read` at
//! specificity 0, so the deny wins for any column in `Secrets`.
//!
//! ## Read-only with a carve-out
//!
//! ```text
//! --allow Read --deny Read(Secrets) --allow Read(Secrets.id)
//! ```
//!
//! All reads are allowed. Reads on `Secrets` are denied — except for the `id`
//! column, which is explicitly re-allowed at specificity 2 (both fields
//! pinned), beating the specificity-1 deny.
//!
//! ## Conflicting rules at the same specificity
//!
//! ```text
//! --deny Read(Students) --allow Read(*.name)
//! ```
//!
//! A read on `Students.name` matches both rules. `Read(Students)` has
//! specificity 1 (table pinned, column glob) and `Read(*.name)` also has
//! specificity 1 (table glob, column pinned). Because both match at the same
//! level, **deny wins**. To allow `Students.name`, add a more specific rule:
//! `--allow Read(Students.name)` (specificity 2).
//!
//! ## Deny everything, allow specific functions
//!
//! ```text
//! --deny Function --allow Function(count) --allow Function(sum)
//! ```
//!
//! All SQL function calls are denied except `count` and `sum`, which win at
//! specificity 1 over the blanket deny at specificity 0.
//!
//! ## Lock down DDL while permitting reads and inserts
//!
//! ```text
//! --allow Read --allow Insert --allow Select --allow Transaction
//! ```
//!
//! With a deny-everything default, only the explicitly allowed actions proceed.
//! All DDL (`CreateTable`, `DropIndex`, etc.) remains denied because no allow
//! rule exists for those actions.
//!
//! # Code generation
//!
//! The `define_access_control_selector_types!` macro generates the selector
//! structs, the [`AccessControlSelector`] enum, the
//! [`AccessControlSelectorSet`], and the [`AuthorizationResolver`] from a set
//! of struct declarations. Each struct's field types are wrapped in
//! [`ValueOrGlob`] so that every field can independently be a concrete value or
//! a wildcard. The macro also generates `Display` / `FromStr` round-tripping,
//! builder methods, and the specificity-aware resolution logic described above.

use std::{error::Error, fmt::Display, str::FromStr};

/// Counts the number of identifier tokens passed to it at compile time.
///
/// This is used internally by `define_access_control_selector_types!` to
/// determine `FIELD_COUNT` for each generated selector struct, which in turn
/// drives field-count validation during parsing.
///
/// # Examples
///
/// ```ignore
/// count_idents!(a, b, c) // expands to 3
/// count_idents!()        // expands to 0
/// ```
macro_rules! count_idents {
    ($ident: ident, $($rest_idents: ident),* $(,)?) => {
        1 + count_idents!($($rest_idents),*)
    };
    ($ident: ident) => {
        1
    };
    () => {
        0
    };
}

/// Builds a `format!`-compatible template string with `{}` placeholders joined
/// by dots, matching the dot-separated field syntax used in selector strings.
///
/// For a selector struct with fields `table_name` and `column_name`, this
/// produces `"{}.{}"`, which is interpolated inside `format!` to render
/// something like `Students.name`.
///
/// # Examples
///
/// ```ignore
/// formatting_string_literal!(a, b)  // expands to "{}.{}"
/// formatting_string_literal!(a)     // expands to "{}"
/// formatting_string_literal!()      // expands to ""
/// ```
macro_rules! formatting_string_literal {
    ($ident: ident, $($rest_idents: ident),* $(,)?) => {
        concat!("{}.", formatting_string_literal!($($rest_idents),*))
    };
    ($ident: ident) => {
        "{}"
    };
    () => {
        ""
    };
}

/// Generates access control selector structs, an umbrella
/// [`AccessControlSelector`] enum, and all associated trait implementations
/// from a set of struct declarations.
///
/// Each struct declaration passed to this macro produces:
///
/// - A public struct whose field types are each wrapped in [`ValueOrGlob<T>`],
///   so every field can independently hold a concrete value or a wildcard glob.
/// - A variant on [`AccessControlSelector`] named `{Struct}` that wraps the
///   generated struct.
/// - `Display` formatting that round-trips with the CLI string syntax: bare
///   identifier when all fields are globs (e.g., `Read`), or identifier with
///   parenthesized dot-separated fields otherwise (e.g.,
///   `Read(Students.name)`).
/// - `FromStr` parsing that accepts the same syntax and validates field counts
///   and selector identifiers.
/// - `From<T> for String` and `TryFrom<String> for T` conversions.
/// - Builder methods: `new(...)`, `empty()`, and `with_{field}(...)` for
///   ergonomic construction.
/// - Inspection methods: `is_all_glob`, `is_all_value`, `is_any_glob`,
///   `is_any_value`.
///
/// Doc comments (`#[doc = "..."]`) and other attributes placed on the struct or
/// its fields in the macro invocation are forwarded to both the generated
/// struct and the corresponding enum variant via the `$(#[$struct_meta])*` and
/// `$(#[$field_meta])*` captures.
///
/// # Usage
///
/// ```ignore
/// define_access_control_selector_types! {
///     /// Controls read access at the table and column level.
///     pub struct Read {
///         /// The table targeted by this selector.
///         pub table_name: String,
///         /// The column targeted by this selector.
///         pub column_name: String,
///     }
/// }
/// ```
macro_rules! define_access_control_selector_types {
    (
        $(
            $(#[$struct_meta: meta])*
            $struct_vis: vis struct $struct_ident: ident {
                $(
                    $(#[$field_meta: meta])*
                    $field_vis: vis $field_ident: ident: $field_ty: ty
                ),* $(,)?
            }
        )*
    ) => {
        paste::paste! {
            /// Resolves incoming SQLite authorization requests against a set of
            /// configured allow/deny rules and per-action default permissions.
            ///
            /// The resolver holds an [`AccessControlSelectorSet`] containing
            /// all user-supplied rules, plus a default
            /// [`rusqlite::hooks::Authorization`] for each action type that is
            /// used when no rule matches. Call [`authorization`] with an
            /// [`AuthContext`] to obtain the final verdict.
            ///
            /// [`AuthContext`]: rusqlite::hooks::AuthContext
            ///
            /// [`authorization`]: AuthorizationResolver::authorization
            pub struct AuthorizationResolver {
                /// The set of allow/deny rules to evaluate.
                pub selector_set: AccessControlSelectorSet,
                $(
                    /// The fallback authorization returned when no rule in the
                    /// selector set matches this action type.
                    pub [< $struct_ident:snake _default_permissions >]: rusqlite::hooks::Authorization,
                )*
            }

            const _: () = {
                impl AuthorizationResolver {
                    /// Creates a resolver that permits every action by default.
                    /// Rules added to the selector set can then selectively
                    /// deny specific operations.
                    pub fn new_allow_everything() -> Self {
                        Self {
                            selector_set: Default::default(),
                            $(
                                [< $struct_ident:snake _default_permissions >]: rusqlite::hooks::Authorization::Allow,
                            )*
                        }
                    }

                    /// Creates a resolver that denies every action by default.
                    /// Rules added to the selector set can then selectively
                    /// allow specific operations.
                    pub fn new_deny_everything() -> Self {
                        Self {
                            selector_set: Default::default(),
                            $(
                                [< $struct_ident:snake _default_permissions >]: rusqlite::hooks::Authorization::Deny,
                            )*
                        }
                    }

                    pub fn with_selector(mut self, selector: impl Into<AccessControlSelector>, allow: bool) -> Self {
                        self.selector_set = self.selector_set.with_selector(selector, allow);
                        self
                    }

                    $(
                        #[doc = concat!(
                            "Sets the default authorization returned for [`",
                            stringify!($struct_ident),
                            "`] actions when no rule matches."
                        )]
                        pub const fn [< with_ $struct_ident:snake _default_permissions >](
                            mut self,
                            default_permissions: rusqlite::hooks::Authorization
                        ) -> Self {
                            self.[< $struct_ident:snake _default_permissions >] = default_permissions;
                            self
                        }
                    )*

                    /// Evaluates the configured rules against an incoming
                    /// SQLite authorization request. Dispatches to the
                    /// appropriate type-specific check on the selector set and
                    /// falls back to the per-action default when no rule
                    /// matches. Unrecognized actions are denied
                    /// unconditionally.
                    pub fn authorization(
                        &self,
                        ctx: rusqlite::hooks::AuthContext<'_>
                    ) -> rusqlite::hooks::Authorization {
                        match ctx.action {
                            $(
                                rusqlite::hooks::AuthAction::$struct_ident { $($field_ident,)* .. } => {
                                    self
                                        .selector_set
                                        .[< check_ $struct_ident: snake >]($(&$field_ident),*)
                                        .map(Into::into)
                                        .unwrap_or(self.[< $struct_ident:snake _default_permissions >])
                                }
                            )*,
                            _ => rusqlite::hooks::Authorization::Deny
                        }
                    }
                }
            };

            /// Holds all configured access control rules, grouped by selector
            /// type and indexed by specificity.
            ///
            /// Each selector type gets its own [`BTreeMap`] keyed by the
            /// selector's [`specificity`] value (number of concrete
            /// [`Value`](ValueOrGlob::Value) fields). This layout enables the
            /// policy resolver to iterate from most-specific to least-specific
            /// rules efficiently: the highest-specificity match wins, with deny
            /// breaking ties.
            ///
            /// [`BTreeMap`]: std::collections::BTreeMap
            /// [`specificity`]: #method.specificity
            #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
            pub struct AccessControlSelectorSet {
                $(
                    $(#[$struct_meta])*
                    pub [<$struct_ident: snake _selectors>]: std::collections::BTreeMap<usize, Vec<Permission<$struct_ident>>>,
                )*
            }

            const _: () = {
                impl AccessControlSelectorSet {
                    /// Creates an empty [`AccessControlSelectorSet`] with no
                    /// rules.
                    pub fn new() -> Self {
                        Default::default()
                    }

                    /// Adds a rule by converting any selector type into an
                    /// [`AccessControlSelector`] and dispatching it to the
                    /// appropriate type-specific builder. `allow` controls
                    /// whether the rule permits or denies the matched
                    /// operation.
                    pub fn with_selector(
                        self,
                        selector: impl Into<AccessControlSelector>,
                        allow: bool
                    ) -> Self {
                        let selector = selector.into();
                        match selector {
                            $(
                                AccessControlSelector::$struct_ident(selector)
                                    => self.[<with_ $struct_ident: snake _selector>](
                                        selector,
                                        allow
                                    )
                            ),*
                        }
                    }

                    $(
                        #[doc = concat!(
                            "Adds a [`", stringify!($struct_ident),
                            "`] rule, inserting it into the ",
                            "bucket matching its specificity."
                        )]
                        pub fn [<with_ $struct_ident: snake _selector>](
                            mut self,
                            selector: $struct_ident,
                            allow: bool
                        ) -> Self {
                            self.[<$struct_ident: snake _selectors>]
                                .entry(selector.specificity())
                                .or_default()
                                .push(Permission {
                                    selector,
                                    allow
                                });
                            self
                        }

                        #[doc = concat!(
                            "Resolves the configured [`",
                            stringify!($struct_ident),
                            "`] rules against the given field values. ",
                            "Iterates from highest to lowest specificity; ",
                            "at each level, deny wins if both allow and deny ",
                            "match. Returns `None` when no rule matches."
                        )]
                        #[allow(clippy::ptr_arg)]
                        pub fn [< check_ $struct_ident: snake >](&self, $($field_ident: &(impl PartialEq<$field_ty> + ?Sized)),*) -> Option<Authorization> {
                            for permissions in self.[<$struct_ident: snake _selectors>].values().rev() {
                                let mut allow_encountered = false;
                                let mut deny_encountered = false;
                                let authorizations = permissions.iter().filter_map(|permission| permission.check($($field_ident),*));
                                for authorization in authorizations {
                                    match authorization {
                                        Authorization::Allow => {
                                            allow_encountered = true
                                        }
                                        Authorization::Deny => {
                                            deny_encountered = true
                                        }
                                    }
                                    if allow_encountered == true && deny_encountered == true {
                                        return Some(Authorization::Deny)
                                    }
                                }
                                match (allow_encountered, deny_encountered) {
                                    (false, false) => {
                                        continue
                                    },
                                    (true, false) => {
                                        return Some(Authorization::Allow)
                                    },
                                    (_, true) => {
                                        return Some(Authorization::Deny)
                                    },
                                }
                            }
                            None
                        }
                    )*
                }
            };

            /// Umbrella enum unifying all access control selector types into a
            /// single type for use with the CLI argument parser.
            ///
            /// Each variant wraps a specific selector struct generated by
            /// `define_access_control_selector_types!`. Parsing a selector
            /// string through this enum automatically dispatches to the correct
            /// variant based on the leading identifier.
            #[allow(clippy::enum_variant_names)]
            #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
            pub enum AccessControlSelector {
                $(
                    $(#[$struct_meta])*
                    $struct_ident($struct_ident)
                ),*
            }

            const _: () = {
                use core::fmt::{Display, Formatter, Result as FmtResult};

                use $crate::access_control::AccessControlSelectorParseError;
                use $crate::access_control::AccessControlSelectorParseError::*;

                impl AccessControlSelector {
                    $(
                        #[doc = concat!(
                            "Returns `true` if this is the [`",
                            stringify!($struct_ident),
                            "`] variant."
                        )]
                        pub const fn [<is_ $struct_ident: snake>](&self) -> bool {
                            matches!(self, Self::$struct_ident(..))
                        }

                        #[doc = concat!(
                            "Returns a reference to the inner [`",
                            stringify!($struct_ident),
                            "`] if this is that variant, ",
                            "or `None` otherwise."
                        )]
                        pub const fn [<as_ $struct_ident: snake>](&self) -> Option<&$struct_ident> {
                            if let Self::$struct_ident(value) = self {
                                Some(value)
                            } else {
                                None
                            }
                        }

                        #[doc = concat!(
                            "Consumes `self` and returns the ",
                            "inner [`",
                            stringify!($struct_ident),
                            "`] if this is that variant, ",
                            "or `None` otherwise."
                        )]
                        pub fn [<into_ $struct_ident: snake>](self) -> Option<$struct_ident> {
                            if let Self::$struct_ident(value) = self {
                                Some(value)
                            } else {
                                None
                            }
                        }
                    )*
                }

                /// Delegates to the wrapped selector variant's [`Display`]
                /// implementation, producing the CLI selector syntax.
                impl Display for AccessControlSelector {
                    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
                        match self {
                            $(
                                Self::$struct_ident(selector) => Display::fmt(selector, f),
                            )*
                        }
                    }
                }

                /// Converts an [`AccessControlSelector`] into its string
                /// representation via [`Display`].
                impl From<AccessControlSelector> for String {
                    fn from(v: AccessControlSelector) -> Self {
                        v.to_string()
                    }
                }

                /// Parses a selector string by extracting the leading
                /// identifier and dispatching to the corresponding variant's
                /// [`FromStr`] implementation.
                ///
                /// # Errors
                ///
                /// Returns
                /// [`AccessControlSelectorParseError::InvalidAccessControlSelectorIdentifier`]
                /// when the leading identifier does not match any known
                /// selector variant, and propagates any error from the
                /// variant-level parser.
                impl FromStr for AccessControlSelector {
                    type Err = AccessControlSelectorParseError;

                    fn from_str(s: &str) -> Result<Self, Self::Err> {
                        let selector = s
                            .split("(")
                            .next()
                            .ok_or_else(|| InvalidAccessControlSelectorIdentifier {
                                found: None,
                                expected: &[$(stringify!($struct_ident)),*],
                                access_control_selector_string: s.into(),
                            })?;

                        match selector {
                            $(
                                stringify!($struct_ident) => s.parse().map(Self::$struct_ident),
                            )*
                            other => Err(InvalidAccessControlSelectorIdentifier {
                                found: Some(other.into()),
                                expected: &[$(stringify!($struct_ident)),*],
                                access_control_selector_string: s.into(),
                            })
                        }
                    }
                }

                /// Parses an owned `String` into an [`AccessControlSelector`]
                /// by delegating to [`FromStr`].
                impl TryFrom<String> for AccessControlSelector {
                    type Error = AccessControlSelectorParseError;

                    fn try_from(v: String) -> Result<Self, Self::Error> {
                        v.parse()
                    }
                }

                $(
                    #[doc = concat!(
                        "Converts a [`",
                        stringify!($struct_ident),
                        "`] into its corresponding [`",
                        "AccessControlSelector`] variant."
                    )]
                    impl From<$struct_ident> for AccessControlSelector {
                        fn from(value: $struct_ident) -> Self {
                            Self::$struct_ident(value)
                        }
                    }
                )*
            };

            $(
                $(#[$struct_meta])*
                #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
                $struct_vis struct $struct_ident {
                    $(
                        $(#[$field_meta])*
                        $field_vis $field_ident: ValueOrGlob<$field_ty>
                    ),*
                }

                const _: () = {
                    use core::fmt::{Display, Formatter, Result as FmtResult};
                    use core::convert::*;
                    use core::str::*;

                    use $crate::access_control::{AccessControlSelectorParseError};
                    use $crate::access_control::AccessControlSelectorParseError::*;

                    impl $struct_ident {
                        #[doc = concat!(
                            "The number of fields declared on [`",
                            stringify!($struct_ident),
                            "`], used for field-count validation during parsing."
                        )]
                        const FIELD_COUNT: usize = count_idents!($($field_ident),*);

                        #[doc = concat!(
                            "Creates a new [`", stringify!($struct_ident),
                            "`] with the provided field values."
                        )]
                        #[doc = ""]
                        #[doc = concat!(
                            "Each argument accepts any type that implements ",
                            "`Into<ValueOrGlob<T>>`, so callers can pass a raw ",
                            "value, a [`ValueOrGlob`], or an `Option<T>`."
                        )]
                        pub fn new(
                            $(
                                $field_ident: impl Into<ValueOrGlob<$field_ty>>
                            ),*
                        ) -> Self {
                            Self {
                                $(
                                    $field_ident: $field_ident.into()
                                ),*
                            }
                        }

                        #[doc = concat!(
                            "Creates a [`", stringify!($struct_ident),
                            "`] where every field is a [`Glob`](ValueOrGlob::Glob), ",
                            "matching all possible values."
                        )]
                        pub fn empty() -> Self {
                            Self {
                                $(
                                    $field_ident: Default::default()
                                ),*
                            }
                        }

                        $(
                            #[doc = concat!(
                                "Sets [`", stringify!($struct_ident),
                                "::", stringify!($field_ident),
                                "`] and returns `self` for method chaining."
                            )]
                            #[doc = ""]
                            $(#[$field_meta])*
                            pub fn [< with_ $field_ident >](mut self, value: impl Into<ValueOrGlob<$field_ty>>) -> Self {
                                self.$field_ident = value.into();
                                self
                            }
                        )*

                        #[doc = concat!(
                            "Returns `true` if every field on this [`",
                            stringify!($struct_ident),
                            "`] is a [`Glob`](ValueOrGlob::Glob)."
                        )]
                        pub const fn is_all_glob(&self) -> bool {
                            if Self::FIELD_COUNT != 0 {
                                true $(&& ValueOrGlob::is_glob(&self.$field_ident))*
                            } else {
                                false
                            }
                        }

                        #[doc = concat!(
                            "Returns `true` if every field on this [`",
                            stringify!($struct_ident),
                            "`] is a [`Value`](ValueOrGlob::Value)."
                        )]
                        pub const fn is_all_value(&self) -> bool {
                            if Self::FIELD_COUNT != 0 {
                                true $(&& ValueOrGlob::is_value(&self.$field_ident))*
                            } else {
                                false
                            }
                        }

                        #[doc = concat!(
                            "Returns `true` if at least one field on this [`",
                            stringify!($struct_ident),
                            "`] is a [`Glob`](ValueOrGlob::Glob)."
                        )]
                        pub const fn is_any_glob(&self) -> bool {
                            if Self::FIELD_COUNT != 0 {
                                false $(|| ValueOrGlob::is_glob(&self.$field_ident))*
                            } else {
                                false
                            }
                        }

                        #[doc = concat!(
                            "Returns `true` if at least one field on this [`",
                            stringify!($struct_ident),
                            "`] is a [`Value`](ValueOrGlob::Value)."
                        )]
                        pub const fn is_any_value(&self) -> bool {
                            if Self::FIELD_COUNT != 0 {
                               false  $(|| ValueOrGlob::is_value(&self.$field_ident))*
                            } else {
                                false
                            }
                        }

                        #[doc = concat!(
                            "Returns the number of ",
                            "[`Value`](ValueOrGlob::Value) ",
                            "fields on this [`",
                            stringify!($struct_ident),
                            "`], used to rank competing ",
                            "policy rules during resolution. ",
                            "A higher specificity means the ",
                            "rule targets a narrower set of ",
                            "operations."
                        )]
                        #[allow(unused_mut)]
                        pub const fn specificity(&self) -> usize {
                            let mut specificity = 0;

                            $(
                                if self.$field_ident.is_value() {
                                    specificity += 1
                                }
                            )*

                            specificity
                        }

                        #[doc = concat!(
                            "Returns `true` if this selector ",
                            "covers the given field values. ",
                            "A [`Glob`](ValueOrGlob::Glob) ",
                            "field matches any value; a ",
                            "[`Value`](ValueOrGlob::Value) ",
                            "field matches only when equal."
                        )]
                        #[allow(clippy::ptr_arg)]
                        pub fn matches(&self, $($field_ident: &(impl PartialEq<$field_ty> + ?Sized)),*) -> bool {
                            true $(&& (self.$field_ident.is_glob() || self.$field_ident.as_value().is_some_and(|field_value| PartialEq::<$field_ty>::eq($field_ident, field_value))))*
                        }
                    }

                    #[allow(clippy::ptr_arg)]
                    impl Permission<$struct_ident> {
                        #[doc = concat!(
                            "If the inner [`",
                            stringify!($struct_ident),
                            "`] selector matches the given ",
                            "fields, returns the ",
                            "[`Authorization`] implied by ",
                            "this permission's `allow` flag. ",
                            "Returns `None` on no match."
                        )]
                        pub fn check(&self, $($field_ident: &(impl PartialEq<$field_ty> + ?Sized)),*) -> Option<Authorization> {
                            self.selector.matches($($field_ident),*).then(|| match self.allow {
                                true => Authorization::Allow,
                                false => Authorization::Deny,
                            })
                        }
                    }

                    #[doc = concat!(
                        "Defaults to [`", stringify!($struct_ident),
                        "::empty`], producing a selector where every field ",
                        "is a glob."
                    )]
                    impl Default for $struct_ident {
                        fn default() -> Self {
                            Self::empty()
                        }
                    }

                    #[doc = concat!(
                        "Formats this [`", stringify!($struct_ident),
                        "`] using the CLI selector syntax. When all fields ",
                        "are globs, renders the bare identifier `",
                        stringify!($struct_ident),
                        "`; otherwise renders the identifier with ",
                        "parenthesized dot-separated fields."
                    )]
                    impl Display for $struct_ident {
                        fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
                            if Self::FIELD_COUNT == 0 || self.is_all_glob() {
                                core::write!(f, stringify!($struct_ident))
                            } else {
                                core::write!(
                                    f,
                                    concat!(
                                        stringify!($struct_ident),
                                        "(",
                                        formatting_string_literal!($($field_ident),*),
                                        ")"
                                    ),
                                    $(self.$field_ident),*
                                )
                            }
                        }
                    }

                    #[doc = concat!(
                        "Converts a [`", stringify!($struct_ident),
                        "`] into its string representation via [`Display`]."
                    )]
                    impl From<$struct_ident> for String {
                        fn from(value: $struct_ident) -> Self {
                            value.to_string()
                        }
                    }

                    #[doc = concat!(
                        "Parses a selector string into a [`",
                        stringify!($struct_ident),
                        "`]. Accepts the syntax `",
                        stringify!($struct_ident),
                        "` or `", stringify!($struct_ident),
                        "(field1.field2)`."
                    )]
                    #[allow(unused_mut, unused_variables)]
                    impl FromStr for $struct_ident {
                        type Err = AccessControlSelectorParseError;

                        fn from_str(s: &str) -> Result<Self, Self::Err> {
                            let parsed_access_control_selector = ParsedAccessControlSelector::<'_, {Self::FIELD_COUNT}>::new(s)?;

                            if parsed_access_control_selector.access_control_selector_ident != stringify!($struct_ident) {
                                return Err(IncorrectAccessControlSelectorIdentifier {
                                    expected: stringify!($struct_ident).into(),
                                    found: parsed_access_control_selector.access_control_selector_ident.into(),
                                    access_control_selector_string: s.into()
                                })
                            }

                            let mut access_control_selector = Self::default();
                            let mut fields = parsed_access_control_selector.fields.into_iter().flatten().map(str::trim);
                            $(
                                let field = fields.next();
                                if let Some(field) = field {
                                    let field_value = ValueOrGlob::<$field_ty>::from_str(field).map_err(|err| FailedToParseFieldValue {
                                        field_ident: stringify!($field_ident).into(),
                                        field_value: field.into(),
                                        error: Box::new(err) as _
                                    })?;
                                    access_control_selector = access_control_selector.[< with_ $field_ident >](field_value)
                                }
                            )*

                            Ok(access_control_selector)
                        }
                    }

                    #[doc = concat!(
                        "Parses an owned `String` into a [`",
                        stringify!($struct_ident),
                        "`] by delegating to [`FromStr`]."
                    )]
                    impl TryFrom<String> for $struct_ident {
                        type Error = AccessControlSelectorParseError;

                        fn try_from(v: String) -> Result<Self, Self::Error> {
                            v.parse()
                        }
                    }
                };
            )*
        }
    };
}

define_access_control_selector_types! {
    /// Selector for `CREATE INDEX` statements, scoped to a table and index
    /// name.
    ///
    /// # String syntax examples
    ///
    /// - `CreateIndex` -- any index on any table.
    /// - `CreateIndex(Students)` -- any index on `Students`.
    /// - `CreateIndex(Students.idx_email)` -- one specific index.
    pub struct CreateIndex {
        /// The table the index is created on, or `*` for any.
        pub table_name: String,
        /// The name of the index being created, or `*` for any.
        pub index_name: String,
    }

    /// Selector for `CREATE TABLE` statements.
    ///
    /// # String syntax examples
    ///
    /// - `CreateTable` -- any table.
    /// - `CreateTable(Students)` -- only `Students`.
    pub struct CreateTable {
        /// The name of the table being created, or `*` for any.
        pub table_name: String,
    }

    /// Selector for `CREATE TEMP INDEX` statements, scoped to a table and index
    /// name.
    ///
    /// # String syntax examples
    ///
    /// - `CreateTempIndex` -- any temporary index on any table.
    /// - `CreateTempIndex(Sessions)` -- temp indexes on `Sessions`.
    pub struct CreateTempIndex {
        /// The table the temp index is created on, or `*` for any.
        pub table_name: String,
        /// The name of the temp index being created, or `*` for any.
        pub index_name: String,
    }

    /// Selector for `CREATE TEMP TABLE` statements.
    ///
    /// # String syntax examples
    ///
    /// - `CreateTempTable` -- any temporary table.
    /// - `CreateTempTable(scratch)` -- only `scratch`.
    pub struct CreateTempTable {
        /// The name of the temp table being created, or `*` for any.
        pub table_name: String,
    }

    /// Selector for `CREATE TEMP TRIGGER` statements, scoped to a table and
    /// trigger name.
    ///
    /// # String syntax examples
    ///
    /// - `CreateTempTrigger` -- any temp trigger on any table.
    /// - `CreateTempTrigger(Orders.trg_audit)` -- one specific trigger.
    pub struct CreateTempTrigger {
        /// The table the temp trigger fires on, or `*` for any.
        pub table_name: String,
        /// The name of the temp trigger, or `*` for any.
        pub trigger_name: String,
    }

    /// Selector for `CREATE TEMP VIEW` statements.
    ///
    /// # String syntax examples
    ///
    /// - `CreateTempView` -- any temporary view.
    /// - `CreateTempView(recent_orders)` -- only `recent_orders`.
    pub struct CreateTempView {
        /// The name of the temp view being created, or `*` for any.
        pub view_name: String,
    }

    /// Selector for `CREATE TRIGGER` statements, scoped to a table and trigger
    /// name.
    ///
    /// # String syntax examples
    ///
    /// - `CreateTrigger` -- any trigger on any table.
    /// - `CreateTrigger(Orders.trg_audit)` -- one specific trigger.
    pub struct CreateTrigger {
        /// The table the trigger fires on, or `*` for any.
        pub table_name: String,
        /// The name of the trigger being created, or `*` for any.
        pub trigger_name: String,
    }

    /// Selector for `CREATE VIEW` statements.
    ///
    /// # String syntax examples
    ///
    /// - `CreateView` -- any view.
    /// - `CreateView(active_users)` -- only `active_users`.
    pub struct CreateView {
        /// The name of the view being created, or `*` for any.
        pub view_name: String,
    }

    /// Selector for `DELETE` statements, scoped to a table.
    ///
    /// # String syntax examples
    ///
    /// - `Delete` -- delete from any table.
    /// - `Delete(Sessions)` -- only from `Sessions`.
    pub struct Delete {
        /// The table being deleted from, or `*` for any.
        pub table_name: String,
    }

    /// Selector for `DROP INDEX` statements, scoped to a table and index name.
    ///
    /// # String syntax examples
    ///
    /// - `DropIndex` -- any index on any table.
    /// - `DropIndex(Students.idx_email)` -- one specific index.
    pub struct DropIndex {
        /// The table the index belongs to, or `*` for any.
        pub table_name: String,
        /// The name of the index being dropped, or `*` for any.
        pub index_name: String,
    }

    /// Selector for `DROP TABLE` statements.
    ///
    /// # String syntax examples
    ///
    /// - `DropTable` -- any table.
    /// - `DropTable(Students)` -- only `Students`.
    pub struct DropTable {
        /// The name of the table being dropped, or `*` for any.
        pub table_name: String,
    }

    /// Selector for `DROP TEMP INDEX` statements, scoped to a table and index
    /// name.
    ///
    /// # String syntax examples
    ///
    /// - `DropTempIndex` -- any temporary index.
    /// - `DropTempIndex(Sessions.idx_ts)` -- one specific index.
    pub struct DropTempIndex {
        /// The table the temp index belongs to, or `*` for any.
        pub table_name: String,
        /// The name of the temp index being dropped, or `*` for any.
        pub index_name: String,
    }

    /// Selector for `DROP TEMP TABLE` statements.
    ///
    /// # String syntax examples
    ///
    /// - `DropTempTable` -- any temporary table.
    /// - `DropTempTable(scratch)` -- only `scratch`.
    pub struct DropTempTable {
        /// The name of the temp table being dropped, or `*` for any.
        pub table_name: String,
    }

    /// Selector for `DROP TEMP TRIGGER` statements, scoped to a table and
    /// trigger name.
    ///
    /// # String syntax examples
    ///
    /// - `DropTempTrigger` -- any temp trigger.
    /// - `DropTempTrigger(Orders.trg_audit)` -- one specific trigger.
    pub struct DropTempTrigger {
        /// The table the temp trigger fires on, or `*` for any.
        pub table_name: String,
        /// The name of the temp trigger being dropped, or `*`.
        pub trigger_name: String,
    }

    /// Selector for `DROP TEMP VIEW` statements.
    ///
    /// # String syntax examples
    ///
    /// - `DropTempView` -- any temporary view.
    /// - `DropTempView(recent_orders)` -- only `recent_orders`.
    pub struct DropTempView {
        /// The name of the temp view being dropped, or `*` for any.
        pub view_name: String,
    }

    /// Selector for `DROP TRIGGER` statements, scoped to a table and trigger
    /// name.
    ///
    /// # String syntax examples
    ///
    /// - `DropTrigger` -- any trigger on any table.
    /// - `DropTrigger(Orders.trg_audit)` -- one specific trigger.
    pub struct DropTrigger {
        /// The table the trigger fires on, or `*` for any.
        pub table_name: String,
        /// The name of the trigger being dropped, or `*` for any.
        pub trigger_name: String,
    }

    /// Selector for `DROP VIEW` statements.
    ///
    /// # String syntax examples
    ///
    /// - `DropView` -- any view.
    /// - `DropView(active_users)` -- only `active_users`.
    pub struct DropView {
        /// The name of the view being dropped, or `*` for any.
        pub view_name: String,
    }

    /// Selector for `INSERT` statements, scoped to a table.
    ///
    /// # String syntax examples
    ///
    /// - `Insert` -- insert into any table.
    /// - `Insert(Students)` -- only into `Students`.
    pub struct Insert {
        /// The table being inserted into, or `*` for any.
        pub table_name: String,
    }

    /// Selector for `PRAGMA` statements, scoped to a pragma name
    ///
    /// # String syntax examples
    ///
    /// - `Pragma` -- any pragma.
    /// - `Pragma(journal_mode)` -- only `journal_mode`.
    pub struct Pragma {
        /// The pragma name, or `*` for any.
        pub pragma_name: String,
    }

    /// Selector for column-level read operations, scoped to a table and column.
    ///
    /// When both fields are globs, this matches all read operations across the
    /// entire database. Specifying a `table_name` narrows the scope to a single
    /// table, and additionally specifying a `column_name` narrows it to one
    /// column.
    ///
    /// # String syntax examples
    ///
    /// - `Read` -- all tables, all columns.
    /// - `Read(Students)` -- the `Students` table, all columns.
    /// - `Read(Students.name)` -- only the `name` column of `Students`.
    /// - `Read(*.name)` -- the `name` column across every table.
    pub struct Read {
        /// The target table name, or `*` to match any table.
        pub table_name: String,
        /// The target column name, or `*` to match any column.
        pub column_name: String,
    }

    /// Selector for bare `SELECT` operations (the statement-level authorization
    /// check, not column-level reads).
    pub struct Select {}

    /// Selector for transaction control operations (`BEGIN`, `COMMIT`,
    /// `ROLLBACK`).
    ///
    /// # String syntax examples
    ///
    /// - `Transaction` -- any transaction operation.
    /// - `Transaction(BEGIN)` -- only `BEGIN` statements.
    pub struct Transaction {
        /// The transaction operation name, or `*` for any.
        pub operation: TransactionOperation,
    }

    /// Selector for `UPDATE` statements, scoped to a table and column.
    ///
    /// # String syntax examples
    ///
    /// - `Update` -- any column on any table.
    /// - `Update(Students)` -- any column on `Students`.
    /// - `Update(Students.email)` -- only the `email` column.
    pub struct Update {
        /// The table being updated, or `*` for any.
        pub table_name: String,
        /// The column being updated, or `*` for any.
        pub column_name: String,
    }

    /// Selector for `ATTACH DATABASE` statements, scoped to a filename.
    ///
    /// # String syntax examples
    ///
    /// - `Attach` -- any attachment.
    /// - `Attach(other.db)` -- only `other.db`.
    pub struct Attach {
        /// The filename being attached, or `*` for any.
        pub filename: String,
    }

    /// Selector for `DETACH DATABASE` statements, scoped to a database name.
    ///
    /// # String syntax examples
    ///
    /// - `Detach` -- any detachment.
    /// - `Detach(aux)` -- only the `aux` database.
    pub struct Detach {
        /// The database name being detached, or `*` for any.
        pub database_name: String,
    }

    /// Selector for `ALTER TABLE` statements, scoped to a database and table.
    ///
    /// # String syntax examples
    ///
    /// - `AlterTable` -- any alter on any table.
    /// - `AlterTable(main.Students)` -- `Students` in `main`.
    pub struct AlterTable {
        /// The database the table belongs to, or `*` for any.
        pub database_name: String,
        /// The table being altered, or `*` for any.
        pub table_name: String,
    }

    /// Selector for `REINDEX` statements, scoped to an index name.
    ///
    /// # String syntax examples
    ///
    /// - `Reindex` -- any index.
    /// - `Reindex(idx_email)` -- only `idx_email`.
    pub struct Reindex {
        /// The name of the index being reindexed, or `*` for any.
        pub index_name: String,
    }

    /// Selector for `ANALYZE` statements, scoped to a table.
    ///
    /// # String syntax examples
    ///
    /// - `Analyze` -- any table.
    /// - `Analyze(Students)` -- only `Students`.
    pub struct Analyze {
        /// The table being analyzed, or `*` for any.
        pub table_name: String,
    }

    /// Selector for `CREATE VIRTUAL TABLE` statements, scoped to a table and
    /// module name.
    ///
    /// # String syntax examples
    ///
    /// - `CreateVtable` -- any virtual table.
    /// - `CreateVtable(docs.fts5)` -- `docs` using `fts5`.
    pub struct CreateVtable {
        /// The name of the virtual table, or `*` for any.
        pub table_name: String,
        /// The module backing the virtual table, or `*` for any.
        pub module_name: String,
    }

    /// Selector for `DROP VIRTUAL TABLE` statements, scoped to a table and
    /// module name.
    ///
    /// # String syntax examples
    ///
    /// - `DropVtable` -- any virtual table.
    /// - `DropVtable(docs.fts5)` -- `docs` backed by `fts5`.
    pub struct DropVtable {
        /// The name of the virtual table, or `*` for any.
        pub table_name: String,
        /// The module backing the virtual table, or `*` for any.
        pub module_name: String,
    }

    /// Selector for SQL function invocations within a query.
    ///
    /// # String syntax examples
    ///
    /// - `Function` -- any function.
    /// - `Function(load_extension)` -- only `load_extension`.
    pub struct Function {
        /// The name of the function being called, or `*` for any.
        pub function_name: String,
    }

    /// Selector for `SAVEPOINT`, `RELEASE`, and `ROLLBACK TO` operations on
    /// named savepoints.
    ///
    /// # String syntax examples
    ///
    /// - `Savepoint` -- any savepoint operation.
    /// - `Savepoint(RELEASE)` -- only `RELEASE` operations.
    /// - `Savepoint(RELEASE.sp1)` -- `RELEASE` on savepoint `sp1`.
    pub struct Savepoint {
        /// The savepoint operation, or `*` for any.
        pub operation: TransactionOperation,
        /// The savepoint name, or `*` for any.
        pub savepoint_name: String,
    }

    /// Selector for recursive query authorization checks.
    pub struct Recursive {}
}

/// A wildcard marker that matches any value in a selector field.
///
/// `Glob` is the unit type behind [`ValueOrGlob::Glob`]. It displays as `*` and
/// is produced whenever a selector field is omitted or explicitly set to `*` in
/// the CLI string syntax.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub struct Glob;

/// Renders the glob as the wildcard character `*`.
impl Display for Glob {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "*")
    }
}

/// Either a concrete value of type `T` or a wildcard [`Glob`].
///
/// Every field on a generated selector struct is wrapped in this enum so that
/// it can independently be pinned to a specific value or left as a glob to
/// match anything. This is the core abstraction that allows selectors to
/// express patterns like `Read(Students.*)` (specific table, any column) or
/// `Read(*.name)` (any table, specific column).
///
/// The `Default` implementation returns `Glob`, matching the convention that an
/// unspecified field matches everything.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum ValueOrGlob<T> {
    /// A concrete, pinned value that this selector field must match exactly.
    Value(T),
    /// A wildcard that matches any value for this selector field.
    Glob(Glob),
}

/// Defaults to [`ValueOrGlob::Glob`] so that omitted fields match everything.
impl<T> Default for ValueOrGlob<T> {
    fn default() -> Self {
        Self::new_glob()
    }
}

impl<T> ValueOrGlob<T> {
    /// Creates a [`ValueOrGlob::Value`] by converting the argument into `T`.
    ///
    /// Accepts anything that implements `Into<T>` so callers can pass owned
    /// values, string slices (when `T = String`), and other convertible types
    /// without explicit conversion at the call site.
    pub fn new_value(value: impl Into<T>) -> Self {
        Self::Value(value.into())
    }

    /// Creates a [`ValueOrGlob::Glob`], representing a wildcard that matches
    /// any value.
    pub const fn new_glob() -> Self {
        Self::Glob(Glob)
    }

    /// Returns `true` if this is a concrete [`Value`](ValueOrGlob::Value).
    pub const fn is_value(&self) -> bool {
        matches!(self, Self::Value(..))
    }

    /// Returns `true` if this is a wildcard [`Glob`](ValueOrGlob::Glob).
    pub const fn is_glob(&self) -> bool {
        matches!(self, Self::Glob(..))
    }

    /// Returns a reference to the inner value if this is a
    /// [`Value`](ValueOrGlob::Value), or `None` if it is a glob.
    pub const fn as_value(&self) -> Option<&T> {
        match self {
            ValueOrGlob::Value(value) => Some(value),
            ValueOrGlob::Glob(_) => None,
        }
    }

    /// Returns a reference to the inner [`Glob`] if this is a
    /// [`Glob`](ValueOrGlob::Glob) variant, or `None` if it is a value.
    pub const fn as_glob(&self) -> Option<&Glob> {
        match self {
            ValueOrGlob::Value(_) => None,
            ValueOrGlob::Glob(glob) => Some(glob),
        }
    }

    /// Consumes `self` and returns the inner `T` if this is a
    /// [`Value`](ValueOrGlob::Value), or `None` if it is a glob.
    pub fn into_value(self) -> Option<T> {
        match self {
            ValueOrGlob::Value(value) => Some(value),
            ValueOrGlob::Glob(_) => None,
        }
    }

    /// Consumes `self` and returns the inner [`Glob`] if this is a
    /// [`Glob`](ValueOrGlob::Glob) variant, or `None` if it is a value.
    pub fn into_glob(self) -> Option<Glob> {
        match self {
            ValueOrGlob::Value(_) => None,
            ValueOrGlob::Glob(glob) => Some(glob),
        }
    }
}

/// Delegates to the inner value's `Display` for [`Value`](ValueOrGlob::Value),
/// or renders `*` for [`Glob`](ValueOrGlob::Glob).
impl<T> Display for ValueOrGlob<T>
where
    T: Display,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ValueOrGlob::Value(value) => Display::fmt(value, f),
            ValueOrGlob::Glob(glob) => Display::fmt(glob, f),
        }
    }
}

/// Converts a [`ValueOrGlob`] to its string representation, enabling `.into()`
/// at call sites that expect a `String`.
impl<T> From<ValueOrGlob<T>> for String
where
    T: Display,
{
    fn from(value: ValueOrGlob<T>) -> Self {
        value.to_string()
    }
}

/// Parses `"*"` as a [`Glob`](ValueOrGlob::Glob) and anything else by
/// delegating to `T::from_str`, yielding a [`Value`](ValueOrGlob::Value) on
/// success.
impl<T> FromStr for ValueOrGlob<T>
where
    T: FromStr,
{
    type Err = T::Err;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        if s == "*" {
            Ok(Self::Glob(Glob))
        } else {
            T::from_str(s).map(Self::Value)
        }
    }
}

/// Parses an owned `String` into a [`ValueOrGlob`] by delegating to
/// [`FromStr`], enabling `value.try_into()` at call sites.
impl<T> TryFrom<String> for ValueOrGlob<T>
where
    T: FromStr,
{
    type Error = T::Err;

    fn try_from(value: String) -> Result<Self, Self::Error> {
        value.parse()
    }
}

/// Converts an `Option<T>` into a [`ValueOrGlob`]: `Some(v)` becomes
/// [`Value(v)`](ValueOrGlob::Value) and `None` becomes
/// [`Glob`](ValueOrGlob::Glob), mirroring the semantics of "present means
/// pinned, absent means match-all."
impl<T> From<Option<T>> for ValueOrGlob<T> {
    fn from(value: Option<T>) -> Self {
        match value {
            Some(value) => Self::Value(value),
            None => Self::Glob(Glob),
        }
    }
}

/// Intermediate representation produced by splitting a raw selector string into
/// its identifier and optional dot-separated field values.
///
/// This is an internal parsing helper consumed by the `FromStr` implementations
/// generated by `define_access_control_selector_types!`. The const generic
/// `FIELD_COUNT` is set to the number of fields declared on the target struct,
/// and is used to validate that the input does not contain more fields than the
/// struct expects.
struct ParsedAccessControlSelector<'a, const FIELD_COUNT: usize> {
    /// The selector identifier portion of the input string (e.g., `"Read"`).
    pub access_control_selector_ident: &'a str,
    /// The dot-separated field values inside the parentheses, if any were
    /// present. `None` when the input was a bare identifier like `"Read"`.
    pub fields: Option<std::str::Split<'a, char>>,
}

impl<'a, const FIELD_COUNT: usize>
    ParsedAccessControlSelector<'a, FIELD_COUNT>
{
    /// Parses a raw selector string into its identifier and optional fields.
    ///
    /// The input `string` is expected to follow the syntax `Identifier` or
    /// `Identifier(field1.field2)`. The method validates balanced parentheses
    /// and enforces that the number of dot-separated fields does not exceed
    /// `FIELD_COUNT`.
    ///
    /// # Errors
    ///
    /// Returns an [`AccessControlSelectorParseError`] when the identifier is
    /// missing, the closing parenthesis is absent, or there are more fields
    /// than the target struct declares.
    pub fn new(
        string: &'a str,
    ) -> Result<Self, AccessControlSelectorParseError> {
        use AccessControlSelectorParseError::*;

        let mut brace_split = string.splitn(2, '(');

        // Get the identifier of the access_control_selector. If it doesn't exist then error
        // out.
        let access_control_selector_ident = brace_split
            .next()
            .ok_or_else(|| NoAccessControlSelectorIdentifierFound {
                expected: stringify!($struct_ident).into(),
                access_control_selector_string: string.to_string(),
            })?
            .trim();

        // Check if there's a remaining portion to the string. If there isn't,
        // then it means that this was a access_control_selector identifier without anything
        // else which is accepted.
        if let Some(remaining_string) = brace_split.next() {
            // Split once at the closing brace, if we fail to do that then this
            // is a malformed access_control_selector.
            let Some((inner_fields, _)) = remaining_string.split_once(')')
            else {
                return Err(NoClosingBraceFound {
                    access_control_selector_string: string.to_string(),
                });
            };

            // Count the number of dot separators in the remaining string. This
            // number can be at most `FIELD_COUNT - 1`. For access_control_selectors with no
            // fields the subtraction fails which would return a correct invalid
            // number of fields error.
            let number_of_fields =
                inner_fields.chars().filter(|c| matches!(c, '.')).count() + 1;
            if number_of_fields > FIELD_COUNT {
                return Err(InvalidNumberOfFields {
                    found: number_of_fields,
                    maximum_expected: FIELD_COUNT,
                    access_control_selector_string: string.to_string(),
                });
            }

            // Split the inner fields (without the closing paren) by dots and return.
            let fields = inner_fields.split('.');

            Ok(Self {
                access_control_selector_ident,
                fields: Some(fields),
            })
        } else {
            Ok(Self {
                access_control_selector_ident,
                fields: None,
            })
        }
    }
}

/// Pairs a selector with a permission disposition (allow or deny).
///
/// Stored inside [`AccessControlSelectorSet`] and evaluated by the policy
/// resolver. When a [`Permission`] 's selector matches an incoming operation,
/// its `allow` flag determines whether the operation is permitted or forbidden.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Permission<T> {
    /// The selector that defines which operations this rule applies to.
    pub selector: T,
    /// `true` to permit the matched operation, `false` to deny it.
    pub allow: bool,
}

/// The outcome of a policy check against the configured rule set.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Authorization {
    /// The operation is permitted.
    Allow,
    /// The operation is forbidden.
    Deny,
}

/// Maps this crate's [`Authorization`] to rusqlite's equivalent so that policy
/// verdicts can be returned directly from the authorization hook.
impl From<Authorization> for rusqlite::hooks::Authorization {
    fn from(value: Authorization) -> Self {
        match value {
            Authorization::Allow => Self::Allow,
            Authorization::Deny => Self::Deny,
        }
    }
}

/// The type of transaction or savepoint operation being authorized.
///
/// Mirrors [`rusqlite::hooks::TransactionOperation`] but is owned by this crate
/// so it can derive [`Display`] and [`FromStr`] via `strum`, enabling
/// round-trip parsing in selector strings like `Transaction(BEGIN)`.
#[derive(
    Clone,
    Copy,
    Debug,
    Eq,
    PartialEq,
    PartialOrd,
    Ord,
    Hash,
    strum::Display,
    strum::EnumString,
)]
#[strum(serialize_all = "SCREAMING_SNAKE_CASE")]
pub enum TransactionOperation {
    /// An unrecognized or unknown operation type.
    Unknown,
    /// A `BEGIN` transaction statement.
    Begin,
    /// A `RELEASE` savepoint statement.
    Release,
    /// A `ROLLBACK` statement.
    Rollback,
}

/// Converts this crate's [`TransactionOperation`] into rusqlite's equivalent
/// for use in authorization hook responses.
impl From<TransactionOperation> for rusqlite::hooks::TransactionOperation {
    fn from(value: TransactionOperation) -> Self {
        match value {
            TransactionOperation::Unknown => Self::Unknown,
            TransactionOperation::Begin => Self::Begin,
            TransactionOperation::Release => Self::Release,
            TransactionOperation::Rollback => Self::Rollback,
        }
    }
}

/// Allows comparing this crate's [`TransactionOperation`] against rusqlite's
/// variant by converting to the rusqlite type first.
impl PartialEq<rusqlite::hooks::TransactionOperation> for TransactionOperation {
    fn eq(&self, other: &rusqlite::hooks::TransactionOperation) -> bool {
        &rusqlite::hooks::TransactionOperation::from(*self) == other
    }
}

/// Allows comparing rusqlite's `TransactionOperation` against this crate's
/// [`TransactionOperation`] by converting to the rusqlite type first.
impl PartialEq<TransactionOperation> for rusqlite::hooks::TransactionOperation {
    fn eq(&self, other: &TransactionOperation) -> bool {
        &rusqlite::hooks::TransactionOperation::from(*other) == self
    }
}

/// Enumerates the ways parsing an access control selector string can fail.
///
/// Each variant captures the original input string together with contextual
/// information about what went wrong, so that error messages can be actionable
/// and specific.
#[derive(Debug, thiserror::Error)]
pub enum AccessControlSelectorParseError {
    /// The input string could not be split into an identifier portion at all.
    ///
    /// This typically means the string was empty or otherwise malformed in a
    /// way that prevented even the first token from being extracted.
    #[error(
        "no access control selector identifier found in \"{access_control_selector_string}\", \
         expected \"{expected}\""
    )]
    NoAccessControlSelectorIdentifierFound {
        /// The identifier that was expected (set by the specific struct's
        /// `FromStr`).
        expected: String,
        /// The raw input string that failed to parse.
        access_control_selector_string: String,
    },
    /// The identifier was successfully extracted but does not match the target
    /// struct's name.
    ///
    /// Returned when parsing into a specific selector type (e.g.,
    /// `"Write".parse::<Read>()`) where the identifier does not agree with the
    /// struct being parsed into.
    #[error(
        "incorrect access control selector identifier in \"{access_control_selector_string}\": \
         expected \"{expected}\", found \"{found}\""
    )]
    IncorrectAccessControlSelectorIdentifier {
        /// The identifier that was expected.
        expected: String,
        /// The identifier that was actually found in the input.
        found: String,
        /// The raw input string that failed to parse.
        access_control_selector_string: String,
    },
    /// The identifier does not match any known selector variant in the
    /// [`AccessControlSelector`] enum.
    ///
    /// Returned when parsing through the umbrella enum and the leading token is
    /// not recognized.
    #[error(
        "invalid access control selector identifier in \"{access_control_selector_string}\": \
         found {found:?}, expected one of {expected:?}"
    )]
    InvalidAccessControlSelectorIdentifier {
        /// The identifier that was found, or `None` if extraction failed.
        found: Option<String>,
        /// The set of valid selector identifiers.
        expected: &'static [&'static str],
        /// The raw input string that failed to parse.
        access_control_selector_string: String,
    },
    /// A `(` was found but the matching `)` was missing.
    #[error(
        "no closing parenthesis found in \"{access_control_selector_string}\""
    )]
    NoClosingBraceFound {
        /// The raw input string that failed to parse.
        access_control_selector_string: String,
    },
    /// The number of dot-separated fields inside the parentheses exceeds the
    /// maximum that the target struct declares.
    #[error(
        "invalid number of fields in \"{access_control_selector_string}\": \
         found {found}, maximum expected {maximum_expected}"
    )]
    InvalidNumberOfFields {
        /// The number of fields found in the input.
        found: usize,
        /// The maximum number of fields the target struct accepts.
        maximum_expected: usize,
        /// The raw input string that failed to parse.
        access_control_selector_string: String,
    },
    /// An individual field value inside the parentheses could not be parsed
    /// into its target type.
    #[error(
        "failed to parse field \"{field_ident}\" with value \"{field_value}\": {error}"
    )]
    FailedToParseFieldValue {
        /// The name of the struct field that failed to parse.
        field_ident: String,
        /// The raw string value that could not be converted.
        field_value: String,
        /// The underlying parse error.
        error: Box<dyn Error + Send + Sync>,
    },
}

/// Predefined permission presets for common access control configurations.
///
/// Each variant maps to an [`AuthorizationResolver`] constructor that sets
/// sensible defaults for a particular use case. Variants are ordered from most
/// restrictive to least restrictive. The preset is selected via the `--preset`
/// CLI flag and determines the baseline permissions before any `--allow` /
/// `--deny` overrides are applied.
#[derive(
    Clone,
    Copy,
    Debug,
    Default,
    PartialEq,
    Eq,
    PartialOrd,
    Ord,
    Hash,
    strum::Display,
    strum::EnumString,
    clap::ValueEnum,
)]
#[strum(serialize_all = "kebab-case")]
pub enum Preset {
    /// Denies all operations. Useful as a starting point when every permitted
    /// action must be explicitly allowed via `--allow` flags.
    DenyEverything,
    /// Allows reads, selects, transactions, SQL functions, recursive CTEs, and
    /// pragmas. Denies all data modification and DDL.
    #[default]
    ReadOnly,
    /// Extends read-only with insert, update, delete, savepoints, analyze,
    /// reindex, and temporary object operations. Permanent DDL, attach, and
    /// detach remain denied.
    ReadWrite,
    /// Extends read-write with permanent DDL (create/drop tables, indexes,
    /// triggers, views, and alter table). Attach, detach, and virtual table
    /// operations remain denied.
    FullDdl,
    /// Allows all operations with no restrictions. Intended for development and
    /// testing only.
    AllowEverything,
}

/// Converts a [`Preset`] into the corresponding [`AuthorizationResolver`] by
/// calling the matching constructor.
impl From<Preset> for AuthorizationResolver {
    fn from(preset: Preset) -> Self {
        match preset {
            Preset::DenyEverything => Self::new_deny_everything(),
            Preset::ReadOnly => Self::new_read_only(),
            Preset::ReadWrite => Self::new_read_write(),
            Preset::FullDdl => Self::new_full_ddl(),
            Preset::AllowEverything => Self::new_allow_everything(),
        }
    }
}

impl AuthorizationResolver {
    /// Creates a read-only resolver.
    ///
    /// Allows reads, selects, transactions, SQL functions, recursive CTEs, and
    /// pragmas. Denies all data modification (insert, update, delete) and all
    /// DDL (create, drop, alter, attach, detach). Users can layer additional
    /// `--allow` / `--deny` rules on top to fine-tune access.
    pub fn new_read_only() -> Self {
        use rusqlite::hooks::Authorization::Allow;

        Self::new_deny_everything()
            .with_read_default_permissions(Allow)
            .with_select_default_permissions(Allow)
            .with_transaction_default_permissions(Allow)
            .with_function_default_permissions(Allow)
            .with_recursive_default_permissions(Allow)
            .with_pragma_default_permissions(Allow)
    }

    /// Creates a read-write resolver that forbids schema changes.
    ///
    /// Extends [`new_read_only`](Self::new_read_only) with insert, update,
    /// delete, savepoints, analyze, reindex, and temporary object
    /// creation/deletion. Permanent DDL (create/drop table, index, trigger,
    /// view, virtual table), attach, and detach remain denied.
    pub fn new_read_write() -> Self {
        use rusqlite::hooks::Authorization::Allow;

        Self::new_read_only()
            .with_insert_default_permissions(Allow)
            .with_update_default_permissions(Allow)
            .with_delete_default_permissions(Allow)
            .with_savepoint_default_permissions(Allow)
            .with_analyze_default_permissions(Allow)
            .with_reindex_default_permissions(Allow)
            .with_create_temp_table_default_permissions(Allow)
            .with_create_temp_index_default_permissions(Allow)
            .with_create_temp_view_default_permissions(Allow)
            .with_create_temp_trigger_default_permissions(Allow)
            .with_drop_temp_table_default_permissions(Allow)
            .with_drop_temp_index_default_permissions(Allow)
            .with_drop_temp_view_default_permissions(Allow)
            .with_drop_temp_trigger_default_permissions(Allow)
    }

    /// Creates a resolver that allows all data and DDL operations but denies
    /// operations that reach outside the database file.
    ///
    /// Extends [`new_read_write`](Self::new_read_write) with permanent DDL
    /// (create/drop tables, indexes, triggers, views, and alter table). Attach,
    /// detach, and virtual table operations remain denied because they can
    /// access the filesystem or load arbitrary code.
    pub fn new_full_ddl() -> Self {
        use rusqlite::hooks::Authorization::Allow;

        Self::new_read_write()
            .with_create_table_default_permissions(Allow)
            .with_drop_table_default_permissions(Allow)
            .with_alter_table_default_permissions(Allow)
            .with_create_index_default_permissions(Allow)
            .with_drop_index_default_permissions(Allow)
            .with_create_trigger_default_permissions(Allow)
            .with_drop_trigger_default_permissions(Allow)
            .with_create_view_default_permissions(Allow)
            .with_drop_view_default_permissions(Allow)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn glob_display_shows_asterisk() {
        // Arrange
        let glob = Glob;

        // Act
        let displayed = glob.to_string();

        // Assert
        assert_eq!(displayed, "*");
    }

    #[test]
    fn value_or_glob_new_value_creates_value_variant() {
        // Arrange
        let input = "hello";

        // Act
        let vog = ValueOrGlob::<String>::new_value(input);

        // Assert
        assert_eq!(vog, ValueOrGlob::Value("hello".to_string()));
    }

    #[test]
    fn value_or_glob_new_glob_creates_glob_variant() {
        // Arrange
        // (no setup needed)

        // Act
        let vog = ValueOrGlob::<String>::new_glob();

        // Assert
        assert_eq!(vog, ValueOrGlob::Glob(Glob));
    }

    #[test]
    fn value_or_glob_default_returns_glob() {
        // Arrange
        // (no setup needed)

        // Act
        let vog = ValueOrGlob::<String>::default();

        // Assert
        assert_eq!(vog, ValueOrGlob::Glob(Glob));
    }

    #[test]
    fn value_or_glob_is_value_returns_true_for_value() {
        // Arrange
        let vog = ValueOrGlob::<String>::new_value("test");

        // Act
        let result = vog.is_value();

        // Assert
        assert!(result);
    }

    #[test]
    fn value_or_glob_is_value_returns_false_for_glob() {
        // Arrange
        let vog = ValueOrGlob::<String>::new_glob();

        // Act
        let result = vog.is_value();

        // Assert
        assert!(!result);
    }

    #[test]
    fn value_or_glob_is_glob_returns_true_for_glob() {
        // Arrange
        let vog = ValueOrGlob::<String>::new_glob();

        // Act
        let result = vog.is_glob();

        // Assert
        assert!(result);
    }

    #[test]
    fn value_or_glob_is_glob_returns_false_for_value() {
        // Arrange
        let vog = ValueOrGlob::<String>::new_value("test");

        // Act
        let result = vog.is_glob();

        // Assert
        assert!(!result);
    }

    #[test]
    fn value_or_glob_as_value_returns_some_for_value() {
        // Arrange
        let vog = ValueOrGlob::<String>::new_value("hello");

        // Act
        let result = vog.as_value();

        // Assert
        assert_eq!(result, Some(&"hello".to_string()));
    }

    #[test]
    fn value_or_glob_as_value_returns_none_for_glob() {
        // Arrange
        let vog = ValueOrGlob::<String>::new_glob();

        // Act
        let result = vog.as_value();

        // Assert
        assert_eq!(result, None);
    }

    #[test]
    fn value_or_glob_as_glob_returns_some_for_glob() {
        // Arrange
        let vog = ValueOrGlob::<String>::new_glob();

        // Act
        let result = vog.as_glob();

        // Assert
        assert_eq!(result, Some(&Glob));
    }

    #[test]
    fn value_or_glob_as_glob_returns_none_for_value() {
        // Arrange
        let vog = ValueOrGlob::<String>::new_value("test");

        // Act
        let result = vog.as_glob();

        // Assert
        assert_eq!(result, None);
    }

    #[test]
    fn value_or_glob_into_value_returns_some_for_value() {
        // Arrange
        let vog = ValueOrGlob::<String>::new_value("hello");

        // Act
        let result = vog.into_value();

        // Assert
        assert_eq!(result, Some("hello".to_string()));
    }

    #[test]
    fn value_or_glob_into_value_returns_none_for_glob() {
        // Arrange
        let vog = ValueOrGlob::<String>::new_glob();

        // Act
        let result = vog.into_value();

        // Assert
        assert_eq!(result, None);
    }

    #[test]
    fn value_or_glob_into_glob_returns_some_for_glob() {
        // Arrange
        let vog = ValueOrGlob::<String>::new_glob();

        // Act
        let result = vog.into_glob();

        // Assert
        assert_eq!(result, Some(Glob));
    }

    #[test]
    fn value_or_glob_into_glob_returns_none_for_value() {
        // Arrange
        let vog = ValueOrGlob::<String>::new_value("test");

        // Act
        let result = vog.into_glob();

        // Assert
        assert_eq!(result, None);
    }

    #[test]
    fn value_or_glob_display_shows_inner_value_for_value() {
        // Arrange
        let vog = ValueOrGlob::<String>::new_value("Students");

        // Act
        let displayed = vog.to_string();

        // Assert
        assert_eq!(displayed, "Students");
    }

    #[test]
    fn value_or_glob_display_shows_asterisk_for_glob() {
        // Arrange
        let vog = ValueOrGlob::<String>::new_glob();

        // Act
        let displayed = vog.to_string();

        // Assert
        assert_eq!(displayed, "*");
    }

    #[test]
    fn value_or_glob_from_str_with_asterisk_returns_glob() {
        // Arrange
        let input = "*";

        // Act
        let result = input.parse::<ValueOrGlob<String>>().unwrap();

        // Assert
        assert_eq!(result, ValueOrGlob::Glob(Glob));
    }

    #[test]
    fn value_or_glob_from_str_with_text_returns_value() {
        // Arrange
        let input = "Students";

        // Act
        let result = input.parse::<ValueOrGlob<String>>().unwrap();

        // Assert
        assert_eq!(result, ValueOrGlob::Value("Students".to_string()));
    }

    #[test]
    fn value_or_glob_from_some_option_gives_value() {
        // Arrange
        let opt = Some("name".to_string());

        // Act
        let vog = ValueOrGlob::<String>::from(opt);

        // Assert
        assert_eq!(vog, ValueOrGlob::Value("name".to_string()));
    }

    #[test]
    fn value_or_glob_from_none_option_gives_glob() {
        // Arrange
        let opt = Option::<String>::None;

        // Act
        let vog = ValueOrGlob::<String>::from(opt);

        // Assert
        assert_eq!(vog, ValueOrGlob::Glob(Glob));
    }

    #[test]
    fn value_or_glob_into_string_for_value() {
        // Arrange
        let vog = ValueOrGlob::<String>::new_value("hello");

        // Act
        let s = String::from(vog);

        // Assert
        assert_eq!(s, "hello");
    }

    #[test]
    fn value_or_glob_into_string_for_glob() {
        // Arrange
        let vog = ValueOrGlob::<String>::new_glob();

        // Act
        let s = String::from(vog);

        // Assert
        assert_eq!(s, "*");
    }

    #[test]
    fn read_new_creates_with_given_values() {
        // Arrange
        let table = ValueOrGlob::<String>::new_value("Students");
        let column = ValueOrGlob::<String>::new_value("name");

        // Act
        let read = Read::new(table, column);

        // Assert
        assert_eq!(read.table_name, ValueOrGlob::Value("Students".to_string()));
        assert_eq!(read.column_name, ValueOrGlob::Value("name".to_string()));
    }

    #[test]
    fn read_empty_creates_with_all_globs() {
        // Arrange
        // (no setup needed)

        // Act
        let read = Read::empty();

        // Assert
        assert_eq!(read.table_name, ValueOrGlob::Glob(Glob));
        assert_eq!(read.column_name, ValueOrGlob::Glob(Glob));
    }

    #[test]
    fn read_with_table_name_sets_table_name() {
        // Arrange
        let read = Read::empty();

        // Act
        let read =
            read.with_table_name(ValueOrGlob::<String>::new_value("Grades"));

        // Assert
        assert_eq!(read.table_name, ValueOrGlob::Value("Grades".to_string()));
        assert_eq!(read.column_name, ValueOrGlob::Glob(Glob));
    }

    #[test]
    fn read_with_column_name_sets_column_name() {
        // Arrange
        let read = Read::empty();

        // Act
        let read =
            read.with_column_name(ValueOrGlob::<String>::new_value("score"));

        // Assert
        assert_eq!(read.table_name, ValueOrGlob::Glob(Glob));
        assert_eq!(read.column_name, ValueOrGlob::Value("score".to_string()));
    }

    #[test]
    fn read_is_all_glob_true_when_both_glob() {
        // Arrange
        let read = Read::empty();

        // Act
        let result = read.is_all_glob();

        // Assert
        assert!(result);
    }

    #[test]
    fn read_is_all_glob_false_when_table_is_value() {
        // Arrange
        let read = Read::empty()
            .with_table_name(ValueOrGlob::<String>::new_value("Students"));

        // Act
        let result = read.is_all_glob();

        // Assert
        assert!(!result);
    }

    #[test]
    fn read_is_all_glob_false_when_column_is_value() {
        // Arrange
        let read = Read::empty()
            .with_column_name(ValueOrGlob::<String>::new_value("name"));

        // Act
        let result = read.is_all_glob();

        // Assert
        assert!(!result);
    }

    #[test]
    fn read_is_all_value_true_when_both_value() {
        // Arrange
        let read = Read::new(
            ValueOrGlob::<String>::new_value("Students"),
            ValueOrGlob::<String>::new_value("name"),
        );

        // Act
        let result = read.is_all_value();

        // Assert
        assert!(result);
    }

    #[test]
    fn read_is_all_value_false_when_one_is_glob() {
        // Arrange
        let read = Read::empty()
            .with_table_name(ValueOrGlob::<String>::new_value("Students"));

        // Act
        let result = read.is_all_value();

        // Assert
        assert!(!result);
    }

    #[test]
    fn read_is_any_glob_true_when_one_is_glob() {
        // Arrange
        let read = Read::empty()
            .with_table_name(ValueOrGlob::<String>::new_value("Students"));

        // Act
        let result = read.is_any_glob();

        // Assert
        assert!(result);
    }

    #[test]
    fn read_is_any_glob_false_when_both_value() {
        // Arrange
        let read = Read::new(
            ValueOrGlob::<String>::new_value("Students"),
            ValueOrGlob::<String>::new_value("name"),
        );

        // Act
        let result = read.is_any_glob();

        // Assert
        assert!(!result);
    }

    #[test]
    fn read_is_any_value_true_when_one_is_value() {
        // Arrange
        let read = Read::empty()
            .with_column_name(ValueOrGlob::<String>::new_value("name"));

        // Act
        let result = read.is_any_value();

        // Assert
        assert!(result);
    }

    #[test]
    fn read_is_any_value_false_when_both_glob() {
        // Arrange
        let read = Read::empty();

        // Act
        let result = read.is_any_value();

        // Assert
        assert!(!result);
    }

    #[test]
    fn read_display_all_glob_shows_read_without_parens() {
        // Arrange
        let read = Read::empty();

        // Act
        let displayed = read.to_string();

        // Assert
        assert_eq!(displayed, "Read");
    }

    #[test]
    fn read_display_specific_shows_read_with_table_and_column() {
        // Arrange
        let read = Read::new(
            ValueOrGlob::<String>::new_value("Students"),
            ValueOrGlob::<String>::new_value("name"),
        );

        // Act
        let displayed = read.to_string();

        // Assert
        assert_eq!(displayed, "Read(Students.name)");
    }

    #[test]
    fn read_display_glob_table_value_column() {
        // Arrange
        let read = Read::empty()
            .with_column_name(ValueOrGlob::<String>::new_value("name"));

        // Act
        let displayed = read.to_string();

        // Assert
        assert_eq!(displayed, "Read(*.name)");
    }

    #[test]
    fn read_display_value_table_glob_column() {
        // Arrange
        let read = Read::empty()
            .with_table_name(ValueOrGlob::<String>::new_value("Students"));

        // Act
        let displayed = read.to_string();

        // Assert
        assert_eq!(displayed, "Read(Students.*)");
    }

    #[test]
    fn read_from_str_bare_read_parses_to_all_glob() {
        // Arrange
        let input = "Read";

        // Act
        let read = input.parse::<Read>().unwrap();

        // Assert
        assert_eq!(read.table_name, ValueOrGlob::Glob(Glob));
        assert_eq!(read.column_name, ValueOrGlob::Glob(Glob));
    }

    #[test]
    fn read_from_str_specific_table_and_column_parses_correctly() {
        // Arrange
        let input = "Read(Students.name)";

        // Act
        let read = input.parse::<Read>().unwrap();

        // Assert
        assert_eq!(read.table_name, ValueOrGlob::Value("Students".to_string()));
        assert_eq!(read.column_name, ValueOrGlob::Value("name".to_string()));
    }

    #[test]
    fn read_from_str_glob_table_value_column_parses_correctly() {
        // Arrange
        let input = "Read(*.name)";

        // Act
        let read = input.parse::<Read>().unwrap();

        // Assert
        assert_eq!(read.table_name, ValueOrGlob::Glob(Glob));
        assert_eq!(read.column_name, ValueOrGlob::Value("name".to_string()));
    }

    #[test]
    fn read_from_str_value_table_glob_column_parses_correctly() {
        // Arrange
        let input = "Read(Students.*)";

        // Act
        let read = input.parse::<Read>().unwrap();

        // Assert
        assert_eq!(read.table_name, ValueOrGlob::Value("Students".to_string()));
        assert_eq!(read.column_name, ValueOrGlob::Glob(Glob));
    }

    #[test]
    fn read_from_str_round_trip_produces_same_result() {
        // Arrange
        let input = "Read(Students.name)";

        // Act
        let read = input.parse::<Read>().unwrap();
        let displayed = read.to_string();
        let reparsed = displayed.parse::<Read>().unwrap();

        // Assert
        assert_eq!(
            reparsed.table_name,
            ValueOrGlob::Value("Students".to_string())
        );
        assert_eq!(
            reparsed.column_name,
            ValueOrGlob::Value("name".to_string())
        );
    }

    #[test]
    fn read_from_str_round_trip_bare_read_produces_same_result() {
        // Arrange
        let input = "Read";

        // Act
        let read = input.parse::<Read>().unwrap();
        let displayed = read.to_string();
        let reparsed = displayed.parse::<Read>().unwrap();

        // Assert
        assert_eq!(reparsed.table_name, ValueOrGlob::Glob(Glob));
        assert_eq!(reparsed.column_name, ValueOrGlob::Glob(Glob));
        assert_eq!(displayed, "Read");
    }

    #[test]
    fn read_into_string_works() {
        // Arrange
        let read = Read::new(
            ValueOrGlob::<String>::new_value("Students"),
            ValueOrGlob::<String>::new_value("name"),
        );

        // Act
        let s = String::from(read);

        // Assert
        assert_eq!(s, "Read(Students.name)");
    }

    #[test]
    fn read_try_from_string_works() {
        // Arrange
        let input = "Read(Students.name)".to_string();

        // Act
        let read = Read::try_from(input).unwrap();

        // Assert
        assert_eq!(read.table_name, ValueOrGlob::Value("Students".to_string()));
        assert_eq!(read.column_name, ValueOrGlob::Value("name".to_string()));
    }

    #[test]
    fn access_control_selector_from_str_bare_read_parses_to_read_selector() {
        // Arrange
        let input = "Read";

        // Act
        let selector = input.parse::<AccessControlSelector>().unwrap();

        // Assert
        match selector {
            AccessControlSelector::Read(read) => {
                assert_eq!(read.table_name, ValueOrGlob::Glob(Glob));
                assert_eq!(read.column_name, ValueOrGlob::Glob(Glob));
            }
            other => panic!("expected ReadSelector, got {other}"),
        }
    }

    #[test]
    fn access_control_selector_from_str_specific_parses_correctly() {
        // Arrange
        let input = "Read(Students.name)";

        // Act
        let selector = input.parse::<AccessControlSelector>().unwrap();

        // Assert
        match selector {
            AccessControlSelector::Read(read) => {
                assert_eq!(
                    read.table_name,
                    ValueOrGlob::Value("Students".to_string())
                );
                assert_eq!(
                    read.column_name,
                    ValueOrGlob::Value("name".to_string())
                );
            }
            other => panic!("expected ReadSelector, got {other}"),
        }
    }

    #[test]
    fn access_control_selector_display_round_trip_works() {
        // Arrange
        let input = "Read(Students.name)";

        // Act
        let selector = input.parse::<AccessControlSelector>().unwrap();
        let displayed = selector.to_string();
        let reparsed = displayed.parse::<AccessControlSelector>().unwrap();

        // Assert
        match reparsed {
            AccessControlSelector::Read(read) => {
                assert_eq!(
                    read.table_name,
                    ValueOrGlob::Value("Students".to_string())
                );
                assert_eq!(
                    read.column_name,
                    ValueOrGlob::Value("name".to_string())
                );
            }
            other => panic!("expected ReadSelector, got {other}"),
        }
    }

    #[test]
    fn access_control_selector_try_from_string_works() {
        // Arrange
        let input = "Read(Students.name)".to_string();

        // Act
        let selector = AccessControlSelector::try_from(input).unwrap();

        // Assert
        match selector {
            AccessControlSelector::Read(read) => {
                assert_eq!(
                    read.table_name,
                    ValueOrGlob::Value("Students".to_string())
                );
                assert_eq!(
                    read.column_name,
                    ValueOrGlob::Value("name".to_string())
                );
            }
            other => panic!("expected ReadSelector, got {other}"),
        }
    }

    #[test]
    fn parsing_with_missing_closing_paren_returns_error() {
        // Arrange
        let input = "Read(Students.name";

        // Act
        let result = input.parse::<Read>();

        // Assert
        assert!(matches!(
            result,
            Err(AccessControlSelectorParseError::NoClosingBraceFound { .. })
        ));
    }

    #[test]
    fn parsing_with_too_many_fields_returns_error() {
        // Arrange
        let input = "Read(Students.name.extra)";

        // Act
        let result = input.parse::<Read>();

        // Assert
        assert!(matches!(
            result,
            Err(AccessControlSelectorParseError::InvalidNumberOfFields { .. })
        ));
    }

    #[test]
    fn parsing_with_wrong_identifier_returns_error_for_struct() {
        // Arrange
        let input = "Write(Students.name)";

        // Act
        let result = input.parse::<Read>();

        // Assert
        assert!(matches!(
            result,
            Err(
                AccessControlSelectorParseError::IncorrectAccessControlSelectorIdentifier {
                    ..
                }
            )
        ));
    }

    #[test]
    fn parsing_with_wrong_identifier_returns_error_for_enum() {
        // Arrange
        let input = "Write(Students.name)";

        // Act
        let result = input.parse::<AccessControlSelector>();

        // Assert
        assert!(matches!(
            result,
            Err(
                AccessControlSelectorParseError::InvalidAccessControlSelectorIdentifier {
                    ..
                }
            )
        ));
    }

    #[test]
    fn parsing_empty_string_returns_error_for_enum() {
        // Arrange
        let input = "";

        // Act
        let result = input.parse::<AccessControlSelector>();

        // Assert
        assert!(result.is_err());
    }

    #[test]
    fn parsing_empty_string_returns_error_for_struct() {
        // Arrange
        let input = "";

        // Act
        let result = input.parse::<Read>();

        // Assert
        assert!(matches!(
            result,
            Err(
                AccessControlSelectorParseError::IncorrectAccessControlSelectorIdentifier {
                    ..
                }
            )
        ));
    }

    #[test]
    fn empty_selector_set_returns_none_for_read() {
        // Arrange
        let set = AccessControlSelectorSet::new();

        // Act
        let result = set.check_read("Students", "name");

        // Assert
        assert_eq!(result, None);
    }

    #[test]
    fn single_allow_rule_matches_and_returns_allow() {
        // Arrange
        let set = AccessControlSelectorSet::new()
            .with_read_selector(Read::empty(), true);

        // Act
        let result = set.check_read("Students", "name");

        // Assert
        assert_eq!(result, Some(Authorization::Allow));
    }

    #[test]
    fn single_deny_rule_matches_and_returns_deny() {
        // Arrange
        let set = AccessControlSelectorSet::new()
            .with_read_selector(Read::empty(), false);

        // Act
        let result = set.check_read("Students", "name");

        // Assert
        assert_eq!(result, Some(Authorization::Deny));
    }

    #[test]
    fn single_allow_rule_that_does_not_match_returns_none() {
        // Arrange
        let set = AccessControlSelectorSet::new().with_read_selector(
            Read::new(
                ValueOrGlob::new_value("Secrets"),
                ValueOrGlob::new_glob(),
            ),
            true,
        );

        // Act
        let result = set.check_read("Students", "name");

        // Assert
        assert_eq!(result, None);
    }

    #[test]
    fn single_deny_rule_that_does_not_match_returns_none() {
        // Arrange
        let set = AccessControlSelectorSet::new().with_read_selector(
            Read::new(
                ValueOrGlob::new_value("Secrets"),
                ValueOrGlob::new_glob(),
            ),
            false,
        );

        // Act
        let result = set.check_read("Students", "name");

        // Assert
        assert_eq!(result, None);
    }

    #[test]
    fn higher_specificity_allow_beats_lower_specificity_deny() {
        // Arrange
        let set = AccessControlSelectorSet::new()
            .with_read_selector(Read::empty(), false)
            .with_read_selector(
                Read::new(
                    ValueOrGlob::new_value("Students"),
                    ValueOrGlob::new_glob(),
                ),
                true,
            );

        // Act
        let result = set.check_read("Students", "name");

        // Assert
        assert_eq!(result, Some(Authorization::Allow));
    }

    #[test]
    fn higher_specificity_deny_beats_lower_specificity_allow() {
        // Arrange
        let set = AccessControlSelectorSet::new()
            .with_read_selector(Read::empty(), true)
            .with_read_selector(
                Read::new(
                    ValueOrGlob::new_value("Secrets"),
                    ValueOrGlob::new_glob(),
                ),
                false,
            );

        // Act
        let result = set.check_read("Secrets", "ssn");

        // Assert
        assert_eq!(result, Some(Authorization::Deny));
    }

    #[test]
    fn specificity_2_beats_specificity_1_beats_specificity_0() {
        // Arrange
        let set = AccessControlSelectorSet::new()
            .with_read_selector(Read::empty(), true)
            .with_read_selector(
                Read::new(
                    ValueOrGlob::new_value("Secrets"),
                    ValueOrGlob::new_glob(),
                ),
                false,
            )
            .with_read_selector(
                Read::new(
                    ValueOrGlob::new_value("Secrets"),
                    ValueOrGlob::new_value("id"),
                ),
                true,
            );

        // Act
        let allow_all = set.check_read("Public", "data");
        let deny_table = set.check_read("Secrets", "ssn");
        let allow_carveout = set.check_read("Secrets", "id");

        // Assert
        assert_eq!(allow_all, Some(Authorization::Allow));
        assert_eq!(deny_table, Some(Authorization::Deny));
        assert_eq!(allow_carveout, Some(Authorization::Allow));
    }

    #[test]
    fn same_specificity_allow_and_deny_resolves_to_deny() {
        // Arrange
        let set = AccessControlSelectorSet::new()
            .with_read_selector(
                Read::new(
                    ValueOrGlob::new_value("Students"),
                    ValueOrGlob::new_glob(),
                ),
                true,
            )
            .with_read_selector(
                Read::new(
                    ValueOrGlob::new_glob(),
                    ValueOrGlob::new_value("name"),
                ),
                false,
            );

        // Act
        let result = set.check_read("Students", "name");

        // Assert
        assert_eq!(result, Some(Authorization::Deny));
    }

    #[test]
    fn same_specificity_multiple_allows_no_deny_returns_allow() {
        // Arrange
        let set = AccessControlSelectorSet::new()
            .with_read_selector(
                Read::new(ValueOrGlob::new_value("A"), ValueOrGlob::new_glob()),
                true,
            )
            .with_read_selector(
                Read::new(ValueOrGlob::new_glob(), ValueOrGlob::new_value("x")),
                true,
            );

        // Act
        let result = set.check_read("A", "x");

        // Assert
        assert_eq!(result, Some(Authorization::Allow));
    }

    #[test]
    fn same_specificity_multiple_denys_no_allow_returns_deny() {
        // Arrange
        let set = AccessControlSelectorSet::new()
            .with_read_selector(
                Read::new(ValueOrGlob::new_value("A"), ValueOrGlob::new_glob()),
                false,
            )
            .with_read_selector(
                Read::new(ValueOrGlob::new_glob(), ValueOrGlob::new_value("x")),
                false,
            );

        // Act
        let result = set.check_read("A", "x");

        // Assert
        assert_eq!(result, Some(Authorization::Deny));
    }

    #[test]
    fn non_matching_rules_are_skipped_to_lower_specificity() {
        // Arrange
        let set = AccessControlSelectorSet::new()
            .with_read_selector(Read::empty(), true)
            .with_read_selector(
                Read::new(
                    ValueOrGlob::new_value("Other"),
                    ValueOrGlob::new_glob(),
                ),
                false,
            );

        // Act
        let result = set.check_read("Students", "name");

        // Assert
        assert_eq!(result, Some(Authorization::Allow));
    }

    #[test]
    fn rules_with_specificity_gap_still_resolve_correctly() {
        // Arrange
        let set = AccessControlSelectorSet::new()
            .with_read_selector(Read::empty(), false)
            .with_read_selector(
                Read::new(
                    ValueOrGlob::new_value("Students"),
                    ValueOrGlob::new_value("name"),
                ),
                true,
            );

        // Act
        let carveout = set.check_read("Students", "name");
        let blocked = set.check_read("Students", "ssn");

        // Assert
        assert_eq!(carveout, Some(Authorization::Allow));
        assert_eq!(blocked, Some(Authorization::Deny));
    }

    #[test]
    fn glob_table_pinned_column_matches_any_table() {
        // Arrange
        let set = AccessControlSelectorSet::new().with_read_selector(
            Read::new(ValueOrGlob::new_glob(), ValueOrGlob::new_value("ssn")),
            false,
        );

        // Act
        let result_a = set.check_read("Students", "ssn");
        let result_b = set.check_read("Employees", "ssn");
        let result_c = set.check_read("Students", "name");

        // Assert
        assert_eq!(result_a, Some(Authorization::Deny));
        assert_eq!(result_b, Some(Authorization::Deny));
        assert_eq!(result_c, None);
    }

    #[test]
    fn pinned_table_glob_column_matches_any_column() {
        // Arrange
        let set = AccessControlSelectorSet::new().with_read_selector(
            Read::new(
                ValueOrGlob::new_value("Secrets"),
                ValueOrGlob::new_glob(),
            ),
            false,
        );

        // Act
        let result_a = set.check_read("Secrets", "ssn");
        let result_b = set.check_read("Secrets", "id");
        let result_c = set.check_read("Public", "data");

        // Assert
        assert_eq!(result_a, Some(Authorization::Deny));
        assert_eq!(result_b, Some(Authorization::Deny));
        assert_eq!(result_c, None);
    }

    #[test]
    fn fully_pinned_selector_matches_only_exact_pair() {
        // Arrange
        let set = AccessControlSelectorSet::new().with_read_selector(
            Read::new(
                ValueOrGlob::new_value("Students"),
                ValueOrGlob::new_value("name"),
            ),
            false,
        );

        // Act
        let exact = set.check_read("Students", "name");
        let wrong_col = set.check_read("Students", "id");
        let wrong_table = set.check_read("Other", "name");

        // Assert
        assert_eq!(exact, Some(Authorization::Deny));
        assert_eq!(wrong_col, None);
        assert_eq!(wrong_table, None);
    }

    #[test]
    fn read_rules_do_not_affect_delete_checks() {
        // Arrange
        let set = AccessControlSelectorSet::new()
            .with_read_selector(Read::empty(), false);

        // Act
        let read_result = set.check_read("Students", "name");
        let delete_result = set.check_delete("Students");

        // Assert
        assert_eq!(read_result, Some(Authorization::Deny));
        assert_eq!(delete_result, None);
    }

    #[test]
    fn delete_single_field_selector_works() {
        // Arrange
        let set = AccessControlSelectorSet::new()
            .with_delete_selector(Delete::empty(), true)
            .with_delete_selector(
                Delete::new(ValueOrGlob::new_value("AuditLog")),
                false,
            );

        // Act
        let allowed = set.check_delete("Students");
        let denied = set.check_delete("AuditLog");

        // Assert
        assert_eq!(allowed, Some(Authorization::Allow));
        assert_eq!(denied, Some(Authorization::Deny));
    }

    #[test]
    fn select_zero_field_selector_allow_works() {
        // Arrange
        let set = AccessControlSelectorSet::new()
            .with_select_selector(Select {}, true);

        // Act
        let result = set.check_select();

        // Assert
        assert_eq!(result, Some(Authorization::Allow));
    }

    #[test]
    fn select_zero_field_allow_and_deny_resolves_to_deny() {
        // Arrange
        let set = AccessControlSelectorSet::new()
            .with_select_selector(Select {}, true)
            .with_select_selector(Select {}, false);

        // Act
        let result = set.check_select();

        // Assert
        assert_eq!(result, Some(Authorization::Deny));
    }

    #[test]
    fn with_selector_dispatches_to_correct_type() {
        // Arrange
        let read = AccessControlSelector::from(Read::empty());
        let set = AccessControlSelectorSet::new().with_selector(read, false);

        // Act
        let result = set.check_read("anything", "anything");

        // Assert
        assert_eq!(result, Some(Authorization::Deny));
    }

    #[test]
    fn resolver_allow_everything_defaults_to_allow() {
        // Arrange
        let resolver = AuthorizationResolver::new_allow_everything();

        // Act
        let result = resolver.selector_set.check_read("X", "Y");

        // Assert
        assert_eq!(result, None);
        assert_eq!(
            resolver.read_default_permissions,
            rusqlite::hooks::Authorization::Allow,
        );
    }

    #[test]
    fn resolver_deny_everything_defaults_to_deny() {
        // Arrange
        let resolver = AuthorizationResolver::new_deny_everything();

        // Act
        let result = resolver.selector_set.check_read("X", "Y");

        // Assert
        assert_eq!(result, None);
        assert_eq!(
            resolver.read_default_permissions,
            rusqlite::hooks::Authorization::Deny,
        );
    }

    #[test]
    fn resolver_per_action_default_override_works() {
        // Arrange
        let resolver = AuthorizationResolver::new_allow_everything()
            .with_read_default_permissions(
                rusqlite::hooks::Authorization::Deny,
            );

        // Act / Assert
        assert_eq!(
            resolver.read_default_permissions,
            rusqlite::hooks::Authorization::Deny,
        );
        assert_eq!(
            resolver.insert_default_permissions,
            rusqlite::hooks::Authorization::Allow,
        );
    }

    #[test]
    fn doc_example_read_only_with_table_blocked() {
        // Arrange
        let set = AccessControlSelectorSet::new()
            .with_selector("Read".parse::<Read>().unwrap(), true)
            .with_selector("Read(Secrets)".parse::<Read>().unwrap(), false);

        // Act
        let public_read = set.check_read("Public", "data");
        let secrets_read = set.check_read("Secrets", "ssn");

        // Assert
        assert_eq!(public_read, Some(Authorization::Allow));
        assert_eq!(secrets_read, Some(Authorization::Deny));
    }

    #[test]
    fn doc_example_read_only_with_carveout() {
        // Arrange
        let set = AccessControlSelectorSet::new()
            .with_selector("Read".parse::<Read>().unwrap(), true)
            .with_selector("Read(Secrets)".parse::<Read>().unwrap(), false)
            .with_selector("Read(Secrets.id)".parse::<Read>().unwrap(), true);

        // Act
        let public = set.check_read("Public", "data");
        let secrets_ssn = set.check_read("Secrets", "ssn");
        let secrets_id = set.check_read("Secrets", "id");

        // Assert
        assert_eq!(public, Some(Authorization::Allow));
        assert_eq!(secrets_ssn, Some(Authorization::Deny));
        assert_eq!(secrets_id, Some(Authorization::Allow));
    }

    #[test]
    fn doc_example_conflicting_same_specificity() {
        // Arrange
        let set = AccessControlSelectorSet::new()
            .with_selector("Read(Students)".parse::<Read>().unwrap(), false)
            .with_selector("Read(*.name)".parse::<Read>().unwrap(), true);

        // Act
        let result = set.check_read("Students", "name");

        // Assert
        assert_eq!(result, Some(Authorization::Deny));
    }

    #[test]
    fn doc_example_deny_functions_allow_specific() {
        // Arrange
        let set = AccessControlSelectorSet::new()
            .with_selector("Function".parse::<Function>().unwrap(), false)
            .with_selector("Function(count)".parse::<Function>().unwrap(), true)
            .with_selector("Function(sum)".parse::<Function>().unwrap(), true);

        // Act
        let count = set.check_function("count");
        let sum = set.check_function("sum");
        let evil = set.check_function("load_extension");

        // Assert
        assert_eq!(count, Some(Authorization::Allow));
        assert_eq!(sum, Some(Authorization::Allow));
        assert_eq!(evil, Some(Authorization::Deny));
    }

    #[test]
    fn multiple_non_matching_rules_returns_none() {
        // Arrange
        let set = AccessControlSelectorSet::new()
            .with_read_selector(
                Read::new(
                    ValueOrGlob::new_value("A"),
                    ValueOrGlob::new_value("x"),
                ),
                true,
            )
            .with_read_selector(
                Read::new(
                    ValueOrGlob::new_value("B"),
                    ValueOrGlob::new_value("y"),
                ),
                false,
            );

        // Act
        let result = set.check_read("C", "z");

        // Assert
        assert_eq!(result, None);
    }

    #[test]
    fn deny_at_higher_specificity_is_not_overridden_by_lower_allow() {
        // Arrange
        let set = AccessControlSelectorSet::new()
            .with_read_selector(Read::empty(), true)
            .with_read_selector(
                Read::new(
                    ValueOrGlob::new_value("Secrets"),
                    ValueOrGlob::new_value("ssn"),
                ),
                false,
            );

        // Act
        let result = set.check_read("Secrets", "ssn");

        // Assert
        assert_eq!(result, Some(Authorization::Deny));
    }

    #[test]
    fn only_matching_rules_at_a_level_contribute_to_verdict() {
        // Arrange
        let set = AccessControlSelectorSet::new()
            .with_read_selector(
                Read::new(ValueOrGlob::new_value("A"), ValueOrGlob::new_glob()),
                false,
            )
            .with_read_selector(
                Read::new(ValueOrGlob::new_value("B"), ValueOrGlob::new_glob()),
                true,
            );

        // Act
        let result_a = set.check_read("A", "x");
        let result_b = set.check_read("B", "x");

        // Assert
        assert_eq!(result_a, Some(Authorization::Deny));
        assert_eq!(result_b, Some(Authorization::Allow));
    }

    #[test]
    fn insertion_order_does_not_affect_specificity_ranking() {
        // Arrange
        let set = AccessControlSelectorSet::new()
            .with_read_selector(
                Read::new(
                    ValueOrGlob::new_value("T"),
                    ValueOrGlob::new_value("c"),
                ),
                true,
            )
            .with_read_selector(Read::empty(), false);

        // Act
        let result = set.check_read("T", "c");

        // Assert
        assert_eq!(result, Some(Authorization::Allow));
    }

    #[test]
    fn three_specificity_levels_middle_deny_overridden_by_top() {
        // Arrange
        let set = AccessControlSelectorSet::new()
            .with_read_selector(Read::empty(), true)
            .with_read_selector(
                Read::new(ValueOrGlob::new_value("T"), ValueOrGlob::new_glob()),
                false,
            )
            .with_read_selector(
                Read::new(
                    ValueOrGlob::new_value("T"),
                    ValueOrGlob::new_value("ok"),
                ),
                true,
            );

        // Act
        let other_table = set.check_read("X", "y");
        let denied_col = set.check_read("T", "secret");
        let carveout = set.check_read("T", "ok");

        // Assert
        assert_eq!(other_table, Some(Authorization::Allow));
        assert_eq!(denied_col, Some(Authorization::Deny));
        assert_eq!(carveout, Some(Authorization::Allow));
    }

    #[test]
    fn duplicate_allow_rules_still_return_allow() {
        // Arrange
        let set = AccessControlSelectorSet::new()
            .with_read_selector(Read::empty(), true)
            .with_read_selector(Read::empty(), true);

        // Act
        let result = set.check_read("T", "c");

        // Assert
        assert_eq!(result, Some(Authorization::Allow));
    }

    #[test]
    fn duplicate_deny_rules_still_return_deny() {
        // Arrange
        let set = AccessControlSelectorSet::new()
            .with_read_selector(Read::empty(), false)
            .with_read_selector(Read::empty(), false);

        // Act
        let result = set.check_read("T", "c");

        // Assert
        assert_eq!(result, Some(Authorization::Deny));
    }

    #[test]
    fn read_only_allows_reads_and_selects() {
        // Arrange
        let r = AuthorizationResolver::new_read_only();

        // Act / Assert
        assert_eq!(
            r.read_default_permissions,
            rusqlite::hooks::Authorization::Allow,
        );
        assert_eq!(
            r.select_default_permissions,
            rusqlite::hooks::Authorization::Allow,
        );
        assert_eq!(
            r.transaction_default_permissions,
            rusqlite::hooks::Authorization::Allow,
        );
        assert_eq!(
            r.function_default_permissions,
            rusqlite::hooks::Authorization::Allow,
        );
        assert_eq!(
            r.recursive_default_permissions,
            rusqlite::hooks::Authorization::Allow,
        );
        assert_eq!(
            r.pragma_default_permissions,
            rusqlite::hooks::Authorization::Allow,
        );
    }

    #[test]
    fn read_only_denies_writes_and_ddl() {
        // Arrange
        let r = AuthorizationResolver::new_read_only();

        // Act / Assert
        assert_eq!(
            r.insert_default_permissions,
            rusqlite::hooks::Authorization::Deny,
        );
        assert_eq!(
            r.update_default_permissions,
            rusqlite::hooks::Authorization::Deny,
        );
        assert_eq!(
            r.delete_default_permissions,
            rusqlite::hooks::Authorization::Deny,
        );
        assert_eq!(
            r.create_table_default_permissions,
            rusqlite::hooks::Authorization::Deny,
        );
        assert_eq!(
            r.drop_table_default_permissions,
            rusqlite::hooks::Authorization::Deny,
        );
        assert_eq!(
            r.attach_default_permissions,
            rusqlite::hooks::Authorization::Deny,
        );
    }

    #[test]
    fn read_write_allows_data_modification() {
        // Arrange
        let r = AuthorizationResolver::new_read_write();

        // Act / Assert
        assert_eq!(
            r.insert_default_permissions,
            rusqlite::hooks::Authorization::Allow,
        );
        assert_eq!(
            r.update_default_permissions,
            rusqlite::hooks::Authorization::Allow,
        );
        assert_eq!(
            r.delete_default_permissions,
            rusqlite::hooks::Authorization::Allow,
        );
        assert_eq!(
            r.savepoint_default_permissions,
            rusqlite::hooks::Authorization::Allow,
        );
        assert_eq!(
            r.analyze_default_permissions,
            rusqlite::hooks::Authorization::Allow,
        );
    }

    #[test]
    fn read_write_allows_temp_objects_but_denies_permanent_ddl() {
        // Arrange
        let r = AuthorizationResolver::new_read_write();

        // Act / Assert
        assert_eq!(
            r.create_temp_table_default_permissions,
            rusqlite::hooks::Authorization::Allow,
        );
        assert_eq!(
            r.drop_temp_table_default_permissions,
            rusqlite::hooks::Authorization::Allow,
        );
        assert_eq!(
            r.create_table_default_permissions,
            rusqlite::hooks::Authorization::Deny,
        );
        assert_eq!(
            r.drop_table_default_permissions,
            rusqlite::hooks::Authorization::Deny,
        );
        assert_eq!(
            r.alter_table_default_permissions,
            rusqlite::hooks::Authorization::Deny,
        );
        assert_eq!(
            r.attach_default_permissions,
            rusqlite::hooks::Authorization::Deny,
        );
    }

    #[test]
    fn full_ddl_allows_permanent_schema_changes() {
        // Arrange
        let r = AuthorizationResolver::new_full_ddl();

        // Act / Assert
        assert_eq!(
            r.create_table_default_permissions,
            rusqlite::hooks::Authorization::Allow,
        );
        assert_eq!(
            r.drop_table_default_permissions,
            rusqlite::hooks::Authorization::Allow,
        );
        assert_eq!(
            r.alter_table_default_permissions,
            rusqlite::hooks::Authorization::Allow,
        );
        assert_eq!(
            r.create_index_default_permissions,
            rusqlite::hooks::Authorization::Allow,
        );
        assert_eq!(
            r.create_view_default_permissions,
            rusqlite::hooks::Authorization::Allow,
        );
        assert_eq!(
            r.create_trigger_default_permissions,
            rusqlite::hooks::Authorization::Allow,
        );
    }

    #[test]
    fn full_ddl_still_denies_attach_detach_and_vtables() {
        // Arrange
        let r = AuthorizationResolver::new_full_ddl();

        // Act / Assert
        assert_eq!(
            r.attach_default_permissions,
            rusqlite::hooks::Authorization::Deny,
        );
        assert_eq!(
            r.detach_default_permissions,
            rusqlite::hooks::Authorization::Deny,
        );
        assert_eq!(
            r.create_vtable_default_permissions,
            rusqlite::hooks::Authorization::Deny,
        );
        assert_eq!(
            r.drop_vtable_default_permissions,
            rusqlite::hooks::Authorization::Deny,
        );
    }

    #[test]
    fn presets_are_composable_with_per_action_overrides() {
        // Arrange
        let r = AuthorizationResolver::new_read_only()
            .with_insert_default_permissions(
                rusqlite::hooks::Authorization::Allow,
            );

        // Act / Assert
        assert_eq!(
            r.insert_default_permissions,
            rusqlite::hooks::Authorization::Allow,
        );
        assert_eq!(
            r.update_default_permissions,
            rusqlite::hooks::Authorization::Deny,
        );
        assert_eq!(
            r.read_default_permissions,
            rusqlite::hooks::Authorization::Allow,
        );
    }
}