reylo-engine-sqlite 0.8.1

Reylo's analysis engine for SQLite: SQLite's own resolved tree, from an amalgamation patched with the engine's hooks, the function tables and the row-count proof, over the core's protocol.
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
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
//! The SQLite analysis, over SQLite's own resolved tree ([`crate::sqlite_tree`], produced by
//! `csrc/reylo_sqlite.c` from a patched amalgamation). SQLite resolves the names, the join sides,
//! every parameter's context and the DML target columns itself, and reports each expression's
//! affinity. What SQLite has no facts for stays here, as explicit tables: the result type and
//! nullability of the built-in functions, the type a function gives its arguments, the arithmetic
//! rule, and the row-count proof from the unique keys. The host runs two queries, one for the
//! schema DDL and one for the functions its SQLite has; everything else happens inside the engine.
//!
//! Two entries share the code: [`analyze`], replayed through the [`Host`] like every dialect, and
//! [`analyze_ddl`], for a host that holds a live connection and runs [`DDL_QUERY`] and
//! [`FUNCTIONS_QUERY`] on it itself, with [`Extras`] naming the scalar functions it registers there.

use crate::analysis::{bare, constant_key, diag, KeyClause, ResultTarget};
use crate::api::{Analysis, Column, Param, Scope};
use crate::dialect::Dialect;
use crate::fresh::Tables;
use crate::host::{as_str, Host, Lazy};
use crate::lex::{self, Lexed, Target};
use crate::sqlite_tree::{self as tree, From, Node, Sel, Tree};
use crate::types::{Cardinality, Field, FloatType, Kind, StatementKind, TextType, Type};

/// What the analysis reasons in: a value's storage class by the affinity name SQLite gives it
/// (`integer`, `real`, `text`, `blob`, `numeric`; `int8` for a value a column declared 64 bits wide
/// holds, `bool` for a truth value or a column declared BOOLEAN), the JSON a constructor builds,
/// or nothing known. The analysis hands each result column and parameter on as the format's type
/// ([`descriptor`]).
#[derive(Debug, Clone, PartialEq)]
enum Ty {
    Scalar { name: String },
    Object { fields: Vec<TyField> },
    List { of: Box<Ty>, nullable_items: bool },
    Json { schema: Option<serde_json::Value> },
    Unknown,
}

#[derive(Debug, Clone, PartialEq)]
struct TyField {
    name: String,
    ty: Ty,
    nullable: bool,
}
use std::collections::{HashMap, HashSet};

/// The schema, as SQLite stores it: its `sql` column is the DDL the engine replays into its
/// in-memory copy. The replayed entry asks the host for it; a host with a connection of its own
/// runs it there and hands the rows to [`analyze_ddl`].
pub const DDL_QUERY: &str = "select sql from sqlite_schema where sql is not null and type in ('table', 'view', 'index', 'trigger') order by rowid";

/// The functions the host's SQLite has, which decide what a statement may call: SQLite builds
/// differ in them (the math functions, `soundex`, a newer release's additions), and the embedded
/// one has every optional family, so it alone would accept a call the host then refuses to run.
/// The replayed entry asks the host for it; a host with a connection of its own runs it there and
/// hands the rows to [`Extras::host`] through [`host_functions`]. A SQLite that cannot answer (an
/// old one whose pragma lacks these columns, or a service that refuses the pragma) is taken to
/// have what the embedded one has.
pub const FUNCTIONS_QUERY: &str = "select name, narg, type from pragma_function_list";

/// One row of [`FUNCTIONS_QUERY`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HostFunction {
    pub name: String,
    /// The argument count as SQLite keeps it: -1 for any number.
    pub arity: i32,
    /// `s` for a scalar function, `a` for an aggregate, `w` for a window function.
    pub kind: char,
}

/// The rows of [`FUNCTIONS_QUERY`] as the host's function list; `None` when there is none to
/// read, since every SQLite has functions and an empty list would refuse every call.
pub fn host_functions(rows: &[Vec<serde_json::Value>]) -> Option<Vec<HostFunction>> {
    let listed: Vec<HostFunction> = rows
        .iter()
        .filter_map(|row| {
            let name = row.first().and_then(as_str)?.to_string();
            let arity = row.get(1).and_then(|v| v.as_i64().or_else(|| v.as_str()?.parse().ok())).unwrap_or(-1) as i32;
            let kind = row.get(2).and_then(as_str).and_then(|k| k.chars().next()).unwrap_or('s');
            Some(HostFunction { name, arity, kind })
        })
        .collect();
    (!listed.is_empty()).then_some(listed)
}

/// A scalar function the host registers on its own connection, which the engine's replay cannot
/// see: the replay registers a stub under the same name and argument count, so a statement calling
/// it prepares, and the function table types a call as `returns`, NULL only when an argument is.
/// A function the host vouches for as total, Postgres's `Trust::total` in SQLite's terms: NULL only
/// when an argument is, with the argument count SQLite resolves a call by.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TotalFunction {
    pub name: String,
    /// How many arguments it takes; -1 for any number.
    pub arity: i32,
    /// The storage class its value lands in.
    pub returns: Affinity,
}

/// A storage class a value lands in, as SQLite names a column's affinity.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Affinity {
    Integer,
    Real,
    Text,
    Blob,
    Numeric,
    /// Any storage class: SQLite's "none".
    Any,
}

impl Affinity {
    /// The affinity's name, as the tree and the type model spell it.
    pub fn name(self) -> &'static str {
        match self {
            Affinity::Integer => "integer",
            Affinity::Real => "real",
            Affinity::Text => "text",
            Affinity::Blob => "blob",
            Affinity::Numeric => "numeric",
            Affinity::Any => "none",
        }
    }
}

/// What a host says of the SQLite on its own connection: the functions it registers there, and
/// the functions that SQLite has ([`FUNCTIONS_QUERY`]; `None` when it cannot list them).
#[derive(Debug, Clone, Default)]
pub struct Extras {
    pub total: Vec<TotalFunction>,
    pub host: Option<Vec<HostFunction>>,
}

impl Extras {
    /// The registration a call resolves to: SQLite prefers a host function over a built-in of the
    /// same name and argument count.
    fn function(&self, name: &str, args: usize) -> Option<&TotalFunction> {
        self.total.iter().find(|f| f.name.eq_ignore_ascii_case(name) && (f.arity < 0 || f.arity as usize == args))
    }
}

/// [`analyze_ddl`]'s answer: the analysis, and what the tree adds for a host that types a result
/// column by the spelling its table declares.
#[derive(Debug, Clone)]
pub struct SqliteAnalysis {
    pub analysis: Analysis,
    /// Per result column, the declared type of the table column it reads
    /// (`sqlite3_column_decltype`, through subqueries and views); `None` for an expression. Empty
    /// when the statement did not prepare.
    pub declared: Vec<Option<String>>,
    /// `sqlite3_stmt_readonly`; false when the statement did not prepare.
    pub readonly: bool,
    /// The unique keys of every table the statement reads or writes (through views and
    /// subqueries), by the table's name as its DDL spells it: every unique, non-partial index over
    /// plain columns, the `INTEGER PRIMARY KEY`, and `rowid` for a rowid table without one. What
    /// the row-count proof reads, for a host that runs that proof over text of its own. Empty when
    /// the statement did not prepare.
    pub unique_keys: HashMap<String, Vec<Vec<String>>>,
    /// Per result column, whether it is a truth value: a comparison, `IN`, `BETWEEN`, `EXISTS`,
    /// `IS`, `IS NULL`, `NOT`, `AND`, `OR`, `TRUE` or `FALSE`, a `like`, `glob`, `regexp` or `match`
    /// call, or a `CASE`, `coalesce`, `ifnull`, `iif`, scalar subquery or subquery column whose
    /// every value is one. SQLite stores one as the integer 0 or 1, and its type stays `integer`;
    /// a host that types by meaning reads it as a boolean. Empty when the
    /// statement did not prepare.
    pub booleans: Vec<bool>,
}

/// The replayed entry: the host answers [`DDL_QUERY`] and [`FUNCTIONS_QUERY`] (session-scoped,
/// asked in one round), the rest is [`run`]. `marked` names the parameters cast to `nullable(…)`.
pub fn analyze(sql: &str, lexed: &Lexed, host: &Host, marked: &[String]) -> Lazy<Analysis> {
    let schema = host.query(DDL_QUERY, Vec::new(), Scope::Session);
    let functions = host.query(FUNCTIONS_QUERY, Vec::new(), Scope::Session);
    let (rows, functions) = (schema?, functions?);
    let ddl: Vec<String> = match rows {
        Ok(rows) => rows.iter().filter_map(|r| r.first().and_then(as_str)).map(String::from).collect(),
        Err(e) => return Some(bare(sql, lexed, Dialect::Sqlite, vec![diag(format!("Cannot read the schema: {}", e.message), 0, 1, 5)])),
    };
    // A host that cannot list its functions keeps the embedded SQLite's.
    let extras = Extras { total: Vec::new(), host: functions.ok().and_then(|rows| host_functions(&rows)) };
    Some(run(sql, lexed, &ddl, &extras, marked).analysis)
}

/// The direct entry, for a host with a connection of its own: `ddl` is the `sql` column of
/// [`DDL_QUERY`] run there, `extras` the functions it registers there. No round trip; a lex
/// error, a prepare error (SQLite's own message, at its offset) and a replay failure come back as
/// diagnostics, as on the replayed path.
pub fn analyze_ddl(sql: &str, ddl: &[String], extras: &Extras) -> SqliteAnalysis {
    crate::stack::run(|| analyze_ddl_here(sql, ddl, extras))
}

fn analyze_ddl_here(sql: &str, ddl: &[String], extras: &Extras) -> SqliteAnalysis {
    match crate::analysis::lexed(sql, Dialect::Sqlite) {
        Ok(lexed) => run(sql, &lexed, ddl, extras, &[]),
        Err(analysis) => SqliteAnalysis { analysis, declared: Vec::new(), readonly: false, unique_keys: HashMap::new(), booleans: Vec::new() },
    }
}

/// How the statement writes its result columns: a write's `RETURNING`, or a query's select list, the
/// first arm's of a compound, whose names are the result's. SQLite has expanded each `*` by now, into
/// columns it names. `None` for a write without `RETURNING`.
fn result_targets(t: &Tree) -> Option<Vec<ResultTarget>> {
    // `RETURNING`'s names are not resolved yet where the serializer reads them.
    let target = |c: &tree::Col| if c.named || matches!(c.expr.op.as_str(), "column" | "id" | "dot") { ResultTarget::Named } else { ResultTarget::Unnamed(None) };
    if let Some(returning) = &t.returning {
        return Some(returning.iter().map(target).collect());
    }
    let mut first = t.statement.as_ref().filter(|_| t.dml.is_none())?;
    while let Some(prior) = first.prior.as_deref() {
        first = prior;
    }
    // `values (1, 2)`: named column1 and column2 by SQLite, by nothing in the statement.
    if first.values {
        return Some(vec![ResultTarget::Unnamed(None); first.columns.len()]);
    }
    Some(first.columns.iter().map(target).collect())
}

/// The statements the SQLite analysis reads; any other is a command ([`lex::Statement`]).
const KINDS: &[&str] = &["select", "with", "values", "insert", "replace", "update", "delete"];

fn run(sql: &str, lexed: &Lexed, ddl: &[String], extras: &Extras, marked: &[String]) -> SqliteAnalysis {
    let failed = |analysis: Analysis| SqliteAnalysis { analysis, declared: Vec::new(), readonly: false, unique_keys: HashMap::new(), booleans: Vec::new() };
    let statement = match lex::one_statement(sql, lexed, KINDS) {
        Ok(statement) => statement,
        Err(message) => return failed(bare(sql, lexed, Dialect::Sqlite, vec![diag(message, 0, sql.trim_end().len(), 10)])),
    };
    // SQLite prepares the `?n` rewrite, not the author's text: its own `:name` ends at the first
    // dot, so `:auth.user_id` survives only as a number. `?n` is the lexer's n-th parameter, which
    // is how `params` matches them back, and an error offset maps back through the rewrite.
    let numbered = lex::rewrite(sql, lexed, Target::Numbered);
    let rewritten = lex::rewrite(sql, lexed, Target::Question);
    let functions: Vec<(&str, i32)> = extras.total.iter().map(|f| (f.name.as_str(), f.arity)).collect();
    let (triggers, replay) = replayed(ddl);
    let skipping = skipping_triggers(&triggers);
    let listed = listed(extras.host.as_deref());
    // libSQL's `ALTER TABLE t ALTER COLUMN c TO <definition>` is prepared as the RENAME COLUMN of
    // the same column, which SQLite has, to a name no table has: it prepares where libSQL's does,
    // on an existing table and column, and the definition is libSQL's to read when it runs.
    let alter = if lexed.params.is_empty() { alter_column(&numbered.sql) } else { None };
    let (prepared, sent) = match &alter {
        Some((stand_in, _)) => (stand_in.as_str(), stand_in.as_str()),
        None => (numbered.sql.as_str(), rewritten.sql.as_str()),
    };
    let t = match tree::analyze(&replay, prepared, sent, &functions, listed.as_deref()) {
        Ok(t) => t,
        Err(message) => return failed(bare(sql, lexed, Dialect::Sqlite, vec![diag(message, 0, sql.trim_end().len(), 6)])),
    };
    let mut diagnostics = Vec::new();
    if let Some(err) = &t.error {
        // An offset into the stand-in past its RENAME is one character past the ALTER it replaced.
        let offset = |o: usize| match &alter {
            Some((_, after)) if o >= *after => o - 1,
            _ => o,
        };
        let start = usize::try_from(err.offset).map_or(0, |o| numbered.to_original(offset(o))).min(sql.len());
        let length = match err.length {
            Some(length) if err.offset >= 0 => length,
            _ if err.offset >= 0 => token_len(&sql[start..]),
            _ => sql.trim_end().len(),
        };
        let message = match (&err.missing_function, &err.missing_schema) {
            // The embedded SQLite has the function; the SQLite the statement will run on does not.
            (Some(name), _) => match &err.view {
                Some(view) => format!("no such function: {name} on this database's SQLite (the view {view} calls it)"),
                None => format!("no such function: {name} on this database's SQLite"),
            },
            // The replay holds the database file's own schema. An ATTACH is an act of the
            // application's connection at run time, and nothing in the file names it.
            (None, Some(schema)) => format!("{}: the database has no schema `{schema}`. A database the application attaches at run time (ATTACH ... AS {schema}) is not in the file the type check reads, so a table in it cannot be typed", err.message),
            (None, None) => err.message.clone(),
        };
        let message = if matches!(statement, lex::Statement::Command(_)) { lex::refused_command(&message) } else { message };
        diagnostics.push(diag(message, start, length, 6));
        // A statement that fails against the replayed schema often fails because a replay step did.
        for e in &t.schema_errors {
            let message = match &e.function {
                Some(name) => format!("The schema replay could not register the host function {name}: {}", e.message),
                None => format!("The schema replay skipped statement {}: {}", e.index + 1, e.message),
            };
            diagnostics.push(diag(message, 0, 1, 8));
        }
        return failed(bare(sql, lexed, Dialect::Sqlite, diagnostics));
    }
    // SQLite prepared the `?n` rewrite, so each of its parameters is one the lexer numbered. Any
    // other is one SQLite reads and the lexer does not (`:été`, whose name the lexer ends before):
    // it stayed in the text, takes no value and would run as NULL. An error where it stands.
    for p in t.params.iter().filter(|p| !lexed_parameter(p, lexed)) {
        // Where it stands: the first place its name is written outside a string, a quoted name or a comment.
        let text = |start: &usize| lexed.opaque.iter().any(|(from, to)| (*from..*to).contains(start));
        let at = p.name.as_deref().and_then(|name| sql.match_indices(name).map(|(start, _)| start).find(|start| !text(start)).map(|start| (start, name.len())));
        let written = p.name.as_deref().unwrap_or("a ? in this statement");
        let (start, length) = at.unwrap_or((0, sql.trim_end().len()));
        diagnostics.push(diag(format!("SQLite reads {written} as a parameter that Reylo does not bind; name a parameter with the letters a to z, digits and underscores, starting with a letter or an underscore"), start, length, 1));
    }
    // A JSON object of an odd count of arguments, which SQLite prepares and refuses when it runs;
    // only the built-in constructors, which a function the host registers under the name overrides
    // (`Extras::function`). The host's list names the built-ins with any argument count (-1).
    let registered = |name: &str| extras.total.iter().any(|f| f.name.eq_ignore_ascii_case(name)) || extras.host.iter().flatten().any(|f| f.name.eq_ignore_ascii_case(name) && f.arity >= 0);
    let constructors: Vec<&str> = ["json_object", "jsonb_object"].into_iter().filter(|n| !registered(n)).collect();
    diagnostics.extend(crate::analysis::odd_pairs(sql, lexed, &constructors));
    // A parameter as a whole sort or group key is an error; the rest is typed all the same.
    diagnostics.extend(constant_keys(sql, lexed, &t));
    // The parameters cast to `nullable(…)`, by the `?n` the tree names each by.
    let nullable_params: HashSet<String> = lexed.params.iter().enumerate().filter(|(_, name)| marked.contains(name)).map(|(k, _)| format!("?{}", k + 1)).collect();
    let a = Analyzer { tree: &t, extras, skipping: &skipping, nullable_values: nullable_params.clone(), nullable_params, written: std::cell::RefCell::new(HashSet::new()), level: std::cell::RefCell::new(Level::default()), shapes: std::cell::RefCell::new(HashMap::new()), recursion: std::cell::RefCell::new(Vec::new()), settled: std::cell::RefCell::new(HashMap::new()) };
    let a = Analyzer { nullable_values: a.bare_nullable().into_iter().chain(a.nullable_params.iter().cloned()).collect(), ..a };
    // A command (DDL, a PRAGMA, a transaction's control) has no tree to read: SQLite's prepare
    // says what it takes and returns, and nothing says where a column comes from, so each is of
    // no known type and may be NULL. One that returns no rows runs as a write does.
    if let lex::Statement::Command(kind) = statement {
        let columns: Vec<Column> = t.columns.iter().map(|c| Column::new(c.name.clone(), Type::unknown(), true)).collect();
        let cardinality = if columns.is_empty() { Cardinality::None } else { Cardinality::Many };
        let capabilities = crate::capabilities::of_command(&rewritten.sql, &kind);
        let analysis = Analysis {
            kind: Some(StatementKind::of(&kind)),
            comment: None,
            params: a.params(lexed).0,
            columns,
            cardinality,
            cardinality_reason: None,
            key: None,
            unique: Vec::new(),
            order: Vec::new(),
            ordered: false,
            value: false,
            rewritten,
            sql_mode: None,
            style: lexed.style,
            diagnostics,
            unresolved: Vec::new(),
            structured: Vec::new(),
            errors: None,
            capabilities: Some(capabilities),
            read_only: false,
            notes: Vec::new(),
            tables: None,
            domains: Default::default(),
        };
        return SqliteAnalysis { analysis, declared: t.columns.iter().map(|c| c.declared.clone()).collect(), readonly: t.readonly, unique_keys: HashMap::new(), booleans: vec![false; t.columns.len()] };
    }
    let (facts, kind) = a.columns();
    let booleans = a.booleans();
    let literals = a.literals();
    // A truth value SQLite computes is a boolean, which the oracle holds to 0 and 1; a column
    // declared BOOLEAN, read or passed through, holds whatever was stored in it, and the loader's
    // run time reads it as a truth value by its name, refusing any other value (src/values.ts).
    let columns: Vec<Column> = facts
        .into_iter()
        .zip(a.flags())
        .zip(&booleans)
        .zip(&t.columns)
        .zip(a.exacts())
        .enumerate()
        .map(|(i, (((((name, fact), flag), computed), public), exact))| {
            let ty = if flag { Ty::Scalar { name: "bool".into() } } else { fact.ty };
            let ty = descriptor(&ty, public.declared.as_deref(), *computed, exact);
            let ty = match literals.get(i) {
                Some(Some(written)) => reylo_engine_core::literal::narrow(&ty, written).unwrap_or(ty),
                _ => ty,
            };
            Column::new(name, ty, !fact.non_null)
        })
        .collect();
    let (params, refused) = a.params(lexed);
    // A parameter cast to `nullable(…)` and written whole to a column that refuses null would be
    // refused at run time for the null its type allows: an error at the parameter.
    for (numbered, table, column) in refused {
        let name = numbered.strip_prefix('?').and_then(|k| k.parse::<usize>().ok()).and_then(|k| lexed.params.get(k.checked_sub(1)?));
        let Some(at) = name.and_then(|name| lexed.placeholders.iter().find(|p| &p.name == name)) else { continue };
        let written = &sql[at.start..at.end];
        diagnostics.push(diag(format!("The parameter {written} is cast to nullable(…), but it is written to {table}.{column}, which refuses null: cast it to its type alone."), at.start, at.end - at.start, crate::structured::CODE));
    }
    let (cardinality, reason) = a.cardinality();
    let mut analysis = Analysis {
        kind: (!kind.is_empty()).then(|| StatementKind::of(&kind)),
        comment: None,
        params,
        columns,
        cardinality,
        cardinality_reason: reason,
        key: None,
        unique: Vec::new(),
        order: Vec::new(),
        ordered: false,
        value: false,
        rewritten,
        sql_mode: None,
        style: lexed.style,
        diagnostics,
        unresolved: Vec::new(),
        structured: Vec::new(),
        errors: None,
        capabilities: Some(crate::capabilities::of_statement(&t)),
        read_only: false,
        notes: Vec::new(),
        tables: Some(tables(&t)),
        domains: Default::default(),
    };
    crate::analysis::names(sql, Dialect::Sqlite, &mut analysis, result_targets(&t).as_deref(), &|_| None);
    let unique_keys = t.tables.iter().map(|(name, info)| (name.clone(), info.unique_keys.clone())).collect();
    SqliteAnalysis { analysis, declared: t.columns.iter().map(|c| c.declared.clone()).collect(), readonly: t.readonly, unique_keys, booleans }
}

/// The schema's triggers, and what the engine replays of the schema. Triggers are not replayed (a
/// body may call a function only the application registers); their headers say which statements a
/// trigger can skip a row of. An INSTEAD OF trigger is replayed with an empty body, which is what
/// lets a write to its view through.
fn replayed(ddl: &[String]) -> (Vec<String>, Vec<String>) {
    let (triggers, mut replay): (Vec<String>, Vec<String>) = ddl.iter().cloned().partition(|s| trigger_header(s).is_some());
    replay.extend(triggers.iter().filter_map(|s| instead_of_stub(s)));
    (triggers, replay)
}

/// The host's functions as the walker takes them.
fn listed(host: Option<&[HostFunction]>) -> Option<Vec<tree::Listed<'_>>> {
    host.map(|host| host.iter().map(|f| (f.name.as_str(), f.arity, f.kind)).collect())
}

/// Whether the table an INSERT writes declares its PRIMARY KEY or a UNIQUE ON CONFLICT REPLACE, as
/// the embedded SQLite parsed the schema ([`tree::TableInfo::replaces`]), however its DDL spells
/// the clause: the INSERT, with no OR clause of its own, then deletes the row it conflicts with,
/// and a foreign key's action follows the delete. The statement is prepared again on the replay
/// the analysis made, from the same answers. True where it does not prepare, or writes no table
/// the tree describes.
pub(crate) fn declares_replace(analysis: &Analysis, host: &Host) -> Lazy<bool> {
    let schema = host.query(DDL_QUERY, Vec::new(), Scope::Session);
    let functions = host.query(FUNCTIONS_QUERY, Vec::new(), Scope::Session);
    let (Ok(rows), functions) = (schema?, functions?) else { return Some(true) };
    let ddl: Vec<String> = rows.iter().filter_map(|r| r.first().and_then(as_str)).map(String::from).collect();
    let host_functions = functions.ok().and_then(|rows| host_functions(&rows));
    let (_, replay) = replayed(&ddl);
    let sql = &analysis.rewritten.sql;
    let Ok(t) = tree::analyze(&replay, sql, sql, &[], listed(host_functions.as_deref()).as_deref()) else { return Some(true) };
    Some(t.dml.as_ref().and_then(|dml| t.tables.get(&dml.table)).is_none_or(|info| info.replaces))
}

/// Whether a WITH query reads itself: an arm of its statement has a FROM item SQLite marks as the
/// query's recursive read of itself.
fn reads_itself(sel: &Sel) -> bool {
    let mut arm = Some(sel);
    while let Some(a) = arm {
        if a.from.iter().any(|f| f.recursive) {
            return true;
        }
        arm = a.prior.as_deref();
    }
    false
}

/// The tables the statement names, as SQLite resolved them, for its errors pass: each table
/// and view a FROM clause reads, in subqueries, WITH queries and expressions too, and the table it
/// writes. A view is named, never what it reads; a WITH query, a subquery and a table-valued
/// function are no table. SQLite expands a view into a subquery as it does a derived table, and
/// marks both a view: a view keeps the name the statement writes, a derived table has none. A
/// recursive WITH query's reference to itself is marked as nothing at all, so a name the statement
/// gives a WITH query is no table anywhere in it.
fn tables(t: &Tree) -> Tables {
    #[derive(Default)]
    struct Walk {
        read: Vec<String>,
        ctes: Vec<String>,
    }
    impl Walk {
        fn node(&mut self, n: &Node) {
            if let Some(q) = &n.select {
                self.sel(q);
            }
            for child in n.left.iter().chain(&n.right) {
                self.node(child);
            }
            for child in n.list.iter().chain(&n.args) {
                self.node(child);
            }
        }
        fn sel(&mut self, s: &Sel) {
            for c in &s.columns {
                self.node(&c.expr);
            }
            for f in &s.from {
                if f.cte {
                    self.ctes.extend(f.table.clone());
                }
                if f.cte || f.subquery.is_some() && f.table.is_none() {
                    if let Some(q) = &f.subquery {
                        self.sel(q);
                    }
                } else if !f.tab_func {
                    self.read.extend(f.table.clone());
                }
                for n in f.args.iter().chain(&f.on) {
                    self.node(n);
                }
            }
            for n in s.rows.iter().flatten().chain(&s.where_).chain(&s.group_by).chain(&s.having).chain(&s.order_by).chain(&s.limit).chain(&s.offset) {
                self.node(n);
            }
            if let Some(prior) = &s.prior {
                self.sel(prior);
            }
        }
    }
    let mut walk = Walk::default();
    if let Some(s) = &t.statement {
        walk.sel(s);
    }
    for c in t.returning.iter().flatten() {
        walk.node(&c.expr);
    }
    let mut write = Vec::new();
    if let Some(dml) = &t.dml {
        write.push(dml.table.clone());
        let upsert = dml.upserts.iter().flat_map(|u| u.set.iter().map(|s| &s.expr).chain(&u.where_));
        for n in dml.values.iter().flatten().chain(dml.set.iter().map(|s| &s.expr)).chain(&dml.where_).chain(upsert) {
            walk.node(n);
        }
    }
    let Walk { mut read, ctes } = walk;
    read.retain(|table| !ctes.iter().any(|cte| cte.eq_ignore_ascii_case(table)));
    Tables { read, write, ..Default::default() }
}

/// Whether SQLite's parameter is one the lexer read: the statement is prepared as its `?n` rewrite,
/// which names the lexer's parameters `?1` to `?N`.
fn lexed_parameter(p: &tree::PublicParam, lexed: &Lexed) -> bool {
    p.name.as_deref().and_then(|name| name.strip_prefix('?')).and_then(|k| k.parse::<usize>().ok()).is_some_and(|k| (1..=lexed.params.len()).contains(&k))
}

/// The error of each parameter that is, bare or under casts and collations, a whole key of an
/// ORDER BY (a statement's, a window's or an aggregate's), a GROUP BY or a window's PARTITION BY,
/// anywhere in the statement, at the placeholder as the author wrote it. A key that only holds a
/// parameter (`case :sort when 'name' then name end`) is none.
fn constant_keys(sql: &str, lexed: &Lexed, t: &Tree) -> Vec<crate::api::Diagnostic> {
    fn param(n: &Node) -> Option<i64> {
        match n.op.as_str() {
            "variable" => Some(n.index),
            "cast" | "collate" => n.left.as_deref().and_then(param),
            _ => None,
        }
    }
    /// Every parameter an expression reads, at any depth.
    fn reads(n: &Node, out: &mut HashSet<i64>) {
        if n.op == "variable" {
            out.insert(n.index);
        }
        for child in n.left.iter().chain(&n.right).map(|b| b.as_ref()).chain(&n.list).chain(&n.args).chain(&n.order_by).chain(&n.partition_by) {
            reads(child, out);
        }
    }
    #[derive(Default)]
    struct Walk {
        found: Vec<(i64, KeyClause, bool)>,
    }
    impl Walk {
        fn keys(&mut self, list: &[Node], clause: KeyClause) {
            self.found.extend(list.iter().filter_map(param).map(|index| (index, clause, list.len() == 1)));
        }
        /// A select's own ORDER BY and GROUP BY. SQLite resolves a key that is a position or a
        /// result column's alias (`order by 2`, `group by tag`) to a copy of that column's
        /// expression, so a key that is a parameter the select list reads is such a copy: the
        /// author writes each parameter once.
        fn select_keys(&mut self, s: &Sel) {
            let mut listed = HashSet::new();
            s.columns.iter().for_each(|c| reads(&c.expr, &mut listed));
            for (list, clause) in [(&s.group_by, KeyClause::GroupBy), (&s.order_by, KeyClause::OrderBy)] {
                let alone = list.len() == 1;
                self.found.extend(list.iter().filter_map(param).filter(|index| !listed.contains(index)).map(|index| (index, clause, alone)));
            }
        }
        fn node(&mut self, n: &Node) {
            self.keys(&n.order_by, KeyClause::OrderBy);
            self.keys(&n.partition_by, KeyClause::PartitionBy);
            if let Some(q) = &n.select {
                self.sel(q);
            }
            for child in n.left.iter().chain(&n.right) {
                self.node(child);
            }
            for child in n.list.iter().chain(&n.args).chain(&n.order_by).chain(&n.partition_by) {
                self.node(child);
            }
        }
        fn sel(&mut self, s: &Sel) {
            self.select_keys(s);
            for c in &s.columns {
                self.node(&c.expr);
            }
            for f in &s.from {
                if let Some(q) = &f.subquery {
                    self.sel(q);
                }
                for n in f.args.iter().chain(&f.on) {
                    self.node(n);
                }
            }
            for n in s.rows.iter().flatten().chain(&s.where_).chain(&s.group_by).chain(&s.having).chain(&s.order_by).chain(&s.limit).chain(&s.offset) {
                self.node(n);
            }
            if let Some(prior) = &s.prior {
                self.sel(prior);
            }
        }
    }
    let mut walk = Walk::default();
    if let Some(s) = &t.statement {
        walk.sel(s);
    }
    for c in t.returning.iter().flatten() {
        walk.node(&c.expr);
    }
    if let Some(dml) = &t.dml {
        let upsert = dml.upserts.iter().flat_map(|u| u.set.iter().map(|s| &s.expr).chain(&u.where_));
        for n in dml.values.iter().flatten().chain(dml.set.iter().map(|s| &s.expr)).chain(&dml.where_).chain(upsert) {
            walk.node(n);
        }
    }
    // SQLite prepared the `?n` rewrite, whose n is the lexer's n-th parameter, which appears once.
    let mut out: Vec<_> = walk
        .found
        .into_iter()
        .filter_map(|(index, clause, alone)| {
            let name = lexed.params.get(usize::try_from(index).ok()?.checked_sub(1)?)?;
            let p = lexed.placeholders.iter().find(|p| &p.name == name)?;
            Some(constant_key(sql, p.start, p.end, clause, alone))
        })
        .collect();
    out.sort_by_key(|d| d.start);
    out.dedup_by_key(|d| d.start);
    out
}

fn token_len(rest: &str) -> usize {
    rest.trim_start().chars().take_while(|c| c.is_alphanumeric() || *c == '_' || *c == ':' || *c == '$' || *c == '@' || *c == '?').count().max(1)
}

/// What an expression is: its affinity as the type model, and whether it can be NULL.
#[derive(Debug, Clone)]
struct Fact {
    ty: Ty,
    non_null: bool,
}

impl Fact {
    fn new(aff: &str, non_null: bool) -> Fact {
        Fact { ty: affinity_type(aff), non_null }
    }
    fn unknown() -> Fact {
        Fact { ty: Ty::Unknown, non_null: false }
    }
}

/// SQLite's storage classes as the format's types: a 64-bit integer, a double that holds the
/// infinities (a NaN is stored as NULL), text that is never validated as UTF-8, and bytes.
fn int64() -> Type {
    Type::integer(64)
}
fn real() -> Type {
    Type::new(Kind::Float(FloatType { exponent_bits: 11, mantissa_bits: 52, infinity: true, ..FloatType::default() }))
}
fn text() -> Type {
    Type::new(Kind::Text(TextType { encoding: Some("UTF-8".into()), ill_formed: true, ..TextType::default() }))
}

/// What a column of an affinity holds outside a STRICT table: an INTEGER or NUMERIC one any
/// storage class, a REAL one a float, text or bytes, a TEXT one text or bytes.
fn stored(aff: &str) -> Type {
    let members = match aff {
        "real" => vec![real(), text(), Type::bytes()],
        "text" => vec![text(), Type::bytes()],
        _ => vec![int64(), real(), text(), Type::bytes()],
    };
    Type::union(members)
}

/// The format's type of a value the analysis typed `ty` ([`Ty`]). A column read as it is
/// (`declared`, the type its table declares, through subqueries and views) holds what its affinity
/// stores, under that name: SQLite keeps what it cannot convert as it is. One that is `exact`, in a
/// STRICT table or a rowid, holds its declared type alone ([`Analyzer::exacts`]). A value the statement
/// computes is the storage class the analysis gives it, a 64-bit column's under `BIGINT` and a
/// column declared BOOLEAN's under `BOOLEAN`, the names a client reads it by; a truth value SQLite
/// computes (`computed`) is a boolean, delivered as 1 or 0.
fn descriptor(ty: &Ty, declared: Option<&str>, computed: bool, exact: bool) -> Type {
    // SQLite gives a compound's column the first arm's declared type: it names the value only
    // where the value is what a column of that type holds.
    let declared = declared.map(str::trim).filter(|d| !d.is_empty()).filter(|d| match ty {
        Ty::Scalar { name } if name == "bool" => is_boolean_declared(d),
        Ty::Scalar { .. } => !is_boolean_declared(d) && column_type(d, affinity(d), false) == *ty,
        _ => false,
    });
    match ty {
        Ty::Scalar { name } if name == "bool" && computed => Type::boolean(),
        Ty::Scalar { name } if name == "bool" => stored("numeric").named(declared.unwrap_or("BOOLEAN")),
        Ty::Scalar { name } => match (declared, name.as_str()) {
            (Some(d), "integer" | "int8") if exact => int64().named(d),
            (Some(d), "real") if exact => real().named(d),
            (Some(d), "text") if exact => text().named(d),
            (Some(d), "blob") if exact => Type::bytes().named(d),
            (Some(d), aff) => stored(if aff == "int8" { "integer" } else { aff }).named(d),
            (None, "integer") => int64(),
            (None, "int8") => int64().named("BIGINT"),
            (None, "real") => real(),
            (None, "text") => text(),
            (None, "blob") => Type::bytes(),
            (None, "numeric") => stored("numeric").named("NUMERIC"),
            _ => Type::unknown(),
        },
        Ty::Object { .. } | Ty::List { .. } => Type::json_of(crate::types::Slot::non_null(content(ty))),
        Ty::Json { schema: Some(schema) } => Type::json_schema_of(schema.clone()),
        Ty::Json { schema: None } => Type::json(),
        Ty::Unknown => Type::unknown(),
    }
}

/// The values an expression is one of, where it writes them all: a string, which SQLite reads as
/// written, a number in decimal, `TRUE` and `FALSE`, a number's negation, and a `CASE` whose every
/// result is one, through a unary plus and a `COLLATE`. NULL is none.
fn literals_of(n: &Node) -> Option<Vec<reylo_engine_core::literal::Literal>> {
    use reylo_engine_core::literal::Literal;
    match n.op.as_str() {
        "null" => Some(Vec::new()),
        "string" => Some(vec![Literal::Text(n.value.clone()?)]),
        "integer" | "float" => Some(vec![Literal::Number(n.value.clone()?)]),
        "truefalse" => Some(vec![Literal::Boolean(n.value.as_deref()?.eq_ignore_ascii_case("true"))]),
        "neg" => match literals_of(n.left.as_deref()?)?.as_slice() {
            [Literal::Number(v)] => Some(vec![Literal::Number(match v.strip_prefix('-') {
                Some(positive) => positive.to_string(),
                None => format!("-{v}"),
            })]),
            _ => None,
        },
        "pos" | "collate" => literals_of(n.left.as_deref()?),
        "case" => {
            // `list` alternates WHEN and THEN; an odd tail is the ELSE.
            let mut values = Vec::new();
            for pair in n.list.chunks(2) {
                values.extend(literals_of(pair.last()?)?);
            }
            Some(values)
        }
        _ => None,
    }
}

/// A value inside a document SQLite built: an object's fields and an array's items, each the
/// value SQLite wrote there.
fn content(ty: &Ty) -> Type {
    match ty {
        Ty::Object { fields } => Type::structure(fields.iter().map(|f| Field::new(f.name.clone(), content(&f.ty), f.nullable)).collect()),
        Ty::List { of, nullable_items } => Type::array(crate::types::Slot::new(content(of), *nullable_items)),
        other => descriptor(other, None, false, false),
    }
}

/// The type of a table column's values: its affinity, except that a column declared with no type,
/// or `ANY` in a STRICT table, holds a value of any storage class, and that a column declared with
/// a 64-bit integer's name ([`is_int8_declared`]) is `int8`, the type Postgres's `int8` and MySQL's
/// `BIGINT` are: the declared width decides, on every database (wiki/driver-decoding.md). (`ANY` in
/// a table that is not STRICT is a declared type like any other, with NUMERIC affinity.)
fn column_type(declared: &str, aff: &str, strict: bool) -> Ty {
    let declared = declared.trim();
    if declared.is_empty() || (strict && declared.eq_ignore_ascii_case("any")) {
        Ty::Unknown
    } else if aff == "integer" && is_int8_declared(declared) {
        Ty::Scalar { name: "int8".into() }
    } else {
        affinity_type(aff)
    }
}

/// Whether a declared type names a 64-bit integer: `BIGINT`, `INT8` or `UNSIGNED BIG INT`, the
/// names SQLite's own documentation lists for one, in any case, with any spacing between words and
/// a size after it ignored (`bigint(20)`, as a MySQL dump writes it). `INTEGER`, `INT` and the
/// other integer names are SQLite's INTEGER, a `number`; so is the rowid, whatever its alias is
/// declared, since only `INTEGER PRIMARY KEY` is one.
fn is_int8_declared(declared: &str) -> bool {
    let base = declared.split('(').next().unwrap_or("").split_whitespace().map(str::to_ascii_lowercase).collect::<Vec<_>>().join(" ");
    matches!(base.as_str(), "bigint" | "int8" | "unsigned big int")
}

/// An affinity name as the type model; `none` is unknown.
fn affinity_type(aff: &str) -> Ty {
    match aff {
        "integer" | "real" | "text" | "blob" | "numeric" => Ty::Scalar { name: aff.to_string() },
        _ => Ty::Unknown,
    }
}

fn scalar_name(t: &Ty) -> Option<&str> {
    match t {
        Ty::Scalar { name } => Some(name.as_str()),
        _ => None,
    }
}

fn is_numeric(t: &Ty) -> bool {
    matches!(scalar_name(t), Some("integer" | "int8" | "real" | "numeric"))
}

/// Whether a type is an integer's: SQLite's INTEGER, or a column declared 64 bits wide.
fn is_integral(t: &Ty) -> bool {
    matches!(scalar_name(t), Some("integer" | "int8"))
}

/// The type of a value computed from one of type `t`: a 64-bit column's value passes through
/// unchanged only as itself (a column, a subquery's or view's column, `min`, `max`, `coalesce`, a
/// `CASE` arm, a window's `lag`), and what SQLite computes from it (`-id`, `abs(id)`, `sum(id)`,
/// `id + 1`) is SQLite's INTEGER, as `count(*)` is.
fn computed(t: Ty) -> Ty {
    if scalar_name(&t) == Some("int8") {
        Ty::Scalar { name: "integer".into() }
    } else {
        t
    }
}

/// The type several arms share: one type when they agree, `int8` for a mix of integers of which
/// one is a 64-bit column's (`coalesce(user_id, 0)`: any integer is exact as a BigInt), `numeric`
/// for a mix with a NUMERIC value, `real` for another mix of numbers, unknown otherwise.
fn shared(facts: &[&Fact]) -> Ty {
    let known: Vec<&Ty> = facts.iter().map(|f| &f.ty).filter(|t| !matches!(t, Ty::Unknown)).collect();
    let Some(first) = known.first() else { return Ty::Unknown };
    // Built JSON is text to SQLite: beside a value of no known type (a parameter:
    // `coalesce(:doc, json_array())`), or another type, it is the text it is.
    if known.len() < facts.len() && known.iter().any(|t| is_built(t)) {
        return Ty::Scalar { name: "text".into() };
    }
    if known.iter().all(|t| t == first) {
        return (*first).clone();
    }
    if let Some(ty) = same_json(&known) {
        return ty;
    }
    let known: Vec<Ty> = known.iter().map(|t| textual(t)).collect();
    let known: Vec<&Ty> = known.iter().collect();
    let first = known[0];
    if known.iter().all(|t| *t == first) {
        return first.clone();
    }
    if known.iter().all(|t| is_integral(t)) {
        return Ty::Scalar { name: "int8".into() };
    }
    if known.iter().all(|t| is_numeric(t)) {
        // A NUMERIC value is a number or the text it could not convert (a DATE's '2024-01-01'),
        // beside a number too.
        let numeric = known.iter().any(|t| scalar_name(t) == Some("numeric"));
        return Ty::Scalar { name: if numeric { "numeric" } else { "real" }.into() };
    }
    Ty::Unknown
}

/// The arguments of `coalesce` or `ifnull` it can hand back: each up to the first that is never
/// NULL, after which none is reached.
fn reached(args: &[Fact]) -> &[Fact] {
    let count = args.iter().position(|f| f.non_null).map_or(args.len(), |i| i + 1);
    &args[..count]
}

/// The type of a value SQLite hands back from one of `values` (a compound's arms, `CASE`'s results,
/// `coalesce`'s arguments): the type [`shared`] finds over them. A value of no known type that is no
/// parameter, such as a column declared without a type or `json_extract`, may be of any storage
/// class, so the result is unknown too; a parameter takes the others' type, and a NULL literal says
/// nothing of the type.
fn values_type(values: &[(&Node, &Fact)]) -> Ty {
    let valued: Vec<&Fact> = values.iter().filter(|(e, _)| e.op != "null").map(|(_, f)| *f).collect();
    if values.iter().any(|(e, f)| matches!(f.ty, Ty::Unknown) && e.op != "null" && e.op != "variable") {
        return Ty::Unknown;
    }
    shared(&valued)
}

/// Whether a type is JSON a constructor built, which SQLite returns as text.
fn is_built(t: &Ty) -> bool {
    matches!(t, Ty::Object { .. } | Ty::List { .. } | Ty::Json { .. })
}

/// A type as SQLite's storage class: built JSON is text.
fn textual(t: &Ty) -> Ty {
    if is_built(t) { Ty::Scalar { name: "text".into() } } else { t.clone() }
}

/// The one JSON shape several types are, where they differ only in that one is an empty array
/// (`json_array()`) and the others one list: the list.
fn same_json(types: &[&Ty]) -> Option<Ty> {
    let empty = |t: &Ty| matches!(t, Ty::Json { schema: Some(s) } if s.get("prefixItems").is_none() && s["type"] == "array" && s["items"] == false);
    let lists: Vec<&Ty> = types.iter().copied().filter(|t| !empty(t)).collect();
    let first = lists.first()?;
    (matches!(first, Ty::List { .. }) && lists.iter().all(|t| t == first)).then(|| (*first).clone())
}

/// Whether a value carries SQLite's JSON subtype, which makes a JSON function that reads it nest
/// it as JSON, where text without it is a string. Every JSON function sets it on what it returns,
/// and a `jsonb_*` blob is read as JSON alike. On SQLite 3.53.4 it passed through `coalesce`,
/// `ifnull`, `nullif`, `iif`, `CASE`, `likely`, `COLLATE`, unary plus, a cast to text, `min` and
/// `max` (the aggregates and the scalars), an aggregate with a FILTER and a scalar subquery, and
/// was dropped by a subquery's or view's column, a WITH query's, `lag`, a scalar subquery that
/// sorts its rows and a window call in a statement with a second window.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Carry {
    /// Never: the value is read as the type it has.
    No,
    /// Always, where it is not NULL.
    Yes,
    /// On some SQLite builds or for some values: the engine says nothing of how it reads.
    Maybe,
}

/// Several values', one of which is the value: no subtype only where none has it.
fn combine(carries: &[Carry]) -> Carry {
    if carries.iter().all(|c| *c == Carry::No) {
        Carry::No
    } else if carries.iter().all(|c| *c == Carry::Yes) {
        Carry::Yes
    } else {
        Carry::Maybe
    }
}

/// A value as a JSON function reads it ([`Analyzer::json_fact`]).
struct JsonFact {
    ty: Ty,
    non_null: bool,
    carry: Carry,
}

/// Whether a built-in returns JSON: every JSON function that returns a document or a value of
/// one (`json_extract`, `->`, `json_quote`), and every `jsonb_*` one, whose blob a JSON function
/// reads as JSON. `->>`, `json_type`, `json_valid` and `json_array_length` return plain values,
/// and `json_pretty` is the engine's to leave unsaid.
fn is_json_result(name: &str) -> bool {
    name.starts_with("jsonb")
        || matches!(
            name,
            "json" | "json_object" | "json_array" | "json_group_array" | "json_group_object" | "json_insert" | "json_replace" | "json_set" | "json_remove" | "json_patch" | "json_extract" | "->" | "json_quote"
        )
}

/// The built-ins that hand back one of their arguments as it is, subtype or not.
const PASSING: &[&str] = &["min", "max", "lag", "lead", "first_value", "last_value", "nth_value"];

/// The built-ins whose value is a new one of their own, which carries no subtype.
const PLAIN: &[&str] = &[
    "row_number", "rank", "dense_rank", "ntile", "percent_rank", "cume_dist", "count", "total", "sum", "avg", "group_concat", "string_agg", "abs", "round", "length", "instr",
    "json_valid", "octet_length", "json_array_length", "json_type", "unicode", "like", "glob", "regexp", "match", "concat", "concat_ws", "substr", "substring", "printf", "format",
    "upper", "lower", "trim", "ltrim", "rtrim", "replace", "char", "date", "time", "datetime", "julianday", "unixepoch", "strftime", "timediff", "hex", "quote", "typeof",
    "soundex", "sqlite_version", "sqlite_source_id", "current_date", "current_time", "current_timestamp", "random", "last_insert_rowid", "changes", "total_changes",
    "randomblob", "zeroblob", "->>", "atan", "atan2", "asinh", "sinh", "cosh", "tanh", "exp", "degrees", "radians", "ceil", "ceiling", "floor", "trunc", "sign", "acos", "acosh",
    "asin", "atanh", "cos", "sin", "tan", "ln", "log", "log10", "log2", "mod", "pow", "power", "sqrt", "pi",
    "bm25", "highlight", "snippet", "offsets", "matchinfo",
];

/// A value without the subtype, as SQLite writes it into JSON: an INTEGER (a 64-bit column's too)
/// as a number, a REAL as a number (an infinity as `9.0e+999`, which JSON.parse reads as one), a
/// TEXT as a string, and a NUMERIC as either. A BLOB is read as JSONB (`x'01'` is `true`,
/// `x'00'` null) or is an error, and a value of no known storage class may be one: any JSON.
fn in_json(t: &Ty) -> Ty {
    match scalar_name(t) {
        Some("integer" | "int8" | "real" | "text" | "numeric") => t.clone(),
        _ => Ty::Unknown,
    }
}

/// Whether a value may be JSON's null inside the JSON a function builds: one that may be NULL,
/// which SQLite writes there as null, and any value of plain JSON, which may be the document `null`
/// itself however NOT NULL it is (`json(doc)` where `doc` holds `'null'`), as on Postgres and
/// MySQL. A value of no known type is left as it is: `unknown` already admits null.
fn nullable_in_json(f: &JsonFact) -> bool {
    match f.ty {
        Ty::Unknown => false,
        Ty::Json { schema: None } => true,
        _ => !f.non_null,
    }
}

/// The JSON Schema of a value inside a document SQLite built, as src/schema.ts spells SQLite's
/// values there, for a tuple's items and an object's values of any key.
fn value_schema(t: &Ty, nullable: bool) -> serde_json::Value {
    use serde_json::json;
    let schema = match t {
        Ty::Scalar { name } => match name.as_str() {
            "integer" | "int8" => json!({"type": "integer", "format": "int64"}),
            "real" => json!({"type": "number", "format": "double"}),
            "text" => json!({"type": "string"}),
            "numeric" => json!({"type": ["number", "string"]}),
            _ => json!({}),
        },
        Ty::Object { fields } => {
            let properties: serde_json::Map<String, serde_json::Value> = fields.iter().map(|f| (f.name.clone(), value_schema(&f.ty, f.nullable))).collect();
            json!({"type": "object", "properties": properties, "required": fields.iter().map(|f| f.name.clone()).collect::<Vec<_>>(), "additionalProperties": false})
        }
        Ty::List { of, nullable_items } => json!({"type": "array", "items": value_schema(of, *nullable_items)}),
        Ty::Json { schema: Some(schema) } => schema.clone(),
        _ => json!({}),
    };
    if nullable { reylo_engine_core::schema::nullable(schema) } else { schema }
}

/// An object of any keys whose values are each one of `values`.
fn record(values: Vec<serde_json::Value>) -> Ty {
    let mut distinct: Vec<serde_json::Value> = Vec::new();
    for v in values {
        if !distinct.contains(&v) {
            distinct.push(v);
        }
    }
    let rest = if distinct.len() == 1 { distinct.pop().unwrap_or_default() } else { serde_json::json!({"anyOf": distinct}) };
    Ty::Json { schema: Some(serde_json::json!({"type": "object", "additionalProperties": rest})) }
}

/// The FROM lists in scope, innermost last: a column reference names a cursor of one of them.
type ScopeStack<'a> = Vec<&'a [From]>;

struct Analyzer<'a> {
    tree: &'a Tree,
    extras: &'a Extras,
    /// Per table (lowercase), the events (`TRIGGER_ROW_INSERT`, `_UPDATE`, `_DELETE`) a BEFORE or
    /// INSTEAD OF trigger fires on: its `SELECT RAISE(IGNORE)` skips the row.
    skipping: &'a HashMap<String, i32>,
    /// The parameters (`?n`) the caller may pass NULL for because they are cast to `nullable(…)`;
    /// with the bare ones written whole to a column that may hold NULL ([`Analyzer::params`]),
    /// every other one is a non-null value, as on Postgres and MySQL.
    nullable_params: HashSet<String>,
    /// The parameters (`?n`) whose value may be NULL: those of `nullable_params`, and each one
    /// that is, bare, the whole value written to a column that may hold NULL, which the caller may
    /// pass NULL for ([`Analyzer::bare_nullable`]).
    nullable_values: HashSet<String>,
    /// The target's columns (lowercase) the statement writes a non-null value to in every row its
    /// RETURNING reads ([`Analyzer::written_non_null`]).
    written: std::cell::RefCell<HashSet<String>>,
    /// What the WHERE and the grouping of the SELECT arm whose columns are being typed prove.
    level: std::cell::RefCell<Level>,
    /// The JSON each constructor builds, by its node ([`Analyzer::shape`]).
    shapes: std::cell::RefCell<HashMap<usize, Option<Ty>>>,
    /// The recursive WITH queries being settled, innermost last: each one's name and what its reads
    /// of itself are taken to be ([`Analyzer::recursive_column`]).
    recursion: std::cell::RefCell<Vec<(String, Vec<Fact>)>>,
    /// Each recursive WITH query's settled columns, by its node.
    settled: std::cell::RefCell<HashMap<usize, Vec<Fact>>>,
}

/// What one SELECT arm's WHERE and grouping prove of the expressions in its select list.
#[derive(Debug, Clone, Default)]
struct Level {
    /// Columns (cursor, name) a strict WHERE test rejects NULL in: not NULL in a returned row.
    narrowed: HashSet<(i64, String)>,
    /// Cursors of outer-joined items a strict WHERE test reads: a returned row has their row.
    reduced: HashSet<i64>,
    /// A plain GROUP BY: no group is empty.
    grouped: bool,
    /// The cursors of the arm's own FROM items where it aggregates with no GROUP BY: over no rows
    /// it still returns one row, in which a column outside an aggregate's arguments is NULL,
    /// whatever its table declares and its WHERE tests.
    lone: HashSet<i64>,
    /// How many aggregate calls the expression being typed stands inside: their arguments are
    /// read from the rows aggregated, each a row that is there.
    aggregating: u32,
    /// The cursors of the arm's own FROM items.
    own: HashSet<i64>,
    /// The same cursors of the arms around this one, each read here outside its arm's
    /// aggregates: a subquery's read of such an arm's column (`(select e.name)`) is NULL in the
    /// row that arm returns over no rows.
    around: HashSet<i64>,
    /// How many of the aggregate calls the expression stands inside read none of this arm's own
    /// items for certain. SQLite gives an aggregate to the innermost query whose items it reads,
    /// so such a call is an arm's around this one (`(select json_group_array(name) from posts)`
    /// over `users` aggregates the users), and reads that arm's rows, each one there.
    foreign: u32,
    /// The arm has a window call. SQLite then computes the arm's aggregates in a subquery and
    /// reads each back as that subquery's column, which drops the JSON subtype:
    /// `json_object('a', json_group_array(x))` beside `count(*) over ()` is `{"a":"[1]"}` on
    /// 3.45.1 to 3.54.1.
    windowed: bool,
}

/// The parameter a value is under the conversion a `::type` cast compiles to: `CAST(?n AS type)`,
/// or the `json(?n)` of a `::json` where no function the host registers takes the name.
fn cast_variable<'n>(n: &'n Node, extras: &Extras) -> Option<&'n String> {
    let inner = match n.op.as_str() {
        "cast" => n.left.as_deref(),
        "function" if matches!(n.name.as_deref(), Some("json" | "jsonb")) && n.args.len() == 1 && extras.function(n.name.as_deref().unwrap_or(""), 1).is_none() => n.args.first(),
        _ => None,
    }?;
    inner.name.as_ref().filter(|_| inner.op == "variable")
}

/// What a SELECT arm's WHERE proves of its own FROM items, by the strict tests at its top level
/// (not the ON terms of outer joins SQLite moved there), and whether it groups plainly.
fn level_of(sel: &Sel, extras: &Extras) -> Level {
    let own: HashSet<i64> = sel.from.iter().map(|f| f.cursor).collect();
    let outer: HashSet<i64> = sel.from.iter().filter(|f| f.outer).map(|f| f.cursor).collect();
    // A RIGHT or FULL JOIN null-extends the items before it after their inner joins' ON terms
    // removed rows: those terms narrow none of their columns.
    let extended: HashSet<i64> = sel.from.iter().filter(|f| f.left_of_right).map(|f| f.cursor).collect();
    let mut narrowed = HashSet::new();
    for term in conjuncts(sel.where_.as_ref()).into_iter().filter(|t| !t.outer_on) {
        narrowed.extend(strict_in(term, extras).into_iter().filter(|(cursor, _)| own.contains(cursor) && !(term.inner_on && extended.contains(cursor))));
    }
    let reduced = narrowed.iter().map(|(cursor, _)| *cursor).filter(|c| outer.contains(c)).collect();
    let lone = if sel.aggregate && sel.group_by.is_empty() { own.clone() } else { HashSet::new() };
    Level { narrowed, reduced, grouped: !sel.group_by.is_empty(), lone, aggregating: 0, own, around: HashSet::new(), foreign: 0, windowed: sel.window }
}

/// Whether an expression reads a column of one of `cursors`, or may: a subquery in it may read
/// one in any of its clauses.
fn reads_cursor(n: &Node, cursors: &HashSet<i64>) -> bool {
    if (n.op == "column" && cursors.contains(&n.cursor)) || n.select.is_some() {
        return true;
    }
    n.left.as_deref().is_some_and(|x| reads_cursor(x, cursors))
        || n.right.as_deref().is_some_and(|x| reads_cursor(x, cursors))
        || n.list.iter().chain(&n.args).chain(&n.order_by).chain(&n.partition_by).any(|x| reads_cursor(x, cursors))
}

/// The columns a WHERE test at the top level rejects NULL in: under OR the ones every arm does; a
/// comparison, `IN`, `BETWEEN`, `IS NOT NULL`, `LIKE` or `GLOB`, in the columns its operands
/// answer NULL for. `IS` and `IS NOT` compare NULL like a value, and reject nothing. A function the
/// host registers over a built-in's name is the one a call resolves to, and proves nothing.
fn strict_in(n: &Node, extras: &Extras) -> HashSet<(i64, String)> {
    let nulls = |x: &Node| nulls_with(x, extras);
    match n.op.as_str() {
        "and" => n.left.iter().chain(n.right.iter()).flat_map(|x| strict_in(x, extras)).collect(),
        "or" => {
            let (Some(l), Some(r)) = (n.left.as_deref(), n.right.as_deref()) else { return HashSet::new() };
            let right = strict_in(r, extras);
            strict_in(l, extras).into_iter().filter(|c| right.contains(c)).collect()
        }
        "notnull" | "in" | "between" => n.left.as_deref().map(nulls).unwrap_or_default(),
        "=" | "!=" | "<" | "<=" | ">" | ">=" => n.left.iter().chain(n.right.iter()).flat_map(|x| nulls(x)).collect(),
        "not" => match n.left.as_deref() {
            Some(inner) if inner.op == "isnull" => inner.left.as_deref().map(nulls).unwrap_or_default(),
            // `x NOT IN (SELECT …)` is true of a NULL `x` where the subquery returns no row; a
            // list is never empty.
            Some(inner) => strict_in(inner, extras).into_iter().filter(|_| matches!(inner.op.as_str(), "=" | "!=" | "<" | "<=" | ">" | ">=" | "between") || (inner.op == "in" && inner.select.is_none())).collect(),
            None => HashSet::new(),
        },
        "function" if !n.agg && !n.window && matches!(n.name.as_deref(), Some("like" | "glob")) && extras.function(n.name.as_deref().unwrap_or(""), n.args.len()).is_none() => {
            n.args.iter().flat_map(nulls).collect()
        }
        "column" => nulls(n),
        _ => HashSet::new(),
    }
}

/// The columns an expression answers NULL for: the column itself, and through arithmetic,
/// concatenation, a cast, a COLLATE or a built-in that is NULL for a NULL argument (not one the
/// host registers over it), every column an operand answers NULL for.
fn nulls_with(n: &Node, extras: &Extras) -> HashSet<(i64, String)> {
    const STRICT: &[&str] = &["upper", "lower", "length", "abs", "trim", "ltrim", "rtrim", "substr", "substring", "replace", "round", "instr", "unicode", "sign", "octet_length"];
    match n.op.as_str() {
        "column" => n.column.clone().map(|c| HashSet::from([(n.cursor, c)])).unwrap_or_default(),
        "+" | "-" | "*" | "/" | "%" | "||" => n.left.iter().chain(n.right.iter()).flat_map(|x| nulls_with(x, extras)).collect(),
        "neg" | "pos" | "cast" | "collate" => n.left.as_deref().map(|x| nulls_with(x, extras)).unwrap_or_default(),
        "function" if !n.agg && !n.window && n.name.as_deref().is_some_and(|f| STRICT.contains(&f) && extras.function(f, n.args.len()).is_none()) => n.args.iter().flat_map(|x| nulls_with(x, extras)).collect(),
        _ => HashSet::new(),
    }
}

/// The RENAME COLUMN that stands in for libSQL's `ALTER TABLE t ALTER [COLUMN] c TO <definition>`
/// ([`run`]): the statement up to its second ALTER, `rename`, the statement on to its TO, and a
/// name no table has; with the byte offset in it where the statement's own text resumes, one past
/// where it does in the statement. `None` for any other statement.
fn alter_column(sql: &str) -> Option<(String, usize)> {
    let words = words(sql);
    let keyword = |i: usize, want: &str| words.get(i).is_some_and(|(w, quoted, _)| !quoted && w.eq_ignore_ascii_case(want));
    if !keyword(0, "alter") || !keyword(1, "table") {
        return None;
    }
    // The table's name, with its schema when it has one.
    let alter = if keyword(3, ".") { 5 } else { 3 };
    if !keyword(alter, "alter") {
        return None;
    }
    let column = if keyword(alter + 1, "column") { alter + 2 } else { alter + 1 };
    if !keyword(column + 1, "to") {
        return None;
    }
    // `words` counts characters; the text is sliced by bytes.
    let byte = |chars: usize| sql.char_indices().nth(chars).map_or(sql.len(), |(at, _)| at);
    let at = byte(words[alter].2);
    let to = byte(words[column + 1].2) + 2;
    Some((format!("{}rename{} \"reylo libsql column\"", &sql[..at], &sql[at + 5..to]), at + 6))
}

/// The words of a statement as SQLite's tokenizer splits them: a name or a keyword, and each
/// other character alone; comments are none. A quoted name (`"a b"`, `` `a` ``, `[a]`, `'a'`) is
/// one word without its quotes, and is marked, since it is never a keyword. Each word comes with
/// the index of the character it starts at.
fn words(sql: &str) -> Vec<(String, bool, usize)> {
    let chars: Vec<char> = sql.chars().collect();
    let mut out = Vec::new();
    let mut i = 0;
    while i < chars.len() {
        let c = chars[i];
        if c.is_whitespace() {
            i += 1;
        } else if c == '-' && chars.get(i + 1) == Some(&'-') {
            i += chars[i..].iter().position(|c| *c == '\n').unwrap_or(chars.len() - i);
        } else if c == '/' && chars.get(i + 1) == Some(&'*') {
            i += 2;
            while i < chars.len() && !(chars[i] == '*' && chars.get(i + 1) == Some(&'/')) {
                i += 1;
            }
            i += 2;
        } else if matches!(c, '"' | '`' | '\'' | '[') {
            // A doubled quote inside the name is the quote itself; `[` ends at the first `]`.
            let close = if c == '[' { ']' } else { c };
            let mut name = String::new();
            let at = i;
            i += 1;
            while i < chars.len() {
                if chars[i] == close {
                    if close != ']' && chars.get(i + 1) == Some(&close) {
                        i += 1;
                    } else {
                        break;
                    }
                }
                name.push(chars[i]);
                i += 1;
            }
            i += 1;
            out.push((name, true, at));
        } else if c.is_alphanumeric() || c == '_' || c == '$' || !c.is_ascii() {
            let end = chars[i..].iter().position(|c| !(c.is_alphanumeric() || *c == '_' || *c == '$' || !c.is_ascii())).map_or(chars.len(), |n| i + n);
            out.push((chars[i..end].iter().collect(), false, i));
            i = end;
        } else {
            out.push((c.to_string(), false, i));
            i += 1;
        }
    }
    out
}

/// A `CREATE TRIGGER` statement's timing (`before`, `after`, `instead`), event (`insert`,
/// `update`, `delete`) and table, the table in ASCII lowercase, as SQLite compares names; `None`
/// for any other statement.
fn trigger_header(sql: &str) -> Option<(String, String, String)> {
    // Most of a schema is tables and indexes, which need no reading here.
    if !sql.as_bytes().windows(7).any(|w| w.eq_ignore_ascii_case(b"trigger")) {
        return None;
    }
    let words = words(sql);
    let keyword = |i: usize| words.get(i).filter(|(_, quoted, _)| !quoted).map(|(w, _, _)| w.to_ascii_lowercase());
    // Steps over the next word when it is one of the keywords `want`.
    let take = |i: &mut usize, want: &[&str]| {
        let hit = keyword(*i).is_some_and(|w| want.contains(&w.as_str()));
        if hit {
            *i += 1;
        }
        hit
    };
    let mut i = 0;
    if !take(&mut i, &["create"]) {
        return None;
    }
    take(&mut i, &["temp", "temporary"]);
    if !take(&mut i, &["trigger"]) {
        return None;
    }
    if take(&mut i, &["if"]) {
        take(&mut i, &["not"]);
        take(&mut i, &["exists"]);
    }
    // The trigger's name, with its schema when it has one.
    i += 1;
    if take(&mut i, &["."]) {
        i += 1;
    }
    let timing = if take(&mut i, &["before"]) {
        "before"
    } else if take(&mut i, &["after"]) {
        "after"
    } else if take(&mut i, &["instead"]) {
        take(&mut i, &["of"]);
        "instead"
    } else {
        // "If no timing is specified, BEFORE is the default."
        "before"
    };
    let event = keyword(i)?;
    // `UPDATE OF a, b ON t`: the first ON that is no quoted column name.
    let on = (i..words.len()).find(|j| keyword(*j).as_deref() == Some("on"))?;
    let mut table = &words.get(on + 1)?.0;
    if keyword(on + 2).as_deref() == Some(".") {
        table = &words.get(on + 3)?.0;
    }
    Some((timing.to_string(), event, table.to_ascii_lowercase()))
}

/// An INSTEAD OF trigger with an empty body: its header up to its WHEN or its BEGIN, either of
/// which may call a function only the application registers. Replayed, it lets a write to its
/// view through as SQLite does, which refuses a write to a view with no INSTEAD OF trigger for it
/// (`UPDATE OF a` only for the columns it names); a WHEN only decides at run time whether the body
/// runs. `None` for any other statement.
fn instead_of_stub(sql: &str) -> Option<String> {
    let (timing, _, _) = trigger_header(sql)?;
    if timing != "instead" {
        return None;
    }
    let words = words(sql);
    let keyword = |w: &(String, bool, usize)| !w.1 && (w.0.eq_ignore_ascii_case("when") || w.0.eq_ignore_ascii_case("begin"));
    let on = words.iter().position(|w| !w.1 && w.0.eq_ignore_ascii_case("on"))?;
    // Past the view's name, with its schema when it has one.
    let after = if words.get(on + 2).is_some_and(|w| !w.1 && w.0 == ".") { on + 4 } else { on + 2 };
    let body = words.iter().skip(after).find(|w| keyword(w))?.2;
    let header: String = sql.chars().take(body).collect();
    // On a line of its own: the header may end in a `--` comment.
    Some(format!("{}\nBEGIN SELECT 1; END", header.trim_end()))
}

/// The events of a row trigger, as bits: Postgres's `pg_trigger.tgtype` values, which the two
/// proofs have always shared.
const TRIGGER_ROW_INSERT: i32 = 4;
const TRIGGER_ROW_DELETE: i32 = 8;
const TRIGGER_ROW_UPDATE: i32 = 16;

/// The events per table that some BEFORE or INSTEAD OF trigger fires on.
fn skipping_triggers(triggers: &[String]) -> HashMap<String, i32> {
    let mut out: HashMap<String, i32> = HashMap::new();
    for sql in triggers {
        let Some((timing, event, table)) = trigger_header(sql) else { continue };
        if timing == "after" {
            continue;
        }
        let bit = match event.as_str() {
            "insert" => TRIGGER_ROW_INSERT,
            "update" => TRIGGER_ROW_UPDATE,
            "delete" => TRIGGER_ROW_DELETE,
            _ => TRIGGER_ROW_INSERT | TRIGGER_ROW_UPDATE | TRIGGER_ROW_DELETE,
        };
        *out.entry(table).or_default() |= bit;
    }
    out
}

/// When a function's result can be NULL.
#[derive(Clone, Copy)]
enum Nulls {
    /// Never, whatever the arguments.
    Never,
    /// Only when an argument can be.
    IfArgs,
    /// Always possibly (an aggregate over no rows, a lookup that can miss).
    Always,
}

impl Analyzer<'_> {
    // ---- result columns ---------------------------------------------------------------------

    fn columns(&self) -> (Vec<(String, Fact)>, String) {
        let t = self.tree;
        let kind = t.dml.as_ref().map(|d| if d.kind == "upsert" { "insert".to_string() } else { d.kind.clone() }).unwrap_or_else(|| if t.statement.is_some() { "select".into() } else { String::new() });
        let facts: Vec<Fact> = if let Some(returning) = &t.returning {
            let written = self.written_non_null();
            *self.written.borrow_mut() = written;
            returning.iter().map(|c| self.type_of(&c.expr, &Vec::new())).collect()
        } else if let (Some(sel), None) = (&t.statement, &t.dml) {
            (0..sel.columns.len()).map(|i| self.select_column(sel, i, &Vec::new())).collect()
        } else {
            Vec::new()
        };
        let columns = t
            .columns
            .iter()
            .enumerate()
            .map(|(i, public)| {
                (public.name.clone(), facts.get(i).cloned().unwrap_or_else(Fact::unknown))
            })
            .collect();
        (columns, kind)
    }

    /// Per result column, the constants it holds, where the statement writes nothing else into it:
    /// a RETURNING list's, and a select's, whose every arm a UNION joins adds its values, where an
    /// INTERSECT's or an EXCEPT's arm only removes rows ([`literals_of`]).
    fn literals(&self) -> Vec<Option<Vec<reylo_engine_core::literal::Literal>>> {
        let t = self.tree;
        if let Some(returning) = &t.returning {
            return returning.iter().map(|c| literals_of(&c.expr)).collect();
        }
        let (Some(sel), None) = (&t.statement, &t.dml) else { return Vec::new() };
        let mut arms: Vec<&Sel> = Vec::new();
        let mut s = Some(sel);
        while let Some(arm) = s {
            arms.push(arm);
            s = arm.prior.as_deref();
        }
        arms.reverse();
        (0..sel.columns.len())
            .map(|i| {
                let mut values = Vec::new();
                for (k, arm) in arms.iter().enumerate() {
                    if k > 0 && matches!(arm.op.as_deref(), Some("intersect" | "except")) {
                        continue;
                    }
                    for e in std::iter::once(arm.columns.get(i).map(|c| &c.expr)).chain(arm.rows.iter().map(|row| row.get(i))) {
                        values.extend(literals_of(e?)?);
                    }
                }
                Some(values)
            })
            .collect()
    }

    /// Per result column, whether it is a truth value ([`SqliteAnalysis::booleans`]).
    fn booleans(&self) -> Vec<bool> {
        self.result_truths(false)
    }

    /// Per result column, whether its values are booleans to a host that decodes them: a truth
    /// value, or a column of a table that declares it `BOOLEAN` or `BOOL`, as Prisma's and other
    /// schemas do, read through any subquery or view, or what passes one of those through. SQLite
    /// holds such a column to nothing (`BOOLEAN` is a NUMERIC affinity), so a host reads 0 and 1
    /// and refuses any other value it finds there.
    fn flags(&self) -> Vec<bool> {
        self.result_truths(true)
    }

    fn result_truths(&self, declared: bool) -> Vec<bool> {
        let t = self.tree;
        let truths: Vec<bool> = if let Some(returning) = &t.returning {
            returning.iter().map(|c| self.truth(&c.expr, &Vec::new(), declared)).collect()
        } else if let (Some(sel), None) = (&t.statement, &t.dml) {
            (0..sel.columns.len()).map(|i| self.select_truth(sel, i, &Vec::new(), declared)).collect()
        } else {
            Vec::new()
        };
        (0..t.columns.len()).map(|i| truths.get(i).copied().unwrap_or(false)).collect()
    }

    /// Per result column, whether it holds its declared type alone, as a column of a STRICT table
    /// and a rowid do: read as it is, through subqueries and views, in every arm of a compound.
    fn exacts(&self) -> Vec<bool> {
        let t = self.tree;
        let exact: Vec<bool> = if let Some(returning) = &t.returning {
            returning.iter().map(|c| self.exact(&c.expr, &Vec::new())).collect()
        } else if let (Some(sel), None) = (&t.statement, &t.dml) {
            (0..sel.columns.len()).map(|i| self.select_exact(sel, i, &Vec::new())).collect()
        } else {
            Vec::new()
        };
        (0..t.columns.len()).map(|i| exact.get(i).copied().unwrap_or(false)).collect()
    }

    fn select_exact(&self, sel: &Sel, i: usize, scope: &ScopeStack) -> bool {
        let mut s = Some(sel);
        while let Some(arm) = s {
            let mut inner = scope.clone();
            inner.push(&arm.from);
            if !arm.columns.get(i).is_some_and(|c| self.exact(&c.expr, &inner)) || !arm.rows.is_empty() {
                return false;
            }
            s = arm.prior.as_deref();
        }
        true
    }

    fn exact(&self, n: &Node, scope: &ScopeStack) -> bool {
        if n.op != "column" {
            return false;
        }
        for froms in scope.iter().rev() {
            if let Some(f) = froms.iter().find(|f| f.cursor == n.cursor) {
                if let Some(sub) = f.subquery.as_deref() {
                    return self.select_exact(sub, n.index.max(0) as usize, scope);
                }
                break;
            }
        }
        // A generated column of a STRICT table is left out: SQLite checks what it computes only
        // from 3.51, and an app's driver may carry an older SQLite, which stores anything there.
        (n.strict && !n.generated) || n.rowid
    }

    /// Whether column `i` of a select is a truth value in every arm of a compound.
    fn select_truth(&self, sel: &Sel, i: usize, scope: &ScopeStack, declared: bool) -> bool {
        let mut s = Some(sel);
        while let Some(arm) = s {
            let mut inner = scope.clone();
            inner.push(&arm.from);
            if !arm.columns.get(i).is_some_and(|c| self.truth(&c.expr, &inner, declared)) || !arm.rows.iter().all(|row| row.get(i).is_some_and(|e| self.truth(e, &inner, declared))) {
                return false;
            }
            s = arm.prior.as_deref();
        }
        true
    }

    /// Whether an expression is a truth value: what a comparison, a test or a logical operator
    /// answers, and what passes one through unchanged. A NULL arm is no counterexample (`CASE`
    /// without `ELSE`), and nullability is [`Analyzer::type_of`]'s business. `declared`: a table's
    /// column declared `BOOLEAN` or `BOOL` counts as one too ([`Analyzer::flags`]).
    fn truth(&self, n: &Node, scope: &ScopeStack, declared: bool) -> bool {
        let every = |nodes: &mut dyn Iterator<Item = &Node>| {
            let mut any = false;
            for x in nodes {
                if x.op == "null" {
                    continue;
                }
                if !self.truth(x, scope, declared) {
                    return false;
                }
                any = true;
            }
            any
        };
        match n.op.as_str() {
            "=" | "!=" | "<" | "<=" | ">" | ">=" | "is" | "is not" | "isnull" | "notnull" | "in" | "between" | "exists" | "and" | "or" | "not" | "truefalse" => true,
            "collate" => n.left.as_deref().is_some_and(|l| self.truth(l, scope, declared)),
            "function" if !n.agg && !n.window => match n.name.as_deref().unwrap_or("") {
                "like" | "glob" | "regexp" | "match" => self.extras.function(n.name.as_deref().unwrap_or(""), n.args.len()).is_none(),
                // sqlean's tests, which answer 1 or 0.
                "starts_with" | "text_has_prefix" | "text_has_suffix" | "text_contains" | "text_like" | "regexp_like" => self.extras.function(n.name.as_deref().unwrap_or(""), n.args.len()).is_none(),
                "likely" | "unlikely" | "likelihood" => n.args.first().is_some_and(|a| self.truth(a, scope, declared)),
                "coalesce" | "ifnull" => every(&mut n.args.iter()),
                "iif" | "if" => every(&mut iif_values(n.args.len()).into_iter().filter_map(|i| n.args.get(i))),
                _ => false,
            },
            // `list` alternates WHEN and THEN; an odd tail is the ELSE.
            "case" => {
                let results = n.list.chunks(2).filter_map(|pair| if pair.len() == 2 { Some(&pair[1]) } else { None });
                let otherwise = if n.list.len() % 2 == 1 { n.list.last() } else { None };
                every(&mut results.chain(otherwise))
            }
            "select" => n.select.as_deref().is_some_and(|sub| self.select_truth(sub, 0, scope, declared)),
            "column" => {
                for froms in scope.iter().rev() {
                    if let Some(f) = froms.iter().find(|f| f.cursor == n.cursor) {
                        if let Some(sub) = f.subquery.as_deref() {
                            return self.select_truth(sub, n.index.max(0) as usize, scope, declared);
                        }
                        break;
                    }
                }
                declared && !n.rowid && n.declared.as_deref().is_some_and(is_boolean_declared)
            }
            _ => false,
        }
    }

    /// Column `i` of a select: for a compound, the type every arm's value shares ([`values_type`]),
    /// and any arm's nullability. Every row of a multi-row VALUES is an arm.
    fn select_column(&self, sel: &Sel, i: usize, scope: &ScopeStack) -> Fact {
        let mut arms: Vec<&Sel> = Vec::new();
        let mut s = Some(sel);
        while let Some(arm) = s {
            arms.push(arm);
            s = arm.prior.as_deref();
        }
        arms.reverse();
        // Each arm's value, and the expression it is.
        let facts: Vec<(Option<&Node>, Fact)> = arms
            .iter()
            .flat_map(|arm| {
                let mut inner = scope.clone();
                inner.push(&arm.from);
                let outer = self.level.replace(self.level_within(arm));
                let rows = std::iter::once(arm.columns.get(i).map(|c| &c.expr)).chain(arm.rows.iter().map(|row| row.get(i)));
                let facts: Vec<(Option<&Node>, Fact)> = rows.map(|e| (e, e.map(|e| self.type_of(e, &inner)).unwrap_or_else(Fact::unknown))).collect();
                self.level.replace(outer);
                facts
            })
            .collect();
        let Some((_, first)) = facts.first() else { return Fact::unknown() };
        let values: Option<Vec<(&Node, &Fact)>> = facts.iter().map(|(e, f)| Some(((*e)?, f))).collect();
        let ty = match values {
            _ if facts.iter().all(|(_, f)| f.ty == first.ty) => first.ty.clone(),
            Some(values) => values_type(&values),
            None => Ty::Unknown,
        };
        Fact { ty, non_null: facts.iter().all(|(_, f)| f.non_null) }
    }

    /// Column `i` of a recursive WITH query, which reads itself, so that its columns are a fixed
    /// point, and the greatest one is sound. Each column is first taken to be non-null and of the
    /// type its first arm gives it, for the query's reads of itself; the query is typed under that
    /// assumption; a column that comes out nullable, or of another type, is taken so, and the query
    /// is typed again, until nothing changes. What survives holds by induction over the recursion:
    /// the first arm's rows are so on their own account, each later row given the rows it was
    /// computed from, and a UNION's column is non-null only where every arm's is. A query that does
    /// not settle within a few rounds proves nothing.
    fn recursive_column(&self, name: &str, sub: &Sel, i: usize, scope: &ScopeStack) -> Fact {
        let key = sub as *const Sel as usize;
        if let Some(facts) = self.settled.borrow().get(&key) {
            return facts.get(i).cloned().unwrap_or_else(Fact::unknown);
        }
        let mut first = sub;
        while let Some(prior) = first.prior.as_deref() {
            first = prior;
        }
        let width = first.columns.len();
        let mut inner = scope.clone();
        inner.push(&first.from);
        let outer = self.level.replace(self.level_within(first));
        let mut assumed: Vec<Fact> = first.columns.iter().map(|c| Fact { ty: self.type_of(&c.expr, &inner).ty, non_null: true }).collect();
        self.level.replace(outer);
        // What a round works out under its assumption, a JSON constructor's shape or a recursive
        // WITH query's columns within this one, holds under that assumption alone: each round
        // starts from what was known before the first, and only the round that settles keeps its own.
        let shapes = self.shapes.borrow().clone();
        let nested = self.settled.borrow().clone();
        let mut settled = None;
        for _ in 0..=width + 1 {
            *self.shapes.borrow_mut() = shapes.clone();
            *self.settled.borrow_mut() = nested.clone();
            self.recursion.borrow_mut().push((name.to_string(), assumed.clone()));
            let got: Vec<Fact> = (0..width).map(|k| self.select_column(sub, k, scope)).collect();
            self.recursion.borrow_mut().pop();
            if got.iter().zip(&assumed).all(|(g, a)| g.ty == a.ty && g.non_null == a.non_null) {
                settled = Some(got);
                break;
            }
            assumed = got.iter().zip(&assumed).map(|(g, a)| Fact { ty: g.ty.clone(), non_null: g.non_null && a.non_null }).collect();
        }
        if settled.is_none() {
            *self.shapes.borrow_mut() = shapes;
            *self.settled.borrow_mut() = nested;
        }
        let facts = settled.unwrap_or_else(|| vec![Fact::unknown(); width]);
        let fact = facts.get(i).cloned().unwrap_or_else(Fact::unknown);
        self.settled.borrow_mut().insert(key, facts);
        fact
    }

    /// A column reference: through the cursor to a subquery's column, or the table column itself.
    fn column_ref(&self, n: &Node, scope: &ScopeStack) -> Fact {
        // RETURNING's read of a column the statement wrote a non-null value to in every row it
        // returns, where no BEFORE trigger fires on the write ([`Analyzer::written_non_null`]): no
        // trigger can assign NEW, and RETURNING reports the row before any AFTER trigger runs. A
        // view's INSTEAD OF trigger is no table.
        if n.register && !n.view && !n.generated && n.column.as_ref().is_some_and(|c| self.written.borrow().contains(&c.to_ascii_lowercase())) {
            let aff = n.affinity.as_deref().unwrap_or(&n.aff);
            let ty = match &n.declared {
                Some(declared) if !n.rowid => column_type(declared, aff, n.strict),
                _ => affinity_type(aff),
            };
            return Fact { ty, non_null: true };
        }
        // A strict WHERE test on the column, or on any column of its outer-joined item, keeps
        // its NULL (or the item's null extension) out of every returned row.
        let (narrowed, reduced, lone) = {
            let level = self.level.borrow();
            (n.column.as_ref().is_some_and(|c| level.narrowed.contains(&(n.cursor, c.clone()))), level.reduced.contains(&n.cursor), (level.aggregating == 0 && level.lone.contains(&n.cursor)) || (level.foreign == 0 && level.around.contains(&n.cursor)))
        };
        for froms in scope.iter().rev() {
            if let Some(f) = froms.iter().find(|f| f.cursor == n.cursor) {
                let index = n.index.max(0) as usize;
                let inner = match (&f.subquery, f.table.as_deref()) {
                    (None, Some("vector_top_k")) if f.tab_func && n.column.as_deref().is_some_and(|c| c.eq_ignore_ascii_case("id")) => self.vector_key(f),
                    // sqlean's series, which Turso Cloud loads: an integer per row, wrapping round
                    // past the largest one rather than stopping.
                    (None, Some("generate_series" | "stats_seq")) if f.tab_func && n.column.as_deref().is_some_and(|c| c.eq_ignore_ascii_case("value")) => Some(Fact::new("integer", true)),
                    (Some(sub), Some(name)) if f.cte && reads_itself(sub) => Some(self.recursive_column(name, sub, index, scope)),
                    (Some(sub), _) => Some(self.select_column(sub, index, scope)),
                    // A recursive WITH query's read of itself, inside the query: what it is taken to be.
                    (None, Some(name)) if f.recursive => self.recursion.borrow().iter().rev().find(|(n, _)| n.eq_ignore_ascii_case(name)).map(|(_, facts)| facts.get(index).cloned().unwrap_or_else(Fact::unknown)),
                    _ => None,
                };
                if let Some(inner) = inner {
                    return Fact { ty: inner.ty, non_null: !lone && (narrowed || (inner.non_null && ((!f.outer && !n.outer) || reduced))) };
                }
                break;
            }
        }
        // An INSERT through a view's INSTEAD OF trigger returns each value as the statement wrote
        // it, with none of the view column's affinity: `values (42)` returns 42 for a TEXT one.
        if n.view && self.tree.dml.as_ref().is_some_and(|d| d.kind == "insert") {
            return Fact::unknown();
        }
        let aff = n.affinity.as_deref().unwrap_or(&n.aff);
        let ty = match &n.declared {
            Some(declared) if !n.rowid => column_type(declared, aff, n.strict),
            _ => affinity_type(aff),
        };
        Fact { ty, non_null: !lone && (narrowed || ((n.not_null || n.rowid) && (!n.outer || reduced))) }
    }

    /// What libSQL's `vector_top_k` returns as `id`: the key of the row of the table its index
    /// holds, as libSQL 0.10.0's search reads it, which is never NULL. A rowid table's rowid, an
    /// integer, whatever its primary key; a WITHOUT ROWID table's first primary key column, as it
    /// is stored, which is of any storage class: libSQL refuses a vector column in a STRICT table,
    /// so a table with a vector index never is one, and the key comes back with no declared type to
    /// name it by. `None` where the index is not written as a string or names no index.
    fn vector_key(&self, f: &From) -> Option<Fact> {
        let table = self.tree.tables.get(f.vector_table.as_deref()?)?;
        Some(if table.without_rowid { Fact { ty: Ty::Unknown, non_null: true } } else { Fact::new("integer", true) })
    }

    // ---- expressions -------------------------------------------------------------------------

    /// A function call's type: the JSON a constructor builds, or what the function returns for
    /// its arguments' types.
    fn call(&self, n: &Node, scope: &ScopeStack) -> Fact {
        // The JSON a `json_*` constructor builds, which SQLite returns as its text.
        if let Some(ty) = self.built_text(n, scope) {
            return Fact { ty, non_null: self.built_non_null(n, scope) };
        }
        let args: Vec<Fact> = n.args.iter().map(|a| self.type_of(a, scope)).collect();
        self.function(n, &args)
    }

    /// Whether JSON a constructor builds ([`Analyzer::shape`]) is never NULL. Every constructor
    /// reads a NULL as a null (`[null]`, `{}`) but `json()` and `jsonb()`, which are NULL where
    /// their argument is: a scalar subquery that finds no row, at any depth of them.
    fn built_non_null(&self, n: &Node, scope: &ScopeStack) -> bool {
        match (self.builtin_name(n), n.args.as_slice()) {
            (Some("json" | "jsonb"), [a]) if !n.agg && !n.window => if a.op == "select" { self.type_of(a, scope).non_null } else { self.built_non_null(a, scope) },
            _ => true,
        }
    }

    fn type_of(&self, n: &Node, scope: &ScopeStack) -> Fact {
        let arg = |x: &Option<Box<Node>>| x.as_deref().map(|x| self.type_of(x, scope)).unwrap_or_else(Fact::unknown);
        match n.op.as_str() {
            "column" => self.column_ref(n, scope),
            "integer" => Fact::new(if integer_literal_fits(n) { "integer" } else { "real" }, true),
            "truefalse" => Fact::new("integer", true),
            "float" => Fact::new("real", true),
            "string" => Fact::new("text", true),
            "blob" => Fact::new("blob", true),
            "null" => Fact::unknown(),
            // A parameter is a non-null value unless the statement means to take NULL for it.
            "variable" => Fact { ty: Ty::Unknown, non_null: n.name.as_ref().is_some_and(|name| !self.nullable_values.contains(name)) },
            "function" => {
                self.aggregated(n, || self.call(n, scope))
            }
            "+" | "-" | "*" => {
                let (l, r) = (arg(&n.left), arg(&n.right));
                Fact { ty: arithmetic(&l.ty, &r.ty), non_null: l.non_null && r.non_null }
            }
            "/" | "%" => {
                // A zero divisor gives NULL; a literal divisor is one the statement rules out. `%`
                // divides by its divisor cast to INTEGER, which truncates toward zero and
                // saturates as `as i64` does, so `x % 0.5` is NULL on every row.
                let (l, r) = (arg(&n.left), arg(&n.right));
                let divisor = n.right.as_deref().filter(|d| matches!(d.op.as_str(), "integer" | "float")).and_then(|d| d.value.as_deref()?.parse::<f64>().ok());
                let literal_divisor = divisor.is_some_and(|v| if n.op == "%" { v as i64 != 0 } else { v != 0.0 });
                Fact { ty: arithmetic(&l.ty, &r.ty), non_null: l.non_null && r.non_null && literal_divisor }
            }
            "||" => {
                let (l, r) = (arg(&n.left), arg(&n.right));
                Fact::new("text", l.non_null && r.non_null)
            }
            "=" | "!=" | "<" | "<=" | ">" | ">=" | "and" | "or" | "in" | "between" | "&" | "|" | "<<" | ">>" => {
                let (l, r) = (arg(&n.left), arg(&n.right));
                let list_non_null = n.list.iter().all(|x| self.type_of(x, scope).non_null);
                let right_non_null = if n.right.is_some() { r.non_null } else { list_non_null && n.select.is_none() };
                Fact::new("integer", l.non_null && right_non_null)
            }
            "is" | "is not" | "isnull" | "notnull" | "exists" => Fact::new("integer", true),
            "not" | "~" => {
                let l = arg(&n.left);
                Fact::new("integer", l.non_null)
            }
            // SQLite reads the literal 2^63 under a minus as its smallest INTEGER, -2^63, though
            // alone it is a REAL.
            "neg" if n.left.as_deref().is_some_and(is_two_to_the_63) => Fact::new("integer", true),
            "neg" => {
                let l = arg(&n.left);
                Fact { ty: if is_numeric(&l.ty) { computed(l.ty) } else { Ty::Scalar { name: "real".into() } }, non_null: l.non_null }
            }
            // Unary plus does nothing to any storage class: `+name` is the text 'bob'. SQLite's
            // parser also writes a one-element `x IN (e)` as `x = +e`.
            "pos" => arg(&n.left),
            "cast" => {
                let l = arg(&n.left);
                Fact::new(n.affinity.as_deref().unwrap_or("none"), l.non_null)
            }
            "collate" => arg(&n.left),
            "case" => {
                // `list` alternates WHEN and THEN; an odd tail is the ELSE.
                let results: Vec<(&Node, Fact)> = n.list.chunks(2).filter_map(|pair| if pair.len() == 2 { Some((&pair[1], self.type_of(&pair[1], scope))) } else { None }).collect();
                let otherwise = if n.list.len() % 2 == 1 { n.list.last().map(|e| (e, self.type_of(e, scope))) } else { None };
                let mut all: Vec<&(&Node, Fact)> = results.iter().collect();
                if let Some(o) = &otherwise {
                    all.push(o);
                }
                let values: Vec<(&Node, &Fact)> = all.iter().map(|(e, f)| (*e, f)).collect();
                Fact { ty: values_type(&values), non_null: otherwise.is_some() && all.iter().all(|(_, f)| f.non_null) }
            }
            "select" => {
                // A scalar subquery: its first column, NULL when it finds no row, unless it always
                // finds exactly one (an ungrouped aggregate: `(SELECT count(*) FROM t)`). Its
                // column is then its own answer, so `(SELECT max(x) FROM t)` stays nullable.
                let Some(sub) = n.select.as_deref() else { return Fact::unknown() };
                let inner = self.select_column(sub, 0, scope);
                Fact { ty: inner.ty, non_null: inner.non_null && self.exactly_one(sub).is_ok() }
            }
            _ => Fact::unknown(),
        }
    }

    /// The built-in functions: their result type, and when it is NULL.
    fn function(&self, n: &Node, args: &[Fact]) -> Fact {
        let name = n.name.as_deref().unwrap_or("");
        let all_non_null = args.iter().all(|a| a.non_null);
        let first = args.first().cloned().unwrap_or_else(Fact::unknown);
        let done = |aff: &str, nulls: Nulls| {
            let non_null = match nulls {
                Nulls::Never => true,
                Nulls::IfArgs => all_non_null,
                Nulls::Always => false,
            };
            Fact::new(aff, non_null)
        };
        let typed = |ty: Ty, nulls: Nulls| Fact { ty, non_null: matches!(nulls, Nulls::Never) || (matches!(nulls, Nulls::IfArgs) && all_non_null) };
        if !n.agg && !n.window {
            if let Some(f) = self.extras.function(name, args.len()) {
                return done(f.returns.name(), Nulls::IfArgs);
            }
        }
        let name = sqlean_alias(name);
        if n.window {
            // A frame that always holds the current row has that row, so there `min` and `max`
            // follow their argument, as under a plain GROUP BY; `sum` and `avg` stay nullable as
            // they do there. So does a window's `group_concat` or `string_agg`: before 3.47.0
            // (libSQL and Turso run 3.45.1) it is NULL over a frame of nothing but `''`.
            let has_a_row = holds_current_row(n);
            return match name {
                "row_number" | "rank" | "dense_rank" | "ntile" => done("integer", Nulls::Never),
                "percent_rank" | "cume_dist" => done("real", Nulls::Never),
                "count" => done("integer", Nulls::Never),
                "total" => done("real", total_nulls(&first)),
                "sum" => typed(if is_numeric(&first.ty) { computed(first.ty.clone()) } else { Ty::Scalar { name: "real".into() } }, Nulls::Always),
                "avg" => done("real", Nulls::Always),
                // `lag` and `lead` hand back their default where the row they read is missing.
                "lag" | "lead" if args.len() >= 3 => typed(values_type(&[(&n.args[0], &args[0]), (&n.args[2], &args[2])]), Nulls::Always),
                "min" | "max" => typed(first.ty.clone(), if has_a_row { Nulls::IfArgs } else { Nulls::Always }),
                "lag" | "lead" | "first_value" | "last_value" | "nth_value" => typed(first.ty.clone(), Nulls::Always),
                "group_concat" | "string_agg" => done("text", Nulls::Always),
                _ => Fact::unknown(),
            };
        }
        if n.agg {
            // Under a plain GROUP BY every group has a row, so an aggregate that is NULL only
            // over no rows or only NULLs follows its argument. (A FILTER makes the call a window
            // call in SQLite's tree, and is read above.) `sum` stays nullable: a sum of `1e999`
            // and `-1e999` is NaN, which SQLite stores as NULL, and so is a `total` of them.
            let grouped = self.level.borrow().grouped;
            return match name {
                "count" => done("integer", Nulls::Never),
                "total" => done("real", total_nulls(&first)),
                "sum" => typed(if is_numeric(&first.ty) { computed(first.ty.clone()) } else { Ty::Scalar { name: "real".into() } }, Nulls::Always),
                "avg" => done("real", Nulls::Always),
                "min" | "max" => typed(first.ty.clone(), if grouped { Nulls::IfArgs } else { Nulls::Always }),
                "group_concat" | "string_agg" => done("text", if grouped { Nulls::IfArgs } else { Nulls::Always }),
                "json_group_array" | "json_group_object" => done("text", Nulls::Never),
                "jsonb_group_array" | "jsonb_group_object" => done("blob", Nulls::Never),
                // A percentile, SQLite's (`SQLITE_ENABLE_PERCENTILE`) or sqlean's, which Turso
                // Cloud loads: NULL over no rows or nothing but NULLs, and an error on text.
                "median" | "percentile" | "percentile_25" | "percentile_75" | "percentile_90" | "percentile_95" | "percentile_99" => done("real", Nulls::Always),
                // sqlean's spread: 0.0 over no rows, NULL where the sum overflows to NaN.
                "stddev" | "stddev_pop" | "stddev_samp" | "variance" | "var_pop" | "var_samp" => done("real", Nulls::Always),
                _ => Fact::unknown(),
            };
        }
        // A number for SQLite's math functions: a value of INTEGER or REAL type. Any other gives
        // NULL, text that reads as no number included (`sqrt('abc')`, `sign('')`).
        let numbers = all_non_null && args.iter().all(|a| matches!(scalar_name(&a.ty), Some("integer" | "int8" | "real")));
        match name {
            // An argument after one that is never NULL is never reached: `coalesce((select
            // json_group_array(…) …), '[]')` is the array.
            "coalesce" | "ifnull" => Fact { ty: values_type(&n.args.iter().zip(reached(args)).collect::<Vec<_>>()), non_null: args.iter().any(|a| a.non_null) },
            "nullif" => Fact { ty: first.ty.clone(), non_null: false },
            // `iif(c1, v1, c2, v2, …, else)`: NULL where no condition holds and there is no ELSE,
            // an even count of arguments.
            "iif" | "if" => {
                let values = iif_values(args.len());
                let arms: Vec<(&Node, &Fact)> = values.iter().filter_map(|i| Some((n.args.get(*i)?, args.get(*i)?))).collect();
                Fact { ty: values_type(&arms), non_null: args.len() >= 3 && args.len() % 2 == 1 && arms.iter().all(|(_, a)| a.non_null) }
            }
            "min" | "max" => Fact { ty: values_type(&n.args.iter().zip(args).collect::<Vec<_>>()), non_null: all_non_null },
            // `abs` of the least integer is an error, not NULL; of text, 0.0.
            "abs" => typed(if is_numeric(&first.ty) { computed(first.ty.clone()) } else { Ty::Scalar { name: "real".into() } }, Nulls::IfArgs),
            "round" => done("real", Nulls::IfArgs),
            "length" | "instr" | "json_valid" | "octet_length" => done("integer", Nulls::IfArgs),
            // A path that finds nothing is NULL: `json_array_length('{}', '$.a')`, `json_type('{}', '$.a')`.
            "json_array_length" => done("integer", if args.len() == 1 { Nulls::IfArgs } else { Nulls::Always }),
            "json_type" => done("text", if args.len() == 1 { Nulls::IfArgs } else { Nulls::Always }),
            // `json_remove(j, '$')` is NULL, and so is a NULL path; with no path it is `json(j)`.
            "json_remove" => done("text", if args.len() == 1 { Nulls::IfArgs } else { Nulls::Always }),
            // `unicode('')` is NULL: an empty string has no first character.
            "unicode" => done("integer", Nulls::Always),
            "like" | "glob" | "regexp" | "match" | "likely" | "unlikely" | "likelihood" => {
                if matches!(name, "likely" | "unlikely" | "likelihood") { first.clone() } else { done("integer", Nulls::IfArgs) }
            }
            // `concat` skips NULL arguments (all NULL is ''), and `concat_ws` too, NULL only for a
            // NULL separator.
            "concat" => done("text", Nulls::Never),
            "concat_ws" => Fact::new("text", first.non_null),
            // A blob's slice is a blob, and the slice of an empty blob is NULL (`substr(x'', 1)`):
            // non-null only over text. A parameter there is typed text ([`Analyzer::argument`]).
            "substr" | "substring" => {
                let blob = matches!(scalar_name(&first.ty), Some("blob"));
                let any = matches!(first.ty, Ty::Unknown) && n.args.first().is_some_and(|a| a.op != "variable");
                let ty = if blob { first.ty.clone() } else if any { Ty::Unknown } else { Ty::Scalar { name: "text".into() } };
                Fact { ty, non_null: all_non_null && !blob && !any }
            }
            // NULL where it writes nothing, as for an empty format or one that stops at a
            // conversion SQLite does not know (`printf('%T')`).
            "printf" | "format" => Fact::new("text", n.args.first().and_then(literal_text).is_some_and(printf_writes)),
            "upper" | "lower" | "trim" | "ltrim" | "rtrim" | "replace" | "json" | "json_patch" | "json_pretty" => done("text", Nulls::IfArgs),
            // A NULL argument is a JSON null or the code point 0; a NULL path changes nothing.
            "char" | "json_array" | "json_object" | "json_quote" => done("text", Nulls::Never),
            "json_insert" | "json_replace" | "json_set" => Fact::new("text", first.non_null),
            "jsonb" => done("blob", Nulls::IfArgs),
            // The date and time functions are NULL for a time value they cannot read and for a
            // modifier that fails, so they are non-null only for the current time with modifiers
            // that cannot fail on it (`date()`, `datetime('now', 'localtime')`).
            "date" | "time" | "datetime" => Fact::new("text", current_time(&n.args)),
            "julianday" => Fact::new("real", current_time(&n.args)),
            // `unixepoch(…, 'subsec')` is a real.
            "unixepoch" => {
                let whole = n.args.iter().skip(1).all(|m| literal_text(m).is_some_and(|m| !matches!(m.to_ascii_lowercase().as_str(), "subsec" | "subsecond")));
                Fact::new(if whole { "integer" } else { "real" }, current_time(&n.args))
            }
            // A conversion it does not know makes `strftime` NULL (`strftime('%Q')`).
            "strftime" => Fact::new("text", n.args.first().and_then(literal_text).is_some_and(strftime_format) && current_time(n.args.get(1..).unwrap_or_default())),
            "timediff" => Fact::new("text", n.args.len() == 2 && current_time(&n.args[..1]) && current_time(&n.args[1..])),
            // `soundex(NULL)` is '?000'.
            "hex" | "quote" | "typeof" => done("text", Nulls::Never),
            // SQLite's `soundex(NULL)` is '?000', and sqlean's, which Turso Cloud loads in its
            // place, is NULL.
            "soundex" => done("text", Nulls::IfArgs),
            "sqlite_version" | "sqlite_source_id" | "current_date" | "current_time" | "current_timestamp" => done("text", Nulls::Never),
            "random" | "last_insert_rowid" | "changes" | "total_changes" => done("integer", Nulls::Never),
            "randomblob" | "zeroblob" => done("blob", Nulls::IfArgs),
            "json_extract" | "jsonb_extract" | "->" | "->>" => Fact::unknown(),
            // Defined on every number, infinities included: NULL only for an argument that is no
            // number.
            "atan" | "atan2" | "asinh" | "sinh" | "cosh" | "tanh" | "exp" | "degrees" | "radians" | "ceil" | "ceiling" | "floor" | "trunc" => Fact::new("real", numbers),
            "sign" => Fact::new("integer", numbers),
            // NULL outside their domain (`sqrt(-1)`, `ln(0)`, `acos(2)`, `mod(1, 0)`,
            // `pow(-1, 0.5)`) and for an infinite argument (`sin(1e999)`).
            "acos" | "acosh" | "asin" | "atanh" | "cos" | "sin" | "tan" | "ln" | "log" | "log10" | "log2" | "mod" | "pow" | "power" | "sqrt" => done("real", Nulls::Always),
            "pi" => done("real", Nulls::Never),
            // The full-text functions, which an FTS table answers for the rows of its own MATCH.
            // FTS5's `bm25` is a real on every row, 0 where no MATCH ranks it; with weights it is
            // NULL where an infinite or overflowing weight makes the score NaN
            // (`bm25(t, 1e308, 1.0)` on a row that matches twice). `highlight` is NULL
            // where its column is, and so is FTS5's `snippet` where its column is (every column,
            // for -1); FTS4's `snippet` has the same name. FTS3's and FTS4's `offsets` and
            // `matchinfo` answer every row.
            "bm25" => done("real", if n.args.len() == 1 { Nulls::Never } else { Nulls::Always }),
            "highlight" | "snippet" => done("text", Nulls::Always),
            "offsets" => done("text", Nulls::Never),
            "matchinfo" => done("blob", Nulls::Never),
            // libSQL's vectors (`csrc/reylo_sqlite.c`, `openLibsql`), as libSQL 0.10.0 answers: each
            // of these is an error on a NULL argument, never NULL. A vector is a blob, and its text
            // is the JSON-like array `vector_extract` writes (`[1,2,3]`, `[inf]`).
            "vector" | "vector32" | "vector64" | "vector1bit" | "vector8" | "vector16" | "vectorb16" => done("blob", Nulls::Never),
            "vector_extract" => done("text", Nulls::Never),
            // NULL where the distance is NaN, which SQLite stores as NULL: a zero vector's cosine,
            // two empty vectors, infinite components.
            "vector_distance_cos" | "vector_distance_l2" => done("real", Nulls::Always),
            // The marker a vector index is made with returns its argument, whatever a vector column
            // holds: a vector index takes a vector's text as well as its blob.
            "libsql_vector_idx" => Fact { ty: Ty::Unknown, non_null: first.non_null },
            // The sqlean extensions Turso Cloud loads (`csrc/reylo_sqlite.c`, `aTurso`), as
            // libsql-ffi 0.10.0 builds them, each by its own name ([`sqlean_alias`]).
            // uuid: a new identifier every call, and a malformed one read as NULL.
            "uuid4" | "gen_random_uuid" | "uuid7" => done("text", Nulls::Never),
            "uuid_str" => done("text", Nulls::Always),
            "uuid_blob" => done("blob", Nulls::Always),
            "uuid7_timestamp_ms" => done("integer", Nulls::Always),
            // crypto: a digest of text or bytes; `encode` and `decode` NULL only for a NULL value,
            // and an error for one they cannot read or a format they do not know.
            "md5" | "sha1" | "sha256" | "sha384" | "sha512" | "blake3" => done("blob", Nulls::IfArgs),
            "encode" => Fact::new("text", first.non_null),
            "decode" => Fact::new("blob", first.non_null),
            // fuzzy: a distance is an error on NULL and on text that is not ASCII, never NULL; a
            // phonetic code follows its argument.
            "levenshtein" | "dlevenshtein" | "edit_distance" | "osa_distance" | "hamming" => done("integer", Nulls::Never),
            "jaro_winkler" => done("real", Nulls::Never),
            "caverphone" | "phonetic_hash" | "rsoundex" => done("text", Nulls::IfArgs),
            "translit" => done("text", Nulls::Never),
            "script_code" => done("integer", Nulls::Never),
            // text: NULL where a text argument is (a count or a length is an error there).
            "bit_length" | "char_length" | "character_length" | "text_size" | "text_bitsize" | "text_length" => done("integer", Nulls::IfArgs),
            "strpos" | "text_index" | "text_last_index" | "text_count" => done("integer", Nulls::IfArgs),
            "starts_with" | "text_has_prefix" | "text_has_suffix" | "text_contains" | "text_like" => done("integer", Nulls::IfArgs),
            "btrim" | "left" | "right" | "lpad" | "rpad" | "repeat" | "reverse" | "split_part" | "translate" | "text_trim" | "text_ltrim" | "text_rtrim" | "text_left" | "text_right"
            | "text_lpad" | "text_rpad" | "text_repeat" | "text_reverse" | "text_split" | "text_translate" | "text_title" | "text_casefold" | "text_lower" | "text_upper"
            | "text_replace" | "text_slice" | "text_substring" => done("text", Nulls::IfArgs),
            // Like `concat` and `concat_ws`, they skip a NULL value.
            "text_concat" => done("text", Nulls::Never),
            "text_join" => Fact::new("text", first.non_null),
            // regexp: a match of NULL text is 0, and a NULL pattern an error.
            "regexp_like" => done("integer", Nulls::Never),
            "regexp_substr" | "regexp_capture" => done("text", Nulls::Always),
            // Where nothing matches, or the replacement is NULL, it hands back its value as it was:
            // `regexp_replace(123, 'z', 'x')` is the integer 123.
            "regexp_replace" => Fact { ty: if scalar_name(&first.ty) == Some("text") { first.ty.clone() } else { Ty::Unknown }, non_null: first.non_null },
            _ => Fact::unknown(),
        }
    }

    // ---- built JSON ----------------------------------------------------------------------------
    //
    // SQLite's JSON functions answer with text (the `jsonb_*` ones with a blob), so a column a
    // constructor builds was `text`. Its shape is in the statement, as on Postgres and MySQL, and
    // the run time parses the text: what follows types it as the JSON it is. Inside a document a
    // value is what SQLite writes there, measured on SQLite 3.53.4 (wiki/dialects.md): an INTEGER,
    // a REAL and a TEXT as a JSON number or string, NULL as null, a truth value as 1 or 0. A value
    // that carries SQLite's JSON subtype, which every JSON function sets on what it returns, nests
    // as JSON rather than as a string, and the subtype passes through some expressions and not
    // others ([`Carry`]).

    /// The JSON a call that SQLite answers with text builds: a `json_object`, `json_array`,
    /// `json_group_array` or `json_group_object` call, or `json()` of one of those or of a
    /// `jsonb_*` constructor. A `jsonb_*` call is a blob, which stays one.
    fn built_text(&self, n: &Node, scope: &ScopeStack) -> Option<Ty> {
        match self.builtin_name(n)? {
            "json_object" | "json_array" | "json_group_array" | "json_group_object" => self.shape(n, scope),
            "json" if n.args.len() == 1 && !n.agg && !n.window => self.shape(&n.args[0], scope).or_else(|| self.subquery_shape(&n.args[0], scope)),
            _ => None,
        }
    }

    /// The JSON a scalar subquery's one column builds, which `json()` of the subquery marks as
    /// JSON again whether or not the subquery's value kept SQLite's subtype ([`Analyzer::carry`]).
    /// None for a compound or a `VALUES` list, whose rows the first arm's column does not type.
    fn subquery_shape(&self, n: &Node, scope: &ScopeStack) -> Option<Ty> {
        if n.op != "select" {
            return None;
        }
        let sub = n.select.as_deref()?;
        if sub.columns.len() != 1 || sub.prior.is_some() || !sub.rows.is_empty() || sub.values {
            return None;
        }
        let col = sub.columns.first()?;
        self.within(sub, scope, |inner| self.built_text(&col.expr, inner))
    }

    /// The built-in a call resolves to: none where the host registers a scalar function of that
    /// name and argument count, which SQLite prefers.
    fn builtin_name<'n>(&self, n: &'n Node) -> Option<&'n str> {
        let name = n.name.as_deref().filter(|_| n.op == "function")?;
        (n.agg || n.window || self.extras.function(name, n.args.len()).is_none()).then_some(name)
    }

    /// The JSON a constructor builds, `json_*` or `jsonb_*`, each value as SQLite writes it
    /// there ([`Analyzer::json_fact`]); `json()` and `jsonb()` of one build the same. Each node's
    /// shape is worked out once: a constructor's nullability and its parent's shape both read it.
    fn shape(&self, n: &Node, scope: &ScopeStack) -> Option<Ty> {
        let key = n as *const Node as usize;
        if let Some(found) = self.shapes.borrow().get(&key) {
            return found.clone();
        }
        let shape = self.aggregated(n, || self.shape_here(n, scope));
        self.shapes.borrow_mut().insert(key, shape.clone());
        shape
    }

    fn shape_here(&self, n: &Node, scope: &ScopeStack) -> Option<Ty> {
        let name = self.builtin_name(n)?;
        let aggregate = n.agg || n.window;
        // What a JSON function reads an argument as, and whether it may be a null there.
        let value = |x: &Node| {
            let f = self.json_fact(x, scope);
            let nullable = nullable_in_json(&f);
            (f.ty, nullable)
        };
        match name {
            "json_object" | "jsonb_object" if !aggregate => {
                // An odd count of arguments is an error, and so is a key that is no text.
                if n.args.len() % 2 != 0 {
                    return Some(Ty::Json { schema: None });
                }
                let mut fields: Vec<TyField> = Vec::new();
                let mut dynamic = false;
                for pair in n.args.chunks(2) {
                    let (ty, nullable) = value(&pair[1]);
                    match literal_text(&pair[0]) {
                        // A key written twice is in the text twice, and JSON.parse keeps the last.
                        Some(key) => match fields.iter_mut().find(|f| f.name == key) {
                            Some(f) => {
                                f.ty = ty;
                                f.nullable = nullable;
                            }
                            None => fields.push(TyField { name: key.to_string(), ty, nullable }),
                        },
                        None => {
                            dynamic = true;
                            fields.push(TyField { name: String::new(), ty, nullable });
                        }
                    }
                }
                // A key the statement computes: an object of any keys, each value one of these.
                if dynamic {
                    return Some(record(fields.iter().map(|f| value_schema(&f.ty, f.nullable)).collect()));
                }
                Some(Ty::Object { fields })
            }
            // A JSON array of exactly these values, in this order: a tuple.
            "json_array" | "jsonb_array" if !aggregate => {
                let items: Vec<serde_json::Value> = n.args.iter().map(|x| {
                    let (ty, nullable) = value(x);
                    value_schema(&ty, nullable)
                }).collect();
                let mut schema = serde_json::json!({"type": "array", "items": false});
                if !items.is_empty() {
                    schema["minItems"] = serde_json::json!(items.len());
                    schema["prefixItems"] = serde_json::Value::Array(items);
                }
                Some(Ty::Json { schema: Some(schema) })
            }
            // `[]` over no rows, never NULL; a FILTER and a window frame alike.
            "json_group_array" | "jsonb_group_array" if aggregate && n.args.len() == 1 => {
                let (ty, nullable) = value(&n.args[0]);
                Some(Ty::List { of: Box::new(ty), nullable_items: nullable })
            }
            // `{}` over no rows; a key aggregated twice is in the text twice.
            "json_group_object" | "jsonb_group_object" if aggregate && n.args.len() == 2 => {
                let (ty, nullable) = value(&n.args[1]);
                Some(record(vec![value_schema(&ty, nullable)]))
            }
            "json" | "jsonb" if !aggregate && n.args.len() == 1 => self.shape(&n.args[0], scope).or_else(|| self.subquery_shape(&n.args[0], scope)),
            _ => None,
        }
    }

    /// A value as a JSON function reads it: its type inside the document, whether it is never
    /// NULL, and whether it carries the JSON subtype. A value that does not carries the type it
    /// has anywhere ([`in_json`]); one that does nests as the JSON it is, where every way it can
    /// take builds the same; a value the engine cannot follow is any JSON.
    fn json_fact(&self, n: &Node, scope: &ScopeStack) -> JsonFact {
        let plain = || {
            let f = self.type_of(n, scope);
            JsonFact { ty: in_json(&f.ty), non_null: f.non_null, carry: Carry::No }
        };
        let any = JsonFact { ty: Ty::Unknown, non_null: false, carry: Carry::Maybe };
        match n.op.as_str() {
            "function" => {
                // A function the host registers may set the subtype on what it returns.
                let Some(name) = self.builtin_name(n) else { return any };
                // A window call's value dropped the subtype on 3.53.4 where the statement has a
                // second window (`json_object('w', json_group_array(x) over ())`).
                if n.over && is_json_result(name) {
                    return any;
                }
                // So did an aggregate's value beside a window call ([`Level::windowed`]).
                if self.windowed_aggregate(n) && self.carry(n, scope) != Carry::No {
                    return any;
                }
                if let Some(ty) = self.shape(n, scope) {
                    let non_null = self.built_non_null(n, scope);
                    return JsonFact { ty, non_null, carry: Carry::Yes };
                }
                let first = n.args.first().into_iter();
                let non_null = || self.type_of(n, scope).non_null;
                match name {
                    "coalesce" | "ifnull" => self.json_arms(n.args.iter(), true, scope).map(|f| JsonFact { non_null: f.non_null, ..f }).unwrap_or_else(plain),
                    "nullif" => self.json_arms(first, false, scope).map(|f| JsonFact { non_null: false, ..f }).unwrap_or_else(plain),
                    "likely" | "unlikely" | "likelihood" => self.json_arms(first, false, scope).unwrap_or_else(plain),
                    "iif" | "if" => {
                        let arms = iif_values(n.args.len()).into_iter().filter_map(|i| n.args.get(i));
                        self.json_arms(arms, false, scope).map(|f| JsonFact { non_null: non_null(), ..f }).unwrap_or_else(plain)
                    }
                    // The aggregate hands back one of its values.
                    "min" | "max" if n.args.len() == 1 && !n.window => self.json_arms(first, false, scope).map(|f| JsonFact { non_null: non_null(), ..f }).unwrap_or_else(plain),
                    _ if is_json_result(name) => JsonFact { ty: Ty::Json { schema: None }, non_null: non_null(), carry: Carry::Yes },
                    // `max(a, b)` and `lag(x)` hand back one of their arguments: `max` kept the
                    // subtype on 3.53.4 and `lag` dropped it.
                    _ if PASSING.contains(&name) => {
                        if n.args.iter().all(|a| self.carry(a, scope) == Carry::No) { plain() } else { any }
                    }
                    _ if PLAIN.contains(&name) => plain(),
                    _ => any,
                }
            }
            // A scalar subquery's JSON may have lost the subtype ([`Analyzer::carry`]): wrapped in
            // `json()`, it nests as the JSON it is on every SQLite.
            "select" => if self.carry(n, scope) == Carry::No { plain() } else { any },
            "collate" | "pos" => n.left.as_deref().map_or(any, |l| self.json_fact(l, scope)),
            "case" => {
                let results = n.list.chunks(2).filter_map(|pair| if pair.len() == 2 { Some(&pair[1]) } else { None });
                let otherwise = if n.list.len() % 2 == 1 { n.list.last() } else { None };
                match self.json_arms(results.chain(otherwise), false, scope) {
                    Some(f) => JsonFact { non_null: self.type_of(n, scope).non_null, ..f },
                    None => plain(),
                }
            }
            // `cast(json_array(1) as text)` kept the subtype on 3.53.4, `as integer` gave 0.
            "cast" | "column" => if self.carry(n, scope) == Carry::No { plain() } else { any },
            _ => plain(),
        }
    }

    /// A value that is one of `arms`, NULL arms aside: `None` where none carries the subtype, so
    /// the value is the plain one its type says. `coalesce`: an arm after one that is never NULL
    /// is never reached.
    fn json_arms<'n>(&self, arms: impl Iterator<Item = &'n Node>, coalesce: bool, scope: &ScopeStack) -> Option<JsonFact> {
        let mut facts: Vec<JsonFact> = Vec::new();
        for arm in arms.filter(|a| a.op != "null") {
            let f = self.json_fact(arm, scope);
            let last = coalesce && f.non_null;
            facts.push(f);
            if last {
                break;
            }
        }
        if facts.iter().all(|f| f.carry == Carry::No) {
            return None;
        }
        let non_null = facts.iter().any(|f| f.non_null);
        if !facts.iter().all(|f| f.carry == Carry::Yes) {
            return Some(JsonFact { ty: Ty::Unknown, non_null, carry: Carry::Maybe });
        }
        let types: Vec<&Ty> = facts.iter().map(|f| &f.ty).collect();
        let ty = if types.iter().all(|t| *t == types[0]) { types[0].clone() } else { same_json(&types).unwrap_or(Ty::Unknown) };
        Some(JsonFact { ty, non_null, carry: Carry::Yes })
    }

    /// Whether a value carries SQLite's JSON subtype ([`Carry`]).
    fn carry(&self, n: &Node, scope: &ScopeStack) -> Carry {
        match n.op.as_str() {
            "function" => {
                let Some(name) = self.builtin_name(n) else { return Carry::Maybe };
                let carry = match name {
                    "coalesce" | "ifnull" => self.carries(n.args.iter(), scope),
                    "nullif" | "likely" | "unlikely" | "likelihood" => self.carries(n.args.first().into_iter(), scope),
                    "iif" | "if" => self.carries(iif_values(n.args.len()).into_iter().filter_map(|i| n.args.get(i)), scope),
                    "min" | "max" if n.args.len() == 1 && !n.window => self.carries(n.args.iter(), scope),
                    _ if is_json_result(name) => if n.over { Carry::Maybe } else { Carry::Yes },
                    _ if PASSING.contains(&name) => {
                        if self.carries(n.args.iter(), scope) == Carry::No { Carry::No } else { Carry::Maybe }
                    }
                    _ if PLAIN.contains(&name) => Carry::No,
                    _ => Carry::Maybe,
                };
                if carry != Carry::No && self.windowed_aggregate(n) { Carry::Maybe } else { carry }
            }
            // A scalar subquery kept the subtype on 3.53.4 and drops it on 3.54.1 (the SQLite of
            // Node 26.11's `node:sqlite`): `json_object('n', (select json_object('a', 1)))` is
            // `{"n":{"a":1}}` on one and `{"n":"{\"a\":1}"}` on the other, so a JSON value from one may
            // be either.
            "select" => {
                let Some(sub) = n.select.as_deref() else { return Carry::No };
                match self.select_carry(sub, 0, scope) {
                    Carry::No => Carry::No,
                    _ => Carry::Maybe,
                }
            }
            "collate" | "pos" => n.left.as_deref().map_or(Carry::No, |l| self.carry(l, scope)),
            "cast" => match n.left.as_deref().map_or(Carry::No, |l| self.carry(l, scope)) {
                Carry::No => Carry::No,
                _ => Carry::Maybe,
            },
            "case" => {
                let results = n.list.chunks(2).filter_map(|pair| if pair.len() == 2 { Some(&pair[1]) } else { None });
                let otherwise = if n.list.len() % 2 == 1 { n.list.last() } else { None };
                self.carries(results.chain(otherwise), scope)
            }
            // A column of a subquery, a view or a WITH query dropped the subtype on 3.53.4
            // (`json_object('a', x) from (select json_array(1) as x)` is `{"a":"[1]"}`), which
            // a SQLite that flattens the subquery may keep.
            "column" => {
                for froms in scope.iter().rev() {
                    if let Some(f) = froms.iter().find(|f| f.cursor == n.cursor) {
                        if let Some(sub) = f.subquery.as_deref() {
                            return if self.select_carry(sub, n.index.max(0) as usize, scope) == Carry::No { Carry::No } else { Carry::Maybe };
                        }
                        break;
                    }
                }
                // A VIRTUAL generated column is computed where it is read, its expression's
                // subtype and all; a STORED one is read back from the row, as any column is.
                if n.subtype { Carry::Maybe } else { Carry::No }
            }
            _ => Carry::No,
        }
    }

    /// Whether column `i` of a select carries the subtype, in every arm and row of a compound.
    fn select_carry(&self, sel: &Sel, i: usize, scope: &ScopeStack) -> Carry {
        let mut carries = Vec::new();
        let mut s = Some(sel);
        while let Some(arm) = s {
            self.within(arm, scope, |inner| {
                for e in std::iter::once(arm.columns.get(i).map(|c| &c.expr)).chain(arm.rows.iter().map(|row| row.get(i))).flatten() {
                    carries.push(self.carry(e, inner));
                }
            });
            s = arm.prior.as_deref();
        }
        combine(&carries)
    }

    /// Whether one of `arms` is the value, NULL arms aside, carries the subtype.
    fn carries<'n>(&self, arms: impl Iterator<Item = &'n Node>, scope: &ScopeStack) -> Carry {
        let carries: Vec<Carry> = arms.filter(|a| a.op != "null").map(|a| self.carry(a, scope)).collect();
        combine(&carries)
    }

    /// `f` inside the arguments of `n` where it is an aggregate call: they are read from the rows
    /// it aggregates ([`Level`]), where a window call's are read from the statement's own rows.
    fn aggregated<T>(&self, n: &Node, f: impl FnOnce() -> T) -> T {
        if !(n.op == "function" && n.agg && !n.over) {
            return f();
        }
        // A FILTER, which the tree does not carry (`window`, on a call with no OVER), may read
        // the arm's own items too: only a call seen to read none of them is an arm's around it.
        let foreign = {
            let level = self.level.borrow();
            !n.window && !reads_cursor(n, &level.own)
        };
        {
            let mut level = self.level.borrow_mut();
            level.aggregating += 1;
            level.foreign += u32::from(foreign);
        }
        let out = f();
        let mut level = self.level.borrow_mut();
        level.aggregating -= 1;
        level.foreign -= u32::from(foreign);
        out
    }

    /// Whether `n` is an aggregate call, a FILTER's included, in a query with a window call
    /// ([`Level::windowed`]): its value reaches the expression around it through a subquery's
    /// column. (SQLite refuses an aggregate of a query with a window call inside a subquery.)
    fn windowed_aggregate(&self, n: &Node) -> bool {
        n.op == "function" && n.agg && !n.over && self.level.borrow().windowed
    }

    /// A select arm's level, read from where the analysis stands: what the arm proves of its own
    /// FROM items, and the cursors of the arms around it that are NULL where it reads them.
    fn level_within(&self, sel: &Sel) -> Level {
        let mut level = level_of(sel, self.extras);
        let outer = self.level.borrow();
        level.around = outer.around.clone();
        if outer.aggregating == 0 {
            level.around.extend(outer.lone.iter().copied());
        }
        level
    }

    /// `f` over a select arm's own scope and level, as [`Analyzer::select_column`] reads its columns.
    fn within<T>(&self, sel: &Sel, scope: &ScopeStack, f: impl FnOnce(&ScopeStack) -> T) -> T {
        let mut inner = scope.clone();
        inner.push(&sel.from);
        let outer = self.level.replace(self.level_within(sel));
        let out = f(&inner);
        self.level.replace(outer);
        out
    }

    // ---- written values ----------------------------------------------------------------------

    /// The target's columns (lowercase) an INSERT, an upsert or an UPDATE with a RETURNING writes
    /// a non-null value to in every row it returns: each value of every row an INSERT writes to
    /// the column, its VALUES or its SELECT's column, and each value every DO UPDATE of an upsert
    /// assigns it (a DO NOTHING returns no row), or each value an UPDATE's SET assigns it, all of
    /// them non-null. A column a write leaves out takes its default, or keeps what the row held,
    /// and `excluded.<column>` proves nothing here. Nothing at all where a BEFORE or INSTEAD OF
    /// trigger on the table fires on the write: SQLite leaves undefined what a BEFORE UPDATE
    /// trigger's change to the row being updated does to the update.
    fn written_non_null(&self) -> HashSet<String> {
        let t = self.tree;
        let (Some(dml), Some(_)) = (&t.dml, &t.returning) else { return HashSet::new() };
        let events = match dml.kind.as_str() {
            "update" => TRIGGER_ROW_UPDATE,
            _ if dml.upserts.iter().any(|u| u.do_update) => TRIGGER_ROW_INSERT | TRIGGER_ROW_UPDATE,
            _ => TRIGGER_ROW_INSERT,
        };
        if self.skipping.get(&dml.table.to_ascii_lowercase()).is_some_and(|mask| mask & events != 0) {
            return HashSet::new();
        }
        let scope: ScopeStack = Vec::new();
        let non_null = |known: HashMap<String, bool>| -> HashSet<String> { known.into_iter().filter(|(_, n)| *n).map(|(c, _)| c).collect() };
        let assigned = |items: &[tree::SetItem]| -> HashSet<String> {
            let mut known: HashMap<String, bool> = HashMap::new();
            for item in items {
                let Some(column) = &item.column else { continue };
                *known.entry(column.to_ascii_lowercase()).or_insert(true) &= self.type_of(&item.expr, &scope).non_null;
            }
            non_null(known)
        };
        match dml.kind.as_str() {
            "update" => assigned(&dml.set),
            "insert" | "upsert" => {
                let mut known: HashMap<String, bool> = HashMap::new();
                for (i, column) in dml.columns.iter().enumerate() {
                    let Some(column) = column else { continue };
                    let fact = match (&dml.values, &t.statement) {
                        (Some(values), _) => values.get(i).map(|v| self.type_of(v, &scope)),
                        (None, Some(sel)) => Some(self.select_column(sel, i, &scope)),
                        (None, None) => None,
                    };
                    *known.entry(column.to_ascii_lowercase()).or_insert(true) &= fact.is_some_and(|f| f.non_null);
                }
                let mut written = non_null(known);
                for upsert in dml.upserts.iter().filter(|u| u.do_update) {
                    let updated = assigned(&upsert.set);
                    written.retain(|c| updated.contains(c));
                }
                written
            }
            _ => HashSet::new(),
        }
    }

    /// The parameters that are, bare, with no cast, the whole value written to a column that may
    /// hold NULL, and to no column that refuses it: the caller may pass NULL for each
    /// ([`Analyzer::params`]), so the value written may be NULL.
    fn bare_nullable(&self) -> HashSet<String> {
        let t = self.tree;
        let Some(dml) = &t.dml else { return HashSet::new() };
        let mut fills: HashMap<String, bool> = HashMap::new();
        let mut fill = |v: &Node, column: Option<&str>| {
            let (Some(name), Some(column)) = (v.name.as_ref().filter(|_| v.op == "variable"), column) else { return };
            let Some(target) = self.table_column(&dml.table, column) else { return };
            let refuses = target.non_null || self.checked_not_null(&dml.table, column);
            *fills.entry(name.clone()).or_insert(true) &= !refuses;
        };
        if let (Some(sel), "insert" | "upsert") = (&t.statement, dml.kind.as_str()) {
            if sel.prior.is_none() {
                for (i, v) in sel.columns.iter().map(|c| &c.expr).enumerate().chain(sel.rows.iter().flat_map(|row| row.iter().enumerate())) {
                    fill(v, dml.columns.get(i).and_then(|c| c.as_deref()));
                }
            }
        }
        for (i, v) in dml.values.iter().flatten().enumerate() {
            fill(v, dml.columns.get(i).and_then(|c| c.as_deref()));
        }
        for item in dml.set.iter().chain(dml.upserts.iter().flat_map(|u| u.set.iter())) {
            fill(&item.expr, item.column.as_deref());
        }
        fills.into_iter().filter(|(_, nullable)| *nullable).map(|(name, _)| name).collect()
    }

    // ---- parameters --------------------------------------------------------------------------

    /// Every parameter, typed by the context SQLite placed it in; the first typed context wins.
    /// Beside them, each parameter cast to `nullable(…)` that is written whole to a column refusing
    /// NULL, as `(?n, table, column)`.
    fn params(&self, lexed: &Lexed) -> (Vec<Param>, Vec<(String, String, String)>) {
        let mut found: Vec<(String, Fact)> = Vec::new();
        let t = self.tree;
        let checked = |c: Option<&str>| t.dml.as_ref().zip(c).is_some_and(|(dml, c)| self.checked_not_null(&dml.table, c));
        // A parameter that is, bare, with no cast, the whole value written to a column may be null
        // where that column may hold NULL, and no column that refuses NULL it also fills forbids
        // it. A cast one, `CAST(? AS type)` or the `json(?)` a `::json` compiles to, is its cast's
        // type, never the column's.
        let mut fills: HashMap<String, bool> = HashMap::new();
        let mut refused: Vec<(String, String, String)> = Vec::new();
        let mut fill = |v: &Node, target: &Option<Fact>, column: Option<&str>| {
            let Some(target) = target else { return };
            let refuses = target.non_null || checked(column);
            let bare = v.op == "variable";
            let Some(name) = (if bare { v.name.as_ref() } else { cast_variable(v, self.extras) }) else { return };
            if bare {
                *fills.entry(name.clone()).or_insert(true) &= !refuses;
            }
            if let (true, true, Some(column), Some(dml)) = (refuses, self.nullable_params.contains(name), column, t.dml.as_ref()) {
                refused.push((name.clone(), dml.table.clone(), column.to_string()));
            }
        };
        if let Some(sel) = &t.statement {
            let targets: Vec<Option<Fact>> = match &t.dml {
                // The SELECT or the VALUES rows that feed an INSERT: their columns type from the
                // target columns.
                Some(dml) if dml.kind == "insert" => dml.columns.iter().map(|c| c.as_deref().and_then(|c| self.table_column(&dml.table, c))).collect(),
                _ => Vec::new(),
            };
            // Every row of a VALUES list writes its values whole, as the one-row form below does,
            // and so does the one SELECT that feeds an INSERT; a compound's columns are any arm's.
            if sel.prior.is_none() {
                for (i, v) in sel.columns.iter().map(|c| &c.expr).enumerate().chain(sel.rows.iter().flat_map(|row| row.iter().enumerate())) {
                    if let Some(target) = targets.get(i) {
                        fill(v, target, t.dml.as_ref().and_then(|d| d.columns.get(i)).and_then(|c| c.as_deref()));
                    }
                }
            }
            self.walk_select(sel, &Vec::new(), &targets, &mut found);
        }
        if let Some(dml) = &t.dml {
            let scope: ScopeStack = Vec::new();
            if let Some(values) = &dml.values {
                for (i, v) in values.iter().enumerate() {
                    let target = dml.columns.get(i).and_then(|c| c.as_deref()).and_then(|c| self.table_column(&dml.table, c));
                    fill(v, &target, dml.columns.get(i).and_then(|c| c.as_deref()));
                    self.walk(v, Ctx::Typed(target), &scope, &mut found);
                }
            }
            for item in dml.set.iter().chain(dml.upserts.iter().flat_map(|u| u.set.iter())) {
                let target = item.column.as_deref().and_then(|c| self.table_column(&dml.table, c));
                fill(&item.expr, &target, item.column.as_deref());
                self.walk(&item.expr, Ctx::Typed(target), &scope, &mut found);
            }
            if let Some(w) = &dml.where_ {
                self.walk(w, Ctx::Bool, &scope, &mut found);
            }
            for w in dml.upserts.iter().filter_map(|u| u.where_.as_ref()) {
                self.walk(w, Ctx::Bool, &scope, &mut found);
            }
        }
        if let Some(returning) = &t.returning {
            for c in returning {
                self.walk(&c.expr, Ctx::None, &Vec::new(), &mut found);
            }
        }
        // The tree was prepared over the `?n` rewrite (see `analyze`): SQLite's `?k` is the lexer's
        // k-th parameter, whatever the author wrote.
        let mut typed: HashMap<&str, &Fact> = HashMap::new();
        for (name, fact) in found.iter().filter(|(_, f)| !matches!(f.ty, Ty::Unknown)) {
            typed.entry(name.as_str()).or_insert(fact);
        }
        let params = lexed
            .params
            .iter()
            .enumerate()
            .map(|(k, name)| {
                let numbered = format!("?{}", k + 1);
                let fact = typed.get(numbered.as_str()).map(|f| (*f).clone()).unwrap_or_else(Fact::unknown);
                // A parameter compared with built JSON is bound as the text it is compared with.
                let fact = Fact { ty: textual(&fact.ty), ..fact };
                let nullable = fills.get(&numbered).copied().unwrap_or(false) || self.nullable_params.contains(&numbered);
                Param { nullable, ..Param::new(name.clone(), descriptor(&fact.ty, None, false, false)) }
            })
            .collect();
        (params, refused)
    }

    /// Whether a CHECK of the table refuses NULL in the column (`check (col is not null)`). A view
    /// is no table here (its INSTEAD OF trigger says what a write takes), so a parameter written
    /// to one has no target column and takes no NULL.
    fn checked_not_null(&self, table: &str, column: &str) -> bool {
        self.tree.tables.get(table).and_then(|info| info.columns.iter().find(|c| c.name.eq_ignore_ascii_case(column))).is_some_and(|c| c.checked_not_null)
    }

    fn table_column(&self, table: &str, column: &str) -> Option<Fact> {
        let info = self.tree.tables.get(table)?;
        let col = info.columns.iter().find(|c| c.name.eq_ignore_ascii_case(column))?;
        Some(Fact { ty: column_type(&col.declared, &col.affinity, info.strict), non_null: col.not_null || info.rowid_alias.as_deref().is_some_and(|a| a.eq_ignore_ascii_case(column)) })
    }

    fn walk_select(&self, sel: &Sel, scope: &ScopeStack, targets: &[Option<Fact>], found: &mut Vec<(String, Fact)>) {
        // In a compound every arm's column i is one result column: a parameter in one arm takes
        // the type the other arms give it (`SELECT name FROM users UNION ALL SELECT :x`).
        let compound: Vec<Option<Fact>>;
        let targets = if targets.is_empty() && (sel.prior.is_some() || !sel.rows.is_empty()) {
            compound = (0..sel.columns.len())
                .map(|i| {
                    let ty = self.select_column(sel, i, scope).ty;
                    (!matches!(ty, Ty::Unknown)).then_some(Fact { ty, non_null: true })
                })
                .collect();
            compound.as_slice()
        } else {
            targets
        };
        let mut inner = scope.clone();
        inner.push(&sel.from);
        for (i, e) in sel.columns.iter().map(|c| &c.expr).enumerate().chain(sel.rows.iter().flat_map(|row| row.iter().enumerate())) {
            self.walk(e, Ctx::Typed(targets.get(i).cloned().flatten()), &inner, found);
        }
        for f in &sel.from {
            if let Some(sub) = &f.subquery {
                self.walk_select(sub, &inner, &[], found);
            }
            if let Some(on) = &f.on {
                self.walk(on, Ctx::Bool, &inner, found);
            }
            // `json_each` and `json_tree` read JSON text and a path (`IN (SELECT value FROM json_each(:ids))`);
            // libSQL's `vector_top_k` an index's name, a vector, as its text, and a count, which it
            // refuses as a real or as text.
            let json = f.tab_func && matches!(f.table.as_deref(), Some("json_each" | "json_tree"));
            let top_k = f.tab_func && f.table.as_deref() == Some("vector_top_k");
            // sqlean's `generate_series(start, stop, step)`, integers all.
            let series = f.tab_func && matches!(f.table.as_deref(), Some("generate_series" | "stats_seq"));
            for (i, a) in f.args.iter().enumerate() {
                let ctx = match i {
                    0 | 1 if json || top_k => Ctx::Typed(Some(Fact::new("text", true))),
                    2 if top_k => Ctx::Typed(Some(Fact::new("integer", true))),
                    _ if series => Ctx::Typed(Some(Fact::new("integer", true))),
                    _ => Ctx::None,
                };
                self.walk(a, ctx, &inner, found);
            }
        }
        if let Some(w) = &sel.where_ {
            self.walk(w, Ctx::Bool, &inner, found);
        }
        for g in &sel.group_by {
            self.walk(g, Ctx::None, &inner, found);
        }
        if let Some(h) = &sel.having {
            self.walk(h, Ctx::Bool, &inner, found);
        }
        for o in &sel.order_by {
            self.walk(o, Ctx::None, &inner, found);
        }
        for l in sel.limit.iter().chain(sel.offset.iter()) {
            self.walk(l, Ctx::Typed(Some(Fact::new("integer", true))), &inner, found);
        }
        if let Some(prior) = &sel.prior {
            self.walk_select(prior, scope, targets, found);
        }
    }

    /// Visits every node; a variable takes the type its context gives it.
    fn walk(&self, n: &Node, ctx: Ctx, scope: &ScopeStack, found: &mut Vec<(String, Fact)>) {
        if n.op == "variable" {
            let fact = match ctx {
                Ctx::Typed(Some(f)) => f,
                Ctx::Typed(None) | Ctx::Row(_) | Ctx::None => Fact::unknown(),
                Ctx::Bool => Fact::new("integer", false),
            };
            found.push((n.name.clone().unwrap_or_default(), fact));
            return;
        }
        let sibling = |other: &Option<Box<Node>>| other.as_deref().map(|o| self.type_of(o, scope));
        let case_results: std::cell::OnceCell<Ty> = std::cell::OnceCell::new();
        let child_ctx = |slot: Position| -> Ctx {
            match n.op.as_str() {
                "=" | "!=" | "<" | "<=" | ">" | ">=" | "is" | "is not" => {
                    let (this, other) = match slot {
                        Position::Left => (&n.left, &n.right),
                        Position::Right => (&n.right, &n.left),
                        _ => return Ctx::None,
                    };
                    // Row values compare element by element, so each element takes the type of
                    // the one it is compared with: `(created_at, id) < (:created_at, :id)`, and a
                    // subquery's columns: `(created_at, id) = (SELECT :at, :id)`.
                    match (this.as_deref(), other.as_deref().and_then(|o| self.row(o, scope))) {
                        (Some(t), Some(row)) if matches!(t.op.as_str(), "vector" | "select") => Ctx::Row(row),
                        _ => Ctx::Typed(sibling(other)),
                    }
                }
                "in" => match slot {
                    // `(created_at, id) IN (SELECT …)`: SQLite writes a list of row values as
                    // a VALUES subquery, which the left side types (see the select walk below).
                    Position::Left if is_vector(&n.left) => n.select.as_deref().map_or(Ctx::None, |s| Ctx::Row(self.select_columns(s, scope))),
                    Position::Left => Ctx::Typed(n.list.first().map(|x| self.type_of(x, scope)).or_else(|| n.select.as_deref().map(|s| self.select_column(s, 0, scope)))),
                    Position::List(_) => Ctx::Typed(sibling(&n.left)),
                    _ => Ctx::None,
                },
                "between" => match slot {
                    Position::Left if is_vector(&n.left) => Ctx::Row(self.rows(&n.list.iter().collect::<Vec<_>>(), scope)),
                    Position::Left => Ctx::Typed(n.list.first().map(|x| self.type_of(x, scope))),
                    Position::List(_) => match n.left.as_deref().and_then(|l| self.row(l, scope)) {
                        Some(row) if is_vector(&n.left) => Ctx::Row(row),
                        _ => Ctx::Typed(sibling(&n.left)),
                    },
                    _ => Ctx::None,
                },
                // An element of a row value takes its place's type.
                "vector" => match (slot, &ctx) {
                    (Position::List(i), Ctx::Row(row)) => Ctx::Typed(row.get(i).cloned().flatten()),
                    _ => Ctx::None,
                },
                // One column of a row subquery, as `UPDATE … SET (a, b) = (SELECT …)` writes it.
                "select_column" => match (slot, &ctx) {
                    (Position::Left, Ctx::Typed(Some(f))) => {
                        let mut row = vec![None; n.index.max(0) as usize + 1];
                        row[n.index.max(0) as usize] = Some(f.clone());
                        Ctx::Row(row)
                    }
                    _ => Ctx::None,
                },
                "cast" => Ctx::Typed(Some(Fact::new(n.affinity.as_deref().unwrap_or("none"), true))),
                "+" | "-" | "*" | "/" | "%" => {
                    let other = match slot {
                        Position::Left => sibling(&n.right),
                        _ => sibling(&n.left),
                    };
                    Ctx::Typed(Some(match other {
                        Some(f) if is_numeric(&f.ty) => f,
                        _ => Fact::new("real", true),
                    }))
                }
                "||" => Ctx::Typed(Some(Fact::new("text", true))),
                "neg" | "~" | "&" | "|" | "<<" | ">>" => Ctx::Typed(Some(Fact::new("real", true))),
                // Unary plus hands its operand the context it stands in: `x IN (?)` is `x = +?`.
                // So does a COLLATE, which names how the value compares and leaves it as it is.
                "pos" | "collate" => ctx.clone(),
                "and" | "or" | "not" => Ctx::Bool,
                "case" => match slot {
                    // A WHEN compares with the base when there is one, else it is a condition; a
                    // THEN or ELSE shares the other results' type, or failing that the type the
                    // CASE stands in (`name = CASE WHEN … THEN :a ELSE :b END`).
                    Position::List(i) if i % 2 == 0 && i + 1 < n.list.len() => match &n.left {
                        Some(base) if base.op == "vector" => self.row(base, scope).map_or(Ctx::None, Ctx::Row),
                        Some(base) => Ctx::Typed(Some(self.type_of(base, scope))),
                        None => Ctx::Bool,
                    },
                    // Typed once for the CASE, not once per arm: a CASE of thousands of arms.
                    Position::List(_) => match case_results.get_or_init(|| {
                        let others: Vec<Fact> = n.list.iter().enumerate().filter(|(j, _)| j % 2 == 1 || (*j == n.list.len() - 1 && n.list.len() % 2 == 1)).map(|(_, x)| self.type_of(x, scope)).collect();
                        shared(&others.iter().collect::<Vec<_>>())
                    }) {
                        Ty::Unknown => outer_type(&ctx),
                        ty => Ctx::Typed(Some(Fact { ty: ty.clone(), non_null: true })),
                    },
                    // A base compares with each WHEN value (`CASE :kind WHEN 'a' THEN …`), a row
                    // value element by element.
                    Position::Left if is_vector(&n.left) => {
                        let values: Vec<&Node> = n.list.iter().enumerate().filter(|(j, _)| j % 2 == 0 && j + 1 < n.list.len()).map(|(_, x)| x).collect();
                        Ctx::Row(self.rows(&values, scope))
                    }
                    // A base compares with each WHEN value (`CASE :kind WHEN 'a' THEN …`).
                    Position::Left => {
                        let values: Vec<Fact> = n.list.iter().enumerate().filter(|(j, _)| j % 2 == 0 && j + 1 < n.list.len()).map(|(_, x)| self.type_of(x, scope)).collect();
                        let refs: Vec<&Fact> = values.iter().collect();
                        match shared(&refs) {
                            Ty::Unknown => Ctx::None,
                            ty => Ctx::Typed(Some(Fact { ty, non_null: true })),
                        }
                    }
                    _ => Ctx::None,
                },
                // A function whose result is one of its arguments gives an argument its siblings'
                // type, or failing that the type the call stands in (`name = coalesce(:a, :b)`).
                "function" => match (slot, self.argument(n, i_of(slot), scope)) {
                    (Position::Arg(_), Ctx::Typed(None) | Ctx::None) if matches!(n.name.as_deref(), Some("coalesce" | "ifnull" | "nullif" | "min" | "max")) && !n.agg => outer_type(&ctx),
                    (Position::Arg(i), Ctx::Typed(None) | Ctx::None) if matches!(n.name.as_deref(), Some("iif" | "if")) && iif_values(n.args.len()).contains(&i) => outer_type(&ctx),
                    (Position::Arg(_), c) => c,
                    _ => Ctx::None,
                },
                _ => Ctx::None,
            }
        };
        if let Some(l) = &n.left {
            self.walk(l, child_ctx(Position::Left), scope, found);
        }
        if let Some(r) = &n.right {
            self.walk(r, child_ctx(Position::Right), scope, found);
        }
        for (i, x) in n.list.iter().enumerate() {
            self.walk(x, child_ctx(Position::List(i)), scope, found);
        }
        for (i, x) in n.args.iter().enumerate() {
            self.walk(x, child_ctx(Position::Arg(i)), scope, found);
        }
        if let Some(s) = &n.select {
            // A subquery's columns take the types they are compared with or stand in: `id IN
            // (SELECT :p)`, `id = (SELECT :p)`, `(created_at, id) IN (VALUES (:at, :id))`.
            let targets: Vec<Option<Fact>> = match (n.op.as_str(), &ctx) {
                ("select", Ctx::Row(row)) => row.clone(),
                ("select", Ctx::Typed(Some(f))) => vec![Some(f.clone())],
                ("in", _) => match n.left.as_deref() {
                    Some(l) if l.op == "vector" => self.row(l, scope).unwrap_or_default(),
                    Some(l) => vec![Some(self.type_of(l, scope))],
                    None => Vec::new(),
                },
                _ => Vec::new(),
            };
            self.walk_select(s, scope, &targets, found);
        }
    }

    /// A row value's elements, one fact per place: a vector's elements, or a subquery's columns.
    fn row(&self, n: &Node, scope: &ScopeStack) -> Option<Vec<Option<Fact>>> {
        match n.op.as_str() {
            "vector" => Some(n.list.iter().map(|x| Some(self.type_of(x, scope))).collect()),
            "select" => n.select.as_deref().map(|s| self.select_columns(s, scope)),
            _ => None,
        }
    }

    fn select_columns(&self, sel: &Sel, scope: &ScopeStack) -> Vec<Option<Fact>> {
        (0..sel.columns.len()).map(|i| Some(self.select_column(sel, i, scope))).collect()
    }

    /// The type at each place of several row values (BETWEEN's bounds, a CASE's WHEN values):
    /// the first that has one there.
    fn rows(&self, values: &[&Node], scope: &ScopeStack) -> Vec<Option<Fact>> {
        let mut out: Vec<Option<Fact>> = Vec::new();
        for row in values.iter().filter_map(|v| self.row(v, scope)) {
            for (i, f) in row.into_iter().enumerate() {
                if i >= out.len() {
                    out.push(None);
                }
                if out[i].as_ref().is_none_or(|known| matches!(known.ty, Ty::Unknown)) {
                    out[i] = f;
                }
            }
        }
        out
    }

    /// The type a built-in function gives its argument `i`, for a parameter written there.
    fn argument(&self, n: &Node, i: usize, scope: &ScopeStack) -> Ctx {
        let name = n.name.as_deref().unwrap_or("");
        if !n.agg && !n.window && self.extras.function(name, n.args.len()).is_some() {
            return Ctx::None;
        }
        let name = sqlean_alias(name);
        let text = || Ctx::Typed(Some(Fact::new("text", true)));
        let integer = || Ctx::Typed(Some(Fact::new("integer", true)));
        let real = || Ctx::Typed(Some(Fact::new("real", true)));
        let others = || {
            let facts: Vec<Fact> = n.args.iter().enumerate().filter(|(j, _)| *j != i).map(|(_, a)| self.type_of(a, scope)).collect();
            let refs: Vec<&Fact> = facts.iter().collect();
            let ty = shared(&refs);
            Ctx::Typed(if matches!(ty, Ty::Unknown) { None } else { Some(Fact { ty, non_null: true }) })
        };
        match name {
            "like" | "glob" | "regexp" | "match" | "upper" | "lower" | "trim" | "ltrim" | "rtrim" | "length" | "hex" | "unicode" | "quote" | "instr" | "replace" | "soundex"
            | "printf" | "format" | "concat" | "concat_ws" | "date" | "time" | "datetime" | "strftime" | "julianday" | "unixepoch" | "timediff" | "json"
            | "json_extract" | "json_type" | "json_valid" | "json_array_length" | "json_quote" | "json_pretty" | "json_insert" | "json_replace" | "json_set"
            | "json_remove" | "json_patch" | "->" | "->>" => text(),
            "substr" | "substring" => {
                if i == 0 { text() } else { integer() }
            }
            "zeroblob" | "randomblob" | "char" => integer(),
            "abs" | "round" | "acos" | "acosh" | "asin" | "asinh" | "atan" | "atan2" | "atanh" | "ceil" | "ceiling" | "cos" | "cosh" | "degrees" | "exp"
            | "floor" | "ln" | "log" | "log10" | "log2" | "mod" | "pow" | "power" | "radians" | "sin" | "sinh" | "sqrt" | "tan" | "tanh" | "trunc" => real(),
            "coalesce" | "ifnull" | "nullif" | "min" | "max" => others(),
            // `lag` and `lead` hand back their default where the row they read is missing, so the
            // value and the default each take the other's type.
            "lag" | "lead" if n.args.len() >= 3 && (i == 0 || i == 2) => {
                let other = self.type_of(&n.args[2 - i], scope);
                Ctx::Typed(if matches!(other.ty, Ty::Unknown) { None } else { Some(Fact { ty: other.ty, non_null: true }) })
            }
            // A condition is a truth value; a value shares the other values' type.
            "iif" | "if" => {
                let values = iif_values(n.args.len());
                if !values.contains(&i) {
                    Ctx::Bool
                } else {
                    let facts: Vec<Fact> = values.iter().filter(|j| **j != i).filter_map(|j| n.args.get(*j)).map(|a| self.type_of(a, scope)).collect();
                    let ty = shared(&facts.iter().collect::<Vec<_>>());
                    Ctx::Typed(if matches!(ty, Ty::Unknown) { None } else { Some(Fact { ty, non_null: true }) })
                }
            }
            "sum" | "avg" | "total" => real(),
            // After the FTS table: `highlight(t, column, open, close)` and `bm25(t, weight, …)`.
            // `snippet` takes its arguments in another order on FTS4 than on FTS5.
            "highlight" if i == 1 => integer(),
            "highlight" if i > 1 => text(),
            "bm25" if i > 0 => real(),
            // libSQL takes a vector as its text (`'[1,2,3]'`) or its blob: a parameter is the text.
            "vector" | "vector32" | "vector64" | "vector1bit" | "vector8" | "vector16" | "vectorb16" | "vector_extract" | "vector_distance_cos" | "vector_distance_l2" => text(),
            // sqlean's, each alias by the name it stands for ([`sqlean_alias`]).
            _ => match name {
                // A count or a length after the text: `left(s, n)`, `lpad(s, n, fill)`,
                // `split_part(s, sep, n)`, `text_slice(s, from, to)`, `regexp_capture(s, re, group)`.
                "left" | "right" | "text_left" | "text_right" | "repeat" | "text_repeat" | "lpad" | "rpad" | "text_lpad" | "text_rpad" if i == 1 => integer(),
                "split_part" | "text_split" | "regexp_capture" if i == 2 => integer(),
                "text_slice" | "text_substring" if i > 0 => integer(),
                "text_replace" if i == 3 => integer(),
                // A value to encode is bytes; a digest takes text as well, and is given text here.
                "encode" if i == 0 => Ctx::None,
                "uuid_str" | "uuid_blob" | "uuid7_timestamp_ms" | "md5" | "sha1" | "sha256" | "sha384" | "sha512" | "blake3" | "encode" | "decode" | "levenshtein" | "dlevenshtein"
                | "edit_distance" | "osa_distance" | "hamming" | "jaro_winkler" | "caverphone" | "phonetic_hash" | "rsoundex" | "translit" | "script_code" | "bit_length"
                | "char_length" | "character_length" | "btrim" | "left" | "right" | "lpad" | "rpad" | "repeat" | "reverse" | "split_part" | "starts_with" | "strpos" | "translate"
                | "regexp_like" | "regexp_substr" | "regexp_capture" | "regexp_replace" => text(),
                t if t.starts_with("text_") => text(),
                // A percentile's value and its rank, between 0 and 100.
                "median" | "percentile" | "percentile_25" | "percentile_75" | "percentile_90" | "percentile_95" | "percentile_99" | "stddev" | "stddev_pop" | "stddev_samp" | "variance"
                | "var_pop" | "var_samp" => real(),
                _ => Ctx::None,
            },
        }
    }

    // ---- the row count -----------------------------------------------------------------------

    fn cardinality(&self) -> (Cardinality, Option<String>) {
        let t = self.tree;
        if let Some(dml) = &t.dml {
            if t.returning.is_none() {
                return (Cardinality::None, None);
            }
            return match dml.kind.as_str() {
                "insert" => {
                    if dml.rows == 1 {
                        let triggered = |events: i32| self.skipping.get(&dml.table.to_ascii_lowercase()).is_some_and(|mask| mask & events != 0);
                        // With no OR clause of its own, a constraint's own conflict clause applies.
                        let declared_ignore = dml.on_error == "default" && self.tree.tables.get(&dml.table).is_some_and(|t| t.ignores);
                        let can_skip = dml.on_error == "ignore"
                            || declared_ignore
                            || dml.upserts.iter().any(|u| !u.do_update || u.where_.is_some() || triggered(TRIGGER_ROW_UPDATE))
                            || triggered(TRIGGER_ROW_INSERT);
                        if can_skip { (Cardinality::AtMostOne, Some("ON CONFLICT DO NOTHING, OR IGNORE, a constraint declared ON CONFLICT IGNORE, a DO UPDATE with a WHERE, or a BEFORE trigger's RAISE(IGNORE) can insert no row".into())) } else { (Cardinality::One, None) }
                    } else if dml.rows > 1 {
                        (Cardinality::Many, Some(format!("a VALUES list of {} rows returns {} rows", dml.rows, dml.rows)))
                    } else {
                        (Cardinality::Many, Some("an INSERT ... SELECT returns a row per row it reads".into()))
                    }
                }
                _ => {
                    // UPDATE or DELETE: the WHERE pins a unique key of the target, or any number.
                    match self.pinned_by_name(&dml.table, dml.where_.as_ref()) {
                        Ok(()) => (Cardinality::AtMostOne, None),
                        Err(why) => (Cardinality::Many, Some(why)),
                    }
                }
            };
        }
        let Some(sel) = &t.statement else { return (Cardinality::None, None) };
        match self.exactly_one(sel) {
            Ok(()) => (Cardinality::One, None),
            Err(one_why) => match self.at_most_one(sel) {
                Ok(()) => (Cardinality::AtMostOne, Some(one_why)),
                Err(why) => (Cardinality::Many, Some(why)),
            },
        }
    }

    fn exactly_one(&self, sel: &Sel) -> Result<(), String> {
        // A constant LIMIT of a row or more keeps the one row, and so does an OFFSET of 0; a
        // parameter may be 0.
        let keeps = |n: &Node, least: i64| integer(n).is_some_and(|n| n >= least);
        if sel.limit.as_ref().is_some_and(|l| !keeps(l, 1)) || sel.offset.as_ref().is_some_and(|o| integer(o) != Some(0)) {
            return Err("a LIMIT or an OFFSET can remove the row (LIMIT 0, OFFSET 1)".into());
        }
        self.one_before_limit(sel)
    }

    /// Exactly one row before the statement's LIMIT and OFFSET apply.
    fn one_before_limit(&self, sel: &Sel) -> Result<(), String> {
        if sel.prior.is_some() {
            return Err("a set operation (UNION, INTERSECT, EXCEPT) returns any number of rows".into());
        }
        if sel.values && !sel.rows.is_empty() {
            return Err("a VALUES list returns a row per row it lists".into());
        }
        if sel.values {
            return Ok(());
        }
        if !sel.group_by.is_empty() {
            return Err("GROUP BY returns one row per group, and none when nothing matches".into());
        }
        if sel.having.is_some() {
            return Err("HAVING can remove the row".into());
        }
        // SQLite marks the SELECT an aggregate belongs to: one whose arguments read only columns
        // of a query around this one (`count(a.id)` in a subquery over `b`) is that query's, and
        // leaves this one a row per row of its FROM.
        if sel.aggregate && sel.columns.iter().any(|c| has_aggregate(&c.expr)) {
            return Ok(());
        }
        if sel.from.is_empty() && sel.where_.is_none() {
            return Ok(());
        }
        // A FROM of exactly one row, as `cardinality` proves it: never empty, and one row at most.
        if !sel.from.is_empty() && self.never_empty(sel) && self.arm_at_most_one(sel).is_ok() {
            return Ok(());
        }
        Err("a FROM returns a row per row it matches, and only an aggregate with no GROUP BY collapses them to one".into())
    }

    /// Whether the FROM returns a row whatever the tables hold: every item is a subquery or a WITH
    /// query of exactly one row, or sits on the nullable side of a LEFT JOIN, which keeps the row
    /// of its other side; and no WHERE term can fail but one from an outer join's ON, which
    /// removes no row. An inner join's ON is a WHERE term here, so `ON 1 = 1` is one that holds.
    /// A VALUES in a FROM is any number of rows: SQLite reads a list of several rows as one such
    /// item, which does not say how many it lists.
    fn never_empty(&self, sel: &Sel) -> bool {
        let holds = |t: &Node| match (t.op.as_str(), t.left.as_deref().and_then(integer), t.right.as_deref().and_then(integer)) {
            ("=", Some(l), Some(r)) => l == r,
            _ => integer(t).is_some_and(|n| n != 0),
        };
        sel.from.iter().all(|f| !f.right && (f.outer || f.subquery.as_ref().is_some_and(|sub| !sub.values && self.exactly_one(sub).is_ok())))
            && conjuncts(sel.where_.as_ref()).iter().all(|t| t.outer_on || holds(t))
    }

    fn at_most_one(&self, sel: &Sel) -> Result<(), String> {
        if sel.limit.as_ref().and_then(integer).is_some_and(|n| (0..=1).contains(&n)) {
            return Ok(());
        }
        // Any other LIMIT, and an OFFSET, only remove rows: the bound is the one the statement has
        // without them.
        if !sel.values && self.one_before_limit(sel).is_ok() {
            return Ok(());
        }
        // An INTERSECT returns only rows both sides return, and an EXCEPT only rows of its left
        // side (`prior`, the arms before this one): at most one row when a side it draws every
        // row from is.
        if let Some(prior) = &sel.prior {
            let drawn = match sel.op.as_deref() {
                Some("intersect") => self.at_most_one(prior).is_ok() || self.arm_at_most_one(sel).is_ok(),
                Some("except") => self.at_most_one(prior).is_ok(),
                _ => false,
            };
            return if drawn { Ok(()) } else { Err("a set operation (UNION, INTERSECT, EXCEPT) returns any number of rows".into()) };
        }
        self.arm_at_most_one(sel)
    }

    /// The proof for one SELECT arm, its set operation aside: the closure of [`Self::determined`],
    /// as `cardinality` proves it over libpg_query's tree. Every FROM item determined is one row
    /// at most; one group at most when every GROUP BY expression is pinned; one row at most from
    /// a DISTINCT over pinned values.
    fn arm_at_most_one(&self, sel: &Sel) -> Result<(), String> {
        if sel.values {
            return Err("a VALUES list returns a row per row it lists".into());
        }
        if !sel.group_by.is_empty() {
            if sel.from.iter().all(|f| !f.right) && self.determined(sel, false).iter().all(|d| *d) {
                return Ok(());
            }
            let constant = self.determined(sel, true);
            if sel.group_by.iter().all(|g| self.pinned(sel, g, &constant)) {
                return Ok(());
            }
            return Err("GROUP BY returns one row per group; the engine proves one group only when every GROUP BY expression is pinned to one value: a column of a relation whose unique key the WHERE pins, or a column the WHERE equates to a value".into());
        }
        if sel.having.is_some() {
            return Err("HAVING leaves a row per group".into());
        }
        if sel.from.is_empty() {
            return Err("a SELECT with no FROM and a WHERE can return no row or one, and the engine proves that only through a LIMIT".into());
        }
        // A RIGHT or FULL JOIN keeps the rows of each side that match nothing: two rows where
        // each side has one.
        if sel.from.iter().any(|f| f.right) {
            return Err("a RIGHT or FULL JOIN returns a row for each side that matches nothing".into());
        }
        let determined = self.determined(sel, false);
        if determined.iter().all(|d| *d) {
            return Ok(());
        }
        if sel.distinct {
            let constant = self.determined(sel, true);
            if !sel.columns.is_empty() && sel.columns.iter().all(|c| self.pinned(sel, &c.expr, &constant)) {
                return Ok(());
            }
        }
        let i = determined.iter().position(|d| !d).unwrap_or(0);
        let f = &sel.from[i];
        let Some(table) = f.table.as_deref().filter(|_| f.subquery.is_none() && !f.tab_func) else {
            return Err(format!("`{}` in the FROM is a subquery or a table-valued function that returns any number of rows", f.alias.as_deref().or(f.table.as_deref()).unwrap_or("?")));
        };
        let keys = self.tree.tables.get(table).map(|t| t.unique_keys.clone()).unwrap_or_default();
        if keys.is_empty() {
            return Err(format!("`{table}` has no unique index the engine can read, so nothing bounds the rows a WHERE matches"));
        }
        let shown: Vec<String> = keys.iter().map(|k| format!("({})", k.join(", "))).collect();
        if sel.from.len() == 1 {
            Err(format!("the WHERE does not equate every column of a unique key of `{table}` — it has {}", shown.join(", ")))
        } else {
            let name = f.alias.as_deref().unwrap_or(table);
            Err(format!("a join returns a row per pair it matches, and the WHERE and ON clauses do not equate every column of a unique key of `{name}` to values or to columns of relations pinned to one row — it has {}", shown.join(", ")))
        }
    }

    /// Which FROM items are determined: every row carries the same row of each, or its null
    /// extension (see `cardinality`'s `From`). A table is, when a unique key's every column is
    /// equated to a value or to a column of a determined item; a subquery or a WITH query, when the
    /// proof bounds it. SQLite moves every ON term into the WHERE: a term from an outer join's ON
    /// pins only that join's right side, and with `constant`, which asks that every row carry the
    /// same row of an item, never: some rows may meet the null extension instead.
    fn determined(&self, sel: &Sel, constant: bool) -> Vec<bool> {
        let derived = self.derived_keys(sel);
        self.determined_from(sel, vec![false; sel.from.len()], &derived, constant)
    }

    /// The keys of each subquery, WITH query and view in the FROM ([`Self::output_keys`]): they
    /// pin it to one row as a unique index pins a table. None for a table.
    fn derived_keys(&self, sel: &Sel) -> Vec<Vec<Vec<i64>>> {
        sel.from.iter().map(|f| f.subquery.as_ref().map(|sub| self.output_keys(sub)).unwrap_or_default()).collect()
    }

    /// [`Self::determined`], with the items `done` names taken as determined from the start: with
    /// one item alone, whether every row of it meets one row at most of each other item.
    fn determined_from(&self, sel: &Sel, mut done: Vec<bool>, derived: &[Vec<Vec<i64>>], constant: bool) -> Vec<bool> {
        let n = sel.from.len();
        let index: HashMap<i64, usize> = sel.from.iter().enumerate().map(|(i, f)| (f.cursor, i)).collect();
        let terms = conjuncts(sel.where_.as_ref());
        loop {
            let mut changed = false;
            for i in 0..n {
                if done[i] {
                    continue;
                }
                let f = &sel.from[i];
                let pinned = if let Some(sub) = &f.subquery {
                    let usable: Vec<&Node> = terms.iter().copied().filter(|t| !t.outer_on || (!constant && t.join == f.cursor)).collect();
                    !(constant && f.outer) && (self.at_most_one(sub).is_ok() || self.derived_pinned(&derived[i], f.cursor, &usable, &done, &index))
                } else if let (Some(table), false, false) = (f.table.as_deref(), f.tab_func, f.virtual_) {
                    // A WHERE term's `=` rejects the null extension, so it pins even an outer
                    // join's right side for every row.
                    let usable: Vec<&Node> = terms.iter().copied().filter(|t| !t.outer_on || (!constant && t.join == f.cursor)).collect();
                    self.key_pinned(table, f.cursor, &usable, &done, &index)
                } else {
                    false
                };
                if pinned {
                    done[i] = true;
                    changed = true;
                }
            }
            if !changed {
                return done;
            }
        }
    }

    /// Whether some unique key of `table` (read through `cursor`) has every column equated by
    /// one of `terms` to a value: one that reads no column of this FROM's undetermined items (a
    /// column of a determined item is one value, and so is an enclosing query's), calls nothing
    /// that changes from row to row, and carries no COLLATE.
    fn key_pinned(&self, table: &str, cursor: i64, terms: &[&Node], done: &[bool], index: &HashMap<i64, usize>) -> bool {
        let Some(info) = self.tree.tables.get(table) else { return false };
        let pins: Vec<&str> = terms.iter().filter_map(|t| self.pins(t, cursor, done, index)).collect();
        info.unique_keys.iter().any(|key| !key.is_empty() && key.iter().all(|c| pins.iter().any(|p| p.eq_ignore_ascii_case(c))))
    }

    /// Whether `terms` equate every column of one of `keys` (output positions of the subquery read
    /// through `cursor`) to a value, as [`Self::key_pinned`] equates a table's.
    fn derived_pinned(&self, keys: &[Vec<i64>], cursor: i64, terms: &[&Node], done: &[bool], index: &HashMap<i64, usize>) -> bool {
        let pinned: Vec<i64> = terms.iter().filter_map(|t| self.pinned_column(t, cursor, done, index)).map(|c| c.index).collect();
        keys.iter().any(|key| !key.is_empty() && key.iter().all(|p| pinned.contains(p)))
    }

    /// The unique keys of a SELECT's rows, each a set of its output columns by position, no two of
    /// its rows sharing a value of every one of them (NULL aside, which no `=` matches):
    ///
    /// - a unique key of one of its FROM items, every column of it in the select list unchanged,
    ///   when every other item is determined against that item ([`Self::determined_from`]): each
    ///   of its rows then meets one row at most of the rest. A WHERE, a HAVING, a LIMIT and an
    ///   OFFSET only remove rows, and a window function adds none;
    /// - the GROUP BY's expressions, each a column of the select list;
    /// - under DISTINCT, the whole select list, every entry a column.
    ///
    /// None for a set operation or a VALUES list, which may repeat a row.
    fn output_keys(&self, sel: &Sel) -> Vec<Vec<i64>> {
        if let Some(prior) = &sel.prior {
            return self.compound_keys(sel, prior);
        }
        if sel.values {
            return Vec::new();
        }
        let index: HashMap<i64, usize> = sel.from.iter().enumerate().map(|(i, f)| (f.cursor, i)).collect();
        // The output position of a column of this FROM, kept unchanged.
        let position = |found: &dyn Fn(&Node) -> bool| sel.columns.iter().position(|c| c.expr.op == "column" && index.contains_key(&c.expr.cursor) && found(&c.expr)).map(|p| p as i64);
        let mut keys = Vec::new();
        if !sel.group_by.is_empty() {
            let key: Option<Vec<i64>> = sel.group_by.iter().map(|g| if g.op == "column" { position(&|e: &Node| e.cursor == g.cursor && e.index == g.index) } else { None }).collect();
            keys.extend(key);
            return keys;
        }
        if sel.distinct && !sel.columns.is_empty() && sel.columns.iter().all(|c| c.expr.op == "column" && index.contains_key(&c.expr.cursor)) {
            keys.push((0..sel.columns.len() as i64).collect());
        }
        // A RIGHT or FULL JOIN keeps rows of a side that match nothing, which the closure does not
        // read.
        if sel.from.iter().any(|f| f.right) {
            return keys;
        }
        let derived = self.derived_keys(sel);
        let n = sel.from.len();
        for (r, f) in sel.from.iter().enumerate() {
            if f.tab_func || f.virtual_ {
                continue;
            }
            let mut seed = vec![false; n];
            seed[r] = true;
            if !self.determined_from(sel, seed, &derived, false).iter().all(|d| *d) {
                continue;
            }
            if f.subquery.is_some() {
                for key in &derived[r] {
                    keys.extend(key.iter().map(|p| position(&|e: &Node| e.cursor == f.cursor && e.index == *p)).collect::<Option<Vec<i64>>>());
                }
            } else if let Some(info) = f.table.as_deref().and_then(|t| self.tree.tables.get(t)) {
                // A key column the select list leaves out still counts where the WHERE pins it to
                // one value.
                let fixed = |c: &str| {
                    let none = vec![false; n];
                    conjuncts(sel.where_.as_ref()).iter().filter(|t| !t.outer_on).any(|t| self.pinned_column(t, f.cursor, &none, &index).and_then(|col| col.column.as_deref()).is_some_and(|name| name.eq_ignore_ascii_case(c)))
                };
                for key in info.unique_keys.iter().filter(|k| !k.is_empty()) {
                    keys.extend(
                        key.iter()
                            .filter_map(|c| match position(&|e: &Node| e.cursor == f.cursor && e.column.as_deref().is_some_and(|name| name.eq_ignore_ascii_case(c))) {
                                Some(p) => Some(Some(p)),
                                None if fixed(c) => None,
                                None => Some(None),
                            })
                            .collect::<Option<Vec<i64>>>(),
                    );
                }
            }
        }
        keys
    }

    /// The keys of a compound SELECT's rows, `sel` its last arm and `prior` the arms before it.
    /// INTERSECT and EXCEPT return only rows of their left side, so they keep its keys. Any operator
    /// but UNION ALL returns distinct rows, so the whole row is a key, where each column is a
    /// column on every arm, of one affinity and one collation, which the comparison that told the
    /// rows apart and the one that reads them agree on.
    fn compound_keys(&self, sel: &Sel, prior: &Sel) -> Vec<Vec<i64>> {
        let op = sel.op.as_deref().unwrap_or("");
        let mut keys = Vec::new();
        if op == "intersect" || op == "except" {
            keys.extend(self.output_keys(prior));
        }
        if op != "union all" {
            let mut arms = vec![sel];
            let mut at = Some(prior);
            while let Some(arm) = at {
                arms.push(arm);
                at = arm.prior.as_deref();
            }
            let width = sel.columns.len();
            let alike = width > 0
                && arms.iter().all(|arm| !arm.values && arm.columns.len() == width)
                && (0..width).all(|i| {
                    let first = &sel.columns[i].expr;
                    first.op == "column" && arms.iter().all(|arm| {
                        let e = &arm.columns[i].expr;
                        e.op == "column" && e.aff == first.aff && e.coll.as_deref().unwrap_or("BINARY").eq_ignore_ascii_case(first.coll.as_deref().unwrap_or("BINARY"))
                    })
                });
            if alike {
                keys.push((0..width as i64).collect());
            }
        }
        keys
    }

    /// The column of `cursor` a term equates to a value, if it does, under a comparison that
    /// leaves the column as it is ([`keeps_column`]) and a collation its unique index holds to:
    /// the left operand's column's, else the right's (`sqlite3BinaryCompareCollSeq`), which must
    /// be BINARY or the key's own.
    fn pins<'n>(&self, t: &'n Node, cursor: i64, done: &[bool], index: &HashMap<i64, usize>) -> Option<&'n str> {
        self.pinned_column(t, cursor, done, index).and_then(|col| col.column.as_deref())
    }

    /// [`Self::pins`]'s column itself.
    fn pinned_column<'n>(&self, t: &'n Node, cursor: i64, done: &[bool], index: &HashMap<i64, usize>) -> Option<&'n Node> {
        if t.op != "=" {
            return None;
        }
        let (l, r) = (t.left.as_deref()?, t.right.as_deref()?);
        let collation = column_of(l).or_else(|| column_of(r)).and_then(|c| c.coll.as_deref()).unwrap_or("BINARY");
        [(l, r), (r, l)].into_iter().find_map(|(col, other)| {
            let value = col.op == "column"
                && col.cursor == cursor
                && !has_op(other, "collate")
                && keeps_column(col, other)
                && (collation.eq_ignore_ascii_case("BINARY") || col.coll.as_deref().is_some_and(|c| c.eq_ignore_ascii_case(collation)))
                && !self.calls_volatile(other)
                && other.select.is_none()
                && cursors(other).is_some_and(|read| read.iter().all(|c| *c != cursor && index.get(c).is_none_or(|i| done[*i])));
            value.then_some(col)
        })
    }

    /// Whether every row carries the same value of `e`: a column of a constant item, a column the
    /// WHERE (not an outer join's ON) equates to a value, or a value itself.
    fn pinned(&self, sel: &Sel, e: &Node, constant: &[bool]) -> bool {
        let index: HashMap<i64, usize> = sel.from.iter().enumerate().map(|(i, f)| (f.cursor, i)).collect();
        if e.op == "column" {
            if index.get(&e.cursor).is_some_and(|i| constant[*i]) {
                return true;
            }
            let terms = conjuncts(sel.where_.as_ref());
            return terms.iter().filter(|t| !t.outer_on).filter_map(|t| self.pins(t, e.cursor, constant, &index)).any(|c| e.column.as_deref().is_some_and(|name| name.eq_ignore_ascii_case(c)));
        }
        e.select.is_none() && !self.calls_volatile(e) && cursors(e).is_some_and(|read| read.iter().all(|c| !index.contains_key(c)))
    }

    /// The DML form: the target table's columns have no stable cursor, so they match by name.
    fn pinned_by_name(&self, table: &str, where_: Option<&Node>) -> Result<(), String> {
        let equated = self.equated(where_);
        let Some(info) = self.tree.tables.get(table) else { return Err(format!("`{table}` is not a table the engine can read")) };
        let names: HashSet<String> = equated.iter().map(|(_, n)| n.to_ascii_lowercase()).collect();
        if info.unique_keys.iter().any(|key| !key.is_empty() && key.iter().all(|c| names.contains(&c.to_ascii_lowercase()))) {
            return Ok(());
        }
        if info.unique_keys.is_empty() {
            return Err(format!("`{table}` has no unique index the engine can read, so nothing bounds the rows a WHERE matches"));
        }
        let shown: Vec<String> = info.unique_keys.iter().map(|k| format!("({})", k.join(", "))).collect();
        Err(format!("the WHERE does not equate every column of a unique key of `{table}` — it has {}", shown.join(", ")))
    }

    /// The columns the WHERE equates to a value: `col = <no column anywhere>` under ANDs, where
    /// the value calls nothing that changes from row to row.
    fn equated(&self, where_: Option<&Node>) -> HashSet<(i64, String)> {
        let mut out = HashSet::new();
        for n in conjuncts(where_) {
            if n.op != "=" || n.outer_on {
                continue;
            }
            if let (Some(l), Some(r)) = (n.left.as_deref(), n.right.as_deref()) {
                for (col, other) in [(l, r), (r, l)] {
                    // An explicit COLLATE (NOCASE) may compare more loosely than the
                    // unique index distinguishes.
                    if col.op == "column" && !reads_column(other) && !has_op(other, "collate") && keeps_column(col, other) && !self.calls_volatile(other) {
                        if let Some(name) = &col.column {
                            out.insert((col.cursor, name.clone()));
                        }
                    }
                }
            }
        }
        out
    }

    /// Whether `n` calls a function that may give each row another value: `random()`,
    /// `changes()`, a date or time function (`'now'` moves), one the host registers or the
    /// engine does not know, whose determinism it cannot tell, or a window call or aggregate,
    /// whose value is its frame's or its group's (`min(1) over (… rows 1 preceding …)` is NULL on
    /// the first row and 1 on the next).
    fn calls_volatile(&self, n: &Node) -> bool {
        const VOLATILE: &[&str] = &["random", "randomblob", "changes", "total_changes", "last_insert_rowid", "date", "time", "datetime", "julianday", "unixepoch", "strftime", "timediff"];
        if n.op == "function" {
            if n.agg || n.window || n.over {
                return true;
            }
            let name = n.name.as_deref().unwrap_or("").to_ascii_lowercase();
            if VOLATILE.contains(&name.as_str()) || self.extras.function(&name, n.args.len()).is_some() || !KNOWN_FUNCTIONS.contains(&name.as_str()) {
                return true;
            }
        }
        n.left.as_deref().is_some_and(|x| self.calls_volatile(x)) || n.right.as_deref().is_some_and(|x| self.calls_volatile(x)) || n.list.iter().any(|x| self.calls_volatile(x)) || n.args.iter().any(|x| self.calls_volatile(x))
    }
}

/// Whether comparing key column `col` with `other` leaves the column's values as they are. SQLite
/// applies NUMERIC affinity to both sides where either side's affinity is INTEGER, REAL or NUMERIC,
/// and one side's affinity to both where the other has none, so a TEXT key compared with a number
/// reads '01' and '1' as 1, and a key of no affinity compared with a TEXT side reads 7 as '7'. A
/// numeric key converts nothing it holds: what stays text there is no number.
fn keeps_column(col: &Node, other: &Node) -> bool {
    let numeric = |a: &str| matches!(a, "integer" | "real" | "numeric");
    let none = |a: &str| matches!(a, "blob" | "none");
    numeric(&col.aff) || none(&other.aff) || (col.aff == "text" && other.aff == "text")
}

/// The column an operand reads through casts and unary plus, as SQLite looks for the collation.
fn column_of(n: &Node) -> Option<&Node> {
    match n.op.as_str() {
        "column" => Some(n),
        "cast" | "pos" => n.left.as_deref().and_then(column_of),
        _ => None,
    }
}

/// A string literal's text.
fn literal_text(n: &Node) -> Option<&str> {
    if n.op == "string" { n.value.as_deref() } else { None }
}

/// The arguments of `iif(c1, v1, c2, v2, …, else)` that are its values: each one after a
/// condition, and the last of an odd count, the ELSE.
fn iif_values(count: usize) -> Vec<usize> {
    let mut out: Vec<usize> = (1..count).step_by(2).collect();
    if count >= 3 && count % 2 == 1 {
        out.push(count - 1);
    }
    out
}

/// Whether a call is a window call whose frame always holds the current row, as SQLite resolved
/// it (a named window's frame copied in), with no FILTER. No frame clause is `RANGE BETWEEN
/// UNBOUNDED PRECEDING AND CURRENT ROW`: every row through the current row's last peer, the whole
/// partition without ORDER BY. A frame that starts UNBOUNDED PRECEDING, `n PRECEDING` or at
/// CURRENT ROW and ends at CURRENT ROW, `n FOLLOWING` or UNBOUNDED FOLLOWING holds it in every
/// mode: SQLite refuses a negative offset and, in RANGE mode, finds the current row within any
/// offset of itself, a NULL, an infinity, a text and a blob included (measured on 3.51 and
/// checked by the oracle on the embedded SQLite). A start `n FOLLOWING` or an end `n PRECEDING`
/// can leave the row out, and `EXCLUDE CURRENT ROW` and `EXCLUDE GROUP` do; `EXCLUDE TIES` keeps it.
fn holds_current_row(n: &Node) -> bool {
    let start = matches!(n.frame_start.as_deref(), Some("unbounded" | "preceding" | "current"));
    let end = matches!(n.frame_end.as_deref(), Some("unbounded" | "following" | "current"));
    let exclude = matches!(n.exclude.as_deref(), Some("no" | "ties"));
    n.over && !n.filter && start && end && exclude
}

/// When `total` is NULL: never over integers, but over reals a `1e999` and a `-1e999` add up to
/// NaN, which SQLite gives as NULL.
fn total_nulls(arg: &Fact) -> Nulls {
    if is_integral(&arg.ty) { Nulls::Never } else { Nulls::Always }
}

/// Whether a date and time function always reads its time value and modifiers. SQLite gives NULL
/// for a time value it cannot read (`date('not a date')`), one outside the julian days 0 to
/// 5373484 it reads (`date(-1)`, `datetime(1e18, 'unixepoch')`), and a modifier that fails
/// (`'weekday 7'`, `'unixepoch'` after a text value) or moves the time out of that range. So this
/// holds only for no time value (the current time), the current time (`'now'` in any case, or
/// `current_timestamp`, `current_date` or `current_time`) moved less than a thousand years, or a
/// number literal (a julian day, or a unix time read by a first `'unixepoch'`) whose modifiers
/// keep it in range; and only for literal modifiers that cannot fail on it.
fn current_time(args: &[Node]) -> bool {
    let Some((value, modifiers)) = args.split_first() else { return true };
    let now = literal_text(value).is_some_and(|v| v.eq_ignore_ascii_case("now"))
        || (value.op == "function" && value.args.is_empty() && matches!(value.name.as_deref(), Some("current_timestamp" | "current_date" | "current_time")));
    let number = if matches!(value.op.as_str(), "integer" | "float") { value.value.as_deref().and_then(|v| v.parse::<f64>().ok()).filter(|v| v.is_finite()) } else { None };
    let mut modifiers = modifiers.iter().map(literal_text).peekable();
    let julian_day = match number {
        Some(v) if modifiers.peek().is_some_and(|m| m.is_some_and(|m| m.eq_ignore_ascii_case("unixepoch"))) => {
            modifiers.next();
            v / 86_400.0 + 2_440_587.5
        }
        Some(v) => v,
        None if now => 0.0,
        None => return false,
    };
    // The days the modifiers may move the time by, each at most.
    let mut days = 0.0;
    for m in modifiers {
        let Some(m) = m else { return false };
        let m = m.to_ascii_lowercase();
        days += match m.as_str() {
            "subsec" | "subsecond" => 0.0,
            // `ceiling` and `floor` are new in 3.46.0, and NULL before it (libSQL's 3.45.1).
            "localtime" | "utc" => 1.0,
            "start of day" | "start of month" | "start of year" => 366.0,
            _ if m.len() == 9 && m.starts_with("weekday ") && matches!(m.as_bytes()[8], b'0'..=b'6') => 7.0,
            _ => match shift_days(&m) {
                Some(d) => d,
                None => return false,
            },
        };
    }
    if now {
        days < 365_000.0
    } else {
        // With a margin for the rounding of months and years.
        let margin = if days > 0.0 { days + 400.0 } else { 0.0 };
        julian_day - margin >= 0.0 && julian_day + margin < 5_373_484.0
    }
}

/// How far a modifier `±N unit` (`'+7 days'`, `'-1.5 hours'`) moves a time, in days at most, as
/// SQLite spells one: a number, spaces, and a unit, with or without its plural `s`.
fn shift_days(m: &str) -> Option<f64> {
    let (number, unit) = m.split_once(' ')?;
    let unit = unit.trim_start_matches(' ');
    let unit = unit.strip_suffix('s').unwrap_or(unit);
    let days = match unit {
        "second" => 1.0 / 86_400.0,
        "minute" => 1.0 / 1_440.0,
        "hour" => 1.0 / 24.0,
        "day" => 1.0,
        "month" => 31.0,
        "year" => 366.0,
        _ => return None,
    };
    let digits = number.strip_prefix(['+', '-']).unwrap_or(number);
    let (whole, fraction) = digits.split_once('.').unwrap_or((digits, "0"));
    let all_digits = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit());
    if !all_digits(whole) || !all_digits(fraction) {
        return None;
    }
    Some(digits.parse::<f64>().ok()? * days)
}

/// Whether `printf` with this format writes a character whatever its arguments are. SQLite gives
/// NULL where it wrote none, as for an empty format, and stops at a conversion it does not know
/// (`printf('%T')` is NULL, `printf('a%T')` is 'a'), so a character of the format itself or a `%%`
/// must come before any such conversion. The directive is read as SQLite's `sqlite3_str_vappendf`
/// reads it: flags, a width, a precision and a length, in that loop's order.
fn printf_writes(format: &str) -> bool {
    let b = format.as_bytes();
    let at = |i: usize| b.get(i).copied().unwrap_or(0);
    let mut i = 0;
    loop {
        match at(i) {
            0 => return false,
            b'%' => {}
            _ => return true,
        }
        i += 1;
        // A `%` that ends the format is written as it is.
        if at(i) == 0 {
            return true;
        }
        let mut c = at(i);
        loop {
            match c {
                b'-' | b'+' | b' ' | b'#' | b'!' | b'0' | b',' => {}
                b'l' => {
                    i += 1;
                    if at(i) == b'l' {
                        i += 1;
                    }
                    c = at(i);
                    break;
                }
                b'1'..=b'9' => {
                    while at(i + 1).is_ascii_digit() {
                        i += 1;
                    }
                    if !matches!(at(i + 1), b'.' | b'l') {
                        i += 1;
                        c = at(i);
                        break;
                    }
                }
                b'*' => {
                    if !matches!(at(i + 1), b'.' | b'l') {
                        i += 1;
                        c = at(i);
                        break;
                    }
                }
                b'.' => {
                    i += 1;
                    if at(i) == b'*' {
                        i += 1;
                    } else {
                        while at(i).is_ascii_digit() {
                            i += 1;
                        }
                    }
                    if at(i) != b'l' {
                        c = at(i);
                        break;
                    }
                    i -= 1;
                }
                _ => break,
            }
            i += 1;
            c = at(i);
            if c == 0 {
                break;
            }
        }
        match c {
            b'%' => return true,
            // `T` and `S` are SQLite's own, which a SQL call cannot use: it stops there.
            b's' | b'E' | b'u' | b'G' | b'w' | b'x' | b'c' | b'z' | b'd' | b'e' | b'f' | b'g' | b'Q' | b'i' | b'X' | b'n' | b'o' | b'p' | b'q' | b'r' => i += 1,
            _ => return false,
        }
    }
}

/// Whether every conversion of a `strftime` format is one SQLite knows; any other makes it NULL,
/// as does a `%` that ends the format. `%G`, `%g`, `%U` and `%V` are left out: they are new in
/// 3.46.0, and before it (libSQL and Turso run 3.45.1) they make the call NULL.
fn strftime_format(format: &str) -> bool {
    let mut bytes = format.bytes();
    while let Some(b) = bytes.next() {
        if b == b'%' && !bytes.next().is_some_and(|c| b"deFfHkIljJmMpPRsSTuwWY%".contains(&c)) {
            return false;
        }
    }
    true
}

/// The function a sqlean alias stands for, as the extensions Turso Cloud loads register both:
/// `math_floor` is `floor`, `fuzzy_leven` is `levenshtein`, `stats_p90` is `percentile_90`.
fn sqlean_alias(name: &str) -> &str {
    match name {
        "fuzzy_caver" => "caverphone",
        "fuzzy_damlev" => "dlevenshtein",
        "fuzzy_editdist" => "edit_distance",
        "fuzzy_hamming" => "hamming",
        "fuzzy_jarowin" => "jaro_winkler",
        "fuzzy_leven" => "levenshtein",
        "fuzzy_osadist" => "osa_distance",
        "fuzzy_phonetic" => "phonetic_hash",
        "fuzzy_rsoundex" => "rsoundex",
        "fuzzy_script" => "script_code",
        "fuzzy_soundex" => "soundex",
        "fuzzy_translit" => "translit",
        "stats_median" => "median",
        "stats_perc" => "percentile",
        "stats_p25" => "percentile_25",
        "stats_p75" => "percentile_75",
        "stats_p90" => "percentile_90",
        "stats_p95" => "percentile_95",
        "stats_p99" => "percentile_99",
        "stats_stddev" => "stddev",
        "stats_stddev_pop" => "stddev_pop",
        "stats_stddev_samp" => "stddev_samp",
        "stats_var" => "variance",
        "stats_var_pop" => "var_pop",
        "stats_var_samp" => "var_samp",
        _ => match name.strip_prefix("crypto_").or_else(|| name.strip_prefix("math_")) {
            Some(base @ ("md5" | "sha1" | "sha256" | "sha384" | "sha512" | "blake3" | "encode" | "decode")) if name.starts_with("crypto_") => base,
            Some(
                base @ ("acos" | "acosh" | "asin" | "asinh" | "atan" | "atan2" | "atanh" | "ceil" | "cos" | "cosh" | "degrees" | "exp" | "floor" | "ln" | "log" | "log10" | "log2" | "mod" | "pi"
                | "pow" | "radians" | "round" | "sin" | "sinh" | "sqrt" | "tan" | "tanh" | "trunc"),
            ) if name.starts_with("math_") => base,
            _ => name,
        },
    }
}

/// SQLite's built-in scalar functions the engine's table reads, by name.
const KNOWN_FUNCTIONS: &[&str] = &[
    "coalesce", "ifnull", "nullif", "iif", "if", "min", "max", "abs", "round", "length", "instr", "unicode", "json_array_length", "json_valid", "octet_length", "sign",
    "like", "glob", "regexp", "match", "likely", "unlikely", "likelihood", "upper", "lower", "trim", "ltrim", "rtrim", "substr", "substring", "replace", "char",
    "printf", "format", "concat", "concat_ws", "json", "jsonb", "json_array", "json_object", "json_insert", "json_replace", "json_set", "json_remove", "json_patch",
    "json_quote", "json_pretty", "json_type", "hex", "quote", "typeof", "soundex", "zeroblob", "json_extract", "jsonb_extract", "->", "->>", "acos", "acosh", "asin", "asinh",
    "atan", "atan2", "atanh", "ceil", "ceiling", "cos", "cosh", "degrees", "exp", "floor", "ln", "log", "log10", "log2", "mod", "pow", "power", "radians", "sin",
    "sinh", "sqrt", "tan", "tanh", "trunc", "pi",
];

/// An integer literal's value.
fn integer(n: &Node) -> Option<i64> {
    if n.op == "integer" { n.value.as_deref().and_then(|v| v.parse().ok()) } else { None }
}

/// Whether SQLite reads an integer literal as an INTEGER: a decimal one that fits in 64 bits, or
/// any hexadecimal one, since one past 64 bits is an error. A decimal one past 2^63 - 1 is a REAL.
/// Its digit separators are gone from its text, and leading zeros do not count.
fn integer_literal_fits(n: &Node) -> bool {
    n.value.as_deref().is_none_or(|v| v.starts_with("0x") || v.starts_with("0X") || v.parse::<i64>().is_ok())
}

/// Whether a node is the decimal integer literal 2^63.
fn is_two_to_the_63(n: &Node) -> bool {
    n.op == "integer" && n.value.as_deref().and_then(|v| v.parse::<u64>().ok()) == Some(1 << 63)
}

/// The terms of a condition's top-level `AND`.
fn conjuncts(n: Option<&Node>) -> Vec<&Node> {
    let mut out = Vec::new();
    let mut stack: Vec<&Node> = n.into_iter().collect();
    while let Some(n) = stack.pop() {
        if n.op == "and" {
            stack.extend(n.left.as_deref());
            stack.extend(n.right.as_deref());
        } else {
            out.push(n);
        }
    }
    out
}

/// The cursors an expression reads, or `None` when it holds a subquery, whose reads the walk
/// does not place.
fn cursors(n: &Node) -> Option<Vec<i64>> {
    if n.select.is_some() {
        return None;
    }
    let mut out = Vec::new();
    if n.op == "column" {
        out.push(n.cursor);
    }
    for child in n.left.iter().chain(n.right.iter()).map(|b| b.as_ref()).chain(n.list.iter()).chain(n.args.iter()) {
        out.extend(cursors(child)?);
    }
    Some(out)
}

/// The type of `a op b` for `+`, `-`, `*`, `/`, `%`: integer stays integer, anything else is real.
fn arithmetic(l: &Ty, r: &Ty) -> Ty {
    match (scalar_name(l), scalar_name(r)) {
        (Some("integer" | "int8"), Some("integer" | "int8")) => Ty::Scalar { name: "integer".into() },
        _ => Ty::Scalar { name: "real".into() },
    }
}

/// Whether a node of this operator sits anywhere in `n`.
fn has_op(n: &Node, op: &str) -> bool {
    n.op == op || n.left.as_deref().is_some_and(|x| has_op(x, op)) || n.right.as_deref().is_some_and(|x| has_op(x, op)) || n.list.iter().any(|x| has_op(x, op)) || n.args.iter().any(|x| has_op(x, op))
}

fn has_aggregate(n: &Node) -> bool {
    if n.op == "function" && n.agg && !n.window {
        return true;
    }
    n.left.as_deref().is_some_and(has_aggregate) || n.right.as_deref().is_some_and(has_aggregate) || n.list.iter().any(has_aggregate) || n.args.iter().any(has_aggregate)
}

/// Whether an expression reads any column, at any depth (a subquery's columns included).
fn reads_column(n: &Node) -> bool {
    if n.op == "column" {
        return true;
    }
    n.left.as_deref().is_some_and(reads_column) || n.right.as_deref().is_some_and(reads_column) || n.list.iter().any(reads_column) || n.args.iter().any(reads_column) || n.select.is_some()
}

/// The type the context an expression stands in gives its operand, when it gives one.
fn is_vector(n: &Option<Box<Node>>) -> bool {
    n.as_deref().is_some_and(|n| n.op == "vector")
}

fn outer_type(ctx: &Ctx) -> Ctx {
    match ctx {
        Ctx::Typed(Some(f)) => Ctx::Typed(Some(f.clone())),
        _ => Ctx::None,
    }
}

/// The argument position of a slot (0 for any other slot).
fn i_of(slot: Position) -> usize {
    match slot {
        Position::Arg(i) => i,
        _ => 0,
    }
}

/// Whether a column's declared type is `BOOLEAN` or `BOOL`, in any case.
fn is_boolean_declared(declared: &str) -> bool {
    let d = declared.trim();
    d.eq_ignore_ascii_case("boolean") || d.eq_ignore_ascii_case("bool")
}

/// SQLite's five affinity rules over a declared type.
pub fn affinity(declared: &str) -> &'static str {
    let d = declared.to_ascii_uppercase();
    if d.contains("INT") {
        "integer"
    } else if d.contains("CHAR") || d.contains("CLOB") || d.contains("TEXT") {
        "text"
    } else if d.contains("BLOB") || d.is_empty() {
        "blob"
    } else if d.contains("REAL") || d.contains("FLOA") || d.contains("DOUB") {
        "real"
    } else {
        "numeric"
    }
}

/// A parameter's context while walking.
#[derive(Clone)]
enum Ctx {
    Typed(Option<Fact>),
    /// A row value's place: element i takes fact i (`(created_at, id) < (:created_at, :id)`).
    Row(Vec<Option<Fact>>),
    Bool,
    None,
}

#[derive(Clone, Copy)]
enum Position {
    Left,
    Right,
    List(usize),
    Arg(usize),
}

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

    #[test]
    fn a_row_assigned_fewer_values_than_columns_is_the_database_s_error() {
        let ddl = vec!["create table t1 (a integer primary key, b, c, d)".to_string(), "create table t2 (w, x, y)".to_string()];
        for sql in ["update t1 set (b, c, d) = (select x, y from t2 where w = a)", "update t1 set (a, a, a, b) = (select 99, 100)"] {
            let a = analyze_ddl(sql, &ddl, &Extras::default()).analysis;
            assert!(!a.diagnostics.is_empty(), "{sql}: {a:?}");
        }
    }

    fn ddl() -> Vec<String> {
        vec![
            "create table users (id integer primary key, name text not null, email text unique, score real, avatar blob, created_at text not null default current_timestamp)".to_string(),
            "create table posts (id integer primary key, user_id integer not null references users(id), title text not null, body text)".to_string(),
        ]
    }

    fn analysis(sql: &str) -> Analysis {
        analyze_ddl(sql, &ddl(), &Extras::default()).analysis
    }

    /// The analysis of `sql`, a statement as the structured pass hands it on, with `names` cast to
    /// `nullable(…)`.
    fn marked(sql: &str, ddl: &[String], names: &[&str]) -> Analysis {
        let names: Vec<String> = names.iter().map(|n| n.to_string()).collect();
        run(sql, &lex::lex(sql, Dialect::Sqlite).unwrap(), ddl, &Extras::default(), &names).analysis
    }

    #[test]
    fn the_facts_are_read_for_every_table_the_statement_names_and_no_with_query() {
        let mut schema = ddl();
        schema.push("create table tags (id integer primary key, post_id integer)".into());
        schema.push("create view titles as select title from posts".into());
        let tables = |sql: &str| {
            let a = analyze_ddl(sql, &schema, &Extras::default()).analysis;
            assert!(a.diagnostics.is_empty(), "{sql}: {:?}", a.diagnostics);
            let mut t = a.tables.expect("the tree names its tables");
            t.read.sort();
            t.read.dedup();
            (t.read, t.write)
        };
        let names = |list: &[&str]| list.iter().map(|s| s.to_string()).collect::<Vec<_>>();
        assert_eq!(tables("select u.id, (select count(*) from posts p where p.user_id = u.id) as n from USERS u where exists (select 1 from tags t where t.id = u.id)"), (names(&["posts", "tags", "users"]), vec![]));
        // A WITH query is no table, and a view is named, not what it reads.
        assert_eq!(tables("with recent as (select user_id from posts) select title from titles join recent on true"), (names(&["posts", "titles"]), vec![]));
        assert_eq!(tables("select value from json_each('[1]')"), (vec![], vec![]));
        assert_eq!(tables("select s.n from (select count(*) as n from posts) s join titles on true"), (names(&["posts", "titles"]), vec![]));
        assert_eq!(tables("update users set score = (with recursive c(n) as (select 1 union all select n + 1 from c where n < 3) select count(*) from c)"), (vec![], names(&["users"])));
        // What an INSERT, an UPDATE and a DELETE write, and the tables they read.
        assert_eq!(tables("insert into tags (post_id) select id from posts"), (names(&["posts"]), names(&["tags"])));
        assert_eq!(tables("update users set name = (select max(title) from posts) where id = 1"), (names(&["posts"]), names(&["users"])));
        assert_eq!(tables("delete from users where id in (select user_id from posts)"), (names(&["posts"]), names(&["users"])));
    }

    #[test]
    fn a_key_declared_on_conflict_replace_is_read_from_sqlite_s_parse_however_the_ddl_spells_it() {
        let replaces = |clause: &str| {
            let ddl = vec![format!("create table p (id integer primary key, email text {clause})")];
            let t = tree::analyze(&ddl, "insert into p (email) values (?1)", "insert into p (email) values (?)", &[], None).expect("the tree parses");
            assert!(t.error.is_none(), "{clause}: {:?}", t.error);
            t.tables["p"].replaces
        };
        for clause in ["unique on conflict replace", "unique on conflict\n  replace", "UNIQUE On Conflict RePlace", "unique on /* the old row goes */ conflict -- and is deleted\n replace"] {
            assert!(replaces(clause), "{clause}");
        }
        // A NOT NULL's REPLACE writes the column's default, and deletes no row.
        for clause in ["unique", "not null on conflict replace default '' unique", "unique on conflict ignore"] {
            assert!(!replaces(clause), "{clause}");
        }
    }

    #[test]
    fn the_schema_replay_reaches_no_file_and_sets_no_pragma() {
        // A row of sqlite_schema may hold more than one statement: SQLite loads the first, and the
        // replay runs the text whole.
        let dir = std::env::temp_dir().join(format!("reylo-sqlite-replay-test-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let (attached, vacuumed) = (dir.join("attached.db"), dir.join("vacuumed.db"));
        let ddl = vec![
            format!("create table t (a integer not null); attach '{}' as x; create table x.y (z)", attached.display()),
            format!("create table u (b); vacuum into '{}'", vacuumed.display()),
            "create table v (c); pragma hard_heap_limit = 1; create table w (d)".to_string(),
        ];
        // What each row made before the refused statement is there.
        let a = analyze_ddl("select a, b, c from t, u, v", &ddl, &Extras::default()).analysis;
        assert!(a.diagnostics.is_empty(), "{:?}", a.diagnostics);
        assert!(!attached.exists() && !vacuumed.exists());
        // A refused statement ends its row's replay, which every statement that fails on what it
        // would have made says, the replay kept from the statement before included.
        for _ in 0..2 {
            let refused = analyze_ddl("select d from w", &ddl, &Extras::default()).analysis;
            let messages: Vec<&str> = refused.diagnostics.iter().map(|d| d.message.as_str()).collect();
            assert_eq!(messages.first(), Some(&"no such table: w"), "{messages:?}");
            assert!(messages.contains(&"The schema replay skipped statement 1: not authorized"), "{messages:?}");
            assert!(messages.contains(&"The schema replay skipped statement 3: not authorized"), "{messages:?}");
        }
        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn the_tree_describes_the_schema_tables_alone_and_no_with_query() {
        // A WITH query's table belongs to the statement, which frees it as the prepare ends,
        // before the serializer lists the tables: read then, a recursive one nested in another,
        // whose memory SQLite had reused, ended the analysis in a crash.
        let described = |sql: &str| {
            let t = tree::analyze(&ddl(), sql, sql, &[], None).expect("the tree parses");
            assert!(t.error.is_none(), "{sql}: {:?}", t.error);
            let mut names = t.tables.into_keys().collect::<Vec<_>>();
            names.sort();
            names
        };
        assert_eq!(described("with recent as (select user_id from posts) select user_id from recent"), ["posts"]);
        assert_eq!(described("with recursive c (n) as (select 1 union all select n + 1 from c where n < 3) select n from c"), Vec::<String>::new());
        assert_eq!(described("with users as (select id from main.users) select id from users"), ["users"]);
        let nested = "with recursive t (n, x, j) as (select 1, 'a', json_array('a') union all select n + 1, null, \
                      (with recursive u (m, y) as (select 1, t.x union all select m + 1, y from u where m < 2) select json_group_array(y) from u) \
                      from t where n < 3) select n, x, j from t";
        assert_eq!(described(nested), Vec::<String>::new());
        assert!(analysis(nested).diagnostics.is_empty());
    }

    #[test]
    fn a_statement_as_deep_as_the_engine_reads_is_typed_and_one_level_past_it_is_an_error_at_the_bound() {
        // From a thread with a small stack, as a host may call from: the embedded SQLite's
        // recursion, the reading of its tree and the walks over it run on the engine's stack.
        let ddl = vec!["create table users (id integer primary key, name text not null, nick text)".to_string()];
        let small = |sql: String| std::thread::scope(|s| std::thread::Builder::new().stack_size(256 << 10).spawn_scoped(s, || analyze_ddl(&sql, &ddl, &Extras::default()).analysis).unwrap().join().unwrap());
        // SQLite's own bound is 1,000; the engine's SQLite takes 350 (`csrc/reylo_sqlite.c`).
        for (shape, n) in [("sum", 350), ("and_or", 348), ("case", 348), ("coalesce", 349), ("subquery", 23)] {
            let at = small(crate::stack::nested(shape, n));
            assert!(at.diagnostics.is_empty() && at.kind == Some(StatementKind::Select), "{shape} at {n}: {:?}", at.diagnostics);
            let past = small(crate::stack::nested(shape, n + 1));
            assert_eq!(past.diagnostics.iter().map(|d| d.message.as_str()).collect::<Vec<_>>(), ["Expression tree is too large (maximum depth 350)"], "{shape} at {}", n + 1);
        }
        // A list does not nest: SQLite's OR is a tree, which its bound counts; an IN list is not.
        let list = (0..5_000).map(|i| i.to_string()).collect::<Vec<_>>().join(", ");
        assert!(small(format!("select id from users where id in ({list})")).diagnostics.is_empty());
    }

    fn col(a: &Analysis, name: &str) -> (String, bool) {
        let c = a.columns.iter().find(|c| c.name == name).unwrap_or_else(|| panic!("no column {name}"));
        (affinity_of(&c.ty).unwrap_or("unknown").to_string(), c.nullable)
    }

    #[test]
    fn returning_reads_a_value_the_statement_wrote_to_the_row() {
        let nullable = |sql: &str| analysis(sql).columns.iter().map(|c| c.nullable).collect::<Vec<_>>();
        // A literal, an expression of written values and a parameter the caller cannot pass NULL
        // for are values; a column the INSERT leaves out takes its default.
        assert_eq!(nullable("insert into users (name, email, score) values ('a', upper(:e), 1.5) returning email, score, avatar, upper(email) as loud"), [false, false, true, false]);
        // A bare parameter written to a column that may hold NULL may be NULL.
        assert_eq!(nullable("insert into users (name, email) values ('a', :e) returning email"), [true]);
        assert_eq!(nullable("update users set email = :e returning email"), [true]);
        // Every row of a VALUES list, and the SELECT that feeds an INSERT, must write a value.
        assert_eq!(nullable("insert into users (name, email) values ('a', 'x'), ('b', null) returning email"), [true]);
        assert_eq!(nullable("insert into users (name, email) values ('a', 'x'), ('b', 'y') returning email"), [false]);
        assert_eq!(nullable("insert into users (name, email) select name, email from users returning email"), [true]);
        assert_eq!(nullable("insert into users (name, email) select name, name from users returning email"), [false]);
        // An UPDATE writes what its SET does, from the row it changes; a column it leaves out keeps
        // what the row held.
        assert_eq!(nullable("update users set email = 'x', score = coalesce(score, 0) where id = 1 returning email, score, avatar"), [false, false, true]);
        assert_eq!(nullable("update users set email = name returning email"), [false]);
        assert_eq!(nullable("update users set email = score returning email"), [true]);
        // An upsert's DO UPDATE must write one too, where a DO NOTHING returns no row.
        assert_eq!(nullable("insert into users (id, name, email) values (1, 'a', 'x') on conflict (id) do update set email = 'y' returning email"), [false]);
        assert_eq!(nullable("insert into users (id, name, email) values (1, 'a', 'x') on conflict (id) do update set name = 'b' returning email"), [true]);
        assert_eq!(nullable("insert into users (id, name, email) values (1, 'a', 'x') on conflict (id) do nothing returning email"), [false]);
        // A BEFORE trigger that fires on the write may change the row, and an AFTER one runs after
        // RETURNING reads it.
        let triggered = |sql: &str, trigger: &str| {
            let mut schema = ddl();
            schema.push(trigger.to_string());
            analyze_ddl(sql, &schema, &Extras::default()).analysis.columns.iter().map(|c| c.nullable).collect::<Vec<_>>()
        };
        assert_eq!(triggered("update users set email = 'x' returning email", "create trigger b before update on users begin select 1; end"), [true]);
        assert_eq!(triggered("insert into users (name, email) values ('a', 'x') on conflict (email) do update set email = 'y' returning email", "create trigger b before update on users begin select 1; end"), [true]);
        assert_eq!(triggered("insert into users (name, email) values ('a', 'x') returning email", "create trigger b before update on users begin select 1; end"), [false]);
        assert_eq!(triggered("insert into users (name, email) values ('a', 'x') returning email", "create trigger a after insert on users begin update users set email = null; end"), [false]);
        // A DELETE returns the row as it was, and a column read elsewhere than the row is the table's.
        assert_eq!(nullable("delete from users where id = 1 returning email"), [true]);
        assert_eq!(nullable("update users set email = 'x' returning (select email from users where id = 2) as other"), [true]);
    }

    fn param(a: &Analysis, name: &str) -> String {
        let p = a.params.iter().find(|p| p.name == name).unwrap_or_else(|| panic!("no param {name}"));
        affinity_of(&p.ty).unwrap_or("unknown").to_string()
    }

    #[test]
    fn the_full_text_functions_are_typed() {
        // Measured on SQLite 3.53.4 over rows with a NULL in each column: `bm25` is a real on
        // every row (0 with no MATCH) and NULL with an infinite weight, `highlight` and FTS5's `snippet` are NULL where their
        // column is, and FTS4's `offsets` and `matchinfo` answer every row.
        let mut schema = ddl();
        schema.push("CREATE VIRTUAL TABLE docs USING fts5(title, body)".into());
        schema.push("CREATE VIRTUAL TABLE notes USING fts4(body)".into());
        let a = |sql: &str| {
            let a = analyze_ddl(sql, &schema, &Extras::default()).analysis;
            assert!(a.diagnostics.is_empty(), "{sql}: {:?}", a.diagnostics);
            a
        };
        let fts5 = a("select rowid as id, bm25(docs) as rank, bm25(docs, :w, 1.0) as weighted, highlight(docs, :col, :open, '</b>') as hit, \
                      snippet(docs, -1, '<b>', '</b>', '…', 8) as excerpt from docs where docs match :q order by rank");
        assert_eq!(col(&fts5, "rank"), ("real".into(), false));
        assert_eq!(col(&fts5, "weighted"), ("real".into(), true));
        assert_eq!(col(&fts5, "hit"), ("text".into(), true));
        assert_eq!(col(&fts5, "excerpt"), ("text".into(), true));
        assert_eq!((param(&fts5, "w"), param(&fts5, "col"), param(&fts5, "open"), param(&fts5, "q")), ("real".into(), "integer".into(), "text".into(), "text".into()));
        let fts4 = a("select offsets(notes) as o, matchinfo(notes) as m, snippet(notes) as s from notes where notes match :q");
        assert_eq!(col(&fts4, "o"), ("text".into(), false));
        assert_eq!(col(&fts4, "m"), ("blob".into(), false));
        assert_eq!(col(&fts4, "s"), ("text".into(), true));
        // Inside built JSON, each nests as the value it is.
        let built = a("select json_object('hit', highlight(docs, 0, '<b>', '</b>'), 'rank', bm25(docs)) as j from docs where docs match :q");
        assert_eq!(shown(&built), "j: { hit: string | null; rank: number }");
    }

    #[test]
    fn a_built_in_is_non_null_only_where_sqlite_never_answers_null_for_non_null_arguments() {
        // Every argument below is non-null; each NULL noted is what SQLite 3.53 answers.
        let ddl = vec![
            "create table o (id integer primary key, placed_at text not null, x real not null, n integer not null, b blob not null, v any not null, doc text not null, fmt text not null) strict".to_string(),
            "create table loose (id integer primary key, num numeric not null)".to_string(),
        ];
        let typed = |expr: &str| {
            let a = analyze_ddl(&format!("select {expr} as v from o, loose"), &ddl, &Extras::default()).analysis;
            assert!(a.diagnostics.is_empty(), "{expr}: {:?}", a.diagnostics);
            col(&a, "v")
        };
        let nullable = |expr: &str| typed(expr).1;
        // A time value SQLite cannot read, a number outside its range, a modifier that fails.
        for expr in [
            "date(placed_at)", "time(placed_at)", "datetime(placed_at)", "julianday(placed_at)", "unixepoch(placed_at)", "strftime('%Y', placed_at)",
            "date(placed_at, '+1 day')", "timediff(placed_at, 'now')", "date(n)", "date(x, 'unixepoch')", "date('2024-01-01')", "date(:d)",
            "date('now', 'weekday 7')", "date('now', 'unixepoch')", "date('now', 'julianday')", "date('now', '+8000 years')", "date('now', '+1 day ')",
            "date('now', '+600 years', '+600 years')", "date('now', fmt)", "date('now ')", "strftime('%Q', 'now')", "strftime('%Y%')", "strftime(fmt)",
            "date(5373485)", "datetime(1e18, 'unixepoch')", "date(0, '-1 day')", "date(1700000000, 'unixepoch', 'unixepoch')", "date(1, 'auto')", "date(-1)",
        ] {
            assert!(nullable(expr), "{expr}");
        }
        // The current time with modifiers that cannot fail on it.
        for expr in [
            "date()", "time()", "datetime()", "julianday()", "unixepoch()", "date('now')", "date('NOW')", "datetime('now', 'localtime')", "datetime('now', 'utc')",
            "date('now', 'start of month', '+1 month', '-1 day')", "date('now', 'weekday 0')", "datetime('now', '-7 days', '+1.5 hours', '+30 MINUTES')",
            "date('now', 'subsec')", "strftime('%Y-%m-%d %H:%M:%f %% %j', 'now')", "strftime('%s')", "strftime('')", "timediff('now', 'now')",
            "strftime('%Y', current_timestamp)", "date(current_date, '+1 month')", "datetime(0, 'unixepoch')", "date(2460000.5)", "date(1700000000, 'unixepoch', 'start of day', '+1 day')",
        ] {
            assert!(!nullable(expr), "{expr}");
        }
        assert_eq!(typed("unixepoch()"), ("integer".into(), false));
        assert_eq!(typed("unixepoch('now', 'subsec')"), ("real".into(), false));
        assert_eq!(typed("unixepoch('now', fmt)"), ("real".into(), true));
        // Outside a function's domain (`sqrt(-1)`, `ln(0)`, `acos(2)`, `mod(1, 0)`, `pow(-1, 0.5)`)
        // or at an infinity (`sin(1e999)`).
        for f in ["acos(x)", "acosh(x)", "asin(x)", "atanh(x)", "cos(x)", "sin(x)", "tan(x)", "ln(x)", "log(x)", "log(2, x)", "log10(x)", "log2(x)", "mod(n, x)", "pow(x, 0.5)", "power(x, n)", "sqrt(x)", "sqrt(4)"] {
            assert_eq!(typed(f), ("real".into(), true), "{f}");
        }
        // Defined on every number; NULL for an argument that is no number (`sign('')`).
        for f in ["atan(x)", "atan2(x, n)", "asinh(x)", "sinh(x)", "cosh(n)", "tanh(x)", "exp(x)", "degrees(x)", "radians(n)", "ceil(x)", "ceiling(x)", "floor(n)", "trunc(x)", "pi()"] {
            assert_eq!(typed(f), ("real".into(), false), "{f}");
        }
        assert_eq!(typed("sign(x)"), ("integer".into(), false));
        for f in ["sign(placed_at)", "sign(v)", "sign(num)", "ceil(placed_at)", "floor(b)", "exp(v)", "atan2(x, placed_at)", "sinh(num)"] {
            assert!(nullable(f), "{f}");
        }
        // An empty format, or one that stops at a conversion SQLite does not know (`printf('%T')`).
        for f in ["printf(fmt, n)", "printf('', n)", "printf('%T')", "printf('%s', placed_at)", "format('%d%d', n, n)", "printf('%T x')", "printf('%5-dx', n)", "printf('%ls', n)", "printf('%.*s', n, placed_at)", "printf('%-')"] {
            assert!(nullable(f), "{f}");
        }
        for f in ["printf('x%s', null)", "format('-%d', n)", "printf('%%')", "printf('%')", "printf('%s-%d', placed_at, n)", "printf('%5.2f%%', x)", "printf('%-10s|', placed_at)", "printf('%lld:', n)", "printf('%*.*s.', n, n, placed_at)", "printf('a%T')"] {
            assert!(!nullable(f), "{f}");
        }
        // The slice of an empty blob is NULL, and of any blob a blob.
        assert_eq!(typed("substr(placed_at, 2)"), ("text".into(), false));
        assert_eq!(typed("substr(n, 2, 1)"), ("text".into(), false));
        assert_eq!(typed("substr(:s, 2)"), ("text".into(), false));
        assert_eq!(typed("substr(b, 2)"), ("blob".into(), true));
        assert_eq!(typed("substring(v, 1, 2)"), ("unknown".into(), true));
        // A path that finds nothing, and `json_remove(j, '$')`.
        for f in ["json_type(doc, '$.a')", "json_array_length(doc, '$.a')", "json_remove(doc, '$')", "json_remove(doc, '$.a')"] {
            assert!(nullable(f), "{f}");
        }
        for f in ["json_type(doc)", "json_array_length(doc)", "json_remove(doc)", "json(doc)", "json_set(doc, '$.a', null)", "json_patch(doc, doc)", "json_valid(doc)"] {
            assert!(!nullable(f), "{f}");
        }
        assert_eq!(typed("jsonb(doc)"), ("blob".into(), false));
        assert_eq!(typed("(select jsonb_group_array(id) from o)"), ("blob".into(), false));
        // `iif` with an even count of arguments has no ELSE: NULL where no condition holds.
        assert_eq!(typed("iif(n > 0, placed_at)"), ("text".into(), true));
        assert_eq!(typed("iif(n > 0, placed_at, n > 1, doc)"), ("text".into(), true));
        assert_eq!(typed("iif(n > 0, placed_at, n > 1, doc, fmt)"), ("text".into(), false));
        assert_eq!(typed("if(n > 0, x, n > 1, x, 1.5)"), ("real".into(), false));
        // A condition takes a truth value, which SQLite reads as an integer; a value the other values' type.
        assert_eq!(param(&analyze_ddl("select id from o where x = iif(n > 0, 1.5, :c, 2.5, :e)", &ddl, &Extras::default()).analysis, "c"), "integer");
        assert_eq!(param(&analyze_ddl("select id from o where x = iif(n > 0, 1.5, :c, 2.5, :e)", &ddl, &Extras::default()).analysis, "e"), "real");
        // `total` of a `1e999` and a `-1e999` is NaN, which SQLite gives as NULL; of integers never.
        assert_eq!(typed("(select total(x) from o)"), ("real".into(), true));
        assert_eq!(typed("(select total(n) from o)"), ("real".into(), false));
        assert_eq!(typed("total(x) over ()"), ("real".into(), true));
        // What never gives NULL for non-null arguments.
        for f in [
            "abs(x)", "round(x, 2)", "length(b)", "instr(placed_at, '')", "octet_length(b)", "upper(b)", "lower(placed_at)", "trim(placed_at, '')", "replace(placed_at, '', 'x')",
            "char(n)", "hex(b)", "quote(v)", "typeof(v)", "concat(placed_at, null)", "like(placed_at, 'a%')", "glob('*', placed_at)", "json_array(n)", "json_object('a', n)", "json_quote(v)",
        ] {
            assert!(!nullable(f), "{f}");
        }
        assert!(nullable("unicode(placed_at)"));
    }

    #[test]
    fn the_postgres_nullability_rules_hold_on_sqlite() {
        let nullable_param = |sql: &str, name: &str| analysis(sql).params.iter().find(|p| p.name == name).is_some_and(|p| p.nullable);
        // A parameter cast to `nullable(…)` takes NULL, through the WITH query that selects it
        // once too; any other is a value, one the statement coalesces or tests for NULL included.
        let marked_param = |sql: &str, name: &str| marked(sql, &ddl(), &[name]).params.iter().find(|p| p.name == name).is_some_and(|p| p.nullable);
        assert!(marked_param("with input as (select cast(:p as integer) as p) select id from users, input where (input.p is null or score > input.p)", "p"));
        assert!(!nullable_param("with input as (select cast(:p as integer) as p) select id from users, input where score = coalesce(input.p, score)", "p"));
        assert!(!nullable_param("with input as (select :p as p) select id from users, input i where score = ifnull(p, score) and score > i.p", "p"));
        assert!(!nullable_param("select id from users, (select :p as p) s where coalesce(s.p, score) = score", "p"));
        assert!(!nullable_param("with input as (select :p as p) select id from users, input where score = coalesce(input.p, score)", "p"));
        assert!(!nullable_param("with input as (select :p as p) select id from users, input where score > input.p", "p"));
        assert!(!nullable_param("with input as (select :p as p union all select 1) select id from users, input where coalesce(input.p, 0) = 0", "p"));
        assert!(!nullable_param("with input as (select cast(:p as integer) as p) select id from users, input where (input.p is null or score > input.p)", "p"));
        assert!(!nullable_param("select id from users where cast(:p as integer) is null", "p"));
        assert!(!nullable_param("select id from users where :p is not null", "p"));
        assert!(!nullable_param("select id from users where email is :p", "p"));
        assert!(!nullable_param("select id from users where :p is not email", "p"));
        assert!(!nullable_param("select id from users where :p isnull", "p"));
        assert!(!nullable_param("select id from users where score = coalesce(score, :p)", "p"));
        let sql = "select id from users where (:p is null or score > :p)";
        let repeated = analysis(sql);
        assert_eq!(repeated.diagnostics.iter().map(|d| (d.code, d.start, d.length)).collect::<Vec<_>>(), [(3, sql.rfind(":p").unwrap(), 2)]);
        assert!(!nullable_param("select coalesce(:s, 0) as x", "s"));
        assert!(!nullable_param("select id from users where score > :p", "p"));
        assert_eq!(col(&analysis("select upper(:s) as u"), "u"), ("text".into(), false));
        // A strict WHERE narrows the column it tests, and reduces the outer join of its item.
        assert_eq!(col(&analysis("select email from users where email is not null"), "email"), ("text".into(), false));
        assert_eq!(col(&analysis("select email from users where lower(email) = :e or email like 'a%'"), "email").1, false);
        assert_eq!(col(&analysis("select email from users where email like 'a%' or id = 1"), "email").1, true);
        assert_eq!(col(&analysis("select email from users where lower(email) = :e and email like 'a%'"), "email").1, false);
        let reduced = analysis("select p.title, u.name from posts p left join users u on u.id = p.user_id where u.email = :e");
        assert_eq!(col(&reduced, "name"), ("text".into(), false));
        assert_eq!(col(&analysis("select p.title, u.name from posts p left join users u on u.id = p.user_id"), "name"), ("text".into(), true));
        // An ON term is not a WHERE test: the posts that meet no user still have NULL there.
        // Nor is an inner join's, for the rows a RIGHT JOIN after it null-extends.
        let right = analysis("select p.title, u.name from posts p join users u on u.email is not null right join posts q on q.id = 0");
        assert_eq!((col(&right, "title").1, col(&right, "name").1), (true, true));
        assert_eq!(col(&analysis("select u.email from posts p join users u on u.email is not null"), "email").1, false);
        assert_eq!(col(&analysis("select p.title, u.name from posts p left join users u on u.id = p.user_id and u.email = :e"), "name"), ("text".into(), true));
        // Under a plain GROUP BY no group is empty.
        let grouped = analysis("select user_id, max(title) as t, min(id) as m, group_concat(title) as g from posts group by user_id");
        assert_eq!((col(&grouped, "t").1, col(&grouped, "m").1, col(&grouped, "g").1), (false, false, false));
        assert!(col(&analysis("select max(title) as t from posts"), "t").1);
        // `concat` skips NULLs; `concat_ws` is NULL only for a NULL separator.
        let concat = analysis("select concat(email, 'x') as c, concat_ws(',', email) as w, concat_ws(email, 'a') as n from users");
        assert_eq!((col(&concat, "c").1, col(&concat, "w").1, col(&concat, "n").1), (false, false, true));
    }

    #[test]
    fn a_cast_parameter_is_its_casts_type_and_a_bare_one_its_columns() {
        // A `:name::type` cast compiles to `CAST(? AS type)`, and `::json` to `json(?)`: the
        // parameter is the cast's type and takes no NULL, written whole or not. A bare one written whole (an INSERT's values, every row of a
        // VALUES list, an UPDATE's or an upsert's SET, a row value's elements) is as nullable as
        // its column; a column a CHECK refuses NULL in, by a conjunct `col is not null`, is not.
        // Neither takes NULL coalesced or tested for NULL; either takes it cast to `nullable(…)`.
        let ddl = vec!["create table users (id integer primary key, name text not null, email text unique, score real, n integer, doc text, meta text not null default '{}', nick text check (nick is not null), code text check (length(code) > 0 and code is not null), tag text check (tag <> '')) strict".to_string()];
        let types = |sql: &str| {
            let a = analyze_ddl(sql, &ddl, &Extras::default()).analysis;
            assert!(a.diagnostics.is_empty(), "{sql}: {:?}", a.diagnostics);
            a.params.iter().map(|p| format!("{}{}", p.name, if p.nullable { "?" } else { "" })).collect::<Vec<_>>().join(" ")
        };
        for (sql, want) in [
            ("insert into users (name, email) values (:name, :email) on conflict (email) do update set name = excluded.name returning id", "name email?"),
            ("insert into users (name, email) values (CAST(:name AS TEXT), CAST(:email AS TEXT)) on conflict (email) do update set name = excluded.name returning id", "name email"),
            ("insert into users (name, email, score, n, doc, meta) values (:name, :email, :score, :n, :doc, :meta)", "name email? score? n? doc? meta"),
            ("insert into users (name, email, score, n, doc, meta) values (CAST(:name AS TEXT), CAST(:email AS TEXT), CAST(:score AS NUMERIC), CAST(:n AS INTEGER), json(:doc), jsonb(:meta))", "name email score n doc meta"),
            ("insert into users (name, email) values (:a, :b), (:c, CAST(:d AS TEXT))", "a b? c d"),
            ("update users set email = :email, name = :name, score = :score, n = CAST(:n AS INTEGER), doc = json(:doc) where id = :id", "email? name score? n doc id"),
            ("update users set (name, email) = (:name, :email) where id = :id", "name email? id"),
            ("update users set (name, email) = (CAST(:name AS TEXT), CAST(:email AS TEXT)) where id = CAST(:id AS INTEGER)", "name email id"),
            ("insert into users (name, email) values ('a', 'b') on conflict (email) do update set email = :e, n = CAST(:n AS INTEGER), name = :name", "e? n name"),
            ("update users set email = CAST(CAST(:e AS INTEGER) AS TEXT), meta = json(:m) where id = 1", "e m"),
            ("insert into users (name, nick, code, tag) values (:name, :nick, :code, :tag)", "name nick code tag?"),
            ("update users set nick = :nick, code = :code, tag = :tag where id = :id", "nick code tag? id"),
            ("update users set n = coalesce(CAST(:n AS INTEGER), n), doc = ifnull(json(:doc), doc), score = coalesce(:s, score) where id = CAST(:id AS INTEGER)", "n doc s id"),
            ("select id from users where (json(:doc) is null or doc = json(:d)) and :x is not null", "doc d x"),
            ("insert into users (name, email) select CAST(:name AS TEXT), CAST(:email AS TEXT)", "name email"),
            ("insert into users (name, email) select :name, :email", "name email?"),
        ] {
            assert_eq!(types(sql), want, "{sql}");
        }
        // Cast to `nullable(…)`, a parameter takes NULL, written whole or not, bare (a typed JSON
        // one is) or under its cast; written whole to a column that refuses NULL, by its NOT NULL
        // or a CHECK, it is an error at the parameter.
        let ddl: Vec<String> = ddl.iter().map(|s| s.to_string()).collect();
        let sql = "insert into users (name, email, nick, doc, meta) values (CAST(:name AS TEXT), CAST(:email AS TEXT), CAST(:nick AS TEXT), :doc, json(:meta))";
        let a = marked(sql, &ddl, &["name", "email", "nick", "doc", "meta"]);
        assert_eq!(a.params.iter().map(|p| p.nullable).collect::<Vec<_>>(), [true; 5]);
        let said = |p: &str, column: &str| format!("The parameter {p} is cast to nullable(…), but it is written to users.{column}, which refuses null: cast it to its type alone.");
        assert_eq!(a.diagnostics.iter().map(|d| (&sql[d.start..d.start + d.length], d.message.clone())).collect::<Vec<_>>(), [(":name", said(":name", "name")), (":nick", said(":nick", "nick")), (":meta", said(":meta", "meta"))]);
        // Written whole by the one SELECT that feeds the INSERT, as a VALUES item is.
        let sql = "insert into users (name, email) select CAST(:name AS TEXT), CAST(:email AS TEXT)";
        let a = marked(sql, &ddl, &["name", "email"]);
        assert_eq!(a.diagnostics.iter().map(|d| (&sql[d.start..d.start + d.length], d.message.clone())).collect::<Vec<_>>(), [(":name", said(":name", "name"))]);
        let a = marked("update users set email = CAST(:e AS TEXT), n = coalesce(CAST(:n AS INTEGER), n) where id = 1", &ddl, &["e", "n"]);
        assert!(a.diagnostics.is_empty(), "{:?}", a.diagnostics);
        assert_eq!(a.params.iter().map(|p| p.nullable).collect::<Vec<_>>(), [true, true]);
    }

    #[test]
    fn a_parameter_takes_the_type_its_call_case_or_compound_stands_in() {
        assert_eq!(param(&analysis("select id from users where name = coalesce(:a, :b)"), "a"), "text");
        assert_eq!(param(&analysis("select id from users where name = coalesce(:a, :b)"), "b"), "text");
        assert_eq!(param(&analysis("select id from users where name = case when id > 1 then :a else :b end"), "a"), "text");
        assert_eq!(param(&analysis("select id from users where name = iif(id > 1, :a, 'x')"), "a"), "text");
        assert_eq!(param(&analysis("select case :kind when 'a' then 1 else 2 end as k from users"), "kind"), "text");
        assert_eq!(param(&analysis("select name from users union all select :x"), "x"), "text");
        assert_eq!(param(&analysis("select :x union all select name from users"), "x"), "text");
        // A call whose result is not an argument's gives none of its own context.
        assert_eq!(param(&analysis("select id from users where name = printf(:f, 1)"), "f"), "text");
        assert_eq!(param(&analysis("select :x as v"), "x"), "unknown");
    }

    #[test]
    fn an_outer_joins_on_term_pins_its_right_side_but_groups_nothing() {
        // SQLite moves the ON terms into the WHERE: `u.id = :id` restricts which user a post
        // meets, and the posts that meet none have NULL there, a second group.
        assert_eq!(analysis("select u.name, count(*) as n from posts p left join users u on u.id = :id and u.id = p.user_id group by u.name").cardinality, "many");
        assert_eq!(analysis("select u.name, count(*) as n from posts p left join users u on u.id = p.user_id where u.id = :id group by u.name").cardinality, "at_most_one");
        // The ON term still pins the right side against a pinned left one.
        assert_eq!(analysis("select p.title, u.name from posts p left join users u on u.id = :u where p.id = :id").cardinality, "at_most_one");
    }

    #[test]
    fn an_insert_returns_no_row_where_something_can_skip_it() {
        let count = |sql: &str, extra: &[&str]| {
            let mut schema = ddl();
            schema.extend(extra.iter().map(|s| s.to_string()));
            analyze_ddl(sql, &schema, &Extras::default()).analysis.cardinality
        };
        let insert = "insert into users (name) values (:n) returning id";
        assert_eq!(count(insert, &[]), "one");
        // A BEFORE trigger's RAISE(IGNORE) skips the row; an AFTER trigger cannot.
        assert_eq!(count(insert, &["create trigger skip before insert on users begin select raise(ignore) where new.name = 'x'; end"]), "at_most_one");
        assert_eq!(count(insert, &["create trigger untimed insert on users begin select 1; end"]), "at_most_one", "BEFORE is the default");
        assert_eq!(count(insert, &["create trigger later after insert on users begin select 1; end"]), "one");
        // `DO UPDATE … WHERE` leaves a conflicting row alone and returns nothing for it.
        assert_eq!(count("insert into users (id, name) values (:id, :n) on conflict (id) do update set name = excluded.name where users.score > 1 returning id", &[]), "at_most_one");
        assert_eq!(count("insert into users (id, name) values (:id, :n) on conflict (id) do update set name = excluded.name returning id", &[]), "one");
        // A later ON CONFLICT clause is tried as the first is.
        assert_eq!(count("insert into users (id, name) values (:id, :n) on conflict (id) do update set name = excluded.name on conflict do nothing returning id", &[]), "at_most_one");
        // A constraint declared ON CONFLICT IGNORE skips the row, unless the statement's own OR
        // clause says otherwise.
        let declared = |sql: &str, table: &str| {
            let schema = vec![table.to_string()];
            analyze_ddl(sql, &schema, &Extras::default()).analysis.cardinality
        };
        assert_eq!(declared("insert into t (k) values (:k) returning id", "create table t (id integer primary key, k text unique on conflict ignore)"), "at_most_one");
        assert_eq!(declared("insert into t (k) values (:k) returning id", "create table t (id integer primary key, k text not null on conflict ignore)"), "at_most_one");
        assert_eq!(declared("insert into t (id) values (:id) returning id", "create table t (id integer primary key on conflict ignore, k text)"), "at_most_one");
        assert_eq!(declared("insert into t (a, b) values (:a, :b) returning a", "create table t (a integer, b integer, unique (a, b) on conflict ignore)"), "at_most_one");
        assert_eq!(declared("insert or abort into t (k) values (:k) returning id", "create table t (id integer primary key, k text unique on conflict ignore)"), "one");
        assert_eq!(declared("insert into t (k) values (:k) returning id", "create table t (id integer primary key, k text unique on conflict replace)"), "one");
    }

    #[test]
    fn a_write_to_a_view_goes_through_its_instead_of_trigger() {
        let schema = vec![
            "create table w (id integer primary key, k text not null, v integer)".to_string(),
            "create view wv as select id, k, v from w".to_string(),
            "create trigger wv_insert instead of insert on wv when lookup(new.k) begin insert into w (k, v) values (new.k, new.v); end".to_string(),
            "create trigger \"wv update\" instead of update of v on main.wv begin update w set v = new.v where id = old.id; end".to_string(),
        ];
        let analysis = |sql: &str| analyze_ddl(sql, &schema, &Extras::default()).analysis;
        let insert = analysis("insert into wv (k, v) values (42, 9) returning k");
        assert!(insert.diagnostics.is_empty(), "{:?}", insert.diagnostics);
        // Returned as written, with no affinity: the INTEGER 42 for a column of TEXT affinity.
        assert_eq!(col(&insert, "k"), ("unknown".into(), true));
        assert!(analysis("update wv set v = :v where id = :id").diagnostics.is_empty());
        // The trigger fires on an update of `v` alone: SQLite refuses an update of `k`, and so does
        // its type check. A view with no trigger for the write stays read-only.
        assert_eq!(analysis("update wv set k = :k").diagnostics.first().map(|d| d.message.as_str()), Some("cannot modify wv because it is a view"));
        assert_eq!(analysis("delete from wv").diagnostics.first().map(|d| d.message.as_str()), Some("cannot modify wv because it is a view"));
        assert_eq!(instead_of_stub("create trigger t before insert on w begin select 1; end"), None);
        assert_eq!(instead_of_stub(&schema[3]).as_deref(), Some("create trigger \"wv update\" instead of update of v on main.wv\nBEGIN SELECT 1; END"));
        assert_eq!(instead_of_stub("CREATE TRIGGER x INSTEAD OF DELETE ON v -- on y\n BEGIN SELECT 1; END").as_deref(), Some("CREATE TRIGGER x INSTEAD OF DELETE ON v -- on y\nBEGIN SELECT 1; END"));
    }

    #[test]
    fn a_unique_key_bounds_only_a_comparison_under_its_own_collation() {
        let count = |sql: &str| {
            let mut schema = ddl();
            schema.push("create table c (id integer primary key, e text collate nocase, b text unique)".into());
            schema.push("create unique index c_e on c (e collate binary)".into());
            analyze_ddl(sql, &schema, &Extras::default()).analysis.cardinality
        };
        // `e` compares under NOCASE, and its unique index tells 'A' from 'a'.
        assert_eq!(count("select id from c where e = :e"), "many");
        assert_eq!(count("select id from c where b = :b"), "at_most_one");
        assert_eq!(count("select id from c where b = :b collate nocase"), "many");
        assert_eq!(count("select e from c where id = :id"), "at_most_one");
    }

    #[test]
    fn a_function_the_host_registers_over_a_built_in_proves_nothing_strict() {
        let lower = Extras { total: vec![TotalFunction { name: "lower".into(), arity: 1, returns: Affinity::Text }], host: None };
        let nullable = |extras: &Extras| col(&analyze_ddl("select email from users where lower(email) = :e", &ddl(), extras).analysis, "email").1;
        assert!(!nullable(&Extras::default()));
        assert!(nullable(&lower));
    }

    #[test]
    fn a_strict_column_and_a_rowid_hold_their_declared_type_alone() {
        let ddl = [
            "create table s (id integer primary key, n int not null, x real, t text, b blob, a any, g integer generated always as (n * 2) virtual) strict",
            "create table loose (id integer primary key, n integer not null, t text)",
            "create table desc_key (a integer primary key desc)",
        ]
        .map(String::from);
        let kinds = |sql: &str| {
            let analysis = analyze_ddl(sql, &ddl, &Extras::default()).analysis;
            analysis.columns.iter().map(|c| serde_json::to_value(&c.ty).unwrap()["kind"].as_str().unwrap().to_string()).collect::<Vec<_>>().join(" ")
        };
        assert_eq!(kinds("select id, n, x, t, b, a from s"), "integer integer float text bytes unknown");
        assert_eq!(kinds("select id, n, t from loose"), "integer union union");
        assert_eq!(kinds("select a from desc_key"), "union");
        // A generated column keeps its affinity's union: SQLite before 3.51 never checks it.
        assert_eq!(kinds("select g from s"), "union");
        // Through subqueries, views and every arm of a compound, and no further.
        assert_eq!(kinds("select n, t from (select n, t from s)"), "integer text");
        assert_eq!(kinds("select n from s union all select id from loose"), "integer");
        assert_eq!(kinds("select n from s union all select n from loose"), "union");
        assert_eq!(kinds("select n from s union all values (1)"), "union");
    }

    /// A schema as libSQL 0.10.0 writes it into `sqlite_schema` for a vector column and its
    /// index: its own shadow tables, then the index on the marker function.
    fn libsql_schema() -> Vec<String> {
        [
            "CREATE TABLE docs (id integer primary key, title text not null, emb F32_BLOB(3))",
            "CREATE TABLE libsql_vector_meta_shadow ( name TEXT PRIMARY KEY, metadata BLOB ) WITHOUT ROWID",
            "CREATE TABLE docs_emb_shadow (index_key  INTEGER , data BLOB, PRIMARY KEY (index_key))",
            "CREATE INDEX docs_emb_shadow_idx ON docs_emb_shadow (index_key)",
            "CREATE INDEX docs_emb on docs (libsql_vector_idx(emb))",
            "CREATE TABLE words (k text primary key, e F32_BLOB(2)) WITHOUT ROWID",
            "CREATE INDEX words_e on words (libsql_vector_idx(e, 'metric=l2'))",
        ]
        .map(String::from)
        .to_vec()
    }

    /// The SQLite that reads the file lists none of libSQL's functions, as the engine's program's does.
    fn sqlite_host() -> Extras {
        Extras { total: vec![], host: Some(["lower", "upper", "length", "count"].map(|name| HostFunction { name: name.into(), arity: -1, kind: 's' }).to_vec()) }
    }

    #[test]
    fn the_sqlean_functions_turso_cloud_loads_are_typed_whatever_the_host_lists() {
        // Measured on libSQL 0.10.0 with the sqlean extensions libsql-ffi builds.
        let ddl = vec!["create table people (id integer primary key, name text not null, nick text, score real not null) strict".to_string()];
        for extras in [Extras::default(), sqlite_host()] {
            let a = |sql: &str| {
                let a = analyze_ddl(sql, &ddl, &extras).analysis;
                assert!(a.diagnostics.is_empty(), "{sql}: {:?}", a.diagnostics);
                a
            };
            let fresh = a("select uuid4() as a, uuid7() as b, gen_random_uuid() as c, uuid_str(:id) as d, uuid_blob(:raw) as e, uuid7_timestamp_ms(:at) as f");
            assert_eq!(["a", "b", "c", "d", "e", "f"].map(|c| col(&fresh, c)), [("text", false), ("text", false), ("text", false), ("text", true), ("blob", true), ("integer", true)].map(|(t, n)| (t.to_string(), n)));
            assert_eq!(param(&fresh, "id"), "text");
            let digest = a("select md5(name) as a, sha256(nick) as b, crypto_sha1(name) as c, encode(md5(name), 'hex') as d, decode(nick, 'base64') as e from people");
            assert_eq!(["a", "b", "c", "d", "e"].map(|c| col(&digest, c)), [("blob", false), ("blob", true), ("blob", false), ("text", false), ("blob", true)].map(|(t, n)| (t.to_string(), n)));
            let fuzzy = a("select levenshtein(name, :q) as a, fuzzy_leven(nick, :q2) as b, jaro_winkler(name, :q3) as c, caverphone(nick) as d, translit(nick) as e, script_code(name) as f from people");
            assert_eq!(["a", "b", "c", "d", "e", "f"].map(|c| col(&fuzzy, c)), [("integer", false), ("integer", false), ("real", false), ("text", true), ("text", false), ("integer", false)].map(|(t, n)| (t.to_string(), n)));
            assert_eq!(param(&fuzzy, "q"), "text");
            let text = a("select left(name, :n) as a, lpad(nick, 5) as b, split_part(name, ',', 2) as c, text_title(name) as d, strpos(name, 'a') as e, char_length(nick) as f, text_concat(name, nick) as g, text_join(',', name, nick) as h from people");
            assert_eq!(["a", "b", "c", "d", "e", "f", "g", "h"].map(|c| col(&text, c)), [("text", false), ("text", true), ("text", false), ("text", false), ("integer", false), ("integer", true), ("text", false), ("text", false)].map(|(t, n)| (t.to_string(), n)));
            assert_eq!(param(&text, "n"), "integer");
            // sqlean's tests answer 1 or 0.
            let tests = a("select starts_with(name, 'a') as a, text_contains(name, :part) as b, regexp_like(nick, '^a') as c from people");
            assert_eq!(["a", "b", "c"].map(|c| col(&tests, c)), [("bool", false), ("bool", false), ("bool", false)].map(|(t, n)| (t.to_string(), n)));
            // `regexp_replace` hands back a value it changes nothing in as it was: an integer stays one.
            let re = a("select regexp_substr(name, 'a+') as a, regexp_capture(name, 'b(a+)', 1) as b, regexp_replace(name, 'a', 'b') as c, regexp_replace(nick, 'a', 'b') as d, regexp_replace(id, 'z', 'x') as e from people where name regexp 'a'");
            assert_eq!(["a", "b", "c", "d", "e"].map(|c| col(&re, c)), [("text", true), ("text", true), ("text", false), ("text", true), ("unknown", false)].map(|(t, n)| (t.to_string(), n)));
            // An alias takes the parameter types of the function it stands for.
            let aliased = a("select math_floor(:x) as a, fuzzy_soundex(:s) as b, stats_perc(score, :p) as c from people");
            assert_eq!((param(&aliased, "x"), param(&aliased, "s"), param(&aliased, "p")), ("real".into(), "text".into(), "real".into()));
            // `math_floor` is `floor`, read by SQLite's own rules, which sqlean's keep.
            let math = a("select math_floor(score) as a, math_sqrt(score) as b, math_pi() as c from people");
            assert_eq!(["a", "b", "c"].map(|c| col(&math, c)), [("real", false), ("real", true), ("real", false)].map(|(t, n)| (t.to_string(), n)));
            let stats = a("select stddev(score) as a, stats_p90(score) as b, variance(score) as c from people group by name");
            assert_eq!(["a", "b", "c"].map(|c| col(&stats, c)), [("real", true), ("real", true), ("real", true)].map(|(t, n)| (t.to_string(), n)));
            let series = a("select value from generate_series(1, :stop)");
            assert_eq!((col(&series, "value"), param(&series, "stop")), (("integer".to_string(), false), "integer".to_string()));
            assert_eq!(col(&a("select value from stats_seq(1, 3)"), "value"), ("integer".to_string(), false));
            assert!(!analyze_ddl("select value from generate_series", &ddl, &extras).analysis.diagnostics.is_empty());
        }
        // Names this build has of its own keep its function, typed for sqlean's too: `soundex(NULL)`
        // is NULL on Turso Cloud, and `median` a nullable real on both.
        let own = analyze_ddl("select soundex(nick) as a, soundex(name) as b, median(score) as c from people group by name", &ddl, &Extras::default()).analysis;
        assert_eq!(["a", "b", "c"].map(|c| col(&own, c)), [("text", true), ("text", false), ("real", true)].map(|(t, n)| (t.to_string(), n)));
    }

    #[test]
    fn libsql_s_vector_functions_are_typed_whatever_the_host_lists() {
        for extras in [Extras::default(), sqlite_host()] {
            let a = |sql: &str| {
                let a = analyze_ddl(sql, &libsql_schema(), &extras).analysis;
                assert!(a.diagnostics.is_empty(), "{sql}: {:?}", a.diagnostics);
                a
            };
            // The schema replays, its vector index and libSQL's tables with it.
            let plain = a("select id, title from docs where id = :id");
            assert_eq!((col(&plain, "id"), col(&plain, "title")), (("integer".into(), false), ("text".into(), false)));
            // A vector column outside a STRICT table, which libSQL refuses them in, holds what its BLOB affinity stores.
            assert_eq!(a("select emb from docs").columns[0].nullable, true);
            let distance = a("select id, vector_distance_cos(emb, vector(:q)) as d, vector_distance_l2(emb, :r) as l from docs order by d limit 5");
            assert_eq!((col(&distance, "d"), col(&distance, "l")), (("real".into(), true), ("real".into(), true)));
            assert_eq!((param(&distance, "q"), param(&distance, "r")), ("text".into(), "text".into()));
            let made = a("select vector(:v) as v, vector32(:a) as a, vector64(:b) as b, vector8(:c) as c, vector16(:d) as d, vectorb16(:e) as e, vector1bit(:f) as f, vector_extract(emb) as text from docs");
            for name in ["v", "a", "b", "c", "d", "e", "f"] {
                assert_eq!(col(&made, name), ("blob".into(), false), "{name}");
            }
            assert_eq!(col(&made, "text"), ("text".into(), false));
            let insert = a("insert into docs (title, emb) values (:title, vector(:v)) returning id");
            assert_eq!((param(&insert, "title"), param(&insert, "v")), ("text".into(), "text".into()));
        }
    }

    #[test]
    fn vector_top_k_returns_the_key_of_its_index_s_table() {
        for extras in [Extras::default(), sqlite_host()] {
            let a = |sql: &str| {
                let a = analyze_ddl(sql, &libsql_schema(), &extras).analysis;
                assert!(a.diagnostics.is_empty(), "{sql}: {:?}", a.diagnostics);
                a
            };
            // A rowid table's rowid.
            let top = a("select id from vector_top_k('docs_emb', vector(:q), :k)");
            assert_eq!(col(&top, "id"), ("integer".into(), false));
            assert_eq!((param(&top, "q"), param(&top, "k")), ("text".into(), "integer".into()));
            assert_eq!(a("select * from vector_top_k('docs_emb', :q, 5)").columns.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(), ["id"]);
            let joined = a("select d.id, d.title from vector_top_k('docs_emb', vector(:q), 5) as t join docs d on d.id = t.id");
            assert_eq!(col(&joined, "title"), ("text".into(), false));
            // A WITHOUT ROWID table's primary key, of any storage class outside a STRICT table.
            assert_eq!(col(&a("select id from vector_top_k('words_e', :q, 3)"), "id"), ("unknown".into(), false));
            // On the nullable side of an outer join, and from an index named some other way.
            assert_eq!(col(&a("select t.id from docs d left join vector_top_k('docs_emb', d.emb, 1) t"), "id"), ("integer".into(), true));
            assert_eq!(a("select id from vector_top_k(:index, :q, 5)").columns[0].nullable, true);
        }
    }

    #[test]
    fn libsql_s_alter_column_prepares_on_a_table_and_column_that_exist() {
        let a = |sql: &str| analyze_ddl(sql, &libsql_schema(), &Extras::default()).analysis;
        for sql in ["alter table docs alter column title to title text not null", "ALTER TABLE main.docs ALTER emb TO emb F32_BLOB(3) NOT NULL", "alter table \"docs\" alter column \"title\" to \"title\" text"] {
            let altered = a(sql);
            assert!(altered.diagnostics.is_empty(), "{sql}: {:?}", altered.diagnostics);
            assert!(altered.columns.is_empty());
            assert_eq!(altered.cardinality, Cardinality::None);
        }
        let missing = a("alter table docs alter column nope to nope integer");
        assert!(missing.diagnostics.len() == 1 && missing.diagnostics[0].message.starts_with("no such column: \"nope\", so if it is a migration"), "{:?}", missing.diagnostics);
        assert!(!a("alter table nope alter column title to title text").diagnostics.is_empty());
        assert!(!a("alter table docs alter column title").diagnostics.is_empty());
    }

    #[test]
    fn a_table_whose_check_calls_a_function_the_host_lacks_still_replays() {
        // sqlite-jsonschema's function, which the application's connection loads and the type
        // check's does not: CREATE TABLE resolves the CHECK, and the table was left out.
        let ddl = vec!["create table docs (id integer primary key, doc text check (doc is null or jsonschema_matches('{\"type\":\"object\"}', doc)))".to_string()];
        let without = Extras { total: vec![], host: Some(vec![HostFunction { name: "lower".into(), arity: 1, kind: 's' }]) };
        for extras in [Extras::default(), without.clone()] {
            let read = analyze_ddl("select id, doc from docs", &ddl, &extras).analysis;
            assert!(read.diagnostics.is_empty(), "{:?}", read.diagnostics);
            assert_eq!(read.columns.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(), ["id", "doc"]);
            let write = analyze_ddl("insert into docs (doc) values (:doc) returning id", &ddl, &extras).analysis;
            assert!(write.diagnostics.is_empty(), "{:?}", write.diagnostics);
            assert_eq!(param(&write, "doc"), "text");
        }
        // A statement that calls the function itself is still refused where the host lacks it.
        let call = analyze_ddl("select jsonschema_matches('{}', doc) as m from docs", &ddl, &without).analysis;
        assert!(!call.diagnostics.is_empty());
    }

    #[test]
    fn columns_from_provenance_and_rules() {
        let a = analysis("select id, name, email, score, length(email) as l, coalesce(email, 'x') as e, id * 2 as d, id / 2 as h from users");
        assert_eq!(col(&a, "id"), ("integer".into(), false));
        assert_eq!(col(&a, "name"), ("text".into(), false));
        assert_eq!(col(&a, "email"), ("text".into(), true));
        assert_eq!(col(&a, "score"), ("real".into(), true));
        assert_eq!(col(&a, "l"), ("integer".into(), true));
        assert_eq!(col(&a, "e"), ("text".into(), false));
        assert_eq!(col(&a, "d"), ("integer".into(), false));
        assert_eq!(col(&a, "h"), ("integer".into(), false));
        assert_eq!(a.cardinality, "many");
    }

    #[test]
    fn a_column_beside_an_aggregate_with_no_group_by_is_null_over_no_rows() {
        // The one row an aggregate with no GROUP BY returns over no rows holds NULL in every
        // column outside an aggregate's arguments, whatever the table declares or the WHERE tests.
        let a = analysis("select id, name, coalesce(email, 'x') as e, id * 2 as d, count(*) as n, count(name) as c, max(id) as m from users where name = 'ada'");
        assert_eq!(col(&a, "id"), ("integer".into(), true));
        assert_eq!(col(&a, "name"), ("text".into(), true));
        assert_eq!(col(&a, "e"), ("text".into(), false));
        assert_eq!(col(&a, "d"), ("integer".into(), true));
        assert_eq!(col(&a, "n"), ("integer".into(), false));
        assert_eq!(col(&a, "c"), ("integer".into(), false));
        assert_eq!(a.cardinality, "one");
        // A group has a row, and an aggregate reads rows that are there.
        let a = analysis("select name, count(*) as n from users group by name");
        assert_eq!(col(&a, "name"), ("text".into(), false));
    }

    #[test]
    fn outer_join_and_subquery_provenance() {
        let a = analysis("select u.id, p.title from users u left join posts p on p.user_id = u.id");
        assert_eq!(col(&a, "title"), ("text".into(), true));
        let a = analysis("select t.id, t.name from (select id, name from users) t where t.id = :id");
        assert_eq!(col(&a, "id"), ("integer".into(), false));
        assert_eq!(col(&a, "name"), ("text".into(), false));
        assert_eq!(param(&a, "id"), "integer");
    }

    #[test]
    fn parameters_from_context() {
        let a = analysis("select id from users where email = :email and score >= :min and id in (:a, :b) and created_at between :from and :to and name like :q and lower(name) = :n limit :lim offset :off");
        assert_eq!(param(&a, "email"), "text");
        assert_eq!(param(&a, "min"), "real");
        assert_eq!(param(&a, "a"), "integer");
        assert_eq!(param(&a, "from"), "text");
        assert_eq!(param(&a, "q"), "text");
        assert_eq!(param(&a, "n"), "text");
        assert_eq!(param(&a, "lim"), "integer");
        assert_eq!(param(&a, "off"), "integer");
        let a = analysis("insert into users (email, name, score) values (:e, upper(:n), :s * 2) returning id");
        assert_eq!(param(&a, "e"), "text");
        assert_eq!(param(&a, "n"), "text");
        assert_eq!(param(&a, "s"), "integer");
        assert_eq!(a.cardinality, "one");
        let a = analysis("update users set name = :name, score = :score where id = :id returning id");
        assert_eq!(param(&a, "name"), "text");
        assert_eq!(param(&a, "score"), "real");
        assert_eq!(param(&a, "id"), "integer");
        assert_eq!(a.cardinality, "at_most_one");
    }

    #[test]
    fn json_each_reads_text() {
        // A list of values in one parameter: the JSON text and the path are text, as written or cast.
        let a = analysis("select id from users where id in (select value from json_each(:ids))");
        assert_eq!(param(&a, "ids"), "text");
        assert!(!a.params.iter().find(|p| p.name == "ids").unwrap().nullable);
        let a = analysis("select key, value from json_tree(:doc, :path)");
        assert_eq!(param(&a, "doc"), "text");
        assert_eq!(param(&a, "path"), "text");
        assert_eq!(param(&analysis("select value from json_each(cast(:ids as text))"), "ids"), "text");
        let a = marked("select value from json_each(coalesce(CAST(:ids AS TEXT), '[]'))", &ddl(), &["ids"]);
        assert_eq!(param(&a, "ids"), "text");
        assert!(a.params.iter().find(|p| p.name == "ids").unwrap().nullable);
        // A parameter beside the call keeps its own context.
        let a = analysis("select users.id from users, json_each(:ids) j where users.id = j.value and users.name = :n");
        assert_eq!(param(&a, "ids"), "text");
        assert_eq!(param(&a, "n"), "text");
    }

    #[test]
    fn cardinality_by_keys() {
        assert_eq!(analysis("select id from users where email = :email").cardinality, "at_most_one");
        assert_eq!(analysis("select id from users where name = :name").cardinality, "many");
        assert_eq!(analysis("select u.id, count(p.id) as n from users u left join posts p on p.user_id = u.id where u.id = :id group by u.id").cardinality, "at_most_one");
        assert_eq!(analysis("select id from users limit 1").cardinality, "at_most_one");
        assert_eq!(analysis("insert or ignore into users (email, name) values (:e, :n) returning id").cardinality, "at_most_one");
        assert_eq!(analysis("insert into users (email, name) values (:e, :n)").cardinality, "none");
        assert_eq!(analysis("delete from users where id = :id returning id").cardinality, "at_most_one");
        assert_eq!(analysis("select id from users union all select user_id from posts").cardinality, "many");
    }

    /// The whole path, schema query included, as the host drives it.
    fn analyzed(sql: &str) -> Analysis {
        let ddl = [
            "create table users (id integer primary key, name text not null, email text unique, score real, avatar blob, created_at text not null default current_timestamp)",
        ];
        let rows = ddl.iter().map(|d| vec![serde_json::Value::String(d.to_string())]).collect();
        let answers = HashMap::from([(format!("query:{DDL_QUERY}|[]"), crate::api::Answer::Rows { rows }), (format!("query:{FUNCTIONS_QUERY}|[]"), functions_answer(&[]))]);
        let host = Host::new(&answers);
        analyze(sql, &lex::lex(sql, Dialect::Sqlite).unwrap(), &host, &[]).expect("the schema and the functions were answered")
    }

    /// What a SQLite with none of the optional families lists, as [`FUNCTIONS_QUERY`]'s rows: the
    /// functions the tests call, and `extra` on top.
    fn listed(extra: &[(&str, i32, char)]) -> Vec<Vec<serde_json::Value>> {
        let core = [("count", 0, 'w'), ("count", 1, 'w'), ("max", 1, 'w'), ("max", -3, 's'), ("upper", 1, 's'), ("lower", 1, 's'), ("like", 2, 's'), ("like", 3, 's'), ("glob", 2, 's')];
        let more = [("coalesce", -4, 's'), ("iif", -4, 's'), ("json_extract", -1, 's'), ("->>", 2, 's'), ("current_timestamp", 0, 's'), ("row_number", 0, 'w'), ("group_concat", 1, 'w'), ("abs", 1, 's')];
        core.iter().chain(more.iter()).chain(extra.iter()).map(|(name, narg, kind)| vec![serde_json::json!(name), serde_json::json!(narg), serde_json::json!(kind.to_string())]).collect()
    }

    fn functions_answer(extra: &[(&str, i32, char)]) -> crate::api::Answer {
        crate::api::Answer::Rows { rows: listed(extra) }
    }

    /// The direct entry on a host whose SQLite lists [`listed`]'s functions.
    fn on_host(sql: &str, schema: &[String], extra: &[(&str, i32, char)], total: Vec<TotalFunction>) -> Analysis {
        analyze_ddl(sql, schema, &Extras { total, host: host_functions(&listed(extra)) }).analysis
    }

    #[test]
    fn names_fold_ascii_case_as_sqlite_folds_them() {
        let schema: Vec<String> = [
            "create table Books (id integer primary key, Title text not null, ISBN text unique, note text)",
            "create table \"\u{c9}t\u{e9}\" (id integer primary key, v text)",
            "create table wr (K text primary key, v text) without rowid",
            "create table rt (RowId integer, v text)",
            "create table \"my table\" (id integer primary key, v text)",
            "create trigger \"skip one\" before insert on \"BOOKS\" begin select raise(ignore) where new.title = 'x'; end",
            "create trigger skip_two before insert on \"my table\" begin select raise(ignore) where new.v = 'x'; end",
            "create trigger [later] after update of \"on\", v on main . [my table] begin select 1; end",
        ]
        .iter()
        .map(|s| s.to_string())
        .collect();
        let a = |sql: &str| analyze_ddl(sql, &schema, &Extras::default()).analysis;
        // The table as the statement spells it, bare, quoted or qualified, is the table the DDL
        // declares, and its keys are that table's.
        for sql in [
            "select * from books where id = :id",
            "select * from BOOKS where ID = :id",
            "select * from \"books\" where \"ID\" = :id",
            "select * from [BOOKS] b where B.Id = :id",
            "select b.* from main.bOOKS b join Books c on c.ID = b.id where C.id = :id",
            "select title from books where isbn = :i",
            "update BOOKS set TITLE = :t where ID = :id returning Title",
            "delete from books where Isbn = :i returning id",
            "select v from WR where k = :k",
            "select v from Rt where _ROWID_ = :r",
        ] {
            let got = a(sql);
            assert!(got.diagnostics.is_empty(), "{sql}: {:?}", got.diagnostics);
            assert_eq!(got.cardinality, "at_most_one", "{sql}: {:?}", got.cardinality_reason);
        }
        // A declared column named rowid in any case hides the rowid, and a table without a rowid
        // has none to name.
        assert_eq!(a("select v from RT where ROWID = :r").cardinality, "many");
        assert_eq!(a("select v from wr where rowid = 1").diagnostics[0].message, "no such column: rowid");
        // A target column in another case is the declared column: its type, and its NOT NULL.
        let insert = a("insert into BOOKS (TITLE, NOTE) values (:t, :n)");
        assert_eq!((param(&insert, "t"), param(&insert, "n")), ("text".into(), "text".into()));
        assert_eq!(insert.params.iter().map(|p| p.nullable).collect::<Vec<_>>(), [false, true]);
        assert_eq!(col(&a("select TITLE, Note from books"), "Title"), ("text".into(), false));
        // The rowid by any of its names, in any case, is the INTEGER PRIMARY KEY column.
        assert_eq!(param(&a("insert into books (ROWID, title) values (:r, :t)"), "r"), "integer");
        assert_eq!(param(&a("insert into rt (_rowid_, v) values (:r, :v)"), "r"), "unknown");
        // SQLite folds ASCII alone: `été` is another name than `Été`, and no table.
        assert_eq!(a("select v from \"\u{c9}t\u{e9}\" where id = :id").cardinality, "at_most_one");
        assert_eq!(a("select v from \"\u{e9}t\u{e9}\" where id = :id").diagnostics[0].message, "no such table: \u{e9}t\u{e9}");
        // A table-valued function in any case is the function.
        assert_eq!(param(&a("select value from JSON_EACH(:ids)"), "ids"), "text");
        // A trigger's table is read as SQLite reads it, quoted and in another case, and so is a
        // trigger whose name or column list holds a keyword.
        assert_eq!(a("insert into books (title) values (:t) returning id").cardinality, "at_most_one");
        assert_eq!(a("insert into \"My Table\" (v) values (:v) returning id").cardinality, "at_most_one");
        assert_eq!(trigger_header(&schema[5]), Some(("before".into(), "insert".into(), "books".into())));
        assert_eq!(trigger_header(&schema[7]), Some(("after".into(), "update".into(), "my table".into())));
        assert_eq!(trigger_header("CREATE TRIGGER main.\"before\" /* on x */ INSTEAD OF DELETE ON v -- on y\n BEGIN SELECT 1; END"), Some(("instead".into(), "delete".into(), "v".into())));
        assert_eq!(trigger_header("create table trigger_log (\"on\" text)"), None);
    }

    #[test]
    fn every_row_of_a_values_list_types_its_parameters() {
        let a = analysis("insert into users (id, name, email) values (:a, :b, :e), (:c, :d, :e2), (:f, upper(:g), 'x') returning id");
        assert!(a.diagnostics.is_empty(), "{:?}", a.diagnostics);
        let got: Vec<(String, String, bool)> = a.params.iter().map(|p| (p.name.clone(), affinity_of(&p.ty).unwrap_or("unknown").to_string(), p.nullable)).collect();
        let want = [("a", "integer", false), ("b", "text", false), ("e", "text", true), ("c", "integer", false), ("d", "text", false), ("e2", "text", true), ("f", "integer", false), ("g", "text", false)];
        assert_eq!(got, want.map(|(n, t, null)| (n.to_string(), t.to_string(), null)));
        assert_eq!((a.cardinality.as_str(), a.cardinality_reason.as_deref()), ("many", Some("a VALUES list of 3 rows returns 3 rows")));
        // A parameter a row does not write whole cannot be null. Each parameter appears once, so
        // one cannot be written to a nullable column in one row and a NOT NULL one in another.
        let a = analysis("insert into users (name, email) values ('a', :x), (:w, 'b'), ('c', lower(:y))");
        assert_eq!(a.params.iter().map(|p| p.nullable).collect::<Vec<_>>(), [true, false, false]);
        assert_eq!(a.cardinality, "none");
        let a = analysis("insert into users (name, email) values ('a', :x), (:x, 'b')");
        assert_eq!(a.diagnostics.iter().map(|d| d.code).collect::<Vec<_>>(), [3]);
        // Without a column list the rows fill the columns in order; under a WITH too.
        let a = analysis("with w as (select 1) insert into posts values (:id, :u, :t, :b), (:id2, :u2, :t2, :b2)");
        assert_eq!(a.params.iter().map(|p| (affinity_of(&p.ty).unwrap_or("unknown"), p.nullable)).collect::<Vec<_>>(), [("integer", false), ("integer", false), ("text", false), ("text", true)].repeat(2));
        // A list of any length: SQLite keeps a row per arm, and the tree nests none of them.
        let rows: Vec<String> = (0..3000).map(|i| format!("(:n{i}, :e{i}, {i})")).collect();
        let a = analysis(&format!("insert into users (name, email, score) values {}", rows.join(", ")));
        assert!(a.diagnostics.is_empty(), "{:?}", a.diagnostics);
        assert_eq!((a.params.len(), param(&a, "n2999"), param(&a, "e2999")), (6000, "text".into(), "text".into()));
        // A VALUES list on its own: a row per row, a column of the type its rows share, NULL where
        // a row has one, and a parameter typed by the rows beside it.
        let a = analysis("values (1, 'a', :p), (2, null, 3), (:q, 'c', 4.5)");
        assert_eq!((col(&a, "column1"), col(&a, "column2")), (("integer".into(), false), ("text".into(), true)));
        assert_eq!((param(&a, "p"), param(&a, "q"), a.cardinality.as_str()), ("real".into(), "integer".into(), "many"));
        assert_eq!(analysis("values (1, 'a')").cardinality, "one");
        assert_eq!(col(&analysis("values (1), ('a')"), "column1").0, "unknown");
        assert_eq!(analysis("select v.column1 from (values (1), (2)) v").cardinality, "many");
        assert_eq!(analysis("select 1 union all values (2), (3)").cardinality, "many");
        assert_eq!(col(&analysis("select (values (1), (2)) as x"), "x"), ("integer".into(), true));
    }

    #[test]
    fn the_select_that_feeds_an_insert_types_its_parameters() {
        let schema = vec!["create table bar (name text not null, ready bool not null, n integer)".to_string(), "create table foo (name text not null, meta text, k integer)".to_string(), "create table foo2 (name text not null, meta text, k integer)".to_string()];
        let a = |sql: &str| {
            let a = analyze_ddl(sql, &schema, &Extras::default()).analysis;
            assert!(a.diagnostics.is_empty(), "{sql}: {:?}", a.diagnostics);
            a
        };
        let params = |a: &Analysis| a.params.iter().map(|p| (affinity_of(&p.ty).unwrap_or("unknown").to_string(), p.nullable)).collect::<Vec<_>>();
        let typed = |types: &[&str]| types.iter().map(|t| (t.to_string(), false)).collect::<Vec<_>>();
        // A select-list parameter takes its target column's type; one the WHERE compares, the
        // column's: `bool` is a declared type of NUMERIC affinity, a number or a text.
        // A bare one written to a column that may hold NULL takes NULL, as in a VALUES row.
        let got = a("insert into foo (name, meta) select name, ? from bar where ready = ?");
        assert_eq!((got.kind.map_or("", StatementKind::as_str), got.cardinality.as_str()), ("insert", "none"));
        assert_eq!(params(&got), [("text".to_string(), true), ("numeric".to_string(), false)]);
        assert_eq!(params(&a("select name from bar where ready = ?")), typed(&["numeric"]));
        // Without a column list, through an expression, in every arm of a compound, and under a
        // LIMIT; only a bare column of the one SELECT is a value written whole.
        assert_eq!(params(&a("insert into foo select :n, :m, :k from bar")), [("text".to_string(), false), ("text".to_string(), true), ("integer".to_string(), true)]);
        assert_eq!(params(&a("insert into foo (k, name) select n + :d, upper(:u) from bar limit :l")), typed(&["integer", "text", "integer"]));
        assert_eq!(params(&a("insert into foo (name, k) select name, :a from bar union all select :b, n from bar")), typed(&["integer", "text"]));
        let returning = a("insert into foo (name, meta) select name, :m from bar where n > :n returning name, meta");
        assert_eq!((params(&returning), returning.cardinality.as_str()), (vec![("text".to_string(), true), ("integer".to_string(), false)], "many"));
        // A subquery elsewhere in the statement is not the INSERT's source: one in RETURNING
        // stands in no typed place, and one in a VALUES row is the value written to its own
        // column (k, not the first target column name), as any scalar subquery takes the type of
        // the place it stands in.
        assert_eq!(params(&a("insert into foo (name, meta) select name, 'x' from bar returning (select :p) as p")), typed(&["unknown"]));
        assert_eq!(params(&a("insert into foo (name, k) values ('a', (select :p))")), typed(&["integer"]));
        // A whole-table copy, which SQLite runs without a SELECT, is still an INSERT.
        let copy = a("insert into foo2 select * from foo");
        assert_eq!((copy.kind.map_or("", StatementKind::as_str), copy.cardinality.as_str()), ("insert", "none"));
    }

    #[test]
    fn the_hosts_sqlite_decides_which_functions_exist() {
        // The embedded SQLite has the math functions and `soundex`; a host may have neither.
        let sql = "select id, ACOS(score) as a from users where name = :n";
        let a = on_host(sql, &ddl(), &[], Vec::new());
        assert_eq!(a.diagnostics.len(), 1, "{:?}", a.diagnostics);
        assert_eq!(a.diagnostics[0].message, "no such function: ACOS on this database's SQLite");
        assert_eq!((a.diagnostics[0].start, a.diagnostics[0].length, a.diagnostics[0].code), (sql.find("ACOS").unwrap(), 4, 6));
        assert!(a.columns.is_empty());
        let a = on_host(sql, &ddl(), &[("acos", 1, 's')], Vec::new());
        assert!(a.diagnostics.is_empty(), "{:?}", a.diagnostics);
        assert_eq!(col(&a, "a"), ("real".into(), true));
        let a = on_host("select soundex(name) as s from users where soundex(:x) = 'A000'", &ddl(), &[("SOUNDEX", 1, 's')], Vec::new());
        assert_eq!((col(&a, "s"), param(&a, "x")), (("text".into(), false), "text".into()));
        assert_eq!(on_host("select soundex(name) as s from users", &ddl(), &[], Vec::new()).diagnostics[0].message, "no such function: soundex on this database's SQLite");
        // A host that cannot list its functions keeps every function the embedded SQLite has.
        assert_eq!(col(&analysis("select acos(score) as a, soundex(name) as s from users"), "a"), ("real".into(), true));
        // What every SQLite has stays: operators that are functions underneath, keywords, `*`.
        let a = on_host("select count(*) as n, max(name) as m, coalesce(email, 'x') as e, current_timestamp as t, email ->> '$.a' as j, row_number() over (order by id) as r from users where name like :p and email glob 'a*' and iif(id > 1, true, false)", &ddl(), &[], Vec::new());
        assert!(a.diagnostics.is_empty(), "{:?}", a.diagnostics);
        // A call inside a window definition, a subquery, a WITH query and an ORDER BY is a call.
        for sql in [
            "select row_number() over (order by sqrt(score)) as r from users",
            "select id from users where id in (select id from users where sqrt(score) > 1)",
            "with w as (select sqrt(score) as s from users) select s from w",
            "select id from users order by sqrt(score)",
            "update users set score = sqrt(score) where id = :id",
            "insert into users (name, score) values (:n, sqrt(:s))",
            "delete from users where id = :id returning sqrt(score) as s",
        ] {
            let a = on_host(sql, &ddl(), &[], Vec::new());
            assert_eq!(a.diagnostics.first().map(|d| (d.message.as_str(), d.start)), Some(("no such function: sqrt on this database's SQLite", sql.find("sqrt").unwrap())), "{sql}");
        }
        // A view that calls one fails every statement that reads it, with no place in the
        // statement to point at; the replay itself keeps the view.
        let mut schema = ddl();
        schema.push("create view roots as select id, sqrt(score) as root from users".into());
        let sql = "select root from roots";
        let a = on_host(sql, &schema, &[], Vec::new());
        assert_eq!(a.diagnostics.len(), 1, "{:?}", a.diagnostics);
        assert_eq!((a.diagnostics[0].message.as_str(), a.diagnostics[0].start, a.diagnostics[0].length), ("no such function: sqrt on this database's SQLite (the view roots calls it)", 0, sql.len()));
        assert_eq!(col(&on_host(sql, &schema, &[("sqrt", 1, 's')], Vec::new()), "root"), ("real".into(), true));
        assert!(on_host("select id from users", &schema, &[], Vec::new()).diagnostics.is_empty());
        // A function the host has and the embedded SQLite lacks prepares, with no type; an
        // aggregate is one row, and a window function takes an OVER.
        let extra = [("host_only", 2, 's'), ("host_only", 3, 's'), ("host_agg", 1, 'a'), ("host_win", -1, 'w')];
        let a = on_host("select host_only(name, 1) as two, host_only(name, 1, 2) as three from users where id = :id", &ddl(), &extra, Vec::new());
        assert!(a.diagnostics.is_empty(), "{:?}", a.diagnostics);
        assert_eq!((col(&a, "two"), col(&a, "three"), a.cardinality.as_str()), (("unknown".into(), true), ("unknown".into(), true), "at_most_one"));
        // It may change from row to row, so it pins no key.
        assert_eq!(on_host("select name from users where id = host_only(1, 2)", &ddl(), &extra, Vec::new()).cardinality, "many");
        let a = on_host("select host_agg(score) as total from users", &ddl(), &extra, Vec::new());
        assert_eq!((col(&a, "total"), a.cardinality.as_str()), (("unknown".into(), true), "one"));
        let a = on_host("select host_win(score, 1) over (partition by name) as w, host_win(id) as plain from users", &ddl(), &extra, Vec::new());
        assert!(a.diagnostics.is_empty(), "{:?}", a.diagnostics);
        assert_eq!(on_host("select host_only(name) from users", &ddl(), &extra, Vec::new()).diagnostics[0].message, "wrong number of arguments to function host_only()");
        // A function the host registers on its connection is one it has, listed or not.
        let html = vec![TotalFunction { name: "reylo_html".into(), arity: 1, returns: Affinity::Text }];
        assert_eq!(col(&on_host("select reylo_html(name) as h from users", &ddl(), &[], html), "h"), ("text".into(), false));
        // No list at all is no list: every SQLite has functions.
        assert_eq!(host_functions(&[]), None);
        assert_eq!(host_functions(&[vec![serde_json::json!("abs"), serde_json::json!("1"), serde_json::json!("s")]]), Some(vec![HostFunction { name: "abs".into(), arity: 1, kind: 's' }]));
    }

    #[test]
    fn the_replay_asks_the_host_for_its_functions_with_the_schema() {
        let sql = "select acos(score) as a from users";
        let lexed = lex::lex(sql, Dialect::Sqlite).unwrap();
        let schema = crate::api::Answer::Rows { rows: ddl().iter().map(|d| vec![serde_json::Value::String(d.clone())]).collect() };
        let ask = |answers: &HashMap<String, crate::api::Answer>| {
            let host = Host::new(answers);
            let analysis = analyze(sql, &lexed, &host, &[]);
            let needs: Vec<String> = host
                .needs()
                .iter()
                .map(|n| match n {
                    crate::api::Need::Query { sql, scope, .. } => format!("{sql} {scope:?}"),
                    crate::api::Need::Describe { sql, .. } => format!("describe {sql}"),
                })
                .collect();
            (analysis, needs)
        };
        // One round asks both, for the session.
        let mut answers = HashMap::new();
        let (analysis, needs) = ask(&answers);
        assert!(analysis.is_none());
        assert_eq!(needs, [format!("{DDL_QUERY} Session"), format!("{FUNCTIONS_QUERY} Session")]);
        answers.insert(format!("query:{DDL_QUERY}|[]"), schema);
        assert_eq!(ask(&answers).1, [format!("{FUNCTIONS_QUERY} Session")]);
        // The host's list decides.
        answers.insert(format!("query:{FUNCTIONS_QUERY}|[]"), functions_answer(&[]));
        let (analysis, needs) = ask(&answers);
        assert!(needs.is_empty());
        assert_eq!(analysis.unwrap().diagnostics[0].message, "no such function: acos on this database's SQLite");
        answers.insert(format!("query:{FUNCTIONS_QUERY}|[]"), functions_answer(&[("acos", 1, 's')]));
        assert!(ask(&answers).0.unwrap().diagnostics.is_empty());
        // A host whose SQLite refuses the question, or answers nothing, keeps the embedded one's.
        answers.insert(format!("query:{FUNCTIONS_QUERY}|[]"), crate::api::Answer::Error { error: crate::api::DbError { message: "not authorized".into(), code: None, position: None } });
        assert_eq!(col(&ask(&answers).0.unwrap(), "a"), ("real".into(), true));
        answers.insert(format!("query:{FUNCTIONS_QUERY}|[]"), crate::api::Answer::Rows { rows: Vec::new() });
        assert_eq!(col(&ask(&answers).0.unwrap(), "a"), ("real".into(), true));
    }

    #[test]
    fn a_table_in_an_attached_database_is_named_as_one() {
        let message = |schema: &str| format!("no such table: {schema}.users: the database has no schema `{schema}`. A database the application attaches at run time (ATTACH ... AS {schema}) is not in the file the type check reads, so a table in it cannot be typed");
        for (sql, reference) in [
            ("select id, name from baz.users where id = :id", "baz.users"),
            ("select u.id from \"baz\".[users] u", "\"baz\".[users]"),
            ("select 1 from users join /* x */ baz . users b on b.id = users.id", "baz . users"),
            ("insert into baz.users (id) values (:id)", "baz.users"),
            ("update baz.users set name = :n where id = :id", "baz.users"),
            ("delete from baz.users where id = :id", "baz.users"),
        ] {
            let a = analysis(sql);
            assert_eq!(a.diagnostics.len(), 1, "{sql}: {:?}", a.diagnostics);
            assert_eq!(a.diagnostics[0].message, message("baz"), "{sql}");
            assert_eq!((a.diagnostics[0].start, a.diagnostics[0].length), (sql.find(reference).unwrap(), reference.len()), "{sql}");
        }
        // The position survives the placeholder rewrite.
        let sql = "select :auth.user_id as u, id from baz.users";
        assert_eq!(analysis(sql).diagnostics[0].start, sql.find("baz").unwrap());
        // A schema the database has, and a name that only holds a dot, are SQLite's own message.
        assert_eq!(analysis("select id from main.nope").diagnostics[0].message, "no such table: main.nope");
        assert_eq!(analysis("select id from temp.nope").diagnostics[0].message, "no such table: temp.nope");
        assert_eq!(analysis("select id from \"baz.users\"").diagnostics[0].message, "no such table: baz.users");
        assert_eq!(analysis("select id from nope").diagnostics[0].message, "no such table: nope");
        assert!(analysis("select main.users.id from main.users").diagnostics.is_empty());
    }

    #[test]
    fn sqlites_own_tables_replay_without_a_note() {
        // `sqlite_schema` lists SQLite's own tables beside the application's: the sequence table
        // an AUTOINCREMENT makes, the statistics ANALYZE writes, a virtual table's shadow tables.
        let schema: Vec<String> = [
            "CREATE TABLE t (id integer primary key autoincrement, v text)",
            "CREATE TABLE sqlite_sequence(name,seq)",
            "CREATE TABLE sqlite_stat1(tbl,idx,stat)",
            "CREATE VIRTUAL TABLE ft USING fts5(body)",
            "CREATE TABLE 'ft_data'(id INTEGER PRIMARY KEY, block BLOB)",
            "CREATE TABLE 'ft_idx'(segid, term, pgno, PRIMARY KEY(segid, term)) WITHOUT ROWID",
            "CREATE TABLE 'ft_content'(id INTEGER PRIMARY KEY, c0)",
            "CREATE TABLE 'ft_docsize'(id INTEGER PRIMARY KEY, sz BLOB)",
            "CREATE TABLE 'ft_config'(k PRIMARY KEY, v) WITHOUT ROWID",
            "CREATE VIRTUAL TABLE rt USING rtree(id, minx, maxx)",
            "CREATE TABLE \"rt_rowid\"(rowid INTEGER PRIMARY KEY,nodeno)",
            "CREATE TABLE \"rt_node\"(nodeno INTEGER PRIMARY KEY,data)",
            "CREATE TABLE \"rt_parent\"(nodeno INTEGER PRIMARY KEY,parentnode)",
            "CREATE VIRTUAL TABLE f4 USING fts4(body)",
            "CREATE TABLE 'f4_content'(docid INTEGER PRIMARY KEY, 'c0body')",
            "CREATE TABLE 'f4_segments'(blockid INTEGER PRIMARY KEY, block BLOB)",
            "CREATE TABLE 'f4_segdir'(level INTEGER,idx INTEGER,start_block INTEGER,leaves_end_block INTEGER,end_block INTEGER,root BLOB,PRIMARY KEY(level, idx))",
            "CREATE TABLE 'f4_docsize'(docid INTEGER PRIMARY KEY, size BLOB)",
            "CREATE TABLE 'f4_stat'(id INTEGER PRIMARY KEY, value BLOB)",
        ]
        .iter()
        .map(|s| s.to_string())
        .collect();
        let a = |sql: &str, schema: &[String]| analyze_ddl(sql, schema, &Extras::default()).analysis;
        // An error in the statement is the only thing reported.
        let failed = a("select nope from t", &schema);
        assert_eq!(failed.diagnostics.iter().map(|d| d.message.as_str()).collect::<Vec<_>>(), ["no such column: nope"]);
        for sql in [
            "select name, seq from sqlite_sequence where name = :n",
            "update sqlite_sequence set seq = :s where name = :n",
            "select tbl, idx, stat from sqlite_stat1",
            "select name, sql from sqlite_schema where type = 'table'",
            "select name from sqlite_master",
            "select rowid, body from ft where ft match :q",
            "select id from rt where minx > :x",
            "select docid from f4 where f4 match :q",
            "select block from ft_data where id = :id",
            "insert into t (v) values (:v) returning id",
        ] {
            let got = a(sql, &schema);
            assert!(got.diagnostics.is_empty(), "{sql}: {:?}", got.diagnostics);
        }
        assert_eq!(a("insert into t (v) values (:v) returning id", &schema).cardinality, "one");
        // The schema table itself stays read-only, as on the host.
        assert_eq!(a("delete from sqlite_schema", &schema).diagnostics[0].message, "table sqlite_master may not be modified");
        // A sequence table that outlived its AUTOINCREMENT table, before one made later.
        let later = vec!["CREATE TABLE sqlite_sequence(name,seq)".to_string(), "CREATE TABLE u (id integer primary key autoincrement, v text)".to_string()];
        assert!(a("select seq from sqlite_sequence", &later).diagnostics.is_empty());
        assert_eq!(a("insert into u (v) values (:v) returning id", &later).cardinality, "one");
        assert_eq!(a("select nope from u", &later).diagnostics.len(), 1);
        // A step that really fails is still named beside the statement's error.
        let broken = vec!["CREATE TABLE t (id integer primary key)".to_string(), "CREATE TABLE t (id integer primary key)".to_string(), "CREATE VIEW v AS SELECT".to_string()];
        let notes: Vec<String> = a("select nope from t", &broken).diagnostics.iter().map(|d| d.message.clone()).collect();
        assert_eq!(notes, ["no such column: nope", "The schema replay skipped statement 2: table t already exists", "The schema replay skipped statement 3: incomplete input"]);
    }

    #[test]
    fn a_double_quoted_word_that_names_no_column_is_refused_as_the_drivers_refuse_it() {
        // A schema that holds one replays, as SQLite reads it from a file.
        let schema = vec!["create table t (id integer primary key, v text default \"none\" check (v <> \"bad\"))".to_string()];
        let a = |sql: &str| analyze_ddl(sql, &schema, &Extras::default()).analysis;
        for sql in ["select \"hello\"", "select \"hello\" from t", "select id from t where v = \"x\""] {
            let messages: Vec<String> = a(sql).diagnostics.iter().map(|d| d.message.clone()).collect();
            assert_eq!(messages, [format!("no such column: \"{}\" - should this be a string literal in single-quotes?", if sql.contains("hello") { "hello" } else { "x" })], "{sql}");
        }
        for sql in ["select \"id\", \"v\" from t", "select 'hello'", "insert into t (id) values (1) returning v"] {
            assert!(a(sql).diagnostics.is_empty(), "{sql}: {:?}", a(sql).diagnostics);
        }
    }

    #[test]
    fn the_version_reported_is_the_embedded_sqlites() {
        // The release the docs name (site/content/docs/sqlite.mdx): a newer amalgamation changes both.
        assert!(tree::version().starts_with("3.53."), "{}", tree::version());
    }

    #[test]
    fn a_parameter_sqlite_reads_and_the_lexer_does_not_is_an_error_at_its_place() {
        let unbound = |sql: &str| analysis(sql).diagnostics.iter().filter(|d| d.code == 1).map(|d| (d.start, d.length, d.message.clone())).collect::<Vec<_>>();
        // SQLite's parameter is `:`, `@` or `$` and any run of name characters, digits and bytes
        // past ASCII among them; the lexer's name is ASCII and starts with no digit.
        for written in [":été", ":1st", "@2x"] {
            let sql = format!("select id from users where name = :n and email = {written}");
            let found = unbound(&sql);
            assert_eq!(found.iter().map(|(s, l, _)| (*s, *l)).collect::<Vec<_>>(), [(sql.find(written).unwrap(), written.len())], "{sql}");
            assert_eq!(found[0].2, format!("SQLite reads {written} as a parameter that Reylo does not bind; name a parameter with the letters a to z, digits and underscores, starting with a letter or an underscore"));
        }
        // The place is the parameter's, not the same text in a string before it.
        let sql = "select ':été' from users where name = :été";
        assert_eq!(unbound(sql).iter().map(|(s, _, _)| *s).collect::<Vec<_>>(), [sql.rfind(":été").unwrap()]);
        // Every parameter the lexer read is one SQLite numbers, in each form, and a bracketed
        // name hides nothing after it.
        for sql in ["select id from users where name = :n and email = :e", "select id from users where name = ?2 and email = ?", "select id as [it's], :n as n from users", "pragma table_info(users)"] {
            assert!(unbound(sql).is_empty(), "{sql}");
        }
        assert_eq!(analysis("select id as [it's], :n as n from users").params.len(), 1);
    }

    #[test]
    fn a_parameter_as_a_whole_sort_or_group_key_is_an_error_at_its_place() {
        // Through the protocol's whole path, which compiles a `::type` cast to SQLite's own.
        let full = |sql: &str| {
            let ddl = ["create table users (id integer primary key, name text not null, email text unique, score real, avatar blob, created_at text not null default current_timestamp)"];
            let rows = ddl.iter().map(|d| vec![serde_json::Value::String(d.to_string())]).collect();
            let answers = HashMap::from([(format!("query:{DDL_QUERY}|[]"), crate::api::Answer::Rows { rows }), (format!("query:{FUNCTIONS_QUERY}|[]"), functions_answer(&[]))]);
            let host = Host::new(&answers);
            <crate::api::Sqlite as reylo_engine_core::database::Database>::analyze(sql, &host).expect("answered")
        };
        let keys = |sql: &str| full(sql).diagnostics.iter().filter(|d| d.code == 17).map(|d| (d.start, d.length, d.message.clone())).collect::<Vec<_>>();
        let at = |sql: &str, written: &str| sql.find(written).unwrap();
        // A `::type` cast is part of the parameter's place, as on every diagnostic at a cast one.
        for (sql, length) in [("select id from users order by :sort", 5), ("select id from users order by :sort::text desc", 11), ("select id from users order by cast(:sort as text)", 5), ("select id from users order by :sort collate nocase", 5)] {
            let found = keys(sql);
            assert_eq!(found.iter().map(|(s, l, _)| (*s, *l)).collect::<Vec<_>>(), [(at(sql, ":sort"), length)], "{sql}");
            assert_eq!(found[0].2, "order by :sort sorts every row by the same value, since a parameter is a value and not a column's name; choose the column with case :sort when 'name' then name end");
        }
        for (sql, written) in [("select id from users order by ?", "?"), ("select id from users order by ?2", "?2"), ("select id from users order by @s", "@s"), ("select id from users order by $s", "$s")] {
            let found = keys(sql);
            assert_eq!(found.iter().map(|(s, l, _)| (*s, *l)).collect::<Vec<_>>(), [(at(sql, written), written.len())], "{sql}");
            assert!(found[0].2.starts_with(&format!("order by {written} sorts every row")), "{sql}");
        }
        assert_eq!(keys("select id from users order by ?2, ?1").iter().map(|(s, ..)| *s).collect::<Vec<_>>(), [30, 34]);
        assert_eq!(keys("select id from users order by name, ?").len(), 1);
        // GROUP BY, alone and beside another key.
        assert_eq!(keys("select count(*) as n from users group by :g")[0].2, "group by :g puts every row in one group, since a parameter is a value and not a column's name; choose the column with case :g when 'name' then name end");
        assert!(keys("select count(*) as n from users group by name, :g::text")[0].2.starts_with("group by :g groups every row by the same value"));
        // A window's keys, a named window's, and an aggregate's ORDER BY.
        let sql = "select row_number() over (partition by :p order by :o) as n from users";
        let found = keys(sql);
        assert_eq!(found.iter().map(|(s, _, m)| (*s, m.split(',').next().unwrap().to_string())).collect::<Vec<_>>(), [(at(sql, ":p"), "partition by :p puts every row in one partition".to_string()), (at(sql, ":o"), "order by :o sorts every row by the same value".to_string())]);
        assert_eq!(keys("select row_number() over w as n from users window w as (order by :o)").len(), 1);
        assert_eq!(keys("select group_concat(name, ',' order by :o) as names from users").len(), 1);
        // In a subquery, a WITH query (read twice, reported once), an expression's subquery and a
        // set operation's ORDER BY.
        assert_eq!(keys("select id from (select id from users order by :s limit 3) t").len(), 1);
        assert_eq!(keys("with t as (select name from users group by :g, name) select a.name from t a, t b").len(), 1);
        assert_eq!(keys("select id from users where id in (select id from users order by :s limit 3)").len(), 1);
        // SQLite itself refuses a compound's ORDER BY term that names no column of its result.
        let refused = full("select id from users union select id from users order by :s");
        assert_eq!(refused.diagnostics.iter().map(|d| (d.code, d.message.as_str())).collect::<Vec<_>>(), [(6, "1st ORDER BY term does not match any column in the result set")]);
        assert_eq!(keys("insert into users (name) select name from users order by :s").len(), 1);
        // A key that holds a parameter chooses a column with it; a position and a LIMIT are none,
        // and so is a position or an alias of a result column that is a parameter, which SQLite
        // resolves to a copy of the parameter.
        for sql in [
            "select id, :tag as tag from users order by 2",
            "select id, :tag as tag from users order by tag",
            "select :tenant as tenant, name, count(*) as n from users group by 1, 2",
            "select id, name from users order by case :sort when 'name' then name end",
            "select id from users order by case when :desc then id end desc, id",
            "select id from users order by 1 limit :n",
            "select id from users order by lower(:x) || name",
        ] {
            assert_eq!(keys(sql), [], "{sql}");
        }
        // The rest of the statement is typed all the same.
        let a = full("select id from users order by :sort::text");
        assert_eq!(a.columns.len(), 1);
        assert_eq!(affinity_of(&a.params[0].ty), Some("text"));
    }

    #[test]
    fn names_a_column_as_the_statement_is_sent() {
        // The tree is read over `?1`; the statement runs with `?`, and a driver's row holds the name that text gives.
        let names = |sql: &str| analysis(sql).columns.iter().map(|c| c.name.clone()).collect::<Vec<_>>();
        assert_eq!(names("select id + cast(:a as integer), name from users"), ["id + cast(? as integer)", "name"]);
        assert_eq!(names("select * from (select id + cast(:a as integer) from users)"), ["id + cast(? as integer)"]);
        assert_eq!(names("update users set name = name returning id + cast(:a as integer)"), ["id + cast(? as integer)"]);
        assert_eq!(names("select cast(:a as integer) as a"), ["a"]);
    }

    #[test]
    fn prepares_the_numbered_rewrite() {
        // SQLite's own `:auth` would end at the dot; the rewrite keeps the whole name one parameter.
        let a = analyzed("select name from users where email = :auth.email and id = :auth.id and score > :auth.email");
        assert!(a.diagnostics.is_empty(), "{:?}", a.diagnostics);
        assert_eq!(param(&a, "auth.email"), "text");
        assert_eq!(param(&a, "auth.id"), "integer");
        assert_eq!(a.rewritten.sql, "select name from users where email = ? and id = ? and score > ?");
        assert_eq!(a.rewritten.order, ["auth.email", "auth.id", "auth.email"]);
        // Positional forms: SQLite's `?3` is the parameter `3`, and a bare `?` the next number.
        assert_eq!(param(&analyzed("select name from users where id = ?3"), "3"), "integer");
        assert_eq!(param(&analyzed("select name from users where email = ?"), "1"), "text");
        // An error SQLite reports in the rewrite lands on the author's text.
        let sql = "select :auth.user_id, nope from users";
        let a = analyzed(sql);
        assert_eq!(a.diagnostics.len(), 1, "{:?}", a.diagnostics);
        assert_eq!((a.diagnostics[0].start, a.diagnostics[0].length), (sql.find("nope").unwrap(), 4));
    }

    #[test]
    fn a_column_declared_without_a_type_holds_any_value() {
        let ddl = vec!["CREATE TABLE t (a, b TEXT, c ANY)".to_string(), "CREATE TABLE s (x ANY, y INTEGER) STRICT".to_string()];
        let r = analyze_ddl("SELECT t.a, t.b, s.x, s.y FROM t, s WHERE t.a = :a AND s.x = :x", &ddl, &Extras::default());
        let a = &r.analysis;
        assert!(a.diagnostics.is_empty(), "{:?}", a.diagnostics);
        // `t.a = :a` and `s.x = :x` keep NULL out of the rows they return.
        assert_eq!(col(a, "a"), ("unknown".into(), false));
        assert_eq!(col(a, "b"), ("text".into(), true));
        assert_eq!(col(a, "x"), ("unknown".into(), false));
        assert_eq!(col(a, "y"), ("integer".into(), true));
        assert_eq!((param(a, "a"), param(a, "x")), ("unknown".into(), "unknown".into()));
        // In a table that is not STRICT, `ANY` is a declared type with NUMERIC affinity, not a wildcard.
        let r = analyze_ddl("SELECT c FROM t", &ddl, &Extras::default());
        assert_eq!(col(&r.analysis, "c"), ("numeric".into(), true));
    }

    #[test]
    fn the_direct_entry_reads_a_schema_it_is_handed() {
        let ddl = vec![
            "CREATE TABLE todos (id uuid PRIMARY KEY NOT NULL, owner_id text NOT NULL, org_id uuid, title varchar(200) NOT NULL, done boolean NOT NULL DEFAULT 0, UNIQUE (owner_id, title))".to_string(),
            "CREATE INDEX todos_org ON todos (org_id)".to_string(),
        ];
        let sql = "SELECT t.id, t.title, t.org_id, t.done, count(*) OVER () AS n FROM todos t WHERE t.owner_id = :auth.user_id AND t.title = :title";
        let r = analyze_ddl(sql, &ddl, &Extras::default());
        let a = &r.analysis;
        assert!(a.diagnostics.is_empty(), "{:?}", a.diagnostics);
        assert_eq!(a.kind, Some(StatementKind::Select));
        assert!(r.readonly);
        assert_eq!(col(a, "id"), ("numeric".into(), false));
        assert_eq!(col(a, "title"), ("text".into(), false));
        assert_eq!(col(a, "org_id"), ("numeric".into(), true));
        assert_eq!(col(a, "n"), ("integer".into(), false));
        assert_eq!(r.declared, [Some("uuid".to_string()), Some("varchar(200)".into()), Some("uuid".into()), Some("boolean".into()), None]);
        assert_eq!(param(a, "auth.user_id"), "text");
        assert_eq!(param(a, "title"), "text");
        assert_eq!(a.cardinality, "at_most_one");
        assert_eq!(a.rewritten.sql, "SELECT t.id, t.title, t.org_id, t.done, count(*) OVER () AS n FROM todos t WHERE t.owner_id = ? AND t.title = ?");
        // A write: not read-only, and its RETURNING typed from the target.
        let r = analyze_ddl("INSERT INTO todos (id, owner_id, title) VALUES (:id, :owner, :title) RETURNING id, done", &ddl, &Extras::default());
        assert!(r.analysis.diagnostics.is_empty(), "{:?}", r.analysis.diagnostics);
        assert!(!r.readonly);
        assert_eq!((r.analysis.kind.map_or("", StatementKind::as_str), r.analysis.cardinality.as_str()), ("insert", "one"));
        // A column declared BOOLEAN is a boolean to the loader's run time, which refuses a value
        // other than 0 or 1 in it.
        assert_eq!(col(&r.analysis, "done"), ("bool".into(), false));
        // The unique keys of the table it read: the primary key's index and the UNIQUE constraint's.
        assert_eq!(r.unique_keys.len(), 1, "{:?}", r.unique_keys);
        let mut keys = r.unique_keys["todos"].clone();
        keys.sort();
        assert_eq!(keys, [vec!["id".to_string()], vec!["owner_id".into(), "title".into()], vec!["rowid".into()]]);
        // A lex error comes back as the replayed path reports it.
        let r = analyze_ddl("SELECT id FROM todos WHERE id = :a AND title = ?", &ddl, &Extras::default());
        assert_eq!(r.analysis.diagnostics.len(), 1, "{:?}", r.analysis.diagnostics);
        assert!(r.declared.is_empty() && !r.readonly);
    }

    #[test]
    fn the_unique_keys_of_every_table_read() {
        let mut schema = ddl();
        schema.push("create unique index users_lower_name on users (lower(name))".into());
        schema.push("create unique index posts_title on posts (title) where body is not null".into());
        schema.push("create table tags (label text not null, post_id integer not null, primary key (post_id, label)) without rowid".into());
        schema.push("create view titled as select p.id, p.title from posts p".into());
        let r = analyze_ddl("select t.title, (select count(*) from tags g where g.post_id = t.id) as n from titled t where exists (select 1 from users u where u.id = :id)", &schema, &Extras::default());
        assert!(r.analysis.diagnostics.is_empty(), "{:?}", r.analysis.diagnostics);
        let mut tables: Vec<&String> = r.unique_keys.keys().collect();
        tables.sort();
        // The view reads through to `posts`; a view has no keys of its own.
        assert_eq!(tables, ["posts", "tags", "users"]);
        // The INTEGER PRIMARY KEY and the UNIQUE column; an expression index is no key.
        assert_eq!(r.unique_keys["users"], [vec!["id".to_string()], vec!["email".into()]]);
        // A partial index is no key either.
        assert_eq!(r.unique_keys["posts"], [vec!["id".to_string()]]);
        // WITHOUT ROWID: no rowid, only the primary key.
        assert_eq!(r.unique_keys["tags"], [vec!["post_id".to_string(), "label".into()]]);
        // A statement that does not prepare has none.
        assert!(analyze_ddl("select nope from users", &schema, &Extras::default()).unique_keys.is_empty());
    }

    fn html() -> Extras {
        Extras { total: vec![TotalFunction { name: "reylo_html".into(), arity: 1, returns: Affinity::Text }], host: None }
    }

    #[test]
    fn a_host_function_prepares_and_is_typed_from_its_argument() {
        let r = analyze_ddl("select reylo_html(name) as h, reylo_html(email) as e, upper(reylo_html(:q)) as q from users", &ddl(), &html());
        let a = &r.analysis;
        assert!(a.diagnostics.is_empty(), "{:?}", a.diagnostics);
        assert_eq!(col(a, "h"), ("text".into(), false));
        assert_eq!(col(a, "e"), ("text".into(), true));
        // The parameter is a non-null value, so the call over it is too.
        assert_eq!(col(a, "q"), ("text".into(), false));
        assert_eq!(r.declared, [None, None, None]);
        // The same call without the registration, and with the wrong argument count: SQLite's own
        // message, at the call.
        let sql = "select id, reylo_html(name) as h from users";
        for (extras, message) in [(Extras::default(), "no such function: reylo_html"), (Extras { total: vec![TotalFunction { name: "reylo_html".into(), arity: 2, returns: Affinity::Text }], host: None }, "wrong number of arguments to function reylo_html()")] {
            let a = analyze_ddl(sql, &ddl(), &extras).analysis;
            assert_eq!(a.diagnostics.len(), 1, "{:?}", a.diagnostics);
            assert_eq!(a.diagnostics[0].message, message);
            assert_eq!((a.diagnostics[0].start, a.diagnostics[0].code), (sql.find("reylo_html").unwrap(), 6));
            assert!(a.columns.is_empty());
        }
        // Any argument count, and a schema that calls the function replays.
        let any = Extras { total: vec![TotalFunction { name: "reylo_html".into(), arity: -1, returns: Affinity::Text }], host: None };
        let mut schema = ddl();
        schema.push("create view safe_users as select id, reylo_html(name) as name from users".into());
        let a = analyze_ddl("select name, reylo_html(name, name) as twice from safe_users", &schema, &any).analysis;
        assert!(a.diagnostics.is_empty(), "{:?}", a.diagnostics);
        assert_eq!(col(&a, "name"), ("text".into(), false));
        assert_eq!(col(&a, "twice"), ("text".into(), false));
    }

    #[test]
    fn a_scalar_subquery_is_non_null_only_when_it_always_finds_one_row() {
        let a = analysis("select (select count(*) from posts p where p.user_id = u.id) as n, (select max(title) from posts) as top, (select title from posts limit 1) as one, (select count(*) from posts group by user_id) as g, (select 1) as k from users u");
        assert_eq!(col(&a, "n"), ("integer".into(), false));
        assert_eq!(col(&a, "top"), ("text".into(), true));
        assert_eq!(col(&a, "one"), ("text".into(), true));
        assert_eq!(col(&a, "g"), ("integer".into(), true));
        assert_eq!(col(&a, "k"), ("integer".into(), false));
    }

    #[test]
    fn truth_values_are_marked_and_typed_boolean() {
        let r = analyze_ddl(
            "select id = 1 as a, exists (select 1 from posts) as b, name like 'x%' as c, not (score > 1) as d, case when id > 1 then true end as e, coalesce(email is null, false) as f, email in ('a', 'b') as g, id as h, id + 1 as i, (select p.id > 1 from posts p limit 1) as j, iif(id > 1, 0, 1) as k from users",
            &ddl(),
            &Extras::default(),
        );
        assert!(r.analysis.diagnostics.is_empty(), "{:?}", r.analysis.diagnostics);
        assert_eq!(r.booleans, [true, true, true, true, true, true, true, false, false, true, false]);
        // The storage class is an integer, 0 or 1, which the type says is a boolean.
        assert_eq!(col(&r.analysis, "a"), ("bool".into(), false));
        assert_eq!(col(&r.analysis, "b"), ("bool".into(), false));
        assert_eq!(col(&r.analysis, "h"), ("integer".into(), false));
        // Through a subquery's column, and across every arm of a compound.
        let r = analyze_ddl("select t.x, t.y from (select id > 1 as x, id as y from users) t", &ddl(), &Extras::default());
        assert_eq!(r.booleans, [true, false]);
        let r = analyze_ddl("select id > 1 as x from users union all select exists (select 1 from posts) union all select 0", &ddl(), &Extras::default());
        assert_eq!(r.booleans, [false]);
        let r = analyze_ddl("select id > 1 as x from users union all select email is null from users", &ddl(), &Extras::default());
        assert_eq!(r.booleans, [true]);
        // RETURNING, and a statement that does not prepare.
        let r = analyze_ddl("insert into users (name) values ('a') returning id, id > 0 as positive", &ddl(), &Extras::default());
        assert_eq!(r.booleans, [false, true]);
        assert!(analyze_ddl("select nope from users", &ddl(), &Extras::default()).booleans.is_empty());
    }

    #[test]
    fn a_column_declared_boolean_is_typed_boolean_and_no_truth_value() {
        let ddl = vec!["CREATE TABLE flags (id INTEGER PRIMARY KEY, done BOOLEAN NOT NULL, b bool, n INTEGER, t TINYINT(1))".to_string(), "CREATE VIEW v AS SELECT done FROM flags".to_string()];
        let r = analyze_ddl("select f.done, b, n, t, f.done + 0 as plus, coalesce(b, f.done) as either, coalesce(b, 0) as zero, case when n > 0 then f.done end as c, (select done from flags limit 1) as sub, x.done as derived from flags f, (select done from flags) x", &ddl, &Extras::default());
        assert!(r.analysis.diagnostics.is_empty(), "{:?}", r.analysis.diagnostics);
        let types: Vec<String> = r.analysis.columns.iter().map(|c| affinity_of(&c.ty).unwrap_or("?").to_string()).collect();
        // `coalesce(b, 0)` is NUMERIC's number or text: a BOOLEAN column may hold 'yes'.
        assert_eq!(types, ["bool", "bool", "integer", "integer", "real", "bool", "numeric", "bool", "bool", "bool"]);
        // The truth values are the ones SQLite computes alone.
        assert_eq!(r.booleans, [false; 10]);
        // Through a view, and across a compound only where every arm is one.
        let r = analyze_ddl("select done from v", &ddl, &Extras::default());
        assert_eq!(col(&r.analysis, "done"), ("bool".into(), false));
        let r = analyze_ddl("select done from flags union all select 5", &ddl, &Extras::default());
        assert_ne!(affinity_of(&r.analysis.columns[0].ty), Some("bool"));
        let r = analyze_ddl("select done from flags union all select id > 1 from flags", &ddl, &Extras::default());
        assert_eq!(affinity_of(&r.analysis.columns[0].ty), Some("bool"));
    }

    /// A type as src/render.ts writes a SQLite one, compactly: the value `.run()` returns at the
    /// top, and what JSON writes inside a document.
    fn ts(t: &Type, in_json: bool) -> String {
        let null = |s: String, nullable: bool| if nullable { format!("{s} | null") } else { s };
        let list = |s: String| if s.contains('|') { format!("({s})[]") } else { format!("{s}[]") };
        match &t.kind {
            Kind::Json(crate::types::JsonType { content: Some(c), .. }) => ts(&c.ty, true),
            Kind::Struct(r) => {
                let fields: Vec<String> = r.fields.iter().map(|f| format!("{}: {}", f.name, null(ts(&f.ty, true), f.nullable))).collect();
                if fields.is_empty() { "Record<never, never>".into() } else { format!("{{ {} }}", fields.join("; ")) }
            }
            Kind::Array(a) => list(null(ts(&a.element.ty, true), a.element.nullable)),
            Kind::Json(crate::types::JsonType { schema: Some(_), .. }) => schema_ts(&t.schema().unwrap_or(serde_json::Value::Bool(true))),
            _ => match (affinity_of(t).unwrap_or("?"), in_json) {
                ("integer" | "real", _) | ("int8", true) => "number".into(),
                ("int8", false) => "bigint".into(),
                ("text", _) => "string".into(),
                ("numeric", _) => "number | string".into(),
                ("blob", false) => "Uint8Array".into(),
                ("bool", _) => "boolean".into(),
                _ => "unknown".into(),
            },
        }
    }

    /// The analysis's affinity name for a value of the format's type, as [`descriptor`] wrote it.
    fn affinity_of(t: &Type) -> Option<&'static str> {
        let name = t.label.as_deref().unwrap_or("");
        match &t.kind {
            // The constants a column holds, of their type's affinity.
            Kind::Enum(e) => affinity_of(&e.ty),
            Kind::Boolean(_) => Some("bool"),
            Kind::Integer(_) if name == "BIGINT" => Some("int8"),
            Kind::Integer(_) => Some("integer"),
            Kind::Float(_) => Some("real"),
            Kind::Text(_) => Some("text"),
            Kind::Bytes(_) => Some("blob"),
            Kind::Union(_) if is_boolean_declared(name) => Some("bool"),
            Kind::Union(u) if u.members.len() == 2 => Some("text"),
            Kind::Union(u) if u.members.len() == 3 => Some("real"),
            Kind::Union(_) if affinity(name) == "integer" && is_int8_declared(name) => Some("int8"),
            Kind::Union(_) => Some(affinity(name)),
            _ => None,
        }
    }

    fn schema_ts(s: &serde_json::Value) -> String {
        if let Some(any) = s["anyOf"].as_array() {
            return any.iter().map(schema_ts).collect::<Vec<_>>().join(" | ");
        }
        let kinds: Vec<&str> = match &s["type"] {
            serde_json::Value::String(k) => vec![k.as_str()],
            serde_json::Value::Array(ks) => ks.iter().filter_map(|k| k.as_str()).collect(),
            _ => return "unknown".into(),
        };
        let one = |kind: &str| match kind {
            "integer" | "number" => "number".to_string(),
            "string" => "string".into(),
            "null" => "null".into(),
            "array" => match s["prefixItems"].as_array() {
                Some(items) => format!("[{}]", items.iter().map(schema_ts).collect::<Vec<_>>().join(", ")),
                None if s["items"] == false => "[]".into(),
                None => {
                    let item = schema_ts(&s["items"]);
                    if item.contains('|') { format!("({item})[]") } else { format!("{item}[]") }
                }
            },
            "object" => match s["properties"].as_object() {
                _ if s["additionalProperties"] == false && s["properties"].as_object().is_none_or(|p| p.is_empty()) => "Record<never, never>".into(),
                Some(p) if !p.is_empty() => format!("{{ {} }}", p.iter().map(|(k, v)| format!("{k}: {}", schema_ts(v))).collect::<Vec<_>>().join("; ")),
                _ => format!("{{ [key: string]: {} }}", schema_ts(&s["additionalProperties"])),
            },
            _ => "unknown".into(),
        };
        kinds.into_iter().map(one).collect::<Vec<_>>().join(" | ")
    }

    /// Each result column as `name: type`, `| null` where it may be NULL.
    fn shown(a: &Analysis) -> String {
        assert!(a.diagnostics.is_empty(), "{:?}", a.diagnostics);
        a.columns.iter().map(|c| format!("{}: {}{}", c.name, ts(&c.ty, false), if c.nullable { " | null" } else { "" })).collect::<Vec<_>>().join("; ")
    }

    fn json_ddl() -> Vec<String> {
        vec![
            "create table users (id integer primary key, name text not null, email text unique, github_id bigint, score real, active boolean not null default 1, avatar blob, doc text, extra, n numeric)".to_string(),
            "create table posts (id integer primary key, user_id integer not null references users(id), title text not null, body text) strict".to_string(),
            "create view titled as select id, json_object('id', id, 'title', title) as post from posts".to_string(),
        ]
    }

    fn json_typed(sql: &str) -> String {
        shown(&analyze_ddl(sql, &json_ddl(), &Extras::default()).analysis)
    }

    #[test]
    fn json_whose_subtype_is_out_of_sight_is_any_json() {
        // Beside a window call, SQLite reads each aggregate back from a subquery of its own, which
        // drops the subtype: `{"ids":"[1]"}`. An aggregate that builds no JSON keeps its type.
        assert_eq!(
            json_typed("select json_object('ids', json_group_array(id)) as doc, json_array(max(json_object('t', title))) as top, json_object('n', count(*)) as counted, count(*) over () as total from posts group by user_id"),
            "doc: { ids: unknown }; top: [unknown]; counted: { n: number }; total: number"
        );
        assert_eq!(json_typed("select json_object('ids', json_group_array(id)) as doc from posts group by user_id"), "doc: { ids: number[] }");
        // A subquery's own aggregate is read where it is computed.
        assert_eq!(json_typed("select json_object('ids', json((select json_group_array(id) from posts where user_id = u.id))) as doc, rank() over () as r from users u"), "doc: { ids: number[] }; r: number");
        // `json()` is NULL where its argument is, however deep the scalar subquery.
        assert_eq!(json_typed("select json(json((select json_object('a', 1) where 0))) as v"), "v: { a: number } | null");
        assert_eq!(json_typed("select json_object('k', json(jsonb((select json_object('a', 1) where 0)))) as w"), "w: { k: { a: number } | null }");
        // A VIRTUAL generated column is computed where it is read: a JSON function's subtype is
        // still on it, and so it may be on one read from another generated column. A STORED one
        // is read back as the text it is, and so is a VIRTUAL one no function computes.
        let schema = vec!["create table d (id integer primary key, a integer not null, j text as (json_object('a', a)) virtual, js text as (json_object('a', a)) stored, jj text as (j) virtual, label text as ('#' || a) virtual)".to_string()];
        assert_eq!(shown(&analyze_ddl("select json_array(j, js, jj, label) as v from d", &schema, &Extras::default()).analysis), "v: [unknown, string | null, unknown, string | null]");
        assert_eq!(shown(&analyze_ddl("select json_object('j', j) as v from (select j from d)", &schema, &Extras::default()).analysis), "v: { j: unknown }");
    }

    #[test]
    fn a_number_beside_a_numeric_value_is_a_number_or_text() {
        let schema = vec!["create table dts (id integer primary key, d date not null, dt datetime, n integer not null, x real not null, ok boolean not null)".to_string()];
        let typed = |sql: &str| col(&analyze_ddl(sql, &schema, &Extras::default()).analysis, "v");
        // A DATE column holds the text '2024-01-01', which no number beside it converts.
        assert_eq!(typed("select ifnull(dt, 0) as v from dts"), ("numeric".into(), false));
        assert_eq!(typed("select case when ok then d else 0 end as v from dts"), ("numeric".into(), false));
        assert_eq!(typed("select coalesce(dt, 1.5) as v from dts"), ("numeric".into(), false));
        assert_eq!(typed("select coalesce(n, 1.5) as v from dts"), ("integer".into(), false));
        assert_eq!(typed("select iif(ok, n, x) as v from dts"), ("real".into(), false));
    }

    #[test]
    fn a_window_call_is_no_value_every_row_shares() {
        let count = |sql: &str| analyze_ddl(sql, &ddl(), &Extras::default()).analysis.cardinality;
        assert_eq!(count("select distinct min(1) over (order by id rows between 1 preceding and 1 preceding) as m from users"), "many");
        assert_eq!(count("select distinct max(1) filter (where id > 2) over (order by id) as m from users"), "many");
        assert_eq!(count("select distinct 1 as m from users"), "at_most_one");
    }

    #[test]
    fn a_date_conversion_newer_than_libsql_s_sqlite_is_nullable() {
        let typed = |sql: &str| col(&analyze_ddl(sql, &ddl(), &Extras::default()).analysis, "v");
        // `%G`, `%g`, `%U`, `%V` and the `floor` and `ceiling` modifiers are new in 3.46.0, and NULL
        // on libSQL's 3.45.1.
        assert_eq!(typed("select strftime('%Y-%m-%d', 'now') as v"), ("text".into(), false));
        assert_eq!(typed("select strftime('%G-W%V', 'now') as v"), ("text".into(), true));
        assert_eq!(typed("select date('now', 'start of month', '+1 month', 'floor') as v"), ("text".into(), true));
    }

    #[test]
    fn a_json_constructor_is_typed_as_the_json_it_builds() {
        // The docs' profile: SQLite answers with the text, which the run time parses. A scalar
        // subquery's JSON nests as JSON in `json()`, on every SQLite.
        let profile = "select json_object('user', json_object('id', u.id, 'name', u.name), 'posts', json((select json_group_array(json_object('id', p.id, 'title', p.title)) from posts p where p.user_id = u.id))) as profile from users u where u.id = :id";
        assert_eq!(json_typed(profile), "profile: { user: { id: number; name: string }; posts: { id: number; title: string }[] }");
        // Without `json()`, SQLite 3.54.1 nests it as its text, and 3.53.4 as JSON.
        let bare = profile.replace("json((select", "((select");
        assert_eq!(json_typed(&bare), "profile: { user: { id: number; name: string }; posts: unknown }");
        // At the top, a scalar subquery's JSON is text either way, which the run time parses.
        assert_eq!(json_typed("select (select json_group_array(id) from posts) as ids"), "ids: number[]");
        assert_eq!(json_typed("select json((select json_object('n', name) from users where id = 1)) as u"), "u: { n: string } | null");
        assert_eq!(json_typed("select json_array((select name from users where id = 1)) as a, json_group_array((select name from users where id = 1)) as g, json_group_object((select name from users where id = 1), id) as o from users"), "a: [string | null]; g: (string | null)[]; o: { [key: string]: number }");
        let a = analyze_ddl(profile, &json_ddl(), &Extras::default()).analysis;
        assert_eq!((a.columns[0].ty.kind.name(), a.cardinality.as_str()), ("json", "at_most_one"));
        // Each value as SQLite writes it there: an INTEGER, a BIGINT column's too, as a number
        // (which JSON.parse rounds past 2^53), a REAL, a TEXT, a NUMERIC as either, NULL as null,
        // a truth value as 1 or 0 and a BOOLEAN column as what it holds. A BLOB is read as JSONB
        // (`x'01'` is `true`) or is an error, and a column of no type may hold one.
        assert_eq!(
            json_typed("select json_object('i', 1, 'id', id, 'big', github_id, 'r', score, 't', name, 'e', email, 'n', n, 'nul', null, 'cmp', id > 1, 'tru', true, 'flag', active, 'b', avatar, 'any', extra) as o from users"),
            "o: { i: number; id: number; big: number | null; r: number | null; t: string; e: string | null; n: number | string | null; nul: unknown; cmp: number; tru: number; flag: number | string; b: unknown; any: unknown }"
        );
        // A JSON array of these values is a tuple; an object with a key the statement computes
        // is one of any keys.
        assert_eq!(json_typed("select json_array(id, name, email, json_array(), json_object()) as a from users"), "a: [number, string, string | null, [], Record<never, never>]");
        assert_eq!(json_typed("select json_object(name, id) as o, json_object('id', id, name, score) as m from users"), "o: { [key: string]: number }; m: { [key: string]: number | number | null }");
        // A key written twice is in the text twice, and JSON.parse keeps the last.
        assert_eq!(json_typed("select json_object('k', id, 'k', name) as o from users"), "o: { k: string }");
        // The aggregates are `[]` and `{}` over no rows, never NULL, with a FILTER or as a window.
        assert_eq!(json_typed("select json_group_array(email) as e, json_group_object(name, id) as g from users where id < 0"), "e: (string | null)[]; g: { [key: string]: number }");
        // Beside an aggregate, a window call runs over the aggregate's one row, where a bare
        // column is NULL over no rows: `[null]`.
        assert_eq!(json_typed("select json_group_array(id) filter (where id > 1) as f, json_group_array(id) over (order by id) as w from users"), "f: number[]; w: (number | null)[]");
        assert_eq!(
            // The window call makes SQLite read the FILTER aggregate back as text: `{"f":"[2,3]"}`.
            json_typed("select json_object('f', json_group_array(id) filter (where id > 1)) as f, json_object('w', json_group_array(id) over ()) as w from users"),
            "f: { f: unknown }; w: { w: unknown }"
        );
        assert_eq!(
            json_typed("select u.id, (select json_group_array(p.title) from posts p where p.user_id = u.id) as titles, (select json_group_array(p.title) from posts p where p.user_id = u.id group by p.user_id) as grouped from users u"),
            "id: number; titles: string[]; grouped: string[] | null"
        );
        // `json()` of a constructor builds the same; `jsonb_*` is a blob, read as JSON inside a
        // document and by `json()`.
        assert_eq!(json_typed("select json(json_object('a', id)) as j, json(jsonb_object('a', id)) as b, json_object('a', jsonb_array(id), 'b', jsonb(json_array(1))) as o from users"), "j: { a: number }; b: { a: number }; o: { a: [number]; b: [number] }");
        assert_eq!(json_typed("select jsonb(json_array(1)) as b, (select jsonb_group_array(id) from users) as g"), "b: Uint8Array; g: Uint8Array");
        // A column that passes built JSON through is the text, parsed all the same.
        assert_eq!(json_typed("select post from titled"), "post: { id: number; title: string }");
        assert_eq!(json_typed("with t as (select json_array(id) as x from users) select x from t"), "x: [number]");
        assert_eq!(json_typed("select max(json_array(id)) as m from users"), "m: [number] | null");
        assert_eq!(json_typed("insert into posts (user_id, title) values (1, 'a') returning json_object('id', id, 'title', title) as post"), "post: { id: number; title: string }");
    }

    #[test]
    fn a_value_nests_as_json_only_where_it_keeps_sqlites_json_subtype() {
        // Through what kept the subtype on SQLite 3.53.4 a JSON value nests as the JSON it is.
        for (expr, ty) in [
            ("coalesce(json_array(id), 'x')", "[number]"),
            ("ifnull(json_array(id), 'x')", "[number]"),
            ("nullif(json_array(id), 'x')", "[number] | null"),
            ("iif(id > 1, json_array(id), json_array(0))", "[number]"),
            ("case when id > 1 then json_object('x', id) end", "{ x: number } | null"),
            ("json_array(id) collate nocase", "[number]"),
            ("+json_array(id)", "[number]"),
            ("likely(json_array(id))", "[number]"),
            // `json()` marks a scalar subquery's JSON again, NULL where it finds no row.
            ("json((select json_object('n', name) from users u2 where u2.id = users.id))", "{ n: string } | null"),
            ("json((select json_group_array(p.id) from posts p where p.user_id = users.id order by p.id))", "number[]"),
            ("json((select json_array(1)))", "[number]"),
            // Another constructor reads the subquery's NULL as a null, and is never NULL.
            ("json_array((select name from users u2 where u2.id = users.id))", "[string | null]"),
            ("json_group_array((select name from users u2 where u2.id = users.id))", "(string | null)[]"),
            // `coalesce` never reaches an argument after one that is never NULL.
            ("coalesce(json((select json_group_array(p.id) from posts p where p.user_id = users.id)), '[]')", "number[]"),
            ("coalesce(json_object('e', email), json_array())", "{ e: string | null }"),
            ("coalesce(json((select json_group_array(p.id) from posts p where p.user_id = users.id group by p.user_id)), json_array())", "number[]"),
            // A plain value: a TEXT is a string, even one that holds JSON.
            ("doc", "string | null"),
            ("json_array(id) || ''", "string"),
            ("upper(json_array(id))", "string"),
            ("length(json_array(id))", "number"),
            ("json_type(json_array(id))", "string"),
            ("json_array_length(json_array(id))", "number"),
        ] {
            assert_eq!(json_typed(&format!("select json_object('a', {expr}) as o from users")), format!("o: {{ a: {ty} }}"), "{expr}");
        }
        // What dropped it on 3.53.4, or keeps it on one SQLite and not another, and what returns
        // any JSON: any JSON.
        for expr in [
            "x",
            "post",
            // A scalar subquery's JSON kept the subtype on 3.53.4 and lost it on 3.54.1.
            "(select json_object('n', name) from users u2 where u2.id = users.id)",
            "(select json_array(1))",
            "(select json_object('id', id) from users order by name limit 1)",
            "(select distinct json_array(id) from users)",
            "(select json_array(1) union all select json_array(2))",
            "lag(json_array(id)) over (order by id)",
            "max(json_array(id), json_array(0))",
            "cast(json_array(id) as text)",
            "doc ->> '$.a'",
            "json_pretty(json_array(1))",
            "case when id > 1 then json_array(id) else 'x' end",
            "case when id > 1 then json_array(id) else json_object('a', 1) end",
        ] {
            let sql = format!("select json_object('a', {expr}) as o from (select *, json_array(id) as x from users) users, (select post from titled)");
            assert_eq!(json_typed(&sql), "o: { a: unknown }", "{expr}");
        }
        // Any JSON a function returns, which may be the document `null` itself, however NOT NULL
        // the value it reads (`json(doc)` where `doc` holds `'null'`): a null there too.
        for expr in ["json(doc)", "json_extract(doc, '$.a')", "doc -> '$.a'", "json_set(doc, '$.a', 1)", "json_quote(name)"] {
            assert_eq!(json_typed(&format!("select json_object('a', {expr}) as o from users")), "o: { a: unknown | null }", "{expr}");
        }
        let not_null = vec!["create table js (id integer primary key, doc text not null check (json_valid(doc)), b blob not null check (json_valid(b, 8)))".to_string()];
        for (expr, ty) in [
            ("json_object('k', json(doc))", "{ k: unknown | null }"),
            ("json_object('k', doc -> '$')", "{ k: unknown | null }"),
            ("json_object('k', json_extract(doc, '$'))", "{ k: unknown | null }"),
            ("json_object('k', json(b))", "{ k: unknown | null }"),
            ("json_group_array(json(doc))", "(unknown | null)[]"),
        ] {
            assert_eq!(shown(&analyze_ddl(&format!("select {expr} as o from js"), &not_null, &Extras::default()).analysis), format!("o: {ty}"), "{expr}");
        }
        // A function the host registers over a built-in is its own, and may set the subtype.
        let host = Extras { total: vec![TotalFunction { name: "json_array".into(), arity: -1, returns: Affinity::Text }, TotalFunction { name: "html".into(), arity: 1, returns: Affinity::Text }], host: None };
        let a = analyze_ddl("select json_array(1) as a, json_object('b', html(name)) as b from users", &json_ddl(), &host).analysis;
        assert_eq!(shown(&a), "a: string; b: { b: unknown }");
    }

    #[test]
    fn a_deep_constructor_is_read_once_per_node() {
        // Each node's shape is worked out once, so a statement as deep as the engine reads takes
        // no longer than its size.
        let ddl = vec!["create table users (id integer primary key, name text not null)".to_string()];
        let deep = |open: &str, close: &str, n: usize| format!("select {}id{} as o from users", open.repeat(n), close.repeat(n));
        let started = std::time::Instant::now();
        for sql in [deep("json_object('a', ", ")", 240), deep("json_array(coalesce(length(json_object('a', ", ")), 1))", 60), deep("coalesce((select json_group_array(", ") from users), 1)", 12)] {
            let a = crate::stack::run(|| analyze_ddl(&sql, &ddl, &Extras::default()).analysis);
            assert!(a.diagnostics.is_empty(), "{:?}", a.diagnostics);
        }
        assert!(started.elapsed() < std::time::Duration::from_secs(10), "{:?}", started.elapsed());
    }

    #[test]
    fn built_json_beside_other_text_is_the_text_it_is() {
        // SQLite returns built JSON as text: where a value may be other text, it is a string.
        assert_eq!(
            json_typed("select coalesce(json_array(id), 'x') as a, case when id > 1 then json_object('a', 1) else json_object('b', 2) end as b, coalesce(doc, json_array()) as c, iif(id > 1, json_array(id), null) as d from users"),
            "a: [number]; b: string; c: string; d: [number] | null"
        );
        assert_eq!(json_typed("select json_array(id) as a from users union all select 'x'"), "a: string");
        assert_eq!(json_typed("select json_array(id) as a from users union all select null"), "a: [number] | null");
        // A parameter that may be any text the caller passes: `coalesce(:doc::nullable(text),
        // json_array())` is that text, and the parameter is a string.
        let a = marked("select coalesce(CAST(:doc AS TEXT), json_array()) as d, json_object('a', :a) as o from users where json_array(id) = :j", &json_ddl(), &["doc"]);
        assert_eq!(shown(&a), "d: string; o: { a: unknown }");
        assert_eq!(a.params.iter().map(|p| format!("{} {} {}", p.name, ts(&p.ty, false), affinity_of(&p.ty).unwrap_or(""))).collect::<Vec<_>>(), ["doc string text", "a unknown ", "j string text"]);
    }

    #[test]
    fn a_json_object_of_an_odd_count_of_arguments_is_built_in_alone() {
        let sql = "select json_object('id', id, 'name') as j from users";
        let odd = |extras: &Extras| analyze_ddl(sql, &ddl(), extras).analysis.diagnostics.iter().filter(|d| d.code == 15).count();
        assert_eq!(odd(&Extras::default()), 1);
        let listed = |arities: &[i32]| Extras { total: vec![], host: Some(arities.iter().map(|&arity| HostFunction { name: "json_object".into(), arity, kind: 's' }).collect()) };
        assert_eq!(odd(&listed(&[-1])), 1);
        // A function of the name the host registers is called in the built-in's place.
        assert_eq!(odd(&listed(&[-1, 3])), 0);
        assert_eq!(odd(&Extras { total: vec![TotalFunction { name: "JSON_OBJECT".into(), arity: 3, returns: Affinity::Text }], host: None }), 0);
    }

    #[test]
    fn a_modulo_by_a_fractional_literal_under_one_is_nullable() {
        // SQLite casts both `%` operands to INTEGER, so 0.5 truncates to 0 and the remainder is
        // NULL on every row. `/ 0.5` stays non-null: division keeps the float.
        let schema = vec!["create table items (id integer primary key, qty integer not null)".to_string()];
        let typed = |sql: &str| {
            let a = analyze_ddl(sql, &schema, &Extras::default()).analysis;
            assert!(a.diagnostics.is_empty(), "{sql}: {:?}", a.diagnostics);
            col(&a, "r")
        };
        assert_eq!(typed("select qty % 0.5 as r from items"), ("real".into(), true));
        assert_eq!(typed("select qty % 0.99 as r from items"), ("real".into(), true));
        assert_eq!(typed("select qty % 1e-3 as r from items"), ("real".into(), true));
        assert_eq!(typed("select qty % 2.5 as r from items"), ("real".into(), false));
        assert_eq!(typed("select qty % 2 as r from items"), ("integer".into(), false));
        // The cast saturates: an infinite divisor is the largest INTEGER.
        assert_eq!(typed("select qty % 1e999 as r from items"), ("real".into(), false));
        assert_eq!(typed("select qty / 0.5 as r from items"), ("real".into(), false));
        assert_eq!(typed("select qty / 0 as r from items"), ("integer".into(), true));
    }

    #[test]
    fn sqlite_only_syntax_parses() {
        let a = analysis("select id from users limit :n, :m");
        assert_eq!(param(&a, "n"), "integer");
        assert_eq!(analysis("insert or replace into users (id, name) values (:id, :name) returning id").cardinality, "one");
    }
}