icydb-core 0.144.13

IcyDB — A schema-first typed query engine and persistence runtime for Internet Computer canisters
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
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
//! Module: db::sql::lowering::tests
//! Covers SQL lowering from parsed statements into structural query shapes.
//! Does not own: production SQL lowering behavior outside this test module.
//! Boundary: verifies this module API while keeping fixture details internal.

use crate::{
    db::{
        executor::PreparedExecutionPlan,
        predicate::{CoercionId, CompareOp, ComparePredicate, MissingRowPolicy, Predicate},
        query::plan::{
            AccessPlannedQuery, AggregateKind, DeleteSpec, QueryMode,
            expr::{
                BinaryOp, CaseWhenArm, Expr, FieldId, Function, ProjectionField,
                canonicalize_grouped_having_bool_expr, canonicalize_scalar_where_bool_expr,
            },
        },
        query::{builder::FieldRef, expr::FilterExpr, intent::Query},
        sql::{
            lowering::{
                PreparedSqlScalarAggregateDescriptorShape, PreparedSqlScalarAggregatePlanFragment,
                PreparedSqlScalarAggregateStrategy, SqlCommand, SqlLoweringError,
                compile_sql_command, compile_sql_global_aggregate_command,
                lower_grouped_post_aggregate_order_expr_text,
                lower_sql_command_from_prepared_statement, lower_supported_order_expr_text,
                prepare_sql_statement,
            },
            parser::{
                SqlAggregateCall, SqlAggregateKind, SqlExplainMode, SqlExpr, SqlExprBinaryOp,
                SqlParseError, parse_sql,
            },
        },
    },
    model::field::FieldKind,
    model::index::{IndexExpression, IndexKeyItem, IndexModel},
    traits::{EntitySchema, Path},
    types::Ulid,
    value::Value,
};
use serde::Deserialize;
use std::{
    fs,
    ops::Bound,
    path::{Path as FsPath, PathBuf},
};

#[derive(Clone, Debug, Default, Deserialize, PartialEq)]
struct SqlLowerEntity {
    id: Ulid,
    name: String,
    age: u64,
}

#[derive(Clone, Debug, Default, Deserialize, PartialEq)]
struct SqlLowerExpressionEntity {
    id: Ulid,
    name: String,
    age: u64,
}

#[derive(Clone, Debug, Default, Deserialize, PartialEq)]
struct SqlLowerBoolEntity {
    id: Ulid,
    label: String,
    active: bool,
    archived: bool,
}

crate::test_canister! {
    ident = SqlLowerCanister,
    commit_memory_id = crate::testing::test_commit_memory_id(),
}

crate::test_store! {
    ident = SqlLowerDataStore,
    canister = SqlLowerCanister,
}

static SQL_LOWER_EXPRESSION_INDEX_FIELDS: [&str; 1] = ["name"];
static SQL_LOWER_EXPRESSION_INDEX_KEY_ITEMS: [IndexKeyItem; 1] =
    [IndexKeyItem::Expression(IndexExpression::Lower("name"))];
static SQL_LOWER_EXPRESSION_INDEX_MODELS: [IndexModel; 1] = [IndexModel::generated_with_key_items(
    "name_lower",
    SqlLowerDataStore::PATH,
    &SQL_LOWER_EXPRESSION_INDEX_FIELDS,
    &SQL_LOWER_EXPRESSION_INDEX_KEY_ITEMS,
    false,
)];

crate::test_entity_schema! {
    ident = SqlLowerEntity,
    id = Ulid,
    entity_name = "SqlLowerEntity",
entity_tag = crate::testing::SQL_LOWER_ENTITY_TAG,
    pk_index = 0,
    fields = [
        ("id", FieldKind::Ulid),
        ("name", FieldKind::Text { max_len: None }),
        ("age", FieldKind::Uint),
    ],
    indexes = [],
    store = SqlLowerDataStore,
    canister = SqlLowerCanister,
}

crate::test_entity_schema! {
    ident = SqlLowerExpressionEntity,
    id = Ulid,
    entity_name = "SqlLowerExpressionEntity",
    entity_tag = crate::types::EntityTag::new(0x1038),
    pk_index = 0,
    fields = [
        ("id", FieldKind::Ulid),
        ("name", FieldKind::Text { max_len: None }),
        ("age", FieldKind::Uint),
    ],
    indexes = [&SQL_LOWER_EXPRESSION_INDEX_MODELS[0]],
    store = SqlLowerDataStore,
    canister = SqlLowerCanister,
}

crate::test_entity_schema! {
    ident = SqlLowerBoolEntity,
    id = Ulid,
    entity_name = "SqlLowerBoolEntity",
    entity_tag = crate::types::EntityTag::new(0x1039),
    pk_index = 0,
    fields = [
        ("id", FieldKind::Ulid),
        ("label", FieldKind::Text { max_len: None }),
        ("active", FieldKind::Bool),
        ("archived", FieldKind::Bool),
    ],
    indexes = [],
    store = SqlLowerDataStore,
    canister = SqlLowerCanister,
}

// Lower one SQL query command and extract the normalized first ORDER BY field
// so matrix tests can assert canonical ordering without repeating unwrap steps.
fn first_lowered_order_field(sql: &str, context: &str) -> String {
    let sql_command = compile_sql_command::<SqlLowerEntity>(sql, MissingRowPolicy::Ignore)
        .unwrap_or_else(|err| panic!("{context} should lower: {err:?}"));
    let SqlCommand::Query(sql_query) = sql_command else {
        panic!("{context} should lower to a query command");
    };
    let plan = sql_query
        .plan()
        .unwrap_or_else(|err| panic!("{context} plan should build: {err:?}"))
        .into_inner();

    plan.scalar_plan()
        .order
        .as_ref()
        .unwrap_or_else(|| panic!("{context} ordering should be present"))
        .fields[0]
        .rendered_label()
}

// Build one expected planner field expression for SQL order-lowering parser
// tests without reaching back into query/plan parser helpers.
fn lowered_field(name: &str) -> Expr {
    Expr::Field(FieldId::new(name))
}

// Build one expected planner integer literal for SQL order-lowering parser
// tests.
fn lowered_int(value: i64) -> Expr {
    Expr::Literal(Value::Int(value))
}

// Build one expected planner unsigned integer literal for SQL order-lowering
// parser tests.
fn lowered_uint(value: u64) -> Expr {
    Expr::Literal(Value::Uint(value))
}

// Build one expected planner scalar function expression for SQL order-lowering
// parser tests.
fn lowered_function(function: Function, args: Vec<Expr>) -> Expr {
    Expr::FunctionCall { function, args }
}

// Build one expected planner binary expression for SQL order-lowering parser
// tests.
fn lowered_binary(op: BinaryOp, left: Expr, right: Expr) -> Expr {
    Expr::Binary {
        op,
        left: Box::new(left),
        right: Box::new(right),
    }
}

// Build one expected planner aggregate expression for SQL order-lowering
// parser tests.
fn lowered_aggregate(kind: AggregateKind, input: Expr) -> Expr {
    Expr::Aggregate(
        crate::db::query::builder::aggregate::AggregateExpr::from_expression_input(kind, input),
    )
}

// Lower one SQL command through the shared reduced SQL lane and extract the
// typed query shell so parity tests do not repeat command unwrap boilerplate.
fn compile_sql_lower_query_command(sql: &str, context: &str) -> Query<SqlLowerEntity> {
    let sql_command = compile_sql_command::<SqlLowerEntity>(sql, MissingRowPolicy::Ignore)
        .unwrap_or_else(|err| panic!("{context} should lower: {err:?}"));
    let SqlCommand::Query(sql_query) = sql_command else {
        panic!("{context} should lower to a query command");
    };

    sql_query
}

#[test]
fn sql_order_expr_text_lowers_scalar_order_terms_to_semantic_expr() {
    let expr = lower_supported_order_expr_text("ROUND((age + rank) / (age + 1), 2)")
        .expect("scalar SQL ORDER BY expression should lower");

    assert_eq!(
        expr,
        lowered_function(
            Function::Round,
            vec![
                lowered_binary(
                    BinaryOp::Div,
                    lowered_binary(BinaryOp::Add, lowered_field("age"), lowered_field("rank")),
                    lowered_binary(BinaryOp::Add, lowered_field("age"), lowered_int(1)),
                ),
                lowered_uint(2),
            ],
        ),
        "SQL ORDER BY token parsing should stay in parser while lowering preserves the semantic planner expression",
    );
}

#[test]
fn sql_order_expr_text_lowers_grouped_aggregate_order_terms_to_semantic_expr() {
    let expr = lower_grouped_post_aggregate_order_expr_text("ROUND(AVG(rank + score), 2)")
        .expect("grouped SQL ORDER BY expression should lower");

    assert_eq!(
        expr,
        lowered_function(
            Function::Round,
            vec![
                lowered_aggregate(
                    AggregateKind::Avg,
                    lowered_binary(BinaryOp::Add, lowered_field("rank"), lowered_field("score"),),
                ),
                lowered_uint(2),
            ],
        ),
        "grouped SQL ORDER BY parsing should preserve aggregate input expression structure",
    );
}

#[test]
fn sql_order_expr_text_lowers_grouped_filtered_aggregate_order_terms_to_semantic_expr() {
    let expr = lower_grouped_post_aggregate_order_expr_text(
        "COUNT(*) FILTER (WHERE IS_NOT_NULL(guild_rank))",
    )
    .expect("filtered grouped SQL ORDER BY expression should lower");

    assert_eq!(
        expr,
        Expr::Aggregate(
            crate::db::query::builder::aggregate::count().with_filter_expr(lowered_function(
                Function::IsNotNull,
                vec![lowered_field("guild_rank")],
            )),
        ),
        "grouped SQL ORDER BY parsing should preserve aggregate FILTER semantics",
    );
}

// Lower one SQL SELECT statement just through the normalized frontend lane so
// shape tests can inspect grouped keys and ORDER BY terms before planner
// validation runs.
fn lower_sql_select_shape_for_test(
    sql: &str,
    context: &str,
) -> crate::db::sql::lowering::LoweredSelectShape {
    let statement = crate::db::sql::parser::parse_sql(sql)
        .unwrap_or_else(|err| panic!("{context} should parse: {err:?}"));
    let prepared = prepare_sql_statement(&statement, SqlLowerEntity::MODEL.name())
        .unwrap_or_else(|err| panic!("{context} should prepare: {err:?}"));
    let lowered = lower_sql_command_from_prepared_statement(prepared, SqlLowerEntity::MODEL)
        .unwrap_or_else(|err| panic!("{context} should lower: {err:?}"));
    let Some(crate::db::sql::lowering::LoweredSqlQuery::Select(select)) = lowered.into_query()
    else {
        panic!("{context} should lower to one SELECT query shape");
    };

    select
}

// Lower one global aggregate SQL command through the shared reduced SQL lane
// so aggregate tests do not each repeat the same typed lowering shell.
fn compile_sql_lower_global_aggregate_command(
    sql: &str,
    context: &str,
) -> crate::db::sql::lowering::SqlGlobalAggregateCommand<SqlLowerEntity> {
    compile_sql_global_aggregate_command::<SqlLowerEntity>(sql, MissingRowPolicy::Ignore)
        .unwrap_or_else(|err| panic!("{context} should lower: {err:?}"))
}

// Strip semantic scalar filter ownership when parity tests only care about the
// canonical predicate/access/runtime contract shared across front doors.
fn strip_semantic_filter_expr_for_parity(mut plan: AccessPlannedQuery) -> AccessPlannedQuery {
    plan.scalar_plan_mut().filter_expr = None;
    plan.scalar_plan_mut().predicate_covers_filter_expr = false;

    plan
}

// Compare two typed query shells through the normalized planned intent so SQL
// parity tests can share one plan-equivalence assertion path.
fn assert_sql_lower_queries_share_plan_identity(
    left: &Query<SqlLowerEntity>,
    left_context: &str,
    right: &Query<SqlLowerEntity>,
    right_context: &str,
    message: &str,
) {
    assert_eq!(
        strip_semantic_filter_expr_for_parity(
            left.plan()
                .unwrap_or_else(|err| panic!("{left_context} plan should build: {err:?}"))
                .into_inner(),
        ),
        strip_semantic_filter_expr_for_parity(
            right
                .plan()
                .unwrap_or_else(|err| panic!("{right_context} plan should build: {err:?}"))
                .into_inner(),
        ),
        "{message}",
    );
}

// Compare two typed query shells through their deterministic query hash so SQL
// parity tests can share one fingerprint-equivalence assertion path.
fn assert_sql_lower_queries_share_plan_hash(
    left: &Query<SqlLowerEntity>,
    left_context: &str,
    right: &Query<SqlLowerEntity>,
    right_context: &str,
    message: &str,
) {
    assert_eq!(
        left.plan_hash_hex()
            .unwrap_or_else(|err| panic!("{left_context} plan hash should build: {err:?}")),
        right
            .plan_hash_hex()
            .unwrap_or_else(|err| panic!("{right_context} plan hash should build: {err:?}")),
        "{message}",
    );
}

// Compare two typed query shells at the structural query-cache boundary so
// SQL canonicalization tests exercise the exact input identity used before
// access planning or executor preparation.
fn assert_sql_lower_queries_share_structural_cache_key(
    left: &Query<SqlLowerEntity>,
    right: &Query<SqlLowerEntity>,
    message: &str,
) {
    assert_eq!(
        left.structural().structural_cache_key(),
        right.structural().structural_cache_key(),
        "{message}",
    );
}

// Lower two SQL query shells and assert their pre-planning structural query
// cache keys are identical. This keeps SQL syntax-convergence coverage on the
// same semantic identity boundary used by shared query-plan caching.
fn assert_sql_lower_queries_share_structural_cache_key_for_sql(
    left_sql: &str,
    left_context: &str,
    right_sql: &str,
    right_context: &str,
    message: &str,
) {
    let left_query = compile_sql_lower_query_command(left_sql, left_context);
    let right_query = compile_sql_lower_query_command(right_sql, right_context);

    assert_sql_lower_queries_share_structural_cache_key(&left_query, &right_query, message);
}

// Compare two typed query shells through their prepared execution contracts so
// parity tests can share one route/runtime identity assertion path.
fn assert_sql_lower_queries_share_executable_identity(
    left: &Query<SqlLowerEntity>,
    left_context: &str,
    right: &Query<SqlLowerEntity>,
    right_context: &str,
    family_message: &str,
    ordering_message: &str,
) {
    let left_executable = PreparedExecutionPlan::from(
        left.plan()
            .unwrap_or_else(|err| panic!("{left_context} executable plan should build: {err:?}")),
    );
    let right_executable = PreparedExecutionPlan::from(
        right
            .plan()
            .unwrap_or_else(|err| panic!("{right_context} executable plan should build: {err:?}")),
    );

    assert_eq!(left_executable.mode(), right_executable.mode());
    assert_eq!(left_executable.is_grouped(), right_executable.is_grouped());
    assert_eq!(left_executable.access(), right_executable.access());
    assert_eq!(
        left_executable.consistency(),
        right_executable.consistency()
    );
    assert_eq!(
        left_executable
            .execution_family()
            .unwrap_or_else(|err| panic!("{left_context} execution family should build: {err:?}")),
        right_executable.execution_family().unwrap_or_else(|err| {
            panic!("{right_context} execution family should build: {err:?}")
        }),
        "{family_message}",
    );
    assert_eq!(
        left_executable.execution_ordering().unwrap_or_else(|err| {
            panic!("{left_context} execution ordering should build: {err:?}")
        }),
        right_executable.execution_ordering().unwrap_or_else(|err| {
            panic!("{right_context} execution ordering should build: {err:?}")
        }),
        "{ordering_message}",
    );
}

// Lower one SQL query shell and compare it to the equivalent fluent query
// through the normalized planned intent so parity tests can share one path.
fn assert_sql_lower_query_matches_fluent_plan(
    sql: &str,
    sql_context: &str,
    fluent_query: &Query<SqlLowerEntity>,
    fluent_context: &str,
    message: &str,
) {
    let sql_query = compile_sql_lower_query_command(sql, sql_context);

    assert_sql_lower_queries_share_plan_identity(
        &sql_query,
        sql_context,
        fluent_query,
        fluent_context,
        message,
    );
}

// Lower two SQL query shells and compare them through the normalized planned
// intent so SQL-only parity tests can reuse the same assertion path.
fn assert_sql_lower_query_matches_sql_plan(
    left_sql: &str,
    left_context: &str,
    right_sql: &str,
    right_context: &str,
    message: &str,
) {
    let left_query = compile_sql_lower_query_command(left_sql, left_context);
    let right_query = compile_sql_lower_query_command(right_sql, right_context);

    assert_sql_lower_queries_share_plan_identity(
        &left_query,
        left_context,
        &right_query,
        right_context,
        message,
    );
}

// Lower one SQL query shell and assert its normalized plan builds so structural
// admission tests do not repeat the same query extraction boilerplate.
fn assert_sql_lower_query_plan_builds(sql: &str, context: &str) {
    compile_sql_lower_query_command(sql, context)
        .plan()
        .unwrap_or_else(|err| panic!("{context} plan should build: {err:?}"));
}

#[test]
fn compile_sql_command_select_star_lowers_to_load_query() {
    let command = compile_sql_command::<SqlLowerEntity>(
        "SELECT * FROM SqlLowerEntity WHERE age >= 21 ORDER BY age DESC LIMIT 10 OFFSET 1",
        MissingRowPolicy::Ignore,
    )
    .expect("SELECT * should lower");

    let SqlCommand::Query(query) = command else {
        panic!("expected lowered query command");
    };

    assert!(matches!(query.mode(), QueryMode::Load(_)));
}

#[test]
fn compile_sql_command_select_preserves_scalar_where_filter_expr_ownership() {
    let sql_query = compile_sql_lower_query_command(
        "SELECT * FROM SqlLowerEntity WHERE age >= 21",
        "scalar WHERE SQL query",
    );
    let plan = sql_query
        .plan()
        .expect("scalar WHERE SQL plan should build")
        .into_inner();

    assert!(
        matches!(
            plan.scalar_plan().filter_expr.as_ref(),
            Some(Expr::Binary {
                op: BinaryOp::Gte,
                left,
                right,
            }) if left.as_ref() == &Expr::Field(FieldId::new("age"))
                && right.as_ref() == &Expr::Literal(Value::Uint(21))
        ),
        "reduced SQL lowering should preserve one planner-owned scalar WHERE expression and keep direct compare literals canonicalized to the resolved field kind",
    );
    assert!(
        plan.scalar_plan().predicate.is_some(),
        "the current 0.100 slice should still derive the existing predicate contract for access planning and runtime fast paths",
    );
}

#[test]
fn compile_sql_command_equivalent_compare_orderings_share_structural_cache_key() {
    assert_sql_lower_queries_share_structural_cache_key_for_sql(
        "SELECT * FROM SqlLowerEntity WHERE age >= 21 ORDER BY name ASC LIMIT 3",
        "field-leading compare SQL",
        "SELECT * FROM SqlLowerEntity WHERE 21 <= age ORDER BY name ASC LIMIT 3",
        "literal-leading compare SQL",
        "field-leading and literal-leading compares should lower to the same structural query cache key",
    );
}

#[test]
fn compile_sql_command_equivalent_function_predicates_share_structural_cache_key() {
    assert_sql_lower_queries_share_structural_cache_key_for_sql(
        "SELECT * FROM SqlLowerEntity WHERE name LIKE 'Al%' ORDER BY age DESC LIMIT 2",
        "LIKE prefix SQL",
        "SELECT * FROM SqlLowerEntity WHERE STARTS_WITH(name, 'Al') ORDER BY age DESC LIMIT 2",
        "direct STARTS_WITH SQL",
        "LIKE prefix syntax and direct STARTS_WITH should lower to the same structural query cache key",
    );
}

#[test]
fn compile_sql_command_alias_qualified_identifiers_share_structural_cache_key() {
    assert_sql_lower_queries_share_structural_cache_key_for_sql(
        "SELECT e.name FROM SqlLowerEntity e WHERE e.age >= 21 ORDER BY e.name ASC LIMIT 5",
        "alias-qualified SQL",
        "SELECT name FROM SqlLowerEntity WHERE age >= 21 ORDER BY name ASC LIMIT 5",
        "canonical unqualified SQL",
        "alias-qualified field references should normalize away before structural query cache identity is built",
    );
}

#[test]
fn compile_sql_command_equivalent_boolean_predicates_share_structural_cache_key() {
    assert_sql_lower_queries_share_structural_cache_key_for_sql(
        "SELECT * FROM SqlLowerEntity WHERE age >= 21 AND name = 'Ada' ORDER BY age ASC LIMIT 4",
        "age then name predicate SQL",
        "SELECT * FROM SqlLowerEntity WHERE name = 'Ada' AND age >= 21 ORDER BY age ASC LIMIT 4",
        "name then age predicate SQL",
        "commuted AND children should lower to the same structural query cache key",
    );
}

#[test]
fn compile_sql_command_numeric_equality_on_uint_field_keeps_strict_plan_parity() {
    let command = compile_sql_command::<SqlLowerEntity>(
        "SELECT * FROM SqlLowerEntity WHERE age = 21 ORDER BY age ASC LIMIT 1",
        MissingRowPolicy::Ignore,
    )
    .expect("strict numeric equality on uint field should lower");

    let SqlCommand::Query(query) = command else {
        panic!("expected lowered query command");
    };

    let fluent_query = Query::<SqlLowerEntity>::new(MissingRowPolicy::Ignore)
        .filter(FieldRef::new("age").eq(21_u64))
        .order_term(crate::db::asc("age"))
        .limit(1);

    assert_eq!(
        strip_semantic_filter_expr_for_parity(
            query.plan().expect("SQL plan should build").into_inner(),
        ),
        strip_semantic_filter_expr_for_parity(
            fluent_query
                .plan()
                .expect("fluent uint-equality plan should build")
                .into_inner(),
        ),
        "SQL uint equality should canonicalize its literal onto the strict runtime field variant",
    );
}

#[test]
fn compile_sql_command_typed_fluent_filter_matches_sql_canonical_predicate() {
    let sql_command = compile_sql_command::<SqlLowerEntity>(
        "SELECT * FROM SqlLowerEntity \
         WHERE (age >= 21 AND name = 'Ada') OR age = age",
        MissingRowPolicy::Ignore,
    )
    .expect("SQL filter convergence query should lower");
    let SqlCommand::Query(sql_query) = sql_command else {
        panic!("expected lowered SQL query command");
    };
    let sql_plan = sql_query
        .plan()
        .expect("SQL filter convergence plan should build")
        .into_inner();
    let fluent_plan = Query::<SqlLowerEntity>::new(MissingRowPolicy::Ignore)
        .filter(FilterExpr::or(vec![
            FilterExpr::and(vec![
                FilterExpr::gte("age", 21_i64),
                FilterExpr::eq("name", "Ada"),
            ]),
            FilterExpr::eq_field("age", "age"),
        ]))
        .plan()
        .expect("typed fluent filter convergence plan should build")
        .into_inner();

    assert_eq!(
        sql_plan.scalar_plan().predicate,
        fluent_plan.scalar_plan().predicate,
        "typed fluent filters and SQL WHERE lowering should produce the same canonical predicate",
    );
}

#[test]
fn compile_sql_command_typed_fluent_filter_matrix_matches_sql_canonical_predicate() {
    let cases = [
        (
            "SELECT * FROM SqlLowerEntity WHERE age >= 21",
            Query::<SqlLowerEntity>::new(MissingRowPolicy::Ignore)
                .filter(FieldRef::new("age").gte(21_i64)),
            "numeric widen compare",
        ),
        (
            "SELECT * FROM SqlLowerEntity WHERE age > age",
            Query::<SqlLowerEntity>::new(MissingRowPolicy::Ignore)
                .filter(FieldRef::new("age").gt_field("age")),
            "field-to-field compare",
        ),
        (
            "SELECT * FROM SqlLowerEntity WHERE age IN (10, 20, 30)",
            Query::<SqlLowerEntity>::new(MissingRowPolicy::Ignore)
                .filter(FieldRef::new("age").in_list([10_u64, 20_u64, 30_u64])),
            "membership compare",
        ),
        (
            "SELECT * FROM SqlLowerEntity WHERE age IS NULL",
            Query::<SqlLowerEntity>::new(MissingRowPolicy::Ignore)
                .filter(FieldRef::new("age").is_null()),
            "null test",
        ),
        (
            "SELECT * FROM SqlLowerEntity WHERE name ILIKE 'al%'",
            Query::<SqlLowerEntity>::new(MissingRowPolicy::Ignore)
                .filter(FieldRef::new("name").text_starts_with_ci("al")),
            "text casefold prefix",
        ),
    ];

    for (sql, fluent_query, context) in cases {
        let sql_command = compile_sql_command::<SqlLowerEntity>(sql, MissingRowPolicy::Ignore)
            .unwrap_or_else(|err| panic!("{context} SQL query should lower: {err:?}"));
        let SqlCommand::Query(sql_query) = sql_command else {
            panic!("expected lowered SQL query command for {context}");
        };
        let sql_plan = sql_query
            .plan()
            .unwrap_or_else(|err| panic!("{context} SQL plan should build: {err:?}"))
            .into_inner();
        let fluent_plan = fluent_query
            .plan()
            .unwrap_or_else(|err| panic!("{context} fluent plan should build: {err:?}"))
            .into_inner();

        assert_eq!(
            sql_plan.scalar_plan().predicate,
            fluent_plan.scalar_plan().predicate,
            "{context} should produce identical canonical predicates through SQL and typed fluent lowering",
        );
    }
}

#[test]
fn compile_sql_explain_numeric_equality_on_uint_field_keeps_strict_plan_parity() {
    let command = compile_sql_command::<SqlLowerEntity>(
        "EXPLAIN EXECUTION SELECT * FROM SqlLowerEntity WHERE age = 21 ORDER BY age ASC LIMIT 1",
        MissingRowPolicy::Ignore,
    )
    .expect("EXPLAIN EXECUTION with strict numeric equality on uint field should lower");

    let SqlCommand::Explain {
        mode,
        verbose: _,
        query,
    } = command
    else {
        panic!("expected lowered explain command");
    };
    assert_eq!(mode, SqlExplainMode::Execution);

    let fluent_query = Query::<SqlLowerEntity>::new(MissingRowPolicy::Ignore)
        .filter(FieldRef::new("age").eq(21_u64))
        .order_term(crate::db::asc("age"))
        .limit(1);

    assert_eq!(
        strip_semantic_filter_expr_for_parity(
            query
                .plan()
                .expect("SQL explain query plan should build")
                .into_inner(),
        ),
        strip_semantic_filter_expr_for_parity(
            fluent_query
                .plan()
                .expect("fluent uint-equality plan should build")
                .into_inner(),
        ),
        "EXPLAIN EXECUTION should reuse the same canonical uint literal lowering as plain SQL execution",
    );
}

#[test]
fn compile_sql_command_field_to_field_predicate_matches_fluent_intent() {
    let command = compile_sql_command::<SqlLowerEntity>(
        "SELECT * FROM SqlLowerEntity WHERE age > age",
        MissingRowPolicy::Ignore,
    )
    .expect("field-to-field predicate should lower");

    let SqlCommand::Query(query) = command else {
        panic!("expected lowered query command");
    };

    let fluent_query = Query::<SqlLowerEntity>::new(MissingRowPolicy::Ignore)
        .filter(crate::db::FieldRef::new("age").gt_field("age"));

    assert_eq!(
        query.plan().expect("SQL plan should build").into_inner(),
        fluent_query
            .plan()
            .expect("fluent field-to-field plan should build")
            .into_inner(),
        "field-to-field SQL lowering should match the canonical fluent predicate leaf",
    );
}

#[test]
fn compile_sql_command_select_distinct_star_lowers_to_distinct_query() {
    let command = compile_sql_command::<SqlLowerEntity>(
        "SELECT DISTINCT * FROM SqlLowerEntity",
        MissingRowPolicy::Ignore,
    )
    .expect("SELECT DISTINCT * should lower");

    let SqlCommand::Query(query) = command else {
        panic!("expected lowered query command");
    };

    assert!(
        query
            .explain()
            .expect("distinct explain should build")
            .distinct(),
        "SELECT DISTINCT * should preserve scalar distinct intent",
    );
}

#[test]
fn compile_sql_command_select_distinct_with_pk_field_list_lowers_to_distinct_query() {
    let command = compile_sql_command::<SqlLowerEntity>(
        "SELECT DISTINCT id, age FROM SqlLowerEntity",
        MissingRowPolicy::Ignore,
    )
    .expect("SELECT DISTINCT with PK-projected field list should lower");

    let SqlCommand::Query(query) = command else {
        panic!("expected lowered query command");
    };

    assert!(
        query
            .explain()
            .expect("distinct explain should build")
            .distinct(),
        "SELECT DISTINCT field-list including PK should preserve scalar distinct intent",
    );
}

#[test]
fn compile_sql_command_select_distinct_without_pk_projection_lowers_to_distinct_query() {
    let command = compile_sql_command::<SqlLowerEntity>(
        "SELECT DISTINCT age FROM SqlLowerEntity",
        MissingRowPolicy::Ignore,
    )
    .expect("SELECT DISTINCT without PK in projection should lower");

    let SqlCommand::Query(query) = command else {
        panic!("expected lowered query command");
    };

    assert!(
        query
            .explain()
            .expect("distinct explain should build")
            .distinct(),
        "SELECT DISTINCT field-list without PK should preserve scalar distinct intent",
    );
}

#[test]
fn compile_sql_command_order_by_field_alias_matches_canonical_order_target() {
    let alias_command = compile_sql_command::<SqlLowerEntity>(
        "SELECT name AS display_name FROM SqlLowerEntity ORDER BY display_name ASC LIMIT 2",
        MissingRowPolicy::Ignore,
    )
    .expect("ORDER BY field alias should lower");
    let canonical_command = compile_sql_command::<SqlLowerEntity>(
        "SELECT name FROM SqlLowerEntity ORDER BY name ASC LIMIT 2",
        MissingRowPolicy::Ignore,
    )
    .expect("canonical ORDER BY field should lower");

    let SqlCommand::Query(alias_query) = alias_command else {
        panic!("expected lowered field-alias query command");
    };
    let SqlCommand::Query(canonical_query) = canonical_command else {
        panic!("expected lowered canonical query command");
    };

    let alias_plan = alias_query
        .plan()
        .expect("field alias plan should build")
        .into_inner();
    let canonical_plan = canonical_query
        .plan()
        .expect("canonical field plan should build")
        .into_inner();

    assert_eq!(
        alias_plan.scalar_plan().order,
        canonical_plan.scalar_plan().order,
        "ORDER BY field aliases should normalize onto the same canonical logical order target",
    );
    assert_eq!(
        alias_plan.resolved_order(),
        canonical_plan.resolved_order(),
        "ORDER BY field aliases should preserve the same executor-facing resolved order contract",
    );
}

#[test]
fn compile_sql_command_normalizes_order_by_alias_for_supported_scalar_text_targets() {
    for (sql, expected_order_field, context) in [
        (
            "SELECT TRIM(name) AS trimmed_name FROM SqlLowerEntity ORDER BY trimmed_name ASC LIMIT 2",
            "TRIM(name)",
            "ORDER BY TRIM alias",
        ),
        (
            "SELECT LTRIM(name) AS left_trimmed_name FROM SqlLowerEntity ORDER BY left_trimmed_name ASC LIMIT 2",
            "LTRIM(name)",
            "ORDER BY LTRIM alias",
        ),
        (
            "SELECT RTRIM(name) AS right_trimmed_name FROM SqlLowerEntity ORDER BY right_trimmed_name ASC LIMIT 2",
            "RTRIM(name)",
            "ORDER BY RTRIM alias",
        ),
        (
            "SELECT LENGTH(name) AS name_len FROM SqlLowerEntity ORDER BY name_len DESC LIMIT 2",
            "LENGTH(name)",
            "ORDER BY LENGTH alias",
        ),
        (
            "SELECT LEFT(name, 2) AS short_name FROM SqlLowerEntity ORDER BY short_name ASC LIMIT 2",
            "LEFT(name, 2)",
            "ORDER BY LEFT alias",
        ),
    ] {
        assert_eq!(
            first_lowered_order_field(sql, context),
            expected_order_field,
            "{context} should normalize onto the canonical scalar-function order expression",
        );
    }
}

#[test]
fn compile_sql_command_normalizes_order_by_alias_for_supported_scalar_numeric_targets() {
    for (sql, expected_order_field, context) in [
        (
            "SELECT ABS(age) AS age_abs FROM SqlLowerEntity ORDER BY age_abs ASC LIMIT 2",
            "ABS(age)",
            "ORDER BY ABS alias",
        ),
        (
            "SELECT CBRT(age) AS age_cbrt FROM SqlLowerEntity ORDER BY age_cbrt ASC LIMIT 2",
            "CBRT(age)",
            "ORDER BY CBRT alias",
        ),
        (
            "SELECT CEIL(age) AS age_ceil FROM SqlLowerEntity ORDER BY age_ceil ASC LIMIT 2",
            "CEILING(age)",
            "ORDER BY CEIL alias",
        ),
        (
            "SELECT EXP(age - age) AS age_exp FROM SqlLowerEntity ORDER BY age_exp ASC LIMIT 2",
            "EXP(age - age)",
            "ORDER BY EXP alias",
        ),
        (
            "SELECT CEILING(age) AS age_ceiling FROM SqlLowerEntity ORDER BY age_ceiling ASC LIMIT 2",
            "CEILING(age)",
            "ORDER BY CEILING alias",
        ),
        (
            "SELECT FLOOR(age) AS age_floor FROM SqlLowerEntity ORDER BY age_floor ASC LIMIT 2",
            "FLOOR(age)",
            "ORDER BY FLOOR alias",
        ),
        (
            "SELECT LN(age) AS age_ln FROM SqlLowerEntity ORDER BY age_ln ASC LIMIT 2",
            "LN(age)",
            "ORDER BY LN alias",
        ),
        (
            "SELECT LOG(2, age) AS age_log FROM SqlLowerEntity ORDER BY age_log ASC LIMIT 2",
            "LOG(2, age)",
            "ORDER BY LOG alias",
        ),
        (
            "SELECT LOG10(age) AS age_log10 FROM SqlLowerEntity ORDER BY age_log10 ASC LIMIT 2",
            "LOG10(age)",
            "ORDER BY LOG10 alias",
        ),
        (
            "SELECT LOG2(age) AS age_log2 FROM SqlLowerEntity ORDER BY age_log2 ASC LIMIT 2",
            "LOG2(age)",
            "ORDER BY LOG2 alias",
        ),
        (
            "SELECT SIGN(age - 30) AS age_sign FROM SqlLowerEntity ORDER BY age_sign ASC LIMIT 2",
            "SIGN(age - 30)",
            "ORDER BY SIGN alias",
        ),
        (
            "SELECT SQRT(age - 17) AS age_sqrt FROM SqlLowerEntity ORDER BY age_sqrt ASC LIMIT 2",
            "SQRT(age - 17)",
            "ORDER BY SQRT alias",
        ),
        (
            "SELECT MOD(age, 10) AS age_mod FROM SqlLowerEntity ORDER BY age_mod ASC LIMIT 2",
            "MOD(age, 10)",
            "ORDER BY MOD alias",
        ),
        (
            "SELECT POWER(age - 30, 2) AS age_power FROM SqlLowerEntity ORDER BY age_power ASC LIMIT 2",
            "POWER(age - 30, 2)",
            "ORDER BY POWER alias",
        ),
        (
            "SELECT POW(age - 30, 2) AS age_pow FROM SqlLowerEntity ORDER BY age_pow ASC LIMIT 2",
            "POWER(age - 30, 2)",
            "ORDER BY POW alias",
        ),
    ] {
        assert_eq!(
            first_lowered_order_field(sql, context),
            expected_order_field,
            "{context} should normalize onto the canonical scalar-function order expression",
        );
    }
}

#[test]
fn compile_sql_command_normalizes_order_by_alias_for_bounded_numeric_projection_targets() {
    for (sql, expected_order_field, context) in [
        (
            "SELECT age + 1 AS next_age FROM SqlLowerEntity ORDER BY next_age ASC LIMIT 2",
            "age + 1",
            "ORDER BY arithmetic aliases",
        ),
        (
            "SELECT age + age AS total_age FROM SqlLowerEntity ORDER BY total_age ASC LIMIT 2",
            "age + age",
            "ORDER BY field-to-field arithmetic aliases",
        ),
        (
            "SELECT ROUND(age / 3, 2) AS rounded_age FROM SqlLowerEntity ORDER BY rounded_age DESC LIMIT 2",
            "ROUND(age / 3, 2)",
            "ORDER BY ROUND aliases",
        ),
        (
            "SELECT ROUND(age + age, 2) AS rounded_total FROM SqlLowerEntity ORDER BY rounded_total DESC LIMIT 2",
            "ROUND(age + age, 2)",
            "ORDER BY ROUND(field + field) aliases",
        ),
        (
            "SELECT TRUNC(age / 3, 2) AS truncated_age FROM SqlLowerEntity ORDER BY truncated_age DESC LIMIT 2",
            "TRUNC(age / 3, 2)",
            "ORDER BY TRUNC aliases",
        ),
        (
            "SELECT TRUNCATE(age / 3, 2) AS truncated_age FROM SqlLowerEntity ORDER BY truncated_age DESC LIMIT 2",
            "TRUNC(age / 3, 2)",
            "ORDER BY TRUNCATE aliases",
        ),
    ] {
        assert_eq!(
            first_lowered_order_field(sql, context),
            expected_order_field,
            "{context} should normalize onto the canonical internal order expression",
        );
    }
}

#[test]
fn compile_sql_command_accepts_direct_bounded_numeric_order_terms() {
    for (sql, expected_order_field, context) in [
        (
            "SELECT age FROM SqlLowerEntity ORDER BY age + 1 ASC LIMIT 2",
            "age + 1",
            "direct ORDER BY arithmetic terms",
        ),
        (
            "SELECT age FROM SqlLowerEntity ORDER BY age + age ASC LIMIT 2",
            "age + age",
            "direct ORDER BY field-to-field arithmetic terms",
        ),
        (
            "SELECT age FROM SqlLowerEntity ORDER BY ROUND(age / 3, 2) DESC LIMIT 2",
            "ROUND(age / 3, 2)",
            "direct ORDER BY ROUND terms",
        ),
    ] {
        assert_eq!(
            first_lowered_order_field(sql, context),
            expected_order_field,
            "{context} should normalize onto the canonical internal order expression",
        );
    }
}

#[test]
fn compile_sql_command_accepts_direct_scalar_function_expression_order_terms() {
    for (sql, expected_order_field, context) in [
        (
            "SELECT age FROM SqlLowerEntity ORDER BY ABS(age - 30) ASC LIMIT 2",
            "ABS(age - 30)",
            "direct ORDER BY ABS expression terms",
        ),
        (
            "SELECT age FROM SqlLowerEntity ORDER BY LOG(2, age + 1) ASC LIMIT 2",
            "LOG(2, age + 1)",
            "direct ORDER BY LOG expression terms",
        ),
        (
            "SELECT age FROM SqlLowerEntity ORDER BY COALESCE(NULLIF(age, 20), 99) DESC LIMIT 2",
            "COALESCE(NULLIF(age, 20), 99)",
            "direct ORDER BY COALESCE/NULLIF expression terms",
        ),
    ] {
        assert_eq!(
            first_lowered_order_field(sql, context),
            expected_order_field,
            "{context} should normalize onto the canonical internal order expression",
        );
    }
}

#[test]
fn compile_sql_command_accepts_direct_unary_text_function_expression_order_terms() {
    for (sql, expected_order_field, context) in [
        (
            "SELECT name FROM SqlLowerEntity \
             ORDER BY LOWER(COALESCE(NULLIF(name, 'alpha'), 'zzz')) ASC LIMIT 2",
            "LOWER(COALESCE(NULLIF(name, 'alpha'), 'zzz'))",
            "direct ORDER BY LOWER/COALESCE/NULLIF expression terms",
        ),
        (
            "SELECT name FROM SqlLowerEntity ORDER BY LENGTH(TRIM(name)) DESC LIMIT 2",
            "LENGTH(TRIM(name))",
            "direct ORDER BY LENGTH/TRIM expression terms",
        ),
    ] {
        assert_eq!(
            first_lowered_order_field(sql, context),
            expected_order_field,
            "{context} should normalize onto the canonical internal order expression",
        );
    }
}

#[test]
fn compile_sql_command_delete_lowers_to_delete_query() {
    let command = compile_sql_command::<SqlLowerEntity>(
        "DELETE FROM SqlLowerEntity WHERE age < 18 ORDER BY age LIMIT 3",
        MissingRowPolicy::Ignore,
    )
    .expect("DELETE should lower");

    let SqlCommand::Query(query) = command else {
        panic!("expected lowered query command");
    };

    assert!(matches!(query.mode(), QueryMode::Delete(_)));
}

#[test]
fn compile_sql_command_delete_with_offset_lowers_to_delete_query() {
    let command = compile_sql_command::<SqlLowerEntity>(
        "DELETE FROM SqlLowerEntity WHERE age < 18 ORDER BY age LIMIT 3 OFFSET 1",
        MissingRowPolicy::Ignore,
    )
    .expect("DELETE with OFFSET should lower");

    let SqlCommand::Query(query) = command else {
        panic!("expected lowered query command");
    };

    assert!(matches!(
        query.mode(),
        QueryMode::Delete(DeleteSpec {
            limit: Some(3),
            offset: 1,
        })
    ));
}

#[test]
fn compile_sql_command_delete_direct_starts_with_family_matches_like_delete_intent() {
    let cases = [
        (
            "DELETE FROM SqlLowerEntity WHERE STARTS_WITH(name, 'Al') ORDER BY id ASC LIMIT 1",
            "DELETE FROM SqlLowerEntity WHERE name LIKE 'Al%' ORDER BY id ASC LIMIT 1",
            "strict direct STARTS_WITH delete lowering",
        ),
        (
            "DELETE FROM SqlLowerEntity WHERE STARTS_WITH(LOWER(name), 'Al') ORDER BY id ASC LIMIT 1",
            "DELETE FROM SqlLowerEntity WHERE LOWER(name) LIKE 'Al%' ORDER BY id ASC LIMIT 1",
            "direct LOWER(field) STARTS_WITH delete lowering",
        ),
        (
            "DELETE FROM SqlLowerEntity WHERE STARTS_WITH(UPPER(name), 'AL') ORDER BY id ASC LIMIT 1",
            "DELETE FROM SqlLowerEntity WHERE UPPER(name) LIKE 'AL%' ORDER BY id ASC LIMIT 1",
            "direct UPPER(field) STARTS_WITH delete lowering",
        ),
    ];

    for (direct_sql, like_sql, context) in cases {
        let direct = compile_sql_command::<SqlLowerEntity>(direct_sql, MissingRowPolicy::Ignore)
            .expect("direct STARTS_WITH delete SQL should lower");
        let like = compile_sql_command::<SqlLowerEntity>(like_sql, MissingRowPolicy::Ignore)
            .expect("LIKE delete SQL should lower");

        let SqlCommand::Query(direct_query) = direct else {
            panic!("expected lowered query command for direct STARTS_WITH delete");
        };
        let SqlCommand::Query(like_query) = like else {
            panic!("expected lowered query command for LIKE delete");
        };

        assert!(
            matches!(direct_query.mode(), QueryMode::Delete(_)),
            "direct STARTS_WITH delete should stay on the delete query lane: {context}",
        );
        assert!(
            matches!(like_query.mode(), QueryMode::Delete(_)),
            "LIKE delete should stay on the delete query lane: {context}",
        );
        assert_eq!(
            direct_query
                .plan()
                .expect("direct STARTS_WITH delete plan should build")
                .into_inner(),
            like_query
                .plan()
                .expect("LIKE delete plan should build")
                .into_inner(),
            "bounded direct STARTS_WITH delete lowering should match the established LIKE delete intent: {context}",
        );
    }
}

#[test]
fn compile_sql_command_delete_wrapped_starts_with_family_matches_like_delete_intent() {
    let cases = [
        (
            "DELETE FROM SqlLowerEntity \
             WHERE STARTS_WITH(REPLACE(name, 'a', 'A'), 'Al') \
             ORDER BY id ASC LIMIT 1",
            "DELETE FROM SqlLowerEntity \
             WHERE REPLACE(name, 'a', 'A') LIKE 'Al%' \
             ORDER BY id ASC LIMIT 1",
            "strict wrapped STARTS_WITH delete lowering",
        ),
        (
            "DELETE FROM SqlLowerEntity \
             WHERE STARTS_WITH(LOWER(REPLACE(name, 'a', 'A')), 'al') \
             ORDER BY id ASC LIMIT 1",
            "DELETE FROM SqlLowerEntity \
             WHERE REPLACE(name, 'a', 'A') ILIKE 'al%' \
             ORDER BY id ASC LIMIT 1",
            "casefold wrapped STARTS_WITH delete lowering",
        ),
    ];

    for (direct_sql, like_sql, context) in cases {
        let direct = compile_sql_command::<SqlLowerEntity>(direct_sql, MissingRowPolicy::Ignore)
            .expect("wrapped direct STARTS_WITH delete SQL should lower");
        let like = compile_sql_command::<SqlLowerEntity>(like_sql, MissingRowPolicy::Ignore)
            .expect("wrapped LIKE delete SQL should lower");

        let SqlCommand::Query(direct_query) = direct else {
            panic!("expected lowered query command for wrapped direct STARTS_WITH delete");
        };
        let SqlCommand::Query(like_query) = like else {
            panic!("expected lowered query command for wrapped LIKE delete");
        };

        assert!(
            matches!(direct_query.mode(), QueryMode::Delete(_)),
            "wrapped direct STARTS_WITH delete should stay on the delete query lane: {context}",
        );
        assert!(
            matches!(like_query.mode(), QueryMode::Delete(_)),
            "wrapped LIKE delete should stay on the delete query lane: {context}",
        );
        assert_eq!(
            direct_query
                .plan()
                .expect("wrapped direct STARTS_WITH delete plan should build")
                .into_inner(),
            like_query
                .plan()
                .expect("wrapped LIKE delete plan should build")
                .into_inner(),
            "wrapped direct STARTS_WITH delete lowering should match the widened LIKE/ILIKE delete intent: {context}",
        );
    }
}

#[test]
fn compile_sql_command_select_expression_order_lowers_to_expression_index_range() {
    let command = compile_sql_command::<SqlLowerExpressionEntity>(
        "SELECT id FROM SqlLowerExpressionEntity ORDER BY LOWER(name) ASC LIMIT 2",
        MissingRowPolicy::Ignore,
    )
    .expect("expression-order SELECT should lower");

    let SqlCommand::Query(query) = command else {
        panic!("expected lowered query command");
    };

    let plan = query
        .plan()
        .expect("expression-order query should plan")
        .into_inner();
    let Some(spec) = plan.access.as_index_range_path() else {
        panic!("expression-order query should use one index-range access path");
    };

    assert_eq!(
        spec.index().name(),
        SQL_LOWER_EXPRESSION_INDEX_MODELS[0].name()
    );
    assert!(
        spec.prefix_values().is_empty(),
        "order-only expression fallback should not invent equality prefix values",
    );
    assert_eq!(spec.lower(), &Bound::Unbounded);
    assert_eq!(spec.upper(), &Bound::Unbounded);
}

#[test]
fn compile_sql_command_normalizes_qualified_expression_order_identifier() {
    let command = compile_sql_command::<SqlLowerExpressionEntity>(
        "SELECT id FROM public.SqlLowerExpressionEntity ORDER BY LOWER(public.SqlLowerExpressionEntity.name) ASC LIMIT 2",
        MissingRowPolicy::Ignore,
    )
    .expect("qualified expression-order SELECT should lower");

    let SqlCommand::Query(query) = command else {
        panic!("expected lowered query command");
    };
    let explain = query
        .plan()
        .expect("qualified expression order should plan")
        .explain();
    let crate::db::query::explain::ExplainOrderBy::Fields(fields) = explain.order_by() else {
        panic!("qualified expression order should survive into explain order fields");
    };

    assert_eq!(
        fields
            .iter()
            .map(crate::db::query::explain::ExplainOrder::field)
            .collect::<Vec<_>>(),
        vec!["LOWER(name)", "id"],
        "qualified expression order identifiers should normalize to model-local canonical form",
    );
}

#[test]
fn compile_sql_command_describe_lowers_to_describe_entity_lane() {
    let command = compile_sql_command::<SqlLowerEntity>(
        "DESCRIBE public.SqlLowerEntity",
        MissingRowPolicy::Ignore,
    )
    .expect("DESCRIBE should lower");

    assert!(
        matches!(command, SqlCommand::DescribeEntity),
        "DESCRIBE should lower to dedicated describe command lane",
    );
}

#[test]
fn compile_sql_command_describe_rejects_entity_mismatch() {
    let err =
        compile_sql_command::<SqlLowerEntity>("DESCRIBE DifferentEntity", MissingRowPolicy::Ignore)
            .expect_err("DESCRIBE entity mismatch should fail lowering");

    assert!(matches!(err, SqlLoweringError::EntityMismatch { .. }));
}

#[test]
fn prepare_sql_statement_rejects_parameters_before_lowering() {
    let cases = [
        (
            "SELECT * FROM SqlLowerEntity WHERE age > ?",
            "SELECT WHERE parameter",
        ),
        (
            "SELECT ? FROM SqlLowerEntity",
            "SELECT projection parameter",
        ),
        (
            "SELECT COUNT(*) FILTER (WHERE age > ?) FROM SqlLowerEntity",
            "aggregate FILTER parameter",
        ),
        (
            "SELECT age, COUNT(*) FROM SqlLowerEntity GROUP BY age HAVING COUNT(*) > ?",
            "HAVING parameter",
        ),
        (
            "DELETE FROM SqlLowerEntity WHERE age > ?",
            "DELETE WHERE parameter",
        ),
        (
            "EXPLAIN SELECT * FROM SqlLowerEntity WHERE age > ?",
            "EXPLAIN target parameter",
        ),
        (
            "INSERT INTO SqlLowerEntity (id, name, age) SELECT id, name, age FROM SqlLowerEntity WHERE age > ?",
            "INSERT SELECT source parameter",
        ),
        (
            "UPDATE SqlLowerEntity SET age = 1 WHERE age > ?",
            "UPDATE WHERE parameter",
        ),
    ];

    for (sql, context) in cases {
        let statement =
            parse_sql(sql).unwrap_or_else(|err| panic!("{context} should parse: {err}"));
        let Err(err) = prepare_sql_statement(&statement, SqlLowerEntity::MODEL.name()) else {
            panic!("{context} should fail during prepare");
        };

        assert!(
            matches!(err, SqlLoweringError::UnsupportedParameterPlacement { .. }),
            "{context} should be rejected by the prepared parameter contract: {err:?}",
        );
    }
}

#[test]
fn compile_sql_command_show_indexes_lowers_to_show_indexes_lane() {
    let command = compile_sql_command::<SqlLowerEntity>(
        "SHOW INDEXES public.SqlLowerEntity",
        MissingRowPolicy::Ignore,
    )
    .expect("SHOW INDEXES should lower");

    assert!(
        matches!(command, SqlCommand::ShowIndexesEntity),
        "SHOW INDEXES should lower to dedicated show-indexes command lane",
    );
}

#[test]
fn compile_sql_command_show_indexes_rejects_entity_mismatch() {
    let err = compile_sql_command::<SqlLowerEntity>(
        "SHOW INDEXES DifferentEntity",
        MissingRowPolicy::Ignore,
    )
    .expect_err("SHOW INDEXES entity mismatch should fail lowering");

    assert!(matches!(err, SqlLoweringError::EntityMismatch { .. }));
}

#[test]
fn compile_sql_command_show_columns_lowers_to_show_columns_lane() {
    let command = compile_sql_command::<SqlLowerEntity>(
        "SHOW COLUMNS public.SqlLowerEntity",
        MissingRowPolicy::Ignore,
    )
    .expect("SHOW COLUMNS should lower");

    assert!(
        matches!(command, SqlCommand::ShowColumnsEntity),
        "SHOW COLUMNS should lower to dedicated show-columns command lane",
    );
}

#[test]
fn compile_sql_command_show_columns_rejects_entity_mismatch() {
    let err = compile_sql_command::<SqlLowerEntity>(
        "SHOW COLUMNS DifferentEntity",
        MissingRowPolicy::Ignore,
    )
    .expect_err("SHOW COLUMNS entity mismatch should fail lowering");

    assert!(matches!(err, SqlLoweringError::EntityMismatch { .. }));
}

#[test]
fn compile_sql_command_show_entities_lowers_to_show_entities_lane() {
    let command = compile_sql_command::<SqlLowerEntity>("SHOW ENTITIES", MissingRowPolicy::Ignore)
        .expect("SHOW ENTITIES should lower");

    assert!(
        matches!(command, SqlCommand::ShowEntities),
        "SHOW ENTITIES should lower to dedicated show-entities command lane",
    );
}

#[test]
fn compile_sql_command_explain_execution_wraps_lowered_query() {
    let command = compile_sql_command::<SqlLowerEntity>(
        "EXPLAIN EXECUTION SELECT * FROM SqlLowerEntity LIMIT 1",
        MissingRowPolicy::Ignore,
    )
    .expect("EXPLAIN EXECUTION should lower");

    let SqlCommand::Explain {
        mode,
        verbose,
        query,
    } = command
    else {
        panic!("expected lowered explain command");
    };

    assert_eq!(mode, SqlExplainMode::Execution);
    assert!(!verbose);
    assert!(matches!(query.mode(), QueryMode::Load(_)));
}

#[test]
fn compile_sql_command_explain_execution_verbose_wraps_lowered_query() {
    let command = compile_sql_command::<SqlLowerEntity>(
        "EXPLAIN EXECUTION VERBOSE SELECT * FROM SqlLowerEntity LIMIT 1",
        MissingRowPolicy::Ignore,
    )
    .expect("EXPLAIN EXECUTION VERBOSE should lower");

    let SqlCommand::Explain {
        mode,
        verbose,
        query,
    } = command
    else {
        panic!("expected lowered explain command");
    };

    assert_eq!(mode, SqlExplainMode::Execution);
    assert!(verbose);
    assert!(matches!(query.mode(), QueryMode::Load(_)));
}

#[test]
fn compile_sql_command_explain_select_distinct_star_lowers_to_distinct_query() {
    let command = compile_sql_command::<SqlLowerEntity>(
        "EXPLAIN SELECT DISTINCT * FROM SqlLowerEntity",
        MissingRowPolicy::Ignore,
    )
    .expect("EXPLAIN SELECT DISTINCT * should lower");

    let SqlCommand::Explain {
        mode,
        verbose: _,
        query,
    } = command
    else {
        panic!("expected lowered explain command");
    };
    assert_eq!(mode, SqlExplainMode::Plan);
    assert!(
        query
            .explain()
            .expect("distinct explain should build")
            .distinct(),
        "EXPLAIN SELECT DISTINCT * should preserve scalar distinct intent",
    );
}

#[test]
fn compile_sql_command_explain_select_distinct_without_pk_projection_lowers() {
    let command = compile_sql_command::<SqlLowerEntity>(
        "EXPLAIN SELECT DISTINCT age FROM SqlLowerEntity",
        MissingRowPolicy::Ignore,
    )
    .expect("EXPLAIN SELECT DISTINCT without PK projection should lower");

    let SqlCommand::Explain {
        mode,
        verbose: _,
        query,
    } = command
    else {
        panic!("expected lowered explain command");
    };
    assert_eq!(mode, SqlExplainMode::Plan);
    assert!(
        query
            .explain()
            .expect("distinct explain should build")
            .distinct(),
        "EXPLAIN SELECT DISTINCT field-list without PK should preserve scalar distinct intent",
    );
}

#[test]
fn compile_sql_command_explain_global_aggregate_lowers_to_dedicated_command() {
    let command = compile_sql_command::<SqlLowerEntity>(
        "EXPLAIN SELECT COUNT(*) FROM SqlLowerEntity",
        MissingRowPolicy::Ignore,
    )
    .expect("EXPLAIN global aggregate SQL should lower");

    let SqlCommand::ExplainGlobalAggregate {
        mode,
        verbose,
        command,
    } = command
    else {
        panic!("expected lowered explain global aggregate command");
    };

    assert_eq!(mode, SqlExplainMode::Plan);
    assert!(!verbose);
    assert_count_rows_strategy(command.terminal());
}

#[test]
fn compile_sql_command_select_field_projection_lowers_to_scalar_field_selection() {
    let command = compile_sql_command::<SqlLowerEntity>(
        "SELECT name, age FROM SqlLowerEntity",
        MissingRowPolicy::Ignore,
    )
    .expect("field-list projection should lower");

    let SqlCommand::Query(query) = command else {
        panic!("expected lowered query command");
    };

    let projection = query
        .plan()
        .expect("field-list plan should build")
        .projection_spec();
    let field_names = projection
        .fields()
        .map(|field| match field {
            ProjectionField::Scalar {
                expr: Expr::Field(field),
                alias: None,
            } => field.as_str().to_string(),
            other @ ProjectionField::Scalar { .. } => {
                panic!("scalar field-list projection should lower to plain field exprs: {other:?}")
            }
        })
        .collect::<Vec<_>>();

    assert_eq!(field_names, vec!["name".to_string(), "age".to_string()]);
}

#[test]
fn compile_sql_command_select_scalar_add_projection_lowers_to_binary_expr() {
    let command = compile_sql_command::<SqlLowerEntity>(
        "SELECT age + 1 FROM SqlLowerEntity",
        MissingRowPolicy::Ignore,
    )
    .expect("scalar arithmetic projection should lower");

    let SqlCommand::Query(query) = command else {
        panic!("expected lowered query command");
    };

    let projection = query
        .plan()
        .expect("scalar arithmetic plan should build")
        .projection_spec();
    let fields = projection.fields().collect::<Vec<_>>();

    assert_eq!(fields.len(), 1);
    match fields[0] {
        ProjectionField::Scalar {
            expr:
                Expr::Binary {
                    op: crate::db::query::plan::expr::BinaryOp::Add,
                    left,
                    right,
                },
            alias: None,
        } => {
            assert!(matches!(left.as_ref(), Expr::Field(field) if field.as_str() == "age"));
            assert!(matches!(right.as_ref(), Expr::Literal(Value::Int(1))));
        }
        other @ ProjectionField::Scalar { .. } => {
            panic!("scalar arithmetic projection should lower to one add expression: {other:?}")
        }
    }
}

#[test]
fn compile_sql_command_select_scalar_field_to_field_projection_lowers_to_binary_expr() {
    let command = compile_sql_command::<SqlLowerEntity>(
        "SELECT age + age AS total FROM SqlLowerEntity",
        MissingRowPolicy::Ignore,
    )
    .expect("field-to-field arithmetic projection should lower");

    let SqlCommand::Query(query) = command else {
        panic!("expected lowered query command");
    };

    let projection = query
        .plan()
        .expect("field-to-field arithmetic plan should build")
        .projection_spec();
    let fields = projection.fields().collect::<Vec<_>>();

    assert_eq!(fields.len(), 1);
    match fields[0] {
        ProjectionField::Scalar {
            expr:
                Expr::Binary {
                    op: crate::db::query::plan::expr::BinaryOp::Add,
                    left,
                    right,
                },
            alias: Some(alias),
        } => {
            assert_eq!(alias.as_str(), "total");
            assert!(matches!(left.as_ref(), Expr::Field(field) if field.as_str() == "age"));
            assert!(matches!(right.as_ref(), Expr::Field(field) if field.as_str() == "age"));
        }
        other @ ProjectionField::Scalar { .. } => {
            panic!(
                "field-to-field arithmetic projection should lower to one add expression: {other:?}"
            )
        }
    }
}

#[test]
fn compile_sql_command_select_scalar_sub_mul_div_projection_lowers_to_binary_expr() {
    for (sql, expected_op, expected_literal, context) in [
        (
            "SELECT age - 1 FROM SqlLowerEntity",
            crate::db::query::plan::expr::BinaryOp::Sub,
            Value::Int(1),
            "subtraction projection",
        ),
        (
            "SELECT age * 2 FROM SqlLowerEntity",
            crate::db::query::plan::expr::BinaryOp::Mul,
            Value::Int(2),
            "multiplication projection",
        ),
        (
            "SELECT age / 2 FROM SqlLowerEntity",
            crate::db::query::plan::expr::BinaryOp::Div,
            Value::Int(2),
            "division projection",
        ),
    ] {
        let command = compile_sql_command::<SqlLowerEntity>(sql, MissingRowPolicy::Ignore)
            .unwrap_or_else(|err| panic!("{context} should lower: {err:?}"));

        let SqlCommand::Query(query) = command else {
            panic!("expected lowered query command");
        };

        let projection = query
            .plan()
            .unwrap_or_else(|err| panic!("{context} plan should build: {err:?}"))
            .projection_spec();
        let fields = projection.fields().collect::<Vec<_>>();

        assert_eq!(
            fields.len(),
            1,
            "{context} should lower one projection field"
        );
        match fields[0] {
            ProjectionField::Scalar {
                expr: Expr::Binary { op, left, right },
                alias: None,
            } => {
                assert_eq!(
                    *op, expected_op,
                    "{context} should preserve the arithmetic operator"
                );
                assert!(matches!(left.as_ref(), Expr::Field(field) if field.as_str() == "age"));
                assert!(
                    matches!(right.as_ref(), Expr::Literal(value) if value == &expected_literal)
                );
            }
            other @ ProjectionField::Scalar { .. } => {
                panic!("{context} should lower to one bounded binary projection: {other:?}")
            }
        }
    }
}

#[test]
fn compile_sql_command_select_scalar_round_projection_lowers_to_function_expr() {
    for (sql, expected_inner, expected_scale, context) in [
        (
            "SELECT ROUND(age, 2) FROM SqlLowerEntity",
            Expr::Field(crate::db::query::plan::expr::FieldId::new("age")),
            Value::Uint(2),
            "round over plain field",
        ),
        (
            "SELECT ROUND(age / 3, 2) FROM SqlLowerEntity",
            Expr::Binary {
                op: crate::db::query::plan::expr::BinaryOp::Div,
                left: Box::new(Expr::Field(crate::db::query::plan::expr::FieldId::new(
                    "age",
                ))),
                right: Box::new(Expr::Literal(Value::Int(3))),
            },
            Value::Uint(2),
            "round over bounded arithmetic expression",
        ),
        (
            "SELECT ROUND(age + age, 2) FROM SqlLowerEntity",
            Expr::Binary {
                op: crate::db::query::plan::expr::BinaryOp::Add,
                left: Box::new(Expr::Field(crate::db::query::plan::expr::FieldId::new(
                    "age",
                ))),
                right: Box::new(Expr::Field(crate::db::query::plan::expr::FieldId::new(
                    "age",
                ))),
            },
            Value::Uint(2),
            "round over bounded field-to-field arithmetic expression",
        ),
    ] {
        let command = compile_sql_command::<SqlLowerEntity>(sql, MissingRowPolicy::Ignore)
            .unwrap_or_else(|err| panic!("{context} should lower: {err:?}"));

        let SqlCommand::Query(query) = command else {
            panic!("expected lowered query command");
        };

        let projection = query
            .plan()
            .unwrap_or_else(|err| panic!("{context} plan should build: {err:?}"))
            .projection_spec();
        let fields = projection.fields().collect::<Vec<_>>();

        assert_eq!(
            fields.len(),
            1,
            "{context} should lower one projection field"
        );
        match fields[0] {
            ProjectionField::Scalar {
                expr: Expr::FunctionCall { function, args },
                alias: None,
            } => {
                assert_eq!(
                    *function,
                    crate::db::query::plan::expr::Function::Round,
                    "{context} should lower to canonical ROUND function",
                );
                assert_eq!(args.len(), 2, "{context} should lower two ROUND args");
                assert_eq!(
                    args[0], expected_inner,
                    "{context} should preserve inner expr"
                );
                assert_eq!(
                    args[1],
                    Expr::Literal(expected_scale.clone()),
                    "{context} should preserve round scale literal",
                );
            }
            other @ ProjectionField::Scalar { .. } => {
                panic!("{context} should lower to one ROUND function call: {other:?}")
            }
        }
    }
}

#[test]
fn compile_sql_command_select_chained_scalar_projection_lowers_to_nested_binary_expr() {
    let command = compile_sql_command::<SqlLowerEntity>(
        "SELECT age + 1 * 2 FROM SqlLowerEntity",
        MissingRowPolicy::Ignore,
    )
    .expect("chained scalar projection should lower");

    let SqlCommand::Query(query) = command else {
        panic!("expected lowered query command");
    };

    let projection = query
        .plan()
        .unwrap_or_else(|err| panic!("chained scalar projection plan should build: {err:?}"))
        .into_inner()
        .projection_selection;

    assert!(
        matches!(
            projection,
            crate::db::query::plan::expr::ProjectionSelection::Exprs(fields)
            if matches!(
                &fields[0],
            ProjectionField::Scalar {
                expr: Expr::Binary { op: BinaryOp::Add, left, right },
                alias: None,
            }
            if matches!(left.as_ref(), Expr::Field(field) if field.as_str() == "age")
                && matches!(
                    right.as_ref(),
                    Expr::Binary { op: BinaryOp::Mul, left, right }
                    if matches!(left.as_ref(), Expr::Literal(Value::Int(1)))
                        && matches!(right.as_ref(), Expr::Literal(Value::Int(2)))
                )
            )
        ),
        "chained scalar projection should lower to nested binary expressions with multiplication precedence preserved",
    );
}

#[test]
fn compile_sql_command_select_searched_case_projection_lowers_to_case_expr() {
    let command = compile_sql_command::<SqlLowerEntity>(
        "SELECT CASE WHEN age >= 21 THEN 'adult' ELSE 'minor' END FROM SqlLowerEntity",
        MissingRowPolicy::Ignore,
    )
    .expect("searched CASE projection should lower");

    let SqlCommand::Query(query) = command else {
        panic!("expected lowered query command");
    };

    let projection = query
        .plan()
        .unwrap_or_else(|err| panic!("searched CASE projection plan should build: {err:?}"))
        .into_inner()
        .projection_selection;

    assert!(
        matches!(
            projection,
            crate::db::query::plan::expr::ProjectionSelection::Exprs(fields)
                if matches!(
                    &fields[0],
                    ProjectionField::Scalar {
                        expr: Expr::Case {
                            when_then_arms,
                            else_expr,
                        },
                        alias: None,
                    }
                    if when_then_arms.as_slice() == [CaseWhenArm::new(
                        Expr::Binary {
                            op: BinaryOp::Gte,
                            left: Box::new(Expr::Field(FieldId::new("age"))),
                            right: Box::new(Expr::Literal(Value::Int(21))),
                        },
                        Expr::Literal(Value::Text("adult".to_string())),
                    )]
                        && else_expr.as_ref() == &Expr::Literal(Value::Text("minor".to_string()))
                )
        ),
        "searched CASE projection should lower onto one planner-owned CASE expression",
    );
}

#[test]
fn compile_sql_command_select_case_text_predicate_preserves_raw_target_expr() {
    let command = compile_sql_command::<SqlLowerEntity>(
        "SELECT CASE WHEN UPPER(name) LIKE 'AL%' THEN 1 ELSE 0 END FROM SqlLowerEntity",
        MissingRowPolicy::Ignore,
    )
    .expect("searched CASE text predicate projection should lower");

    let SqlCommand::Query(query) = command else {
        panic!("expected lowered query command");
    };

    let projection = query
        .plan()
        .unwrap_or_else(|err| {
            panic!("searched CASE text predicate projection plan should build: {err:?}")
        })
        .into_inner()
        .projection_selection;

    assert!(
        matches!(
            projection,
            crate::db::query::plan::expr::ProjectionSelection::Exprs(fields)
                if matches!(
                    &fields[0],
                    ProjectionField::Scalar {
                        expr: Expr::Case {
                            when_then_arms,
                            else_expr,
                        },
                        alias: None,
                    }
                    if when_then_arms.as_slice() == [CaseWhenArm::new(
                        Expr::FunctionCall {
                            function: Function::StartsWith,
                            args: vec![
                                Expr::FunctionCall {
                                    function: Function::Upper,
                                    args: vec![Expr::Field(FieldId::new("name"))],
                                },
                                Expr::Literal(Value::Text("AL".to_string())),
                            ],
                        },
                        Expr::Literal(Value::Int(1)),
                    )]
                        && else_expr.as_ref() == &Expr::Literal(Value::Int(0))
                )
        ),
        "non-WHERE expression lowering must preserve the raw text predicate target",
    );
}

#[test]
fn compile_sql_command_select_searched_case_is_null_projection_lowers_to_case_expr() {
    let command = compile_sql_command::<SqlLowerEntity>(
        "SELECT CASE WHEN name IS NULL THEN 'missing' ELSE name END FROM SqlLowerEntity",
        MissingRowPolicy::Ignore,
    )
    .expect("searched CASE projection with IS NULL should lower");

    let SqlCommand::Query(query) = command else {
        panic!("expected lowered query command");
    };

    let projection = query
        .plan()
        .unwrap_or_else(|err| panic!("searched CASE IS NULL projection plan should build: {err:?}"))
        .into_inner()
        .projection_selection;

    assert!(
        matches!(
            projection,
            crate::db::query::plan::expr::ProjectionSelection::Exprs(fields)
                if matches!(
                    &fields[0],
                    ProjectionField::Scalar {
                        expr: Expr::Case {
                            when_then_arms,
                            else_expr,
                        },
                        alias: None,
                    }
                    if when_then_arms.as_slice() == [CaseWhenArm::new(
                        Expr::FunctionCall {
                            function: Function::IsNull,
                            args: vec![Expr::Field(FieldId::new("name"))],
                        },
                        Expr::Literal(Value::Text("missing".to_string())),
                    )]
                        && else_expr.as_ref() == &Expr::Field(FieldId::new("name"))
                )
        ),
        "searched CASE IS NULL projection should lower onto one planner-owned CASE expression",
    );
}

#[test]
fn compile_sql_command_select_searched_case_without_else_canonicalizes_to_null() {
    let command = compile_sql_command::<SqlLowerEntity>(
        "SELECT CASE WHEN age >= 21 THEN 'adult' END FROM SqlLowerEntity",
        MissingRowPolicy::Ignore,
    )
    .expect("searched CASE without ELSE should lower");

    let SqlCommand::Query(query) = command else {
        panic!("expected lowered query command");
    };

    let projection = query
        .plan()
        .unwrap_or_else(|err| panic!("searched CASE without ELSE plan should build: {err:?}"))
        .into_inner()
        .projection_selection;

    assert!(
        matches!(
            projection,
            crate::db::query::plan::expr::ProjectionSelection::Exprs(fields)
                if matches!(
                    &fields[0],
                    ProjectionField::Scalar {
                        expr: Expr::Case { else_expr, .. },
                        alias: None,
                    } if else_expr.as_ref() == &Expr::Literal(Value::Null)
                )
        ),
        "searched CASE without ELSE should canonicalize onto one explicit planner NULL fallback",
    );
}

#[test]
fn compile_sql_command_select_where_searched_case_matches_null_safe_canonical_filter_expr() {
    let sql_query = compile_sql_lower_query_command(
        "SELECT * FROM SqlLowerEntity \
         WHERE CASE WHEN age >= 30 THEN TRUE ELSE age = 20 END",
        "searched CASE WHERE SQL query",
    );
    let sql_plan = sql_query
        .plan()
        .expect("searched CASE WHERE SQL plan should build")
        .into_inner();

    assert!(
        sql_plan.scalar_plan().predicate.is_none(),
        "null-safe searched CASE WHERE should stay expression-owned instead of claiming one derived predicate subset",
    );
    assert!(
        matches!(
            sql_plan.scalar_plan().filter_expr,
            Some(Expr::Binary {
                op: BinaryOp::Or,
                ref left,
                ref right,
            })
                if matches!(
                    left.as_ref(),
                    Expr::FunctionCall {
                        function: Function::Coalesce,
                        args,
                    }
                        if args.as_slice()
                            == [
                                Expr::Binary {
                                    op: BinaryOp::Gte,
                                    left: Box::new(Expr::Field(FieldId::new("age"))),
                                    right: Box::new(Expr::Literal(Value::Int(30))),
                                },
                                Expr::Literal(Value::Bool(false)),
                            ]
                )
                    && matches!(
                        right.as_ref(),
                        Expr::Binary {
                            op: BinaryOp::And,
                            left,
                            right,
                        }
                            if matches!(
                                left.as_ref(),
                                Expr::Unary {
                                    op: crate::db::query::plan::expr::UnaryOp::Not,
                                    expr,
                                }
                                    if matches!(
                                        expr.as_ref(),
                                        Expr::FunctionCall {
                                            function: Function::Coalesce,
                                            args,
                                        }
                                            if args.as_slice()
                                                == [
                                                    Expr::Binary {
                                                        op: BinaryOp::Gte,
                                                        left: Box::new(Expr::Field(FieldId::new("age"))),
                                                        right: Box::new(Expr::Literal(Value::Int(30))),
                                                    },
                                                    Expr::Literal(Value::Bool(false)),
                                                ]
                                    )
                            )
                                && right.as_ref()
                                    == &Expr::Binary {
                                        op: BinaryOp::Eq,
                                        left: Box::new(Expr::Field(FieldId::new("age"))),
                                        right: Box::new(Expr::Literal(Value::Int(20))),
                                    }
                    )
        ),
        "searched CASE WHERE should lower onto the null-safe canonical first-match boolean filter expression",
    );
}

#[test]
fn compile_sql_command_select_where_affine_numeric_compare_matches_canonical_intent() {
    let fluent_query = Query::<SqlLowerEntity>::new(MissingRowPolicy::Ignore).filter_predicate(
        Predicate::Compare(ComparePredicate::with_coercion(
            "age",
            CompareOp::Gte,
            Value::Decimal(crate::types::Decimal::from(20_u64)),
            CoercionId::NumericWiden,
        )),
    );

    let sql_query = compile_sql_lower_query_command(
        "SELECT * FROM SqlLowerEntity WHERE age + 1 >= 21",
        "affine numeric WHERE SQL query",
    );
    let mut sql_plan = sql_query
        .plan()
        .expect("affine numeric WHERE SQL plan should build")
        .into_inner();
    let mut fluent_plan = fluent_query
        .plan()
        .expect("canonical fluent WHERE plan should build")
        .into_inner();
    sql_plan.scalar_plan_mut().filter_expr = None;
    sql_plan.scalar_plan_mut().predicate_covers_filter_expr = false;
    fluent_plan.scalar_plan_mut().filter_expr = None;
    fluent_plan.scalar_plan_mut().predicate_covers_filter_expr = false;

    assert_eq!(
        sql_plan, fluent_plan,
        "simple field-plus-literal WHERE compares should still normalize onto the same canonical predicate intent once semantic filter ownership is ignored",
    );
}

#[test]
fn compile_sql_command_select_where_coalesce_and_nullif_preserves_filter_expr_with_fallback_predicate()
 {
    let sql_query = compile_sql_lower_query_command(
        "SELECT * FROM SqlLowerEntity WHERE COALESCE(NULLIF(age, 20), 99) = 99",
        "COALESCE/NULLIF WHERE SQL query",
    );
    let plan = sql_query
        .plan()
        .expect("COALESCE/NULLIF WHERE SQL plan should build")
        .into_inner();

    assert!(
        matches!(
            plan.scalar_plan().filter_expr.as_ref(),
            Some(Expr::Binary {
                op: BinaryOp::Eq,
                left,
                right,
            }) if matches!(
                left.as_ref(),
                Expr::FunctionCall {
                    function: Function::Coalesce,
                    args,
                } if matches!(
                    args.as_slice(),
                    [
                        Expr::FunctionCall {
                            function: Function::NullIf,
                            args: nullif_args,
                        },
                        Expr::Literal(Value::Int(99)),
                    ] if matches!(
                        nullif_args.as_slice(),
                        [
                            Expr::Field(field),
                            Expr::Literal(Value::Int(20)),
                        ] if *field == FieldId::new("age")
                    )
                )
            ) && right.as_ref() == &Expr::Literal(Value::Int(99))
        ),
        "COALESCE/NULLIF WHERE should preserve the semantic planner-owned filter expression through SQL lowering",
    );
    assert!(
        plan.scalar_plan().predicate.is_none(),
        "COALESCE/NULLIF WHERE should currently fall back to residual filter execution instead of claiming one derived predicate shape",
    );
}

#[test]
fn compile_sql_command_select_where_compare_constant_arguments_derive_predicate() {
    let sql_query = compile_sql_lower_query_command(
        "SELECT * FROM SqlLowerEntity WHERE name = TRIM('alpha')",
        "compare constant arguments WHERE SQL query",
    );
    let plan = sql_query
        .plan()
        .expect("compare constant arguments WHERE SQL plan should build")
        .into_inner();

    assert!(
        matches!(
            plan.scalar_plan().filter_expr.as_ref(),
            Some(Expr::Binary {
                op: BinaryOp::Eq,
                left,
                right,
            }) if left.as_ref() == &Expr::Field(FieldId::new("name"))
                && right.as_ref() == &Expr::Literal(Value::Text("alpha".to_string()))
        ),
        "compare constant arguments WHERE should preserve one folded planner-owned equality expression",
    );
    assert_eq!(
        plan.scalar_plan().predicate,
        Some(Predicate::Compare(ComparePredicate::with_coercion(
            "name",
            CompareOp::Eq,
            Value::Text("alpha".to_string()),
            CoercionId::Strict,
        ))),
        "compare constant arguments WHERE should now derive the strict field-vs-literal predicate contract after literal-only folding",
    );
}

#[test]
fn compile_sql_command_select_where_equivalent_extractable_and_shapes_share_plan_identity() {
    assert_sql_lower_query_matches_sql_plan(
        "SELECT * FROM SqlLowerEntity WHERE age = 20 AND name = 'alpha'",
        "left equivalent extractable AND WHERE SQL query",
        "SELECT * FROM SqlLowerEntity WHERE name = 'alpha' AND (age = 20)",
        "right equivalent extractable AND WHERE SQL query",
        "equivalent extractable AND WHERE SQL queries should normalize onto one identical planned filter shape",
    );
}

#[test]
fn compile_sql_command_select_where_equivalent_residual_and_shapes_share_plan_identity() {
    assert_sql_lower_query_matches_sql_plan(
        "SELECT * FROM SqlLowerEntity \
         WHERE STARTS_WITH(REPLACE(name, 'a', 'A'), TRIM('Al')) AND age = 20",
        "left equivalent residual AND WHERE SQL query",
        "SELECT * FROM SqlLowerEntity \
         WHERE age = 20 AND (STARTS_WITH(REPLACE(name, 'a', 'A'), TRIM('Al')))",
        "right equivalent residual AND WHERE SQL query",
        "equivalent residual AND WHERE SQL queries should normalize onto one identical planned filter shape",
    );
}

#[test]
fn compile_sql_command_select_where_equivalent_extractable_or_shapes_share_plan_identity() {
    assert_sql_lower_query_matches_sql_plan(
        "SELECT * FROM SqlLowerEntity WHERE age = 20 OR name = 'alpha'",
        "left equivalent extractable OR WHERE SQL query",
        "SELECT * FROM SqlLowerEntity WHERE name = 'alpha' OR (age = 20)",
        "right equivalent extractable OR WHERE SQL query",
        "equivalent extractable OR WHERE SQL queries should normalize onto one identical planned filter shape",
    );
}

#[test]
fn compile_sql_command_select_where_equivalent_residual_or_shapes_share_plan_identity() {
    assert_sql_lower_query_matches_sql_plan(
        "SELECT * FROM SqlLowerEntity \
         WHERE STARTS_WITH(REPLACE(name, 'a', 'A'), TRIM('Al')) OR age = 20",
        "left equivalent residual OR WHERE SQL query",
        "SELECT * FROM SqlLowerEntity \
         WHERE age = 20 OR (STARTS_WITH(REPLACE(name, 'a', 'A'), TRIM('Al')))",
        "right equivalent residual OR WHERE SQL query",
        "equivalent residual OR WHERE SQL queries should normalize onto one identical planned filter shape",
    );
}

#[test]
fn compile_sql_command_select_where_equivalent_mixed_extractable_shapes_share_plan_identity() {
    assert_sql_lower_query_matches_sql_plan(
        "SELECT * FROM SqlLowerEntity \
         WHERE (age = 20 AND name = 'alpha') OR age = 30",
        "left equivalent mixed extractable WHERE SQL query",
        "SELECT * FROM SqlLowerEntity \
         WHERE age = 30 OR (name = 'alpha' AND age = 20)",
        "right equivalent mixed extractable WHERE SQL query",
        "equivalent mixed extractable WHERE SQL queries should normalize onto one identical planned filter shape",
    );
}

#[test]
fn compile_sql_command_select_where_equivalent_mixed_residual_shapes_share_plan_identity() {
    assert_sql_lower_query_matches_sql_plan(
        "SELECT * FROM SqlLowerEntity \
         WHERE (age = 20 AND STARTS_WITH(REPLACE(name, 'a', 'A'), TRIM('Al'))) OR name = 'alpha'",
        "left equivalent mixed residual WHERE SQL query",
        "SELECT * FROM SqlLowerEntity \
         WHERE name = 'alpha' OR (STARTS_WITH(REPLACE(name, 'a', 'A'), TRIM('Al')) AND age = 20)",
        "right equivalent mixed residual WHERE SQL query",
        "equivalent mixed residual WHERE SQL queries should normalize onto one identical planned filter shape",
    );
}

#[test]
fn compile_sql_command_select_where_duplicate_extractable_boolean_children_collapse() {
    assert_sql_lower_query_matches_sql_plan(
        "SELECT * FROM SqlLowerEntity WHERE age = 20 AND age = 20",
        "duplicate extractable AND WHERE SQL query",
        "SELECT * FROM SqlLowerEntity WHERE age = 20",
        "canonical extractable WHERE SQL query",
        "duplicate extractable boolean children should collapse onto one canonical planned filter shape",
    );
}

#[test]
fn compile_sql_command_select_where_duplicate_residual_boolean_children_collapse() {
    assert_sql_lower_query_matches_sql_plan(
        "SELECT * FROM SqlLowerEntity \
         WHERE STARTS_WITH(REPLACE(name, 'a', 'A'), TRIM('Al')) \
           OR STARTS_WITH(REPLACE(name, 'a', 'A'), TRIM('Al'))",
        "duplicate residual OR WHERE SQL query",
        "SELECT * FROM SqlLowerEntity \
         WHERE STARTS_WITH(REPLACE(name, 'a', 'A'), TRIM('Al'))",
        "canonical residual WHERE SQL query",
        "duplicate residual boolean children should collapse onto one canonical planned filter shape",
    );
}

#[test]
fn compile_sql_command_select_where_equivalent_extractable_compare_orientations_share_plan_identity()
 {
    assert_sql_lower_query_matches_sql_plan(
        "SELECT * FROM SqlLowerEntity WHERE 20 = age",
        "literal-left extractable compare WHERE SQL query",
        "SELECT * FROM SqlLowerEntity WHERE age = 20",
        "canonical extractable compare WHERE SQL query",
        "equivalent extractable compare orientations should normalize onto one identical planned filter shape",
    );
}

#[test]
fn compile_sql_command_select_where_equivalent_residual_compare_orientations_share_plan_identity() {
    assert_sql_lower_query_matches_sql_plan(
        "SELECT * FROM SqlLowerEntity WHERE 'AlphA' = REPLACE(name, 'a', 'A')",
        "literal-left residual compare WHERE SQL query",
        "SELECT * FROM SqlLowerEntity WHERE REPLACE(name, 'a', 'A') = 'AlphA'",
        "canonical residual compare WHERE SQL query",
        "equivalent residual compare orientations should normalize onto one identical planned filter shape",
    );
}

#[test]
fn compile_sql_command_select_where_casefold_compare_constant_arguments_derive_predicate() {
    let sql_query = compile_sql_lower_query_command(
        "SELECT * FROM SqlLowerEntity WHERE LOWER(name) = TRIM('ALPHA')",
        "casefold compare constant arguments WHERE SQL query",
    );
    let plan = sql_query
        .plan()
        .expect("casefold compare constant arguments WHERE SQL plan should build")
        .into_inner();

    assert!(
        matches!(
            plan.scalar_plan().filter_expr.as_ref(),
            Some(Expr::Binary {
                op: BinaryOp::Eq,
                left,
                right,
            }) if matches!(
                left.as_ref(),
                Expr::FunctionCall {
                    function: Function::Lower,
                    args,
                } if matches!(args.as_slice(), [Expr::Field(field)] if *field == FieldId::new("name"))
            ) && right.as_ref() == &Expr::Literal(Value::Text("ALPHA".to_string()))
        ),
        "casefold compare constant arguments WHERE should preserve the semantic LOWER(field) equality expression after literal-only folding",
    );
    assert_eq!(
        plan.scalar_plan().predicate,
        Some(Predicate::Compare(ComparePredicate::with_coercion(
            "name",
            CompareOp::Eq,
            Value::Text("ALPHA".to_string()),
            CoercionId::TextCasefold,
        ))),
        "casefold compare constant arguments WHERE should now derive the existing LOWER(field)-vs-literal predicate contract after literal-only folding",
    );
}

#[test]
fn compile_sql_command_select_where_compare_and_true_constant_arguments_derive_predicate() {
    let sql_query = compile_sql_lower_query_command(
        "SELECT * FROM SqlLowerEntity \
         WHERE name = TRIM('alpha') AND NULLIF('alpha', 'alpha') IS NULL",
        "compare and true constant arguments WHERE SQL query",
    );
    let plan = sql_query
        .plan()
        .expect("compare and true constant arguments WHERE SQL plan should build")
        .into_inner();

    assert!(
        matches!(
            plan.scalar_plan().filter_expr.as_ref(),
            Some(Expr::Binary {
                op: BinaryOp::Eq,
                left,
                right,
            }) if left.as_ref() == &Expr::Field(FieldId::new("name"))
                && right.as_ref() == &Expr::Literal(Value::Text("alpha".to_string()))
        ),
        "compare and true constant arguments WHERE should simplify back to one folded planner-owned equality expression",
    );
    assert_eq!(
        plan.scalar_plan().predicate,
        Some(Predicate::Compare(ComparePredicate::with_coercion(
            "name",
            CompareOp::Eq,
            Value::Text("alpha".to_string()),
            CoercionId::Strict,
        ))),
        "compare and true constant arguments WHERE should recover the strict field-vs-literal predicate lane after boolean simplification",
    );
}

#[test]
fn compile_sql_command_select_where_compare_and_false_constant_arguments_derive_false_predicate() {
    let sql_query = compile_sql_lower_query_command(
        "SELECT * FROM SqlLowerEntity \
         WHERE name = TRIM('alpha') AND NULLIF('alpha', 'alpha') IS NOT NULL",
        "compare and false constant arguments WHERE SQL query",
    );
    let plan = sql_query
        .plan()
        .expect("compare and false constant arguments WHERE SQL plan should build")
        .into_inner();

    assert!(
        matches!(
            plan.scalar_plan().filter_expr.as_ref(),
            Some(Expr::Literal(Value::Bool(false)))
        ),
        "compare and false constant arguments WHERE should simplify all the way down to one folded FALSE filter expression",
    );
    assert_eq!(
        plan.scalar_plan().predicate,
        Some(Predicate::False),
        "compare and false constant arguments WHERE should recover the existing FALSE derived predicate lane after boolean simplification",
    );
}

#[test]
fn compile_sql_command_select_where_compare_or_false_constant_arguments_derive_predicate() {
    let sql_query = compile_sql_lower_query_command(
        "SELECT * FROM SqlLowerEntity \
         WHERE name = TRIM('alpha') OR NULLIF('alpha', 'alpha') IS NOT NULL",
        "compare or false constant arguments WHERE SQL query",
    );
    let plan = sql_query
        .plan()
        .expect("compare or false constant arguments WHERE SQL plan should build")
        .into_inner();

    assert!(
        matches!(
            plan.scalar_plan().filter_expr.as_ref(),
            Some(Expr::Binary {
                op: BinaryOp::Eq,
                left,
                right,
            }) if left.as_ref() == &Expr::Field(FieldId::new("name"))
                && right.as_ref() == &Expr::Literal(Value::Text("alpha".to_string()))
        ),
        "compare or false constant arguments WHERE should simplify back to one folded planner-owned equality expression",
    );
    assert_eq!(
        plan.scalar_plan().predicate,
        Some(Predicate::Compare(ComparePredicate::with_coercion(
            "name",
            CompareOp::Eq,
            Value::Text("alpha".to_string()),
            CoercionId::Strict,
        ))),
        "compare or false constant arguments WHERE should recover the strict field-vs-literal predicate lane after boolean simplification",
    );
}

#[test]
fn compile_sql_command_select_where_compare_or_true_constant_arguments_derive_true_filter_expr() {
    let sql_query = compile_sql_lower_query_command(
        "SELECT * FROM SqlLowerEntity \
         WHERE name = TRIM('alpha') OR NULLIF('alpha', 'alpha') IS NULL",
        "compare or true constant arguments WHERE SQL query",
    );
    let plan = sql_query
        .plan()
        .expect("compare or true constant arguments WHERE SQL plan should build")
        .into_inner();

    assert!(
        matches!(
            plan.scalar_plan().filter_expr.as_ref(),
            Some(Expr::Literal(Value::Bool(true)))
        ),
        "compare or true constant arguments WHERE should simplify all the way down to one folded TRUE filter expression",
    );
    assert_eq!(
        plan.scalar_plan().predicate,
        None,
        "compare or true constant arguments WHERE should preserve the current TRUE predicate storage behavior",
    );
}

#[test]
fn compile_sql_command_select_where_null_test_constant_arguments_derive_boolean_predicates() {
    let cases = [
        (
            "SELECT * FROM SqlLowerEntity WHERE NULLIF('alpha', 'alpha') IS NULL",
            true,
            None,
            "constant null-test WHERE that folds to TRUE",
        ),
        (
            "SELECT * FROM SqlLowerEntity WHERE NULLIF('alpha', 'alpha') IS NOT NULL",
            false,
            Some(Predicate::False),
            "constant null-test WHERE that folds to FALSE",
        ),
    ];

    for (sql, expected_value, expected_predicate, context) in cases {
        let sql_query = compile_sql_lower_query_command(sql, context);
        let plan = sql_query
            .plan()
            .unwrap_or_else(|err| panic!("{context} SQL plan should build: {err:?}"))
            .into_inner();

        assert!(
            matches!(
                plan.scalar_plan().filter_expr.as_ref(),
                Some(Expr::Literal(Value::Bool(found))) if *found == expected_value
            ),
            "{context} should preserve one folded planner-owned boolean literal expression",
        );
        assert_eq!(
            plan.scalar_plan().predicate,
            expected_predicate.clone(),
            "{context} should preserve the current folded boolean predicate storage behavior",
        );
    }
}

#[test]
fn compile_sql_command_select_where_unary_text_wrapped_value_selection_preserves_filter_expr_with_fallback_predicate()
 {
    let sql_query = compile_sql_lower_query_command(
        "SELECT * FROM SqlLowerEntity \
         WHERE LOWER(COALESCE(NULLIF(name, 'alpha'), 'zzz')) = 'zzz'",
        "unary text wrapped value-selection WHERE SQL query",
    );
    let plan = sql_query
        .plan()
        .expect("unary text wrapped value-selection WHERE SQL plan should build")
        .into_inner();

    assert!(
        matches!(
            plan.scalar_plan().filter_expr.as_ref(),
            Some(Expr::Binary {
                op: BinaryOp::Eq,
                left,
                right,
            }) if matches!(
                left.as_ref(),
                Expr::FunctionCall {
                    function: Function::Lower,
                    args,
                } if matches!(
                    args.as_slice(),
                    [Expr::FunctionCall {
                        function: Function::Coalesce,
                        args: coalesce_args,
                    }] if matches!(
                        coalesce_args.as_slice(),
                        [
                            Expr::FunctionCall {
                                function: Function::NullIf,
                                args: nullif_args,
                            },
                            Expr::Literal(Value::Text(fallback)),
                        ] if fallback == "zzz"
                            && matches!(
                                nullif_args.as_slice(),
                                [
                                    Expr::Field(field),
                                    Expr::Literal(Value::Text(excluded)),
                                ] if *field == FieldId::new("name") && excluded == "alpha"
                            )
                    )
                )
            ) && right.as_ref() == &Expr::Literal(Value::Text("zzz".to_string()))
        ),
        "unary text wrappers should preserve the semantic planner-owned filter expression through SQL lowering",
    );
    assert!(
        plan.scalar_plan().predicate.is_none(),
        "unary text wrapped value-selection WHERE should currently fall back to residual filter execution instead of claiming one derived predicate shape",
    );
}

#[test]
fn compile_sql_command_select_where_text_transform_operands_preserve_filter_expr_with_fallback_predicate()
 {
    let sql_query = compile_sql_lower_query_command(
        "SELECT * FROM SqlLowerEntity \
         WHERE REPLACE(name, 'a', 'A') = 'AlphA'",
        "text transform WHERE SQL query",
    );
    let plan = sql_query
        .plan()
        .expect("text transform WHERE SQL plan should build")
        .into_inner();
    let filter_expr = plan
        .scalar_plan()
        .filter_expr
        .as_ref()
        .expect("text transform WHERE should preserve semantic filter ownership");
    let Expr::Binary {
        op: BinaryOp::Eq,
        left,
        right,
    } = filter_expr
    else {
        panic!("text transform WHERE should lower to an equality comparison");
    };
    let Expr::FunctionCall {
        function: Function::Replace,
        args: replace_args,
    } = left.as_ref()
    else {
        panic!("text transform WHERE left operand should stay on the REPLACE(...) expression seam");
    };
    let [
        Expr::Field(field),
        Expr::Literal(Value::Text(from)),
        Expr::Literal(Value::Text(to)),
    ] = replace_args.as_slice()
    else {
        panic!("text transform WHERE should preserve the REPLACE(field, from, to) argument order");
    };

    assert_eq!(field, &FieldId::new("name"));
    assert_eq!(from, "a");
    assert_eq!(to, "A");
    assert_eq!(
        right.as_ref(),
        &Expr::Literal(Value::Text("AlphA".to_string()))
    );

    assert!(
        plan.scalar_plan().predicate.is_none(),
        "text transform WHERE should currently fall back to residual filter execution instead of claiming one derived predicate shape",
    );
}

#[test]
fn compile_sql_command_select_where_text_predicate_wrapped_transform_preserves_filter_expr_with_fallback_predicate()
 {
    let sql_query = compile_sql_lower_query_command(
        "SELECT * FROM SqlLowerEntity \
         WHERE STARTS_WITH(REPLACE(name, 'a', 'A'), 'Al')",
        "text predicate wrapped transform WHERE SQL query",
    );
    let plan = sql_query
        .plan()
        .expect("text predicate wrapped transform WHERE SQL plan should build")
        .into_inner();
    let filter_expr =
        plan.scalar_plan().filter_expr.as_ref().expect(
            "text predicate wrapped transform WHERE should preserve semantic filter ownership",
        );

    let Expr::FunctionCall {
        function: Function::StartsWith,
        args,
    } = filter_expr
    else {
        panic!("text predicate wrapped transform WHERE should lower to STARTS_WITH(...)");
    };
    let [left, Expr::Literal(Value::Text(prefix))] = args.as_slice() else {
        panic!("text predicate wrapped transform WHERE should preserve one text literal prefix");
    };
    let Expr::FunctionCall {
        function: Function::Replace,
        args: replace_args,
    } = left
    else {
        panic!(
            "text predicate wrapped transform WHERE should preserve the nested REPLACE(...) operand"
        );
    };
    let [
        Expr::Field(field),
        Expr::Literal(Value::Text(from)),
        Expr::Literal(Value::Text(to)),
    ] = replace_args.as_slice()
    else {
        panic!(
            "text predicate wrapped transform WHERE should preserve the REPLACE(field, from, to) argument order"
        );
    };

    assert_eq!(field, &FieldId::new("name"));
    assert_eq!(from, "a");
    assert_eq!(to, "A");
    assert_eq!(prefix, "Al");
    assert!(
        plan.scalar_plan().predicate.is_none(),
        "text predicate wrapped transform WHERE should currently fall back to residual filter execution instead of claiming one derived predicate shape",
    );
}

#[test]
fn compile_sql_command_select_where_text_predicate_expression_arguments_preserve_filter_expr_with_fallback_predicate()
 {
    let sql_query = compile_sql_lower_query_command(
        "SELECT * FROM SqlLowerEntity \
         WHERE STARTS_WITH(REPLACE(name, 'a', 'A'), TRIM('Al'))",
        "text predicate expression arguments WHERE SQL query",
    );
    let plan = sql_query
        .plan()
        .expect("text predicate expression arguments WHERE SQL plan should build")
        .into_inner();
    let filter_expr = plan.scalar_plan().filter_expr.as_ref().expect(
        "text predicate expression arguments WHERE should preserve semantic filter ownership",
    );

    let Expr::FunctionCall {
        function: Function::StartsWith,
        args,
    } = filter_expr
    else {
        panic!("text predicate expression arguments WHERE should lower to STARTS_WITH(...)");
    };
    let [left, right] = args.as_slice() else {
        panic!("text predicate expression arguments WHERE should preserve two operands");
    };
    let Expr::FunctionCall {
        function: Function::Replace,
        args: replace_args,
    } = left
    else {
        panic!(
            "text predicate expression arguments WHERE should preserve the nested REPLACE(...) left operand"
        );
    };
    let [
        Expr::Field(field),
        Expr::Literal(Value::Text(from)),
        Expr::Literal(Value::Text(to)),
    ] = replace_args.as_slice()
    else {
        panic!(
            "text predicate expression arguments WHERE should preserve the REPLACE(field, from, to) argument order"
        );
    };
    let Expr::Literal(Value::Text(source)) = right else {
        panic!(
            "text predicate expression arguments WHERE should fold the literal-only TRIM(...) right operand before predicate admission"
        );
    };

    assert_eq!(field, &FieldId::new("name"));
    assert_eq!(from, "a");
    assert_eq!(to, "A");
    assert_eq!(source, "Al");
    assert!(
        plan.scalar_plan().predicate.is_none(),
        "text predicate expression arguments WHERE should currently fall back to residual filter execution instead of claiming one derived predicate shape",
    );
}

#[test]
fn compile_sql_command_select_where_text_predicate_constant_arguments_derive_predicate() {
    let sql_query = compile_sql_lower_query_command(
        "SELECT * FROM SqlLowerEntity \
         WHERE STARTS_WITH(name, TRIM('Al'))",
        "text predicate constant arguments WHERE SQL query",
    );
    let plan = sql_query
        .plan()
        .expect("text predicate constant arguments WHERE SQL plan should build")
        .into_inner();

    assert!(
        matches!(
            plan.scalar_plan().filter_expr.as_ref(),
            Some(Expr::FunctionCall {
                function: Function::StartsWith,
                ..
            })
        ),
        "text predicate constant arguments WHERE should still preserve semantic filter ownership",
    );
    assert_eq!(
        plan.scalar_plan().predicate,
        Some(Predicate::Compare(ComparePredicate::with_coercion(
            "name",
            CompareOp::StartsWith,
            Value::Text("Al".to_string()),
            CoercionId::Strict,
        ))),
        "text predicate constant arguments WHERE should now derive the existing STARTS_WITH predicate contract after literal-only folding",
    );
}

#[test]
fn compile_sql_command_select_where_casefold_text_predicate_constant_arguments_derive_predicate() {
    let sql_query = compile_sql_lower_query_command(
        "SELECT * FROM SqlLowerEntity \
         WHERE STARTS_WITH(LOWER(name), TRIM('AL'))",
        "casefold text predicate constant arguments WHERE SQL query",
    );
    let plan = sql_query
        .plan()
        .expect("casefold text predicate constant arguments WHERE SQL plan should build")
        .into_inner();

    assert!(
        matches!(
            plan.scalar_plan().filter_expr.as_ref(),
            Some(Expr::FunctionCall {
                function: Function::StartsWith,
                args,
            }) if matches!(
                args.as_slice(),
                [
                    Expr::FunctionCall {
                        function: Function::Lower,
                        args: lower_args,
                    },
                    Expr::Literal(Value::Text(prefix)),
                ] if matches!(lower_args.as_slice(), [Expr::Field(field)] if *field == FieldId::new("name"))
                    && prefix == "AL"
            )
        ),
        "casefold text predicate constant arguments WHERE should preserve semantic filter ownership around LOWER(field)",
    );
    assert_eq!(
        plan.scalar_plan().predicate,
        Some(Predicate::Compare(ComparePredicate::with_coercion(
            "name",
            CompareOp::StartsWith,
            Value::Text("AL".to_string()),
            CoercionId::TextCasefold,
        ))),
        "casefold text predicate constant arguments WHERE should now derive the existing casefold STARTS_WITH predicate contract after literal-only folding",
    );
}

#[test]
fn compile_sql_command_select_where_casefold_text_predicate_and_true_constant_arguments_derive_predicate()
 {
    let sql_query = compile_sql_lower_query_command(
        "SELECT * FROM SqlLowerEntity \
         WHERE STARTS_WITH(LOWER(name), TRIM('AL')) \
           AND NULLIF('alpha', 'alpha') IS NULL",
        "casefold text predicate and true constant arguments WHERE SQL query",
    );
    let plan = sql_query
        .plan()
        .expect("casefold text predicate and true constant arguments WHERE SQL plan should build")
        .into_inner();

    assert!(
        matches!(
            plan.scalar_plan().filter_expr.as_ref(),
            Some(Expr::FunctionCall {
                function: Function::StartsWith,
                args,
            }) if matches!(
                args.as_slice(),
                [
                    Expr::FunctionCall {
                        function: Function::Lower,
                        args: lower_args,
                    },
                    Expr::Literal(Value::Text(prefix)),
                ] if matches!(lower_args.as_slice(), [Expr::Field(field)] if *field == FieldId::new("name"))
                    && prefix == "AL"
            )
        ),
        "casefold text predicate and true constant arguments WHERE should simplify back to one folded STARTS_WITH semantic filter expression",
    );
    assert_eq!(
        plan.scalar_plan().predicate,
        Some(Predicate::Compare(ComparePredicate::with_coercion(
            "name",
            CompareOp::StartsWith,
            Value::Text("AL".to_string()),
            CoercionId::TextCasefold,
        ))),
        "casefold text predicate and true constant arguments WHERE should recover the casefold STARTS_WITH predicate lane after boolean simplification",
    );
}

#[test]
fn compile_sql_command_select_where_casefold_text_predicate_or_false_constant_arguments_derive_predicate()
 {
    let sql_query = compile_sql_lower_query_command(
        "SELECT * FROM SqlLowerEntity \
         WHERE STARTS_WITH(LOWER(name), TRIM('AL')) \
           OR NULLIF('alpha', 'alpha') IS NOT NULL",
        "casefold text predicate or false constant arguments WHERE SQL query",
    );
    let plan = sql_query
        .plan()
        .expect("casefold text predicate or false constant arguments WHERE SQL plan should build")
        .into_inner();

    assert!(
        matches!(
            plan.scalar_plan().filter_expr.as_ref(),
            Some(Expr::FunctionCall {
                function: Function::StartsWith,
                args,
            }) if matches!(
                args.as_slice(),
                [
                    Expr::FunctionCall {
                        function: Function::Lower,
                        args: lower_args,
                    },
                    Expr::Literal(Value::Text(prefix)),
                ] if matches!(lower_args.as_slice(), [Expr::Field(field)] if *field == FieldId::new("name"))
                    && prefix == "AL"
            )
        ),
        "casefold text predicate or false constant arguments WHERE should simplify back to one folded STARTS_WITH semantic filter expression",
    );
    assert_eq!(
        plan.scalar_plan().predicate,
        Some(Predicate::Compare(ComparePredicate::with_coercion(
            "name",
            CompareOp::StartsWith,
            Value::Text("AL".to_string()),
            CoercionId::TextCasefold,
        ))),
        "casefold text predicate or false constant arguments WHERE should recover the casefold STARTS_WITH predicate lane after boolean simplification",
    );
}

#[test]
fn compile_sql_command_select_where_ilike_wrapped_transform_preserves_filter_expr_with_fallback_predicate()
 {
    let sql_query = compile_sql_lower_query_command(
        "SELECT * FROM SqlLowerEntity \
         WHERE REPLACE(name, 'a', 'A') ILIKE 'al%'",
        "ILIKE wrapped transform WHERE SQL query",
    );
    let plan = sql_query
        .plan()
        .expect("ILIKE wrapped transform WHERE SQL plan should build")
        .into_inner();
    let filter_expr = plan
        .scalar_plan()
        .filter_expr
        .as_ref()
        .expect("ILIKE wrapped transform WHERE should preserve semantic filter ownership");

    let Expr::FunctionCall {
        function: Function::StartsWith,
        args,
    } = filter_expr
    else {
        panic!("ILIKE wrapped transform WHERE should lower to STARTS_WITH(...)");
    };
    let [left, Expr::Literal(Value::Text(prefix))] = args.as_slice() else {
        panic!("ILIKE wrapped transform WHERE should preserve one text literal prefix");
    };
    let Expr::FunctionCall {
        function: Function::Lower,
        args: lower_args,
    } = left
    else {
        panic!("ILIKE wrapped transform WHERE should preserve LOWER(...) around the target");
    };
    let [
        Expr::FunctionCall {
            function: Function::Replace,
            args: replace_args,
        },
    ] = lower_args.as_slice()
    else {
        panic!("ILIKE wrapped transform WHERE should preserve the nested REPLACE(...) operand");
    };
    let [
        Expr::Field(field),
        Expr::Literal(Value::Text(from)),
        Expr::Literal(Value::Text(to)),
    ] = replace_args.as_slice()
    else {
        panic!(
            "ILIKE wrapped transform WHERE should preserve the REPLACE(field, from, to) argument order"
        );
    };

    assert_eq!(field, &FieldId::new("name"));
    assert_eq!(from, "a");
    assert_eq!(to, "A");
    assert_eq!(prefix, "al");
    assert!(
        plan.scalar_plan().predicate.is_none(),
        "ILIKE wrapped transform WHERE should currently fall back to residual filter execution instead of claiming one derived predicate shape",
    );
}

#[test]
fn compile_sql_command_distinguishes_is_null_from_eq_null_predicates() {
    let is_null = compile_sql_command::<SqlLowerEntity>(
        "SELECT * FROM SqlLowerEntity WHERE age IS NULL",
        MissingRowPolicy::Ignore,
    )
    .expect("IS NULL SQL query should lower");
    let eq_null = compile_sql_command::<SqlLowerEntity>(
        "SELECT * FROM SqlLowerEntity WHERE age = NULL",
        MissingRowPolicy::Ignore,
    )
    .expect("= NULL SQL query should lower");

    let SqlCommand::Query(is_null_query) = is_null else {
        panic!("expected lowered IS NULL query command");
    };
    let SqlCommand::Query(eq_null_query) = eq_null else {
        panic!("expected lowered = NULL query command");
    };

    assert_ne!(
        is_null_query
            .plan()
            .expect("IS NULL SQL plan should build")
            .into_inner(),
        eq_null_query
            .plan()
            .expect("= NULL SQL plan should build")
            .into_inner(),
        "IS NULL and = NULL should remain semantically distinct through SQL lowering",
    );
}

#[test]
fn compile_sql_command_select_where_searched_case_with_bool_field_stays_expression_owned_under_null_safe_canonicalization()
 {
    let sql_query = compile_sql_command::<SqlLowerBoolEntity>(
        "SELECT * FROM SqlLowerBoolEntity \
         WHERE CASE WHEN active THEN FALSE ELSE TRUE END",
        MissingRowPolicy::Ignore,
    )
    .expect("searched CASE bool-field WHERE SQL query should lower");
    let SqlCommand::Query(sql_query) = sql_query else {
        panic!("expected lowered searched CASE bool-field WHERE query command");
    };

    let sql_plan = sql_query
        .plan()
        .expect("searched CASE bool-field WHERE SQL plan should build")
        .into_inner();

    assert!(
        sql_plan.scalar_plan().predicate.is_none(),
        "null-safe searched CASE bool-field WHERE should stay expression-owned instead of collapsing onto the older predicate-only seam",
    );
    assert!(
        matches!(
            sql_plan.scalar_plan().filter_expr,
            Some(Expr::Binary {
                op: BinaryOp::Or,
                ref left,
                ref right,
            }) if left.as_ref() == &Expr::Literal(Value::Bool(false))
                && matches!(
                    right.as_ref(),
                    Expr::Unary {
                        op: crate::db::query::plan::expr::UnaryOp::Not,
                        expr,
                    }
                        if matches!(
                            expr.as_ref(),
                            Expr::FunctionCall {
                                function: Function::Coalesce,
                                args,
                            }
                                if args.as_slice()
                                    == [
                                        Expr::Field(FieldId::new("active")),
                                        Expr::Literal(Value::Bool(false)),
                                    ]
                        )
                )
        ),
        "null-safe searched CASE bool-field WHERE should lower onto the canonical COALESCE-backed boolean residual form",
    );
}

#[test]
fn compile_sql_command_select_where_is_true_matches_bare_bool_field_plan_identity() {
    let wrapped_query = compile_sql_command::<SqlLowerBoolEntity>(
        "SELECT * FROM SqlLowerBoolEntity WHERE active IS TRUE",
        MissingRowPolicy::Ignore,
    )
    .expect("IS TRUE bool-field SQL query should lower");
    let canonical_query = compile_sql_command::<SqlLowerBoolEntity>(
        "SELECT * FROM SqlLowerBoolEntity WHERE active",
        MissingRowPolicy::Ignore,
    )
    .expect("bare bool-field SQL query should lower");

    let SqlCommand::Query(wrapped_query) = wrapped_query else {
        panic!("expected lowered IS TRUE bool-field query command");
    };
    let SqlCommand::Query(canonical_query) = canonical_query else {
        panic!("expected lowered bare bool-field query command");
    };

    assert_eq!(
        wrapped_query
            .plan()
            .expect("IS TRUE bool-field SQL plan should build")
            .into_inner(),
        canonical_query
            .plan()
            .expect("bare bool-field SQL plan should build")
            .into_inner(),
        "IS TRUE should lower onto the same canonical scalar bool-field plan as the bare truth condition",
    );
    assert_eq!(
        wrapped_query
            .plan_hash_hex()
            .expect("IS TRUE bool-field plan hash should build"),
        canonical_query
            .plan_hash_hex()
            .expect("bare bool-field plan hash should build"),
        "IS TRUE should keep the same plan hash as the bare bool-field truth condition once planner wrapper canonicalization owns that family",
    );
}

#[test]
fn compile_sql_command_select_where_is_false_matches_not_bool_field_plan_identity() {
    let wrapped_query = compile_sql_command::<SqlLowerBoolEntity>(
        "SELECT * FROM SqlLowerBoolEntity WHERE active IS FALSE",
        MissingRowPolicy::Ignore,
    )
    .expect("IS FALSE bool-field SQL query should lower");
    let canonical_query = compile_sql_command::<SqlLowerBoolEntity>(
        "SELECT * FROM SqlLowerBoolEntity WHERE NOT active",
        MissingRowPolicy::Ignore,
    )
    .expect("NOT bool-field SQL query should lower");

    let SqlCommand::Query(wrapped_query) = wrapped_query else {
        panic!("expected lowered IS FALSE bool-field query command");
    };
    let SqlCommand::Query(canonical_query) = canonical_query else {
        panic!("expected lowered NOT bool-field query command");
    };

    assert_eq!(
        wrapped_query
            .plan()
            .expect("IS FALSE bool-field SQL plan should build")
            .into_inner(),
        canonical_query
            .plan()
            .expect("NOT bool-field SQL plan should build")
            .into_inner(),
        "IS FALSE should lower onto the same canonical scalar bool-field plan as NOT <bool field>",
    );
    assert_eq!(
        wrapped_query
            .plan_hash_hex()
            .expect("IS FALSE bool-field plan hash should build"),
        canonical_query
            .plan_hash_hex()
            .expect("NOT bool-field plan hash should build"),
        "IS FALSE should keep the same plan hash as NOT <bool field> once planner wrapper canonicalization owns that family",
    );
}

#[test]
fn compile_sql_command_rejects_round_with_negative_scale() {
    let err = compile_sql_command::<SqlLowerEntity>(
        "SELECT ROUND(age, -1) FROM SqlLowerEntity",
        MissingRowPolicy::Ignore,
    )
    .expect_err("ROUND should reject negative scale in the bounded slice");

    assert!(matches!(err, SqlLoweringError::Query(_)));
}

#[test]
fn compile_sql_command_select_table_qualified_fields_parity_matches_unqualified_intent() {
    let fluent_query = Query::<SqlLowerEntity>::new(MissingRowPolicy::Ignore)
        .select_fields(["name", "age"])
        .filter(FieldRef::new("age").gte(21_i64))
        .order_term(crate::db::desc("age"))
        .limit(5)
        .offset(1);

    assert_sql_lower_query_matches_fluent_plan(
        "SELECT SqlLowerEntity.name, SqlLowerEntity.age \
         FROM SqlLowerEntity \
         WHERE SqlLowerEntity.age >= 21 \
         ORDER BY SqlLowerEntity.age DESC LIMIT 5 OFFSET 1",
        "qualified field-list SQL query",
        &fluent_query,
        "unqualified fluent query",
        "qualified SQL field references should normalize to the same canonical planned intent as unqualified fluent references",
    );
}

#[test]
fn compile_sql_command_select_table_alias_fields_parity_matches_unqualified_intent() {
    let fluent_query = Query::<SqlLowerEntity>::new(MissingRowPolicy::Ignore)
        .select_fields(["name", "age"])
        .filter(FieldRef::new("age").gte(21_i64))
        .order_term(crate::db::desc("age"))
        .limit(5)
        .offset(1);

    assert_sql_lower_query_matches_fluent_plan(
        "SELECT alias.name, alias.age \
         FROM SqlLowerEntity alias \
         WHERE alias.age >= 21 \
         ORDER BY alias.age DESC LIMIT 5 OFFSET 1",
        "table-alias field-list SQL query",
        &fluent_query,
        "unqualified fluent query",
        "single-table alias SQL field references should normalize to the same canonical planned intent as unqualified fluent references",
    );
}

#[test]
fn compile_sql_command_qualified_nested_predicate_matches_unqualified_fluent_intent() {
    let fluent_query =
        Query::<SqlLowerEntity>::new(MissingRowPolicy::Ignore).filter(FilterExpr::and(vec![
            FilterExpr::or(vec![
                FieldRef::new("age").gte(21_i64),
                FieldRef::new("name").eq("Ada"),
            ]),
            FilterExpr::not(FieldRef::new("name").eq("Bob")),
        ]));

    assert_sql_lower_query_matches_fluent_plan(
        "SELECT * FROM SqlLowerEntity \
         WHERE (SqlLowerEntity.age >= 21 OR SqlLowerEntity.name = 'Ada') \
         AND NOT (SqlLowerEntity.name = 'Bob')",
        "qualified nested-predicate SQL query",
        &fluent_query,
        "unqualified fluent nested-predicate query",
        "qualified nested predicate identifiers should normalize to the same canonical planned intent as unqualified fluent predicates",
    );
}

#[test]
fn compile_sql_command_strict_like_prefix_parity_matches_strict_starts_with_intent() {
    let fluent_query = Query::<SqlLowerEntity>::new(MissingRowPolicy::Ignore)
        .filter(FieldRef::new("name").text_starts_with("Al"));

    assert_sql_lower_query_matches_fluent_plan(
        "SELECT * FROM SqlLowerEntity WHERE name LIKE 'Al%'",
        "strict LIKE prefix SQL query",
        &fluent_query,
        "fluent strict starts-with query",
        "plain LIKE 'prefix%' SQL lowering and fluent strict starts-with query must produce identical normalized planned intent",
    );
}

#[test]
fn compile_sql_command_angle_bracket_not_equal_matches_canonical_ne_intent() {
    let fluent_query = Query::<SqlLowerEntity>::new(MissingRowPolicy::Ignore)
        .filter(FieldRef::new("name").ne("Al"));

    assert_sql_lower_query_matches_fluent_plan(
        "SELECT * FROM SqlLowerEntity WHERE name <> 'Al'",
        "angle-bracket not-equal SQL query",
        &fluent_query,
        "canonical fluent not-equal query",
        "SQL <> lowering must match the canonical != intent",
    );
}

#[test]
fn compile_sql_command_in_trailing_comma_matches_canonical_in_intent() {
    let sql_command = compile_sql_command::<SqlLowerEntity>(
        "SELECT * FROM SqlLowerEntity WHERE age IN (10, 20, 30,)",
        MissingRowPolicy::Ignore,
    )
    .expect("IN with trailing comma SQL query should lower");
    let SqlCommand::Query(sql_query) = sql_command else {
        panic!("expected lowered SQL query command");
    };

    let canonical_command = compile_sql_command::<SqlLowerEntity>(
        "SELECT * FROM SqlLowerEntity WHERE age IN (10, 20, 30)",
        MissingRowPolicy::Ignore,
    )
    .expect("canonical IN SQL query should lower");
    let SqlCommand::Query(canonical_query) = canonical_command else {
        panic!("expected lowered canonical query command");
    };

    assert_eq!(
        sql_query
            .plan()
            .expect("IN with trailing comma SQL plan should build")
            .into_inner(),
        canonical_query
            .plan()
            .expect("canonical IN SQL plan should build")
            .into_inner(),
        "SQL IN with trailing comma must match the canonical IN intent",
    );
}

#[test]
fn compile_sql_command_strict_not_like_prefix_parity_matches_negated_starts_with_intent() {
    let fluent_query = Query::<SqlLowerEntity>::new(MissingRowPolicy::Ignore).filter(
        FilterExpr::not(FieldRef::new("name").text_starts_with("Al")),
    );

    assert_sql_lower_query_matches_fluent_plan(
        "SELECT * FROM SqlLowerEntity WHERE name NOT LIKE 'Al%'",
        "strict NOT LIKE prefix SQL query",
        &fluent_query,
        "fluent negated strict starts-with query",
        "plain NOT LIKE 'prefix%' SQL lowering and fluent negated strict starts-with query must produce identical normalized planned intent",
    );
}

#[test]
fn compile_sql_command_ilike_prefix_matches_casefold_starts_with_intent() {
    let fluent_query = Query::<SqlLowerEntity>::new(MissingRowPolicy::Ignore)
        .filter(FieldRef::new("name").text_starts_with_ci("al"));

    assert_sql_lower_query_matches_fluent_plan(
        "SELECT * FROM SqlLowerEntity WHERE name ILIKE 'al%'",
        "ILIKE prefix SQL query",
        &fluent_query,
        "fluent casefold starts-with query",
        "plain ILIKE 'prefix%' SQL lowering must match the canonical casefold starts-with intent",
    );
}

#[test]
fn compile_sql_command_not_ilike_prefix_matches_negated_casefold_starts_with_intent() {
    let fluent_query = Query::<SqlLowerEntity>::new(MissingRowPolicy::Ignore).filter(
        FilterExpr::not(FieldRef::new("name").text_starts_with_ci("al")),
    );

    assert_sql_lower_query_matches_fluent_plan(
        "SELECT * FROM SqlLowerEntity WHERE name NOT ILIKE 'al%'",
        "NOT ILIKE prefix SQL query",
        &fluent_query,
        "fluent negated casefold starts-with query",
        "plain NOT ILIKE 'prefix%' SQL lowering must match the canonical negated casefold starts-with intent",
    );
}

#[test]
fn compile_sql_command_direct_starts_with_parity_matches_strict_starts_with_intent() {
    let fluent_query = Query::<SqlLowerEntity>::new(MissingRowPolicy::Ignore)
        .filter(FieldRef::new("name").text_starts_with("Al"));

    assert_sql_lower_query_matches_fluent_plan(
        "SELECT * FROM SqlLowerEntity WHERE STARTS_WITH(name, 'Al')",
        "direct STARTS_WITH SQL query",
        &fluent_query,
        "fluent strict starts-with query",
        "direct STARTS_WITH SQL lowering and fluent strict starts-with query must produce identical normalized planned intent",
    );
}

#[test]
fn compile_sql_command_direct_lower_starts_with_parity_matches_casefold_starts_with_intent() {
    let fluent_query = Query::<SqlLowerEntity>::new(MissingRowPolicy::Ignore)
        .filter(FieldRef::new("name").text_starts_with_ci("Al"));

    assert_sql_lower_query_matches_fluent_plan(
        "SELECT * FROM SqlLowerEntity WHERE STARTS_WITH(LOWER(name), 'Al')",
        "direct LOWER(field) STARTS_WITH SQL query",
        &fluent_query,
        "fluent text-casefold starts-with query",
        "direct LOWER(field) STARTS_WITH SQL lowering and fluent text-casefold starts-with query must produce identical normalized planned intent",
    );
}

#[test]
fn compile_sql_command_casefold_not_like_prefix_matrix_matches_negated_casefold_starts_with_intent()
{
    let cases = [
        (
            "SELECT * FROM SqlLowerEntity WHERE LOWER(name) NOT LIKE 'Al%'",
            "LOWER(field) NOT LIKE 'prefix%' SQL lowering",
            "Al",
        ),
        (
            "SELECT * FROM SqlLowerEntity WHERE UPPER(name) NOT LIKE 'AL%'",
            "UPPER(field) NOT LIKE 'prefix%' SQL lowering",
            "AL",
        ),
    ];

    for (sql, context, prefix) in cases {
        let sql_command = compile_sql_command::<SqlLowerEntity>(sql, MissingRowPolicy::Ignore)
            .unwrap_or_else(|err| panic!("{context} should lower: {err}"));
        let SqlCommand::Query(sql_query) = sql_command else {
            panic!("expected lowered SQL query command");
        };

        let fluent_query = Query::<SqlLowerEntity>::new(MissingRowPolicy::Ignore).filter(
            FilterExpr::not(FieldRef::new("name").text_starts_with_ci(prefix)),
        );

        assert_sql_lower_queries_share_plan_identity(
            &sql_query,
            context,
            &fluent_query,
            context,
            &format!(
                "{context} and fluent negated casefold starts-with query must produce identical normalized planned intent"
            ),
        );
    }
}

#[test]
fn compile_sql_command_direct_upper_starts_with_parity_matches_casefold_starts_with_intent() {
    let fluent_query = Query::<SqlLowerEntity>::new(MissingRowPolicy::Ignore)
        .filter(FieldRef::new("name").text_starts_with_ci("AL"));

    assert_sql_lower_query_matches_fluent_plan(
        "SELECT * FROM SqlLowerEntity WHERE STARTS_WITH(UPPER(name), 'AL')",
        "direct UPPER(field) STARTS_WITH SQL query",
        &fluent_query,
        "fluent text-casefold starts-with query",
        "direct UPPER(field) STARTS_WITH SQL lowering and fluent text-casefold starts-with query must produce identical normalized planned intent",
    );
}

#[test]
fn compile_sql_command_lower_like_prefix_parity_matches_casefold_starts_with_intent() {
    let fluent_query = Query::<SqlLowerEntity>::new(MissingRowPolicy::Ignore)
        .filter(FieldRef::new("name").text_starts_with_ci("Al"));

    assert_sql_lower_query_matches_fluent_plan(
        "SELECT * FROM SqlLowerEntity WHERE LOWER(name) LIKE 'Al%'",
        "LOWER(field) LIKE prefix SQL query",
        &fluent_query,
        "fluent text-casefold starts-with query",
        "LOWER(field) LIKE 'prefix%' SQL lowering and fluent text-casefold starts-with query must produce identical normalized planned intent",
    );
}

#[test]
fn compile_sql_command_upper_like_prefix_parity_matches_casefold_starts_with_intent() {
    let fluent_query = Query::<SqlLowerEntity>::new(MissingRowPolicy::Ignore)
        .filter(FieldRef::new("name").text_starts_with_ci("AL"));

    assert_sql_lower_query_matches_fluent_plan(
        "SELECT * FROM SqlLowerEntity WHERE UPPER(name) LIKE 'AL%'",
        "UPPER(field) LIKE prefix SQL query",
        &fluent_query,
        "fluent text-casefold starts-with query",
        "UPPER(field) LIKE 'prefix%' SQL lowering and fluent text-casefold starts-with query must produce identical normalized planned intent",
    );
}

#[test]
fn compile_sql_command_lower_ordered_text_range_parity_matches_casefold_range_intent() {
    let fluent_query = Query::<SqlLowerEntity>::new(MissingRowPolicy::Ignore).filter_predicate(
        Predicate::And(vec![
            Predicate::Compare(ComparePredicate::with_coercion(
                "name",
                CompareOp::Gte,
                Value::Text("Al".to_string()),
                CoercionId::TextCasefold,
            )),
            Predicate::Compare(ComparePredicate::with_coercion(
                "name",
                CompareOp::Lt,
                Value::Text("Am".to_string()),
                CoercionId::TextCasefold,
            )),
        ]),
    );

    assert_sql_lower_query_matches_fluent_plan(
        "SELECT * FROM SqlLowerEntity WHERE LOWER(name) >= 'Al' AND LOWER(name) < 'Am'",
        "LOWER(field) ordered text range SQL query",
        &fluent_query,
        "fluent text-casefold range query",
        "LOWER(field) ordered text range SQL lowering and fluent text-casefold range query must produce identical normalized planned intent",
    );
}

#[test]
fn compile_sql_command_upper_ordered_text_range_parity_matches_casefold_range_intent() {
    let fluent_query = Query::<SqlLowerEntity>::new(MissingRowPolicy::Ignore).filter_predicate(
        Predicate::And(vec![
            Predicate::Compare(ComparePredicate::with_coercion(
                "name",
                CompareOp::Gte,
                Value::Text("AL".to_string()),
                CoercionId::TextCasefold,
            )),
            Predicate::Compare(ComparePredicate::with_coercion(
                "name",
                CompareOp::Lt,
                Value::Text("AM".to_string()),
                CoercionId::TextCasefold,
            )),
        ]),
    );

    assert_sql_lower_query_matches_fluent_plan(
        "SELECT * FROM SqlLowerEntity WHERE UPPER(name) >= 'AL' AND UPPER(name) < 'AM'",
        "UPPER(field) ordered text range SQL query",
        &fluent_query,
        "fluent text-casefold range query",
        "UPPER(field) ordered text range SQL lowering and fluent text-casefold range query must produce identical normalized planned intent",
    );
}

#[test]
fn compile_sql_command_like_non_prefix_pattern_rejects() {
    let cases = [
        "SELECT * FROM SqlLowerEntity WHERE name LIKE '%Al'",
        "SELECT * FROM SqlLowerEntity WHERE LOWER(name) LIKE '%Al'",
        "SELECT * FROM SqlLowerEntity WHERE UPPER(name) LIKE '%Al'",
    ];

    for sql in cases {
        let err = compile_sql_command::<SqlLowerEntity>(sql, MissingRowPolicy::Ignore)
            .expect_err("non-prefix LIKE pattern should fail closed");

        assert!(matches!(
            err,
            SqlLoweringError::Parse(SqlParseError::UnsupportedFeature {
                feature: "LIKE patterns beyond trailing '%' prefix form"
            })
        ));
    }
}

#[test]
fn compile_sql_command_select_schema_qualified_entity_lowers_to_load_query() {
    let query = compile_sql_lower_query_command(
        "SELECT * FROM public.SqlLowerEntity",
        "schema-qualified entity SQL",
    );

    assert!(matches!(query.mode(), QueryMode::Load(_)));
}

#[test]
fn compile_sql_command_global_aggregate_select_lowers_to_dedicated_command() {
    let command = compile_sql_command::<SqlLowerEntity>(
        "SELECT COUNT(*) FROM SqlLowerEntity",
        MissingRowPolicy::Ignore,
    )
    .expect("global aggregate projection should lower to the dedicated aggregate command");

    assert!(
        matches!(command, SqlCommand::GlobalAggregate(_)),
        "global aggregate SELECT should lower to the dedicated aggregate command instead of failing through the scalar query lane",
    );
}

#[test]
fn compile_sql_command_rejects_mixed_scalar_and_aggregate_projection_in_current_slice() {
    let err = compile_sql_command::<SqlLowerEntity>(
        "SELECT name, COUNT(*) FROM SqlLowerEntity",
        MissingRowPolicy::Ignore,
    )
    .expect_err("mixed scalar+aggregate projection should remain gated in this slice");

    assert!(matches!(err, SqlLoweringError::UnsupportedSelectProjection));
}

#[test]
fn lower_aggregate_call_attaches_filter_expr_to_aggregate_expr() {
    let aggregate = super::aggregate::lower_aggregate_call(SqlAggregateCall {
        kind: SqlAggregateKind::Count,
        input: None,
        filter_expr: Some(Box::new(SqlExpr::Binary {
            op: SqlExprBinaryOp::Gt,
            left: Box::new(SqlExpr::Field("age".to_string())),
            right: Box::new(SqlExpr::Literal(Value::Int(1))),
        })),
        distinct: false,
    })
    .expect("aggregate FILTER should lower onto the aggregate expression");

    assert_eq!(aggregate.kind(), AggregateKind::Count);
    assert_eq!(
        aggregate.filter_expr(),
        Some(&Expr::Binary {
            op: BinaryOp::Gt,
            left: Box::new(Expr::Field(FieldId::new("age"))),
            right: Box::new(Expr::Literal(Value::Int(1))),
        }),
    );
}

#[test]
fn lower_aggregate_call_preserves_raw_extrema_distinct_marker() {
    for kind in [SqlAggregateKind::Min, SqlAggregateKind::Max] {
        let field_aggregate = super::aggregate::lower_aggregate_call(SqlAggregateCall {
            kind,
            input: Some(Box::new(SqlExpr::Field("age".to_string()))),
            filter_expr: None,
            distinct: true,
        })
        .expect("field-target extrema DISTINCT should lower before semantic normalization");

        assert_eq!(field_aggregate.kind(), kind.aggregate_kind());
        assert_eq!(field_aggregate.target_field(), Some("age"));
        assert!(
            field_aggregate.is_distinct(),
            "field-target extrema lowering must preserve raw DISTINCT syntax",
        );

        let expression_aggregate = super::aggregate::lower_aggregate_call(SqlAggregateCall {
            kind,
            input: Some(Box::new(SqlExpr::Binary {
                op: SqlExprBinaryOp::Add,
                left: Box::new(SqlExpr::Field("age".to_string())),
                right: Box::new(SqlExpr::Literal(Value::Int(1))),
            })),
            filter_expr: None,
            distinct: true,
        })
        .expect("expression extrema DISTINCT should lower before semantic normalization");

        assert_eq!(expression_aggregate.kind(), kind.aggregate_kind());
        assert!(
            expression_aggregate.is_distinct(),
            "expression extrema lowering must preserve raw DISTINCT syntax",
        );
    }
}

#[test]
fn lower_aggregate_call_rejects_distinct_filter_pairing_in_0940() {
    let err = super::aggregate::lower_aggregate_call(SqlAggregateCall {
        kind: SqlAggregateKind::Count,
        input: Some(Box::new(SqlExpr::Field("age".to_string()))),
        filter_expr: Some(Box::new(SqlExpr::Binary {
            op: SqlExprBinaryOp::Gt,
            left: Box::new(SqlExpr::Field("age".to_string())),
            right: Box::new(SqlExpr::Literal(Value::Int(1))),
        })),
        distinct: true,
    })
    .expect_err("DISTINCT + FILTER should stay fail-closed in 0.94.0");

    assert!(matches!(err, SqlLoweringError::UnsupportedSelectProjection));
}

#[test]
fn lower_aggregate_call_rejects_aggregate_predicates_inside_filter() {
    let err = super::aggregate::lower_aggregate_call(SqlAggregateCall {
        kind: SqlAggregateKind::Count,
        input: None,
        filter_expr: Some(Box::new(SqlExpr::Binary {
            op: SqlExprBinaryOp::Gt,
            left: Box::new(SqlExpr::Aggregate(SqlAggregateCall {
                kind: SqlAggregateKind::Count,
                input: None,
                filter_expr: None,
                distinct: false,
            })),
            right: Box::new(SqlExpr::Literal(Value::Int(1))),
        })),
        distinct: false,
    })
    .expect_err("aggregate expressions inside FILTER should stay fail-closed");

    assert!(matches!(
        err,
        SqlLoweringError::UnsupportedAggregateInputExpressions
    ));
}

#[test]
fn compile_sql_command_rejects_subqueries_inside_filter_predicates() {
    let err = compile_sql_command::<SqlLowerEntity>(
        "SELECT COUNT(*) FILTER (WHERE (SELECT age FROM SqlLowerEntity) > 1) FROM SqlLowerEntity",
        MissingRowPolicy::Ignore,
    )
    .expect_err("subqueries inside FILTER should stay fail-closed before execution");

    assert!(matches!(err, SqlLoweringError::Parse(_)));
}

#[test]
fn compile_sql_command_rejects_grouped_filter_alias_references_before_execution() {
    let err = compile_sql_command::<SqlLowerEntity>(
        "SELECT age, \
         COUNT(*) FILTER (WHERE total_count > 0) AS total_count \
         FROM SqlLowerEntity \
         GROUP BY age \
         ORDER BY age ASC LIMIT 10",
        MissingRowPolicy::Ignore,
    )
    .expect_err("grouped FILTER alias leakage should stay fail-closed before execution");

    assert!(matches!(
        err,
        SqlLoweringError::UnknownField { field } if field == "total_count"
    ));
}

#[test]
fn compile_sql_command_rejects_grouped_filter_alias_references_inside_case_before_execution() {
    let err = compile_sql_command::<SqlLowerEntity>(
        "SELECT age, \
         COUNT(*) FILTER ( \
           WHERE CASE \
             WHEN total_count > 0 THEN TRUE \
             ELSE FALSE \
           END \
         ) AS total_count \
         FROM SqlLowerEntity \
         GROUP BY age \
         ORDER BY age ASC LIMIT 10",
        MissingRowPolicy::Ignore,
    )
    .expect_err(
        "grouped FILTER alias leakage inside CASE should stay fail-closed before execution",
    );

    assert!(matches!(
        err,
        SqlLoweringError::UnknownField { field } if field == "total_count"
    ));
}

#[test]
fn compile_sql_command_select_grouped_aggregate_projection_lowers_to_grouped_intent() {
    let query = compile_sql_lower_query_command(
        "SELECT age, COUNT(*) FROM SqlLowerEntity GROUP BY age",
        "grouped aggregate projection",
    );
    assert!(
        query.has_grouping(),
        "grouped aggregate SQL lowering should produce grouped query intent",
    );
}

#[test]
fn compile_sql_command_select_grouped_qualified_identifiers_match_unqualified_intent() {
    assert_sql_lower_query_matches_sql_plan(
        "SELECT SqlLowerEntity.age, COUNT(*) \
         FROM public.SqlLowerEntity \
         WHERE SqlLowerEntity.age >= 21 \
         GROUP BY SqlLowerEntity.age \
         ORDER BY SqlLowerEntity.age DESC LIMIT 2 OFFSET 1",
        "qualified grouped SQL query",
        "SELECT age, COUNT(*) \
         FROM SqlLowerEntity \
         WHERE age >= 21 \
         GROUP BY age \
         ORDER BY age DESC LIMIT 2 OFFSET 1",
        "unqualified grouped SQL query",
        "qualified grouped SQL identifiers should normalize to the same canonical planned intent as unqualified grouped SQL",
    );
}

#[test]
fn compile_sql_command_select_grouped_top_level_distinct_normalizes_to_grouped_query() {
    assert_sql_lower_query_matches_sql_plan(
        "SELECT DISTINCT age, COUNT(*) FROM SqlLowerEntity GROUP BY age",
        "top-level grouped SELECT DISTINCT",
        "SELECT age, COUNT(*) FROM SqlLowerEntity GROUP BY age",
        "plain grouped aggregate projection",
        "top-level grouped SELECT DISTINCT should normalize to the same grouped intent as the non-DISTINCT form",
    );
}

#[test]
fn compile_sql_command_allows_grouped_text_projection_over_grouped_field() {
    assert_sql_lower_query_plan_builds(
        "SELECT name, TRIM(name), COUNT(*) FROM SqlLowerEntity GROUP BY name",
        "grouped text projection over grouped field",
    );
}

#[test]
fn compile_sql_command_grouped_projection_unknown_field_stays_specific() {
    let err = compile_sql_command::<SqlLowerEntity>(
        "SELECT agge, AVG(age) FROM SqlLowerEntity GROUP BY age",
        MissingRowPolicy::Ignore,
    )
    .expect_err("grouped projection typo should stay a field-resolution error");

    assert!(matches!(
        err,
        SqlLoweringError::UnknownField { ref field } if field == "agge"
    ));
}

#[test]
fn compile_sql_command_allows_grouped_arithmetic_projection_over_grouped_field() {
    assert_sql_lower_query_plan_builds(
        "SELECT age, age + 1, COUNT(*) FROM SqlLowerEntity GROUP BY age",
        "grouped arithmetic projection over grouped field",
    );
}

#[test]
fn compile_sql_command_allows_grouped_round_projection_over_grouped_field() {
    assert_sql_lower_query_plan_builds(
        "SELECT age, ROUND(age / 3, 2), COUNT(*) FROM SqlLowerEntity GROUP BY age",
        "grouped ROUND projection over grouped field",
    );
}

#[test]
fn compile_sql_command_allows_grouped_round_projection_over_aggregate_output() {
    assert_sql_lower_query_plan_builds(
        "SELECT age, ROUND(AVG(age), 2) FROM SqlLowerEntity GROUP BY age",
        "grouped ROUND projection over aggregate output",
    );
}

#[test]
fn compile_sql_command_allows_grouped_arithmetic_projection_over_aggregate_output() {
    assert_sql_lower_query_plan_builds(
        "SELECT age, COUNT(*) + MAX(age) FROM SqlLowerEntity GROUP BY age",
        "grouped arithmetic projection over aggregate output",
    );
}

#[test]
fn compile_sql_command_deduplicates_repeated_grouped_aggregate_leaves_in_projection_expr() {
    assert_sql_lower_query_plan_builds(
        "SELECT age, COUNT(*) + COUNT(*) FROM SqlLowerEntity GROUP BY age",
        "grouped arithmetic projection with repeated aggregate leaves",
    );
}

#[test]
fn compile_sql_command_deduplicates_repeated_grouped_aggregate_input_leaves_in_projection_expr() {
    let query = compile_sql_lower_query_command(
        "SELECT age, AVG(age + 1) + AVG(age + 1) \
         FROM SqlLowerEntity \
         GROUP BY age",
        "grouped arithmetic projection with repeated aggregate-input leaves",
    );
    let planned = query
        .plan()
        .expect("grouped arithmetic projection with repeated aggregate-input leaves should plan")
        .into_inner();
    let grouped = planned
        .grouped_plan()
        .expect("grouped arithmetic projection should keep grouped plan shape");

    assert_eq!(
        grouped.group.aggregates.len(),
        1,
        "repeated grouped aggregate-input leaves should keep one semantic grouped aggregate declaration",
    );
}

#[test]
fn compile_sql_command_allows_grouped_additive_order_over_grouped_field() {
    assert_sql_lower_query_plan_builds(
        "SELECT age, COUNT(*) FROM SqlLowerEntity GROUP BY age ORDER BY age + 1 ASC LIMIT 1",
        "grouped additive ORDER BY over grouped field",
    );
}

#[test]
fn compile_sql_command_allows_grouped_subtractive_order_over_grouped_field() {
    assert_sql_lower_query_plan_builds(
        "SELECT age, COUNT(*) FROM SqlLowerEntity GROUP BY age ORDER BY age - 2 ASC LIMIT 1",
        "grouped subtractive ORDER BY over grouped field",
    );
}

#[test]
fn compile_sql_command_rejects_grouped_non_preserving_computed_order() {
    let query = compile_sql_lower_query_command(
        "SELECT age, COUNT(*) FROM SqlLowerEntity GROUP BY age ORDER BY age + age ASC LIMIT 1",
        "grouped non-preserving computed ORDER BY",
    );

    let err = query.plan().expect_err(
        "grouped ORDER BY expressions that do not preserve grouped-key order should remain fail-closed",
    );

    assert!(matches!(
        err,
        crate::db::query::intent::QueryError::Plan(inner)
            if matches!(
                inner.as_ref(),
                crate::db::query::plan::validate::PlanError::Policy(policy)
                    if matches!(
                        policy.as_ref(),
                        crate::db::query::plan::validate::PlanPolicyError::Group(group)
                            if matches!(
                                group.as_ref(),
                                crate::db::query::plan::validate::GroupPlanError::OrderExpressionNotAdmissible { term } if term == "age + age"
                            )
                    )
            )
    ));
}

#[test]
fn compile_sql_command_allows_grouped_aggregate_order_with_limit() {
    assert_sql_lower_query_plan_builds(
        "SELECT age, AVG(age) \
         FROM SqlLowerEntity \
         GROUP BY age \
         ORDER BY AVG(age) DESC, age ASC \
         LIMIT 1",
        "grouped aggregate ORDER BY with LIMIT",
    );
}

#[test]
fn compile_sql_command_normalizes_grouped_aggregate_order_by_alias_with_limit() {
    assert_eq!(
        first_lowered_order_field(
            "SELECT age, AVG(age) AS avg_age \
             FROM SqlLowerEntity \
             GROUP BY age \
             ORDER BY avg_age DESC, age ASC \
             LIMIT 1",
            "grouped aggregate ORDER BY alias with LIMIT",
        ),
        "AVG(age)",
        "grouped aggregate ORDER BY aliases should normalize onto the canonical aggregate term",
    );
}

#[test]
fn compile_sql_command_allows_grouped_aggregate_order_with_multi_key_tie_breakers() {
    assert_sql_lower_query_plan_builds(
        "SELECT name, age, COUNT(*) \
         FROM SqlLowerEntity \
         GROUP BY name, age \
         ORDER BY COUNT(*) DESC, name ASC, age ASC \
         LIMIT 1",
        "grouped aggregate ORDER BY with grouped-key tie-breakers",
    );
}

#[test]
fn grouped_aggregate_order_with_multi_key_tie_breakers_preserves_lowered_shape() {
    let lowered = lower_sql_select_shape_for_test(
        "SELECT name, age, COUNT(*) \
         FROM SqlLowerEntity \
         GROUP BY name, age \
         ORDER BY COUNT(*) DESC, name ASC, age ASC \
         LIMIT 1",
        "grouped aggregate ORDER BY lowered shape",
    );

    assert_eq!(
        lowered.group_by_fields_for_test(),
        &["name".to_string(), "age".to_string()],
        "multi-key GROUP BY lowering should preserve both grouped keys in declaration order",
    );
    assert_eq!(
        lowered.order_labels_for_test(),
        vec![
            "COUNT(*)".to_string(),
            "name".to_string(),
            "age".to_string(),
        ],
        "grouped aggregate ORDER BY lowering should preserve the aggregate leader and grouped-key tie-breakers canonically",
    );
}

#[test]
fn compile_sql_command_normalizes_grouped_aggregate_input_order_by_alias_with_limit() {
    assert_eq!(
        first_lowered_order_field(
            "SELECT age, AVG(age + 1) AS avg_plus_one \
             FROM SqlLowerEntity \
             GROUP BY age \
             ORDER BY avg_plus_one DESC, age ASC \
             LIMIT 1",
            "grouped aggregate input ORDER BY alias with LIMIT",
        ),
        "AVG(age + 1)",
        "grouped aggregate input ORDER BY aliases should normalize onto the canonical aggregate term",
    );
}

#[test]
fn compile_sql_command_normalizes_grouped_wrapped_aggregate_input_order_by_alias_with_limit() {
    assert_eq!(
        first_lowered_order_field(
            "SELECT age, ROUND(AVG((age + age) / 2), 2) AS avg_balanced \
             FROM SqlLowerEntity \
             GROUP BY age \
             ORDER BY avg_balanced DESC, age ASC \
             LIMIT 1",
            "grouped wrapped aggregate input ORDER BY alias with LIMIT",
        ),
        "ROUND(AVG((age + age) / 2), 2)",
        "grouped wrapped aggregate input ORDER BY aliases should preserve the canonical parenthesized aggregate term",
    );
}

#[test]
fn compile_sql_command_normalizes_grouped_case_aggregate_input_order_by_alias_with_limit() {
    assert_eq!(
        first_lowered_order_field(
            "SELECT age, SUM(CASE WHEN age > 10 THEN 1 ELSE 0 END) AS high_count \
             FROM SqlLowerEntity \
             GROUP BY age \
             ORDER BY high_count DESC, age ASC \
             LIMIT 1",
            "grouped searched CASE aggregate input ORDER BY alias with LIMIT",
        ),
        "SUM(CASE WHEN age > 10 THEN 1 ELSE 0 END)",
        "grouped searched CASE aggregate input ORDER BY aliases should normalize onto the canonical aggregate term",
    );
}

#[test]
fn compile_sql_command_accepts_grouped_wrapped_aggregate_order_terms_with_limit() {
    assert_eq!(
        first_lowered_order_field(
            "SELECT age, AVG(age) \
             FROM SqlLowerEntity \
             GROUP BY age \
             ORDER BY COALESCE(NULLIF(AVG(age), 20), 99) DESC, age ASC \
             LIMIT 1",
            "grouped wrapped aggregate ORDER BY with LIMIT",
        ),
        "COALESCE(NULLIF(AVG(age), 20), 99)",
        "grouped wrapped aggregate ORDER BY terms should lower onto the canonical wrapped post-aggregate order expression",
    );
}

#[test]
fn compile_sql_command_normalizes_grouped_wrapped_aggregate_order_by_alias_with_limit() {
    assert_eq!(
        first_lowered_order_field(
            "SELECT age, COALESCE(NULLIF(AVG(age), 20), 99) AS adjusted_avg \
             FROM SqlLowerEntity \
             GROUP BY age \
             ORDER BY adjusted_avg DESC, age ASC \
             LIMIT 1",
            "grouped wrapped aggregate ORDER BY alias with LIMIT",
        ),
        "COALESCE(NULLIF(AVG(age), 20), 99)",
        "grouped wrapped aggregate ORDER BY aliases should normalize onto the canonical wrapped post-aggregate value-selection term",
    );
}

#[test]
fn compile_sql_command_normalizes_grouped_filtered_aggregate_order_by_alias_with_limit() {
    let sql_command = compile_sql_command::<SqlLowerBoolEntity>(
        "SELECT label, COUNT(*) FILTER (WHERE NOT active) AS inactive_count \
         FROM SqlLowerBoolEntity \
         GROUP BY label \
         ORDER BY inactive_count DESC, label ASC \
         LIMIT 1",
        MissingRowPolicy::Ignore,
    )
    .expect("grouped filtered aggregate ORDER BY alias with LIMIT should lower");
    let SqlCommand::Query(sql_query) = sql_command else {
        panic!("grouped filtered aggregate ORDER BY alias should lower to a query command");
    };
    let plan = sql_query
        .plan()
        .expect("grouped filtered aggregate ORDER BY alias plan should build")
        .into_inner();

    assert_eq!(
        plan.scalar_plan()
            .order
            .as_ref()
            .expect("grouped filtered aggregate ORDER BY alias should keep ordering")
            .fields[0]
            .rendered_label(),
        "COUNT(*) FILTER (WHERE NOT active)",
        "grouped filtered aggregate ORDER BY aliases should normalize onto the canonical filtered aggregate term",
    );
}

#[test]
fn compile_sql_command_normalizes_grouped_count_order_by_alias_inside_expression_with_limit() {
    assert_eq!(
        first_lowered_order_field(
            "SELECT age, COUNT(*) AS total_count \
             FROM SqlLowerEntity \
             GROUP BY age \
             ORDER BY total_count + 1 DESC, age ASC \
             LIMIT 1",
            "grouped COUNT ORDER BY alias inside expression with LIMIT",
        ),
        "COUNT(*) + 1",
        "grouped aggregate ORDER BY aliases should substitute recursively inside larger arithmetic order expressions",
    );
}

#[test]
fn compile_sql_command_normalizes_grouped_wrapped_aggregate_order_by_alias_inside_expression_with_limit()
 {
    assert_eq!(
        first_lowered_order_field(
            "SELECT age, ROUND(AVG(age), 2) AS avg_age \
             FROM SqlLowerEntity \
             GROUP BY age \
             ORDER BY avg_age + 1 DESC, age ASC \
             LIMIT 1",
            "grouped wrapped aggregate ORDER BY alias inside expression with LIMIT",
        ),
        "ROUND(AVG(age), 2) + 1",
        "grouped wrapped aggregate ORDER BY aliases should substitute recursively inside larger arithmetic order expressions",
    );
}

#[test]
fn compile_sql_command_accepts_grouped_aggregate_order_by_alias_with_field_compare_predicate() {
    assert_sql_lower_query_plan_builds(
        "SELECT age, ROUND(AVG(age), 2) AS avg_age \
         FROM SqlLowerEntity \
         WHERE name > name \
         GROUP BY age \
         ORDER BY avg_age DESC, age ASC \
         LIMIT 1",
        "grouped aggregate ORDER BY alias with grouped residual filter",
    );
}

#[test]
fn compile_sql_command_accepts_grouped_aggregate_order_with_offset() {
    let command = compile_sql_command::<SqlLowerEntity>(
        "SELECT age, AVG(age) \
         FROM SqlLowerEntity \
         GROUP BY age \
         ORDER BY AVG(age) DESC \
         LIMIT 1 OFFSET 1",
        MissingRowPolicy::Ignore,
    )
    .expect("grouped aggregate ORDER BY with OFFSET should lower structurally");

    let SqlCommand::Query(query) = command else {
        panic!("expected lowered grouped query command");
    };

    query
        .plan()
        .expect("grouped aggregate ORDER BY with OFFSET should build through grouped Top-K");
}

#[test]
fn compile_sql_command_accepts_grouped_filtered_aggregate_order_by_alias_with_offset() {
    let sql_command = compile_sql_command::<SqlLowerBoolEntity>(
        "SELECT label, COUNT(*) FILTER (WHERE NOT active) AS inactive_count \
         FROM SqlLowerBoolEntity \
         GROUP BY label \
         ORDER BY inactive_count DESC, label ASC \
         LIMIT 1 OFFSET 1",
        MissingRowPolicy::Ignore,
    )
    .expect("grouped filtered aggregate ORDER BY alias with OFFSET should lower");
    let SqlCommand::Query(sql_query) = sql_command else {
        panic!(
            "grouped filtered aggregate ORDER BY alias with OFFSET should lower to a query command"
        );
    };
    let plan = sql_query
        .plan()
        .expect("grouped filtered aggregate ORDER BY alias with OFFSET should plan")
        .into_inner();

    assert_eq!(
        plan.scalar_plan()
            .order
            .as_ref()
            .expect("grouped filtered aggregate ORDER BY alias with OFFSET should keep ordering")
            .fields[0]
            .rendered_label(),
        "COUNT(*) FILTER (WHERE NOT active)",
        "grouped filtered aggregate ORDER BY aliases with OFFSET should normalize onto the canonical filtered aggregate term",
    );
}

#[test]
fn compile_sql_command_rejects_grouped_non_group_field_projection() {
    let err = compile_sql_command::<SqlLowerEntity>(
        "SELECT age, name, COUNT(*) FROM SqlLowerEntity GROUP BY age",
        MissingRowPolicy::Ignore,
    )
    .expect_err("grouped non-group field projection should stay fail-closed");

    assert!(matches!(
        err,
        SqlLoweringError::GroupedProjectionReferencesNonGroupField { index: 1 }
    ));
}

#[test]
fn compile_sql_command_rejects_grouped_projection_without_aggregate_specifically() {
    let err = compile_sql_command::<SqlLowerEntity>(
        "SELECT age FROM SqlLowerEntity GROUP BY age",
        MissingRowPolicy::Ignore,
    )
    .expect_err("grouped projection without aggregates should stay fail-closed");

    assert!(matches!(
        err,
        SqlLoweringError::GroupedProjectionRequiresAggregate
    ));
}

#[test]
fn compile_sql_command_rejects_grouped_star_projection_specifically() {
    let err = compile_sql_command::<SqlLowerEntity>(
        "SELECT * FROM SqlLowerEntity GROUP BY age",
        MissingRowPolicy::Ignore,
    )
    .expect_err("grouped star projection should stay fail-closed");

    assert!(matches!(
        err,
        SqlLoweringError::GroupedProjectionRequiresExplicitList
    ));
}

#[test]
fn compile_sql_command_rejects_grouped_scalar_projection_after_aggregate_specifically() {
    let err = compile_sql_command::<SqlLowerEntity>(
        "SELECT COUNT(*), age FROM SqlLowerEntity GROUP BY age",
        MissingRowPolicy::Ignore,
    )
    .expect_err("grouped scalar terms after aggregate terms should stay fail-closed");

    assert!(matches!(
        err,
        SqlLoweringError::GroupedProjectionScalarAfterAggregate { index: 1 }
    ));
}

#[test]
fn compile_sql_command_accepts_grouped_field_to_field_predicate() {
    assert_sql_lower_query_plan_builds(
        "SELECT age, COUNT(*) FROM SqlLowerEntity WHERE name > name GROUP BY age ORDER BY age ASC LIMIT 10",
        "grouped field-to-field predicate SQL",
    );
}

#[test]
fn compile_sql_command_accepts_projected_direct_bounded_numeric_order_terms() {
    let sql_command = compile_sql_command::<SqlLowerEntity>(
        "SELECT age + 1 FROM SqlLowerEntity ORDER BY age + 1 ASC",
        MissingRowPolicy::Ignore,
    )
    .expect("projected direct ORDER BY arithmetic term should lower");

    let SqlCommand::Query(sql_query) = sql_command else {
        panic!("expected lowered projected arithmetic order query command");
    };

    let plan = sql_query
        .plan()
        .expect("projected direct arithmetic order plan should build")
        .into_inner();
    assert_eq!(
        plan.scalar_plan()
            .order
            .as_ref()
            .expect("projected direct arithmetic order should be present")
            .fields[0]
            .rendered_label(),
        "age + 1",
        "projected direct ORDER BY arithmetic terms should normalize onto the canonical internal numeric expression",
    );
}

#[test]
fn compile_sql_command_accepts_distinct_order_by_expression_derived_from_projected_field() {
    let sql_command = compile_sql_command::<SqlLowerExpressionEntity>(
        "SELECT DISTINCT name FROM SqlLowerExpressionEntity ORDER BY LOWER(name) ASC",
        MissingRowPolicy::Ignore,
    )
    .expect("DISTINCT ORDER BY expressions derived from projected fields should lower");

    let SqlCommand::Query(sql_query) = sql_command else {
        panic!("expected lowered DISTINCT scalar query command");
    };

    let plan = sql_query
        .plan()
        .expect("DISTINCT derived ORDER BY plan should build")
        .into_inner();
    assert_eq!(
        plan.scalar_plan()
            .order
            .as_ref()
            .expect("DISTINCT derived ORDER BY should be present")
            .fields[0]
            .rendered_label(),
        "LOWER(name)",
        "DISTINCT ORDER BY expressions derived from projected fields should keep the canonical order expression",
    );
}

#[test]
fn compile_sql_command_rejects_distinct_order_by_non_projected_field() {
    let err = compile_sql_command::<SqlLowerEntity>(
        "SELECT DISTINCT name FROM SqlLowerEntity ORDER BY age ASC",
        MissingRowPolicy::Ignore,
    )
    .expect_err("DISTINCT ORDER BY on a non-projected field should fail closed");

    assert!(
        err.to_string().contains(
            "SELECT DISTINCT ORDER BY terms must be derivable from the projected distinct tuple"
        ),
        "DISTINCT ORDER BY rejection should explain the projected-tuple boundary: {err}",
    );
}

#[test]
fn compile_sql_command_rejects_distinct_order_by_wrapped_non_projected_field() {
    let err = compile_sql_command::<SqlLowerEntity>(
        "SELECT DISTINCT name FROM SqlLowerEntity ORDER BY LOWER(age) ASC",
        MissingRowPolicy::Ignore,
    )
    .expect_err("DISTINCT ORDER BY wrapping a non-projected field should fail closed");

    assert!(
        err.to_string().contains(
            "SELECT DISTINCT ORDER BY terms must be derivable from the projected distinct tuple"
        ),
        "wrapped DISTINCT ORDER BY rejection should preserve the projected-tuple boundary: {err}",
    );
}

#[test]
fn compile_sql_command_rejects_distinct_order_by_direct_field_from_expression_projection() {
    let err = compile_sql_command::<SqlLowerExpressionEntity>(
        "SELECT DISTINCT LOWER(name) FROM SqlLowerExpressionEntity ORDER BY name ASC",
        MissingRowPolicy::Ignore,
    )
    .expect_err(
        "DISTINCT ORDER BY on the source field behind an expression projection should fail closed",
    );

    assert!(
        err.to_string().contains(
            "SELECT DISTINCT ORDER BY terms must be derivable from the projected distinct tuple"
        ),
        "expression-projection DISTINCT ORDER BY rejection should preserve the projected-tuple boundary: {err}",
    );
}

#[test]
fn compile_sql_command_select_grouped_having_parity_matches_fluent_intent() {
    let sql_command = compile_sql_command::<SqlLowerEntity>(
        "SELECT age, COUNT(*) \
         FROM SqlLowerEntity \
         WHERE age >= 21 \
         GROUP BY age \
         HAVING age >= 21 AND COUNT(*) > 1 \
         ORDER BY age DESC LIMIT 3",
        MissingRowPolicy::Ignore,
    )
    .expect("grouped HAVING SQL query should lower");
    let SqlCommand::Query(sql_query) = sql_command else {
        panic!("expected lowered grouped HAVING SQL query command");
    };

    let fluent_query = Query::<SqlLowerEntity>::new(MissingRowPolicy::Ignore)
        .filter(FieldRef::new("age").gte(21_i64))
        .group_by("age")
        .expect("fluent grouped query should accept grouped field")
        .aggregate(crate::db::count())
        .having_group(
            "age",
            CompareOp::Gte,
            crate::value::InputValue::from(Value::Int(21)),
        )
        .expect("fluent grouped HAVING group-field clause should be accepted")
        .having_aggregate(
            0,
            CompareOp::Gt,
            crate::value::InputValue::from(Value::Int(1)),
        )
        .expect("fluent grouped HAVING aggregate clause should be accepted")
        .order_term(crate::db::desc("age"))
        .limit(3);

    assert_eq!(
        sql_query
            .plan()
            .expect("grouped HAVING SQL plan should build")
            .into_inner(),
        fluent_query
            .plan()
            .expect("fluent grouped HAVING plan should build")
            .into_inner(),
        "grouped HAVING SQL lowering and fluent grouped HAVING query must produce identical normalized planned intent",
    );
}

#[test]
fn compile_sql_command_select_grouped_having_is_null_parity_matches_fluent_intent() {
    let sql_command = compile_sql_command::<SqlLowerEntity>(
        "SELECT age, COUNT(*) \
         FROM SqlLowerEntity \
         GROUP BY age \
         HAVING age IS NOT NULL AND COUNT(*) IS NOT NULL \
         ORDER BY age DESC LIMIT 3",
        MissingRowPolicy::Ignore,
    )
    .expect("grouped HAVING IS [NOT] NULL SQL query should lower");
    let SqlCommand::Query(sql_query) = sql_command else {
        panic!("expected lowered grouped HAVING IS [NOT] NULL SQL query command");
    };

    let fluent_query = Query::<SqlLowerEntity>::new(MissingRowPolicy::Ignore)
        .group_by("age")
        .expect("fluent grouped query should accept grouped field")
        .aggregate(crate::db::count())
        .having_group(
            "age",
            CompareOp::Ne,
            crate::value::InputValue::from(Value::Null),
        )
        .expect("fluent grouped HAVING group-field IS NOT NULL should be accepted")
        .having_aggregate(
            0,
            CompareOp::Ne,
            crate::value::InputValue::from(Value::Null),
        )
        .expect("fluent grouped HAVING aggregate IS NOT NULL should be accepted")
        .order_term(crate::db::desc("age"))
        .limit(3);

    assert_eq!(
        sql_query
            .plan()
            .expect("grouped HAVING IS [NOT] NULL SQL plan should build")
            .into_inner(),
        fluent_query
            .plan()
            .expect("fluent grouped HAVING IS [NOT] NULL plan should build")
            .into_inner(),
        "grouped HAVING IS [NOT] NULL SQL lowering and fluent grouped HAVING query must produce identical normalized planned intent",
    );
}

#[test]
fn compile_sql_command_select_grouped_post_aggregate_having_exprs_lowers() {
    let sql_command = compile_sql_command::<SqlLowerEntity>(
        "SELECT age, COUNT(*) \
         FROM SqlLowerEntity \
         GROUP BY age \
         HAVING ROUND(AVG(age), 2) >= 10 AND COUNT(*) + 1 > 1 \
         ORDER BY age DESC LIMIT 3",
        MissingRowPolicy::Ignore,
    )
    .expect("grouped post-aggregate HAVING SQL query should lower");

    let SqlCommand::Query(sql_query) = sql_command else {
        panic!("expected lowered grouped HAVING SQL query command");
    };

    sql_query
        .plan()
        .expect("grouped post-aggregate HAVING SQL plan should build");
}

#[test]
fn compile_sql_command_select_grouped_searched_case_having_exprs_lowers() {
    let command = compile_sql_command::<SqlLowerEntity>(
        "SELECT age, COUNT(*) \
         FROM SqlLowerEntity \
         GROUP BY age \
         HAVING CASE WHEN COUNT(*) > 1 THEN 1 ELSE 0 END = 1 \
         ORDER BY age ASC LIMIT 10",
        MissingRowPolicy::Ignore,
    )
    .expect("grouped searched CASE HAVING SQL query should lower");
    let SqlCommand::Query(query) = command else {
        panic!("expected lowered grouped searched CASE HAVING SQL query command");
    };

    let planned = query
        .plan()
        .expect("grouped searched CASE HAVING SQL plan should build")
        .into_inner();
    let grouped = planned
        .grouped_plan()
        .expect("grouped searched CASE HAVING SQL should keep grouped plan shape");

    assert!(
        matches!(
            grouped.having_expr.as_ref(),
            Some(Expr::Binary { op: BinaryOp::Eq, left, right })
                if matches!(
                    left.as_ref(),
                    Expr::Case { else_expr, .. }
                        if else_expr.as_ref() == &Expr::Literal(Value::Int(0))
                ) && matches!(
                    right.as_ref(),
                    Expr::Literal(Value::Int(1))
                )
        ),
        "grouped searched CASE HAVING should lower through the shared post-aggregate value seam",
    );
}

#[test]
fn compile_sql_command_select_grouped_boolean_searched_case_having_canonicalizes() {
    let command = compile_sql_command::<SqlLowerEntity>(
        "SELECT age, COUNT(*) \
         FROM SqlLowerEntity \
         GROUP BY age \
         HAVING CASE WHEN COUNT(*) > 1 THEN TRUE ELSE FALSE END \
         ORDER BY age ASC LIMIT 10",
        MissingRowPolicy::Ignore,
    )
    .expect("grouped boolean searched CASE HAVING SQL query should lower");
    let SqlCommand::Query(query) = command else {
        panic!("expected lowered grouped boolean searched CASE HAVING SQL query command");
    };

    let planned = query
        .plan()
        .expect("grouped boolean searched CASE HAVING SQL plan should build")
        .into_inner();
    let grouped = planned
        .grouped_plan()
        .expect("grouped boolean searched CASE HAVING SQL should keep grouped plan shape");

    let case_expr = Expr::Case {
        when_then_arms: vec![CaseWhenArm::new(
            Expr::Binary {
                op: BinaryOp::Gt,
                left: Box::new(Expr::Aggregate(crate::db::count())),
                right: Box::new(Expr::Literal(Value::Int(1))),
            },
            Expr::Literal(Value::Bool(true)),
        )],
        else_expr: Box::new(Expr::Literal(Value::Bool(false))),
    };

    assert_eq!(
        grouped.having_expr.as_ref(),
        Some(&canonicalize_grouped_having_bool_expr(case_expr)),
        "grouped boolean searched CASE HAVING should lower onto the canonical grouped semantic form",
    );
}

#[test]
fn compile_sql_command_select_where_searched_case_hash_matches_fluent_canonical_hash() {
    let sql_query = compile_sql_lower_query_command(
        "SELECT name \
         FROM SqlLowerEntity \
         WHERE CASE WHEN age >= 30 THEN TRUE ELSE age = 20 END \
         ORDER BY age ASC LIMIT 5",
        "searched CASE scalar WHERE SQL query",
    );
    let searched_case = Expr::Case {
        when_then_arms: vec![CaseWhenArm::new(
            Expr::Binary {
                op: BinaryOp::Gte,
                left: Box::new(Expr::Field(FieldId::new("age"))),
                right: Box::new(Expr::Literal(Value::Int(30))),
            },
            Expr::Literal(Value::Bool(true)),
        )],
        else_expr: Box::new(Expr::Binary {
            op: BinaryOp::Eq,
            left: Box::new(Expr::Field(FieldId::new("age"))),
            right: Box::new(Expr::Literal(Value::Int(20))),
        }),
    };
    let fluent_query = Query::<SqlLowerEntity>::new(MissingRowPolicy::Ignore)
        .select_fields(["name"])
        .filter_expr(canonicalize_scalar_where_bool_expr(searched_case))
        .order_term(crate::db::asc("age"))
        .limit(5);

    assert_sql_lower_queries_share_plan_identity(
        &sql_query,
        "searched CASE scalar WHERE SQL query",
        &fluent_query,
        "canonical-equivalent fluent scalar filter query",
        "searched CASE scalar WHERE should share normalized planned intent with the equivalent fluent canonical filter form",
    );
    assert_sql_lower_queries_share_plan_hash(
        &sql_query,
        "searched CASE scalar WHERE SQL query",
        &fluent_query,
        "canonical-equivalent fluent scalar filter query",
        "searched CASE scalar WHERE should share one plan hash with the equivalent fluent canonical filter form",
    );
}

#[test]
fn compile_sql_command_select_grouped_boolean_searched_case_truth_wrapper_keeps_same_canonical_shape()
 {
    let canonical = compile_sql_command::<SqlLowerEntity>(
        "SELECT age, COUNT(*) \
         FROM SqlLowerEntity \
         GROUP BY age \
         HAVING CASE WHEN COUNT(*) > 1 THEN TRUE ELSE FALSE END \
         ORDER BY age ASC LIMIT 10",
        MissingRowPolicy::Ignore,
    )
    .expect("canonical grouped boolean searched CASE HAVING SQL query should lower");
    let wrapped = compile_sql_command::<SqlLowerEntity>(
        "SELECT age, COUNT(*) \
         FROM SqlLowerEntity \
         GROUP BY age \
         HAVING CASE WHEN (COUNT(*) > 1) = TRUE THEN TRUE ELSE FALSE END \
         ORDER BY age ASC LIMIT 10",
        MissingRowPolicy::Ignore,
    )
    .expect("truth-wrapped grouped boolean searched CASE HAVING SQL query should lower");
    let SqlCommand::Query(canonical_query) = canonical else {
        panic!("expected canonical grouped boolean searched CASE HAVING SQL query command");
    };
    let SqlCommand::Query(wrapped_query) = wrapped else {
        panic!("expected truth-wrapped grouped boolean searched CASE HAVING SQL query command");
    };

    assert_sql_lower_queries_share_plan_identity(
        &canonical_query,
        "canonical grouped boolean searched CASE HAVING",
        &wrapped_query,
        "truth-wrapped grouped boolean searched CASE HAVING",
        "grouped searched CASE truth wrappers should lower onto the same canonical planned identity",
    );
    assert_sql_lower_queries_share_plan_hash(
        &canonical_query,
        "canonical grouped boolean searched CASE HAVING",
        &wrapped_query,
        "truth-wrapped grouped boolean searched CASE HAVING",
        "grouped searched CASE truth wrappers should keep the same plan hash once canonicalized",
    );
}

#[test]
fn compile_sql_command_select_grouped_boolean_searched_case_hash_matches_fluent_canonical_hash() {
    let sql_query = compile_sql_lower_query_command(
        "SELECT age, COUNT(*) \
         FROM SqlLowerEntity \
         GROUP BY age \
         HAVING CASE WHEN COUNT(*) > 1 THEN TRUE ELSE FALSE END \
         ORDER BY age ASC LIMIT 10",
        "grouped searched CASE HAVING SQL query",
    );
    let grouped_case = Expr::Case {
        when_then_arms: vec![CaseWhenArm::new(
            Expr::Binary {
                op: BinaryOp::Gt,
                left: Box::new(Expr::Aggregate(crate::db::count())),
                right: Box::new(Expr::Literal(Value::Int(1))),
            },
            Expr::Literal(Value::Bool(true)),
        )],
        else_expr: Box::new(Expr::Literal(Value::Bool(false))),
    };
    let fluent_query = Query::<SqlLowerEntity>::new(MissingRowPolicy::Ignore)
        .group_by("age")
        .expect("fluent grouped query should accept grouped field")
        .aggregate(crate::db::count())
        .having_expr(canonicalize_grouped_having_bool_expr(grouped_case))
        .expect("fluent grouped query should accept canonical grouped searched CASE HAVING")
        .order_term(crate::db::asc("age"))
        .limit(10);

    assert_sql_lower_queries_share_plan_identity(
        &sql_query,
        "grouped searched CASE HAVING SQL query",
        &fluent_query,
        "canonical-equivalent fluent grouped HAVING query",
        "grouped searched CASE HAVING should share normalized planned intent with the equivalent fluent canonical grouped filter form",
    );
    assert_sql_lower_queries_share_plan_hash(
        &sql_query,
        "grouped searched CASE HAVING SQL query",
        &fluent_query,
        "canonical-equivalent fluent grouped HAVING query",
        "grouped searched CASE HAVING should share one plan hash with the equivalent fluent canonical grouped filter form",
    );
}

#[test]
fn compile_sql_command_select_grouped_boolean_searched_case_without_else_canonicalizes_to_null_family()
 {
    let command = compile_sql_command::<SqlLowerEntity>(
        "SELECT age, COUNT(*) \
         FROM SqlLowerEntity \
         GROUP BY age \
         HAVING CASE WHEN COUNT(*) > 1 THEN TRUE END \
         ORDER BY age ASC LIMIT 10",
        MissingRowPolicy::Ignore,
    )
    .expect("grouped searched CASE HAVING without ELSE should lower");
    let SqlCommand::Query(query) = command else {
        panic!("expected lowered grouped searched CASE HAVING without ELSE SQL query command");
    };

    let planned = query
        .plan()
        .expect("grouped searched CASE HAVING without ELSE SQL plan should build")
        .into_inner();
    let grouped = planned
        .grouped_plan()
        .expect("grouped searched CASE HAVING without ELSE should keep grouped plan shape");

    let case_expr = Expr::Case {
        when_then_arms: vec![CaseWhenArm::new(
            Expr::Binary {
                op: BinaryOp::Gt,
                left: Box::new(Expr::Aggregate(crate::db::count())),
                right: Box::new(Expr::Literal(Value::Int(1))),
            },
            Expr::Literal(Value::Bool(true)),
        )],
        else_expr: Box::new(Expr::Literal(Value::Null)),
    };

    assert_eq!(
        grouped.having_expr.as_ref(),
        Some(&canonicalize_grouped_having_bool_expr(case_expr)),
        "grouped searched CASE HAVING without ELSE should join the grouped null-family canonical form when the omitted-ELSE expansion is provably identical",
    );
}

#[test]
fn compile_sql_command_select_grouped_boolean_searched_case_without_else_truth_wrapper_keeps_same_null_family_shape()
 {
    let canonical = compile_sql_lower_query_command(
        "SELECT age, COUNT(*) \
         FROM SqlLowerEntity \
         GROUP BY age \
         HAVING CASE WHEN COUNT(*) > 1 THEN TRUE ELSE NULL END \
         ORDER BY age ASC LIMIT 10",
        "canonical grouped searched CASE HAVING with explicit ELSE NULL SQL query",
    );
    let wrapped = compile_sql_lower_query_command(
        "SELECT age, COUNT(*) \
         FROM SqlLowerEntity \
         GROUP BY age \
         HAVING CASE WHEN (COUNT(*) > 1) = TRUE THEN TRUE END \
         ORDER BY age ASC LIMIT 10",
        "truth-wrapped grouped searched CASE HAVING without ELSE SQL query",
    );

    assert_sql_lower_queries_share_plan_identity(
        &canonical,
        "canonical grouped searched CASE HAVING with explicit ELSE NULL SQL query",
        &wrapped,
        "truth-wrapped grouped searched CASE HAVING without ELSE SQL query",
        "grouped searched CASE HAVING without ELSE should keep the same canonical planned identity even when the admitted WHEN condition carries a redundant truth wrapper",
    );
    assert_sql_lower_queries_share_plan_hash(
        &canonical,
        "canonical grouped searched CASE HAVING with explicit ELSE NULL SQL query",
        &wrapped,
        "truth-wrapped grouped searched CASE HAVING without ELSE SQL query",
        "grouped searched CASE HAVING without ELSE should keep the same plan hash as the explicit ELSE NULL grouped boolean family even when the admitted WHEN condition carries a redundant truth wrapper",
    );
}

#[test]
fn compile_sql_command_select_grouped_value_searched_case_without_else_is_rejected() {
    let err = compile_sql_command::<SqlLowerEntity>(
        "SELECT age, COUNT(*) \
         FROM SqlLowerEntity \
         GROUP BY age \
         HAVING CASE WHEN COUNT(*) > 1 THEN 1 END = 1 \
         ORDER BY age ASC LIMIT 10",
        MissingRowPolicy::Ignore,
    )
    .expect_err(
        "grouped omitted-ELSE searched CASE outside the admitted boolean family must fail closed",
    );

    assert!(
        matches!(err, SqlLoweringError::UnsupportedSelectHaving),
        "grouped omitted-ELSE searched CASE outside the admitted boolean family should reject with the grouped HAVING boundary error: {err:?}",
    );
}

#[test]
fn compile_sql_command_select_grouped_having_alias_matches_canonical_expr_plan() {
    assert_sql_lower_query_matches_sql_plan(
        "SELECT age, SUM(CASE WHEN age > 10 THEN 1 ELSE 0 END) AS high_count \
         FROM SqlLowerEntity \
         GROUP BY age \
         HAVING high_count > 0 \
         ORDER BY age ASC LIMIT 10",
        "grouped HAVING aggregate alias SQL query",
        "SELECT age, SUM(CASE WHEN age > 10 THEN 1 ELSE 0 END) AS high_count \
         FROM SqlLowerEntity \
         GROUP BY age \
         HAVING SUM(CASE WHEN age > 10 THEN 1 ELSE 0 END) > 0 \
         ORDER BY age ASC LIMIT 10",
        "canonical grouped HAVING aggregate expression SQL query",
        "grouped HAVING aliases should normalize onto the same canonical post-aggregate expression target",
    );
}

#[test]
fn compile_sql_command_select_having_without_group_by_rejects() {
    let err = compile_sql_command::<SqlLowerEntity>(
        "SELECT * FROM SqlLowerEntity HAVING COUNT(*) > 1",
        MissingRowPolicy::Ignore,
    )
    .expect_err("HAVING without GROUP BY should fail closed");

    assert!(matches!(err, SqlLoweringError::HavingRequiresGroupBy));
}

#[test]
fn compile_sql_command_select_global_aggregate_having_alias_lowers_to_global_aggregate_command() {
    let command = compile_sql_command::<SqlLowerEntity>(
        "SELECT COUNT(*) AS total_rows \
         FROM SqlLowerEntity \
         HAVING total_rows > 1",
        MissingRowPolicy::Ignore,
    )
    .expect("aliased global aggregate HAVING should lower through the dedicated aggregate lane");

    let SqlCommand::GlobalAggregate(command) = command else {
        panic!("aliased global aggregate HAVING should lower to the dedicated aggregate command");
    };

    assert!(
        command.having().is_some(),
        "aliased global aggregate HAVING should normalize onto the shared post-aggregate expression contract",
    );
    assert_eq!(
        command.terminals().len(),
        1,
        "aliased global aggregate HAVING should still reuse the single unique aggregate terminal",
    );
}

#[test]
fn compile_sql_command_select_grouped_aggregate_parity_matches_query_and_executable_identity() {
    // Phase 1: lower equivalent grouped SQL and fluent grouped intents.
    let sql_query = compile_sql_lower_query_command(
        "SELECT age, COUNT(*) \
         FROM SqlLowerEntity \
         WHERE age >= 21 \
         GROUP BY age \
         ORDER BY age DESC LIMIT 3 OFFSET 1",
        "grouped aggregate SQL query",
    );
    let fluent_query = Query::<SqlLowerEntity>::new(MissingRowPolicy::Ignore)
        .filter(FieldRef::new("age").gte(21_i64))
        .group_by("age")
        .expect("fluent grouped query should accept grouped field")
        .aggregate(crate::db::count())
        .order_term(crate::db::desc("age"))
        .limit(3)
        .offset(1);

    // Phase 2: assert canonical planned identity + fingerprint parity.
    let sql_compiled = sql_query.plan().expect("grouped SQL plan should build");
    let fluent_compiled = fluent_query
        .plan()
        .expect("fluent grouped plan should build");
    assert_eq!(
        sql_compiled.into_inner(),
        fluent_compiled.into_inner(),
        "grouped SQL lowering and fluent grouped query must produce identical normalized planned intent",
    );
    assert_eq!(
        sql_query
            .plan_hash_hex()
            .expect("grouped SQL plan hash should build"),
        fluent_query
            .plan_hash_hex()
            .expect("fluent grouped plan hash should build"),
        "equivalent grouped SQL and fluent grouped queries must produce identical fingerprints",
    );

    // Phase 3: assert executable-contract parity at route/runtime planning boundary.
    assert_sql_lower_queries_share_executable_identity(
        &sql_query,
        "grouped SQL",
        &fluent_query,
        "fluent grouped",
        "equivalent grouped SQL and fluent grouped queries must produce identical executable family",
        "equivalent grouped SQL and fluent grouped queries must produce identical executable ordering",
    );
}

#[test]
fn compile_sql_command_select_field_projection_parity_matches_query_and_executable_identity() {
    // Phase 1: lower equivalent SQL and fluent field-list intents.
    let sql_query = compile_sql_lower_query_command(
        "SELECT name, age FROM SqlLowerEntity WHERE age >= 21 ORDER BY age DESC LIMIT 5 OFFSET 1",
        "field-list SQL query",
    );
    let fluent_query = Query::<SqlLowerEntity>::new(MissingRowPolicy::Ignore)
        .select_fields(["name", "age"])
        .filter(FieldRef::new("age").gte(21_i64))
        .order_term(crate::db::desc("age"))
        .limit(5)
        .offset(1);

    // Phase 2: assert canonical planned identity + fingerprint parity.
    let sql_compiled = sql_query.plan().expect("SQL plan should build");
    let fluent_compiled = fluent_query.plan().expect("fluent plan should build");
    assert_eq!(
        sql_compiled.into_inner(),
        fluent_compiled.into_inner(),
        "SQL field-list lowering and fluent field-list query must produce identical normalized planned intent",
    );
    assert_eq!(
        sql_query
            .plan_hash_hex()
            .expect("SQL field-list plan hash should build"),
        fluent_query
            .plan_hash_hex()
            .expect("fluent field-list plan hash should build"),
        "equivalent SQL and fluent field-list projections must produce identical fingerprints",
    );

    // Phase 3: assert executable-contract parity at route/runtime planning boundary.
    assert_sql_lower_queries_share_executable_identity(
        &sql_query,
        "SQL field-list",
        &fluent_query,
        "fluent field-list",
        "equivalent SQL and fluent field-list projections must produce identical executable family",
        "equivalent SQL and fluent field-list projections must produce identical executable ordering",
    );
}

#[test]
fn compile_sql_command_rejects_entity_mismatch() {
    let err = compile_sql_command::<SqlLowerEntity>(
        "SELECT * FROM DifferentEntity",
        MissingRowPolicy::Ignore,
    )
    .expect_err("entity mismatch should fail lowering");

    assert!(matches!(err, SqlLoweringError::EntityMismatch { .. }));
}

#[test]
fn compile_sql_global_aggregate_command_count_star_lowers() {
    let command = compile_sql_lower_global_aggregate_command(
        "SELECT COUNT(*) FROM SqlLowerEntity WHERE age >= 21",
        "global aggregate count SQL",
    );

    assert_count_rows_strategy(command.terminal());
    assert!(
        !command.query().has_grouping(),
        "global aggregate SQL command should lower to scalar base query shape",
    );
}

#[test]
fn compile_sql_global_aggregate_command_count_sum_avg_min_max_lower() {
    let count_by_command = compile_sql_lower_global_aggregate_command(
        "SELECT COUNT(age) FROM SqlLowerEntity",
        "COUNT(field) SQL",
    );
    let sum_command = compile_sql_lower_global_aggregate_command(
        "SELECT SUM(age) FROM SqlLowerEntity",
        "SUM(field) SQL",
    );
    let avg_command = compile_sql_lower_global_aggregate_command(
        "SELECT AVG(age) FROM SqlLowerEntity",
        "AVG(field) SQL",
    );
    let min_command = compile_sql_lower_global_aggregate_command(
        "SELECT MIN(age) FROM SqlLowerEntity",
        "MIN(field) SQL",
    );
    let max_command = compile_sql_lower_global_aggregate_command(
        "SELECT MAX(age) FROM SqlLowerEntity",
        "MAX(field) SQL",
    );

    assert_field_aggregate_strategy(
        count_by_command.terminal(),
        AggregateKind::Count,
        "age",
        false,
    );
    assert_field_aggregate_strategy(sum_command.terminal(), AggregateKind::Sum, "age", false);
    assert_field_aggregate_strategy(avg_command.terminal(), AggregateKind::Avg, "age", false);
    assert_field_aggregate_strategy(min_command.terminal(), AggregateKind::Min, "age", false);
    assert_field_aggregate_strategy(max_command.terminal(), AggregateKind::Max, "age", false);
}

#[test]
fn compile_sql_global_aggregate_command_multiple_terminals_lower() {
    let command = compile_sql_lower_global_aggregate_command(
        "SELECT MIN(age), MAX(age) FROM SqlLowerEntity",
        "multiple global aggregate terminals",
    );

    assert_eq!(
        command.terminals().len(),
        2,
        "multi-terminal global aggregate SQL should preserve both aggregate terminals",
    );
    assert_field_aggregate_strategy(&command.terminals()[0], AggregateKind::Min, "age", false);
    assert_field_aggregate_strategy(&command.terminals()[1], AggregateKind::Max, "age", false);
}

#[test]
fn compile_sql_global_aggregate_command_duplicate_terminals_dedup_to_unique_terminal_remap() {
    let command = compile_sql_lower_global_aggregate_command(
        "SELECT COUNT(age), COUNT(age), SUM(age), COUNT(age) FROM SqlLowerEntity",
        "duplicate global aggregate terminals",
    );

    assert_eq!(
        command.terminals().len(),
        2,
        "duplicate global aggregate SQL should keep only unique executable terminals",
    );
    assert_field_aggregate_strategy(&command.terminals()[0], AggregateKind::Count, "age", false);
    assert_field_aggregate_strategy(&command.terminals()[1], AggregateKind::Sum, "age", false);
    assert_eq!(
        command.output_remap(),
        &[0, 0, 1, 0],
        "duplicate aggregate outputs should remap back to the original projection order",
    );
}

#[test]
fn compile_sql_global_aggregate_command_mixed_duplicate_terminals_preserve_unique_order_remap() {
    let command = compile_sql_lower_global_aggregate_command(
        "SELECT COUNT(age), SUM(age), COUNT(age), SUM(age), MAX(age) FROM SqlLowerEntity",
        "mixed duplicate global aggregate terminals",
    );

    assert_eq!(
        command.terminals().len(),
        3,
        "mixed duplicate global aggregate SQL should keep one unique terminal per aggregate semantics",
    );
    assert_field_aggregate_strategy(&command.terminals()[0], AggregateKind::Count, "age", false);
    assert_field_aggregate_strategy(&command.terminals()[1], AggregateKind::Sum, "age", false);
    assert_field_aggregate_strategy(&command.terminals()[2], AggregateKind::Max, "age", false);
    assert_eq!(
        command.output_remap(),
        &[0, 1, 0, 1, 2],
        "mixed duplicate aggregate outputs should remap to the first-seen unique terminal order",
    );
}

#[test]
fn compile_sql_global_aggregate_command_distinct_terminals_do_not_collapse_into_plain_count() {
    let command = compile_sql_lower_global_aggregate_command(
        "SELECT COUNT(age), COUNT(DISTINCT age), COUNT(age) FROM SqlLowerEntity",
        "distinct and non-distinct global aggregate terminals",
    );

    assert_eq!(
        command.terminals().len(),
        2,
        "COUNT(age) and COUNT(DISTINCT age) should remain separate executable terminals",
    );
    assert_field_aggregate_strategy(&command.terminals()[0], AggregateKind::Count, "age", false);
    assert_field_aggregate_strategy(&command.terminals()[1], AggregateKind::Count, "age", true);
    assert_eq!(
        command.output_remap(),
        &[0, 1, 0],
        "distinct and non-distinct aggregate outputs should only collapse exact duplicates",
    );
}

#[test]
fn compile_sql_global_aggregate_command_extrema_distinct_dedupes_by_semantics() {
    let command = compile_sql_lower_global_aggregate_command(
        "SELECT MIN(age), MIN(DISTINCT age), MAX(DISTINCT age), MAX(age) FROM SqlLowerEntity",
        "extrema DISTINCT aggregate semantic terminals",
    );

    assert_eq!(
        command.terminals().len(),
        2,
        "MIN/MAX DISTINCT should dedupe with their plain extrema semantic terminals",
    );
    assert_field_aggregate_strategy(&command.terminals()[0], AggregateKind::Min, "age", false);
    assert_field_aggregate_strategy(&command.terminals()[1], AggregateKind::Max, "age", false);
    assert_eq!(
        command.output_remap(),
        &[0, 0, 1, 1],
        "semantic extrema dedup should preserve first-seen output remap order",
    );
}

#[test]
fn compile_sql_global_aggregate_command_qualified_and_unqualified_duplicates_collapse() {
    let command = compile_sql_lower_global_aggregate_command(
        "SELECT COUNT(age), COUNT(SqlLowerEntity.age), COUNT(age) FROM SqlLowerEntity",
        "qualified and unqualified duplicate global aggregate terminals",
    );

    assert_eq!(
        command.terminals().len(),
        1,
        "qualified and unqualified aggregate terminals should normalize to one unique executable terminal",
    );
    assert_field_aggregate_strategy(&command.terminals()[0], AggregateKind::Count, "age", false);
    assert_eq!(
        command.output_remap(),
        &[0, 0, 0],
        "qualified and unqualified duplicate outputs should remap to the same unique terminal",
    );
}

#[test]
fn compile_sql_global_aggregate_command_qualified_field_lowers_to_unqualified_terminal() {
    let command = compile_sql_lower_global_aggregate_command(
        "SELECT SUM(SqlLowerEntity.age) FROM SqlLowerEntity",
        "qualified global aggregate field SQL",
    );

    assert_field_aggregate_strategy(command.terminal(), AggregateKind::Sum, "age", false);
}

#[test]
fn compile_sql_global_aggregate_command_accepts_expression_input_terminals() {
    let command = compile_sql_lower_global_aggregate_command(
        "SELECT COUNT(1), SUM(age + 1), AVG(age + 1) FROM SqlLowerEntity",
        "aggregate input expressions",
    );

    assert_eq!(
        command.terminals().len(),
        3,
        "expression aggregate inputs should preserve one prepared strategy per aggregate leaf",
    );
    assert_expr_aggregate_strategy(&command.terminals()[0], AggregateKind::Count, false);
    assert_expr_aggregate_strategy(&command.terminals()[1], AggregateKind::Sum, false);
    assert_expr_aggregate_strategy(&command.terminals()[2], AggregateKind::Avg, false);
}

#[test]
fn compile_sql_global_aggregate_command_accepts_chained_expression_input_terminals() {
    let command = compile_sql_lower_global_aggregate_command(
        "SELECT AVG(age + 1 * 2), ROUND(AVG((age + age) / 2), 2) FROM SqlLowerEntity",
        "chained aggregate input expressions",
    );

    assert_eq!(
        command.terminals().len(),
        2,
        "chained aggregate input expressions should lower onto one terminal per aggregate leaf",
    );
    assert!(
        matches!(
            assert_expr_aggregate_strategy(&command.terminals()[0], AggregateKind::Avg, false),
            Expr::Binary { op: BinaryOp::Add, left, right }
            if matches!(left.as_ref(), Expr::Field(field) if field.as_str() == "age")
                && matches!(right.as_ref(), Expr::Literal(Value::Decimal(value)) if *value == crate::types::Decimal::from(2_u64))
        ),
        "AVG(age + 1 * 2) should preserve the folded semantic input shape in the prepared aggregate strategy",
    );
    assert_eq!(
        command.projection().len(),
        2,
        "chained aggregate input expressions should still preserve the outward projection shape",
    );
}

#[test]
fn compile_sql_global_aggregate_command_accepts_post_aggregate_projection_expressions() {
    let command = compile_sql_lower_global_aggregate_command(
        "SELECT ROUND(AVG(age), 4), COUNT(*) + 1, MAX(age) - MIN(age) FROM SqlLowerEntity",
        "post-aggregate scalar wrappers",
    );

    assert_eq!(
        command.terminals().len(),
        4,
        "wrapped global aggregate output expressions should dedupe onto one unique executable terminal per aggregate leaf",
    );
    assert_eq!(
        command.projection().len(),
        3,
        "wrapped global aggregate output expressions should preserve the outward projection shape",
    );
    assert!(
        command.output_remap().is_empty(),
        "wrapped global aggregate output expressions should stop depending on the legacy top-level terminal remap",
    );
}

#[test]
fn compile_sql_global_aggregate_command_ignores_singleton_output_order_by_alias() {
    let ordered = compile_sql_lower_global_aggregate_command(
        "SELECT AVG(age) AS avg_age FROM SqlLowerEntity ORDER BY avg_age DESC",
        "ordered singleton global aggregate output",
    );
    let canonical = compile_sql_lower_global_aggregate_command(
        "SELECT AVG(age) AS avg_age FROM SqlLowerEntity",
        "canonical singleton global aggregate",
    );

    assert_sql_lower_queries_share_plan_identity(
        ordered.query(),
        "ordered singleton global aggregate base query",
        canonical.query(),
        "canonical singleton global aggregate base query",
        "singleton global aggregate ORDER BY aliases should not leak into the base-row aggregate window query",
    );
}

#[test]
fn compile_sql_global_aggregate_command_ignores_singleton_wrapped_output_order_by_alias() {
    let ordered = compile_sql_lower_global_aggregate_command(
        "SELECT ROUND(AVG(age), 2) AS avg_age FROM SqlLowerEntity ORDER BY avg_age DESC",
        "ordered singleton wrapped global aggregate output",
    );
    let canonical = compile_sql_lower_global_aggregate_command(
        "SELECT ROUND(AVG(age), 2) AS avg_age FROM SqlLowerEntity",
        "canonical singleton wrapped global aggregate",
    );

    assert_sql_lower_queries_share_plan_identity(
        ordered.query(),
        "ordered singleton wrapped global aggregate base query",
        canonical.query(),
        "canonical singleton wrapped global aggregate base query",
        "singleton wrapped global aggregate ORDER BY aliases should not leak into the base-row aggregate window query",
    );
}

#[test]
fn compile_sql_global_aggregate_command_deduplicates_expression_input_terminals() {
    let command = compile_sql_lower_global_aggregate_command(
        "SELECT COUNT(1), SUM(age + 1), COUNT(1), SUM(age + 1) FROM SqlLowerEntity",
        "duplicate expression aggregate inputs",
    );

    assert_eq!(
        command.terminals().len(),
        2,
        "duplicate expression aggregate inputs should keep one unique executable terminal per aggregate semantics",
    );
    assert_expr_aggregate_strategy(&command.terminals()[0], AggregateKind::Count, false);
    assert_expr_aggregate_strategy(&command.terminals()[1], AggregateKind::Sum, false);
    assert_eq!(
        command.output_remap(),
        &[0, 1, 0, 1],
        "duplicate expression aggregate outputs should remap to the first-seen unique terminal order",
    );
}

#[test]
fn compile_sql_global_aggregate_command_constant_folds_expression_input_terminals_before_dedup() {
    let command = compile_sql_lower_global_aggregate_command(
        "SELECT SUM(2 * 3), SUM(6), AVG(ROUND(2 * 3, 1)), AVG(6.0) FROM SqlLowerEntity",
        "constant aggregate input expressions",
    );

    assert_eq!(
        command.terminals().len(),
        2,
        "constant-folded aggregate input expressions should dedupe onto one semantic terminal per aggregate kind",
    );
    assert_eq!(
        assert_expr_aggregate_strategy(&command.terminals()[0], AggregateKind::Sum, false),
        &Expr::Literal(Value::Decimal(crate::types::Decimal::from(6_u64))),
        "SUM(2 * 3) should fold onto the canonical SUM(6) strategy input",
    );
    assert_eq!(
        assert_expr_aggregate_strategy(&command.terminals()[1], AggregateKind::Avg, false),
        &Expr::Literal(Value::Decimal(crate::types::Decimal::from(6_u64))),
        "AVG(ROUND(2 * 3, 1)) should fold onto the canonical AVG(6) strategy input",
    );
    assert_eq!(
        command.output_remap(),
        &[0, 0, 1, 1],
        "constant-folded aggregate outputs should remap to the first-seen folded terminal order",
    );
}

#[test]
fn compile_sql_command_accepts_grouped_aggregate_input_expressions() {
    let command = compile_sql_command::<SqlLowerEntity>(
        "SELECT age, AVG(age + 1) FROM SqlLowerEntity GROUP BY age",
        MissingRowPolicy::Ignore,
    )
    .expect("grouped aggregate input expressions should lower once grouped runtime widens");

    let SqlCommand::Query(query) = command else {
        panic!("expected lowered grouped query command");
    };
    let planned = query
        .plan()
        .expect("grouped aggregate input SQL should plan")
        .into_inner();
    let grouped = planned
        .grouped_plan()
        .expect("grouped aggregate input SQL should keep grouped plan shape");
    let aggregate = grouped
        .group
        .aggregates
        .first()
        .expect("grouped aggregate input SQL should declare one aggregate");

    assert_eq!(aggregate.target_field(), None);
    assert_eq!(
        aggregate.input_expr(),
        Some(&Expr::Binary {
            op: BinaryOp::Add,
            left: Box::new(Expr::Field(FieldId::new("age"))),
            right: Box::new(Expr::Literal(Value::Decimal(crate::types::Decimal::from(
                1_u64
            ),))),
        }),
        "grouped aggregate input SQL should preserve the canonical normalized aggregate input expression in grouped plan semantics",
    );
}

#[test]
fn compile_sql_global_aggregate_command_accepts_case_input_expressions() {
    let command = compile_sql_lower_global_aggregate_command(
        "SELECT SUM(CASE WHEN age >= 21 THEN 1 ELSE 0 END) FROM SqlLowerEntity",
        "searched CASE aggregate inputs",
    );
    let terminal = command.terminal();

    assert!(
        matches!(
            assert_expr_aggregate_strategy(terminal, AggregateKind::Sum, false),
            Expr::Case {
                when_then_arms,
                else_expr,
            }
                if when_then_arms.as_slice() == [CaseWhenArm::new(
                    Expr::Binary {
                        op: BinaryOp::Gte,
                        left: Box::new(Expr::Field(FieldId::new("age"))),
                        right: Box::new(Expr::Literal(Value::Decimal(
                            crate::types::Decimal::from(21_u64),
                        ))),
                    },
                    Expr::Literal(Value::Decimal(crate::types::Decimal::from(1_u64))),
                )]
                    && else_expr.as_ref()
                        == &Expr::Literal(Value::Decimal(crate::types::Decimal::from(0_u64)))
        ),
        "searched CASE aggregate inputs should lower through the shared pre-aggregate expression seam: {terminal:?}",
    );
}

fn assert_count_rows_strategy(strategy: &PreparedSqlScalarAggregateStrategy) {
    assert_eq!(
        strategy.descriptor_shape(),
        PreparedSqlScalarAggregateDescriptorShape::CountRows,
        "COUNT(*) should lower to the dedicated count-rows prepared strategy",
    );
    assert_eq!(
        strategy.aggregate_kind(),
        AggregateKind::Count,
        "COUNT(*) should preserve COUNT aggregate semantics",
    );
    assert!(
        strategy.target_slot().is_none(),
        "COUNT(*) should not resolve a field target slot",
    );
    assert!(
        strategy.input_expr().is_none(),
        "COUNT(*) should not keep an input expression payload",
    );
    assert!(
        !strategy.is_distinct(),
        "COUNT(*) should not preserve distinct-input semantics",
    );
}

fn assert_field_aggregate_strategy(
    strategy: &PreparedSqlScalarAggregateStrategy,
    kind: AggregateKind,
    field: &str,
    distinct: bool,
) {
    assert_eq!(
        strategy.aggregate_kind(),
        kind,
        "field-target aggregate should preserve aggregate kind",
    );
    assert_eq!(
        strategy
            .target_slot()
            .expect("field-target aggregate should resolve target slot")
            .field(),
        field,
        "field-target aggregate should resolve the canonical target slot",
    );
    assert!(
        strategy.input_expr().is_none(),
        "field-target aggregate should not retain an input expression payload",
    );
    assert_eq!(
        strategy.is_distinct(),
        distinct,
        "field-target aggregate should preserve distinct-input semantics",
    );
}

fn assert_expr_aggregate_strategy(
    strategy: &PreparedSqlScalarAggregateStrategy,
    kind: AggregateKind,
    distinct: bool,
) -> &Expr {
    assert_eq!(
        strategy.aggregate_kind(),
        kind,
        "expression aggregate should preserve aggregate kind",
    );
    assert!(
        strategy.target_slot().is_none(),
        "expression aggregate should not resolve a field target slot",
    );
    assert_eq!(
        strategy.is_distinct(),
        distinct,
        "expression aggregate should preserve distinct-input semantics",
    );

    strategy
        .input_expr()
        .expect("expression aggregate should retain canonical input expression")
}

fn compile_prepared_sql_scalar_strategy(sql: &str) -> PreparedSqlScalarAggregateStrategy {
    let command = compile_sql_lower_global_aggregate_command(sql, "prepared scalar aggregate SQL");

    command.terminal().clone()
}

///
/// ExpectedPreparedSqlScalarAggregateStrategy
///
/// Test-only expectation bundle for prepared SQL scalar aggregate strategy
/// assertions. This keeps the descriptor/domain/runtime contract checks on one
/// helper seam instead of repeating the same assertion block per aggregate kind.
///

struct ExpectedPreparedSqlScalarAggregateStrategy {
    sql: &'static str,
    aggregate_kind: AggregateKind,
    descriptor_shape: PreparedSqlScalarAggregateDescriptorShape,
    plan_fragment: PreparedSqlScalarAggregatePlanFragment,
    target_field: Option<&'static str>,
    distinct: bool,
}

fn assert_prepared_sql_scalar_strategy(expected: &ExpectedPreparedSqlScalarAggregateStrategy) {
    let strategy = compile_prepared_sql_scalar_strategy(expected.sql);

    assert_eq!(
        strategy.aggregate_kind(),
        expected.aggregate_kind,
        "prepared aggregate strategy should preserve aggregate kind: {}",
        expected.sql,
    );
    assert_eq!(
        strategy.descriptor_shape(),
        expected.descriptor_shape,
        "prepared aggregate strategy should preserve descriptor shape: {}",
        expected.sql,
    );
    assert_eq!(
        strategy.plan_fragment(),
        expected.plan_fragment,
        "prepared aggregate strategy should preserve plan fragment: {}",
        expected.sql,
    );
    assert_eq!(
        strategy.is_distinct(),
        expected.distinct,
        "prepared aggregate strategy should preserve distinct-input semantics: {}",
        expected.sql,
    );

    if let Some(field) = expected.target_field {
        assert_eq!(
            strategy
                .target_slot()
                .expect("field-target strategy should keep target slot")
                .field(),
            field,
            "prepared aggregate strategy should preserve canonical target slot: {}",
            expected.sql,
        );
        assert!(
            strategy.input_expr().is_none(),
            "field-target strategy should not retain input expression payload: {}",
            expected.sql,
        );
    } else {
        assert!(
            strategy.target_slot().is_none(),
            "non-field strategy should not resolve target slot: {}",
            expected.sql,
        );
        assert!(
            strategy.input_expr().is_none(),
            "non-field strategy should not retain input expression payload: {}",
            expected.sql,
        );
    }
}

#[test]
fn compile_sql_global_aggregate_command_prepares_scalar_strategies_for_field_and_row_shapes() {
    for expected in [
        ExpectedPreparedSqlScalarAggregateStrategy {
            sql: "SELECT COUNT(*) FROM SqlLowerEntity",
            aggregate_kind: AggregateKind::Count,
            descriptor_shape: PreparedSqlScalarAggregateDescriptorShape::CountRows,
            plan_fragment: PreparedSqlScalarAggregatePlanFragment::CountRows,
            target_field: None,
            distinct: false,
        },
        ExpectedPreparedSqlScalarAggregateStrategy {
            sql: "SELECT COUNT(age) FROM SqlLowerEntity",
            aggregate_kind: AggregateKind::Count,
            descriptor_shape: PreparedSqlScalarAggregateDescriptorShape::CountField,
            plan_fragment: PreparedSqlScalarAggregatePlanFragment::CountField,
            target_field: Some("age"),
            distinct: false,
        },
        ExpectedPreparedSqlScalarAggregateStrategy {
            sql: "SELECT SUM(age) FROM SqlLowerEntity",
            aggregate_kind: AggregateKind::Sum,
            descriptor_shape: PreparedSqlScalarAggregateDescriptorShape::NumericField {
                kind: AggregateKind::Sum,
            },
            plan_fragment: PreparedSqlScalarAggregatePlanFragment::NumericField {
                kind: AggregateKind::Sum,
            },
            target_field: Some("age"),
            distinct: false,
        },
        ExpectedPreparedSqlScalarAggregateStrategy {
            sql: "SELECT MIN(age) FROM SqlLowerEntity",
            aggregate_kind: AggregateKind::Min,
            descriptor_shape: PreparedSqlScalarAggregateDescriptorShape::ExtremalWinnerField {
                kind: AggregateKind::Min,
            },
            plan_fragment: PreparedSqlScalarAggregatePlanFragment::ExtremalWinnerField {
                kind: AggregateKind::Min,
            },
            target_field: Some("age"),
            distinct: false,
        },
    ] {
        assert_prepared_sql_scalar_strategy(&expected);
    }
}

#[test]
fn compile_sql_global_aggregate_command_prepares_scalar_strategies_for_distinct_field_shapes() {
    for expected in [
        ExpectedPreparedSqlScalarAggregateStrategy {
            sql: "SELECT COUNT(DISTINCT age) FROM SqlLowerEntity",
            aggregate_kind: AggregateKind::Count,
            descriptor_shape: PreparedSqlScalarAggregateDescriptorShape::CountField,
            plan_fragment: PreparedSqlScalarAggregatePlanFragment::CountField,
            target_field: Some("age"),
            distinct: true,
        },
        ExpectedPreparedSqlScalarAggregateStrategy {
            sql: "SELECT SUM(DISTINCT age) FROM SqlLowerEntity",
            aggregate_kind: AggregateKind::Sum,
            descriptor_shape: PreparedSqlScalarAggregateDescriptorShape::NumericField {
                kind: AggregateKind::Sum,
            },
            plan_fragment: PreparedSqlScalarAggregatePlanFragment::NumericField {
                kind: AggregateKind::Sum,
            },
            target_field: Some("age"),
            distinct: true,
        },
        ExpectedPreparedSqlScalarAggregateStrategy {
            sql: "SELECT AVG(DISTINCT age) FROM SqlLowerEntity",
            aggregate_kind: AggregateKind::Avg,
            descriptor_shape: PreparedSqlScalarAggregateDescriptorShape::NumericField {
                kind: AggregateKind::Avg,
            },
            plan_fragment: PreparedSqlScalarAggregatePlanFragment::NumericField {
                kind: AggregateKind::Avg,
            },
            target_field: Some("age"),
            distinct: true,
        },
        ExpectedPreparedSqlScalarAggregateStrategy {
            sql: "SELECT MIN(DISTINCT age) FROM SqlLowerEntity",
            aggregate_kind: AggregateKind::Min,
            descriptor_shape: PreparedSqlScalarAggregateDescriptorShape::ExtremalWinnerField {
                kind: AggregateKind::Min,
            },
            plan_fragment: PreparedSqlScalarAggregatePlanFragment::ExtremalWinnerField {
                kind: AggregateKind::Min,
            },
            target_field: Some("age"),
            distinct: false,
        },
        ExpectedPreparedSqlScalarAggregateStrategy {
            sql: "SELECT MAX(DISTINCT age) FROM SqlLowerEntity",
            aggregate_kind: AggregateKind::Max,
            descriptor_shape: PreparedSqlScalarAggregateDescriptorShape::ExtremalWinnerField {
                kind: AggregateKind::Max,
            },
            plan_fragment: PreparedSqlScalarAggregatePlanFragment::ExtremalWinnerField {
                kind: AggregateKind::Max,
            },
            target_field: Some("age"),
            distinct: false,
        },
    ] {
        assert_prepared_sql_scalar_strategy(&expected);
    }
}

#[test]
fn compile_sql_global_aggregate_command_prepares_scalar_strategies_for_distinct_expression_shapes()
{
    let sum_terminal = compile_sql_lower_global_aggregate_command(
        "SELECT SUM(DISTINCT age + 1) FROM SqlLowerEntity",
        "distinct SUM expression aggregate input",
    )
    .terminal()
    .clone();
    let min_terminal = compile_sql_lower_global_aggregate_command(
        "SELECT MIN(DISTINCT age + 1) FROM SqlLowerEntity",
        "distinct MIN expression aggregate input",
    )
    .terminal()
    .clone();

    assert_expr_aggregate_strategy(&sum_terminal, AggregateKind::Sum, true);
    assert_expr_aggregate_strategy(&min_terminal, AggregateKind::Min, false);
}

#[test]
fn compile_sql_global_aggregate_command_preserves_base_query_window_semantics() {
    let command = compile_sql_global_aggregate_command::<SqlLowerEntity>(
        "SELECT SUM(age) FROM SqlLowerEntity WHERE age >= 21 ORDER BY age DESC LIMIT 2 OFFSET 1",
        MissingRowPolicy::Ignore,
    )
    .expect("global aggregate SQL command should lower");
    let fluent_query = Query::<SqlLowerEntity>::new(MissingRowPolicy::Ignore)
        .filter(FieldRef::new("age").gte(21_i64))
        .order_term(crate::db::desc("age"))
        .limit(2)
        .offset(1);

    assert_sql_lower_queries_share_plan_identity(
        command.query(),
        "SQL global aggregate base query",
        &fluent_query,
        "fluent base query",
        "global aggregate SQL lowering should preserve scalar base query predicate/order/window semantics",
    );
    assert_sql_lower_queries_share_plan_hash(
        command.query(),
        "SQL global aggregate base query",
        &fluent_query,
        "fluent base query",
        "global aggregate SQL lowering should preserve deterministic base query fingerprint semantics",
    );
}

#[test]
fn compile_sql_global_aggregate_command_parity_matches_fluent_query_and_executable_identity() {
    // Phase 1: lower equivalent global aggregate SQL and fluent scalar base query intent.
    let sql_command = compile_sql_global_aggregate_command::<SqlLowerEntity>(
        "SELECT SUM(age) \
         FROM SqlLowerEntity \
         WHERE age >= 21 \
         ORDER BY age DESC LIMIT 3 OFFSET 1",
        MissingRowPolicy::Ignore,
    )
    .expect("global aggregate SQL should lower");
    let fluent_query = Query::<SqlLowerEntity>::new(MissingRowPolicy::Ignore)
        .filter(FieldRef::new("age").gte(21_i64))
        .order_term(crate::db::desc("age"))
        .limit(3)
        .offset(1);

    // Phase 2: assert aggregate-terminal contract and canonical planned identity + fingerprint parity.
    assert_field_aggregate_strategy(sql_command.terminal(), AggregateKind::Sum, "age", false);
    assert_sql_lower_queries_share_plan_identity(
        sql_command.query(),
        "global aggregate SQL base query",
        &fluent_query,
        "fluent scalar base query",
        "global aggregate SQL base query lowering and fluent scalar query must produce identical normalized planned intent",
    );
    assert_sql_lower_queries_share_plan_hash(
        sql_command.query(),
        "global aggregate SQL base query",
        &fluent_query,
        "fluent scalar base query",
        "equivalent global aggregate SQL base query and fluent scalar query must produce identical fingerprints",
    );

    // Phase 3: assert executable-contract parity at route/runtime planning boundary.
    assert_sql_lower_queries_share_executable_identity(
        sql_command.query(),
        "global aggregate SQL base query",
        &fluent_query,
        "fluent scalar base query",
        "equivalent global aggregate SQL base query and fluent scalar query must produce identical executable family",
        "equivalent global aggregate SQL base query and fluent scalar query must produce identical executable ordering",
    );
}

#[test]
fn compile_sql_global_aggregate_command_rejects_unsupported_shapes() {
    for sql in [
        "SELECT age FROM SqlLowerEntity",
        "SELECT COUNT(*), age FROM SqlLowerEntity",
    ] {
        let err =
            compile_sql_global_aggregate_command::<SqlLowerEntity>(sql, MissingRowPolicy::Ignore)
                .expect_err("unsupported global aggregate SQL shape should fail closed");

        assert!(
            matches!(err, SqlLoweringError::UnsupportedGlobalAggregateProjection),
            "unsupported global aggregate SQL shape should remain lowering-gated: {sql}",
        );
    }

    let err = compile_sql_global_aggregate_command::<SqlLowerEntity>(
        "SELECT age, COUNT(*) FROM SqlLowerEntity GROUP BY age",
        MissingRowPolicy::Ignore,
    )
    .expect_err("grouped SQL shape should stay out of the dedicated global aggregate lane");

    assert!(
        matches!(err, SqlLoweringError::GlobalAggregateDoesNotSupportGroupBy),
        "grouped SQL shape should fail through the grouped/global aggregate boundary specifically",
    );
}

#[test]
fn compile_sql_global_aggregate_command_accepts_global_aggregate_having() {
    let command = compile_sql_global_aggregate_command::<SqlLowerEntity>(
        "SELECT COUNT(*) FROM SqlLowerEntity HAVING COUNT(*) > 1",
        MissingRowPolicy::Ignore,
    )
    .expect("global aggregate lane should admit aggregate-only HAVING");

    assert!(
        command.having().is_some(),
        "global aggregate HAVING should lower onto the shared post-aggregate boolean contract",
    );
    assert_eq!(
        command.terminals().len(),
        1,
        "global aggregate HAVING should reuse the same unique terminal list instead of introducing a second aggregate lane",
    );
    assert_count_rows_strategy(&command.terminals()[0]);
}

#[test]
fn compile_sql_global_aggregate_command_without_else_canonicalizes_to_null_family() {
    let command = compile_sql_global_aggregate_command::<SqlLowerEntity>(
        "SELECT COUNT(*) \
         FROM SqlLowerEntity \
         HAVING CASE WHEN COUNT(*) > 1 THEN TRUE END",
        MissingRowPolicy::Ignore,
    )
    .expect("global aggregate omitted-ELSE grouped boolean HAVING should lower");

    let case_expr = Expr::Case {
        when_then_arms: vec![CaseWhenArm::new(
            Expr::Binary {
                op: BinaryOp::Gt,
                left: Box::new(Expr::Aggregate(crate::db::count())),
                right: Box::new(Expr::Literal(Value::Int(1))),
            },
            Expr::Literal(Value::Bool(true)),
        )],
        else_expr: Box::new(Expr::Literal(Value::Null)),
    };

    assert_eq!(
        command.having(),
        Some(&canonicalize_grouped_having_bool_expr(case_expr)),
        "global aggregate omitted-ELSE grouped boolean HAVING should join the explicit ELSE NULL canonical family when the grouped boolean proof succeeds",
    );
}

#[test]
fn compile_sql_global_aggregate_command_without_else_truth_wrapper_keeps_same_null_family_shape() {
    let canonical = compile_sql_global_aggregate_command::<SqlLowerEntity>(
        "SELECT COUNT(*) \
         FROM SqlLowerEntity \
         HAVING CASE WHEN COUNT(*) > 1 THEN TRUE ELSE NULL END",
        MissingRowPolicy::Ignore,
    )
    .expect("global aggregate explicit ELSE NULL grouped boolean HAVING should lower");
    let wrapped = compile_sql_global_aggregate_command::<SqlLowerEntity>(
        "SELECT COUNT(*) \
         FROM SqlLowerEntity \
         HAVING CASE WHEN (COUNT(*) > 1) = TRUE THEN TRUE END",
        MissingRowPolicy::Ignore,
    )
    .expect("truth-wrapped global aggregate omitted-ELSE grouped boolean HAVING should lower");

    assert_eq!(
        canonical.having(),
        wrapped.having(),
        "truth-wrapped global aggregate omitted-ELSE grouped boolean HAVING should join the same explicit ELSE NULL canonical family",
    );
    assert_eq!(
        canonical.terminals(),
        wrapped.terminals(),
        "truth-wrapped global aggregate omitted-ELSE grouped boolean HAVING should keep the same unique terminal contract as the explicit ELSE NULL family",
    );
}

#[test]
fn compile_sql_global_aggregate_command_rejects_value_case_without_else() {
    let err = compile_sql_global_aggregate_command::<SqlLowerEntity>(
        "SELECT COUNT(*) \
         FROM SqlLowerEntity \
         HAVING CASE WHEN COUNT(*) > 1 THEN 1 END = 1",
        MissingRowPolicy::Ignore,
    )
    .expect_err(
        "global aggregate omitted-ELSE searched CASE outside the admitted boolean family must fail closed",
    );

    assert!(
        matches!(err, SqlLoweringError::UnsupportedSelectHaving),
        "global aggregate omitted-ELSE searched CASE outside the admitted boolean family should reject with the grouped/global HAVING boundary error: {err:?}",
    );
}

#[test]
fn compile_sql_global_aggregate_having_matches_fluent_global_aggregate_intent() {
    let command = compile_sql_global_aggregate_command::<SqlLowerEntity>(
        "SELECT COUNT(*) FROM SqlLowerEntity HAVING COUNT(*) > 1",
        MissingRowPolicy::Ignore,
    )
    .expect("global aggregate SQL HAVING should lower");
    let fluent = Query::<SqlLowerEntity>::new(MissingRowPolicy::Ignore)
        .aggregate(crate::db::count())
        .having_aggregate(
            0,
            CompareOp::Gt,
            crate::value::InputValue::from(Value::Int(1)),
        )
        .expect("global aggregate fluent HAVING should append")
        .plan()
        .expect("global aggregate fluent HAVING should plan")
        .into_inner();
    let Some(grouped) = fluent.grouped_plan() else {
        panic!("global aggregate fluent HAVING should compile to grouped logical plan");
    };

    assert_eq!(
        command.having(),
        grouped.having_expr.as_ref(),
        "global aggregate SQL and fluent HAVING should share the same post-aggregate expression shape",
    );
}

#[test]
fn compile_sql_global_aggregate_command_rejects_direct_field_global_having() {
    let err = compile_sql_global_aggregate_command::<SqlLowerEntity>(
        "SELECT COUNT(*) FROM SqlLowerEntity HAVING age > 1",
        MissingRowPolicy::Ignore,
    )
    .expect_err("global aggregate HAVING should stay aggregate-only");

    assert!(
        matches!(err, SqlLoweringError::UnsupportedSelectHaving),
        "global aggregate HAVING should reject direct field references through the existing HAVING boundary",
    );
}

#[test]
fn compile_sql_global_aggregate_command_rejection_message_names_global_aggregate_list_support() {
    let err = compile_sql_global_aggregate_command::<SqlLowerEntity>(
        "SELECT MIN(age), name FROM SqlLowerEntity",
        MissingRowPolicy::Ignore,
    )
    .expect_err("mixed global aggregate and scalar projection should remain fail-closed");

    assert!(
        err.to_string()
            .contains("scalar wrappers over aggregate results"),
        "mixed aggregate rejection should name the admitted global aggregate list shape: {err}",
    );
}

#[test]
fn sql_global_aggregate_terminal_runtime_mapping_stays_strategy_owned() {
    let aggregate_root =
        FsPath::new(env!("CARGO_MANIFEST_DIR")).join("src/db/sql/lowering/aggregate");
    let mut sources = Vec::new();
    collect_rust_sources(aggregate_root.as_path(), &mut sources);
    sources.sort();

    let mut violations = Vec::new();
    for source_path in sources {
        let relative = source_path
            .strip_prefix(
                FsPath::new(env!("CARGO_MANIFEST_DIR"))
                    .join("src")
                    .as_path(),
            )
            .unwrap_or_else(|err| {
                panic!(
                    "failed to compute relative source path for {}: {err}",
                    source_path.display()
                )
            });
        if relative == FsPath::new("db/sql/lowering/aggregate/strategy.rs")
            || relative == FsPath::new("db/sql/lowering/aggregate/terminal.rs")
        {
            continue;
        }

        let source = fs::read_to_string(&source_path)
            .unwrap_or_else(|err| panic!("failed to read {}: {err}", source_path.display()));
        if source.contains("StructuralAggregateTerminal")
            || source.contains("StructuralAggregateTerminalKind")
            || source.contains("into_executor_terminal")
        {
            violations.push(relative.display().to_string());
        }
    }

    assert!(
        violations.is_empty(),
        "SQL global aggregate terminal runtime mapping must remain strategy-owned; unexpected references: {violations:?}",
    );
}

// Walk one source tree and collect every Rust source path deterministically.
fn collect_rust_sources(root: &FsPath, out: &mut Vec<PathBuf>) {
    let entries = fs::read_dir(root)
        .unwrap_or_else(|err| panic!("failed to read source directory {}: {err}", root.display()));
    for entry in entries {
        let entry = entry.unwrap_or_else(|err| {
            panic!(
                "failed to read source directory entry under {}: {err}",
                root.display()
            )
        });
        let path = entry.path();
        if path.is_dir() {
            collect_rust_sources(path.as_path(), out);
        } else if path.extension().is_some_and(|extension| extension == "rs") {
            out.push(path);
        }
    }
}