datafusion-optimizer 56.0.0

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

//! [`DecorrelatePredicateSubquery`] converts `IN`/`EXISTS` subquery predicates to `SEMI`/`ANTI` joins
use std::collections::BTreeSet;
use std::ops::Deref;
use std::sync::Arc;

use crate::analyzer::type_coercion::TypeCoercionRewriter;
use crate::decorrelate::{
    PullUpCorrelatedExpr, UN_MATCHED_ROW_INDICATOR, build_join_filter,
};
use crate::extract_equijoin_predicate::split_eq_and_noneq_join_predicate;
use crate::optimizer::ApplyOrder;
use crate::{OptimizerConfig, OptimizerRule};

use datafusion_common::alias::AliasGenerator;
use datafusion_common::tree_node::{
    Transformed, TransformedResult, TreeNode, TreeNodeRecursion,
};
use datafusion_common::{
    Column, DFSchema, NullEquality, Result, ScalarValue, assert_or_internal_err,
    internal_datafusion_err, internal_err, not_impl_err, plan_err,
};
use datafusion_expr::expr::{Exists, InSubquery, in_subquery_tuple_values};
use datafusion_expr::expr_rewriter::{
    create_col_from_scalar_expr, strip_outer_reference,
};
use datafusion_expr::logical_plan::{JoinType, Subquery};
use datafusion_expr::utils::{conjunction, expr_to_columns, split_conjunction_owned};
use datafusion_expr::{
    BinaryExpr, Expr, ExprSchemable, Filter, LogicalPlan, LogicalPlanBuilder, Operator,
    exists, in_subquery, lit, not, not_exists, not_in_subquery, when,
};

use log::debug;

/// Optimizer rule for rewriting predicate(IN/EXISTS) subquery to left semi/anti joins
#[derive(Default, Debug)]
pub struct DecorrelatePredicateSubquery {}

impl DecorrelatePredicateSubquery {
    #[expect(missing_docs)]
    pub fn new() -> Self {
        Self::default()
    }
}

impl OptimizerRule for DecorrelatePredicateSubquery {
    fn rewrite(
        &self,
        plan: LogicalPlan,
        config: &dyn OptimizerConfig,
    ) -> Result<Transformed<LogicalPlan>> {
        let plan = plan
            .map_subqueries(|subquery| {
                subquery.transform_down(|p| self.rewrite(p, config))
            })?
            .data;

        if let LogicalPlan::Projection(projection) = plan {
            if !projection.expr.iter().any(has_subquery) {
                return Ok(Transformed::no(LogicalPlan::Projection(projection)));
            }

            let original_projection = projection.clone();
            let mut cur_input = Arc::unwrap_or_clone(projection.input);
            let mut rewritten_exprs = Vec::with_capacity(projection.expr.len());
            for expr in projection.expr {
                let original_name = expr.schema_name().to_string();
                let (new_input, mut rewritten_expr) =
                    rewrite_inner_subqueries(cur_input, expr, config, true, true)?;
                if has_subquery(&rewritten_expr) {
                    return Ok(Transformed::no(LogicalPlan::Projection(
                        original_projection,
                    )));
                }
                cur_input = new_input;

                if rewritten_expr.schema_name().to_string() != original_name {
                    rewritten_expr = rewritten_expr.alias(original_name);
                }
                rewritten_exprs.push(rewritten_expr);
            }

            let new_plan = LogicalPlanBuilder::from(cur_input)
                .project(rewritten_exprs)?
                .build()?;
            return Ok(Transformed::yes(new_plan));
        }

        let LogicalPlan::Filter(filter) = plan else {
            return Ok(Transformed::no(plan));
        };

        if !has_subquery(&filter.predicate) {
            return Ok(Transformed::no(LogicalPlan::Filter(filter)));
        }

        let (with_subqueries, mut other_exprs): (Vec<_>, Vec<_>) =
            split_conjunction_owned(filter.predicate)
                .into_iter()
                .partition(has_subquery);

        assert_or_internal_err!(
            !with_subqueries.is_empty(),
            "can not find expected subqueries in DecorrelatePredicateSubquery"
        );

        // iterate through all exists clauses in predicate, turning each into a join
        let mut cur_input = Arc::unwrap_or_clone(filter.input);
        let original_schema = cur_input.schema().columns();
        for subquery_expr in with_subqueries {
            match extract_subquery_info(subquery_expr) {
                // The subquery expression is at the top level of the filter
                SubqueryPredicate::Top(subquery) => {
                    match build_join_top(&subquery, &cur_input, config.alias_generator())?
                    {
                        Some(plan) => cur_input = plan,
                        // The subquery cannot become a semi or anti join. A
                        // `NOT IN` may still become mark joins that
                        // materialize its three-valued result, see
                        // `in_subquery_value_mark_join`. Any other subquery
                        // expression goes back into the filter as it is.
                        None => match subquery.expr() {
                            expr @ Expr::InSubquery(InSubquery {
                                negated: true, ..
                            }) => {
                                let (plan, expr) = rewrite_inner_subqueries(
                                    cur_input, expr, config, true, true,
                                )?;
                                cur_input = plan;
                                other_exprs.push(expr);
                            }
                            expr => other_exprs.push(expr),
                        },
                    }
                }
                // The subquery expression is embedded within another expression
                SubqueryPredicate::Embedded(expr) => {
                    let (plan, expr_without_subqueries) =
                        rewrite_filter_subqueries(cur_input, expr, config)?;
                    cur_input = plan;
                    other_exprs.push(expr_without_subqueries);
                }
            }
        }

        let expr = conjunction(other_exprs);
        if let Some(expr) = expr {
            let new_filter = Filter::try_new(expr, Arc::new(cur_input))?;
            cur_input = LogicalPlan::Filter(new_filter);
        }

        if cur_input.schema().fields().len() != original_schema.len() {
            cur_input = LogicalPlanBuilder::from(cur_input)
                .project(original_schema.into_iter().map(Expr::from))?
                .build()?;
        }

        Ok(Transformed::yes(cur_input))
    }

    fn name(&self) -> &str {
        "decorrelate_predicate_subquery"
    }

    fn apply_order(&self) -> Option<ApplyOrder> {
        Some(ApplyOrder::TopDown)
    }
}

/// Rewrites the subqueries of one embedded `Filter` conjunct, deciding for each
/// occurrence whether its mark join has to be null-aware.
///
/// A `Filter` keeps a row only when the predicate is TRUE, and `AND`/`OR` make
/// TRUE only out of TRUE. A NULL mark therefore acts exactly like a FALSE mark
/// under them, so a non-negated `IN` reached through nothing but `AND`/`OR`
/// does not need the more expensive null-aware join. Every other context can
/// tell NULL from FALSE and gets one.
///
/// The decision is taken at the occurrence rather than once for the whole
/// conjunct, so a sibling's shape cannot change it, and any expression this
/// function does not name falls through to the null-aware branch.
fn rewrite_filter_subqueries(
    outer: LogicalPlan,
    expr: Expr,
    config: &dyn OptimizerConfig,
) -> Result<(LogicalPlan, Expr)> {
    match expr {
        Expr::BinaryExpr(BinaryExpr {
            left,
            op: op @ (Operator::And | Operator::Or),
            right,
        }) => {
            let (outer, left) = rewrite_filter_subqueries(outer, *left, config)?;
            let (outer, right) = rewrite_filter_subqueries(outer, *right, config)?;
            Ok((
                outer,
                Expr::BinaryExpr(BinaryExpr::new(Box::new(left), op, Box::new(right))),
            ))
        }
        Expr::InSubquery(in_subquery) => {
            // A subquery in the `IN` value is compared, not used as a filter
            // truth value, so its own mark is observable there.
            let needs_null_aware_mark =
                in_subquery.negated || has_subquery(&in_subquery.expr);
            rewrite_inner_subqueries(
                outer,
                Expr::InSubquery(in_subquery),
                config,
                false,
                needs_null_aware_mark,
            )
        }
        other => rewrite_inner_subqueries(outer, other, config, false, true),
    }
}

/// `needs_null_aware_mark` is `false` only when the caller can prove that a NULL
/// mark and a FALSE mark give the same answer. See [`rewrite_filter_subqueries`].
fn rewrite_inner_subqueries(
    outer: LogicalPlan,
    expr: Expr,
    config: &dyn OptimizerConfig,
    materialize_in_value: bool,
    needs_null_aware_mark: bool,
) -> Result<(LogicalPlan, Expr)> {
    let mut cur_input = outer;
    let alias = config.alias_generator();
    let expr_without_subqueries = expr.transform(|e| match e {
        Expr::Exists(Exists {
            subquery: Subquery { subquery, .. },
            negated,
        }) => match mark_join(
            &cur_input,
            &subquery,
            None,
            negated,
            alias,
            needs_null_aware_mark,
        )? {
            Some(MarkJoin {
                plan,
                mark: exists_expr,
                ..
            }) => {
                cur_input = plan;
                Ok(Transformed::yes(exists_expr))
            }
            None if negated => Ok(Transformed::no(not_exists(subquery))),
            None => Ok(Transformed::no(exists(subquery))),
        },
        Expr::InSubquery(InSubquery {
            expr,
            subquery: Subquery { subquery, .. },
            negated,
        }) => {
            let rewritten = if materialize_in_value {
                in_subquery_value_mark_join(
                    &cur_input,
                    &subquery,
                    *expr.clone(),
                    negated,
                    alias,
                )?
            } else {
                let in_predicate = subquery
                    .head_output_expr()?
                    .map_or(plan_err!("single expression required."), |output_expr| {
                        Ok(Expr::eq(*expr.clone(), output_expr))
                    })?;
                mark_join(
                    &cur_input,
                    &subquery,
                    Some(&in_predicate),
                    negated,
                    alias,
                    needs_null_aware_mark,
                )?
                .map(|join| (join.plan, join.mark))
            };
            match rewritten {
                Some((plan, exists_expr)) => {
                    cur_input = plan;
                    Ok(Transformed::yes(exists_expr))
                }
                None if negated => Ok(Transformed::no(not_in_subquery(*expr, subquery))),
                None => Ok(Transformed::no(in_subquery(*expr, subquery))),
            }
        }
        _ => Ok(Transformed::no(e)),
    })?;
    Ok((cur_input, expr_without_subqueries.data))
}

/// Rewrites an `IN` subquery that gives a value, for example in a SELECT list.
/// The value follows SQL three-valued logic: TRUE for a match, FALSE for a miss
/// and NULL (UNKNOWN) when the answer depends on a NULL.
///
/// There are two paths:
///
/// * One mark join. When the mark column is already exact under three-valued
///   logic (see [`MarkJoin::three_valued_exact`]), the mark column is the
///   answer and this single join is the full rewrite. This is the usual case.
/// * Three mark joins. In the other case the mark column only tells TRUE from
///   not-TRUE, so the UNKNOWN cases must be materialized: one more join tells
///   if the subquery gives a NULL, and one more tells if the subquery gives
///   any row. A `CASE` expression puts the three marks together. The two extra
///   joins have no join predicate, so use them only when the first path
///   cannot apply.
fn in_subquery_value_mark_join(
    left: &LogicalPlan,
    subquery: &LogicalPlan,
    expr: Expr,
    negated: bool,
    alias: &Arc<AliasGenerator>,
) -> Result<Option<(LogicalPlan, Expr)>> {
    let output_expr = subquery
        .head_output_expr()?
        .map_or(plan_err!("single expression required."), Ok)?;
    let in_predicate = Expr::eq(expr.clone(), output_expr.clone());
    let Some(MarkJoin {
        plan: matched_plan,
        mark: matched,
        three_valued_exact,
    }) = mark_join(left, subquery, Some(&in_predicate), false, alias, true)?
    else {
        return Ok(None);
    };

    // The mark column is the full answer when it is exact. Negation does not
    // change that, because NOT UNKNOWN is UNKNOWN.
    if three_valued_exact {
        return Ok(Some((
            matched_plan,
            if negated { not(matched) } else { matched },
        )));
    }

    // The fallback below compares the `IN` value as a single value, which a
    // multi-column `(a, b) IN (SELECT x, y ...)` is not. `build_join` rejects
    // the tuples whose mark cannot be exact, so this is not reached for them.
    if in_subquery_tuple_values(&expr, subquery)?.is_some() {
        return internal_err!(
            "a multi-column IN subquery needs a three-valued exact mark join"
        );
    }
    // SQL IN needs three facts per outer row to distinguish FALSE from UNKNOWN.
    let null_subquery = LogicalPlanBuilder::from(subquery.clone())
        .filter(output_expr.is_null())?
        .build()?;
    let Some(MarkJoin {
        plan: null_plan,
        mark: subquery_has_null,
        ..
    }) = mark_join(&matched_plan, &null_subquery, None, false, alias, true)?
    else {
        return Ok(None);
    };
    let Some(MarkJoin {
        plan: final_plan,
        mark: subquery_non_empty,
        ..
    }) = mark_join(&null_plan, subquery, None, false, alias, true)?
    else {
        return Ok(None);
    };

    let unknown = subquery_has_null.or(expr.is_null().and(subquery_non_empty));
    let result = when(matched, lit(true))
        .when(unknown, lit(ScalarValue::Boolean(None)))
        .otherwise(lit(false))?;
    Ok(Some((
        final_plan,
        if negated { not(result) } else { result },
    )))
}

enum SubqueryPredicate {
    // The subquery expression is at the top level of the filter and can be fully replaced by a
    // semi/anti join
    Top(SubqueryInfo),
    // The subquery expression is embedded within another expression and is replaced using an
    // existence join
    Embedded(Expr),
}

fn extract_subquery_info(expr: Expr) -> SubqueryPredicate {
    match expr {
        Expr::Not(not_expr) => match *not_expr {
            Expr::InSubquery(InSubquery {
                expr,
                subquery,
                negated,
            }) => SubqueryPredicate::Top(SubqueryInfo::new_with_in_expr(
                subquery, *expr, !negated,
            )),
            Expr::Exists(Exists { subquery, negated }) => {
                SubqueryPredicate::Top(SubqueryInfo::new(subquery, !negated))
            }
            expr => SubqueryPredicate::Embedded(not(expr)),
        },
        Expr::InSubquery(InSubquery {
            expr,
            subquery,
            negated,
        }) => SubqueryPredicate::Top(SubqueryInfo::new_with_in_expr(
            subquery, *expr, negated,
        )),
        Expr::Exists(Exists { subquery, negated }) => {
            SubqueryPredicate::Top(SubqueryInfo::new(subquery, negated))
        }
        expr => SubqueryPredicate::Embedded(expr),
    }
}

fn has_subquery(expr: &Expr) -> bool {
    expr.exists(|e| match e {
        Expr::InSubquery(_) | Expr::Exists(_) => Ok(true),
        _ => Ok(false),
    })
    .unwrap()
}

/// Optimize the subquery to left-anti/left-semi join.
/// If the subquery is a correlated subquery, we need extract the join predicate from the subquery.
///
/// For example, given a query like:
/// `select t1.a, t1.b from t1 where t1 in (select t2.a from t2 where t1.b = t2.b and t1.c > t2.c)`
///
/// The optimized plan will be:
///
/// ```text
/// Projection: t1.a, t1.b
///   LeftSemi Join:  Filter: t1.a = __correlated_sq_1.a AND t1.b = __correlated_sq_1.b AND t1.c > __correlated_sq_1.c
///     TableScan: t1
///     SubqueryAlias: __correlated_sq_1
///       Projection: t2.a, t2.b, t2.c
///         TableScan: t2
/// ```
///
/// Given another query like:
/// `select t1.id from t1 where exists(SELECT t2.id FROM t2 WHERE t1.id = t2.id)`
///
/// The optimized plan will be:
///
/// ```text
/// Projection: t1.id
///   LeftSemi Join:  Filter: t1.id = __correlated_sq_1.id
///     TableScan: t1
///     SubqueryAlias: __correlated_sq_1
///       Projection: t2.id
///         TableScan: t2
/// ```
fn build_join_top(
    query_info: &SubqueryInfo,
    left: &LogicalPlan,
    alias: &Arc<AliasGenerator>,
) -> Result<Option<LogicalPlan>> {
    let where_in_expr_opt = &query_info.where_in_expr;
    let in_predicate_opt = where_in_expr_opt
        .clone()
        .map(|where_in_expr| {
            query_info
                .query
                .subquery
                .head_output_expr()?
                .map_or(plan_err!("single expression required."), |expr| {
                    Ok(Expr::eq(where_in_expr, expr))
                })
        })
        .map_or(Ok(None), |v| v.map(Some))?;

    let join_type = match query_info.negated {
        true => JoinType::LeftAnti,
        false => JoinType::LeftSemi,
    };
    let subquery = query_info.query.subquery.as_ref();
    let subquery_alias = alias.next("__correlated_sq");
    Ok(build_join(
        left,
        subquery,
        in_predicate_opt.as_ref(),
        join_type,
        &subquery_alias,
        true,
    )?
    .map(|join| join.plan))
}

/// This is used to handle the case when the subquery is embedded in a more complex boolean
/// expression like and OR. For example
///
/// `select t1.id from t1 where t1.id < 0 OR exists(SELECT t2.id FROM t2 WHERE t1.id = t2.id)`
///
/// The optimized plan will be:
///
/// ```text
/// Projection: t1.id
///   Filter: t1.id < 0 OR __correlated_sq_1.mark
///     LeftMark Join:  Filter: t1.id = __correlated_sq_1.id
///       TableScan: t1
///       SubqueryAlias: __correlated_sq_1
///         Projection: t2.id
///           TableScan: t2
fn mark_join(
    left: &LogicalPlan,
    subquery: &LogicalPlan,
    in_predicate_opt: Option<&Expr>,
    negated: bool,
    alias_generator: &Arc<AliasGenerator>,
    needs_null_aware_mark: bool,
) -> Result<Option<MarkJoin>> {
    let alias = alias_generator.next("__correlated_sq");

    let exists_col = Expr::Column(Column::new(Some(alias.clone()), "mark"));
    let exists_expr = if negated { !exists_col } else { exists_col };

    Ok(build_join(
        left,
        subquery,
        in_predicate_opt,
        JoinType::LeftMark,
        &alias,
        needs_null_aware_mark,
    )?
    .map(|join| MarkJoin {
        plan: join.plan,
        mark: exists_expr,
        three_valued_exact: join.mark_is_three_valued_exact,
    }))
}

/// A [`JoinType::LeftMark`] join that replaces a subquery predicate.
struct MarkJoin {
    /// The outer plan with the subquery joined into it.
    plan: LogicalPlan,
    /// Reads the mark column of the join, negated if the caller asked for it.
    mark: Expr,
    /// True when the mark column already gives SQL three-valued `IN`
    /// semantics: TRUE for a match, FALSE for a miss and NULL for UNKNOWN.
    ///
    /// A plain mark is exact when neither side of the `IN` predicate can be
    /// NULL in scope. Otherwise the join must be null-aware, and the `IN`
    /// equality must be its first key, which is where the null-aware hash join
    /// reads the `IN` value. That join also applies a residual non-equality
    /// filter when it decides whether a NULL makes the mark UNKNOWN.
    ///
    /// In any other case the caller materializes the UNKNOWN rows with more
    /// joins, see [`in_subquery_value_mark_join`].
    three_valued_exact: bool,
}

/// Are the `IN` equalities, in order, the first equalities of `join_filter`
/// that the hash join can use as keys? A null-aware hash join reads its first
/// `V` keys as the `IN` values (one per tuple element of a multi-column
/// `IN`) and the other keys as the correlation.
fn values_are_first_keys(
    in_values: &[InValue],
    join_filter: &Expr,
    left_schema: &DFSchema,
    right_schema: &DFSchema,
) -> Result<bool> {
    let (equijoin_keys, _) = split_eq_and_noneq_join_predicate(
        join_filter.clone(),
        left_schema,
        right_schema,
    )?;
    Ok(equijoin_keys.len() >= in_values.len()
        && equijoin_keys
            .iter()
            .zip(in_values)
            .all(|((value, column), in_value)| {
                value == &in_value.value && column == &in_value.subquery_column
            }))
}

/// The two sides of an `IN` predicate, `value IN (SELECT output_expr ..)`, or
/// of one tuple element of a multi-column `(a, b) IN (SELECT x, y ..)`.
struct InValue {
    /// The value from the outer plan, as the join filter refers to it. This is
    /// a projected column when `value_as_written` is a constant.
    value: Expr,
    /// The subquery output, as the join filter refers to it: a column of the
    /// aliased subquery.
    subquery_column: Expr,
    /// The value as the query writes it.
    value_as_written: Expr,
    /// The subquery output expression as the query writes it.
    output_expr: Expr,
}

impl InValue {
    /// Can either side be NULL for a row inside the scope of an outer row?
    /// See [`key_may_be_null_in_scope`]. The correlated filters name the
    /// expressions as the query writes them, so the test matches on those.
    ///
    /// Only then can `IN` be UNKNOWN, so only then does the join need
    /// null-aware semantics. A correlation key that is NULL just empties the
    /// scope, which makes `IN` FALSE.
    fn may_be_null_in_scope(
        &self,
        left_schema: &DFSchema,
        right_schema: &DFSchema,
        scope_filters: &[Expr],
    ) -> Result<bool> {
        Ok(key_may_be_null_in_scope(
            self.value.nullable(left_schema)?,
            &self.value_as_written,
            true,
            scope_filters,
        ) || key_may_be_null_in_scope(
            self.subquery_column.nullable(right_schema)?,
            &self.output_expr,
            false,
            scope_filters,
        ))
    }
}

/// Can this join key be NULL for a row inside the scope of an outer row?
///
/// `nullable` is what the schema says about the key. The key is a full
/// expression, not only a column. An expression can be NULL although none of
/// its columns is nullable: `NULLIF(id, 1)`, `TRY_CAST(s AS INT)`, a `CASE`
/// with no `ELSE` branch, or a scalar function that does not declare its
/// nullability. So the caller asks the key expression itself, against the
/// schema of its own side.
///
/// The subquery can still keep every NULL out of its result. A correlated
/// conjunct such as `y = x`, `y > x` or `y IS NOT NULL` is never TRUE for a
/// NULL `y`, so no row with a NULL `y` is in the scope of any outer row, and
/// an outer row with a NULL `x` has an empty scope. Neither can make `IN`
/// UNKNOWN, so such a key does not need null-aware semantics. The usual shape
/// is a correlation that repeats the `IN` predicate, `x IN (SELECT y FROM t
/// WHERE y = x)`: the pull up drops that conjunct from the join filter, but
/// it still bounds the subquery result
/// (<https://github.com/apache/datafusion/issues/25480>).
///
/// This is a sufficient test, not an exact one. A conjunct counts only if it
/// is a comparison or an `IS NOT NULL` on the key expression itself, casts
/// aside. Any other conjunct is assumed to let a NULL through, which keeps
/// the join null-aware.
///
/// `key_is_outer` tells on which side of the join the key is. The scope
/// filters keep their outer references, and a side of a conjunct matches an
/// outer key only if it names outer columns alone. A subquery column can have
/// the same qualified name as an outer column (`FROM t AS a` inside a query
/// over `a`), and it must not be read as the outer key.
fn key_may_be_null_in_scope(
    nullable: bool,
    key: &Expr,
    key_is_outer: bool,
    scope_filters: &[Expr],
) -> bool {
    if !nullable {
        return false;
    }
    let key = strip_casts(key);
    !scope_filters
        .iter()
        .any(|filter| filter_rejects_null(filter, key, key_is_outer))
}

/// Is `filter` never TRUE when `key` is NULL? See
/// [`key_may_be_null_in_scope`] for `key_is_outer`.
fn filter_rejects_null(filter: &Expr, key: &Expr, key_is_outer: bool) -> bool {
    let is_key = |side: &Expr| {
        let side = strip_casts(side);
        if key_is_outer {
            side.contains_outer()
                && side.column_refs().is_empty()
                && &strip_outer_reference(side.clone()) == key
        } else {
            !side.contains_outer() && side == key
        }
    };
    match filter {
        Expr::BinaryExpr(BinaryExpr { left, op, right }) => {
            matches!(
                op,
                Operator::Eq
                    | Operator::NotEq
                    | Operator::Lt
                    | Operator::LtEq
                    | Operator::Gt
                    | Operator::GtEq
            ) && (is_key(left) || is_key(right))
        }
        Expr::IsNotNull(expr) => is_key(expr),
        _ => false,
    }
}

/// `CAST(NULL)` is NULL and `CAST(x)` is not NULL for a non-null `x`, so a
/// conjunct on `x` says the same about `CAST(x)`, and the other way round.
/// Type coercion adds such casts on one side only. `TRY_CAST` can make a NULL
/// from a value, so it is not unwrapped.
fn strip_casts(expr: &Expr) -> &Expr {
    let mut expr = expr;
    while let Expr::Cast(cast) = expr {
        expr = cast.expr.as_ref();
    }
    expr
}

/// Combines the `IN`/`NOT IN` equalities, one per value, with the correlation
/// predicates, if any.
///
/// The equalities stay the leading conjuncts, in order, so that they become
/// `on[..V]`, the key positions a null-aware hash join reads as the `NOT IN`
/// value keys (see `HashJoinExec::null_aware`).
fn in_join_filter(in_values: &[InValue], correlation: Option<Expr>) -> Result<Expr> {
    conjunction(
        in_values
            .iter()
            .map(|in_value| {
                Expr::eq(in_value.value.clone(), in_value.subquery_column.clone())
            })
            .chain(correlation),
    )
    .ok_or_else(|| internal_datafusion_err!("an `IN` predicate has at least one value"))
}

/// The `i`-th output expression of `subquery`, as the query writes it.
fn subquery_output_expr(subquery: &LogicalPlan, i: usize) -> Result<Expr> {
    match subquery {
        _ if i == 0 => subquery
            .head_output_expr()?
            .ok_or_else(|| internal_datafusion_err!("subquery has no output expression")),
        LogicalPlan::Projection(projection) => Ok(projection.expr[i].clone()),
        _ => Ok(Expr::Column(Column::from(
            subquery.schema().qualified_field(i),
        ))),
    }
}

/// Sets [`Join::null_aware_value_keys`](datafusion_expr::Join::null_aware_value_keys)
/// on a null-aware join built by [`build_join`]. Only a null-aware join reads
/// the count, so any other join keeps it unset, as [`Join::try_new`] leaves
/// it, and equal joins compare equal however they were built.
///
/// [`Join::try_new`]: datafusion_expr::Join::try_new
fn with_null_aware_value_keys(
    plan: LogicalPlan,
    null_aware_value_keys: usize,
) -> Result<LogicalPlan> {
    let LogicalPlan::Join(join) = plan else {
        return internal_err!("expected a join, got {}", plan.display());
    };
    if !join.null_aware {
        return Ok(LogicalPlan::Join(join));
    }
    Ok(LogicalPlan::Join(
        join.with_null_aware_value_keys(null_aware_value_keys),
    ))
}

fn subquery_operands_are_bare_columns(
    join_filters: &[Expr],
    subquery_cols: &BTreeSet<Column>,
) -> bool {
    join_filters.iter().all(|filter| {
        let mut bare = true;
        filter
            .apply(|e| {
                let refs = e.column_refs();
                // `column_refs` skips outer references, which the join filters keep, so check them separately.
                if !refs.is_empty()
                    && !e.contains_outer()
                    && refs.iter().all(|c| subquery_cols.contains(*c))
                {
                    bare = matches!(e, Expr::Column(_));
                    return Ok(if bare {
                        TreeNodeRecursion::Jump
                    } else {
                        TreeNodeRecursion::Stop
                    });
                }
                Ok(TreeNodeRecursion::Continue)
            })
            .expect("infallible");
        bare
    })
}

/// The outcome of [`build_join`].
struct BuiltJoin {
    /// The outer plan with the subquery joined into it.
    plan: LogicalPlan,
    /// See [`MarkJoin::three_valued_exact`]. This is always false unless the
    /// join is a [`JoinType::LeftMark`] join built for an `IN` predicate.
    mark_is_three_valued_exact: bool,
}

fn build_join(
    left: &LogicalPlan,
    subquery: &LogicalPlan,
    in_predicate_opt: Option<&Expr>,
    join_type: JoinType,
    alias: &str,
    needs_null_aware_mark: bool,
) -> Result<Option<BuiltJoin>> {
    let exists_sub_query = in_predicate_opt.is_none();
    let rewrite =
        |handle_count_bug: bool| -> Result<(LogicalPlan, PullUpCorrelatedExpr)> {
            let mut pull_up = PullUpCorrelatedExpr::new()
                .with_in_predicate_opt(in_predicate_opt.cloned())
                .with_exists_sub_query(exists_sub_query)
                .with_need_handle_count_bug(handle_count_bug);
            let new_plan = subquery.clone().rewrite(&mut pull_up).data()?;
            Ok((new_plan, pull_up))
        };
    let (mut new_plan, mut pull_up) = rewrite(exists_sub_query)?;

    let mut count_bug_compensation = pull_up
        .collected_count_expr_map
        .get(&new_plan)
        .filter(|m| !m.is_empty())
        .cloned();
    // A HAVING-failure miss looks identical to an absent group once compensated, so bail if the join filter reads the aggregate's own output.
    let reads_agg_output = count_bug_compensation.as_ref().is_some_and(|expr_map| {
        pull_up
            .join_filters
            .iter()
            .flat_map(|f| f.column_refs())
            .any(|c| expr_map.contains_key(&c.name))
    });
    let subquery_cols: BTreeSet<Column> = pull_up
        .correlated_subquery_cols_map
        .values()
        .flatten()
        .cloned()
        .collect();
    let keys_are_bare = count_bug_compensation.is_none()
        || subquery_operands_are_bare_columns(&pull_up.join_filters, &subquery_cols);
    // Fall back to the uncompensated rewrite whenever compensation can't safely apply, so a HAVING never gets silently dropped.
    let compensable = pull_up.can_pull_up
        && !reads_agg_output
        && keys_are_bare
        && (count_bug_compensation.is_some() || pull_up.pull_up_having_expr.is_none());
    if exists_sub_query && !compensable {
        (new_plan, pull_up) = rewrite(false)?;
        count_bug_compensation = None;
    }
    if !pull_up.can_pull_up {
        return Ok(None);
    }
    // TODO(#24960): stopgap until count-bug compensation covers `IN`/`NOT IN`.
    // The subquery stays correlated unless an outer row with no match gets the
    // right answer anyway.
    if !exists_sub_query && pull_up.pulled_up_scalar_agg {
        let null_reads_as_false = match join_type {
            JoinType::LeftSemi => true,
            JoinType::LeftMark => !needs_null_aware_mark,
            _ => false,
        };
        let count_bug_is_harmless = match rewrite(true) {
            Ok((plan, pull_up)) => pull_up
                .collected_count_expr_map
                .get(&plan)
                .filter(|m| !m.is_empty())
                .is_none_or(|empty_input_values| {
                    null_reads_as_false
                        && empty_input_values
                            .get(subquery.schema().field(0).name())
                            .is_some_and(|value| {
                                matches!(value, Expr::Literal(v, _) if v.is_null())
                            })
                }),
            // Count-bug handling errors on some shapes it cannot compensate.
            Err(_) => false,
        };
        if !count_bug_is_harmless {
            return Ok(None);
        }
    }

    let sub_query_alias = LogicalPlanBuilder::from(new_plan)
        .alias(alias.to_string())?
        .build()?;
    let join_filter_opt = build_join_filter(
        pull_up.join_filters,
        pull_up.correlated_subquery_cols_map.values().flatten(),
        alias,
    )?;

    if let Some(expr_map) = count_bug_compensation
        && !expr_map.is_empty()
    {
        return build_join_with_count_bug(
            left,
            sub_query_alias,
            join_filter_opt,
            join_type,
            alias,
            &expr_map,
            pull_up.pull_up_having_expr.as_ref(),
        )
        .map(|plan| {
            Some(BuiltJoin {
                plan,
                mark_is_three_valued_exact: false,
            })
        });
    }

    // The two sides of the `IN` predicate: the value from the outer plan and
    // the subquery output it is compared with, renamed to the alias. A
    // multi-column `(a, b) IN (SELECT x, y ...)` has one pair per tuple
    // element; its `in_predicate` compares the whole tuple with the first
    // subquery output, so each element is paired with its own output here.
    // `EXISTS` has none.
    let in_values = match in_predicate_opt {
        Some(Expr::BinaryExpr(BinaryExpr {
            left,
            op: Operator::Eq,
            right,
        })) => {
            let values = match in_subquery_tuple_values(left, subquery)? {
                Some(values) => values.into_owned(),
                None => vec![left.deref().clone()],
            };
            values
                .into_iter()
                .enumerate()
                .map(|(i, value)| {
                    let output_expr = if i == 0 {
                        right.deref().clone()
                    } else {
                        subquery_output_expr(subquery, i)?
                    };
                    let right_col =
                        create_col_from_scalar_expr(&output_expr, alias.to_string())?;
                    Ok(InValue {
                        value: value.clone(),
                        subquery_column: Expr::Column(right_col),
                        value_as_written: value,
                        output_expr,
                    })
                })
                .collect::<Result<Vec<_>>>()?
        }
        Some(_) => return Ok(None),
        None => vec![],
    };

    // True if an `IN` value or the subquery column it is compared with can be
    // NULL inside the scope of an outer row.
    let mut value_may_be_null = false;
    for in_value in &in_values {
        value_may_be_null |= in_value.may_be_null_in_scope(
            left.schema(),
            sub_query_alias.schema(),
            &pull_up.correlated_filters,
        )?;
    }

    // Whether this join needs null-aware (`NOT IN` three-valued) semantics.
    // Decided once: the constant projection below, the mark branch and the anti
    // branch all depend on the same answer. `NOT EXISTS` is two-valued and has
    // no `IN` value, so it never qualifies.
    //
    // The left projection below only adds a column for a constant value and
    // the right projection only drops unreferenced columns, so neither changes
    // the nullability this looks at.
    let null_aware = value_may_be_null
        && match join_type {
            JoinType::LeftAnti => true,
            JoinType::LeftMark => needs_null_aware_mark,
            _ => false,
        };

    // `<constant> IN/NOT IN (<subquery>)`: the outer value expression holds no
    // column reference, so `<constant> = __correlated_sq.col` is not a valid
    // equi-join key (see `find_valid_equijoin_key_pair`) and stays in the join
    // filter. Two things then go wrong for a null-aware join: the filter is
    // right-only, so `push_down_filter` moves it into the subquery and drops the
    // very NULLs that make `NOT IN` UNKNOWN, and a join without equi-join keys
    // is planned as a nested loop join, which has no null-aware implementation.
    // A correlated subquery hits a third problem: its correlation predicate is a
    // valid equi-join key, so it takes `on[0]`, the position the null-aware hash
    // join reads as the `NOT IN` value key.
    // Projecting the constant as a column of the outer side turns the predicate
    // into a real equi-join key, which fixes all three. It only pays for itself
    // on a join that ends up null-aware.
    //
    // Every constant element of a tuple is projected the same way, so that all
    // value keys lead the equi-join keys in order.
    let mut projected_left = None;
    let mut in_values = in_values;
    if null_aware
        && in_values
            .iter()
            .any(|in_value| in_value.value.column_refs().is_empty())
    {
        let left_schema = left.schema();
        let mut projections = left_schema
            .columns()
            .into_iter()
            .map(Expr::from)
            .collect::<Vec<_>>();
        let is_tuple = in_values.len() > 1;
        for (i, in_value) in in_values.iter_mut().enumerate() {
            if !in_value.value.column_refs().is_empty() {
                continue;
            }
            // The projected column is unqualified, so a left field that already
            // has this name — however unlikely — would make the reference
            // ambiguous.
            let mut value_name = if is_tuple {
                format!("{alias}_value_{i}")
            } else {
                format!("{alias}_value")
            };
            while left_schema.fields().iter().any(|f| f.name() == &value_name) {
                value_name.push('_');
            }
            let value_col = Column::new_unqualified(value_name);
            let constant =
                std::mem::replace(&mut in_value.value, Expr::Column(value_col.clone()));
            projections.push(constant.alias(value_col.name()));
        }
        projected_left = Some(
            LogicalPlanBuilder::from(left.clone())
                .project(projections)?
                .build()?,
        );
    }
    let left = projected_left.as_ref().unwrap_or(left);

    let join_filter = match (in_values.is_empty(), join_filter_opt) {
        (false, correlation_opt) => in_join_filter(&in_values, correlation_opt)?,
        (true, Some(correlation)) => correlation,
        (true, None) => lit(true),
    };

    // Only a null-aware join reads the key order.
    let value_is_first_key = null_aware
        && values_are_first_keys(
            &in_values,
            &join_filter,
            left.schema(),
            sub_query_alias.schema(),
        )?;

    // A multi-column `IN` has no fallback that materializes the UNKNOWN rows
    // (see below), so a tuple element that does not become its key, for
    // example because its type is not hashable, is rejected instead of being
    // read in the wrong key position.
    if null_aware && !value_is_first_key && in_values.len() > 1 {
        return not_impl_err!(
            "Multi-column NOT IN subquery is not supported when a tuple element is not a hashable equi-join key: {join_filter}"
        );
    }
    // The first `V` keys of a null-aware join are its `NOT IN` value keys.
    let null_aware_value_keys = in_values.len().max(1);

    // A `NOT IN` in a filter builds a `LeftAnti` join. The null-aware hash
    // join reads its first key as the `NOT IN` value and the other keys as the
    // scope of the outer row (see `HashJoinExec::null_aware`). If the `IN`
    // equality did not become that first key, give up here. The caller then
    // materializes the UNKNOWN rows with more joins, see
    // `in_subquery_value_mark_join`.
    if join_type == JoinType::LeftAnti && null_aware && !value_is_first_key {
        return Ok(None);
    }

    if matches!(join_type, JoinType::LeftMark | JoinType::RightMark) {
        let right_schema = sub_query_alias.schema();

        // Gather all columns needed for the join filter + predicates
        let mut needed = std::collections::HashSet::new();
        expr_to_columns(&join_filter, &mut needed)?;
        if let Some(in_pred) = in_predicate_opt {
            expr_to_columns(in_pred, &mut needed)?;
        }

        // Keep only columns that actually belong to the RIGHT child, and sort by their
        // position in the right schema for deterministic order.
        let mut right_col_indices: Vec<usize> = needed
            .into_iter()
            .filter_map(|column| right_schema.index_of_column(&column).ok())
            .collect();

        right_col_indices.sort_unstable();
        right_col_indices.dedup();

        let right_proj_exprs: Vec<Expr> = right_col_indices
            .into_iter()
            .map(|index| Expr::Column(Column::from(right_schema.qualified_field(index))))
            .collect();

        let right_projected = if !right_proj_exprs.is_empty() {
            LogicalPlanBuilder::from(sub_query_alias.clone())
                .project(right_proj_exprs)?
                .build()?
        } else {
            // Degenerate case: no right columns referenced by the predicate(s)
            sub_query_alias.clone()
        };

        // For scalar NOT IN mark joins, propagate null-aware semantics into the
        // nullable mark column. A non-equality correlation stays behind as a
        // join filter, which the hash join also applies when it decides
        // whether a NULL makes the mark UNKNOWN.
        let mark_is_three_valued_exact = !in_values.is_empty()
            && (!value_may_be_null || (null_aware && value_is_first_key));

        let new_plan = with_null_aware_value_keys(
            LogicalPlanBuilder::from(left.clone())
                .join_detailed_with_options(
                    right_projected,
                    join_type,
                    (Vec::<Column>::new(), Vec::<Column>::new()),
                    Some(join_filter),
                    NullEquality::NullEqualsNothing,
                    null_aware,
                )?
                .build()?,
            null_aware_value_keys,
        )?;

        debug!(
            "predicate subquery optimized:\n{}",
            new_plan.display_indent()
        );

        return Ok(Some(BuiltJoin {
            plan: new_plan,
            mark_is_three_valued_exact,
        }));
    }

    // join our sub query into the main plan
    let new_plan = if null_aware {
        // Use join_detailed_with_options to set null_aware flag
        with_null_aware_value_keys(
            LogicalPlanBuilder::from(left.clone())
                .join_detailed_with_options(
                    sub_query_alias,
                    join_type,
                    (Vec::<Column>::new(), Vec::<Column>::new()), // No equijoin keys, filter-based join
                    Some(join_filter),
                    NullEquality::NullEqualsNothing,
                    true, // null_aware
                )?
                .build()?,
            null_aware_value_keys,
        )?
    } else {
        LogicalPlanBuilder::from(left.clone())
            .join_on(sub_query_alias, join_type, Some(join_filter))?
            .build()?
    };
    debug!(
        "predicate subquery optimized:\n{}",
        new_plan.display_indent()
    );
    Ok(Some(BuiltJoin {
        plan: new_plan,
        mark_is_three_valued_exact: false,
    }))
}

/// Builds the join for a correlated `EXISTS` subquery whose groupless
/// aggregate requires count-bug compensation.
fn build_join_with_count_bug(
    left: &LogicalPlan,
    sub_query_alias: LogicalPlan,
    join_filter_opt: Option<Expr>,
    join_type: JoinType,
    alias: &str,
    expr_map: &crate::decorrelate::ExprResultMap,
    pull_up_having_expr: Option<&Expr>,
) -> Result<LogicalPlan> {
    let pull_up_having_expr = pull_up_having_expr
        .map(|f| {
            f.clone()
                .transform_up(|e| match e {
                    Expr::Column(c) => Ok(Transformed::yes(Expr::Column(Column::new(
                        Some(alias),
                        c.name,
                    )))),
                    _ => Ok(Transformed::no(e)),
                })
                .data()
        })
        .transpose()?;
    let pull_up_having_expr = pull_up_having_expr.as_ref();

    let joined = LogicalPlanBuilder::from(left.clone())
        .join_on(sub_query_alias, JoinType::Left, join_filter_opt)?
        .build()?;

    let left_projection: Vec<Expr> = left
        .schema()
        .columns()
        .into_iter()
        .map(Expr::from)
        .collect();

    let indicator_col = Expr::Column(Column::new(Some(alias), UN_MATCHED_ROW_INDICATOR));

    let having_arm = pull_up_having_expr.map(|f| f.clone().is_not_true());

    let mut expr_rewrite = TypeCoercionRewriter::new(joined.schema());

    // The subquery's HAVING clause, evaluated against an unmatched row's
    // default aggregate values (e.g. count(*) defaults to 0, sum(x) to
    // NULL), is usually `true`, but not once a second filter is combined
    // into it, so it cannot be assumed.
    let unmatched_having_default = match pull_up_having_expr {
        Some(f) => f
            .clone()
            .transform_up(|e| {
                if let Expr::Column(Column { name, .. }) = &e
                    && let Some(default_value) = expr_map.get(name)
                {
                    return Ok(Transformed::yes(default_value.clone()));
                }
                Ok(Transformed::no(e))
            })
            .data()
            .and_then(|simplified| simplified.rewrite(&mut expr_rewrite).data())?,
        None => lit(true),
    };

    // EXISTS is true by default (the groupless aggregate always
    // produces a row), unless one of three cases holds:
    // (1) the outer row joined against an inner group whose HAVING
    //     predicate failed,
    // (2) an unmatched outer row's own default aggregate values fail
    //     that same HAVING clause.
    let exists_expr = match having_arm {
        Some(when_expr) => when(
            indicator_col.clone().is_null(),
            unmatched_having_default.is_true(),
        )
        .when(when_expr, lit(false))
        .otherwise(lit(true))?
        .rewrite(&mut expr_rewrite)
        .data()?,
        None => lit(true),
    };

    let new_plan = match join_type {
        JoinType::LeftMark | JoinType::RightMark => {
            let mut proj_exprs = left_projection;
            proj_exprs.push(exists_expr.alias_qualified(Some(alias), "mark"));
            LogicalPlanBuilder::from(joined)
                .project(proj_exprs)?
                .build()?
        }
        JoinType::LeftAnti => LogicalPlanBuilder::from(joined)
            .filter(not(exists_expr))?
            .project(left_projection)?
            .build()?,
        JoinType::LeftSemi => LogicalPlanBuilder::from(joined)
            .filter(exists_expr)?
            .project(left_projection)?
            .build()?,
        _ => {
            return internal_err!("unsupported join type {join_type:?}");
        }
    };

    debug!(
        "predicate subquery (count bug) optimized:\n{}",
        new_plan.display_indent()
    );

    Ok(new_plan)
}

#[derive(Debug)]
struct SubqueryInfo {
    query: Subquery,
    where_in_expr: Option<Expr>,
    negated: bool,
}

impl SubqueryInfo {
    pub fn new(query: Subquery, negated: bool) -> Self {
        Self {
            query,
            where_in_expr: None,
            negated,
        }
    }

    pub fn new_with_in_expr(query: Subquery, expr: Expr, negated: bool) -> Self {
        Self {
            query,
            where_in_expr: Some(expr),
            negated,
        }
    }

    pub fn expr(self) -> Expr {
        match self.where_in_expr {
            Some(expr) => match self.negated {
                true => not_in_subquery(expr, self.query.subquery),
                false => in_subquery(expr, self.query.subquery),
            },
            None => match self.negated {
                true => not_exists(self.query.subquery),
                false => exists(self.query.subquery),
            },
        }
    }
}

#[cfg(test)]
mod tests {
    use std::ops::Add;

    use super::*;
    use crate::test::*;

    use crate::assert_optimized_plan_eq_display_indent_snapshot;
    use arrow::datatypes::{DataType, Field, Schema};
    use datafusion_expr::builder::table_source;
    use datafusion_expr::{
        TableScanBuilder, and, binary_expr, col, cube, grouping_set, out_ref_col, rollup,
        table_scan,
    };
    use datafusion_functions_aggregate::count::count_udaf;

    macro_rules! assert_optimized_plan_equal {
        (
            $plan:expr,
            @ $expected:literal $(,)?
        ) => {{
            let rule: Arc<dyn crate::OptimizerRule + Send + Sync> = Arc::new(DecorrelatePredicateSubquery::new());
            assert_optimized_plan_eq_display_indent_snapshot!(
                rule,
                $plan,
                @ $expected,
            )
        }};
    }

    fn test_subquery_with_name(name: &str) -> Result<Arc<LogicalPlan>> {
        let table_scan = test_table_scan_with_name(name)?;
        Ok(Arc::new(
            LogicalPlanBuilder::from(table_scan)
                .project(vec![col("c")])?
                .build()?,
        ))
    }

    fn nullable_scalar_mark_scan(name: &str) -> Result<LogicalPlan> {
        let schema = Schema::new(vec![
            Field::new("id", DataType::Int32, true),
            Field::new("grp", DataType::Int32, true),
        ]);
        table_scan(Some(name), &schema, None)?.build()
    }

    /// `CASE WHEN test.c = 1 THEN NULL ELSE test.c END`: an expression that can
    /// be NULL although `test.c` is not nullable. `NULLIF(c, 1)` and
    /// `TRY_CAST(c AS INT)` have the same shape, but the optimizer crate cannot
    /// depend on the function crates.
    fn nullable_key_expr() -> Result<Expr> {
        when(col("test.c").eq(lit(1u32)), lit(ScalarValue::UInt32(None)))
            .otherwise(col("test.c"))
    }

    fn has_null_aware_left_mark_join(plan: &LogicalPlan) -> bool {
        if let LogicalPlan::Join(join) = plan
            && join.join_type == JoinType::LeftMark
        {
            return join.null_aware;
        }

        plan.inputs().into_iter().any(has_null_aware_left_mark_join)
    }

    fn has_non_null_aware_left_mark_join(plan: &LogicalPlan) -> bool {
        if let LogicalPlan::Join(join) = plan
            && join.join_type == JoinType::LeftMark
        {
            return !join.null_aware;
        }

        plan.inputs()
            .into_iter()
            .any(has_non_null_aware_left_mark_join)
    }

    fn optimize_with_decorrelate(plan: LogicalPlan) -> Result<LogicalPlan> {
        let optimizer = crate::Optimizer::with_rules(vec![Arc::new(
            DecorrelatePredicateSubquery::new(),
        )]);
        optimizer.optimize(plan, &crate::OptimizerContext::new(), |_, _| {})
    }

    /// A grouping set subquery for the tests below: `SELECT c FROM <name> WHERE
    /// c = test.c GROUP BY <group_expr>`.
    fn correlated_grouping_set_subquery(
        name: &str,
        group_expr: Expr,
    ) -> Result<Arc<LogicalPlan>> {
        Ok(Arc::new(
            LogicalPlanBuilder::from(test_table_scan_with_name(name)?)
                .filter(
                    col(format!("{name}.c")).eq(out_ref_col(DataType::UInt32, "test.c")),
                )?
                .aggregate(vec![group_expr], Vec::<Expr>::new())?
                .project(vec![col(format!("{name}.c"))])?
                .build()?,
        ))
    }

    /// `ROLLUP(c)` is `GROUPING SETS ((c), ())`. Adding the correlated column to
    /// every set drops the empty one, so the subquery is left correlated.
    /// <https://github.com/apache/datafusion/issues/25519>
    #[test]
    fn exists_subquery_with_rollup_is_not_decorrelated() -> Result<()> {
        let subquery = correlated_grouping_set_subquery("sq", rollup(vec![col("sq.c")]))?;
        let plan = LogicalPlanBuilder::from(test_table_scan()?)
            .filter(exists(subquery))?
            .project(vec![col("test.b")])?
            .build()?;

        assert_optimized_plan_equal!(
            plan,
            @r"
        Projection: test.b [b:UInt32]
          Filter: EXISTS (<subquery>) [a:UInt32, b:UInt32, c:UInt32]
            Subquery: [c:UInt32;N]
              Projection: sq.c [c:UInt32;N]
                Aggregate: groupBy=[[ROLLUP (sq.c)]], aggr=[[]] [c:UInt32;N, __grouping_id:UInt8]
                  Filter: sq.c = outer_ref(test.c) [a:UInt32, b:UInt32, c:UInt32]
                    TableScan: sq [a:UInt32, b:UInt32, c:UInt32]
            TableScan: test [a:UInt32, b:UInt32, c:UInt32]
        "
        )
    }

    /// `CUBE(c)` holds the empty set for the same reason. The correlation is on
    /// `a` rather than on the `IN` key, so it stays a filter of its own instead
    /// of being folded into the `IN` predicate.
    /// <https://github.com/apache/datafusion/issues/25519>
    #[test]
    fn in_subquery_with_cube_is_not_decorrelated() -> Result<()> {
        let subquery = Arc::new(
            LogicalPlanBuilder::from(test_table_scan_with_name("sq")?)
                .filter(col("sq.a").eq(out_ref_col(DataType::UInt32, "test.a")))?
                .aggregate(vec![cube(vec![col("sq.c")])], Vec::<Expr>::new())?
                .project(vec![col("sq.c")])?
                .build()?,
        );
        let plan = LogicalPlanBuilder::from(test_table_scan()?)
            .filter(in_subquery(col("test.c"), subquery))?
            .project(vec![col("test.b")])?
            .build()?;

        assert_optimized_plan_equal!(
            plan,
            @r"
        Projection: test.b [b:UInt32]
          Filter: test.c IN (<subquery>) [a:UInt32, b:UInt32, c:UInt32]
            Subquery: [c:UInt32;N]
              Projection: sq.c [c:UInt32;N]
                Aggregate: groupBy=[[CUBE (sq.c)]], aggr=[[]] [c:UInt32;N, __grouping_id:UInt8]
                  Filter: sq.a = outer_ref(test.a) [a:UInt32, b:UInt32, c:UInt32]
                    TableScan: sq [a:UInt32, b:UInt32, c:UInt32]
            TableScan: test [a:UInt32, b:UInt32, c:UInt32]
        "
        )
    }

    /// A set that groups by another column does not carry the correlated one.
    /// <https://github.com/apache/datafusion/issues/25519>
    #[test]
    fn exists_subquery_with_partial_grouping_set_is_not_decorrelated() -> Result<()> {
        let subquery = correlated_grouping_set_subquery(
            "sq",
            grouping_set(vec![vec![col("sq.c")], vec![col("sq.b")]]),
        )?;
        let plan = LogicalPlanBuilder::from(test_table_scan()?)
            .filter(exists(subquery))?
            .project(vec![col("test.b")])?
            .build()?;

        assert_optimized_plan_equal!(
            plan,
            @r"
        Projection: test.b [b:UInt32]
          Filter: EXISTS (<subquery>) [a:UInt32, b:UInt32, c:UInt32]
            Subquery: [c:UInt32;N]
              Projection: sq.c [c:UInt32;N]
                Aggregate: groupBy=[[GROUPING SETS ((sq.c), (sq.b))]], aggr=[[]] [c:UInt32;N, b:UInt32;N, __grouping_id:UInt8]
                  Filter: sq.c = outer_ref(test.c) [a:UInt32, b:UInt32, c:UInt32]
                    TableScan: sq [a:UInt32, b:UInt32, c:UInt32]
            TableScan: test [a:UInt32, b:UInt32, c:UInt32]
        "
        )
    }

    /// Every set already groups by the correlated column, so the pull up adds
    /// nothing and the subquery decorrelates as it did before.
    /// <https://github.com/apache/datafusion/issues/25519>
    #[test]
    fn exists_subquery_with_covering_grouping_set_is_decorrelated() -> Result<()> {
        let subquery = correlated_grouping_set_subquery(
            "sq",
            grouping_set(vec![vec![col("sq.c")], vec![col("sq.c"), col("sq.b")]]),
        )?;
        let plan = LogicalPlanBuilder::from(test_table_scan()?)
            .filter(exists(subquery))?
            .project(vec![col("test.b")])?
            .build()?;

        assert_optimized_plan_equal!(
            plan,
            @r"
        Projection: test.b [b:UInt32]
          LeftSemi Join:  Filter: __correlated_sq_1.c = test.c [a:UInt32, b:UInt32, c:UInt32]
            TableScan: test [a:UInt32, b:UInt32, c:UInt32]
            SubqueryAlias: __correlated_sq_1 [c:UInt32;N]
              Projection: sq.c [c:UInt32;N]
                Aggregate: groupBy=[[GROUPING SETS ((sq.c), (sq.c, sq.b))]], aggr=[[]] [c:UInt32;N, b:UInt32;N, __grouping_id:UInt8]
                  TableScan: sq [a:UInt32, b:UInt32, c:UInt32]
        "
        )
    }

    /// Test for several IN subquery expressions
    #[test]
    fn in_subquery_multiple() -> Result<()> {
        let table_scan = test_table_scan()?;
        let plan = LogicalPlanBuilder::from(table_scan)
            .filter(and(
                in_subquery(col("c"), test_subquery_with_name("sq_1")?),
                in_subquery(col("b"), test_subquery_with_name("sq_2")?),
            ))?
            .project(vec![col("test.b")])?
            .build()?;

        assert_optimized_plan_equal!(
            plan,
            @r"
        Projection: test.b [b:UInt32]
          LeftSemi Join:  Filter: test.b = __correlated_sq_2.c [a:UInt32, b:UInt32, c:UInt32]
            LeftSemi Join:  Filter: test.c = __correlated_sq_1.c [a:UInt32, b:UInt32, c:UInt32]
              TableScan: test [a:UInt32, b:UInt32, c:UInt32]
              SubqueryAlias: __correlated_sq_1 [c:UInt32]
                Projection: sq_1.c [c:UInt32]
                  TableScan: sq_1 [a:UInt32, b:UInt32, c:UInt32]
            SubqueryAlias: __correlated_sq_2 [c:UInt32]
              Projection: sq_2.c [c:UInt32]
                TableScan: sq_2 [a:UInt32, b:UInt32, c:UInt32]
        "
        )
    }

    /// Test for IN subquery with additional AND filter
    #[test]
    fn in_subquery_with_and_filters() -> Result<()> {
        let table_scan = test_table_scan()?;
        let plan = LogicalPlanBuilder::from(table_scan)
            .filter(and(
                in_subquery(col("c"), test_subquery_with_name("sq")?),
                and(
                    binary_expr(col("a"), Operator::Eq, lit(1_u32)),
                    binary_expr(col("b"), Operator::Lt, lit(30_u32)),
                ),
            ))?
            .project(vec![col("test.b")])?
            .build()?;

        assert_optimized_plan_equal!(
            plan,
            @r"
        Projection: test.b [b:UInt32]
          Filter: test.a = UInt32(1) AND test.b < UInt32(30) [a:UInt32, b:UInt32, c:UInt32]
            LeftSemi Join:  Filter: test.c = __correlated_sq_1.c [a:UInt32, b:UInt32, c:UInt32]
              TableScan: test [a:UInt32, b:UInt32, c:UInt32]
              SubqueryAlias: __correlated_sq_1 [c:UInt32]
                Projection: sq.c [c:UInt32]
                  TableScan: sq [a:UInt32, b:UInt32, c:UInt32]
        "
        )
    }

    /// Test for nested IN subqueries
    #[test]
    fn in_subquery_nested() -> Result<()> {
        let table_scan = test_table_scan()?;

        let subquery = LogicalPlanBuilder::from(test_table_scan_with_name("sq")?)
            .filter(in_subquery(col("a"), test_subquery_with_name("sq_nested")?))?
            .project(vec![col("a")])?
            .build()?;

        let plan = LogicalPlanBuilder::from(table_scan)
            .filter(in_subquery(col("b"), Arc::new(subquery)))?
            .project(vec![col("test.b")])?
            .build()?;

        assert_optimized_plan_equal!(
            plan,
            @r"
        Projection: test.b [b:UInt32]
          LeftSemi Join:  Filter: test.b = __correlated_sq_2.a [a:UInt32, b:UInt32, c:UInt32]
            TableScan: test [a:UInt32, b:UInt32, c:UInt32]
            SubqueryAlias: __correlated_sq_2 [a:UInt32]
              Projection: sq.a [a:UInt32]
                LeftSemi Join:  Filter: sq.a = __correlated_sq_1.c [a:UInt32, b:UInt32, c:UInt32]
                  TableScan: sq [a:UInt32, b:UInt32, c:UInt32]
                  SubqueryAlias: __correlated_sq_1 [c:UInt32]
                    Projection: sq_nested.c [c:UInt32]
                      TableScan: sq_nested [a:UInt32, b:UInt32, c:UInt32]
        "
        )
    }

    /// Test multiple correlated subqueries
    /// See subqueries.rs where_in_multiple()
    #[test]
    fn multiple_subqueries() -> Result<()> {
        let orders = Arc::new(
            LogicalPlanBuilder::from(scan_tpch_table("orders"))
                .filter(
                    col("orders.o_custkey")
                        .eq(out_ref_col(DataType::Int64, "customer.c_custkey")),
                )?
                .project(vec![col("orders.o_custkey")])?
                .build()?,
        );
        let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
            .filter(
                in_subquery(col("customer.c_custkey"), Arc::clone(&orders))
                    .and(in_subquery(col("customer.c_custkey"), orders)),
            )?
            .project(vec![col("customer.c_custkey")])?
            .build()?;
        debug!("plan to optimize:\n{}", plan.display_indent());

        assert_optimized_plan_equal!(
                plan,
                @r"
        Projection: customer.c_custkey [c_custkey:Int64]
          LeftSemi Join:  Filter: customer.c_custkey = __correlated_sq_2.o_custkey [c_custkey:Int64, c_name:Utf8]
            LeftSemi Join:  Filter: customer.c_custkey = __correlated_sq_1.o_custkey [c_custkey:Int64, c_name:Utf8]
              TableScan: customer [c_custkey:Int64, c_name:Utf8]
              SubqueryAlias: __correlated_sq_1 [o_custkey:Int64]
                Projection: orders.o_custkey [o_custkey:Int64]
                  TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
            SubqueryAlias: __correlated_sq_2 [o_custkey:Int64]
              Projection: orders.o_custkey [o_custkey:Int64]
                TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
        "
        )
    }

    /// Test recursive correlated subqueries
    /// See subqueries.rs where_in_recursive()
    #[test]
    fn recursive_subqueries() -> Result<()> {
        let lineitem = Arc::new(
            LogicalPlanBuilder::from(scan_tpch_table("lineitem"))
                .filter(
                    col("lineitem.l_orderkey")
                        .eq(out_ref_col(DataType::Int64, "orders.o_orderkey")),
                )?
                .project(vec![col("lineitem.l_orderkey")])?
                .build()?,
        );

        let orders = Arc::new(
            LogicalPlanBuilder::from(scan_tpch_table("orders"))
                .filter(
                    in_subquery(col("orders.o_orderkey"), lineitem).and(
                        col("orders.o_custkey")
                            .eq(out_ref_col(DataType::Int64, "customer.c_custkey")),
                    ),
                )?
                .project(vec![col("orders.o_custkey")])?
                .build()?,
        );

        let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
            .filter(in_subquery(col("customer.c_custkey"), orders))?
            .project(vec![col("customer.c_custkey")])?
            .build()?;

        assert_optimized_plan_equal!(
            plan,
            @r"
        Projection: customer.c_custkey [c_custkey:Int64]
          LeftSemi Join:  Filter: customer.c_custkey = __correlated_sq_2.o_custkey [c_custkey:Int64, c_name:Utf8]
            TableScan: customer [c_custkey:Int64, c_name:Utf8]
            SubqueryAlias: __correlated_sq_2 [o_custkey:Int64]
              Projection: orders.o_custkey [o_custkey:Int64]
                LeftSemi Join:  Filter: orders.o_orderkey = __correlated_sq_1.l_orderkey [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
                  TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
                  SubqueryAlias: __correlated_sq_1 [l_orderkey:Int64]
                    Projection: lineitem.l_orderkey [l_orderkey:Int64]
                      TableScan: lineitem [l_orderkey:Int64, l_partkey:Int64, l_suppkey:Int64, l_linenumber:Int32, l_quantity:Float64, l_extendedprice:Float64]
        "
        )
    }

    /// Test for correlated IN subquery filter with additional subquery filters
    #[test]
    fn in_subquery_with_subquery_filters() -> Result<()> {
        let sq = Arc::new(
            LogicalPlanBuilder::from(scan_tpch_table("orders"))
                .filter(
                    out_ref_col(DataType::Int64, "customer.c_custkey")
                        .eq(col("orders.o_custkey"))
                        .and(col("o_orderkey").eq(lit(1))),
                )?
                .project(vec![col("orders.o_custkey")])?
                .build()?,
        );

        let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
            .filter(in_subquery(col("customer.c_custkey"), sq))?
            .project(vec![col("customer.c_custkey")])?
            .build()?;

        assert_optimized_plan_equal!(
            plan,
            @r"
        Projection: customer.c_custkey [c_custkey:Int64]
          LeftSemi Join:  Filter: customer.c_custkey = __correlated_sq_1.o_custkey [c_custkey:Int64, c_name:Utf8]
            TableScan: customer [c_custkey:Int64, c_name:Utf8]
            SubqueryAlias: __correlated_sq_1 [o_custkey:Int64]
              Projection: orders.o_custkey [o_custkey:Int64]
                Filter: orders.o_orderkey = Int32(1) [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
                  TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
        "
        )
    }

    /// Test for correlated IN subquery with no columns in schema
    #[test]
    fn in_subquery_no_cols() -> Result<()> {
        let sq = Arc::new(
            LogicalPlanBuilder::from(scan_tpch_table("orders"))
                .filter(
                    out_ref_col(DataType::Int64, "customer.c_custkey")
                        .eq(out_ref_col(DataType::Int64, "customer.c_custkey")),
                )?
                .project(vec![col("orders.o_custkey")])?
                .build()?,
        );

        let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
            .filter(in_subquery(col("customer.c_custkey"), sq))?
            .project(vec![col("customer.c_custkey")])?
            .build()?;

        assert_optimized_plan_equal!(
            plan,
            @r"
        Projection: customer.c_custkey [c_custkey:Int64]
          LeftSemi Join:  Filter: customer.c_custkey = __correlated_sq_1.o_custkey [c_custkey:Int64, c_name:Utf8]
            TableScan: customer [c_custkey:Int64, c_name:Utf8]
            SubqueryAlias: __correlated_sq_1 [o_custkey:Int64]
              Projection: orders.o_custkey [o_custkey:Int64]
                TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
        "
        )
    }

    /// Test for IN subquery with both columns in schema
    #[test]
    fn in_subquery_with_no_correlated_cols() -> Result<()> {
        let sq = Arc::new(
            LogicalPlanBuilder::from(scan_tpch_table("orders"))
                .filter(col("orders.o_custkey").eq(col("orders.o_custkey")))?
                .project(vec![col("orders.o_custkey")])?
                .build()?,
        );

        let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
            .filter(in_subquery(col("customer.c_custkey"), sq))?
            .project(vec![col("customer.c_custkey")])?
            .build()?;

        assert_optimized_plan_equal!(
            plan,
            @r"
        Projection: customer.c_custkey [c_custkey:Int64]
          LeftSemi Join:  Filter: customer.c_custkey = __correlated_sq_1.o_custkey [c_custkey:Int64, c_name:Utf8]
            TableScan: customer [c_custkey:Int64, c_name:Utf8]
            SubqueryAlias: __correlated_sq_1 [o_custkey:Int64]
              Projection: orders.o_custkey [o_custkey:Int64]
                Filter: orders.o_custkey = orders.o_custkey [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
                  TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
        "
        )
    }

    /// Test for correlated IN subquery not equal
    #[test]
    fn in_subquery_where_not_eq() -> Result<()> {
        let sq = Arc::new(
            LogicalPlanBuilder::from(scan_tpch_table("orders"))
                .filter(
                    out_ref_col(DataType::Int64, "customer.c_custkey")
                        .not_eq(col("orders.o_custkey")),
                )?
                .project(vec![col("orders.o_custkey")])?
                .build()?,
        );

        let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
            .filter(in_subquery(col("customer.c_custkey"), sq))?
            .project(vec![col("customer.c_custkey")])?
            .build()?;

        assert_optimized_plan_equal!(
            plan,
            @r"
        Projection: customer.c_custkey [c_custkey:Int64]
          LeftSemi Join:  Filter: customer.c_custkey = __correlated_sq_1.o_custkey AND customer.c_custkey != __correlated_sq_1.o_custkey [c_custkey:Int64, c_name:Utf8]
            TableScan: customer [c_custkey:Int64, c_name:Utf8]
            SubqueryAlias: __correlated_sq_1 [o_custkey:Int64]
              Projection: orders.o_custkey [o_custkey:Int64]
                TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
        "
        )
    }

    /// Test for correlated IN subquery less than
    #[test]
    fn in_subquery_where_less_than() -> Result<()> {
        let sq = Arc::new(
            LogicalPlanBuilder::from(scan_tpch_table("orders"))
                .filter(
                    out_ref_col(DataType::Int64, "customer.c_custkey")
                        .lt(col("orders.o_custkey")),
                )?
                .project(vec![col("orders.o_custkey")])?
                .build()?,
        );

        let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
            .filter(in_subquery(col("customer.c_custkey"), sq))?
            .project(vec![col("customer.c_custkey")])?
            .build()?;

        assert_optimized_plan_equal!(
            plan,
            @r"
        Projection: customer.c_custkey [c_custkey:Int64]
          LeftSemi Join:  Filter: customer.c_custkey = __correlated_sq_1.o_custkey AND customer.c_custkey < __correlated_sq_1.o_custkey [c_custkey:Int64, c_name:Utf8]
            TableScan: customer [c_custkey:Int64, c_name:Utf8]
            SubqueryAlias: __correlated_sq_1 [o_custkey:Int64]
              Projection: orders.o_custkey [o_custkey:Int64]
                TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
        "
        )
    }

    /// Test for correlated IN subquery filter with subquery disjunction
    #[test]
    fn in_subquery_with_subquery_disjunction() -> Result<()> {
        let sq = Arc::new(
            LogicalPlanBuilder::from(scan_tpch_table("orders"))
                .filter(
                    out_ref_col(DataType::Int64, "customer.c_custkey")
                        .eq(col("orders.o_custkey"))
                        .or(col("o_orderkey").eq(lit(1))),
                )?
                .project(vec![col("orders.o_custkey")])?
                .build()?,
        );

        let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
            .filter(in_subquery(col("customer.c_custkey"), sq))?
            .project(vec![col("customer.c_custkey")])?
            .build()?;

        assert_optimized_plan_equal!(
            plan,
            @"
        Projection: customer.c_custkey [c_custkey:Int64]
          LeftSemi Join:  Filter: customer.c_custkey = __correlated_sq_1.o_custkey AND (customer.c_custkey = __correlated_sq_1.o_custkey OR __correlated_sq_1.o_orderkey = Int32(1)) [c_custkey:Int64, c_name:Utf8]
            TableScan: customer [c_custkey:Int64, c_name:Utf8]
            SubqueryAlias: __correlated_sq_1 [o_custkey:Int64, o_orderkey:Int64]
              Projection: orders.o_custkey, orders.o_orderkey [o_custkey:Int64, o_orderkey:Int64]
                TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
        "
        )
    }

    /// Test for correlated IN without projection
    #[test]
    fn in_subquery_no_projection() -> Result<()> {
        let sq = Arc::new(
            LogicalPlanBuilder::from(scan_tpch_table("orders"))
                .filter(col("customer.c_custkey").eq(col("orders.o_custkey")))?
                .build()?,
        );

        let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
            .filter(in_subquery(col("customer.c_custkey"), sq))?
            .project(vec![col("customer.c_custkey")])?
            .build()?;

        // Maybe okay if the table only has a single column?
        let expected = "Invalid (non-executable) plan after Analyzer\
        \ncaused by\
        \nError during planning: InSubquery should only return one column, but found 4";
        assert_analyzer_check_err(vec![], plan, expected);

        Ok(())
    }

    /// Test for correlated IN subquery join on expression
    #[test]
    fn in_subquery_join_expr() -> Result<()> {
        let sq = Arc::new(
            LogicalPlanBuilder::from(scan_tpch_table("orders"))
                .filter(
                    out_ref_col(DataType::Int64, "customer.c_custkey")
                        .eq(col("orders.o_custkey")),
                )?
                .project(vec![col("orders.o_custkey")])?
                .build()?,
        );

        let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
            .filter(in_subquery(col("customer.c_custkey").add(lit(1)), sq))?
            .project(vec![col("customer.c_custkey")])?
            .build()?;

        assert_optimized_plan_equal!(
            plan,
            @r"
        Projection: customer.c_custkey [c_custkey:Int64]
          LeftSemi Join:  Filter: customer.c_custkey + Int32(1) = __correlated_sq_1.o_custkey AND customer.c_custkey = __correlated_sq_1.o_custkey [c_custkey:Int64, c_name:Utf8]
            TableScan: customer [c_custkey:Int64, c_name:Utf8]
            SubqueryAlias: __correlated_sq_1 [o_custkey:Int64]
              Projection: orders.o_custkey [o_custkey:Int64]
                TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
        "
        )
    }

    /// Test for correlated IN expressions
    #[test]
    fn in_subquery_project_expr() -> Result<()> {
        let sq = Arc::new(
            LogicalPlanBuilder::from(scan_tpch_table("orders"))
                .filter(
                    out_ref_col(DataType::Int64, "customer.c_custkey")
                        .eq(col("orders.o_custkey")),
                )?
                .project(vec![col("orders.o_custkey").add(lit(1))])?
                .build()?,
        );

        let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
            .filter(in_subquery(col("customer.c_custkey"), sq))?
            .project(vec![col("customer.c_custkey")])?
            .build()?;

        assert_optimized_plan_equal!(
            plan,
            @r"
        Projection: customer.c_custkey [c_custkey:Int64]
          LeftSemi Join:  Filter: customer.c_custkey = __correlated_sq_1.orders.o_custkey + Int32(1) AND customer.c_custkey = __correlated_sq_1.o_custkey [c_custkey:Int64, c_name:Utf8]
            TableScan: customer [c_custkey:Int64, c_name:Utf8]
            SubqueryAlias: __correlated_sq_1 [orders.o_custkey + Int32(1):Int64, o_custkey:Int64]
              Projection: orders.o_custkey + Int32(1), orders.o_custkey [orders.o_custkey + Int32(1):Int64, o_custkey:Int64]
                TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
        "
        )
    }

    /// Test for correlated IN subquery multiple projected columns
    #[test]
    fn in_subquery_multi_col() -> Result<()> {
        let sq = Arc::new(
            LogicalPlanBuilder::from(scan_tpch_table("orders"))
                .filter(
                    out_ref_col(DataType::Int64, "customer.c_custkey")
                        .eq(col("orders.o_custkey")),
                )?
                .project(vec![col("orders.o_custkey"), col("orders.o_orderkey")])?
                .build()?,
        );

        let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
            .filter(
                in_subquery(col("customer.c_custkey"), sq)
                    .and(col("c_custkey").eq(lit(1))),
            )?
            .project(vec![col("customer.c_custkey")])?
            .build()?;

        let expected = "Invalid (non-executable) plan after Analyzer\
        \ncaused by\
        \nError during planning: InSubquery should only return one column";
        assert_analyzer_check_err(vec![], plan, expected);

        Ok(())
    }

    /// Test for correlated IN subquery filter with additional filters
    #[test]
    fn should_support_additional_filters() -> Result<()> {
        let sq = Arc::new(
            LogicalPlanBuilder::from(scan_tpch_table("orders"))
                .filter(
                    out_ref_col(DataType::Int64, "customer.c_custkey")
                        .eq(col("orders.o_custkey")),
                )?
                .project(vec![col("orders.o_custkey")])?
                .build()?,
        );

        let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
            .filter(
                in_subquery(col("customer.c_custkey"), sq)
                    .and(col("c_custkey").eq(lit(1))),
            )?
            .project(vec![col("customer.c_custkey")])?
            .build()?;

        assert_optimized_plan_equal!(
            plan,
            @r"
        Projection: customer.c_custkey [c_custkey:Int64]
          Filter: customer.c_custkey = Int32(1) [c_custkey:Int64, c_name:Utf8]
            LeftSemi Join:  Filter: customer.c_custkey = __correlated_sq_1.o_custkey [c_custkey:Int64, c_name:Utf8]
              TableScan: customer [c_custkey:Int64, c_name:Utf8]
              SubqueryAlias: __correlated_sq_1 [o_custkey:Int64]
                Projection: orders.o_custkey [o_custkey:Int64]
                  TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
        "
        )
    }

    /// Test for correlated IN subquery filter
    #[test]
    fn in_subquery_correlated() -> Result<()> {
        let sq = Arc::new(
            LogicalPlanBuilder::from(test_table_scan_with_name("sq")?)
                .filter(out_ref_col(DataType::UInt32, "test.a").eq(col("sq.a")))?
                .project(vec![col("c")])?
                .build()?,
        );

        let plan = LogicalPlanBuilder::from(test_table_scan_with_name("test")?)
            .filter(in_subquery(col("c"), sq))?
            .project(vec![col("test.b")])?
            .build()?;

        assert_optimized_plan_equal!(
            plan,
            @r"
        Projection: test.b [b:UInt32]
          LeftSemi Join:  Filter: test.c = __correlated_sq_1.c AND test.a = __correlated_sq_1.a [a:UInt32, b:UInt32, c:UInt32]
            TableScan: test [a:UInt32, b:UInt32, c:UInt32]
            SubqueryAlias: __correlated_sq_1 [c:UInt32, a:UInt32]
              Projection: sq.c, sq.a [c:UInt32, a:UInt32]
                TableScan: sq [a:UInt32, b:UInt32, c:UInt32]
        "
        )
    }

    /// Test for single IN subquery filter
    #[test]
    fn in_subquery_simple() -> Result<()> {
        let table_scan = test_table_scan()?;
        let plan = LogicalPlanBuilder::from(table_scan)
            .filter(in_subquery(col("c"), test_subquery_with_name("sq")?))?
            .project(vec![col("test.b")])?
            .build()?;

        assert_optimized_plan_equal!(
            plan,
            @r"
        Projection: test.b [b:UInt32]
          LeftSemi Join:  Filter: test.c = __correlated_sq_1.c [a:UInt32, b:UInt32, c:UInt32]
            TableScan: test [a:UInt32, b:UInt32, c:UInt32]
            SubqueryAlias: __correlated_sq_1 [c:UInt32]
              Projection: sq.c [c:UInt32]
                TableScan: sq [a:UInt32, b:UInt32, c:UInt32]
        "
        )
    }

    #[test]
    fn in_subquery_in_projection() -> Result<()> {
        let plan = LogicalPlanBuilder::from(test_table_scan()?)
            .project(vec![
                in_subquery(col("c"), test_subquery_with_name("sq")?).alias("is_present"),
            ])?
            .build()?;

        assert_optimized_plan_equal!(
            plan,
            @r"
        Projection: __correlated_sq_1.mark AS is_present [is_present:Boolean;N]
          LeftMark Join:  Filter: test.c = __correlated_sq_1.c [a:UInt32, b:UInt32, c:UInt32, mark:Boolean;N]
            TableScan: test [a:UInt32, b:UInt32, c:UInt32]
            Projection: __correlated_sq_1.c [c:UInt32]
              SubqueryAlias: __correlated_sq_1 [c:UInt32]
                Projection: sq.c [c:UInt32]
                  TableScan: sq [a:UInt32, b:UInt32, c:UInt32]
        "
        )
    }

    /// A residual non-equality correlation stays on the one mark join. The
    /// null-aware hash join applies it when it decides whether a NULL makes
    /// the mark UNKNOWN, so the mark is still exact.
    #[test]
    fn in_subquery_in_projection_with_residual_filter() -> Result<()> {
        let subquery = Arc::new(
            LogicalPlanBuilder::from(nullable_scalar_mark_scan("inner_t")?)
                .filter(
                    out_ref_col(DataType::Int32, "outer_t.grp").gt(col("inner_t.grp")),
                )?
                .project(vec![col("inner_t.id")])?
                .build()?,
        );

        let plan = LogicalPlanBuilder::from(nullable_scalar_mark_scan("outer_t")?)
            .project(vec![
                in_subquery(col("outer_t.id"), subquery).alias("is_present"),
            ])?
            .build()?;

        assert_optimized_plan_equal!(
            plan,
            @r"
        Projection: __correlated_sq_1.mark AS is_present [is_present:Boolean;N]
          LeftMark Join:  Filter: outer_t.id = __correlated_sq_1.id AND outer_t.grp > __correlated_sq_1.grp null_aware [id:Int32;N, grp:Int32;N, mark:Boolean;N]
            TableScan: outer_t [id:Int32;N, grp:Int32;N]
            Projection: __correlated_sq_1.id, __correlated_sq_1.grp [id:Int32;N, grp:Int32;N]
              SubqueryAlias: __correlated_sq_1 [id:Int32;N, grp:Int32;N]
                Projection: inner_t.id, inner_t.grp [id:Int32;N, grp:Int32;N]
                  TableScan: inner_t [id:Int32;N, grp:Int32;N]
        "
        )
    }

    /// `NOT IN` reads the same mark column, negated. The keys are nullable here,
    /// so the join is null-aware and the mark is NULL for the UNKNOWN rows.
    #[test]
    fn not_in_subquery_in_projection() -> Result<()> {
        let subquery = Arc::new(
            LogicalPlanBuilder::from(nullable_scalar_mark_scan("inner_t")?)
                .project(vec![col("inner_t.id")])?
                .build()?,
        );

        let plan = LogicalPlanBuilder::from(nullable_scalar_mark_scan("outer_t")?)
            .project(vec![
                not_in_subquery(col("outer_t.id"), subquery).alias("is_absent"),
            ])?
            .build()?;

        assert_optimized_plan_equal!(
            plan,
            @r"
        Projection: NOT __correlated_sq_1.mark AS is_absent [is_absent:Boolean;N]
          LeftMark Join:  Filter: outer_t.id = __correlated_sq_1.id null_aware [id:Int32;N, grp:Int32;N, mark:Boolean;N]
            TableScan: outer_t [id:Int32;N, grp:Int32;N]
            Projection: __correlated_sq_1.id [id:Int32;N]
              SubqueryAlias: __correlated_sq_1 [id:Int32;N]
                Projection: inner_t.id [id:Int32;N]
                  TableScan: inner_t [id:Int32;N, grp:Int32;N]
        "
        )
    }

    /// A key expression can be NULL although none of its columns is nullable.
    /// The mark join must then be null-aware, so the mark is NULL for the rows
    /// that give UNKNOWN.
    #[test]
    fn in_subquery_in_projection_with_nullable_key_expr() -> Result<()> {
        let plan = LogicalPlanBuilder::from(test_table_scan()?)
            .project(vec![
                in_subquery(nullable_key_expr()?, test_subquery_with_name("sq")?)
                    .alias("is_present"),
            ])?
            .build()?;

        assert_optimized_plan_equal!(
            plan,
            @r"
        Projection: __correlated_sq_1.mark AS is_present [is_present:Boolean;N]
          LeftMark Join:  Filter: CASE WHEN test.c = UInt32(1) THEN UInt32(NULL) ELSE test.c END = __correlated_sq_1.c null_aware [a:UInt32, b:UInt32, c:UInt32, mark:Boolean;N]
            TableScan: test [a:UInt32, b:UInt32, c:UInt32]
            Projection: __correlated_sq_1.c [c:UInt32]
              SubqueryAlias: __correlated_sq_1 [c:UInt32]
                Projection: sq.c [c:UInt32]
                  TableScan: sq [a:UInt32, b:UInt32, c:UInt32]
        "
        )
    }

    /// The `NOT IN` filter path builds a `LeftAnti` join. It reads the key
    /// nullability the same way, so a nullable key expression over columns that
    /// are not nullable also makes that join null-aware.
    #[test]
    fn not_in_subquery_filter_with_nullable_key_expr() -> Result<()> {
        let plan = LogicalPlanBuilder::from(test_table_scan()?)
            .filter(not_in_subquery(
                nullable_key_expr()?,
                test_subquery_with_name("sq")?,
            ))?
            .project(vec![col("test.b")])?
            .build()?;

        assert_optimized_plan_equal!(
            plan,
            @r"
        Projection: test.b [b:UInt32]
          LeftAnti Join:  Filter: CASE WHEN test.c = UInt32(1) THEN UInt32(NULL) ELSE test.c END = __correlated_sq_1.c null_aware [a:UInt32, b:UInt32, c:UInt32]
            TableScan: test [a:UInt32, b:UInt32, c:UInt32]
            SubqueryAlias: __correlated_sq_1 [c:UInt32]
              Projection: sq.c [c:UInt32]
                TableScan: sq [a:UInt32, b:UInt32, c:UInt32]
        "
        )
    }

    #[test]
    fn unsupported_correlated_in_projection_is_left_unchanged() -> Result<()> {
        let subquery = Arc::new(
            LogicalPlanBuilder::from(scan_tpch_table("orders"))
                .filter(
                    out_ref_col(DataType::Int64, "customer.c_custkey")
                        .eq(col("orders.o_custkey")),
                )?
                .limit(0, Some(1))?
                .project(vec![col("orders.o_custkey")])?
                .build()?,
        );
        let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
            .project(vec![
                in_subquery(col("customer.c_custkey"), subquery).alias("is_present"),
            ])?
            .build()?;

        let result = DecorrelatePredicateSubquery::new()
            .rewrite(plan.clone(), &crate::OptimizerContext::new())?;

        assert!(!result.transformed);
        assert_eq!(result.data, plan);
        Ok(())
    }

    /// Test for single NOT IN subquery filter
    #[test]
    fn not_in_subquery_simple() -> Result<()> {
        let table_scan = test_table_scan()?;
        let plan = LogicalPlanBuilder::from(table_scan)
            .filter(not_in_subquery(col("c"), test_subquery_with_name("sq")?))?
            .project(vec![col("test.b")])?
            .build()?;

        assert_optimized_plan_equal!(
            plan,
            @r"
        Projection: test.b [b:UInt32]
          LeftAnti Join:  Filter: test.c = __correlated_sq_1.c [a:UInt32, b:UInt32, c:UInt32]
            TableScan: test [a:UInt32, b:UInt32, c:UInt32]
            SubqueryAlias: __correlated_sq_1 [c:UInt32]
              Projection: sq.c [c:UInt32]
                TableScan: sq [a:UInt32, b:UInt32, c:UInt32]
        "
        )
    }

    #[test]
    fn wrapped_not_in_subquery() -> Result<()> {
        let table_scan = test_table_scan()?;
        let plan = LogicalPlanBuilder::from(table_scan)
            .filter(not(in_subquery(col("c"), test_subquery_with_name("sq")?)))?
            .project(vec![col("test.b")])?
            .build()?;

        assert_optimized_plan_equal!(
            plan,
            @r"
        Projection: test.b [b:UInt32]
          LeftAnti Join:  Filter: test.c = __correlated_sq_1.c [a:UInt32, b:UInt32, c:UInt32]
            TableScan: test [a:UInt32, b:UInt32, c:UInt32]
            SubqueryAlias: __correlated_sq_1 [c:UInt32]
              Projection: sq.c [c:UInt32]
                TableScan: sq [a:UInt32, b:UInt32, c:UInt32]
        "
        )
    }

    #[test]
    fn wrapped_not_not_in_subquery() -> Result<()> {
        let table_scan = test_table_scan()?;
        let plan = LogicalPlanBuilder::from(table_scan)
            .filter(not(not_in_subquery(
                col("c"),
                test_subquery_with_name("sq")?,
            )))?
            .project(vec![col("test.b")])?
            .build()?;

        assert_optimized_plan_equal!(
            plan,
            @r"
        Projection: test.b [b:UInt32]
          LeftSemi Join:  Filter: test.c = __correlated_sq_1.c [a:UInt32, b:UInt32, c:UInt32]
            TableScan: test [a:UInt32, b:UInt32, c:UInt32]
            SubqueryAlias: __correlated_sq_1 [c:UInt32]
              Projection: sq.c [c:UInt32]
                TableScan: sq [a:UInt32, b:UInt32, c:UInt32]
        "
        )
    }

    /// A constant value expression has no column, so `Int32(3) = inner_t.id`
    /// cannot be an equi-join key on its own. The rule projects the constant as
    /// a column of the outer side; `ExtractEquijoinPredicate` (not run here)
    /// then turns the filter into a real key for the null-aware hash join.
    #[test]
    fn constant_not_in_subquery_projects_value_as_join_key() -> Result<()> {
        let outer_scan = nullable_scalar_mark_scan("outer_t")?;
        let inner_scan = nullable_scalar_mark_scan("inner_t")?;

        let subquery = Arc::new(
            LogicalPlanBuilder::from(inner_scan)
                .project(vec![col("inner_t.id")])?
                .build()?,
        );

        let plan = LogicalPlanBuilder::from(outer_scan)
            .filter(not_in_subquery(lit(3i32), subquery))?
            .build()?;

        assert_optimized_plan_equal!(
            plan,
            @r"
        Projection: outer_t.id, outer_t.grp [id:Int32;N, grp:Int32;N]
          LeftAnti Join:  Filter: __correlated_sq_1_value = __correlated_sq_1.id null_aware [id:Int32;N, grp:Int32;N, __correlated_sq_1_value:Int32]
            Projection: outer_t.id, outer_t.grp, Int32(3) AS __correlated_sq_1_value [id:Int32;N, grp:Int32;N, __correlated_sq_1_value:Int32]
              TableScan: outer_t [id:Int32;N, grp:Int32;N]
            SubqueryAlias: __correlated_sq_1 [id:Int32;N]
              Projection: inner_t.id [id:Int32;N]
                TableScan: inner_t [id:Int32;N, grp:Int32;N]
        "
        )
    }

    /// A NULL constant has no column, but it is still nullable. The join must
    /// be null-aware although the subquery column `sq.c` is not nullable
    /// (<https://github.com/apache/datafusion/issues/25473>).
    #[test]
    fn null_constant_not_in_non_nullable_subquery_is_null_aware() -> Result<()> {
        let plan = LogicalPlanBuilder::from(test_table_scan()?)
            .filter(not_in_subquery(
                lit(ScalarValue::UInt32(None)),
                test_subquery_with_name("sq")?,
            ))?
            .project(vec![col("test.b")])?
            .build()?;

        assert_optimized_plan_equal!(
            plan,
            @r"
        Projection: test.b [b:UInt32]
          Projection: test.a, test.b, test.c [a:UInt32, b:UInt32, c:UInt32]
            LeftAnti Join:  Filter: __correlated_sq_1_value = __correlated_sq_1.c null_aware [a:UInt32, b:UInt32, c:UInt32, __correlated_sq_1_value:UInt32;N]
              Projection: test.a, test.b, test.c, UInt32(NULL) AS __correlated_sq_1_value [a:UInt32, b:UInt32, c:UInt32, __correlated_sq_1_value:UInt32;N]
                TableScan: test [a:UInt32, b:UInt32, c:UInt32]
              SubqueryAlias: __correlated_sq_1 [c:UInt32]
                Projection: sq.c [c:UInt32]
                  TableScan: sq [a:UInt32, b:UInt32, c:UInt32]
        "
        )
    }

    /// `test.c + 1` over a non-nullable `test.c` cannot be NULL, and neither can
    /// `sq.c`, so the anti join stays plain
    /// (<https://github.com/apache/datafusion/issues/25474>).
    #[test]
    fn non_nullable_key_expr_not_in_is_not_null_aware() -> Result<()> {
        let plan = LogicalPlanBuilder::from(test_table_scan()?)
            .filter(not_in_subquery(
                col("test.c") + lit(1u32),
                test_subquery_with_name("sq")?,
            ))?
            .project(vec![col("test.b")])?
            .build()?;

        assert_optimized_plan_equal!(
            plan,
            @r"
        Projection: test.b [b:UInt32]
          LeftAnti Join:  Filter: test.c + UInt32(1) = __correlated_sq_1.c [a:UInt32, b:UInt32, c:UInt32]
            TableScan: test [a:UInt32, b:UInt32, c:UInt32]
            SubqueryAlias: __correlated_sq_1 [c:UInt32]
              Projection: sq.c [c:UInt32]
                TableScan: sq [a:UInt32, b:UInt32, c:UInt32]
        "
        )
    }

    #[test]
    fn correlated_not_in_mark_join_is_null_aware_for_hashable_filter() -> Result<()> {
        let outer_scan = nullable_scalar_mark_scan("outer_t")?;
        let inner_scan = nullable_scalar_mark_scan("inner_t")?;

        let subquery = Arc::new(
            LogicalPlanBuilder::from(inner_scan)
                .filter(
                    out_ref_col(DataType::Int32, "outer_t.grp").eq(col("inner_t.grp")),
                )?
                .project(vec![col("inner_t.id")])?
                .build()?,
        );

        let plan = LogicalPlanBuilder::from(outer_scan)
            .filter(not_in_subquery(col("outer_t.id"), subquery).is_null())?
            .build()?;

        let optimized = optimize_with_decorrelate(plan)?;
        assert!(
            has_null_aware_left_mark_join(&optimized),
            "{}",
            optimized.display_indent_schema()
        );

        Ok(())
    }

    /// A correlation that repeats the `IN` predicate keeps every NULL out of
    /// the subquery result, so the mark join must not be null-aware.
    #[test]
    fn mark_join_for_in_predicate_correlation_is_not_null_aware() -> Result<()> {
        let outer_scan = nullable_scalar_mark_scan("outer_t")?;
        let inner_scan = nullable_scalar_mark_scan("inner_t")?;

        let subquery = Arc::new(
            LogicalPlanBuilder::from(inner_scan)
                .filter(out_ref_col(DataType::Int32, "outer_t.id").eq(col("inner_t.id")))?
                .project(vec![col("inner_t.id")])?
                .build()?,
        );

        let plan = LogicalPlanBuilder::from(outer_scan)
            .filter(in_subquery(col("outer_t.id"), subquery).is_null())?
            .build()?;

        let optimized = optimize_with_decorrelate(plan)?;
        assert!(
            has_non_null_aware_left_mark_join(&optimized),
            "{}",
            optimized.display_indent_schema()
        );

        Ok(())
    }

    /// A grouping set above the correlation puts a NULL back into the key: the
    /// grand-total row of `ROLLUP` is a NULL for every outer row. The
    /// correlation then no longer bounds the subquery result, and the mark
    /// join stays null-aware.
    #[test]
    fn mark_join_for_in_predicate_correlation_below_rollup_is_null_aware() -> Result<()> {
        let subquery = correlated_grouping_set_subquery("sq", rollup(vec![col("sq.c")]))?;
        let plan = LogicalPlanBuilder::from(test_table_scan()?)
            .project(vec![in_subquery(col("test.c"), subquery).alias("m")])?
            .build()?;

        let optimized = optimize_with_decorrelate(plan)?;
        assert!(
            has_null_aware_left_mark_join(&optimized),
            "{}",
            optimized.display_indent_schema()
        );

        Ok(())
    }

    /// The same for the `LeftAnti` join that a `NOT IN` filter builds.
    #[test]
    fn anti_join_for_in_predicate_correlation_is_not_null_aware() -> Result<()> {
        let outer_scan = nullable_scalar_mark_scan("outer_t")?;
        let inner_scan = nullable_scalar_mark_scan("inner_t")?;

        let subquery = Arc::new(
            LogicalPlanBuilder::from(inner_scan)
                .filter(out_ref_col(DataType::Int32, "outer_t.id").eq(col("inner_t.id")))?
                .project(vec![col("inner_t.id")])?
                .build()?,
        );

        let plan = LogicalPlanBuilder::from(outer_scan)
            .filter(not_in_subquery(col("outer_t.id"), subquery))?
            .build()?;

        assert_optimized_plan_equal!(
            plan,
            @r"
        LeftAnti Join:  Filter: outer_t.id = __correlated_sq_1.id [id:Int32;N, grp:Int32;N]
          TableScan: outer_t [id:Int32;N, grp:Int32;N]
          SubqueryAlias: __correlated_sq_1 [id:Int32;N]
            Projection: inner_t.id [id:Int32;N]
              TableScan: inner_t [id:Int32;N, grp:Int32;N]
        "
        )
    }

    #[test]
    fn in_subquery_both_side_expr() -> Result<()> {
        let table_scan = test_table_scan()?;
        let subquery_scan = test_table_scan_with_name("sq")?;

        let subquery = LogicalPlanBuilder::from(subquery_scan)
            .project(vec![col("c") * lit(2u32)])?
            .build()?;

        let plan = LogicalPlanBuilder::from(table_scan)
            .filter(in_subquery(col("c") + lit(1u32), Arc::new(subquery)))?
            .project(vec![col("test.b")])?
            .build()?;

        assert_optimized_plan_equal!(
            plan,
            @r"
        Projection: test.b [b:UInt32]
          LeftSemi Join:  Filter: test.c + UInt32(1) = __correlated_sq_1.sq.c * UInt32(2) [a:UInt32, b:UInt32, c:UInt32]
            TableScan: test [a:UInt32, b:UInt32, c:UInt32]
            SubqueryAlias: __correlated_sq_1 [sq.c * UInt32(2):UInt32]
              Projection: sq.c * UInt32(2) [sq.c * UInt32(2):UInt32]
                TableScan: sq [a:UInt32, b:UInt32, c:UInt32]
        "
        )
    }

    #[test]
    fn in_subquery_join_filter_and_inner_filter() -> Result<()> {
        let table_scan = test_table_scan()?;
        let subquery_scan = test_table_scan_with_name("sq")?;

        let subquery = LogicalPlanBuilder::from(subquery_scan)
            .filter(
                out_ref_col(DataType::UInt32, "test.a")
                    .eq(col("sq.a"))
                    .and(col("sq.a").add(lit(1u32)).eq(col("sq.b"))),
            )?
            .project(vec![col("c") * lit(2u32)])?
            .build()?;

        let plan = LogicalPlanBuilder::from(table_scan)
            .filter(in_subquery(col("c") + lit(1u32), Arc::new(subquery)))?
            .project(vec![col("test.b")])?
            .build()?;

        assert_optimized_plan_equal!(
            plan,
            @r"
        Projection: test.b [b:UInt32]
          LeftSemi Join:  Filter: test.c + UInt32(1) = __correlated_sq_1.sq.c * UInt32(2) AND test.a = __correlated_sq_1.a [a:UInt32, b:UInt32, c:UInt32]
            TableScan: test [a:UInt32, b:UInt32, c:UInt32]
            SubqueryAlias: __correlated_sq_1 [sq.c * UInt32(2):UInt32, a:UInt32]
              Projection: sq.c * UInt32(2), sq.a [sq.c * UInt32(2):UInt32, a:UInt32]
                Filter: sq.a + UInt32(1) = sq.b [a:UInt32, b:UInt32, c:UInt32]
                  TableScan: sq [a:UInt32, b:UInt32, c:UInt32]
        "
        )
    }

    #[test]
    fn in_subquery_multi_project_subquery_cols() -> Result<()> {
        let table_scan = test_table_scan()?;
        let subquery_scan = test_table_scan_with_name("sq")?;

        let subquery = LogicalPlanBuilder::from(subquery_scan)
            .filter(
                out_ref_col(DataType::UInt32, "test.a")
                    .add(out_ref_col(DataType::UInt32, "test.b"))
                    .eq(col("sq.a").add(col("sq.b")))
                    .and(col("sq.a").add(lit(1u32)).eq(col("sq.b"))),
            )?
            .project(vec![col("c") * lit(2u32)])?
            .build()?;

        let plan = LogicalPlanBuilder::from(table_scan)
            .filter(in_subquery(col("c") + lit(1u32), Arc::new(subquery)))?
            .project(vec![col("test.b")])?
            .build()?;

        assert_optimized_plan_equal!(
            plan,
            @r"
        Projection: test.b [b:UInt32]
          LeftSemi Join:  Filter: test.c + UInt32(1) = __correlated_sq_1.sq.c * UInt32(2) AND test.a + test.b = __correlated_sq_1.a + __correlated_sq_1.b [a:UInt32, b:UInt32, c:UInt32]
            TableScan: test [a:UInt32, b:UInt32, c:UInt32]
            SubqueryAlias: __correlated_sq_1 [sq.c * UInt32(2):UInt32, a:UInt32, b:UInt32]
              Projection: sq.c * UInt32(2), sq.a, sq.b [sq.c * UInt32(2):UInt32, a:UInt32, b:UInt32]
                Filter: sq.a + UInt32(1) = sq.b [a:UInt32, b:UInt32, c:UInt32]
                  TableScan: sq [a:UInt32, b:UInt32, c:UInt32]
        "
        )
    }

    #[test]
    fn two_in_subquery_with_outer_filter() -> Result<()> {
        let table_scan = test_table_scan()?;
        let subquery_scan1 = test_table_scan_with_name("sq1")?;
        let subquery_scan2 = test_table_scan_with_name("sq2")?;

        let subquery1 = LogicalPlanBuilder::from(subquery_scan1)
            .filter(out_ref_col(DataType::UInt32, "test.a").gt(col("sq1.a")))?
            .project(vec![col("c") * lit(2u32)])?
            .build()?;

        let subquery2 = LogicalPlanBuilder::from(subquery_scan2)
            .filter(out_ref_col(DataType::UInt32, "test.a").gt(col("sq2.a")))?
            .project(vec![col("c") * lit(2u32)])?
            .build()?;

        let plan = LogicalPlanBuilder::from(table_scan)
            .filter(
                in_subquery(col("c") + lit(1u32), Arc::new(subquery1)).and(
                    in_subquery(col("c") * lit(2u32), Arc::new(subquery2))
                        .and(col("test.c").gt(lit(1u32))),
                ),
            )?
            .project(vec![col("test.b")])?
            .build()?;

        assert_optimized_plan_equal!(
            plan,
            @r"
        Projection: test.b [b:UInt32]
          Filter: test.c > UInt32(1) [a:UInt32, b:UInt32, c:UInt32]
            LeftSemi Join:  Filter: test.c * UInt32(2) = __correlated_sq_2.sq2.c * UInt32(2) AND test.a > __correlated_sq_2.a [a:UInt32, b:UInt32, c:UInt32]
              LeftSemi Join:  Filter: test.c + UInt32(1) = __correlated_sq_1.sq1.c * UInt32(2) AND test.a > __correlated_sq_1.a [a:UInt32, b:UInt32, c:UInt32]
                TableScan: test [a:UInt32, b:UInt32, c:UInt32]
                SubqueryAlias: __correlated_sq_1 [sq1.c * UInt32(2):UInt32, a:UInt32]
                  Projection: sq1.c * UInt32(2), sq1.a [sq1.c * UInt32(2):UInt32, a:UInt32]
                    TableScan: sq1 [a:UInt32, b:UInt32, c:UInt32]
              SubqueryAlias: __correlated_sq_2 [sq2.c * UInt32(2):UInt32, a:UInt32]
                Projection: sq2.c * UInt32(2), sq2.a [sq2.c * UInt32(2):UInt32, a:UInt32]
                  TableScan: sq2 [a:UInt32, b:UInt32, c:UInt32]
        "
        )
    }

    #[test]
    fn in_subquery_with_same_table() -> Result<()> {
        let outer_scan = test_table_scan()?;
        let subquery_scan = test_table_scan()?;
        let subquery = LogicalPlanBuilder::from(subquery_scan)
            .filter(col("test.a").gt(col("test.b")))?
            .project(vec![col("c")])?
            .build()?;

        let plan = LogicalPlanBuilder::from(outer_scan)
            .filter(in_subquery(col("test.a"), Arc::new(subquery)))?
            .project(vec![col("test.b")])?
            .build()?;

        // Subquery and outer query refer to the same table.
        assert_optimized_plan_equal!(
            plan,
            @r"
        Projection: test.b [b:UInt32]
          LeftSemi Join:  Filter: test.a = __correlated_sq_1.c [a:UInt32, b:UInt32, c:UInt32]
            TableScan: test [a:UInt32, b:UInt32, c:UInt32]
            SubqueryAlias: __correlated_sq_1 [c:UInt32]
              Projection: test.c [c:UInt32]
                Filter: test.a > test.b [a:UInt32, b:UInt32, c:UInt32]
                  TableScan: test [a:UInt32, b:UInt32, c:UInt32]
        "
        )
    }

    #[test]
    fn in_subquery_correlated_with_same_table() -> Result<()> {
        let outer_scan = test_table_scan()?;
        let subquery_scan = test_table_scan()?;
        let subquery = LogicalPlanBuilder::from(subquery_scan)
            .filter(out_ref_col(DataType::UInt32, "test.a").gt(col("test.a")))?
            .project(vec![col("c")])?
            .build()?;

        let plan = LogicalPlanBuilder::from(outer_scan)
            .filter(in_subquery(col("test.b"), Arc::new(subquery)))?
            .project(vec![col("test.b")])?
            .build()?;

        // The outer `test.a` and the subquery's `test.a` stay apart in the join filter.
        assert_optimized_plan_equal!(
            plan,
            @r"
        Projection: test.b [b:UInt32]
          LeftSemi Join:  Filter: test.b = __correlated_sq_1.c AND test.a > __correlated_sq_1.a [a:UInt32, b:UInt32, c:UInt32]
            TableScan: test [a:UInt32, b:UInt32, c:UInt32]
            SubqueryAlias: __correlated_sq_1 [c:UInt32, a:UInt32]
              Projection: test.c, test.a [c:UInt32, a:UInt32]
                TableScan: test [a:UInt32, b:UInt32, c:UInt32]
        "
        )
    }

    /// Test for multiple exists subqueries in the same filter expression
    #[test]
    fn multiple_exists_subqueries() -> Result<()> {
        let orders = Arc::new(
            LogicalPlanBuilder::from(scan_tpch_table("orders"))
                .filter(
                    col("orders.o_custkey")
                        .eq(out_ref_col(DataType::Int64, "customer.c_custkey")),
                )?
                .project(vec![col("orders.o_custkey")])?
                .build()?,
        );

        let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
            .filter(exists(Arc::clone(&orders)).and(exists(orders)))?
            .project(vec![col("customer.c_custkey")])?
            .build()?;

        assert_optimized_plan_equal!(
            plan,
            @r"
        Projection: customer.c_custkey [c_custkey:Int64]
          LeftSemi Join:  Filter: __correlated_sq_2.o_custkey = customer.c_custkey [c_custkey:Int64, c_name:Utf8]
            LeftSemi Join:  Filter: __correlated_sq_1.o_custkey = customer.c_custkey [c_custkey:Int64, c_name:Utf8]
              TableScan: customer [c_custkey:Int64, c_name:Utf8]
              SubqueryAlias: __correlated_sq_1 [o_custkey:Int64]
                Projection: orders.o_custkey [o_custkey:Int64]
                  TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
            SubqueryAlias: __correlated_sq_2 [o_custkey:Int64]
              Projection: orders.o_custkey [o_custkey:Int64]
                TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
        "
        )
    }

    /// Test recursive correlated subqueries
    #[test]
    fn recursive_exists_subqueries() -> Result<()> {
        let lineitem = Arc::new(
            LogicalPlanBuilder::from(scan_tpch_table("lineitem"))
                .filter(
                    col("lineitem.l_orderkey")
                        .eq(out_ref_col(DataType::Int64, "orders.o_orderkey")),
                )?
                .project(vec![col("lineitem.l_orderkey")])?
                .build()?,
        );

        let orders = Arc::new(
            LogicalPlanBuilder::from(scan_tpch_table("orders"))
                .filter(
                    exists(lineitem).and(
                        col("orders.o_custkey")
                            .eq(out_ref_col(DataType::Int64, "customer.c_custkey")),
                    ),
                )?
                .project(vec![col("orders.o_custkey")])?
                .build()?,
        );

        let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
            .filter(exists(orders))?
            .project(vec![col("customer.c_custkey")])?
            .build()?;

        assert_optimized_plan_equal!(
            plan,
            @r"
        Projection: customer.c_custkey [c_custkey:Int64]
          LeftSemi Join:  Filter: __correlated_sq_2.o_custkey = customer.c_custkey [c_custkey:Int64, c_name:Utf8]
            TableScan: customer [c_custkey:Int64, c_name:Utf8]
            SubqueryAlias: __correlated_sq_2 [o_custkey:Int64]
              Projection: orders.o_custkey [o_custkey:Int64]
                LeftSemi Join:  Filter: __correlated_sq_1.l_orderkey = orders.o_orderkey [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
                  TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
                  SubqueryAlias: __correlated_sq_1 [l_orderkey:Int64]
                    Projection: lineitem.l_orderkey [l_orderkey:Int64]
                      TableScan: lineitem [l_orderkey:Int64, l_partkey:Int64, l_suppkey:Int64, l_linenumber:Int32, l_quantity:Float64, l_extendedprice:Float64]
        "
        )
    }

    /// Test for correlated exists subquery filter with additional subquery filters
    #[test]
    fn exists_subquery_with_subquery_filters() -> Result<()> {
        let sq = Arc::new(
            LogicalPlanBuilder::from(scan_tpch_table("orders"))
                .filter(
                    out_ref_col(DataType::Int64, "customer.c_custkey")
                        .eq(col("orders.o_custkey"))
                        .and(col("o_orderkey").eq(lit(1))),
                )?
                .project(vec![col("orders.o_custkey")])?
                .build()?,
        );

        let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
            .filter(exists(sq))?
            .project(vec![col("customer.c_custkey")])?
            .build()?;

        assert_optimized_plan_equal!(
            plan,
            @r"
        Projection: customer.c_custkey [c_custkey:Int64]
          LeftSemi Join:  Filter: customer.c_custkey = __correlated_sq_1.o_custkey [c_custkey:Int64, c_name:Utf8]
            TableScan: customer [c_custkey:Int64, c_name:Utf8]
            SubqueryAlias: __correlated_sq_1 [o_custkey:Int64]
              Projection: orders.o_custkey [o_custkey:Int64]
                Filter: orders.o_orderkey = Int32(1) [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
                  TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
        "
        )
    }

    #[test]
    fn exists_subquery_no_cols() -> Result<()> {
        let sq = Arc::new(
            LogicalPlanBuilder::from(scan_tpch_table("orders"))
                .filter(out_ref_col(DataType::Int64, "customer.c_custkey").eq(lit(1u32)))?
                .project(vec![col("orders.o_custkey")])?
                .build()?,
        );

        let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
            .filter(exists(sq))?
            .project(vec![col("customer.c_custkey")])?
            .build()?;

        // Other rule will pushdown `customer.c_custkey = 1`,
        assert_optimized_plan_equal!(
            plan,
            @r"
        Projection: customer.c_custkey [c_custkey:Int64]
          LeftSemi Join:  Filter: customer.c_custkey = UInt32(1) [c_custkey:Int64, c_name:Utf8]
            TableScan: customer [c_custkey:Int64, c_name:Utf8]
            SubqueryAlias: __correlated_sq_1 [o_custkey:Int64]
              Projection: orders.o_custkey [o_custkey:Int64]
                TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
        "
        )
    }

    /// Test for exists subquery with both columns in schema
    #[test]
    fn exists_subquery_with_no_correlated_cols() -> Result<()> {
        let sq = Arc::new(
            LogicalPlanBuilder::from(scan_tpch_table("orders"))
                .filter(col("orders.o_custkey").eq(col("orders.o_custkey")))?
                .project(vec![col("orders.o_custkey")])?
                .build()?,
        );

        let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
            .filter(exists(sq))?
            .project(vec![col("customer.c_custkey")])?
            .build()?;

        assert_optimized_plan_equal!(
            plan,
            @r"
        Projection: customer.c_custkey [c_custkey:Int64]
          LeftSemi Join:  Filter: Boolean(true) [c_custkey:Int64, c_name:Utf8]
            TableScan: customer [c_custkey:Int64, c_name:Utf8]
            SubqueryAlias: __correlated_sq_1 [o_custkey:Int64]
              Projection: orders.o_custkey [o_custkey:Int64]
                Filter: orders.o_custkey = orders.o_custkey [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
                  TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
        "
        )
    }

    /// Test for correlated exists subquery not equal
    #[test]
    fn exists_subquery_where_not_eq() -> Result<()> {
        let sq = Arc::new(
            LogicalPlanBuilder::from(scan_tpch_table("orders"))
                .filter(
                    out_ref_col(DataType::Int64, "customer.c_custkey")
                        .not_eq(col("orders.o_custkey")),
                )?
                .project(vec![col("orders.o_custkey")])?
                .build()?,
        );

        let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
            .filter(exists(sq))?
            .project(vec![col("customer.c_custkey")])?
            .build()?;

        assert_optimized_plan_equal!(
            plan,
            @r"
        Projection: customer.c_custkey [c_custkey:Int64]
          LeftSemi Join:  Filter: customer.c_custkey != __correlated_sq_1.o_custkey [c_custkey:Int64, c_name:Utf8]
            TableScan: customer [c_custkey:Int64, c_name:Utf8]
            SubqueryAlias: __correlated_sq_1 [o_custkey:Int64]
              Projection: orders.o_custkey [o_custkey:Int64]
                TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
        "
        )
    }

    /// Test for correlated exists subquery less than
    #[test]
    fn exists_subquery_where_less_than() -> Result<()> {
        let sq = Arc::new(
            LogicalPlanBuilder::from(scan_tpch_table("orders"))
                .filter(
                    out_ref_col(DataType::Int64, "customer.c_custkey")
                        .lt(col("orders.o_custkey")),
                )?
                .project(vec![col("orders.o_custkey")])?
                .build()?,
        );

        let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
            .filter(exists(sq))?
            .project(vec![col("customer.c_custkey")])?
            .build()?;

        assert_optimized_plan_equal!(
            plan,
            @r"
        Projection: customer.c_custkey [c_custkey:Int64]
          LeftSemi Join:  Filter: customer.c_custkey < __correlated_sq_1.o_custkey [c_custkey:Int64, c_name:Utf8]
            TableScan: customer [c_custkey:Int64, c_name:Utf8]
            SubqueryAlias: __correlated_sq_1 [o_custkey:Int64]
              Projection: orders.o_custkey [o_custkey:Int64]
                TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
        "
        )
    }

    /// Test for correlated exists subquery filter with subquery disjunction
    #[test]
    fn exists_subquery_with_subquery_disjunction() -> Result<()> {
        let sq = Arc::new(
            LogicalPlanBuilder::from(scan_tpch_table("orders"))
                .filter(
                    out_ref_col(DataType::Int64, "customer.c_custkey")
                        .eq(col("orders.o_custkey"))
                        .or(col("o_orderkey").eq(lit(1))),
                )?
                .project(vec![col("orders.o_custkey")])?
                .build()?,
        );

        let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
            .filter(exists(sq))?
            .project(vec![col("customer.c_custkey")])?
            .build()?;

        assert_optimized_plan_equal!(
            plan,
            @"
        Projection: customer.c_custkey [c_custkey:Int64]
          LeftSemi Join:  Filter: customer.c_custkey = __correlated_sq_1.o_custkey OR __correlated_sq_1.o_orderkey = Int32(1) [c_custkey:Int64, c_name:Utf8]
            TableScan: customer [c_custkey:Int64, c_name:Utf8]
            SubqueryAlias: __correlated_sq_1 [o_custkey:Int64, o_orderkey:Int64]
              Projection: orders.o_custkey, orders.o_orderkey [o_custkey:Int64, o_orderkey:Int64]
                TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
        "
        )
    }

    /// Test for correlated exists without projection
    #[test]
    fn exists_subquery_no_projection() -> Result<()> {
        let sq = Arc::new(
            LogicalPlanBuilder::from(scan_tpch_table("orders"))
                .filter(
                    out_ref_col(DataType::Int64, "customer.c_custkey")
                        .eq(col("orders.o_custkey")),
                )?
                .build()?,
        );

        let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
            .filter(exists(sq))?
            .project(vec![col("customer.c_custkey")])?
            .build()?;

        assert_optimized_plan_equal!(
            plan,
            @r"
        Projection: customer.c_custkey [c_custkey:Int64]
          LeftSemi Join:  Filter: customer.c_custkey = __correlated_sq_1.o_custkey [c_custkey:Int64, c_name:Utf8]
            TableScan: customer [c_custkey:Int64, c_name:Utf8]
            SubqueryAlias: __correlated_sq_1 [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
              TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
        "
        )
    }

    /// Test for correlated exists expressions
    #[test]
    fn exists_subquery_project_expr() -> Result<()> {
        let sq = Arc::new(
            LogicalPlanBuilder::from(scan_tpch_table("orders"))
                .filter(
                    out_ref_col(DataType::Int64, "customer.c_custkey")
                        .eq(col("orders.o_custkey")),
                )?
                .project(vec![col("orders.o_custkey").add(lit(1))])?
                .build()?,
        );

        let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
            .filter(exists(sq))?
            .project(vec![col("customer.c_custkey")])?
            .build()?;

        assert_optimized_plan_equal!(
            plan,
            @r"
        Projection: customer.c_custkey [c_custkey:Int64]
          LeftSemi Join:  Filter: customer.c_custkey = __correlated_sq_1.o_custkey [c_custkey:Int64, c_name:Utf8]
            TableScan: customer [c_custkey:Int64, c_name:Utf8]
            SubqueryAlias: __correlated_sq_1 [orders.o_custkey + Int32(1):Int64, o_custkey:Int64]
              Projection: orders.o_custkey + Int32(1), orders.o_custkey [orders.o_custkey + Int32(1):Int64, o_custkey:Int64]
                TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
        "
        )
    }

    /// Test for correlated exists subquery filter with additional filters
    #[test]
    fn exists_subquery_should_support_additional_filters() -> Result<()> {
        let sq = Arc::new(
            LogicalPlanBuilder::from(scan_tpch_table("orders"))
                .filter(
                    out_ref_col(DataType::Int64, "customer.c_custkey")
                        .eq(col("orders.o_custkey")),
                )?
                .project(vec![col("orders.o_custkey")])?
                .build()?,
        );
        let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
            .filter(exists(sq).and(col("c_custkey").eq(lit(1))))?
            .project(vec![col("customer.c_custkey")])?
            .build()?;

        assert_optimized_plan_equal!(
            plan,
            @r"
        Projection: customer.c_custkey [c_custkey:Int64]
          Filter: customer.c_custkey = Int32(1) [c_custkey:Int64, c_name:Utf8]
            LeftSemi Join:  Filter: customer.c_custkey = __correlated_sq_1.o_custkey [c_custkey:Int64, c_name:Utf8]
              TableScan: customer [c_custkey:Int64, c_name:Utf8]
              SubqueryAlias: __correlated_sq_1 [o_custkey:Int64]
                Projection: orders.o_custkey [o_custkey:Int64]
                  TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
        "
        )
    }

    /// Test for correlated exists subquery filter with disjunctions
    #[test]
    fn exists_subquery_disjunction() -> Result<()> {
        let sq = Arc::new(
            LogicalPlanBuilder::from(scan_tpch_table("orders"))
                .filter(col("customer.c_custkey").eq(col("orders.o_custkey")))?
                .project(vec![col("orders.o_custkey")])?
                .build()?,
        );

        let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
            .filter(exists(sq).or(col("customer.c_custkey").eq(lit(1))))?
            .project(vec![col("customer.c_custkey")])?
            .build()?;

        assert_optimized_plan_equal!(
            plan,
            @r"
        Projection: customer.c_custkey [c_custkey:Int64]
          Projection: customer.c_custkey, customer.c_name [c_custkey:Int64, c_name:Utf8]
            Filter: __correlated_sq_1.mark OR customer.c_custkey = Int32(1) [c_custkey:Int64, c_name:Utf8, mark:Boolean;N]
              LeftMark Join:  Filter: Boolean(true) [c_custkey:Int64, c_name:Utf8, mark:Boolean;N]
                TableScan: customer [c_custkey:Int64, c_name:Utf8]
                SubqueryAlias: __correlated_sq_1 [o_custkey:Int64]
                  Projection: orders.o_custkey [o_custkey:Int64]
                    Filter: customer.c_custkey = orders.o_custkey [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
                      TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
        "
        )
    }

    /// Test for correlated exists subquery filter with disjunction and count bug
    #[test]
    fn exists_subquery_disjunction_with_count_bug() -> Result<()> {
        let sq = Arc::new(
            LogicalPlanBuilder::from(test_table_scan_with_name("sq")?)
                .filter(out_ref_col(DataType::UInt32, "test.a").eq(col("sq.a")))?
                .aggregate(Vec::<Expr>::new(), vec![count_udaf().call(vec![])])?
                .build()?,
        );

        let plan = LogicalPlanBuilder::from(test_table_scan()?)
            .filter(exists(sq).or(col("test.c").eq(lit(1))))?
            .project(vec![col("test.b")])?
            .build()?;

        assert_optimized_plan_equal!(
            plan,
            @r"
        Projection: test.b [b:UInt32]
          Projection: test.a, test.b, test.c [a:UInt32, b:UInt32, c:UInt32]
            Filter: __correlated_sq_1.mark OR test.c = Int32(1) [a:UInt32, b:UInt32, c:UInt32, mark:Boolean]
              Projection: test.a, test.b, test.c, Boolean(true) AS mark [a:UInt32, b:UInt32, c:UInt32, mark:Boolean]
                Left Join:  Filter: test.a = __correlated_sq_1.a [a:UInt32, b:UInt32, c:UInt32, a:UInt32;N, __always_true:Boolean;N, count():Int64;N]
                  TableScan: test [a:UInt32, b:UInt32, c:UInt32]
                  SubqueryAlias: __correlated_sq_1 [a:UInt32, __always_true:Boolean, count():Int64]
                    Aggregate: groupBy=[[sq.a, Boolean(true) AS __always_true]], aggr=[[count()]] [a:UInt32, __always_true:Boolean, count():Int64]
                      TableScan: sq [a:UInt32, b:UInt32, c:UInt32]
        "
        )
    }

    /// Test for correlated EXISTS subquery filter
    #[test]
    fn exists_subquery_correlated() -> Result<()> {
        let sq = Arc::new(
            LogicalPlanBuilder::from(test_table_scan_with_name("sq")?)
                .filter(out_ref_col(DataType::UInt32, "test.a").eq(col("sq.a")))?
                .project(vec![col("c")])?
                .build()?,
        );

        let plan = LogicalPlanBuilder::from(test_table_scan_with_name("test")?)
            .filter(exists(sq))?
            .project(vec![col("test.c")])?
            .build()?;

        assert_optimized_plan_equal!(
            plan,
            @r"
        Projection: test.c [c:UInt32]
          LeftSemi Join:  Filter: test.a = __correlated_sq_1.a [a:UInt32, b:UInt32, c:UInt32]
            TableScan: test [a:UInt32, b:UInt32, c:UInt32]
            SubqueryAlias: __correlated_sq_1 [c:UInt32, a:UInt32]
              Projection: sq.c, sq.a [c:UInt32, a:UInt32]
                TableScan: sq [a:UInt32, b:UInt32, c:UInt32]
        "
        )
    }

    /// Test for single exists subquery filter
    #[test]
    fn exists_subquery_simple() -> Result<()> {
        let table_scan = test_table_scan()?;
        let plan = LogicalPlanBuilder::from(table_scan)
            .filter(exists(test_subquery_with_name("sq")?))?
            .project(vec![col("test.b")])?
            .build()?;

        assert_optimized_plan_equal!(
            plan,
            @r"
        Projection: test.b [b:UInt32]
          LeftSemi Join:  Filter: Boolean(true) [a:UInt32, b:UInt32, c:UInt32]
            TableScan: test [a:UInt32, b:UInt32, c:UInt32]
            SubqueryAlias: __correlated_sq_1 [c:UInt32]
              Projection: sq.c [c:UInt32]
                TableScan: sq [a:UInt32, b:UInt32, c:UInt32]
        "
        )
    }

    /// Test for single NOT exists subquery filter
    #[test]
    fn not_exists_subquery_simple() -> Result<()> {
        let table_scan = test_table_scan()?;
        let plan = LogicalPlanBuilder::from(table_scan)
            .filter(not_exists(test_subquery_with_name("sq")?))?
            .project(vec![col("test.b")])?
            .build()?;

        assert_optimized_plan_equal!(
            plan,
            @r"
        Projection: test.b [b:UInt32]
          LeftAnti Join:  Filter: Boolean(true) [a:UInt32, b:UInt32, c:UInt32]
            TableScan: test [a:UInt32, b:UInt32, c:UInt32]
            SubqueryAlias: __correlated_sq_1 [c:UInt32]
              Projection: sq.c [c:UInt32]
                TableScan: sq [a:UInt32, b:UInt32, c:UInt32]
        "
        )
    }

    #[test]
    fn two_exists_subquery_with_outer_filter() -> Result<()> {
        let table_scan = test_table_scan()?;
        let subquery_scan1 = test_table_scan_with_name("sq1")?;
        let subquery_scan2 = test_table_scan_with_name("sq2")?;

        let subquery1 = LogicalPlanBuilder::from(subquery_scan1)
            .filter(out_ref_col(DataType::UInt32, "test.a").eq(col("sq1.a")))?
            .project(vec![col("c")])?
            .build()?;

        let subquery2 = LogicalPlanBuilder::from(subquery_scan2)
            .filter(out_ref_col(DataType::UInt32, "test.a").eq(col("sq2.a")))?
            .project(vec![col("c")])?
            .build()?;

        let plan = LogicalPlanBuilder::from(table_scan)
            .filter(
                exists(Arc::new(subquery1))
                    .and(exists(Arc::new(subquery2)).and(col("test.c").gt(lit(1u32)))),
            )?
            .project(vec![col("test.b")])?
            .build()?;

        assert_optimized_plan_equal!(
            plan,
            @r"
        Projection: test.b [b:UInt32]
          Filter: test.c > UInt32(1) [a:UInt32, b:UInt32, c:UInt32]
            LeftSemi Join:  Filter: test.a = __correlated_sq_2.a [a:UInt32, b:UInt32, c:UInt32]
              LeftSemi Join:  Filter: test.a = __correlated_sq_1.a [a:UInt32, b:UInt32, c:UInt32]
                TableScan: test [a:UInt32, b:UInt32, c:UInt32]
                SubqueryAlias: __correlated_sq_1 [c:UInt32, a:UInt32]
                  Projection: sq1.c, sq1.a [c:UInt32, a:UInt32]
                    TableScan: sq1 [a:UInt32, b:UInt32, c:UInt32]
              SubqueryAlias: __correlated_sq_2 [c:UInt32, a:UInt32]
                Projection: sq2.c, sq2.a [c:UInt32, a:UInt32]
                  TableScan: sq2 [a:UInt32, b:UInt32, c:UInt32]
        "
        )
    }

    #[test]
    fn exists_subquery_expr_filter() -> Result<()> {
        let table_scan = test_table_scan()?;
        let subquery_scan = test_table_scan_with_name("sq")?;
        let subquery = LogicalPlanBuilder::from(subquery_scan)
            .filter(
                (lit(1u32) + col("sq.a"))
                    .gt(out_ref_col(DataType::UInt32, "test.a") * lit(2u32)),
            )?
            .project(vec![lit(1u32)])?
            .build()?;
        let plan = LogicalPlanBuilder::from(table_scan)
            .filter(exists(Arc::new(subquery)))?
            .project(vec![col("test.b")])?
            .build()?;

        assert_optimized_plan_equal!(
            plan,
            @"
        Projection: test.b [b:UInt32]
          LeftSemi Join:  Filter: UInt32(1) + __correlated_sq_1.a > test.a * UInt32(2) [a:UInt32, b:UInt32, c:UInt32]
            TableScan: test [a:UInt32, b:UInt32, c:UInt32]
            SubqueryAlias: __correlated_sq_1 [UInt32(1):UInt32, a:UInt32]
              Projection: UInt32(1), sq.a [UInt32(1):UInt32, a:UInt32]
                TableScan: sq [a:UInt32, b:UInt32, c:UInt32]
        "
        )
    }

    #[test]
    fn exists_subquery_with_same_table() -> Result<()> {
        let outer_scan = test_table_scan()?;
        let subquery_scan = test_table_scan()?;
        let subquery = LogicalPlanBuilder::from(subquery_scan)
            .filter(col("test.a").gt(col("test.b")))?
            .project(vec![col("c")])?
            .build()?;

        let plan = LogicalPlanBuilder::from(outer_scan)
            .filter(exists(Arc::new(subquery)))?
            .project(vec![col("test.b")])?
            .build()?;

        // Subquery and outer query refer to the same table.
        assert_optimized_plan_equal!(
            plan,
            @r"
        Projection: test.b [b:UInt32]
          LeftSemi Join:  Filter: Boolean(true) [a:UInt32, b:UInt32, c:UInt32]
            TableScan: test [a:UInt32, b:UInt32, c:UInt32]
            SubqueryAlias: __correlated_sq_1 [c:UInt32]
              Projection: test.c [c:UInt32]
                Filter: test.a > test.b [a:UInt32, b:UInt32, c:UInt32]
                  TableScan: test [a:UInt32, b:UInt32, c:UInt32]
        "
        )
    }

    #[test]
    fn exists_distinct_subquery() -> Result<()> {
        let table_scan = test_table_scan()?;
        let subquery_scan = test_table_scan_with_name("sq")?;
        let subquery = LogicalPlanBuilder::from(subquery_scan)
            .filter(
                (lit(1u32) + col("sq.a"))
                    .gt(out_ref_col(DataType::UInt32, "test.a") * lit(2u32)),
            )?
            .project(vec![col("sq.c")])?
            .distinct()?
            .build()?;
        let plan = LogicalPlanBuilder::from(table_scan)
            .filter(exists(Arc::new(subquery)))?
            .project(vec![col("test.b")])?
            .build()?;

        assert_optimized_plan_equal!(
            plan,
            @"
        Projection: test.b [b:UInt32]
          LeftSemi Join:  Filter: UInt32(1) + __correlated_sq_1.a > test.a * UInt32(2) [a:UInt32, b:UInt32, c:UInt32]
            TableScan: test [a:UInt32, b:UInt32, c:UInt32]
            SubqueryAlias: __correlated_sq_1 [c:UInt32, a:UInt32]
              Distinct: [c:UInt32, a:UInt32]
                Projection: sq.c, sq.a [c:UInt32, a:UInt32]
                  TableScan: sq [a:UInt32, b:UInt32, c:UInt32]
        "
        )
    }

    #[test]
    fn exists_distinct_expr_subquery() -> Result<()> {
        let table_scan = test_table_scan()?;
        let subquery_scan = test_table_scan_with_name("sq")?;
        let subquery = LogicalPlanBuilder::from(subquery_scan)
            .filter(
                (lit(1u32) + col("sq.a"))
                    .gt(out_ref_col(DataType::UInt32, "test.a") * lit(2u32)),
            )?
            .project(vec![col("sq.b") + col("sq.c")])?
            .distinct()?
            .build()?;
        let plan = LogicalPlanBuilder::from(table_scan)
            .filter(exists(Arc::new(subquery)))?
            .project(vec![col("test.b")])?
            .build()?;

        assert_optimized_plan_equal!(
            plan,
            @"
        Projection: test.b [b:UInt32]
          LeftSemi Join:  Filter: UInt32(1) + __correlated_sq_1.a > test.a * UInt32(2) [a:UInt32, b:UInt32, c:UInt32]
            TableScan: test [a:UInt32, b:UInt32, c:UInt32]
            SubqueryAlias: __correlated_sq_1 [sq.b + sq.c:UInt32, a:UInt32]
              Distinct: [sq.b + sq.c:UInt32, a:UInt32]
                Projection: sq.b + sq.c, sq.a [sq.b + sq.c:UInt32, a:UInt32]
                  TableScan: sq [a:UInt32, b:UInt32, c:UInt32]
        "
        )
    }

    #[test]
    fn exists_distinct_subquery_with_literal() -> Result<()> {
        let table_scan = test_table_scan()?;
        let subquery_scan = test_table_scan_with_name("sq")?;
        let subquery = LogicalPlanBuilder::from(subquery_scan)
            .filter(
                (lit(1u32) + col("sq.a"))
                    .gt(out_ref_col(DataType::UInt32, "test.a") * lit(2u32)),
            )?
            .project(vec![lit(1u32), col("sq.c")])?
            .distinct()?
            .build()?;
        let plan = LogicalPlanBuilder::from(table_scan)
            .filter(exists(Arc::new(subquery)))?
            .project(vec![col("test.b")])?
            .build()?;

        assert_optimized_plan_equal!(
            plan,
            @"
        Projection: test.b [b:UInt32]
          LeftSemi Join:  Filter: UInt32(1) + __correlated_sq_1.a > test.a * UInt32(2) [a:UInt32, b:UInt32, c:UInt32]
            TableScan: test [a:UInt32, b:UInt32, c:UInt32]
            SubqueryAlias: __correlated_sq_1 [UInt32(1):UInt32, c:UInt32, a:UInt32]
              Distinct: [UInt32(1):UInt32, c:UInt32, a:UInt32]
                Projection: UInt32(1), sq.c, sq.a [UInt32(1):UInt32, c:UInt32, a:UInt32]
                  TableScan: sq [a:UInt32, b:UInt32, c:UInt32]
        "
        )
    }

    #[test]
    fn exists_uncorrelated_unnest() -> Result<()> {
        let subquery_table_source = table_source(&Schema::new(vec![Field::new(
            "arr",
            DataType::List(Arc::new(Field::new_list_field(DataType::Int32, true))),
            true,
        )]));
        let subquery_table_scan =
            TableScanBuilder::new("sq", subquery_table_source).build()?;
        let subquery = LogicalPlanBuilder::table_scan(subquery_table_scan)?
            .unnest_column("arr")?
            .build()?;
        let table_scan = test_table_scan()?;
        let plan = LogicalPlanBuilder::from(table_scan)
            .filter(exists(Arc::new(subquery)))?
            .project(vec![col("test.b")])?
            .build()?;

        assert_optimized_plan_equal!(
            plan,
            @r"
        Projection: test.b [b:UInt32]
          LeftSemi Join:  Filter: Boolean(true) [a:UInt32, b:UInt32, c:UInt32]
            TableScan: test [a:UInt32, b:UInt32, c:UInt32]
            SubqueryAlias: __correlated_sq_1 [arr:Int32;N]
              Unnest: lists[sq.arr|depth=1] structs[] [arr:Int32;N]
                TableScan: sq [arr:List(Int32);N]
        "
        )
    }

    #[test]
    fn exists_correlated_unnest() -> Result<()> {
        let table_scan = test_table_scan()?;
        let subquery_table_source = table_source(&Schema::new(vec![Field::new(
            "a",
            DataType::List(Arc::new(Field::new_list_field(DataType::UInt32, true))),
            true,
        )]));
        let subquery_table_scan =
            TableScanBuilder::new("sq", subquery_table_source).build()?;
        let subquery = LogicalPlanBuilder::table_scan(subquery_table_scan)?
            .unnest_column("a")?
            .filter(col("a").eq(out_ref_col(DataType::UInt32, "test.b")))?
            .build()?;
        let plan = LogicalPlanBuilder::from(table_scan)
            .filter(exists(Arc::new(subquery)))?
            .project(vec![col("test.b")])?
            .build()?;

        assert_optimized_plan_equal!(
            plan,
            @r"
        Projection: test.b [b:UInt32]
          LeftSemi Join:  Filter: __correlated_sq_1.a = test.b [a:UInt32, b:UInt32, c:UInt32]
            TableScan: test [a:UInt32, b:UInt32, c:UInt32]
            SubqueryAlias: __correlated_sq_1 [a:UInt32;N]
              Unnest: lists[sq.a|depth=1] structs[] [a:UInt32;N]
                TableScan: sq [a:List(UInt32);N]
        "
        )
    }

    #[test]
    fn upper_case_ident() -> Result<()> {
        let fields = vec![
            Field::new("A", DataType::UInt32, false),
            Field::new("B", DataType::UInt32, false),
        ];

        let schema = Schema::new(fields);
        let table_scan_a = table_scan(Some("\"TEST_A\""), &schema, None)?.build()?;
        let table_scan_b = table_scan(Some("\"TEST_B\""), &schema, None)?.build()?;

        let subquery = LogicalPlanBuilder::from(table_scan_b)
            .filter(col("\"A\"").eq(out_ref_col(DataType::UInt32, "\"TEST_A\".\"A\"")))?
            .project(vec![lit(1)])?
            .build()?;

        let plan = LogicalPlanBuilder::from(table_scan_a)
            .filter(exists(Arc::new(subquery)))?
            .project(vec![col("\"TEST_A\".\"B\"")])?
            .build()?;

        assert_optimized_plan_equal!(
            plan,
            @r"
        Projection: TEST_A.B [B:UInt32]
          LeftSemi Join:  Filter: __correlated_sq_1.A = TEST_A.A [A:UInt32, B:UInt32]
            TableScan: TEST_A [A:UInt32, B:UInt32]
            SubqueryAlias: __correlated_sq_1 [Int32(1):Int32, A:UInt32]
              Projection: Int32(1), TEST_B.A [Int32(1):Int32, A:UInt32]
                TableScan: TEST_B [A:UInt32, B:UInt32]
        "
        )
    }

    /// An Unnest replaces the column it unnests with the values of that
    /// column. A correlated filter on that column below the Unnest compares
    /// the whole list, so it cannot move above the Unnest.
    #[test]
    fn exists_subquery_filter_on_unnested_column() -> Result<()> {
        let list_type =
            DataType::List(Arc::new(Field::new_list_field(DataType::Int32, true)));
        let schema = Schema::new(vec![
            Field::new("id", DataType::Int32, true),
            Field::new("arr", list_type.clone(), true),
        ]);
        let subquery = Arc::new(
            table_scan(Some("sq"), &schema, None)?
                .filter(col("sq.arr").eq(out_ref_col(list_type, "outer_t.arr")))?
                .unnest_column("arr")?
                .project(vec![col("sq.id")])?
                .build()?,
        );
        let plan = table_scan(Some("outer_t"), &schema, None)?
            .filter(exists(subquery))?
            .project(vec![col("outer_t.id")])?
            .build()?;

        assert_optimized_plan_equal!(
            plan,
            @r"
        Projection: outer_t.id [id:Int32;N]
          Filter: EXISTS (<subquery>) [id:Int32;N, arr:List(Int32);N]
            Subquery: [id:Int32;N]
              Projection: sq.id [id:Int32;N]
                Unnest: lists[sq.arr|depth=1] structs[] [id:Int32;N, arr:Int32;N]
                  Filter: sq.arr = outer_ref(outer_t.arr) [id:Int32;N, arr:List(Int32);N]
                    TableScan: sq [id:Int32;N, arr:List(Int32);N]
            TableScan: outer_t [id:Int32;N, arr:List(Int32);N]
        "
        )
    }

    #[test]
    fn exists_subquery_filter_above_correlated_derived_table() -> Result<()> {
        let sq_scan = test_table_scan_with_name("sq")?;
        let derived = LogicalPlanBuilder::from(sq_scan)
            .filter(col("sq.c").eq(out_ref_col(DataType::UInt32, "test.a")))?
            .project(vec![col("sq.c")])?
            .alias("t")?
            .build()?;
        let subquery = LogicalPlanBuilder::from(derived)
            .filter(out_ref_col(DataType::UInt32, "test.b").gt(lit(0u32)))?
            .project(vec![lit(1)])?
            .build()?;

        let outer_scan = test_table_scan()?;
        let plan = LogicalPlanBuilder::from(outer_scan)
            .filter(exists(Arc::new(subquery)))?
            .project(vec![col("test.a")])?
            .build()?;

        assert_optimized_plan_equal!(
            plan,
            @r"
        Projection: test.a [a:UInt32]
          LeftSemi Join:  Filter: __correlated_sq_1.c = test.a AND test.b > UInt32(0) [a:UInt32, b:UInt32, c:UInt32]
            TableScan: test [a:UInt32, b:UInt32, c:UInt32]
            SubqueryAlias: __correlated_sq_1 [Int32(1):Int32, c:UInt32]
              Projection: Int32(1), t.c [Int32(1):Int32, c:UInt32]
                SubqueryAlias: t [c:UInt32]
                  Projection: sq.c [c:UInt32]
                    TableScan: sq [a:UInt32, b:UInt32, c:UInt32]
        "
        )
    }
}