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
// Copyright Materialize, Inc. and contributors. All rights reserved.
//
// Use of this software is governed by the Business Source License
// included in the LICENSE file.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0.

//! This file houses a representation of a SQL plan that is parallel to that found in
//! src/expr/relation/mod.rs, but represents an earlier phase of planning. It's structurally very
//! similar to that file, with some differences which are noted below. It gets turned into that
//! representation via a call to lower().

use std::collections::{BTreeMap, BTreeSet};
use std::fmt::{Display, Formatter};
use std::{fmt, mem};

use itertools::Itertools;
use mz_expr::virtual_syntax::{AlgExcept, Except, IR};
use mz_expr::visit::{Visit, VisitChildren};
use mz_expr::{func, CollectionPlan, Id, LetRecLimit, RowSetFinishing};
// these happen to be unchanged at the moment, but there might be additions later
use mz_expr::AggregateFunc::{FusedWindowAggregate, WindowAggregate};
pub use mz_expr::{
    BinaryFunc, ColumnOrder, TableFunc, UnaryFunc, UnmaterializableFunc, VariadicFunc, WindowFrame,
};
use mz_ore::collections::CollectionExt;
use mz_ore::stack;
use mz_ore::stack::RecursionLimitError;
use mz_ore::str::separated;
use mz_repr::adt::array::ArrayDimension;
use mz_repr::adt::numeric::NumericMaxScale;
use mz_repr::*;
use serde::{Deserialize, Serialize};

use crate::plan::error::PlanError;
use crate::plan::query::ExprContext;
use crate::plan::typeconv::{self, CastContext};
use crate::plan::Params;

use super::plan_utils::GroupSizeHints;

#[allow(missing_debug_implementations)]
pub struct Hir;

impl IR for Hir {
    type Relation = HirRelationExpr;
    type Scalar = HirScalarExpr;
}

impl AlgExcept for Hir {
    fn except(all: &bool, lhs: Self::Relation, rhs: Self::Relation) -> Self::Relation {
        if *all {
            let rhs = rhs.negate();
            HirRelationExpr::union(lhs, rhs).threshold()
        } else {
            let lhs = lhs.distinct();
            let rhs = rhs.distinct().negate();
            HirRelationExpr::union(lhs, rhs).threshold()
        }
    }

    fn un_except<'a>(expr: &'a Self::Relation) -> Option<Except<'a, Self>> {
        let mut result = None;

        use HirRelationExpr::*;
        if let Threshold { input } = expr {
            if let Union { base: lhs, inputs } = input.as_ref() {
                if let [rhs] = &inputs[..] {
                    if let Negate { input: rhs } = rhs {
                        match (lhs.as_ref(), rhs.as_ref()) {
                            (Distinct { input: lhs }, Distinct { input: rhs }) => {
                                let all = false;
                                let lhs = lhs.as_ref();
                                let rhs = rhs.as_ref();
                                result = Some(Except { all, lhs, rhs })
                            }
                            (lhs, rhs) => {
                                let all = true;
                                result = Some(Except { all, lhs, rhs })
                            }
                        }
                    }
                }
            }
        }

        result
    }
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
/// Just like [`mz_expr::MirRelationExpr`], except where otherwise noted below.
pub enum HirRelationExpr {
    Constant {
        rows: Vec<Row>,
        typ: RelationType,
    },
    Get {
        id: mz_expr::Id,
        typ: RelationType,
    },
    /// Mutually recursive CTE
    LetRec {
        /// Maximum number of iterations to evaluate. If None, then there is no limit.
        limit: Option<LetRecLimit>,
        /// List of bindings all of which are in scope of each other.
        bindings: Vec<(String, mz_expr::LocalId, HirRelationExpr, RelationType)>,
        /// Result of the AST node.
        body: Box<HirRelationExpr>,
    },
    /// CTE
    Let {
        name: String,
        /// The identifier to be used in `Get` variants to retrieve `value`.
        id: mz_expr::LocalId,
        /// The collection to be bound to `name`.
        value: Box<HirRelationExpr>,
        /// The result of the `Let`, evaluated with `name` bound to `value`.
        body: Box<HirRelationExpr>,
    },
    Project {
        input: Box<HirRelationExpr>,
        outputs: Vec<usize>,
    },
    Map {
        input: Box<HirRelationExpr>,
        scalars: Vec<HirScalarExpr>,
    },
    CallTable {
        func: TableFunc,
        exprs: Vec<HirScalarExpr>,
    },
    Filter {
        input: Box<HirRelationExpr>,
        predicates: Vec<HirScalarExpr>,
    },
    /// Unlike MirRelationExpr, we haven't yet compiled LeftOuter/RightOuter/FullOuter
    /// joins away into more primitive exprs
    Join {
        left: Box<HirRelationExpr>,
        right: Box<HirRelationExpr>,
        on: HirScalarExpr,
        kind: JoinKind,
    },
    /// Unlike MirRelationExpr, when `key` is empty AND `input` is empty this returns
    /// a single row with the aggregates evaluated over empty groups, rather than returning zero
    /// rows
    Reduce {
        input: Box<HirRelationExpr>,
        group_key: Vec<usize>,
        aggregates: Vec<AggregateExpr>,
        expected_group_size: Option<u64>,
    },
    Distinct {
        input: Box<HirRelationExpr>,
    },
    /// Groups and orders within each group, limiting output.
    TopK {
        /// The source collection.
        input: Box<HirRelationExpr>,
        /// Column indices used to form groups.
        group_key: Vec<usize>,
        /// Column indices used to order rows within groups.
        order_key: Vec<ColumnOrder>,
        /// Number of records to retain
        limit: Option<HirScalarExpr>,
        /// Number of records to skip
        offset: usize,
        /// User-supplied hint: how many rows will have the same group key.
        expected_group_size: Option<u64>,
    },
    Negate {
        input: Box<HirRelationExpr>,
    },
    /// Keep rows from a dataflow where the row counts are positive.
    Threshold {
        input: Box<HirRelationExpr>,
    },
    Union {
        base: Box<HirRelationExpr>,
        inputs: Vec<HirRelationExpr>,
    },
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
/// Just like [`mz_expr::MirScalarExpr`], except where otherwise noted below.
pub enum HirScalarExpr {
    /// Unlike mz_expr::MirScalarExpr, we can nest HirRelationExprs via eg Exists. This means that a
    /// variable could refer to a column of the current input, or to a column of an outer relation.
    /// We use ColumnRef to denote the difference.
    Column(ColumnRef),
    Parameter(usize),
    Literal(Row, ColumnType),
    CallUnmaterializable(UnmaterializableFunc),
    CallUnary {
        func: UnaryFunc,
        expr: Box<HirScalarExpr>,
    },
    CallBinary {
        func: BinaryFunc,
        expr1: Box<HirScalarExpr>,
        expr2: Box<HirScalarExpr>,
    },
    CallVariadic {
        func: VariadicFunc,
        exprs: Vec<HirScalarExpr>,
    },
    If {
        cond: Box<HirScalarExpr>,
        then: Box<HirScalarExpr>,
        els: Box<HirScalarExpr>,
    },
    /// Returns true if `expr` returns any rows
    Exists(Box<HirRelationExpr>),
    /// Given `expr` with arity 1. If expr returns:
    /// * 0 rows, return NULL
    /// * 1 row, return the value of that row
    /// * >1 rows, the sql spec says we should throw an error but we can't
    ///   (see <https://github.com/MaterializeInc/database-issues/issues/154>)
    ///   so instead we return all the rows.
    ///   If there are multiple `Select` expressions in a single SQL query, the result is that we take the product of all of them.
    ///   This is counter to the spec, but is consistent with eg postgres' treatment of multiple set-returning-functions
    ///   (see <https://tapoueh.org/blog/2017/10/set-returning-functions-and-postgresql-10/>).
    Select(Box<HirRelationExpr>),
    Windowing(WindowExpr),
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
/// Represents the invocation of a window function over an optional partitioning with an optional
/// order.
pub struct WindowExpr {
    pub func: WindowExprType,
    pub partition_by: Vec<HirScalarExpr>,
    /// ORDER BY is represented in a complicated way: `plan_function_order_by` gave us two things:
    ///  - the `ColumnOrder`s we have put in the `order_by` fields in the `WindowExprType` in `func`
    ///    above,
    ///  - the `HirScalarExpr`s we have put in the following `order_by` field.
    /// These are separated because they are used in different places: the outer `order_by` is used
    /// in the lowering: based on it, we create a Row constructor that collects the scalar exprs;
    /// the inner `order_by` is used in the rendering to actually execute the ordering on these Rows.
    /// (`WindowExpr` exists only in HIR, but not in MIR.)
    /// Note that the `column` field in the `ColumnOrder`s point into the Row constructed in the
    /// lowering, and not to original input columns.
    pub order_by: Vec<HirScalarExpr>,
}

impl WindowExpr {
    pub fn visit_expressions<'a, F, E>(&'a self, f: &mut F) -> Result<(), E>
    where
        F: FnMut(&'a HirScalarExpr) -> Result<(), E>,
    {
        #[allow(deprecated)]
        self.func.visit_expressions(f)?;
        for expr in self.partition_by.iter() {
            f(expr)?;
        }
        for expr in self.order_by.iter() {
            f(expr)?;
        }
        Ok(())
    }

    pub fn visit_expressions_mut<'a, F, E>(&'a mut self, f: &mut F) -> Result<(), E>
    where
        F: FnMut(&'a mut HirScalarExpr) -> Result<(), E>,
    {
        #[allow(deprecated)]
        self.func.visit_expressions_mut(f)?;
        for expr in self.partition_by.iter_mut() {
            f(expr)?;
        }
        for expr in self.order_by.iter_mut() {
            f(expr)?;
        }
        Ok(())
    }
}

impl VisitChildren<HirScalarExpr> for WindowExpr {
    fn visit_children<F>(&self, mut f: F)
    where
        F: FnMut(&HirScalarExpr),
    {
        self.func.visit_children(&mut f);
        for expr in self.partition_by.iter() {
            f(expr);
        }
        for expr in self.order_by.iter() {
            f(expr);
        }
    }

    fn visit_mut_children<F>(&mut self, mut f: F)
    where
        F: FnMut(&mut HirScalarExpr),
    {
        self.func.visit_mut_children(&mut f);
        for expr in self.partition_by.iter_mut() {
            f(expr);
        }
        for expr in self.order_by.iter_mut() {
            f(expr);
        }
    }

    fn try_visit_children<F, E>(&self, mut f: F) -> Result<(), E>
    where
        F: FnMut(&HirScalarExpr) -> Result<(), E>,
        E: From<RecursionLimitError>,
    {
        self.func.try_visit_children(&mut f)?;
        for expr in self.partition_by.iter() {
            f(expr)?;
        }
        for expr in self.order_by.iter() {
            f(expr)?;
        }
        Ok(())
    }

    fn try_visit_mut_children<F, E>(&mut self, mut f: F) -> Result<(), E>
    where
        F: FnMut(&mut HirScalarExpr) -> Result<(), E>,
        E: From<RecursionLimitError>,
    {
        self.func.try_visit_mut_children(&mut f)?;
        for expr in self.partition_by.iter_mut() {
            f(expr)?;
        }
        for expr in self.order_by.iter_mut() {
            f(expr)?;
        }
        Ok(())
    }
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
/// A window function with its parameters.
///
/// There are three types of window functions:
/// - scalar window functions, which return a different scalar value for each
///   row within a partition that depends exclusively on the position of the row
///   within the partition;
/// - value window functions, which return a scalar value for each row within a
///   partition that might be computed based on a single row, which is usually not
///   the current row (e.g., previous or following row; first or last row of the
///   partition);
/// - aggregate window functions, which compute a traditional aggregation as a
///   window function (e.g. `sum(x) OVER (...)`).
///   (Aggregate window  functions can in some cases be computed by joining the
///   input relation with a reduction over the same relation that computes the
///   aggregation using the partition key as its grouping key, but we don't
///   automatically do this currently.)
pub enum WindowExprType {
    Scalar(ScalarWindowExpr),
    Value(ValueWindowExpr),
    Aggregate(AggregateWindowExpr),
}

impl WindowExprType {
    #[deprecated = "Use `VisitChildren<HirScalarExpr>::visit_children` instead."]
    pub fn visit_expressions<'a, F, E>(&'a self, f: &mut F) -> Result<(), E>
    where
        F: FnMut(&'a HirScalarExpr) -> Result<(), E>,
    {
        #[allow(deprecated)]
        match self {
            Self::Scalar(expr) => expr.visit_expressions(f),
            Self::Value(expr) => expr.visit_expressions(f),
            Self::Aggregate(expr) => expr.visit_expressions(f),
        }
    }

    #[deprecated = "Use `VisitChildren<HirScalarExpr>::visit_mut_children` instead."]
    pub fn visit_expressions_mut<'a, F, E>(&'a mut self, f: &mut F) -> Result<(), E>
    where
        F: FnMut(&'a mut HirScalarExpr) -> Result<(), E>,
    {
        #[allow(deprecated)]
        match self {
            Self::Scalar(expr) => expr.visit_expressions_mut(f),
            Self::Value(expr) => expr.visit_expressions_mut(f),
            Self::Aggregate(expr) => expr.visit_expressions_mut(f),
        }
    }

    fn typ(
        &self,
        outers: &[RelationType],
        inner: &RelationType,
        params: &BTreeMap<usize, ScalarType>,
    ) -> ColumnType {
        match self {
            Self::Scalar(expr) => expr.typ(outers, inner, params),
            Self::Value(expr) => expr.typ(outers, inner, params),
            Self::Aggregate(expr) => expr.typ(outers, inner, params),
        }
    }
}

impl VisitChildren<HirScalarExpr> for WindowExprType {
    fn visit_children<F>(&self, f: F)
    where
        F: FnMut(&HirScalarExpr),
    {
        match self {
            Self::Scalar(_) => (),
            Self::Value(expr) => expr.visit_children(f),
            Self::Aggregate(expr) => expr.visit_children(f),
        }
    }

    fn visit_mut_children<F>(&mut self, f: F)
    where
        F: FnMut(&mut HirScalarExpr),
    {
        match self {
            Self::Scalar(_) => (),
            Self::Value(expr) => expr.visit_mut_children(f),
            Self::Aggregate(expr) => expr.visit_mut_children(f),
        }
    }

    fn try_visit_children<F, E>(&self, f: F) -> Result<(), E>
    where
        F: FnMut(&HirScalarExpr) -> Result<(), E>,
        E: From<RecursionLimitError>,
    {
        match self {
            Self::Scalar(_) => Ok(()),
            Self::Value(expr) => expr.try_visit_children(f),
            Self::Aggregate(expr) => expr.try_visit_children(f),
        }
    }

    fn try_visit_mut_children<F, E>(&mut self, f: F) -> Result<(), E>
    where
        F: FnMut(&mut HirScalarExpr) -> Result<(), E>,
        E: From<RecursionLimitError>,
    {
        match self {
            Self::Scalar(_) => Ok(()),
            Self::Value(expr) => expr.try_visit_mut_children(f),
            Self::Aggregate(expr) => expr.try_visit_mut_children(f),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct ScalarWindowExpr {
    pub func: ScalarWindowFunc,
    pub order_by: Vec<ColumnOrder>,
}

impl ScalarWindowExpr {
    #[deprecated = "Implement `VisitChildren<HirScalarExpr>` if needed."]
    pub fn visit_expressions<'a, F, E>(&'a self, _f: &mut F) -> Result<(), E>
    where
        F: FnMut(&'a HirScalarExpr) -> Result<(), E>,
    {
        match self.func {
            ScalarWindowFunc::RowNumber => {}
            ScalarWindowFunc::Rank => {}
            ScalarWindowFunc::DenseRank => {}
        }
        Ok(())
    }

    #[deprecated = "Implement `VisitChildren<HirScalarExpr>` if needed."]
    pub fn visit_expressions_mut<'a, F, E>(&'a self, _f: &mut F) -> Result<(), E>
    where
        F: FnMut(&'a mut HirScalarExpr) -> Result<(), E>,
    {
        match self.func {
            ScalarWindowFunc::RowNumber => {}
            ScalarWindowFunc::Rank => {}
            ScalarWindowFunc::DenseRank => {}
        }
        Ok(())
    }

    fn typ(
        &self,
        _outers: &[RelationType],
        _inner: &RelationType,
        _params: &BTreeMap<usize, ScalarType>,
    ) -> ColumnType {
        self.func.output_type()
    }

    pub fn into_expr(self) -> mz_expr::AggregateFunc {
        match self.func {
            ScalarWindowFunc::RowNumber => mz_expr::AggregateFunc::RowNumber {
                order_by: self.order_by,
            },
            ScalarWindowFunc::Rank => mz_expr::AggregateFunc::Rank {
                order_by: self.order_by,
            },
            ScalarWindowFunc::DenseRank => mz_expr::AggregateFunc::DenseRank {
                order_by: self.order_by,
            },
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
/// Scalar Window functions
pub enum ScalarWindowFunc {
    RowNumber,
    Rank,
    DenseRank,
}

impl Display for ScalarWindowFunc {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            ScalarWindowFunc::RowNumber => write!(f, "row_number"),
            ScalarWindowFunc::Rank => write!(f, "rank"),
            ScalarWindowFunc::DenseRank => write!(f, "dense_rank"),
        }
    }
}

impl ScalarWindowFunc {
    pub fn output_type(&self) -> ColumnType {
        match self {
            ScalarWindowFunc::RowNumber => ScalarType::Int64.nullable(false),
            ScalarWindowFunc::Rank => ScalarType::Int64.nullable(false),
            ScalarWindowFunc::DenseRank => ScalarType::Int64.nullable(false),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct ValueWindowExpr {
    pub func: ValueWindowFunc,
    /// If the argument list has a single element (e.g., for `first_value`), then it's that element.
    /// If the argument list has multiple elements (e.g., for `lag`), then it's encoded in a record,
    /// e.g., `row(#1, 3, null)`.
    /// If it's a fused window function, then the arguments of each of the constituent function
    /// calls are wrapped in an outer record.
    pub args: Box<HirScalarExpr>,
    /// See comment on `WindowExpr::order_by`.
    pub order_by: Vec<ColumnOrder>,
    pub window_frame: WindowFrame,
    pub ignore_nulls: bool,
}

impl Display for ValueWindowFunc {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            ValueWindowFunc::Lag => write!(f, "lag"),
            ValueWindowFunc::Lead => write!(f, "lead"),
            ValueWindowFunc::FirstValue => write!(f, "first_value"),
            ValueWindowFunc::LastValue => write!(f, "last_value"),
            ValueWindowFunc::Fused(funcs) => write!(f, "fused[{}]", separated(", ", funcs)),
        }
    }
}

impl ValueWindowExpr {
    #[deprecated = "Use `VisitChildren<HirScalarExpr>::visit_children` instead."]
    pub fn visit_expressions<'a, F, E>(&'a self, f: &mut F) -> Result<(), E>
    where
        F: FnMut(&'a HirScalarExpr) -> Result<(), E>,
    {
        f(&self.args)
    }

    #[deprecated = "Use `VisitChildren<HirScalarExpr>::visit_mut_children` instead."]
    pub fn visit_expressions_mut<'a, F, E>(&'a mut self, f: &mut F) -> Result<(), E>
    where
        F: FnMut(&'a mut HirScalarExpr) -> Result<(), E>,
    {
        f(&mut self.args)
    }

    fn typ(
        &self,
        outers: &[RelationType],
        inner: &RelationType,
        params: &BTreeMap<usize, ScalarType>,
    ) -> ColumnType {
        self.func.output_type(self.args.typ(outers, inner, params))
    }

    /// Converts into `mz_expr::AggregateFunc`.
    pub fn into_expr(self) -> (Box<HirScalarExpr>, mz_expr::AggregateFunc) {
        (
            self.args,
            self.func
                .into_expr(self.order_by, self.window_frame, self.ignore_nulls),
        )
    }
}

impl VisitChildren<HirScalarExpr> for ValueWindowExpr {
    fn visit_children<F>(&self, mut f: F)
    where
        F: FnMut(&HirScalarExpr),
    {
        f(&self.args)
    }

    fn visit_mut_children<F>(&mut self, mut f: F)
    where
        F: FnMut(&mut HirScalarExpr),
    {
        f(&mut self.args)
    }

    fn try_visit_children<F, E>(&self, mut f: F) -> Result<(), E>
    where
        F: FnMut(&HirScalarExpr) -> Result<(), E>,
        E: From<RecursionLimitError>,
    {
        f(&self.args)
    }

    fn try_visit_mut_children<F, E>(&mut self, mut f: F) -> Result<(), E>
    where
        F: FnMut(&mut HirScalarExpr) -> Result<(), E>,
        E: From<RecursionLimitError>,
    {
        f(&mut self.args)
    }
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
/// Value Window functions
pub enum ValueWindowFunc {
    Lag,
    Lead,
    FirstValue,
    LastValue,
    Fused(Vec<ValueWindowFunc>),
}

impl ValueWindowFunc {
    pub fn output_type(&self, input_type: ColumnType) -> ColumnType {
        match self {
            ValueWindowFunc::Lag | ValueWindowFunc::Lead => {
                // The input is a (value, offset, default) record, so extract the type of the first arg
                input_type.scalar_type.unwrap_record_element_type()[0]
                    .clone()
                    .nullable(true)
            }
            ValueWindowFunc::FirstValue | ValueWindowFunc::LastValue => {
                input_type.scalar_type.nullable(true)
            }
            ValueWindowFunc::Fused(funcs) => {
                let input_types = input_type.scalar_type.unwrap_record_element_column_type();
                ScalarType::Record {
                    fields: funcs
                        .iter()
                        .zip_eq(input_types)
                        .map(|(f, t)| (ColumnName::from(""), f.output_type(t.clone())))
                        .collect(),
                    custom_id: None,
                }
                .nullable(false)
            }
        }
    }

    pub fn into_expr(
        self,
        order_by: Vec<ColumnOrder>,
        window_frame: WindowFrame,
        ignore_nulls: bool,
    ) -> mz_expr::AggregateFunc {
        match self {
            // Lag and Lead are fundamentally the same function, just with opposite directions
            ValueWindowFunc::Lag => mz_expr::AggregateFunc::LagLead {
                order_by,
                lag_lead: mz_expr::LagLeadType::Lag,
                ignore_nulls,
            },
            ValueWindowFunc::Lead => mz_expr::AggregateFunc::LagLead {
                order_by,
                lag_lead: mz_expr::LagLeadType::Lead,
                ignore_nulls,
            },
            ValueWindowFunc::FirstValue => mz_expr::AggregateFunc::FirstValue {
                order_by,
                window_frame,
            },
            ValueWindowFunc::LastValue => mz_expr::AggregateFunc::LastValue {
                order_by,
                window_frame,
            },
            ValueWindowFunc::Fused(funcs) => mz_expr::AggregateFunc::FusedValueWindowFunc {
                funcs: funcs
                    .into_iter()
                    .map(|func| {
                        func.into_expr(order_by.clone(), window_frame.clone(), ignore_nulls)
                    })
                    .collect(),
                order_by,
            },
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct AggregateWindowExpr {
    pub aggregate_expr: AggregateExpr,
    pub order_by: Vec<ColumnOrder>,
    pub window_frame: WindowFrame,
}

impl AggregateWindowExpr {
    #[deprecated = "Use `VisitChildren<HirScalarExpr>::visit_children` instead."]
    pub fn visit_expressions<'a, F, E>(&'a self, f: &mut F) -> Result<(), E>
    where
        F: FnMut(&'a HirScalarExpr) -> Result<(), E>,
    {
        f(&self.aggregate_expr.expr)
    }

    #[deprecated = "Use `VisitChildren<HirScalarExpr>::visit_mut_children` instead."]
    pub fn visit_expressions_mut<'a, F, E>(&'a mut self, f: &mut F) -> Result<(), E>
    where
        F: FnMut(&'a mut HirScalarExpr) -> Result<(), E>,
    {
        f(&mut self.aggregate_expr.expr)
    }

    fn typ(
        &self,
        outers: &[RelationType],
        inner: &RelationType,
        params: &BTreeMap<usize, ScalarType>,
    ) -> ColumnType {
        self.aggregate_expr
            .func
            .output_type(self.aggregate_expr.expr.typ(outers, inner, params))
    }

    pub fn into_expr(self) -> (Box<HirScalarExpr>, mz_expr::AggregateFunc) {
        if let AggregateFunc::FusedWindowAgg { funcs } = &self.aggregate_expr.func {
            (
                self.aggregate_expr.expr,
                FusedWindowAggregate {
                    wrapped_aggregates: funcs.iter().map(|f| f.clone().into_expr()).collect(),
                    order_by: self.order_by,
                    window_frame: self.window_frame,
                },
            )
        } else {
            (
                self.aggregate_expr.expr,
                WindowAggregate {
                    wrapped_aggregate: Box::new(self.aggregate_expr.func.into_expr()),
                    order_by: self.order_by,
                    window_frame: self.window_frame,
                },
            )
        }
    }
}

impl VisitChildren<HirScalarExpr> for AggregateWindowExpr {
    fn visit_children<F>(&self, mut f: F)
    where
        F: FnMut(&HirScalarExpr),
    {
        f(&self.aggregate_expr.expr)
    }

    fn visit_mut_children<F>(&mut self, mut f: F)
    where
        F: FnMut(&mut HirScalarExpr),
    {
        f(&mut self.aggregate_expr.expr)
    }

    fn try_visit_children<F, E>(&self, mut f: F) -> Result<(), E>
    where
        F: FnMut(&HirScalarExpr) -> Result<(), E>,
        E: From<RecursionLimitError>,
    {
        f(&self.aggregate_expr.expr)
    }

    fn try_visit_mut_children<F, E>(&mut self, mut f: F) -> Result<(), E>
    where
        F: FnMut(&mut HirScalarExpr) -> Result<(), E>,
        E: From<RecursionLimitError>,
    {
        f(&mut self.aggregate_expr.expr)
    }
}

/// A `CoercibleScalarExpr` is a [`HirScalarExpr`] whose type is not fully
/// determined. Several SQL expressions can be freely coerced based upon where
/// in the expression tree they appear. For example, the string literal '42'
/// will be automatically coerced to the integer 42 if used in a numeric
/// context:
///
/// ```sql
/// SELECT '42' + 42
/// ```
///
/// This separate type gives the code that needs to interact with coercions very
/// fine-grained control over what coercions happen and when.
///
/// The primary driver of coercion is function and operator selection, as
/// choosing the correct function or operator implementation depends on the type
/// of the provided arguments. Coercion also occurs at the very root of the
/// scalar expression tree. For example in
///
/// ```sql
/// SELECT ... WHERE $1
/// ```
///
/// the `WHERE` clause will coerce the contained unconstrained type parameter
/// `$1` to have type bool.
#[derive(Clone, Debug)]
pub enum CoercibleScalarExpr {
    Coerced(HirScalarExpr),
    Parameter(usize),
    LiteralNull,
    LiteralString(String),
    LiteralRecord(Vec<CoercibleScalarExpr>),
}

impl CoercibleScalarExpr {
    pub fn type_as(self, ecx: &ExprContext, ty: &ScalarType) -> Result<HirScalarExpr, PlanError> {
        let expr = typeconv::plan_coerce(ecx, self, ty)?;
        let expr_ty = ecx.scalar_type(&expr);
        if ty != &expr_ty {
            sql_bail!(
                "{} must have type {}, not type {}",
                ecx.name,
                ecx.humanize_scalar_type(ty),
                ecx.humanize_scalar_type(&expr_ty),
            );
        }
        Ok(expr)
    }

    pub fn type_as_any(self, ecx: &ExprContext) -> Result<HirScalarExpr, PlanError> {
        typeconv::plan_coerce(ecx, self, &ScalarType::String)
    }

    pub fn cast_to(
        self,
        ecx: &ExprContext,
        ccx: CastContext,
        ty: &ScalarType,
    ) -> Result<HirScalarExpr, PlanError> {
        let expr = typeconv::plan_coerce(ecx, self, ty)?;
        typeconv::plan_cast(ecx, ccx, expr, ty)
    }
}

/// The column type for a [`CoercibleScalarExpr`].
#[derive(Clone, Debug)]
pub enum CoercibleColumnType {
    Coerced(ColumnType),
    Record(Vec<CoercibleColumnType>),
    Uncoerced,
}

impl CoercibleColumnType {
    /// Reports the nullability of the type.
    pub fn nullable(&self) -> bool {
        match self {
            // A coerced value's nullability is known.
            CoercibleColumnType::Coerced(ct) => ct.nullable,

            // A literal record can never be null.
            CoercibleColumnType::Record(_) => false,

            // An uncoerced literal may be the literal `NULL`, so we have
            // to conservatively assume it is nullable.
            CoercibleColumnType::Uncoerced => true,
        }
    }
}

/// The scalar type for a [`CoercibleScalarExpr`].
#[derive(Clone, Debug)]
pub enum CoercibleScalarType {
    Coerced(ScalarType),
    Record(Vec<CoercibleColumnType>),
    Uncoerced,
}

impl CoercibleScalarType {
    /// Reports whether the scalar type has been coerced.
    pub fn is_coerced(&self) -> bool {
        matches!(self, CoercibleScalarType::Coerced(_))
    }

    /// Returns the coerced scalar type, if the type is coerced.
    pub fn as_coerced(&self) -> Option<&ScalarType> {
        match self {
            CoercibleScalarType::Coerced(t) => Some(t),
            _ => None,
        }
    }

    /// If the type is coerced, apply the mapping function to the contained
    /// scalar type.
    pub fn map_coerced<F>(self, f: F) -> CoercibleScalarType
    where
        F: FnOnce(ScalarType) -> ScalarType,
    {
        match self {
            CoercibleScalarType::Coerced(t) => CoercibleScalarType::Coerced(f(t)),
            _ => self,
        }
    }

    /// If the type is an coercible record, forcibly converts to a coerced
    /// record type. Any uncoerced field types are assumed to be of type text.
    ///
    /// Generally you should prefer to use [`typeconv::plan_coerce`], which
    /// accepts a type hint that can indicate the types of uncoerced field
    /// types.
    pub fn force_coerced_if_record(&mut self) {
        fn convert(uncoerced_fields: impl Iterator<Item = CoercibleColumnType>) -> ScalarType {
            let mut fields = vec![];
            for (i, uf) in uncoerced_fields.enumerate() {
                let name = ColumnName::from(format!("f{}", i + 1));
                let ty = match uf {
                    CoercibleColumnType::Coerced(ty) => ty,
                    CoercibleColumnType::Record(mut fields) => {
                        convert(fields.drain(..)).nullable(false)
                    }
                    CoercibleColumnType::Uncoerced => ScalarType::String.nullable(true),
                };
                fields.push((name, ty))
            }
            ScalarType::Record {
                fields: fields.into(),
                custom_id: None,
            }
        }

        if let CoercibleScalarType::Record(fields) = self {
            *self = CoercibleScalarType::Coerced(convert(fields.drain(..)));
        }
    }
}

/// An expression whose type can be ascertained.
///
/// Abstracts over `ScalarExpr` and `CoercibleScalarExpr`.
pub trait AbstractExpr {
    type Type: AbstractColumnType;

    /// Computes the type of the expression.
    fn typ(
        &self,
        outers: &[RelationType],
        inner: &RelationType,
        params: &BTreeMap<usize, ScalarType>,
    ) -> Self::Type;
}

impl AbstractExpr for CoercibleScalarExpr {
    type Type = CoercibleColumnType;

    fn typ(
        &self,
        outers: &[RelationType],
        inner: &RelationType,
        params: &BTreeMap<usize, ScalarType>,
    ) -> Self::Type {
        match self {
            CoercibleScalarExpr::Coerced(expr) => {
                CoercibleColumnType::Coerced(expr.typ(outers, inner, params))
            }
            CoercibleScalarExpr::LiteralRecord(scalars) => {
                let fields = scalars
                    .iter()
                    .map(|s| s.typ(outers, inner, params))
                    .collect();
                CoercibleColumnType::Record(fields)
            }
            _ => CoercibleColumnType::Uncoerced,
        }
    }
}

/// A column type-like object whose underlying scalar type-like object can be
/// ascertained.
///
/// Abstracts over `ColumnType` and `CoercibleColumnType`.
pub trait AbstractColumnType {
    type AbstractScalarType;

    /// Converts the column type-like object into its inner scalar type-like
    /// object.
    fn scalar_type(self) -> Self::AbstractScalarType;
}

impl AbstractColumnType for ColumnType {
    type AbstractScalarType = ScalarType;

    fn scalar_type(self) -> Self::AbstractScalarType {
        self.scalar_type
    }
}

impl AbstractColumnType for CoercibleColumnType {
    type AbstractScalarType = CoercibleScalarType;

    fn scalar_type(self) -> Self::AbstractScalarType {
        match self {
            CoercibleColumnType::Coerced(t) => CoercibleScalarType::Coerced(t.scalar_type),
            CoercibleColumnType::Record(t) => CoercibleScalarType::Record(t),
            CoercibleColumnType::Uncoerced => CoercibleScalarType::Uncoerced,
        }
    }
}

impl From<HirScalarExpr> for CoercibleScalarExpr {
    fn from(expr: HirScalarExpr) -> CoercibleScalarExpr {
        CoercibleScalarExpr::Coerced(expr)
    }
}

/// A leveled column reference.
///
/// In the course of decorrelation, multiple levels of nested subqueries are
/// traversed, and references to columns may correspond to different levels
/// of containing outer subqueries.
///
/// A `ColumnRef` allows expressions to refer to columns while being clear
/// about which level the column references without manually performing the
/// bookkeeping tracking their actual column locations.
///
/// Specifically, a `ColumnRef` refers to a column `level` subquery level *out*
/// from the reference, using `column` as a unique identifier in that subquery level.
/// A `level` of zero corresponds to the current scope, and levels increase to
/// indicate subqueries further "outwards".
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd, Serialize, Deserialize)]
pub struct ColumnRef {
    // scope level, where 0 is the current scope and 1+ are outer scopes.
    pub level: usize,
    // level-local column identifier used.
    pub column: usize,
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub enum JoinKind {
    Inner,
    LeftOuter,
    RightOuter,
    FullOuter,
}

impl fmt::Display for JoinKind {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "{}",
            match self {
                JoinKind::Inner => "Inner",
                JoinKind::LeftOuter => "LeftOuter",
                JoinKind::RightOuter => "RightOuter",
                JoinKind::FullOuter => "FullOuter",
            }
        )
    }
}

impl JoinKind {
    pub fn can_be_correlated(&self) -> bool {
        match self {
            JoinKind::Inner | JoinKind::LeftOuter => true,
            JoinKind::RightOuter | JoinKind::FullOuter => false,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct AggregateExpr {
    pub func: AggregateFunc,
    pub expr: Box<HirScalarExpr>,
    pub distinct: bool,
}

/// Aggregate functions analogous to `mz_expr::AggregateFunc`, but whose
/// types may be different.
///
/// Specifically, the nullability of the aggregate columns is more common
/// here than in `expr`, as these aggregates may be applied over empty
/// result sets and should be null in those cases, whereas `expr` variants
/// only return null values when supplied nulls as input.
#[derive(Clone, Debug, Eq, PartialEq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub enum AggregateFunc {
    MaxNumeric,
    MaxInt16,
    MaxInt32,
    MaxInt64,
    MaxUInt16,
    MaxUInt32,
    MaxUInt64,
    MaxMzTimestamp,
    MaxFloat32,
    MaxFloat64,
    MaxBool,
    MaxString,
    MaxDate,
    MaxTimestamp,
    MaxTimestampTz,
    MaxInterval,
    MaxTime,
    MinNumeric,
    MinInt16,
    MinInt32,
    MinInt64,
    MinUInt16,
    MinUInt32,
    MinUInt64,
    MinMzTimestamp,
    MinFloat32,
    MinFloat64,
    MinBool,
    MinString,
    MinDate,
    MinTimestamp,
    MinTimestampTz,
    MinInterval,
    MinTime,
    SumInt16,
    SumInt32,
    SumInt64,
    SumUInt16,
    SumUInt32,
    SumUInt64,
    SumFloat32,
    SumFloat64,
    SumNumeric,
    Count,
    Any,
    All,
    /// Accumulates `Datum::List`s whose first element is a JSON-typed `Datum`s
    /// into a JSON list. The other elements are columns used by `order_by`.
    ///
    /// WARNING: Unlike the `jsonb_agg` function that is exposed by the SQL
    /// layer, this function filters out `Datum::Null`, for consistency with
    /// the other aggregate functions.
    JsonbAgg {
        order_by: Vec<ColumnOrder>,
    },
    /// Zips `Datum::List`s whose first element is a JSON-typed `Datum`s into a
    /// JSON map. The other elements are columns used by `order_by`.
    JsonbObjectAgg {
        order_by: Vec<ColumnOrder>,
    },
    /// Zips a `Datum::List` whose first element is a `Datum::List` guaranteed
    /// to be non-empty and whose len % 2 == 0 into a `Datum::Map`. The other
    /// elements are columns used by `order_by`.
    MapAgg {
        order_by: Vec<ColumnOrder>,
        value_type: ScalarType,
    },
    /// Accumulates `Datum::List`s whose first element is a `Datum::Array` into a
    /// single `Datum::Array`. The other elements are columns used by `order_by`.
    ArrayConcat {
        order_by: Vec<ColumnOrder>,
    },
    /// Accumulates `Datum::List`s whose first element is a `Datum::List` into a
    /// single `Datum::List`. The other elements are columns used by `order_by`.
    ListConcat {
        order_by: Vec<ColumnOrder>,
    },
    StringAgg {
        order_by: Vec<ColumnOrder>,
    },
    /// A bundle of fused window aggregations: its input is a record, whose each
    /// component will be the input to one of the `AggregateFunc`s.
    ///
    /// Importantly, this aggregation can only be present inside a `WindowExpr`,
    /// more specifically an `AggregateWindowExpr`.
    FusedWindowAgg {
        funcs: Vec<AggregateFunc>,
    },
    /// Accumulates any number of `Datum::Dummy`s into `Datum::Dummy`.
    ///
    /// Useful for removing an expensive aggregation while maintaining the shape
    /// of a reduce operator.
    Dummy,
}

impl AggregateFunc {
    /// Converts the `sql::AggregateFunc` to a corresponding `mz_expr::AggregateFunc`.
    pub fn into_expr(self) -> mz_expr::AggregateFunc {
        match self {
            AggregateFunc::MaxNumeric => mz_expr::AggregateFunc::MaxNumeric,
            AggregateFunc::MaxInt16 => mz_expr::AggregateFunc::MaxInt16,
            AggregateFunc::MaxInt32 => mz_expr::AggregateFunc::MaxInt32,
            AggregateFunc::MaxInt64 => mz_expr::AggregateFunc::MaxInt64,
            AggregateFunc::MaxUInt16 => mz_expr::AggregateFunc::MaxUInt16,
            AggregateFunc::MaxUInt32 => mz_expr::AggregateFunc::MaxUInt32,
            AggregateFunc::MaxUInt64 => mz_expr::AggregateFunc::MaxUInt64,
            AggregateFunc::MaxMzTimestamp => mz_expr::AggregateFunc::MaxMzTimestamp,
            AggregateFunc::MaxFloat32 => mz_expr::AggregateFunc::MaxFloat32,
            AggregateFunc::MaxFloat64 => mz_expr::AggregateFunc::MaxFloat64,
            AggregateFunc::MaxBool => mz_expr::AggregateFunc::MaxBool,
            AggregateFunc::MaxString => mz_expr::AggregateFunc::MaxString,
            AggregateFunc::MaxDate => mz_expr::AggregateFunc::MaxDate,
            AggregateFunc::MaxTimestamp => mz_expr::AggregateFunc::MaxTimestamp,
            AggregateFunc::MaxTimestampTz => mz_expr::AggregateFunc::MaxTimestampTz,
            AggregateFunc::MaxInterval => mz_expr::AggregateFunc::MaxInterval,
            AggregateFunc::MaxTime => mz_expr::AggregateFunc::MaxTime,
            AggregateFunc::MinNumeric => mz_expr::AggregateFunc::MinNumeric,
            AggregateFunc::MinInt16 => mz_expr::AggregateFunc::MinInt16,
            AggregateFunc::MinInt32 => mz_expr::AggregateFunc::MinInt32,
            AggregateFunc::MinInt64 => mz_expr::AggregateFunc::MinInt64,
            AggregateFunc::MinUInt16 => mz_expr::AggregateFunc::MinUInt16,
            AggregateFunc::MinUInt32 => mz_expr::AggregateFunc::MinUInt32,
            AggregateFunc::MinUInt64 => mz_expr::AggregateFunc::MinUInt64,
            AggregateFunc::MinMzTimestamp => mz_expr::AggregateFunc::MinMzTimestamp,
            AggregateFunc::MinFloat32 => mz_expr::AggregateFunc::MinFloat32,
            AggregateFunc::MinFloat64 => mz_expr::AggregateFunc::MinFloat64,
            AggregateFunc::MinBool => mz_expr::AggregateFunc::MinBool,
            AggregateFunc::MinString => mz_expr::AggregateFunc::MinString,
            AggregateFunc::MinDate => mz_expr::AggregateFunc::MinDate,
            AggregateFunc::MinTimestamp => mz_expr::AggregateFunc::MinTimestamp,
            AggregateFunc::MinTimestampTz => mz_expr::AggregateFunc::MinTimestampTz,
            AggregateFunc::MinInterval => mz_expr::AggregateFunc::MinInterval,
            AggregateFunc::MinTime => mz_expr::AggregateFunc::MinTime,
            AggregateFunc::SumInt16 => mz_expr::AggregateFunc::SumInt16,
            AggregateFunc::SumInt32 => mz_expr::AggregateFunc::SumInt32,
            AggregateFunc::SumInt64 => mz_expr::AggregateFunc::SumInt64,
            AggregateFunc::SumUInt16 => mz_expr::AggregateFunc::SumUInt16,
            AggregateFunc::SumUInt32 => mz_expr::AggregateFunc::SumUInt32,
            AggregateFunc::SumUInt64 => mz_expr::AggregateFunc::SumUInt64,
            AggregateFunc::SumFloat32 => mz_expr::AggregateFunc::SumFloat32,
            AggregateFunc::SumFloat64 => mz_expr::AggregateFunc::SumFloat64,
            AggregateFunc::SumNumeric => mz_expr::AggregateFunc::SumNumeric,
            AggregateFunc::Count => mz_expr::AggregateFunc::Count,
            AggregateFunc::Any => mz_expr::AggregateFunc::Any,
            AggregateFunc::All => mz_expr::AggregateFunc::All,
            AggregateFunc::JsonbAgg { order_by } => mz_expr::AggregateFunc::JsonbAgg { order_by },
            AggregateFunc::JsonbObjectAgg { order_by } => {
                mz_expr::AggregateFunc::JsonbObjectAgg { order_by }
            }
            AggregateFunc::MapAgg {
                order_by,
                value_type,
            } => mz_expr::AggregateFunc::MapAgg {
                order_by,
                value_type,
            },
            AggregateFunc::ArrayConcat { order_by } => {
                mz_expr::AggregateFunc::ArrayConcat { order_by }
            }
            AggregateFunc::ListConcat { order_by } => {
                mz_expr::AggregateFunc::ListConcat { order_by }
            }
            AggregateFunc::StringAgg { order_by } => mz_expr::AggregateFunc::StringAgg { order_by },
            // `AggregateFunc::FusedWindowAgg` should be specially handled in
            // `AggregateWindowExpr::into_expr`.
            AggregateFunc::FusedWindowAgg { funcs: _ } => {
                panic!("into_expr called on FusedWindowAgg")
            }
            AggregateFunc::Dummy => mz_expr::AggregateFunc::Dummy,
        }
    }

    /// Returns a datum whose inclusion in the aggregation will not change its
    /// result.
    ///
    /// # Panics
    ///
    /// Panics if called on a `FusedWindowAgg`.
    pub fn identity_datum(&self) -> Datum<'static> {
        match self {
            AggregateFunc::Any => Datum::False,
            AggregateFunc::All => Datum::True,
            AggregateFunc::Dummy => Datum::Dummy,
            AggregateFunc::ArrayConcat { .. } => Datum::empty_array(),
            AggregateFunc::ListConcat { .. } => Datum::empty_list(),
            AggregateFunc::MaxNumeric
            | AggregateFunc::MaxInt16
            | AggregateFunc::MaxInt32
            | AggregateFunc::MaxInt64
            | AggregateFunc::MaxUInt16
            | AggregateFunc::MaxUInt32
            | AggregateFunc::MaxUInt64
            | AggregateFunc::MaxMzTimestamp
            | AggregateFunc::MaxFloat32
            | AggregateFunc::MaxFloat64
            | AggregateFunc::MaxBool
            | AggregateFunc::MaxString
            | AggregateFunc::MaxDate
            | AggregateFunc::MaxTimestamp
            | AggregateFunc::MaxTimestampTz
            | AggregateFunc::MaxInterval
            | AggregateFunc::MaxTime
            | AggregateFunc::MinNumeric
            | AggregateFunc::MinInt16
            | AggregateFunc::MinInt32
            | AggregateFunc::MinInt64
            | AggregateFunc::MinUInt16
            | AggregateFunc::MinUInt32
            | AggregateFunc::MinUInt64
            | AggregateFunc::MinMzTimestamp
            | AggregateFunc::MinFloat32
            | AggregateFunc::MinFloat64
            | AggregateFunc::MinBool
            | AggregateFunc::MinString
            | AggregateFunc::MinDate
            | AggregateFunc::MinTimestamp
            | AggregateFunc::MinTimestampTz
            | AggregateFunc::MinInterval
            | AggregateFunc::MinTime
            | AggregateFunc::SumInt16
            | AggregateFunc::SumInt32
            | AggregateFunc::SumInt64
            | AggregateFunc::SumUInt16
            | AggregateFunc::SumUInt32
            | AggregateFunc::SumUInt64
            | AggregateFunc::SumFloat32
            | AggregateFunc::SumFloat64
            | AggregateFunc::SumNumeric
            | AggregateFunc::Count
            | AggregateFunc::JsonbAgg { .. }
            | AggregateFunc::JsonbObjectAgg { .. }
            | AggregateFunc::MapAgg { .. }
            | AggregateFunc::StringAgg { .. } => Datum::Null,
            AggregateFunc::FusedWindowAgg { funcs: _ } => {
                // `identity_datum` is used only in HIR planning, and `FusedWindowAgg` can't occur
                // in HIR planning, because it is introduced only during HIR transformation.
                //
                // The implementation could be something like the following, except that we need to
                // return a `Datum<'static>`, so we can't actually dynamically compute this.
                // ```
                // let temp_storage = RowArena::new();
                // temp_storage.make_datum(|packer| packer.push_list(funcs.iter().map(|f| f.identity_datum())))
                // ```
                panic!("FusedWindowAgg doesn't have an identity_datum")
            }
        }
    }

    /// The output column type for the result of an aggregation.
    ///
    /// The output column type also contains nullability information, which
    /// is (without further information) true for aggregations that are not
    /// counts.
    pub fn output_type(&self, input_type: ColumnType) -> ColumnType {
        let scalar_type = match self {
            AggregateFunc::Count => ScalarType::Int64,
            AggregateFunc::Any => ScalarType::Bool,
            AggregateFunc::All => ScalarType::Bool,
            AggregateFunc::JsonbAgg { .. } => ScalarType::Jsonb,
            AggregateFunc::JsonbObjectAgg { .. } => ScalarType::Jsonb,
            AggregateFunc::StringAgg { .. } => ScalarType::String,
            AggregateFunc::SumInt16 | AggregateFunc::SumInt32 => ScalarType::Int64,
            AggregateFunc::SumInt64 => ScalarType::Numeric {
                max_scale: Some(NumericMaxScale::ZERO),
            },
            AggregateFunc::SumUInt16 | AggregateFunc::SumUInt32 => ScalarType::UInt64,
            AggregateFunc::SumUInt64 => ScalarType::Numeric {
                max_scale: Some(NumericMaxScale::ZERO),
            },
            AggregateFunc::MapAgg { value_type, .. } => ScalarType::Map {
                value_type: Box::new(value_type.clone()),
                custom_id: None,
            },
            AggregateFunc::ArrayConcat { .. } | AggregateFunc::ListConcat { .. } => {
                match input_type.scalar_type {
                    // The input is wrapped in a Record if there's an ORDER BY, so extract it out.
                    ScalarType::Record { fields, .. } => fields[0].1.scalar_type.clone(),
                    _ => unreachable!(),
                }
            }
            AggregateFunc::MaxNumeric
            | AggregateFunc::MaxInt16
            | AggregateFunc::MaxInt32
            | AggregateFunc::MaxInt64
            | AggregateFunc::MaxUInt16
            | AggregateFunc::MaxUInt32
            | AggregateFunc::MaxUInt64
            | AggregateFunc::MaxMzTimestamp
            | AggregateFunc::MaxFloat32
            | AggregateFunc::MaxFloat64
            | AggregateFunc::MaxBool
            | AggregateFunc::MaxString
            | AggregateFunc::MaxDate
            | AggregateFunc::MaxTimestamp
            | AggregateFunc::MaxTimestampTz
            | AggregateFunc::MaxInterval
            | AggregateFunc::MaxTime
            | AggregateFunc::MinNumeric
            | AggregateFunc::MinInt16
            | AggregateFunc::MinInt32
            | AggregateFunc::MinInt64
            | AggregateFunc::MinUInt16
            | AggregateFunc::MinUInt32
            | AggregateFunc::MinUInt64
            | AggregateFunc::MinMzTimestamp
            | AggregateFunc::MinFloat32
            | AggregateFunc::MinFloat64
            | AggregateFunc::MinBool
            | AggregateFunc::MinString
            | AggregateFunc::MinDate
            | AggregateFunc::MinTimestamp
            | AggregateFunc::MinTimestampTz
            | AggregateFunc::MinInterval
            | AggregateFunc::MinTime
            | AggregateFunc::SumFloat32
            | AggregateFunc::SumFloat64
            | AggregateFunc::SumNumeric
            | AggregateFunc::Dummy => input_type.scalar_type,
            AggregateFunc::FusedWindowAgg { funcs } => {
                let input_types = input_type.scalar_type.unwrap_record_element_column_type();
                ScalarType::Record {
                    fields: funcs
                        .iter()
                        .zip_eq(input_types)
                        .map(|(f, t)| (ColumnName::from(""), f.output_type(t.clone())))
                        .collect(),
                    custom_id: None,
                }
            }
        };
        // max/min/sum return null on empty sets
        let nullable = !matches!(self, AggregateFunc::Count);
        scalar_type.nullable(nullable)
    }

    pub fn is_order_sensitive(&self) -> bool {
        use AggregateFunc::*;
        matches!(
            self,
            JsonbAgg { .. }
                | JsonbObjectAgg { .. }
                | MapAgg { .. }
                | ArrayConcat { .. }
                | ListConcat { .. }
                | StringAgg { .. }
        )
    }
}

impl HirRelationExpr {
    pub fn typ(
        &self,
        outers: &[RelationType],
        params: &BTreeMap<usize, ScalarType>,
    ) -> RelationType {
        stack::maybe_grow(|| match self {
            HirRelationExpr::Constant { typ, .. } => typ.clone(),
            HirRelationExpr::Get { typ, .. } => typ.clone(),
            HirRelationExpr::Let { body, .. } => body.typ(outers, params),
            HirRelationExpr::LetRec { body, .. } => body.typ(outers, params),
            HirRelationExpr::Project { input, outputs } => {
                let input_typ = input.typ(outers, params);
                RelationType::new(
                    outputs
                        .iter()
                        .map(|&i| input_typ.column_types[i].clone())
                        .collect(),
                )
            }
            HirRelationExpr::Map { input, scalars } => {
                let mut typ = input.typ(outers, params);
                for scalar in scalars {
                    typ.column_types.push(scalar.typ(outers, &typ, params));
                }
                typ
            }
            HirRelationExpr::CallTable { func, exprs: _ } => func.output_type(),
            HirRelationExpr::Filter { input, .. } | HirRelationExpr::TopK { input, .. } => {
                input.typ(outers, params)
            }
            HirRelationExpr::Join {
                left, right, kind, ..
            } => {
                let left_nullable = matches!(kind, JoinKind::RightOuter | JoinKind::FullOuter);
                let right_nullable =
                    matches!(kind, JoinKind::LeftOuter { .. } | JoinKind::FullOuter);
                let lt = left.typ(outers, params).column_types.into_iter().map(|t| {
                    let nullable = t.nullable || left_nullable;
                    t.nullable(nullable)
                });
                let mut outers = outers.to_vec();
                outers.insert(0, RelationType::new(lt.clone().collect()));
                let rt = right
                    .typ(&outers, params)
                    .column_types
                    .into_iter()
                    .map(|t| {
                        let nullable = t.nullable || right_nullable;
                        t.nullable(nullable)
                    });
                RelationType::new(lt.chain(rt).collect())
            }
            HirRelationExpr::Reduce {
                input,
                group_key,
                aggregates,
                expected_group_size: _,
            } => {
                let input_typ = input.typ(outers, params);
                let mut column_types = group_key
                    .iter()
                    .map(|&i| input_typ.column_types[i].clone())
                    .collect::<Vec<_>>();
                for agg in aggregates {
                    column_types.push(agg.typ(outers, &input_typ, params));
                }
                // TODO(frank): add primary key information.
                RelationType::new(column_types)
            }
            // TODO(frank): check for removal; add primary key information.
            HirRelationExpr::Distinct { input }
            | HirRelationExpr::Negate { input }
            | HirRelationExpr::Threshold { input } => input.typ(outers, params),
            HirRelationExpr::Union { base, inputs } => {
                let mut base_cols = base.typ(outers, params).column_types;
                for input in inputs {
                    for (base_col, col) in base_cols
                        .iter_mut()
                        .zip_eq(input.typ(outers, params).column_types)
                    {
                        *base_col = base_col.union(&col).unwrap();
                    }
                }
                RelationType::new(base_cols)
            }
        })
    }

    pub fn arity(&self) -> usize {
        match self {
            HirRelationExpr::Constant { typ, .. } => typ.column_types.len(),
            HirRelationExpr::Get { typ, .. } => typ.column_types.len(),
            HirRelationExpr::Let { body, .. } => body.arity(),
            HirRelationExpr::LetRec { body, .. } => body.arity(),
            HirRelationExpr::Project { outputs, .. } => outputs.len(),
            HirRelationExpr::Map { input, scalars } => input.arity() + scalars.len(),
            HirRelationExpr::CallTable { func, .. } => func.output_arity(),
            HirRelationExpr::Filter { input, .. }
            | HirRelationExpr::TopK { input, .. }
            | HirRelationExpr::Distinct { input }
            | HirRelationExpr::Negate { input }
            | HirRelationExpr::Threshold { input } => input.arity(),
            HirRelationExpr::Join { left, right, .. } => left.arity() + right.arity(),
            HirRelationExpr::Union { base, .. } => base.arity(),
            HirRelationExpr::Reduce {
                group_key,
                aggregates,
                ..
            } => group_key.len() + aggregates.len(),
        }
    }

    /// If self is a constant, return the value and the type, otherwise `None`.
    pub fn as_const(&self) -> Option<(&Vec<Row>, &RelationType)> {
        match self {
            Self::Constant { rows, typ } => Some((rows, typ)),
            _ => None,
        }
    }

    /// Reports whether this expression contains a column reference to its
    /// direct parent scope.
    pub fn is_correlated(&self) -> bool {
        let mut correlated = false;
        #[allow(deprecated)]
        self.visit_columns(0, &mut |depth, col| {
            if col.level > depth && col.level - depth == 1 {
                correlated = true;
            }
        });
        correlated
    }

    pub fn is_join_identity(&self) -> bool {
        match self {
            HirRelationExpr::Constant { rows, .. } => rows.len() == 1 && self.arity() == 0,
            _ => false,
        }
    }

    pub fn project(self, outputs: Vec<usize>) -> Self {
        if outputs.iter().copied().eq(0..self.arity()) {
            // The projection is trivial. Suppress it.
            self
        } else {
            HirRelationExpr::Project {
                input: Box::new(self),
                outputs,
            }
        }
    }

    pub fn map(mut self, scalars: Vec<HirScalarExpr>) -> Self {
        if scalars.is_empty() {
            // The map is trivial. Suppress it.
            self
        } else if let HirRelationExpr::Map {
            scalars: old_scalars,
            input: _,
        } = &mut self
        {
            // Map applied to a map. Fuse the maps.
            old_scalars.extend(scalars);
            self
        } else {
            HirRelationExpr::Map {
                input: Box::new(self),
                scalars,
            }
        }
    }

    pub fn filter(mut self, mut preds: Vec<HirScalarExpr>) -> Self {
        if let HirRelationExpr::Filter {
            input: _,
            predicates,
        } = &mut self
        {
            predicates.extend(preds);
            predicates.sort();
            predicates.dedup();
            self
        } else {
            preds.sort();
            preds.dedup();
            HirRelationExpr::Filter {
                input: Box::new(self),
                predicates: preds,
            }
        }
    }

    pub fn reduce(
        self,
        group_key: Vec<usize>,
        aggregates: Vec<AggregateExpr>,
        expected_group_size: Option<u64>,
    ) -> Self {
        HirRelationExpr::Reduce {
            input: Box::new(self),
            group_key,
            aggregates,
            expected_group_size,
        }
    }

    pub fn top_k(
        self,
        group_key: Vec<usize>,
        order_key: Vec<ColumnOrder>,
        limit: Option<HirScalarExpr>,
        offset: usize,
        expected_group_size: Option<u64>,
    ) -> Self {
        HirRelationExpr::TopK {
            input: Box::new(self),
            group_key,
            order_key,
            limit,
            offset,
            expected_group_size,
        }
    }

    pub fn negate(self) -> Self {
        if let HirRelationExpr::Negate { input } = self {
            *input
        } else {
            HirRelationExpr::Negate {
                input: Box::new(self),
            }
        }
    }

    pub fn distinct(self) -> Self {
        if let HirRelationExpr::Distinct { .. } = self {
            self
        } else {
            HirRelationExpr::Distinct {
                input: Box::new(self),
            }
        }
    }

    pub fn threshold(self) -> Self {
        if let HirRelationExpr::Threshold { .. } = self {
            self
        } else {
            HirRelationExpr::Threshold {
                input: Box::new(self),
            }
        }
    }

    pub fn union(self, other: Self) -> Self {
        let mut terms = Vec::new();
        if let HirRelationExpr::Union { base, inputs } = self {
            terms.push(*base);
            terms.extend(inputs);
        } else {
            terms.push(self);
        }
        if let HirRelationExpr::Union { base, inputs } = other {
            terms.push(*base);
            terms.extend(inputs);
        } else {
            terms.push(other);
        }
        HirRelationExpr::Union {
            base: Box::new(terms.remove(0)),
            inputs: terms,
        }
    }

    pub fn exists(self) -> HirScalarExpr {
        HirScalarExpr::Exists(Box::new(self))
    }

    pub fn select(self) -> HirScalarExpr {
        HirScalarExpr::Select(Box::new(self))
    }

    pub fn join(
        self,
        mut right: HirRelationExpr,
        on: HirScalarExpr,
        kind: JoinKind,
    ) -> HirRelationExpr {
        if self.is_join_identity() && !right.is_correlated() && on == HirScalarExpr::literal_true()
        {
            // The join can be elided, but we need to adjust column references
            // on the right-hand side to account for the removal of the scope
            // introduced by the join.
            #[allow(deprecated)]
            right.visit_columns_mut(0, &mut |depth, col| {
                if col.level > depth {
                    col.level -= 1;
                }
            });
            right
        } else if right.is_join_identity() && on == HirScalarExpr::literal_true() {
            self
        } else {
            HirRelationExpr::Join {
                left: Box::new(self),
                right: Box::new(right),
                on,
                kind,
            }
        }
    }

    pub fn take(&mut self) -> HirRelationExpr {
        mem::replace(
            self,
            HirRelationExpr::constant(vec![], RelationType::new(Vec::new())),
        )
    }

    #[deprecated = "Use `Visit::visit_post`."]
    pub fn visit<'a, F>(&'a self, depth: usize, f: &mut F)
    where
        F: FnMut(&'a Self, usize),
    {
        #[allow(deprecated)]
        let _ = self.visit_fallible(depth, &mut |e: &HirRelationExpr,
                                                 depth: usize|
         -> Result<(), ()> {
            f(e, depth);
            Ok(())
        });
    }

    #[deprecated = "Use `Visit::try_visit_post`."]
    pub fn visit_fallible<'a, F, E>(&'a self, depth: usize, f: &mut F) -> Result<(), E>
    where
        F: FnMut(&'a Self, usize) -> Result<(), E>,
    {
        #[allow(deprecated)]
        self.visit1(depth, |e: &HirRelationExpr, depth: usize| {
            e.visit_fallible(depth, f)
        })?;
        f(self, depth)
    }

    #[deprecated = "Use `VisitChildren<HirRelationExpr>::try_visit_children` instead."]
    pub fn visit1<'a, F, E>(&'a self, depth: usize, mut f: F) -> Result<(), E>
    where
        F: FnMut(&'a Self, usize) -> Result<(), E>,
    {
        match self {
            HirRelationExpr::Constant { .. }
            | HirRelationExpr::Get { .. }
            | HirRelationExpr::CallTable { .. } => (),
            HirRelationExpr::Let { body, value, .. } => {
                f(value, depth)?;
                f(body, depth)?;
            }
            HirRelationExpr::LetRec {
                limit: _,
                bindings,
                body,
            } => {
                for (_, _, value, _) in bindings.iter() {
                    f(value, depth)?;
                }
                f(body, depth)?;
            }
            HirRelationExpr::Project { input, .. } => {
                f(input, depth)?;
            }
            HirRelationExpr::Map { input, .. } => {
                f(input, depth)?;
            }
            HirRelationExpr::Filter { input, .. } => {
                f(input, depth)?;
            }
            HirRelationExpr::Join { left, right, .. } => {
                f(left, depth)?;
                f(right, depth + 1)?;
            }
            HirRelationExpr::Reduce { input, .. } => {
                f(input, depth)?;
            }
            HirRelationExpr::Distinct { input } => {
                f(input, depth)?;
            }
            HirRelationExpr::TopK { input, .. } => {
                f(input, depth)?;
            }
            HirRelationExpr::Negate { input } => {
                f(input, depth)?;
            }
            HirRelationExpr::Threshold { input } => {
                f(input, depth)?;
            }
            HirRelationExpr::Union { base, inputs } => {
                f(base, depth)?;
                for input in inputs {
                    f(input, depth)?;
                }
            }
        }
        Ok(())
    }

    #[deprecated = "Use `Visit::visit_mut_post` instead."]
    pub fn visit_mut<F>(&mut self, depth: usize, f: &mut F)
    where
        F: FnMut(&mut Self, usize),
    {
        #[allow(deprecated)]
        let _ = self.visit_mut_fallible(depth, &mut |e: &mut HirRelationExpr,
                                                     depth: usize|
         -> Result<(), ()> {
            f(e, depth);
            Ok(())
        });
    }

    #[deprecated = "Use `Visit::try_visit_mut_post` instead."]
    pub fn visit_mut_fallible<F, E>(&mut self, depth: usize, f: &mut F) -> Result<(), E>
    where
        F: FnMut(&mut Self, usize) -> Result<(), E>,
    {
        #[allow(deprecated)]
        self.visit1_mut(depth, |e: &mut HirRelationExpr, depth: usize| {
            e.visit_mut_fallible(depth, f)
        })?;
        f(self, depth)
    }

    #[deprecated = "Use `VisitChildren<HirRelationExpr>::try_visit_mut_children` instead."]
    pub fn visit1_mut<'a, F, E>(&'a mut self, depth: usize, mut f: F) -> Result<(), E>
    where
        F: FnMut(&'a mut Self, usize) -> Result<(), E>,
    {
        match self {
            HirRelationExpr::Constant { .. }
            | HirRelationExpr::Get { .. }
            | HirRelationExpr::CallTable { .. } => (),
            HirRelationExpr::Let { body, value, .. } => {
                f(value, depth)?;
                f(body, depth)?;
            }
            HirRelationExpr::LetRec {
                limit: _,
                bindings,
                body,
            } => {
                for (_, _, value, _) in bindings.iter_mut() {
                    f(value, depth)?;
                }
                f(body, depth)?;
            }
            HirRelationExpr::Project { input, .. } => {
                f(input, depth)?;
            }
            HirRelationExpr::Map { input, .. } => {
                f(input, depth)?;
            }
            HirRelationExpr::Filter { input, .. } => {
                f(input, depth)?;
            }
            HirRelationExpr::Join { left, right, .. } => {
                f(left, depth)?;
                f(right, depth + 1)?;
            }
            HirRelationExpr::Reduce { input, .. } => {
                f(input, depth)?;
            }
            HirRelationExpr::Distinct { input } => {
                f(input, depth)?;
            }
            HirRelationExpr::TopK { input, .. } => {
                f(input, depth)?;
            }
            HirRelationExpr::Negate { input } => {
                f(input, depth)?;
            }
            HirRelationExpr::Threshold { input } => {
                f(input, depth)?;
            }
            HirRelationExpr::Union { base, inputs } => {
                f(base, depth)?;
                for input in inputs {
                    f(input, depth)?;
                }
            }
        }
        Ok(())
    }

    #[deprecated = "Use a combination of `Visit` and `VisitChildren` methods."]
    /// Visits all scalar expressions within the sub-tree of the given relation.
    ///
    /// The `depth` argument should indicate the subquery nesting depth of the expression,
    /// which will be incremented when entering the RHS of a join or a subquery and
    /// presented to the supplied function `f`.
    pub fn visit_scalar_expressions<F, E>(&self, depth: usize, f: &mut F) -> Result<(), E>
    where
        F: FnMut(&HirScalarExpr, usize) -> Result<(), E>,
    {
        #[allow(deprecated)]
        self.visit_fallible(depth, &mut |e: &HirRelationExpr,
                                         depth: usize|
         -> Result<(), E> {
            match e {
                HirRelationExpr::Join { on, .. } => {
                    f(on, depth)?;
                }
                HirRelationExpr::Map { scalars, .. } => {
                    for scalar in scalars {
                        f(scalar, depth)?;
                    }
                }
                HirRelationExpr::CallTable { exprs, .. } => {
                    for expr in exprs {
                        f(expr, depth)?;
                    }
                }
                HirRelationExpr::Filter { predicates, .. } => {
                    for predicate in predicates {
                        f(predicate, depth)?;
                    }
                }
                HirRelationExpr::Reduce { aggregates, .. } => {
                    for aggregate in aggregates {
                        f(&aggregate.expr, depth)?;
                    }
                }
                HirRelationExpr::TopK { limit, .. } => {
                    if let Some(limit) = limit {
                        f(limit, depth)?;
                    }
                }
                HirRelationExpr::Union { .. }
                | HirRelationExpr::Let { .. }
                | HirRelationExpr::LetRec { .. }
                | HirRelationExpr::Project { .. }
                | HirRelationExpr::Distinct { .. }
                | HirRelationExpr::Negate { .. }
                | HirRelationExpr::Threshold { .. }
                | HirRelationExpr::Constant { .. }
                | HirRelationExpr::Get { .. } => (),
            }
            Ok(())
        })
    }

    #[deprecated = "Use a combination of `Visit` and `VisitChildren` methods."]
    /// Like `visit_scalar_expressions`, but permits mutating the expressions.
    pub fn visit_scalar_expressions_mut<F, E>(&mut self, depth: usize, f: &mut F) -> Result<(), E>
    where
        F: FnMut(&mut HirScalarExpr, usize) -> Result<(), E>,
    {
        #[allow(deprecated)]
        self.visit_mut_fallible(depth, &mut |e: &mut HirRelationExpr,
                                             depth: usize|
         -> Result<(), E> {
            match e {
                HirRelationExpr::Join { on, .. } => {
                    f(on, depth)?;
                }
                HirRelationExpr::Map { scalars, .. } => {
                    for scalar in scalars.iter_mut() {
                        f(scalar, depth)?;
                    }
                }
                HirRelationExpr::CallTable { exprs, .. } => {
                    for expr in exprs.iter_mut() {
                        f(expr, depth)?;
                    }
                }
                HirRelationExpr::Filter { predicates, .. } => {
                    for predicate in predicates.iter_mut() {
                        f(predicate, depth)?;
                    }
                }
                HirRelationExpr::Reduce { aggregates, .. } => {
                    for aggregate in aggregates.iter_mut() {
                        f(&mut aggregate.expr, depth)?;
                    }
                }
                HirRelationExpr::TopK { limit, .. } => {
                    if let Some(limit) = limit {
                        f(limit, depth)?;
                    }
                }
                HirRelationExpr::Union { .. }
                | HirRelationExpr::Let { .. }
                | HirRelationExpr::LetRec { .. }
                | HirRelationExpr::Project { .. }
                | HirRelationExpr::Distinct { .. }
                | HirRelationExpr::Negate { .. }
                | HirRelationExpr::Threshold { .. }
                | HirRelationExpr::Constant { .. }
                | HirRelationExpr::Get { .. } => (),
            }
            Ok(())
        })
    }

    #[deprecated = "Redefine this based on the `Visit` and `VisitChildren` methods."]
    /// Visits the column references in this relation expression.
    ///
    /// The `depth` argument should indicate the subquery nesting depth of the expression,
    /// which will be incremented when entering the RHS of a join or a subquery and
    /// presented to the supplied function `f`.
    pub fn visit_columns<F>(&self, depth: usize, f: &mut F)
    where
        F: FnMut(usize, &ColumnRef),
    {
        #[allow(deprecated)]
        let _ = self.visit_scalar_expressions(depth, &mut |e: &HirScalarExpr,
                                                           depth: usize|
         -> Result<(), ()> {
            e.visit_columns(depth, f);
            Ok(())
        });
    }

    #[deprecated = "Redefine this based on the `Visit` and `VisitChildren` methods."]
    /// Like `visit_columns`, but permits mutating the column references.
    pub fn visit_columns_mut<F>(&mut self, depth: usize, f: &mut F)
    where
        F: FnMut(usize, &mut ColumnRef),
    {
        #[allow(deprecated)]
        let _ = self.visit_scalar_expressions_mut(depth, &mut |e: &mut HirScalarExpr,
                                                               depth: usize|
         -> Result<(), ()> {
            e.visit_columns_mut(depth, f);
            Ok(())
        });
    }

    /// Replaces any parameter references in the expression with the
    /// corresponding datum from `params`.
    pub fn bind_parameters(&mut self, params: &Params) -> Result<(), PlanError> {
        #[allow(deprecated)]
        self.visit_scalar_expressions_mut(0, &mut |e: &mut HirScalarExpr, _: usize| {
            e.bind_parameters(params)
        })
    }

    /// See the documentation for [`HirScalarExpr::splice_parameters`].
    pub fn splice_parameters(&mut self, params: &[HirScalarExpr], depth: usize) {
        #[allow(deprecated)]
        let _ = self.visit_scalar_expressions_mut(depth, &mut |e: &mut HirScalarExpr,
                                                               depth: usize|
         -> Result<(), ()> {
            e.splice_parameters(params, depth);
            Ok(())
        });
    }

    /// Constructs a constant collection from specific rows and schema.
    pub fn constant(rows: Vec<Vec<Datum>>, typ: RelationType) -> Self {
        let rows = rows
            .into_iter()
            .map(move |datums| Row::pack_slice(&datums))
            .collect();
        HirRelationExpr::Constant { rows, typ }
    }

    /// A `RowSetFinishing` can only be directly applied to the result of a one-shot select.
    /// This function is concerned with maintained queries, e.g., an index or materialized view.
    /// Instead of directly applying the given `RowSetFinishing`, it converts the `RowSetFinishing`
    /// to a `TopK`, which it then places at the top of `self`. Additionally, it turns the given
    /// finishing into a trivial finishing.
    pub fn finish_maintained(
        &mut self,
        finishing: &mut RowSetFinishing<HirScalarExpr>,
        group_size_hints: GroupSizeHints,
    ) {
        if !finishing.is_trivial(self.arity()) {
            let old_finishing =
                mem::replace(finishing, RowSetFinishing::trivial(finishing.project.len()));
            *self = HirRelationExpr::top_k(
                std::mem::replace(
                    self,
                    HirRelationExpr::Constant {
                        rows: vec![],
                        typ: RelationType::new(Vec::new()),
                    },
                ),
                vec![],
                old_finishing.order_by,
                old_finishing.limit,
                old_finishing.offset,
                group_size_hints.limit_input_group_size,
            )
            .project(old_finishing.project);
        }
    }

    /// The HirRelationExpr is considered potentially expensive if and only if
    /// at least one of the following conditions is true:
    ///
    ///  - It contains at least one CallTable or a Reduce operator.
    ///  - It contains at least one HirScalarExpr with a function call.
    ///
    /// !!!WARNING!!!: this method has an MirRelationExpr counterpart. The two
    /// should be kept in sync w.r.t. HIR ⇒ MIR lowering!
    pub fn could_run_expensive_function(&self) -> bool {
        let mut result = false;
        if let Err(_) = self.visit_pre(&mut |e: &HirRelationExpr| {
            use HirRelationExpr::*;
            use HirScalarExpr::*;

            self.visit_children(|scalar: &HirScalarExpr| {
                if let Err(_) = scalar.visit_pre(&mut |scalar: &HirScalarExpr| {
                    result |= match scalar {
                        Column(_)
                        | Literal(_, _)
                        | CallUnmaterializable(_)
                        | If { .. }
                        | Parameter(..)
                        | Select(..)
                        | Exists(..) => false,
                        // Function calls are considered expensive
                        CallUnary { .. }
                        | CallBinary { .. }
                        | CallVariadic { .. }
                        | Windowing(..) => true,
                    };
                }) {
                    // Conservatively set `true` on RecursionLimitError.
                    result = true;
                }
            });

            // CallTable has a table function; Reduce has an aggregate function.
            // Other constructs use MirScalarExpr to run a function
            result |= matches!(e, CallTable { .. } | Reduce { .. });
        }) {
            // Conservatively set `true` on RecursionLimitError.
            result = true;
        }

        result
    }

    /// Whether the expression contains an [`UnmaterializableFunc::MzNow`] call.
    pub fn contains_temporal(&self) -> Result<bool, RecursionLimitError> {
        let mut contains = false;
        self.visit_post(&mut |expr| {
            expr.visit_children(|expr: &HirScalarExpr| {
                contains = contains || expr.contains_temporal()
            })
        })?;
        Ok(contains)
    }
}

impl CollectionPlan for HirRelationExpr {
    // !!!WARNING!!!: this method has an MirRelationExpr counterpart. The two
    // should be kept in sync w.r.t. HIR ⇒ MIR lowering!
    fn depends_on_into(&self, out: &mut BTreeSet<GlobalId>) {
        if let Self::Get {
            id: Id::Global(id), ..
        } = self
        {
            out.insert(*id);
        }
        self.visit_children(|expr: &HirRelationExpr| expr.depends_on_into(out))
    }
}

impl VisitChildren<Self> for HirRelationExpr {
    fn visit_children<F>(&self, mut f: F)
    where
        F: FnMut(&Self),
    {
        // subqueries of type HirRelationExpr might be wrapped in
        // Exists or Select variants within HirScalarExpr trees
        // attached at the current node, and we want to visit them as well
        VisitChildren::visit_children(self, |expr: &HirScalarExpr| {
            #[allow(deprecated)]
            Visit::visit_post_nolimit(expr, &mut |expr| match expr {
                HirScalarExpr::Exists(expr) | HirScalarExpr::Select(expr) => f(expr.as_ref()),
                _ => (),
            });
        });

        use HirRelationExpr::*;
        match self {
            Constant { rows: _, typ: _ } | Get { id: _, typ: _ } => (),
            Let {
                name: _,
                id: _,
                value,
                body,
            } => {
                f(value);
                f(body);
            }
            LetRec {
                limit: _,
                bindings,
                body,
            } => {
                for (_, _, value, _) in bindings.iter() {
                    f(value);
                }
                f(body);
            }
            Project { input, outputs: _ } => f(input),
            Map { input, scalars: _ } => {
                f(input);
            }
            CallTable { func: _, exprs: _ } => (),
            Filter {
                input,
                predicates: _,
            } => {
                f(input);
            }
            Join {
                left,
                right,
                on: _,
                kind: _,
            } => {
                f(left);
                f(right);
            }
            Reduce {
                input,
                group_key: _,
                aggregates: _,
                expected_group_size: _,
            } => {
                f(input);
            }
            Distinct { input }
            | TopK {
                input,
                group_key: _,
                order_key: _,
                limit: _,
                offset: _,
                expected_group_size: _,
            }
            | Negate { input }
            | Threshold { input } => {
                f(input);
            }
            Union { base, inputs } => {
                f(base);
                for input in inputs {
                    f(input);
                }
            }
        }
    }

    fn visit_mut_children<F>(&mut self, mut f: F)
    where
        F: FnMut(&mut Self),
    {
        // subqueries of type HirRelationExpr might be wrapped in
        // Exists or Select variants within HirScalarExpr trees
        // attached at the current node, and we want to visit them as well
        VisitChildren::visit_mut_children(self, |expr: &mut HirScalarExpr| {
            #[allow(deprecated)]
            Visit::visit_mut_post_nolimit(expr, &mut |expr| match expr {
                HirScalarExpr::Exists(expr) | HirScalarExpr::Select(expr) => f(expr.as_mut()),
                _ => (),
            });
        });

        use HirRelationExpr::*;
        match self {
            Constant { rows: _, typ: _ } | Get { id: _, typ: _ } => (),
            Let {
                name: _,
                id: _,
                value,
                body,
            } => {
                f(value);
                f(body);
            }
            LetRec {
                limit: _,
                bindings,
                body,
            } => {
                for (_, _, value, _) in bindings.iter_mut() {
                    f(value);
                }
                f(body);
            }
            Project { input, outputs: _ } => f(input),
            Map { input, scalars: _ } => {
                f(input);
            }
            CallTable { func: _, exprs: _ } => (),
            Filter {
                input,
                predicates: _,
            } => {
                f(input);
            }
            Join {
                left,
                right,
                on: _,
                kind: _,
            } => {
                f(left);
                f(right);
            }
            Reduce {
                input,
                group_key: _,
                aggregates: _,
                expected_group_size: _,
            } => {
                f(input);
            }
            Distinct { input }
            | TopK {
                input,
                group_key: _,
                order_key: _,
                limit: _,
                offset: _,
                expected_group_size: _,
            }
            | Negate { input }
            | Threshold { input } => {
                f(input);
            }
            Union { base, inputs } => {
                f(base);
                for input in inputs {
                    f(input);
                }
            }
        }
    }

    fn try_visit_children<F, E>(&self, mut f: F) -> Result<(), E>
    where
        F: FnMut(&Self) -> Result<(), E>,
        E: From<RecursionLimitError>,
    {
        // subqueries of type HirRelationExpr might be wrapped in
        // Exists or Select variants within HirScalarExpr trees
        // attached at the current node, and we want to visit them as well
        VisitChildren::try_visit_children(self, |expr: &HirScalarExpr| {
            Visit::try_visit_post(expr, &mut |expr| match expr {
                HirScalarExpr::Exists(expr) | HirScalarExpr::Select(expr) => f(expr.as_ref()),
                _ => Ok(()),
            })
        })?;

        use HirRelationExpr::*;
        match self {
            Constant { rows: _, typ: _ } | Get { id: _, typ: _ } => (),
            Let {
                name: _,
                id: _,
                value,
                body,
            } => {
                f(value)?;
                f(body)?;
            }
            LetRec {
                limit: _,
                bindings,
                body,
            } => {
                for (_, _, value, _) in bindings.iter() {
                    f(value)?;
                }
                f(body)?;
            }
            Project { input, outputs: _ } => f(input)?,
            Map { input, scalars: _ } => {
                f(input)?;
            }
            CallTable { func: _, exprs: _ } => (),
            Filter {
                input,
                predicates: _,
            } => {
                f(input)?;
            }
            Join {
                left,
                right,
                on: _,
                kind: _,
            } => {
                f(left)?;
                f(right)?;
            }
            Reduce {
                input,
                group_key: _,
                aggregates: _,
                expected_group_size: _,
            } => {
                f(input)?;
            }
            Distinct { input }
            | TopK {
                input,
                group_key: _,
                order_key: _,
                limit: _,
                offset: _,
                expected_group_size: _,
            }
            | Negate { input }
            | Threshold { input } => {
                f(input)?;
            }
            Union { base, inputs } => {
                f(base)?;
                for input in inputs {
                    f(input)?;
                }
            }
        }
        Ok(())
    }

    fn try_visit_mut_children<F, E>(&mut self, mut f: F) -> Result<(), E>
    where
        F: FnMut(&mut Self) -> Result<(), E>,
        E: From<RecursionLimitError>,
    {
        // subqueries of type HirRelationExpr might be wrapped in
        // Exists or Select variants within HirScalarExpr trees
        // attached at the current node, and we want to visit them as well
        VisitChildren::try_visit_mut_children(self, |expr: &mut HirScalarExpr| {
            Visit::try_visit_mut_post(expr, &mut |expr| match expr {
                HirScalarExpr::Exists(expr) | HirScalarExpr::Select(expr) => f(expr.as_mut()),
                _ => Ok(()),
            })
        })?;

        use HirRelationExpr::*;
        match self {
            Constant { rows: _, typ: _ } | Get { id: _, typ: _ } => (),
            Let {
                name: _,
                id: _,
                value,
                body,
            } => {
                f(value)?;
                f(body)?;
            }
            LetRec {
                limit: _,
                bindings,
                body,
            } => {
                for (_, _, value, _) in bindings.iter_mut() {
                    f(value)?;
                }
                f(body)?;
            }
            Project { input, outputs: _ } => f(input)?,
            Map { input, scalars: _ } => {
                f(input)?;
            }
            CallTable { func: _, exprs: _ } => (),
            Filter {
                input,
                predicates: _,
            } => {
                f(input)?;
            }
            Join {
                left,
                right,
                on: _,
                kind: _,
            } => {
                f(left)?;
                f(right)?;
            }
            Reduce {
                input,
                group_key: _,
                aggregates: _,
                expected_group_size: _,
            } => {
                f(input)?;
            }
            Distinct { input }
            | TopK {
                input,
                group_key: _,
                order_key: _,
                limit: _,
                offset: _,
                expected_group_size: _,
            }
            | Negate { input }
            | Threshold { input } => {
                f(input)?;
            }
            Union { base, inputs } => {
                f(base)?;
                for input in inputs {
                    f(input)?;
                }
            }
        }
        Ok(())
    }
}

impl VisitChildren<HirScalarExpr> for HirRelationExpr {
    fn visit_children<F>(&self, mut f: F)
    where
        F: FnMut(&HirScalarExpr),
    {
        use HirRelationExpr::*;
        match self {
            Constant { rows: _, typ: _ }
            | Get { id: _, typ: _ }
            | Let {
                name: _,
                id: _,
                value: _,
                body: _,
            }
            | LetRec {
                limit: _,
                bindings: _,
                body: _,
            }
            | Project {
                input: _,
                outputs: _,
            } => (),
            Map { input: _, scalars } => {
                for scalar in scalars {
                    f(scalar);
                }
            }
            CallTable { func: _, exprs } => {
                for expr in exprs {
                    f(expr);
                }
            }
            Filter {
                input: _,
                predicates,
            } => {
                for predicate in predicates {
                    f(predicate);
                }
            }
            Join {
                left: _,
                right: _,
                on,
                kind: _,
            } => f(on),
            Reduce {
                input: _,
                group_key: _,
                aggregates,
                expected_group_size: _,
            } => {
                for aggregate in aggregates {
                    f(aggregate.expr.as_ref());
                }
            }
            TopK {
                input: _,
                group_key: _,
                order_key: _,
                limit,
                offset: _,
                expected_group_size: _,
            } => {
                if let Some(limit) = limit {
                    f(limit)
                }
            }
            Distinct { input: _ }
            | Negate { input: _ }
            | Threshold { input: _ }
            | Union { base: _, inputs: _ } => (),
        }
    }

    fn visit_mut_children<F>(&mut self, mut f: F)
    where
        F: FnMut(&mut HirScalarExpr),
    {
        use HirRelationExpr::*;
        match self {
            Constant { rows: _, typ: _ }
            | Get { id: _, typ: _ }
            | Let {
                name: _,
                id: _,
                value: _,
                body: _,
            }
            | LetRec {
                limit: _,
                bindings: _,
                body: _,
            }
            | Project {
                input: _,
                outputs: _,
            } => (),
            Map { input: _, scalars } => {
                for scalar in scalars {
                    f(scalar);
                }
            }
            CallTable { func: _, exprs } => {
                for expr in exprs {
                    f(expr);
                }
            }
            Filter {
                input: _,
                predicates,
            } => {
                for predicate in predicates {
                    f(predicate);
                }
            }
            Join {
                left: _,
                right: _,
                on,
                kind: _,
            } => f(on),
            Reduce {
                input: _,
                group_key: _,
                aggregates,
                expected_group_size: _,
            } => {
                for aggregate in aggregates {
                    f(aggregate.expr.as_mut());
                }
            }
            Distinct { input: _ }
            | TopK {
                input: _,
                group_key: _,
                order_key: _,
                limit: _,
                offset: _,
                expected_group_size: _,
            }
            | Negate { input: _ }
            | Threshold { input: _ }
            | Union { base: _, inputs: _ } => (),
        }
    }

    fn try_visit_children<F, E>(&self, mut f: F) -> Result<(), E>
    where
        F: FnMut(&HirScalarExpr) -> Result<(), E>,
        E: From<RecursionLimitError>,
    {
        use HirRelationExpr::*;
        match self {
            Constant { rows: _, typ: _ }
            | Get { id: _, typ: _ }
            | Let {
                name: _,
                id: _,
                value: _,
                body: _,
            }
            | LetRec {
                limit: _,
                bindings: _,
                body: _,
            }
            | Project {
                input: _,
                outputs: _,
            } => (),
            Map { input: _, scalars } => {
                for scalar in scalars {
                    f(scalar)?;
                }
            }
            CallTable { func: _, exprs } => {
                for expr in exprs {
                    f(expr)?;
                }
            }
            Filter {
                input: _,
                predicates,
            } => {
                for predicate in predicates {
                    f(predicate)?;
                }
            }
            Join {
                left: _,
                right: _,
                on,
                kind: _,
            } => f(on)?,
            Reduce {
                input: _,
                group_key: _,
                aggregates,
                expected_group_size: _,
            } => {
                for aggregate in aggregates {
                    f(aggregate.expr.as_ref())?;
                }
            }
            Distinct { input: _ }
            | TopK {
                input: _,
                group_key: _,
                order_key: _,
                limit: _,
                offset: _,
                expected_group_size: _,
            }
            | Negate { input: _ }
            | Threshold { input: _ }
            | Union { base: _, inputs: _ } => (),
        }
        Ok(())
    }

    fn try_visit_mut_children<F, E>(&mut self, mut f: F) -> Result<(), E>
    where
        F: FnMut(&mut HirScalarExpr) -> Result<(), E>,
        E: From<RecursionLimitError>,
    {
        use HirRelationExpr::*;
        match self {
            Constant { rows: _, typ: _ }
            | Get { id: _, typ: _ }
            | Let {
                name: _,
                id: _,
                value: _,
                body: _,
            }
            | LetRec {
                limit: _,
                bindings: _,
                body: _,
            }
            | Project {
                input: _,
                outputs: _,
            } => (),
            Map { input: _, scalars } => {
                for scalar in scalars {
                    f(scalar)?;
                }
            }
            CallTable { func: _, exprs } => {
                for expr in exprs {
                    f(expr)?;
                }
            }
            Filter {
                input: _,
                predicates,
            } => {
                for predicate in predicates {
                    f(predicate)?;
                }
            }
            Join {
                left: _,
                right: _,
                on,
                kind: _,
            } => f(on)?,
            Reduce {
                input: _,
                group_key: _,
                aggregates,
                expected_group_size: _,
            } => {
                for aggregate in aggregates {
                    f(aggregate.expr.as_mut())?;
                }
            }
            Distinct { input: _ }
            | TopK {
                input: _,
                group_key: _,
                order_key: _,
                limit: _,
                offset: _,
                expected_group_size: _,
            }
            | Negate { input: _ }
            | Threshold { input: _ }
            | Union { base: _, inputs: _ } => (),
        }
        Ok(())
    }
}

impl HirScalarExpr {
    /// Replaces any parameter references in the expression with the
    /// corresponding datum in `params`.
    pub fn bind_parameters(&mut self, params: &Params) -> Result<(), PlanError> {
        #[allow(deprecated)]
        self.visit_recursively_mut(0, &mut |_: usize, e: &mut HirScalarExpr| {
            if let HirScalarExpr::Parameter(n) = e {
                let datum = match params.datums.iter().nth(*n - 1) {
                    None => sql_bail!("there is no parameter ${}", n),
                    Some(datum) => datum,
                };
                let scalar_type = &params.types[*n - 1];
                let row = Row::pack([datum]);
                let column_type = scalar_type.clone().nullable(datum.is_null());
                *e = HirScalarExpr::Literal(row, column_type);
            }
            Ok(())
        })
    }

    /// Like [`HirScalarExpr::bind_parameters`], except that parameters are
    /// replaced with the corresponding expression fragment from `params` rather
    /// than a datum.
    ///
    /// Specifically, the parameter `$1` will be replaced with `params[0]`, the
    /// parameter `$2` will be replaced with `params[1]`, and so on. Parameters
    /// in `self` that refer to invalid indices of `params` will cause a panic.
    ///
    /// Column references in parameters will be corrected to account for the
    /// depth at which they are spliced.
    pub fn splice_parameters(&mut self, params: &[HirScalarExpr], depth: usize) {
        #[allow(deprecated)]
        let _ = self.visit_recursively_mut(depth, &mut |depth: usize,
                                                        e: &mut HirScalarExpr|
         -> Result<(), ()> {
            if let HirScalarExpr::Parameter(i) = e {
                *e = params[*i - 1].clone();
                // Correct any column references in the parameter expression for
                // its new depth.
                e.visit_columns_mut(0, &mut |d: usize, col: &mut ColumnRef| {
                    if col.level >= d {
                        col.level += depth
                    }
                });
            }
            Ok(())
        });
    }

    /// Whether the expression contains an [`UnmaterializableFunc::MzNow`] call.
    pub fn contains_temporal(&self) -> bool {
        let mut contains = false;
        #[allow(deprecated)]
        self.visit_post_nolimit(&mut |e| {
            if let Self::CallUnmaterializable(UnmaterializableFunc::MzNow) = e {
                contains = true;
            }
        });
        contains
    }

    /// Constructs a column reference in the current scope.
    pub fn column(index: usize) -> HirScalarExpr {
        HirScalarExpr::Column(ColumnRef {
            level: 0,
            column: index,
        })
    }

    pub fn literal(datum: Datum, scalar_type: ScalarType) -> HirScalarExpr {
        let row = Row::pack([datum]);
        HirScalarExpr::Literal(row, scalar_type.nullable(datum.is_null()))
    }

    pub fn literal_true() -> HirScalarExpr {
        HirScalarExpr::literal(Datum::True, ScalarType::Bool)
    }

    pub fn literal_false() -> HirScalarExpr {
        HirScalarExpr::literal(Datum::False, ScalarType::Bool)
    }

    pub fn literal_null(scalar_type: ScalarType) -> HirScalarExpr {
        HirScalarExpr::literal(Datum::Null, scalar_type)
    }

    pub fn literal_1d_array(
        datums: Vec<Datum>,
        element_scalar_type: ScalarType,
    ) -> Result<HirScalarExpr, PlanError> {
        let scalar_type = match element_scalar_type {
            ScalarType::Array(_) => {
                sql_bail!("cannot build array from array type");
            }
            typ => ScalarType::Array(Box::new(typ)).nullable(false),
        };

        let mut row = Row::default();
        row.packer()
            .push_array(
                &[ArrayDimension {
                    lower_bound: 1,
                    length: datums.len(),
                }],
                datums,
            )
            .expect("array constructed to be valid");

        Ok(HirScalarExpr::Literal(row, scalar_type))
    }

    pub fn as_literal(&self) -> Option<Datum> {
        if let HirScalarExpr::Literal(row, _column_type) = self {
            Some(row.unpack_first())
        } else {
            None
        }
    }

    pub fn is_literal_true(&self) -> bool {
        Some(Datum::True) == self.as_literal()
    }

    pub fn is_literal_false(&self) -> bool {
        Some(Datum::False) == self.as_literal()
    }

    pub fn is_literal_null(&self) -> bool {
        Some(Datum::Null) == self.as_literal()
    }

    /// Return true iff `self` consists only of constants, function calls, and
    /// if-else statements.
    pub fn is_constant(&self) -> bool {
        let mut worklist = vec![self];
        while let Some(expr) = worklist.pop() {
            match expr {
                Self::Literal(_, _) => {
                    // leaf node, do nothing
                }
                Self::CallUnary { expr, .. } => {
                    worklist.push(expr);
                }
                Self::CallBinary {
                    func: _,
                    expr1,
                    expr2,
                } => {
                    worklist.push(expr1);
                    worklist.push(expr2);
                }
                Self::CallVariadic { func: _, exprs } => {
                    worklist.extend(exprs.iter());
                }
                Self::If { cond, then, els } => {
                    worklist.push(cond);
                    worklist.push(then);
                    worklist.push(els);
                }
                _ => {
                    return false; // Any other node makes `self` non-constant.
                }
            }
        }
        true
    }

    pub fn call_unary(self, func: UnaryFunc) -> Self {
        HirScalarExpr::CallUnary {
            func,
            expr: Box::new(self),
        }
    }

    pub fn call_binary(self, other: Self, func: BinaryFunc) -> Self {
        HirScalarExpr::CallBinary {
            func,
            expr1: Box::new(self),
            expr2: Box::new(other),
        }
    }

    pub fn or(self, other: Self) -> Self {
        HirScalarExpr::CallVariadic {
            func: VariadicFunc::Or,
            exprs: vec![self, other],
        }
    }

    pub fn and(self, other: Self) -> Self {
        HirScalarExpr::CallVariadic {
            func: VariadicFunc::And,
            exprs: vec![self, other],
        }
    }

    pub fn not(self) -> Self {
        self.call_unary(UnaryFunc::Not(func::Not))
    }

    pub fn call_is_null(self) -> Self {
        self.call_unary(UnaryFunc::IsNull(func::IsNull))
    }

    /// Calls AND with the given arguments. Simplifies if 0 or 1 args.
    pub fn variadic_and(mut args: Vec<HirScalarExpr>) -> HirScalarExpr {
        match args.len() {
            0 => HirScalarExpr::literal_true(), // Same as unit_of_and_or, but that's MirScalarExpr
            1 => args.swap_remove(0),
            _ => HirScalarExpr::CallVariadic {
                func: VariadicFunc::And,
                exprs: args,
            },
        }
    }

    /// Calls OR with the given arguments. Simplifies if 0 or 1 args.
    pub fn variadic_or(mut args: Vec<HirScalarExpr>) -> HirScalarExpr {
        match args.len() {
            0 => HirScalarExpr::literal_false(), // Same as unit_of_and_or, but that's MirScalarExpr
            1 => args.swap_remove(0),
            _ => HirScalarExpr::CallVariadic {
                func: VariadicFunc::Or,
                exprs: args,
            },
        }
    }

    pub fn take(&mut self) -> Self {
        mem::replace(self, HirScalarExpr::literal_null(ScalarType::String))
    }

    pub fn visit<'a, F>(&'a self, f: &mut F)
    where
        F: FnMut(&'a Self),
    {
        self.visit1(|e: &HirScalarExpr| e.visit(f));
        f(self);
    }

    pub fn visit1<'a, F>(&'a self, mut f: F)
    where
        F: FnMut(&'a Self),
    {
        use HirScalarExpr::*;
        match self {
            Column(..) | Parameter(..) | Literal(..) | CallUnmaterializable(..) => (),
            CallUnary { expr, .. } => f(expr),
            CallBinary { expr1, expr2, .. } => {
                f(expr1);
                f(expr2);
            }
            CallVariadic { exprs, .. } => {
                for expr in exprs {
                    f(expr);
                }
            }
            If { cond, then, els } => {
                f(cond);
                f(then);
                f(els);
            }
            Exists(..) | Select(..) => (),
            Windowing(expr) => {
                let _ = expr.visit_expressions(&mut |e| -> Result<(), ()> {
                    f(e);
                    Ok(())
                });
            }
        }
    }

    #[deprecated = "Use `Visit::visit_post` instead."]
    pub fn visit_mut<F>(&mut self, f: &mut F)
    where
        F: FnMut(&mut Self),
    {
        #[allow(deprecated)]
        self.visit1_mut(|e: &mut HirScalarExpr| e.visit_mut(f));
        f(self);
    }

    #[deprecated = "Use `Visit::visit_mut_pre` instead."]
    pub fn visit_mut_pre<F>(&mut self, f: &mut F)
    where
        F: FnMut(&mut Self),
    {
        f(self);
        #[allow(deprecated)]
        self.visit1_mut(|e: &mut HirScalarExpr| e.visit_mut(f));
    }

    #[deprecated = "Use `VisitChildren<HirScalarExpr>::visit_children` instead."]
    pub fn visit1_mut<F>(&mut self, mut f: F)
    where
        F: FnMut(&mut Self),
    {
        use HirScalarExpr::*;
        match self {
            Column(..) | Parameter(..) | Literal(..) | CallUnmaterializable(..) => (),
            CallUnary { expr, .. } => f(expr),
            CallBinary { expr1, expr2, .. } => {
                f(expr1);
                f(expr2);
            }
            CallVariadic { exprs, .. } => {
                for expr in exprs {
                    f(expr);
                }
            }
            If { cond, then, els } => {
                f(cond);
                f(then);
                f(els);
            }
            Exists(..) | Select(..) => (),
            Windowing(expr) => {
                let _ = expr.visit_expressions_mut(&mut |e| -> Result<(), ()> {
                    f(e);
                    Ok(())
                });
            }
        }
    }

    #[deprecated = "Use `Visit::visit_pre_post` instead."]
    /// A generalization of `visit`. The function `pre` runs on a
    /// `HirScalarExpr` before it runs on any of the child `HirScalarExpr`s.
    /// The function `post` runs on child `HirScalarExpr`s first before the
    /// parent. Optionally, `pre` can return which child `HirScalarExpr`s, if
    /// any, should be visited (default is to visit all children).
    pub fn visit_pre_post<F1, F2>(&self, pre: &mut F1, post: &mut F2)
    where
        F1: FnMut(&Self) -> Option<Vec<&Self>>,
        F2: FnMut(&Self),
    {
        let to_visit = pre(self);
        if let Some(to_visit) = to_visit {
            for e in to_visit {
                e.visit_pre_post(pre, post);
            }
        } else {
            self.visit1(|e| e.visit_pre_post(pre, post));
        }
        post(self);
    }

    #[deprecated = "Redefine this based on the `Visit` and `VisitChildren` methods."]
    /// Visits the column references in this scalar expression.
    ///
    /// The `depth` argument should indicate the subquery nesting depth of the expression,
    /// which will be incremented with each subquery entered and presented to the supplied
    /// function `f`.
    pub fn visit_columns<F>(&self, depth: usize, f: &mut F)
    where
        F: FnMut(usize, &ColumnRef),
    {
        #[allow(deprecated)]
        let _ = self.visit_recursively(depth, &mut |depth: usize,
                                                    e: &HirScalarExpr|
         -> Result<(), ()> {
            if let HirScalarExpr::Column(col) = e {
                f(depth, col)
            }
            Ok(())
        });
    }

    #[deprecated = "Redefine this based on the `Visit` and `VisitChildren` methods."]
    /// Like `visit_columns`, but permits mutating the column references.
    pub fn visit_columns_mut<F>(&mut self, depth: usize, f: &mut F)
    where
        F: FnMut(usize, &mut ColumnRef),
    {
        #[allow(deprecated)]
        let _ = self.visit_recursively_mut(depth, &mut |depth: usize,
                                                        e: &mut HirScalarExpr|
         -> Result<(), ()> {
            if let HirScalarExpr::Column(col) = e {
                f(depth, col)
            }
            Ok(())
        });
    }

    /// Visits those column references in this scalar expression that refer to the root
    /// level. These include column references that are at the root level, as well as column
    /// references that are at a deeper subquery nesting depth, but refer back to the root level.
    /// (Note that even if `self` is embedded inside a larger expression, we consider the
    /// "root level" to be `self`'s level.)
    pub fn visit_columns_referring_to_root_level<F>(&self, f: &mut F)
    where
        F: FnMut(usize),
    {
        #[allow(deprecated)]
        let _ = self.visit_recursively(0, &mut |depth: usize,
                                                e: &HirScalarExpr|
         -> Result<(), ()> {
            if let HirScalarExpr::Column(col) = e {
                if col.level == depth {
                    f(col.column)
                }
            }
            Ok(())
        });
    }

    /// Like `visit_columns_referring_to_root_level`, but permits mutating the column references.
    pub fn visit_columns_referring_to_root_level_mut<F>(&mut self, f: &mut F)
    where
        F: FnMut(&mut usize),
    {
        #[allow(deprecated)]
        let _ = self.visit_recursively_mut(0, &mut |depth: usize,
                                                    e: &mut HirScalarExpr|
         -> Result<(), ()> {
            if let HirScalarExpr::Column(col) = e {
                if col.level == depth {
                    f(&mut col.column)
                }
            }
            Ok(())
        });
    }

    #[deprecated = "Redefine this based on the `Visit` and `VisitChildren` methods."]
    /// Like `visit` but it enters the subqueries visiting the scalar expressions contained
    /// in them. It takes the current depth of the expression and increases it when
    /// entering a subquery.
    pub fn visit_recursively<F, E>(&self, depth: usize, f: &mut F) -> Result<(), E>
    where
        F: FnMut(usize, &HirScalarExpr) -> Result<(), E>,
    {
        match self {
            HirScalarExpr::Literal(_, _)
            | HirScalarExpr::Parameter(_)
            | HirScalarExpr::CallUnmaterializable(_)
            | HirScalarExpr::Column(_) => (),
            HirScalarExpr::CallUnary { expr, .. } => expr.visit_recursively(depth, f)?,
            HirScalarExpr::CallBinary { expr1, expr2, .. } => {
                expr1.visit_recursively(depth, f)?;
                expr2.visit_recursively(depth, f)?;
            }
            HirScalarExpr::CallVariadic { exprs, .. } => {
                for expr in exprs {
                    expr.visit_recursively(depth, f)?;
                }
            }
            HirScalarExpr::If { cond, then, els } => {
                cond.visit_recursively(depth, f)?;
                then.visit_recursively(depth, f)?;
                els.visit_recursively(depth, f)?;
            }
            HirScalarExpr::Exists(expr) | HirScalarExpr::Select(expr) => {
                #[allow(deprecated)]
                expr.visit_scalar_expressions(depth + 1, &mut |e, depth| {
                    e.visit_recursively(depth, f)
                })?;
            }
            HirScalarExpr::Windowing(expr) => {
                expr.visit_expressions(&mut |e| e.visit_recursively(depth, f))?;
            }
        }
        f(depth, self)
    }

    #[deprecated = "Redefine this based on the `Visit` and `VisitChildren` methods."]
    /// Like `visit_recursively`, but permits mutating the scalar expressions.
    pub fn visit_recursively_mut<F, E>(&mut self, depth: usize, f: &mut F) -> Result<(), E>
    where
        F: FnMut(usize, &mut HirScalarExpr) -> Result<(), E>,
    {
        match self {
            HirScalarExpr::Literal(_, _)
            | HirScalarExpr::Parameter(_)
            | HirScalarExpr::CallUnmaterializable(_)
            | HirScalarExpr::Column(_) => (),
            HirScalarExpr::CallUnary { expr, .. } => expr.visit_recursively_mut(depth, f)?,
            HirScalarExpr::CallBinary { expr1, expr2, .. } => {
                expr1.visit_recursively_mut(depth, f)?;
                expr2.visit_recursively_mut(depth, f)?;
            }
            HirScalarExpr::CallVariadic { exprs, .. } => {
                for expr in exprs {
                    expr.visit_recursively_mut(depth, f)?;
                }
            }
            HirScalarExpr::If { cond, then, els } => {
                cond.visit_recursively_mut(depth, f)?;
                then.visit_recursively_mut(depth, f)?;
                els.visit_recursively_mut(depth, f)?;
            }
            HirScalarExpr::Exists(expr) | HirScalarExpr::Select(expr) => {
                #[allow(deprecated)]
                expr.visit_scalar_expressions_mut(depth + 1, &mut |e, depth| {
                    e.visit_recursively_mut(depth, f)
                })?;
            }
            HirScalarExpr::Windowing(expr) => {
                expr.visit_expressions_mut(&mut |e| e.visit_recursively_mut(depth, f))?;
            }
        }
        f(depth, self)
    }

    fn simplify_to_literal(self) -> Option<Row> {
        let mut expr = self.lower_uncorrelated().ok()?;
        expr.reduce(&[]);
        match expr {
            mz_expr::MirScalarExpr::Literal(Ok(row), _) => Some(row),
            _ => None,
        }
    }

    /// Attempts to simplify this expression to a literal 64-bit integer.
    ///
    /// Returns `None` if this expression cannot be simplified, e.g. because it
    /// contains non-literal values.
    ///
    /// # Panics
    ///
    /// Panics if this expression does not have type [`ScalarType::Int64`].
    pub fn into_literal_int64(self) -> Option<i64> {
        self.simplify_to_literal().and_then(|row| {
            let datum = row.unpack_first();
            if datum.is_null() {
                None
            } else {
                Some(datum.unwrap_int64())
            }
        })
    }

    /// Attempts to simplify this expression to a literal string.
    ///
    /// Returns `None` if this expression cannot be simplified, e.g. because it
    /// contains non-literal values.
    ///
    /// # Panics
    ///
    /// Panics if this expression does not have type [`ScalarType::String`].
    pub fn into_literal_string(self) -> Option<String> {
        self.simplify_to_literal().and_then(|row| {
            let datum = row.unpack_first();
            if datum.is_null() {
                None
            } else {
                Some(datum.unwrap_str().to_owned())
            }
        })
    }

    /// Attempts to simplify this expression to a literal MzTimestamp.
    ///
    /// Returns `None` if this expression cannot be simplified, e.g. because it
    /// contains non-literal values.
    ///
    /// TODO: Make this (and the other similar fns above) return Result, so that we can show the
    /// error when it fails. (E.g., there can be non-trivial cast errors.)
    ///
    /// # Panics
    ///
    /// Panics if this expression does not have type [`ScalarType::MzTimestamp`].
    pub fn into_literal_mz_timestamp(self) -> Option<Timestamp> {
        self.simplify_to_literal().and_then(|row| {
            let datum = row.unpack_first();
            if datum.is_null() {
                None
            } else {
                Some(datum.unwrap_mz_timestamp())
            }
        })
    }
}

impl VisitChildren<Self> for HirScalarExpr {
    fn visit_children<F>(&self, mut f: F)
    where
        F: FnMut(&Self),
    {
        use HirScalarExpr::*;
        match self {
            Column(..) | Parameter(..) | Literal(..) | CallUnmaterializable(..) => (),
            CallUnary { expr, .. } => f(expr),
            CallBinary { expr1, expr2, .. } => {
                f(expr1);
                f(expr2);
            }
            CallVariadic { exprs, .. } => {
                for expr in exprs {
                    f(expr);
                }
            }
            If { cond, then, els } => {
                f(cond);
                f(then);
                f(els);
            }
            Exists(..) | Select(..) => (),
            Windowing(expr) => expr.visit_children(f),
        }
    }

    fn visit_mut_children<F>(&mut self, mut f: F)
    where
        F: FnMut(&mut Self),
    {
        use HirScalarExpr::*;
        match self {
            Column(..) | Parameter(..) | Literal(..) | CallUnmaterializable(..) => (),
            CallUnary { expr, .. } => f(expr),
            CallBinary { expr1, expr2, .. } => {
                f(expr1);
                f(expr2);
            }
            CallVariadic { exprs, .. } => {
                for expr in exprs {
                    f(expr);
                }
            }
            If { cond, then, els } => {
                f(cond);
                f(then);
                f(els);
            }
            Exists(..) | Select(..) => (),
            Windowing(expr) => expr.visit_mut_children(f),
        }
    }

    fn try_visit_children<F, E>(&self, mut f: F) -> Result<(), E>
    where
        F: FnMut(&Self) -> Result<(), E>,
        E: From<RecursionLimitError>,
    {
        use HirScalarExpr::*;
        match self {
            Column(..) | Parameter(..) | Literal(..) | CallUnmaterializable(..) => (),
            CallUnary { expr, .. } => f(expr)?,
            CallBinary { expr1, expr2, .. } => {
                f(expr1)?;
                f(expr2)?;
            }
            CallVariadic { exprs, .. } => {
                for expr in exprs {
                    f(expr)?;
                }
            }
            If { cond, then, els } => {
                f(cond)?;
                f(then)?;
                f(els)?;
            }
            Exists(..) | Select(..) => (),
            Windowing(expr) => expr.try_visit_children(f)?,
        }
        Ok(())
    }

    fn try_visit_mut_children<F, E>(&mut self, mut f: F) -> Result<(), E>
    where
        F: FnMut(&mut Self) -> Result<(), E>,
        E: From<RecursionLimitError>,
    {
        use HirScalarExpr::*;
        match self {
            Column(..) | Parameter(..) | Literal(..) | CallUnmaterializable(..) => (),
            CallUnary { expr, .. } => f(expr)?,
            CallBinary { expr1, expr2, .. } => {
                f(expr1)?;
                f(expr2)?;
            }
            CallVariadic { exprs, .. } => {
                for expr in exprs {
                    f(expr)?;
                }
            }
            If { cond, then, els } => {
                f(cond)?;
                f(then)?;
                f(els)?;
            }
            Exists(..) | Select(..) => (),
            Windowing(expr) => expr.try_visit_mut_children(f)?,
        }
        Ok(())
    }
}

impl AbstractExpr for HirScalarExpr {
    type Type = ColumnType;

    fn typ(
        &self,
        outers: &[RelationType],
        inner: &RelationType,
        params: &BTreeMap<usize, ScalarType>,
    ) -> Self::Type {
        stack::maybe_grow(|| match self {
            HirScalarExpr::Column(ColumnRef { level, column }) => {
                if *level == 0 {
                    inner.column_types[*column].clone()
                } else {
                    outers[*level - 1].column_types[*column].clone()
                }
            }
            HirScalarExpr::Parameter(n) => params[n].clone().nullable(true),
            HirScalarExpr::Literal(_, typ) => typ.clone(),
            HirScalarExpr::CallUnmaterializable(func) => func.output_type(),
            HirScalarExpr::CallUnary { expr, func } => {
                func.output_type(expr.typ(outers, inner, params))
            }
            HirScalarExpr::CallBinary { expr1, expr2, func } => func.output_type(
                expr1.typ(outers, inner, params),
                expr2.typ(outers, inner, params),
            ),
            HirScalarExpr::CallVariadic { exprs, func } => {
                func.output_type(exprs.iter().map(|e| e.typ(outers, inner, params)).collect())
            }
            HirScalarExpr::If { cond: _, then, els } => {
                let then_type = then.typ(outers, inner, params);
                let else_type = els.typ(outers, inner, params);
                then_type.union(&else_type).unwrap()
            }
            HirScalarExpr::Exists(_) => ScalarType::Bool.nullable(true),
            HirScalarExpr::Select(expr) => {
                let mut outers = outers.to_vec();
                outers.insert(0, inner.clone());
                expr.typ(&outers, params)
                    .column_types
                    .into_element()
                    .nullable(true)
            }
            HirScalarExpr::Windowing(expr) => expr.func.typ(outers, inner, params),
        })
    }
}

impl AggregateExpr {
    /// Replaces any parameter references in the expression with the
    /// corresponding datum from `parameters`.
    pub fn bind_parameters(&mut self, params: &Params) -> Result<(), PlanError> {
        self.expr.bind_parameters(params)
    }

    pub fn typ(
        &self,
        outers: &[RelationType],
        inner: &RelationType,
        params: &BTreeMap<usize, ScalarType>,
    ) -> ColumnType {
        self.func.output_type(self.expr.typ(outers, inner, params))
    }

    pub fn is_count_asterisk(&self) -> bool {
        // This could be much less cumbersome if box/deref pattern
        // syntax were stable: <https://github.com/rust-lang/rust/issues/29641>
        if self.func != AggregateFunc::Count {
            return false;
        }
        match &*self.expr {
            HirScalarExpr::Literal(
                row,
                mz_repr::ColumnType {
                    scalar_type: mz_repr::ScalarType::Bool,
                    nullable: false,
                },
            ) => row.unpack_first() == mz_repr::Datum::True,
            _ => false,
        }
    }
}