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
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//! Expression simplification API
use std::ops::Not;
use super::or_in_list_simplifier::OrInListSimplifier;
use super::utils::*;
use crate::analyzer::type_coercion::TypeCoercionRewriter;
use crate::simplify_expressions::regex::simplify_regex_expr;
use arrow::{
array::new_null_array,
datatypes::{DataType, Field, Schema},
error::ArrowError,
record_batch::RecordBatch,
};
use datafusion_common::tree_node::{RewriteRecursion, TreeNode, TreeNodeRewriter};
use datafusion_common::{
exec_err, internal_err, DFSchema, DFSchemaRef, DataFusionError, Result, ScalarValue,
};
use datafusion_expr::expr::{InList, InSubquery, ScalarFunction};
use datafusion_expr::{
and, expr, lit, or, BinaryExpr, BuiltinScalarFunction, Case, ColumnarValue, Expr,
Like, Volatility,
};
use datafusion_physical_expr::{create_physical_expr, execution_props::ExecutionProps};
use crate::simplify_expressions::SimplifyInfo;
/// This structure handles API for expression simplification
pub struct ExprSimplifier<S> {
info: S,
}
pub const THRESHOLD_INLINE_INLIST: usize = 3;
impl<S: SimplifyInfo> ExprSimplifier<S> {
/// Create a new `ExprSimplifier` with the given `info` such as an
/// instance of [`SimplifyContext`]. See
/// [`simplify`](Self::simplify) for an example.
///
/// [`SimplifyContext`]: crate::simplify_expressions::context::SimplifyContext
pub fn new(info: S) -> Self {
Self { info }
}
/// Simplifies this [`Expr`]`s as much as possible, evaluating
/// constants and applying algebraic simplifications.
///
/// The types of the expression must match what operators expect,
/// or else an error may occur trying to evaluate. See
/// [`coerce`](Self::coerce) for a function to help.
///
/// # Example:
///
/// `b > 2 AND b > 2`
///
/// can be written to
///
/// `b > 2`
///
/// ```
/// use arrow::datatypes::DataType;
/// use datafusion_expr::{col, lit, Expr};
/// use datafusion_common::Result;
/// use datafusion_physical_expr::execution_props::ExecutionProps;
/// use datafusion_optimizer::simplify_expressions::{ExprSimplifier, SimplifyInfo};
///
/// /// Simple implementation that provides `Simplifier` the information it needs
/// /// See SimplifyContext for a structure that does this.
/// #[derive(Default)]
/// struct Info {
/// execution_props: ExecutionProps,
/// };
///
/// impl SimplifyInfo for Info {
/// fn is_boolean_type(&self, expr: &Expr) -> Result<bool> {
/// Ok(false)
/// }
/// fn nullable(&self, expr: &Expr) -> Result<bool> {
/// Ok(true)
/// }
/// fn execution_props(&self) -> &ExecutionProps {
/// &self.execution_props
/// }
/// fn get_data_type(&self, expr: &Expr) -> Result<DataType> {
/// Ok(DataType::Int32)
/// }
/// }
///
/// // Create the simplifier
/// let simplifier = ExprSimplifier::new(Info::default());
///
/// // b < 2
/// let b_lt_2 = col("b").gt(lit(2));
///
/// // (b < 2) OR (b < 2)
/// let expr = b_lt_2.clone().or(b_lt_2.clone());
///
/// // (b < 2) OR (b < 2) --> (b < 2)
/// let expr = simplifier.simplify(expr).unwrap();
/// assert_eq!(expr, b_lt_2);
/// ```
pub fn simplify(&self, expr: Expr) -> Result<Expr> {
let mut simplifier = Simplifier::new(&self.info);
let mut const_evaluator = ConstEvaluator::try_new(self.info.execution_props())?;
let mut or_in_list_simplifier = OrInListSimplifier::new();
// TODO iterate until no changes are made during rewrite
// (evaluating constants can enable new simplifications and
// simplifications can enable new constant evaluation)
// https://github.com/apache/arrow-datafusion/issues/1160
expr.rewrite(&mut const_evaluator)?
.rewrite(&mut simplifier)?
.rewrite(&mut or_in_list_simplifier)?
// run both passes twice to try an minimize simplifications that we missed
.rewrite(&mut const_evaluator)?
.rewrite(&mut simplifier)
}
/// Apply type coercion to an [`Expr`] so that it can be
/// evaluated as a [`PhysicalExpr`](datafusion_physical_expr::PhysicalExpr).
///
/// See the [type coercion module](datafusion_expr::type_coercion)
/// documentation for more details on type coercion
///
// Would be nice if this API could use the SimplifyInfo
// rather than creating an DFSchemaRef coerces rather than doing
// it manually.
// https://github.com/apache/arrow-datafusion/issues/3793
pub fn coerce(&self, expr: Expr, schema: DFSchemaRef) -> Result<Expr> {
let mut expr_rewrite = TypeCoercionRewriter { schema };
expr.rewrite(&mut expr_rewrite)
}
}
#[allow(rustdoc::private_intra_doc_links)]
/// Partially evaluate `Expr`s so constant subtrees are evaluated at plan time.
///
/// Note it does not handle algebraic rewrites such as `(a or false)`
/// --> `a`, which is handled by [`Simplifier`]
struct ConstEvaluator<'a> {
/// `can_evaluate` is used during the depth-first-search of the
/// `Expr` tree to track if any siblings (or their descendants) were
/// non evaluatable (e.g. had a column reference or volatile
/// function)
///
/// Specifically, `can_evaluate[N]` represents the state of
/// traversal when we are N levels deep in the tree, one entry for
/// this Expr and each of its parents.
///
/// After visiting all siblings if `can_evaluate.top()` is true, that
/// means there were no non evaluatable siblings (or their
/// descendants) so this `Expr` can be evaluated
can_evaluate: Vec<bool>,
execution_props: &'a ExecutionProps,
input_schema: DFSchema,
input_batch: RecordBatch,
}
impl<'a> TreeNodeRewriter for ConstEvaluator<'a> {
type N = Expr;
fn pre_visit(&mut self, expr: &Expr) -> Result<RewriteRecursion> {
// Default to being able to evaluate this node
self.can_evaluate.push(true);
// if this expr is not ok to evaluate, mark entire parent
// stack as not ok (as all parents have at least one child or
// descendant that can not be evaluated
if !Self::can_evaluate(expr) {
// walk back up stack, marking first parent that is not mutable
let parent_iter = self.can_evaluate.iter_mut().rev();
for p in parent_iter {
if !*p {
// optimization: if we find an element on the
// stack already marked, know all elements above are also marked
break;
}
*p = false;
}
}
// NB: do not short circuit recursion even if we find a non
// evaluatable node (so we can fold other children, args to
// functions, etc)
Ok(RewriteRecursion::Continue)
}
fn mutate(&mut self, expr: Expr) -> Result<Expr> {
match self.can_evaluate.pop() {
Some(true) => Ok(Expr::Literal(self.evaluate_to_scalar(expr)?)),
Some(false) => Ok(expr),
_ => internal_err!("Failed to pop can_evaluate"),
}
}
}
impl<'a> ConstEvaluator<'a> {
/// Create a new `ConstantEvaluator`. Session constants (such as
/// the time for `now()` are taken from the passed
/// `execution_props`.
pub fn try_new(execution_props: &'a ExecutionProps) -> Result<Self> {
// The dummy column name is unused and doesn't matter as only
// expressions without column references can be evaluated
static DUMMY_COL_NAME: &str = ".";
let schema = Schema::new(vec![Field::new(DUMMY_COL_NAME, DataType::Null, true)]);
let input_schema = DFSchema::try_from(schema.clone())?;
// Need a single "input" row to produce a single output row
let col = new_null_array(&DataType::Null, 1);
let input_batch = RecordBatch::try_new(std::sync::Arc::new(schema), vec![col])?;
Ok(Self {
can_evaluate: vec![],
execution_props,
input_schema,
input_batch,
})
}
/// Can a function of the specified volatility be evaluated?
fn volatility_ok(volatility: Volatility) -> bool {
match volatility {
Volatility::Immutable => true,
// Values for functions such as now() are taken from ExecutionProps
Volatility::Stable => true,
Volatility::Volatile => false,
}
}
/// Can the expression be evaluated at plan time, (assuming all of
/// its children can also be evaluated)?
fn can_evaluate(expr: &Expr) -> bool {
// check for reasons we can't evaluate this node
//
// NOTE all expr types are listed here so when new ones are
// added they can be checked for their ability to be evaluated
// at plan time
match expr {
// Has no runtime cost, but needed during planning
Expr::Alias(..)
| Expr::AggregateFunction { .. }
| Expr::AggregateUDF { .. }
| Expr::ScalarVariable(_, _)
| Expr::Column(_)
| Expr::OuterReferenceColumn(_, _)
| Expr::Exists { .. }
| Expr::InSubquery(_)
| Expr::ScalarSubquery(_)
| Expr::WindowFunction { .. }
| Expr::Sort { .. }
| Expr::GroupingSet(_)
| Expr::Wildcard
| Expr::QualifiedWildcard { .. }
| Expr::Placeholder(_) => false,
Expr::ScalarFunction(ScalarFunction { fun, .. }) => {
Self::volatility_ok(fun.volatility())
}
Expr::ScalarUDF(expr::ScalarUDF { fun, .. }) => {
Self::volatility_ok(fun.signature.volatility)
}
Expr::Literal(_)
| Expr::BinaryExpr { .. }
| Expr::Not(_)
| Expr::IsNotNull(_)
| Expr::IsNull(_)
| Expr::IsTrue(_)
| Expr::IsFalse(_)
| Expr::IsUnknown(_)
| Expr::IsNotTrue(_)
| Expr::IsNotFalse(_)
| Expr::IsNotUnknown(_)
| Expr::Negative(_)
| Expr::Between { .. }
| Expr::Like { .. }
| Expr::SimilarTo { .. }
| Expr::Case(_)
| Expr::Cast { .. }
| Expr::TryCast { .. }
| Expr::InList { .. }
| Expr::GetIndexedField { .. } => true,
}
}
/// Internal helper to evaluates an Expr
pub(crate) fn evaluate_to_scalar(&mut self, expr: Expr) -> Result<ScalarValue> {
if let Expr::Literal(s) = expr {
return Ok(s);
}
let phys_expr = create_physical_expr(
&expr,
&self.input_schema,
&self.input_batch.schema(),
self.execution_props,
)?;
let col_val = phys_expr.evaluate(&self.input_batch)?;
match col_val {
ColumnarValue::Array(a) => {
if a.len() != 1 {
exec_err!(
"Could not evaluate the expression, found a result of length {}",
a.len()
)
} else {
Ok(ScalarValue::try_from_array(&a, 0)?)
}
}
ColumnarValue::Scalar(s) => Ok(s),
}
}
}
/// Simplifies [`Expr`]s by applying algebraic transformation rules
///
/// Example transformations that are applied:
/// * `expr = true` and `expr != false` to `expr` when `expr` is of boolean type
/// * `expr = false` and `expr != true` to `!expr` when `expr` is of boolean type
/// * `true = true` and `false = false` to `true`
/// * `false = true` and `true = false` to `false`
/// * `!!expr` to `expr`
/// * `expr = null` and `expr != null` to `null`
struct Simplifier<'a, S> {
info: &'a S,
}
impl<'a, S> Simplifier<'a, S> {
pub fn new(info: &'a S) -> Self {
Self { info }
}
}
impl<'a, S: SimplifyInfo> TreeNodeRewriter for Simplifier<'a, S> {
type N = Expr;
/// rewrite the expression simplifying any constant expressions
fn mutate(&mut self, expr: Expr) -> Result<Expr> {
use datafusion_expr::Operator::{
And, BitwiseAnd, BitwiseOr, BitwiseShiftLeft, BitwiseShiftRight, BitwiseXor,
Divide, Eq, Modulo, Multiply, NotEq, Or, RegexIMatch, RegexMatch,
RegexNotIMatch, RegexNotMatch,
};
let info = self.info;
let new_expr = match expr {
//
// Rules for Eq
//
// true = A --> A
// false = A --> !A
// null = A --> null
Expr::BinaryExpr(BinaryExpr {
left,
op: Eq,
right,
}) if is_bool_lit(&left) && info.is_boolean_type(&right)? => {
match as_bool_lit(*left)? {
Some(true) => *right,
Some(false) => Expr::Not(right),
None => lit_bool_null(),
}
}
// A = true --> A
// A = false --> !A
// A = null --> null
Expr::BinaryExpr(BinaryExpr {
left,
op: Eq,
right,
}) if is_bool_lit(&right) && info.is_boolean_type(&left)? => {
match as_bool_lit(*right)? {
Some(true) => *left,
Some(false) => Expr::Not(left),
None => lit_bool_null(),
}
}
// expr IN () --> false
// expr NOT IN () --> true
Expr::InList(InList {
expr,
list,
negated,
}) if list.is_empty() && *expr != Expr::Literal(ScalarValue::Null) => {
lit(negated)
}
// expr IN ((subquery)) -> expr IN (subquery), see ##5529
Expr::InList(InList {
expr,
mut list,
negated,
}) if list.len() == 1
&& matches!(list.first(), Some(Expr::ScalarSubquery { .. })) =>
{
let Expr::ScalarSubquery(subquery) = list.remove(0) else {
unreachable!()
};
Expr::InSubquery(InSubquery::new(expr, subquery, negated))
}
// if expr is a single column reference:
// expr IN (A, B, ...) --> (expr = A) OR (expr = B) OR (expr = C)
Expr::InList(InList {
expr,
list,
negated,
}) if !list.is_empty()
&& (
// For lists with only 1 value we allow more complex expressions to be simplified
// e.g SUBSTR(c1, 2, 3) IN ('1') -> SUBSTR(c1, 2, 3) = '1'
// for more than one we avoid repeating this potentially expensive
// expressions
list.len() == 1
|| list.len() <= THRESHOLD_INLINE_INLIST
&& expr.try_into_col().is_ok()
) =>
{
let first_val = list[0].clone();
if negated {
list.into_iter().skip(1).fold(
(*expr.clone()).not_eq(first_val),
|acc, y| {
// Note that `A and B and C and D` is a left-deep tree structure
// as such we want to maintain this structure as much as possible
// to avoid reordering the expression during each optimization
// pass.
//
// Left-deep tree structure for `A and B and C and D`:
// ```
// &
// / \
// & D
// / \
// & C
// / \
// A B
// ```
//
// The code below maintain the left-deep tree structure.
acc.and((*expr.clone()).not_eq(y))
},
)
} else {
list.into_iter().skip(1).fold(
(*expr.clone()).eq(first_val),
|acc, y| {
// Same reasoning as above
acc.or((*expr.clone()).eq(y))
},
)
}
}
//
// Rules for NotEq
//
// true != A --> !A
// false != A --> A
// null != A --> null
Expr::BinaryExpr(BinaryExpr {
left,
op: NotEq,
right,
}) if is_bool_lit(&left) && info.is_boolean_type(&right)? => {
match as_bool_lit(*left)? {
Some(true) => Expr::Not(right),
Some(false) => *right,
None => lit_bool_null(),
}
}
// A != true --> !A
// A != false --> A
// A != null --> null,
Expr::BinaryExpr(BinaryExpr {
left,
op: NotEq,
right,
}) if is_bool_lit(&right) && info.is_boolean_type(&left)? => {
match as_bool_lit(*right)? {
Some(true) => Expr::Not(left),
Some(false) => *left,
None => lit_bool_null(),
}
}
//
// Rules for OR
//
// true OR A --> true (even if A is null)
Expr::BinaryExpr(BinaryExpr {
left,
op: Or,
right: _,
}) if is_true(&left) => *left,
// false OR A --> A
Expr::BinaryExpr(BinaryExpr {
left,
op: Or,
right,
}) if is_false(&left) => *right,
// A OR true --> true (even if A is null)
Expr::BinaryExpr(BinaryExpr {
left: _,
op: Or,
right,
}) if is_true(&right) => *right,
// A OR false --> A
Expr::BinaryExpr(BinaryExpr {
left,
op: Or,
right,
}) if is_false(&right) => *left,
// A OR !A ---> true (if A not nullable)
Expr::BinaryExpr(BinaryExpr {
left,
op: Or,
right,
}) if is_not_of(&right, &left) && !info.nullable(&left)? => {
Expr::Literal(ScalarValue::Boolean(Some(true)))
}
// !A OR A ---> true (if A not nullable)
Expr::BinaryExpr(BinaryExpr {
left,
op: Or,
right,
}) if is_not_of(&left, &right) && !info.nullable(&right)? => {
Expr::Literal(ScalarValue::Boolean(Some(true)))
}
// (..A..) OR A --> (..A..)
Expr::BinaryExpr(BinaryExpr {
left,
op: Or,
right,
}) if expr_contains(&left, &right, Or) => *left,
// A OR (..A..) --> (..A..)
Expr::BinaryExpr(BinaryExpr {
left,
op: Or,
right,
}) if expr_contains(&right, &left, Or) => *right,
// A OR (A AND B) --> A (if B not null)
Expr::BinaryExpr(BinaryExpr {
left,
op: Or,
right,
}) if !info.nullable(&right)? && is_op_with(And, &right, &left) => *left,
// (A AND B) OR A --> A (if B not null)
Expr::BinaryExpr(BinaryExpr {
left,
op: Or,
right,
}) if !info.nullable(&left)? && is_op_with(And, &left, &right) => *right,
//
// Rules for AND
//
// true AND A --> A
Expr::BinaryExpr(BinaryExpr {
left,
op: And,
right,
}) if is_true(&left) => *right,
// false AND A --> false (even if A is null)
Expr::BinaryExpr(BinaryExpr {
left,
op: And,
right: _,
}) if is_false(&left) => *left,
// A AND true --> A
Expr::BinaryExpr(BinaryExpr {
left,
op: And,
right,
}) if is_true(&right) => *left,
// A AND false --> false (even if A is null)
Expr::BinaryExpr(BinaryExpr {
left: _,
op: And,
right,
}) if is_false(&right) => *right,
// A AND !A ---> false (if A not nullable)
Expr::BinaryExpr(BinaryExpr {
left,
op: And,
right,
}) if is_not_of(&right, &left) && !info.nullable(&left)? => {
Expr::Literal(ScalarValue::Boolean(Some(false)))
}
// !A AND A ---> false (if A not nullable)
Expr::BinaryExpr(BinaryExpr {
left,
op: And,
right,
}) if is_not_of(&left, &right) && !info.nullable(&right)? => {
Expr::Literal(ScalarValue::Boolean(Some(false)))
}
// (..A..) AND A --> (..A..)
Expr::BinaryExpr(BinaryExpr {
left,
op: And,
right,
}) if expr_contains(&left, &right, And) => *left,
// A AND (..A..) --> (..A..)
Expr::BinaryExpr(BinaryExpr {
left,
op: And,
right,
}) if expr_contains(&right, &left, And) => *right,
// A AND (A OR B) --> A (if B not null)
Expr::BinaryExpr(BinaryExpr {
left,
op: And,
right,
}) if !info.nullable(&right)? && is_op_with(Or, &right, &left) => *left,
// (A OR B) AND A --> A (if B not null)
Expr::BinaryExpr(BinaryExpr {
left,
op: And,
right,
}) if !info.nullable(&left)? && is_op_with(Or, &left, &right) => *right,
//
// Rules for Multiply
//
// A * 1 --> A
Expr::BinaryExpr(BinaryExpr {
left,
op: Multiply,
right,
}) if is_one(&right) => *left,
// 1 * A --> A
Expr::BinaryExpr(BinaryExpr {
left,
op: Multiply,
right,
}) if is_one(&left) => *right,
// A * null --> null
Expr::BinaryExpr(BinaryExpr {
left: _,
op: Multiply,
right,
}) if is_null(&right) => *right,
// null * A --> null
Expr::BinaryExpr(BinaryExpr {
left,
op: Multiply,
right: _,
}) if is_null(&left) => *left,
// A * 0 --> 0 (if A is not null)
Expr::BinaryExpr(BinaryExpr {
left,
op: Multiply,
right,
}) if !info.nullable(&left)? && is_zero(&right) => *right,
// 0 * A --> 0 (if A is not null)
Expr::BinaryExpr(BinaryExpr {
left,
op: Multiply,
right,
}) if !info.nullable(&right)? && is_zero(&left) => *left,
//
// Rules for Divide
//
// A / 1 --> A
Expr::BinaryExpr(BinaryExpr {
left,
op: Divide,
right,
}) if is_one(&right) => *left,
// null / A --> null
Expr::BinaryExpr(BinaryExpr {
left,
op: Divide,
right: _,
}) if is_null(&left) => *left,
// A / null --> null
Expr::BinaryExpr(BinaryExpr {
left: _,
op: Divide,
right,
}) if is_null(&right) => *right,
// A / 0 -> DivideByZero Error
Expr::BinaryExpr(BinaryExpr {
left,
op: Divide,
right,
}) if !info.nullable(&left)? && is_zero(&right) => {
return Err(DataFusionError::ArrowError(ArrowError::DivideByZero));
}
//
// Rules for Modulo
//
// A % null --> null
Expr::BinaryExpr(BinaryExpr {
left: _,
op: Modulo,
right,
}) if is_null(&right) => *right,
// null % A --> null
Expr::BinaryExpr(BinaryExpr {
left,
op: Modulo,
right: _,
}) if is_null(&left) => *left,
// A % 1 --> 0
Expr::BinaryExpr(BinaryExpr {
left,
op: Modulo,
right,
}) if !info.nullable(&left)? && is_one(&right) => lit(0),
// A % 0 --> DivideByZero Error
Expr::BinaryExpr(BinaryExpr {
left,
op: Modulo,
right,
}) if !info.nullable(&left)? && is_zero(&right) => {
return Err(DataFusionError::ArrowError(ArrowError::DivideByZero));
}
//
// Rules for BitwiseAnd
//
// A & null -> null
Expr::BinaryExpr(BinaryExpr {
left: _,
op: BitwiseAnd,
right,
}) if is_null(&right) => *right,
// null & A -> null
Expr::BinaryExpr(BinaryExpr {
left,
op: BitwiseAnd,
right: _,
}) if is_null(&left) => *left,
// A & 0 -> 0 (if A not nullable)
Expr::BinaryExpr(BinaryExpr {
left,
op: BitwiseAnd,
right,
}) if !info.nullable(&left)? && is_zero(&right) => *right,
// 0 & A -> 0 (if A not nullable)
Expr::BinaryExpr(BinaryExpr {
left,
op: BitwiseAnd,
right,
}) if !info.nullable(&right)? && is_zero(&left) => *left,
// !A & A -> 0 (if A not nullable)
Expr::BinaryExpr(BinaryExpr {
left,
op: BitwiseAnd,
right,
}) if is_negative_of(&left, &right) && !info.nullable(&right)? => {
Expr::Literal(ScalarValue::new_zero(&info.get_data_type(&left)?)?)
}
// A & !A -> 0 (if A not nullable)
Expr::BinaryExpr(BinaryExpr {
left,
op: BitwiseAnd,
right,
}) if is_negative_of(&right, &left) && !info.nullable(&left)? => {
Expr::Literal(ScalarValue::new_zero(&info.get_data_type(&left)?)?)
}
// (..A..) & A --> (..A..)
Expr::BinaryExpr(BinaryExpr {
left,
op: BitwiseAnd,
right,
}) if expr_contains(&left, &right, BitwiseAnd) => *left,
// A & (..A..) --> (..A..)
Expr::BinaryExpr(BinaryExpr {
left,
op: BitwiseAnd,
right,
}) if expr_contains(&right, &left, BitwiseAnd) => *right,
// A & (A | B) --> A (if B not null)
Expr::BinaryExpr(BinaryExpr {
left,
op: BitwiseAnd,
right,
}) if !info.nullable(&right)? && is_op_with(BitwiseOr, &right, &left) => {
*left
}
// (A | B) & A --> A (if B not null)
Expr::BinaryExpr(BinaryExpr {
left,
op: BitwiseAnd,
right,
}) if !info.nullable(&left)? && is_op_with(BitwiseOr, &left, &right) => {
*right
}
//
// Rules for BitwiseOr
//
// A | null -> null
Expr::BinaryExpr(BinaryExpr {
left: _,
op: BitwiseOr,
right,
}) if is_null(&right) => *right,
// null | A -> null
Expr::BinaryExpr(BinaryExpr {
left,
op: BitwiseOr,
right: _,
}) if is_null(&left) => *left,
// A | 0 -> A (even if A is null)
Expr::BinaryExpr(BinaryExpr {
left,
op: BitwiseOr,
right,
}) if is_zero(&right) => *left,
// 0 | A -> A (even if A is null)
Expr::BinaryExpr(BinaryExpr {
left,
op: BitwiseOr,
right,
}) if is_zero(&left) => *right,
// !A | A -> -1 (if A not nullable)
Expr::BinaryExpr(BinaryExpr {
left,
op: BitwiseOr,
right,
}) if is_negative_of(&left, &right) && !info.nullable(&right)? => {
Expr::Literal(ScalarValue::new_negative_one(&info.get_data_type(&left)?)?)
}
// A | !A -> -1 (if A not nullable)
Expr::BinaryExpr(BinaryExpr {
left,
op: BitwiseOr,
right,
}) if is_negative_of(&right, &left) && !info.nullable(&left)? => {
Expr::Literal(ScalarValue::new_negative_one(&info.get_data_type(&left)?)?)
}
// (..A..) | A --> (..A..)
Expr::BinaryExpr(BinaryExpr {
left,
op: BitwiseOr,
right,
}) if expr_contains(&left, &right, BitwiseOr) => *left,
// A | (..A..) --> (..A..)
Expr::BinaryExpr(BinaryExpr {
left,
op: BitwiseOr,
right,
}) if expr_contains(&right, &left, BitwiseOr) => *right,
// A | (A & B) --> A (if B not null)
Expr::BinaryExpr(BinaryExpr {
left,
op: BitwiseOr,
right,
}) if !info.nullable(&right)? && is_op_with(BitwiseAnd, &right, &left) => {
*left
}
// (A & B) | A --> A (if B not null)
Expr::BinaryExpr(BinaryExpr {
left,
op: BitwiseOr,
right,
}) if !info.nullable(&left)? && is_op_with(BitwiseAnd, &left, &right) => {
*right
}
//
// Rules for BitwiseXor
//
// A ^ null -> null
Expr::BinaryExpr(BinaryExpr {
left: _,
op: BitwiseXor,
right,
}) if is_null(&right) => *right,
// null ^ A -> null
Expr::BinaryExpr(BinaryExpr {
left,
op: BitwiseXor,
right: _,
}) if is_null(&left) => *left,
// A ^ 0 -> A (if A not nullable)
Expr::BinaryExpr(BinaryExpr {
left,
op: BitwiseXor,
right,
}) if !info.nullable(&left)? && is_zero(&right) => *left,
// 0 ^ A -> A (if A not nullable)
Expr::BinaryExpr(BinaryExpr {
left,
op: BitwiseXor,
right,
}) if !info.nullable(&right)? && is_zero(&left) => *right,
// !A ^ A -> -1 (if A not nullable)
Expr::BinaryExpr(BinaryExpr {
left,
op: BitwiseXor,
right,
}) if is_negative_of(&left, &right) && !info.nullable(&right)? => {
Expr::Literal(ScalarValue::new_negative_one(&info.get_data_type(&left)?)?)
}
// A ^ !A -> -1 (if A not nullable)
Expr::BinaryExpr(BinaryExpr {
left,
op: BitwiseXor,
right,
}) if is_negative_of(&right, &left) && !info.nullable(&left)? => {
Expr::Literal(ScalarValue::new_negative_one(&info.get_data_type(&left)?)?)
}
// (..A..) ^ A --> (the expression without A, if number of A is odd, otherwise one A)
Expr::BinaryExpr(BinaryExpr {
left,
op: BitwiseXor,
right,
}) if expr_contains(&left, &right, BitwiseXor) => {
let expr = delete_xor_in_complex_expr(&left, &right, false);
if expr == *right {
Expr::Literal(ScalarValue::new_zero(&info.get_data_type(&right)?)?)
} else {
expr
}
}
// A ^ (..A..) --> (the expression without A, if number of A is odd, otherwise one A)
Expr::BinaryExpr(BinaryExpr {
left,
op: BitwiseXor,
right,
}) if expr_contains(&right, &left, BitwiseXor) => {
let expr = delete_xor_in_complex_expr(&right, &left, true);
if expr == *left {
Expr::Literal(ScalarValue::new_zero(&info.get_data_type(&left)?)?)
} else {
expr
}
}
//
// Rules for BitwiseShiftRight
//
// A >> null -> null
Expr::BinaryExpr(BinaryExpr {
left: _,
op: BitwiseShiftRight,
right,
}) if is_null(&right) => *right,
// null >> A -> null
Expr::BinaryExpr(BinaryExpr {
left,
op: BitwiseShiftRight,
right: _,
}) if is_null(&left) => *left,
// A >> 0 -> A (even if A is null)
Expr::BinaryExpr(BinaryExpr {
left,
op: BitwiseShiftRight,
right,
}) if is_zero(&right) => *left,
//
// Rules for BitwiseShiftRight
//
// A << null -> null
Expr::BinaryExpr(BinaryExpr {
left: _,
op: BitwiseShiftLeft,
right,
}) if is_null(&right) => *right,
// null << A -> null
Expr::BinaryExpr(BinaryExpr {
left,
op: BitwiseShiftLeft,
right: _,
}) if is_null(&left) => *left,
// A << 0 -> A (even if A is null)
Expr::BinaryExpr(BinaryExpr {
left,
op: BitwiseShiftLeft,
right,
}) if is_zero(&right) => *left,
//
// Rules for Not
//
Expr::Not(inner) => negate_clause(*inner),
//
// Rules for Negative
//
Expr::Negative(inner) => distribute_negation(*inner),
//
// Rules for Case
//
// CASE
// WHEN X THEN A
// WHEN Y THEN B
// ...
// ELSE Q
// END
//
// ---> (X AND A) OR (Y AND B AND NOT X) OR ... (NOT (X OR Y) AND Q)
//
// Note: the rationale for this rewrite is that the expr can then be further
// simplified using the existing rules for AND/OR
Expr::Case(Case {
expr: None,
when_then_expr,
else_expr,
}) if !when_then_expr.is_empty()
&& when_then_expr.len() < 3 // The rewrite is O(n!) so limit to small number
&& info.is_boolean_type(&when_then_expr[0].1)? =>
{
// The disjunction of all the when predicates encountered so far
let mut filter_expr = lit(false);
// The disjunction of all the cases
let mut out_expr = lit(false);
for (when, then) in when_then_expr {
let case_expr = when
.as_ref()
.clone()
.and(filter_expr.clone().not())
.and(*then);
out_expr = out_expr.or(case_expr);
filter_expr = filter_expr.or(*when);
}
if let Some(else_expr) = else_expr {
let case_expr = filter_expr.not().and(*else_expr);
out_expr = out_expr.or(case_expr);
}
// Do a first pass at simplification
out_expr.rewrite(self)?
}
// log
Expr::ScalarFunction(ScalarFunction {
fun: BuiltinScalarFunction::Log,
args,
}) => simpl_log(args, <&S>::clone(&info))?,
// power
Expr::ScalarFunction(ScalarFunction {
fun: BuiltinScalarFunction::Power,
args,
}) => simpl_power(args, <&S>::clone(&info))?,
// concat
Expr::ScalarFunction(ScalarFunction {
fun: BuiltinScalarFunction::Concat,
args,
}) => simpl_concat(args)?,
// concat_ws
Expr::ScalarFunction(ScalarFunction {
fun: BuiltinScalarFunction::ConcatWithSeparator,
args,
}) => match &args[..] {
[delimiter, vals @ ..] => simpl_concat_ws(delimiter, vals)?,
_ => Expr::ScalarFunction(ScalarFunction::new(
BuiltinScalarFunction::ConcatWithSeparator,
args,
)),
},
//
// Rules for Between
//
// a between 3 and 5 --> a >= 3 AND a <=5
// a not between 3 and 5 --> a < 3 OR a > 5
Expr::Between(between) => {
if between.negated {
let l = *between.expr.clone();
let r = *between.expr;
or(l.lt(*between.low), r.gt(*between.high))
} else {
and(
between.expr.clone().gt_eq(*between.low),
between.expr.lt_eq(*between.high),
)
}
}
//
// Rules for regexes
//
Expr::BinaryExpr(BinaryExpr {
left,
op: op @ (RegexMatch | RegexNotMatch | RegexIMatch | RegexNotIMatch),
right,
}) => simplify_regex_expr(left, op, right)?,
// Rules for Like
Expr::Like(Like {
expr,
pattern,
negated,
escape_char: _,
case_insensitive: _,
}) if !is_null(&expr)
&& matches!(
pattern.as_ref(),
Expr::Literal(ScalarValue::Utf8(Some(pattern_str))) if pattern_str == "%"
) =>
{
lit(!negated)
}
// a is not null/unknown --> true (if a is not nullable)
Expr::IsNotNull(expr) | Expr::IsNotUnknown(expr)
if !info.nullable(&expr)? =>
{
lit(true)
}
// a is null/unknown --> false (if a is not nullable)
Expr::IsNull(expr) | Expr::IsUnknown(expr) if !info.nullable(&expr)? => {
lit(false)
}
// no additional rewrites possible
expr => expr,
};
Ok(new_expr)
}
}
#[cfg(test)]
mod tests {
use std::{
collections::HashMap,
ops::{BitAnd, BitOr, BitXor},
sync::Arc,
};
use crate::simplify_expressions::{
utils::for_test::{cast_to_int64_expr, now_expr, to_timestamp_expr},
SimplifyContext,
};
use super::*;
use crate::test::test_table_scan_with_name;
use arrow::{
array::{ArrayRef, Int32Array},
datatypes::{DataType, Field, Schema},
};
use chrono::{DateTime, TimeZone, Utc};
use datafusion_common::{assert_contains, cast::as_int32_array, DFField, ToDFSchema};
use datafusion_expr::*;
use datafusion_physical_expr::{
execution_props::ExecutionProps, functions::make_scalar_function,
};
// ------------------------------
// --- ExprSimplifier tests -----
// ------------------------------
#[test]
fn api_basic() {
let props = ExecutionProps::new();
let simplifier =
ExprSimplifier::new(SimplifyContext::new(&props).with_schema(test_schema()));
let expr = lit(1) + lit(2);
let expected = lit(3);
assert_eq!(expected, simplifier.simplify(expr).unwrap());
}
#[test]
fn basic_coercion() {
let schema = test_schema();
let props = ExecutionProps::new();
let simplifier =
ExprSimplifier::new(SimplifyContext::new(&props).with_schema(schema.clone()));
// Note expr type is int32 (not int64)
// (1i64 + 2i32) < i
let expr = (lit(1i64) + lit(2i32)).lt(col("i"));
// should fully simplify to 3 < i (though i has been coerced to i64)
let expected = lit(3i64).lt(col("i"));
// Would be nice if this API could use the SimplifyInfo
// rather than creating an DFSchemaRef coerces rather than doing
// it manually.
// https://github.com/apache/arrow-datafusion/issues/3793
let expr = simplifier.coerce(expr, schema).unwrap();
assert_eq!(expected, simplifier.simplify(expr).unwrap());
}
fn test_schema() -> DFSchemaRef {
Schema::new(vec![
Field::new("i", DataType::Int64, false),
Field::new("b", DataType::Boolean, true),
])
.to_dfschema_ref()
.unwrap()
}
#[test]
fn simplify_and_constant_prop() {
let props = ExecutionProps::new();
let simplifier =
ExprSimplifier::new(SimplifyContext::new(&props).with_schema(test_schema()));
// should be able to simplify to false
// (i * (1 - 2)) > 0
let expr = (col("i") * (lit(1) - lit(1))).gt(lit(0));
let expected = lit(false);
assert_eq!(expected, simplifier.simplify(expr).unwrap());
}
#[test]
fn simplify_and_constant_prop_with_case() {
let props = ExecutionProps::new();
let simplifier =
ExprSimplifier::new(SimplifyContext::new(&props).with_schema(test_schema()));
// CASE
// WHEN i>5 AND false THEN i > 5
// WHEN i<5 AND true THEN i < 5
// ELSE false
// END
//
// Can be simplified to `i < 5`
let expr = when(col("i").gt(lit(5)).and(lit(false)), col("i").gt(lit(5)))
.when(col("i").lt(lit(5)).and(lit(true)), col("i").lt(lit(5)))
.otherwise(lit(false))
.unwrap();
let expected = col("i").lt(lit(5));
assert_eq!(expected, simplifier.simplify(expr).unwrap());
}
// ------------------------------
// --- ConstEvaluator tests -----
// ------------------------------
fn test_evaluate_with_start_time(
input_expr: Expr,
expected_expr: Expr,
date_time: &DateTime<Utc>,
) {
let execution_props =
ExecutionProps::new().with_query_execution_start_time(*date_time);
let mut const_evaluator = ConstEvaluator::try_new(&execution_props).unwrap();
let evaluated_expr = input_expr
.clone()
.rewrite(&mut const_evaluator)
.expect("successfully evaluated");
assert_eq!(
evaluated_expr, expected_expr,
"Mismatch evaluating {input_expr}\n Expected:{expected_expr}\n Got:{evaluated_expr}"
);
}
fn test_evaluate(input_expr: Expr, expected_expr: Expr) {
test_evaluate_with_start_time(input_expr, expected_expr, &Utc::now())
}
// Make a UDF that adds its two values together, with the specified volatility
fn make_udf_add(volatility: Volatility) -> Arc<ScalarUDF> {
let input_types = vec![DataType::Int32, DataType::Int32];
let return_type = Arc::new(DataType::Int32);
let fun = |args: &[ArrayRef]| {
let arg0 = as_int32_array(&args[0])?;
let arg1 = as_int32_array(&args[1])?;
// 2. perform the computation
let array = arg0
.iter()
.zip(arg1.iter())
.map(|args| {
if let (Some(arg0), Some(arg1)) = args {
Some(arg0 + arg1)
} else {
// one or both args were Null
None
}
})
.collect::<Int32Array>();
Ok(Arc::new(array) as ArrayRef)
};
let fun = make_scalar_function(fun);
Arc::new(create_udf(
"udf_add",
input_types,
return_type,
volatility,
fun,
))
}
#[test]
fn test_const_evaluator() {
// true --> true
test_evaluate(lit(true), lit(true));
// true or true --> true
test_evaluate(lit(true).or(lit(true)), lit(true));
// true or false --> true
test_evaluate(lit(true).or(lit(false)), lit(true));
// "foo" == "foo" --> true
test_evaluate(lit("foo").eq(lit("foo")), lit(true));
// "foo" != "foo" --> false
test_evaluate(lit("foo").not_eq(lit("foo")), lit(false));
// c = 1 --> c = 1
test_evaluate(col("c").eq(lit(1)), col("c").eq(lit(1)));
// c = 1 + 2 --> c + 3
test_evaluate(col("c").eq(lit(1) + lit(2)), col("c").eq(lit(3)));
// (foo != foo) OR (c = 1) --> false OR (c = 1)
test_evaluate(
(lit("foo").not_eq(lit("foo"))).or(col("c").eq(lit(1))),
lit(false).or(col("c").eq(lit(1))),
);
}
#[test]
fn test_const_evaluator_scalar_functions() {
// concat("foo", "bar") --> "foobar"
let expr = call_fn("concat", vec![lit("foo"), lit("bar")]).unwrap();
test_evaluate(expr, lit("foobar"));
// ensure arguments are also constant folded
// concat("foo", concat("bar", "baz")) --> "foobarbaz"
let concat1 = call_fn("concat", vec![lit("bar"), lit("baz")]).unwrap();
let expr = call_fn("concat", vec![lit("foo"), concat1]).unwrap();
test_evaluate(expr, lit("foobarbaz"));
// Check non string arguments
// to_timestamp("2020-09-08T12:00:00+00:00") --> timestamp(1599566400000000000i64)
let expr =
call_fn("to_timestamp", vec![lit("2020-09-08T12:00:00+00:00")]).unwrap();
test_evaluate(expr, lit_timestamp_nano(1599566400000000000i64));
// check that non foldable arguments are folded
// to_timestamp(a) --> to_timestamp(a) [no rewrite possible]
let expr = call_fn("to_timestamp", vec![col("a")]).unwrap();
test_evaluate(expr.clone(), expr);
// volatile / stable functions should not be evaluated
// rand() + (1 + 2) --> rand() + 3
let fun = BuiltinScalarFunction::Random;
assert_eq!(fun.volatility(), Volatility::Volatile);
let rand = Expr::ScalarFunction(ScalarFunction::new(fun, vec![]));
let expr = rand.clone() + (lit(1) + lit(2));
let expected = rand + lit(3);
test_evaluate(expr, expected);
// parenthesization matters: can't rewrite
// (rand() + 1) + 2 --> (rand() + 1) + 2)
let fun = BuiltinScalarFunction::Random;
let rand = Expr::ScalarFunction(ScalarFunction::new(fun, vec![]));
let expr = (rand + lit(1)) + lit(2);
test_evaluate(expr.clone(), expr);
}
#[test]
fn test_const_evaluator_now() {
let ts_nanos = 1599566400000000000i64;
let time = chrono::Utc.timestamp_nanos(ts_nanos);
let ts_string = "2020-09-08T12:05:00+00:00";
// now() --> ts
test_evaluate_with_start_time(now_expr(), lit_timestamp_nano(ts_nanos), &time);
// CAST(now() as int64) + 100_i64 --> ts + 100_i64
let expr = cast_to_int64_expr(now_expr()) + lit(100_i64);
test_evaluate_with_start_time(expr, lit(ts_nanos + 100), &time);
// CAST(now() as int64) < cast(to_timestamp(...) as int64) + 50000_i64 ---> true
let expr = cast_to_int64_expr(now_expr())
.lt(cast_to_int64_expr(to_timestamp_expr(ts_string)) + lit(50000i64));
test_evaluate_with_start_time(expr, lit(true), &time);
}
#[test]
fn test_evaluator_udfs() {
let args = vec![lit(1) + lit(2), lit(30) + lit(40)];
let folded_args = vec![lit(3), lit(70)];
// immutable UDF should get folded
// udf_add(1+2, 30+40) --> 73
let expr = Expr::ScalarUDF(expr::ScalarUDF::new(
make_udf_add(Volatility::Immutable),
args.clone(),
));
test_evaluate(expr, lit(73));
// stable UDF should be entirely folded
// udf_add(1+2, 30+40) --> 73
let fun = make_udf_add(Volatility::Stable);
let expr = Expr::ScalarUDF(expr::ScalarUDF::new(Arc::clone(&fun), args.clone()));
test_evaluate(expr, lit(73));
// volatile UDF should have args folded
// udf_add(1+2, 30+40) --> udf_add(3, 70)
let fun = make_udf_add(Volatility::Volatile);
let expr = Expr::ScalarUDF(expr::ScalarUDF::new(Arc::clone(&fun), args));
let expected_expr =
Expr::ScalarUDF(expr::ScalarUDF::new(Arc::clone(&fun), folded_args));
test_evaluate(expr, expected_expr);
}
// ------------------------------
// --- Simplifier tests -----
// ------------------------------
#[test]
fn test_simplify_or_true() {
let expr_a = col("c2").or(lit(true));
let expr_b = lit(true).or(col("c2"));
let expected = lit(true);
assert_eq!(simplify(expr_a), expected);
assert_eq!(simplify(expr_b), expected);
}
#[test]
fn test_simplify_or_false() {
let expr_a = lit(false).or(col("c2"));
let expr_b = col("c2").or(lit(false));
let expected = col("c2");
assert_eq!(simplify(expr_a), expected);
assert_eq!(simplify(expr_b), expected);
}
#[test]
fn test_simplify_or_same() {
let expr = col("c2").or(col("c2"));
let expected = col("c2");
assert_eq!(simplify(expr), expected);
}
#[test]
fn test_simplify_or_not_self() {
// A OR !A if A is not nullable --> true
// !A OR A if A is not nullable --> true
let expr_a = col("c2_non_null").or(col("c2_non_null").not());
let expr_b = col("c2_non_null").not().or(col("c2_non_null"));
let expected = lit(true);
assert_eq!(simplify(expr_a), expected);
assert_eq!(simplify(expr_b), expected);
}
#[test]
fn test_simplify_and_false() {
let expr_a = lit(false).and(col("c2"));
let expr_b = col("c2").and(lit(false));
let expected = lit(false);
assert_eq!(simplify(expr_a), expected);
assert_eq!(simplify(expr_b), expected);
}
#[test]
fn test_simplify_and_same() {
let expr = col("c2").and(col("c2"));
let expected = col("c2");
assert_eq!(simplify(expr), expected);
}
#[test]
fn test_simplify_and_true() {
let expr_a = lit(true).and(col("c2"));
let expr_b = col("c2").and(lit(true));
let expected = col("c2");
assert_eq!(simplify(expr_a), expected);
assert_eq!(simplify(expr_b), expected);
}
#[test]
fn test_simplify_and_not_self() {
// A AND !A if A is not nullable --> false
// !A AND A if A is not nullable --> false
let expr_a = col("c2_non_null").and(col("c2_non_null").not());
let expr_b = col("c2_non_null").not().and(col("c2_non_null"));
let expected = lit(false);
assert_eq!(simplify(expr_a), expected);
assert_eq!(simplify(expr_b), expected);
}
#[test]
fn test_simplify_multiply_by_one() {
let expr_a = col("c2") * lit(1);
let expr_b = lit(1) * col("c2");
let expected = col("c2");
assert_eq!(simplify(expr_a), expected);
assert_eq!(simplify(expr_b), expected);
let expr = col("c2") * lit(ScalarValue::Decimal128(Some(10000000000), 38, 10));
assert_eq!(simplify(expr), expected);
let expr = lit(ScalarValue::Decimal128(Some(10000000000), 31, 10)) * col("c2");
assert_eq!(simplify(expr), expected);
}
#[test]
fn test_simplify_multiply_by_null() {
let null = Expr::Literal(ScalarValue::Null);
// A * null --> null
{
let expr = col("c2") * null.clone();
assert_eq!(simplify(expr), null);
}
// null * A --> null
{
let expr = null.clone() * col("c2");
assert_eq!(simplify(expr), null);
}
}
#[test]
fn test_simplify_multiply_by_zero() {
// cannot optimize A * null (null * A) if A is nullable
{
let expr_a = col("c2") * lit(0);
let expr_b = lit(0) * col("c2");
assert_eq!(simplify(expr_a.clone()), expr_a);
assert_eq!(simplify(expr_b.clone()), expr_b);
}
// 0 * A --> 0 if A is not nullable
{
let expr = lit(0) * col("c2_non_null");
assert_eq!(simplify(expr), lit(0));
}
// A * 0 --> 0 if A is not nullable
{
let expr = col("c2_non_null") * lit(0);
assert_eq!(simplify(expr), lit(0));
}
// A * Decimal128(0) --> 0 if A is not nullable
{
let expr = col("c2_non_null") * lit(ScalarValue::Decimal128(Some(0), 31, 10));
assert_eq!(
simplify(expr),
lit(ScalarValue::Decimal128(Some(0), 31, 10))
);
let expr = binary_expr(
lit(ScalarValue::Decimal128(Some(0), 31, 10)),
Operator::Multiply,
col("c2_non_null"),
);
assert_eq!(
simplify(expr),
lit(ScalarValue::Decimal128(Some(0), 31, 10))
);
}
}
#[test]
fn test_simplify_divide_by_one() {
let expr = binary_expr(col("c2"), Operator::Divide, lit(1));
let expected = col("c2");
assert_eq!(simplify(expr), expected);
let expr = col("c2") / lit(ScalarValue::Decimal128(Some(10000000000), 31, 10));
assert_eq!(simplify(expr), expected);
}
#[test]
fn test_simplify_divide_null() {
// A / null --> null
let null = lit(ScalarValue::Null);
{
let expr = col("c") / null.clone();
assert_eq!(simplify(expr), null);
}
// null / A --> null
{
let expr = null.clone() / col("c");
assert_eq!(simplify(expr), null);
}
}
#[test]
fn test_simplify_divide_by_same() {
let expr = col("c2") / col("c2");
// if c2 is null, c2 / c2 = null, so can't simplify
let expected = expr.clone();
assert_eq!(simplify(expr), expected);
}
#[test]
fn test_simplify_divide_zero_by_zero() {
// 0 / 0 -> DivideByZero
let expr = lit(0) / lit(0);
let err = try_simplify(expr).unwrap_err();
assert!(
matches!(err, DataFusionError::ArrowError(ArrowError::DivideByZero)),
"{err}"
);
}
#[test]
#[should_panic(
expected = "called `Result::unwrap()` on an `Err` value: ArrowError(DivideByZero)"
)]
fn test_simplify_divide_by_zero() {
// A / 0 -> DivideByZeroError
let expr = col("c2_non_null") / lit(0);
simplify(expr);
}
#[test]
fn test_simplify_modulo_by_null() {
let null = lit(ScalarValue::Null);
// A % null --> null
{
let expr = col("c2") % null.clone();
assert_eq!(simplify(expr), null);
}
// null % A --> null
{
let expr = null.clone() % col("c2");
assert_eq!(simplify(expr), null);
}
}
#[test]
fn test_simplify_modulo_by_one() {
let expr = col("c2") % lit(1);
// if c2 is null, c2 % 1 = null, so can't simplify
let expected = expr.clone();
assert_eq!(simplify(expr), expected);
}
#[test]
fn test_simplify_modulo_by_one_non_null() {
let expr = col("c2_non_null") % lit(1);
let expected = lit(0);
assert_eq!(simplify(expr), expected);
let expr =
col("c2_non_null") % lit(ScalarValue::Decimal128(Some(10000000000), 31, 10));
assert_eq!(simplify(expr), expected);
}
#[test]
fn test_simplify_bitwise_xor_by_null() {
let null = lit(ScalarValue::Null);
// A ^ null --> null
{
let expr = col("c2") ^ null.clone();
assert_eq!(simplify(expr), null);
}
// null ^ A --> null
{
let expr = null.clone() ^ col("c2");
assert_eq!(simplify(expr), null);
}
}
#[test]
fn test_simplify_bitwise_shift_right_by_null() {
let null = lit(ScalarValue::Null);
// A >> null --> null
{
let expr = col("c2") >> null.clone();
assert_eq!(simplify(expr), null);
}
// null >> A --> null
{
let expr = null.clone() >> col("c2");
assert_eq!(simplify(expr), null);
}
}
#[test]
fn test_simplify_bitwise_shift_left_by_null() {
let null = lit(ScalarValue::Null);
// A << null --> null
{
let expr = col("c2") << null.clone();
assert_eq!(simplify(expr), null);
}
// null << A --> null
{
let expr = null.clone() << col("c2");
assert_eq!(simplify(expr), null);
}
}
#[test]
fn test_simplify_bitwise_and_by_zero() {
// A & 0 --> 0
{
let expr = col("c2_non_null") & lit(0);
assert_eq!(simplify(expr), lit(0));
}
// 0 & A --> 0
{
let expr = lit(0) & col("c2_non_null");
assert_eq!(simplify(expr), lit(0));
}
}
#[test]
fn test_simplify_bitwise_or_by_zero() {
// A | 0 --> A
{
let expr = col("c2_non_null") | lit(0);
assert_eq!(simplify(expr), col("c2_non_null"));
}
// 0 | A --> A
{
let expr = lit(0) | col("c2_non_null");
assert_eq!(simplify(expr), col("c2_non_null"));
}
}
#[test]
fn test_simplify_bitwise_xor_by_zero() {
// A ^ 0 --> A
{
let expr = col("c2_non_null") ^ lit(0);
assert_eq!(simplify(expr), col("c2_non_null"));
}
// 0 ^ A --> A
{
let expr = lit(0) ^ col("c2_non_null");
assert_eq!(simplify(expr), col("c2_non_null"));
}
}
#[test]
fn test_simplify_bitwise_bitwise_shift_right_by_zero() {
// A >> 0 --> A
{
let expr = col("c2_non_null") >> lit(0);
assert_eq!(simplify(expr), col("c2_non_null"));
}
}
#[test]
fn test_simplify_bitwise_bitwise_shift_left_by_zero() {
// A << 0 --> A
{
let expr = col("c2_non_null") << lit(0);
assert_eq!(simplify(expr), col("c2_non_null"));
}
}
#[test]
fn test_simplify_bitwise_and_by_null() {
let null = lit(ScalarValue::Null);
// A & null --> null
{
let expr = col("c2") & null.clone();
assert_eq!(simplify(expr), null);
}
// null & A --> null
{
let expr = null.clone() & col("c2");
assert_eq!(simplify(expr), null);
}
}
#[test]
fn test_simplify_composed_bitwise_and() {
// ((c2 > 5) & (c1 < 6)) & (c2 > 5) --> (c2 > 5) & (c1 < 6)
let expr = bitwise_and(
bitwise_and(col("c2").gt(lit(5)), col("c1").lt(lit(6))),
col("c2").gt(lit(5)),
);
let expected = bitwise_and(col("c2").gt(lit(5)), col("c1").lt(lit(6)));
assert_eq!(simplify(expr), expected);
// (c2 > 5) & ((c2 > 5) & (c1 < 6)) --> (c2 > 5) & (c1 < 6)
let expr = bitwise_and(
col("c2").gt(lit(5)),
bitwise_and(col("c2").gt(lit(5)), col("c1").lt(lit(6))),
);
let expected = bitwise_and(col("c2").gt(lit(5)), col("c1").lt(lit(6)));
assert_eq!(simplify(expr), expected);
}
#[test]
fn test_simplify_composed_bitwise_or() {
// ((c2 > 5) | (c1 < 6)) | (c2 > 5) --> (c2 > 5) | (c1 < 6)
let expr = bitwise_or(
bitwise_or(col("c2").gt(lit(5)), col("c1").lt(lit(6))),
col("c2").gt(lit(5)),
);
let expected = bitwise_or(col("c2").gt(lit(5)), col("c1").lt(lit(6)));
assert_eq!(simplify(expr), expected);
// (c2 > 5) | ((c2 > 5) | (c1 < 6)) --> (c2 > 5) | (c1 < 6)
let expr = bitwise_or(
col("c2").gt(lit(5)),
bitwise_or(col("c2").gt(lit(5)), col("c1").lt(lit(6))),
);
let expected = bitwise_or(col("c2").gt(lit(5)), col("c1").lt(lit(6)));
assert_eq!(simplify(expr), expected);
}
#[test]
fn test_simplify_composed_bitwise_xor() {
// with an even number of the column "c2"
// c2 ^ ((c2 ^ (c2 | c1)) ^ (c1 & c2)) --> (c2 | c1) ^ (c1 & c2)
let expr = bitwise_xor(
col("c2"),
bitwise_xor(
bitwise_xor(col("c2"), bitwise_or(col("c2"), col("c1"))),
bitwise_and(col("c1"), col("c2")),
),
);
let expected = bitwise_xor(
bitwise_or(col("c2"), col("c1")),
bitwise_and(col("c1"), col("c2")),
);
assert_eq!(simplify(expr), expected);
// with an odd number of the column "c2"
// c2 ^ (c2 ^ (c2 | c1)) ^ ((c1 & c2) ^ c2) --> c2 ^ ((c2 | c1) ^ (c1 & c2))
let expr = bitwise_xor(
col("c2"),
bitwise_xor(
bitwise_xor(col("c2"), bitwise_or(col("c2"), col("c1"))),
bitwise_xor(bitwise_and(col("c1"), col("c2")), col("c2")),
),
);
let expected = bitwise_xor(
col("c2"),
bitwise_xor(
bitwise_or(col("c2"), col("c1")),
bitwise_and(col("c1"), col("c2")),
),
);
assert_eq!(simplify(expr), expected);
// with an even number of the column "c2"
// ((c2 ^ (c2 | c1)) ^ (c1 & c2)) ^ c2 --> (c2 | c1) ^ (c1 & c2)
let expr = bitwise_xor(
bitwise_xor(
bitwise_xor(col("c2"), bitwise_or(col("c2"), col("c1"))),
bitwise_and(col("c1"), col("c2")),
),
col("c2"),
);
let expected = bitwise_xor(
bitwise_or(col("c2"), col("c1")),
bitwise_and(col("c1"), col("c2")),
);
assert_eq!(simplify(expr), expected);
// with an odd number of the column "c2"
// (c2 ^ (c2 | c1)) ^ ((c1 & c2) ^ c2) ^ c2 --> ((c2 | c1) ^ (c1 & c2)) ^ c2
let expr = bitwise_xor(
bitwise_xor(
bitwise_xor(col("c2"), bitwise_or(col("c2"), col("c1"))),
bitwise_xor(bitwise_and(col("c1"), col("c2")), col("c2")),
),
col("c2"),
);
let expected = bitwise_xor(
bitwise_xor(
bitwise_or(col("c2"), col("c1")),
bitwise_and(col("c1"), col("c2")),
),
col("c2"),
);
assert_eq!(simplify(expr), expected);
}
#[test]
fn test_simplify_negated_bitwise_and() {
// !c4 & c4 --> 0
let expr = (-col("c4_non_null")) & col("c4_non_null");
let expected = lit(0u32);
assert_eq!(simplify(expr), expected);
// c4 & !c4 --> 0
let expr = col("c4_non_null") & (-col("c4_non_null"));
let expected = lit(0u32);
assert_eq!(simplify(expr), expected);
// !c3 & c3 --> 0
let expr = (-col("c3_non_null")) & col("c3_non_null");
let expected = lit(0i64);
assert_eq!(simplify(expr), expected);
// c3 & !c3 --> 0
let expr = col("c3_non_null") & (-col("c3_non_null"));
let expected = lit(0i64);
assert_eq!(simplify(expr), expected);
}
#[test]
fn test_simplify_negated_bitwise_or() {
// !c4 | c4 --> -1
let expr = (-col("c4_non_null")) | col("c4_non_null");
let expected = lit(-1i32);
assert_eq!(simplify(expr), expected);
// c4 | !c4 --> -1
let expr = col("c4_non_null") | (-col("c4_non_null"));
let expected = lit(-1i32);
assert_eq!(simplify(expr), expected);
// !c3 | c3 --> -1
let expr = (-col("c3_non_null")) | col("c3_non_null");
let expected = lit(-1i64);
assert_eq!(simplify(expr), expected);
// c3 | !c3 --> -1
let expr = col("c3_non_null") | (-col("c3_non_null"));
let expected = lit(-1i64);
assert_eq!(simplify(expr), expected);
}
#[test]
fn test_simplify_negated_bitwise_xor() {
// !c4 ^ c4 --> -1
let expr = (-col("c4_non_null")) ^ col("c4_non_null");
let expected = lit(-1i32);
assert_eq!(simplify(expr), expected);
// c4 ^ !c4 --> -1
let expr = col("c4_non_null") ^ (-col("c4_non_null"));
let expected = lit(-1i32);
assert_eq!(simplify(expr), expected);
// !c3 ^ c3 --> -1
let expr = (-col("c3_non_null")) ^ col("c3_non_null");
let expected = lit(-1i64);
assert_eq!(simplify(expr), expected);
// c3 ^ !c3 --> -1
let expr = col("c3_non_null") ^ (-col("c3_non_null"));
let expected = lit(-1i64);
assert_eq!(simplify(expr), expected);
}
#[test]
fn test_simplify_bitwise_and_or() {
// (c2 < 3) & ((c2 < 3) | c1) -> (c2 < 3)
let expr = bitwise_and(
col("c2_non_null").lt(lit(3)),
bitwise_or(col("c2_non_null").lt(lit(3)), col("c1_non_null")),
);
let expected = col("c2_non_null").lt(lit(3));
assert_eq!(simplify(expr), expected);
}
#[test]
fn test_simplify_bitwise_or_and() {
// (c2 < 3) | ((c2 < 3) & c1) -> (c2 < 3)
let expr = bitwise_or(
col("c2_non_null").lt(lit(3)),
bitwise_and(col("c2_non_null").lt(lit(3)), col("c1_non_null")),
);
let expected = col("c2_non_null").lt(lit(3));
assert_eq!(simplify(expr), expected);
}
#[test]
fn test_simplify_simple_bitwise_and() {
// (c2 > 5) & (c2 > 5) -> (c2 > 5)
let expr = (col("c2").gt(lit(5))).bitand(col("c2").gt(lit(5)));
let expected = col("c2").gt(lit(5));
assert_eq!(simplify(expr), expected);
}
#[test]
fn test_simplify_simple_bitwise_or() {
// (c2 > 5) | (c2 > 5) -> (c2 > 5)
let expr = (col("c2").gt(lit(5))).bitor(col("c2").gt(lit(5)));
let expected = col("c2").gt(lit(5));
assert_eq!(simplify(expr), expected);
}
#[test]
fn test_simplify_simple_bitwise_xor() {
// c4 ^ c4 -> 0
let expr = (col("c4")).bitxor(col("c4"));
let expected = lit(0u32);
assert_eq!(simplify(expr), expected);
// c3 ^ c3 -> 0
let expr = col("c3").bitxor(col("c3"));
let expected = lit(0i64);
assert_eq!(simplify(expr), expected);
}
#[test]
#[should_panic(
expected = "called `Result::unwrap()` on an `Err` value: ArrowError(DivideByZero)"
)]
fn test_simplify_modulo_by_zero_non_null() {
let expr = col("c2_non_null") % lit(0);
simplify(expr);
}
#[test]
fn test_simplify_simple_and() {
// (c2 > 5) AND (c2 > 5) -> (c2 > 5)
let expr = (col("c2").gt(lit(5))).and(col("c2").gt(lit(5)));
let expected = col("c2").gt(lit(5));
assert_eq!(simplify(expr), expected);
}
#[test]
fn test_simplify_composed_and() {
// ((c2 > 5) AND (c1 < 6)) AND (c2 > 5)
let expr = and(
and(col("c2").gt(lit(5)), col("c1").lt(lit(6))),
col("c2").gt(lit(5)),
);
let expected = and(col("c2").gt(lit(5)), col("c1").lt(lit(6)));
assert_eq!(simplify(expr), expected);
}
#[test]
fn test_simplify_negated_and() {
// (c2 > 5) AND !(c2 > 5) --> (c2 > 5) AND (c2 <= 5)
let expr = and(col("c2").gt(lit(5)), Expr::not(col("c2").gt(lit(5))));
let expected = col("c2").gt(lit(5)).and(col("c2").lt_eq(lit(5)));
assert_eq!(simplify(expr), expected);
}
#[test]
fn test_simplify_or_and() {
let l = col("c2").gt(lit(5));
let r = and(col("c1").lt(lit(6)), col("c2").gt(lit(5)));
// (c2 > 5) OR ((c1 < 6) AND (c2 > 5))
let expr = or(l.clone(), r.clone());
// no rewrites if c1 can be null
let expected = expr.clone();
assert_eq!(simplify(expr), expected);
// ((c1 < 6) AND (c2 > 5)) OR (c2 > 5)
let expr = or(l, r);
// no rewrites if c1 can be null
let expected = expr.clone();
assert_eq!(simplify(expr), expected);
}
#[test]
fn test_simplify_or_and_non_null() {
let l = col("c2_non_null").gt(lit(5));
let r = and(col("c1_non_null").lt(lit(6)), col("c2_non_null").gt(lit(5)));
// (c2 > 5) OR ((c1 < 6) AND (c2 > 5)) --> c2 > 5
let expr = or(l.clone(), r.clone());
// This is only true if `c1 < 6` is not nullable / can not be null.
let expected = col("c2_non_null").gt(lit(5));
assert_eq!(simplify(expr), expected);
// ((c1 < 6) AND (c2 > 5)) OR (c2 > 5) --> c2 > 5
let expr = or(l, r);
assert_eq!(simplify(expr), expected);
}
#[test]
fn test_simplify_and_or() {
let l = col("c2").gt(lit(5));
let r = or(col("c1").lt(lit(6)), col("c2").gt(lit(5)));
// (c2 > 5) AND ((c1 < 6) OR (c2 > 5)) --> c2 > 5
let expr = and(l.clone(), r.clone());
// no rewrites if c1 can be null
let expected = expr.clone();
assert_eq!(simplify(expr), expected);
// ((c1 < 6) OR (c2 > 5)) AND (c2 > 5) --> c2 > 5
let expr = and(l, r);
let expected = expr.clone();
assert_eq!(simplify(expr), expected);
}
#[test]
fn test_simplify_and_or_non_null() {
let l = col("c2_non_null").gt(lit(5));
let r = or(col("c1_non_null").lt(lit(6)), col("c2_non_null").gt(lit(5)));
// (c2 > 5) AND ((c1 < 6) OR (c2 > 5)) --> c2 > 5
let expr = and(l.clone(), r.clone());
// This is only true if `c1 < 6` is not nullable / can not be null.
let expected = col("c2_non_null").gt(lit(5));
assert_eq!(simplify(expr), expected);
// ((c1 < 6) OR (c2 > 5)) AND (c2 > 5) --> c2 > 5
let expr = and(l, r);
assert_eq!(simplify(expr), expected);
}
#[test]
fn test_simplify_by_de_morgan_laws() {
// Laws with logical operations
// !(c3 AND c4) --> !c3 OR !c4
let expr = and(col("c3"), col("c4")).not();
let expected = or(col("c3").not(), col("c4").not());
assert_eq!(simplify(expr), expected);
// !(c3 OR c4) --> !c3 AND !c4
let expr = or(col("c3"), col("c4")).not();
let expected = and(col("c3").not(), col("c4").not());
assert_eq!(simplify(expr), expected);
// !(!c3) --> c3
let expr = col("c3").not().not();
let expected = col("c3");
assert_eq!(simplify(expr), expected);
// Laws with bitwise operations
// !(c3 & c4) --> !c3 | !c4
let expr = -bitwise_and(col("c3"), col("c4"));
let expected = bitwise_or(-col("c3"), -col("c4"));
assert_eq!(simplify(expr), expected);
// !(c3 | c4) --> !c3 & !c4
let expr = -bitwise_or(col("c3"), col("c4"));
let expected = bitwise_and(-col("c3"), -col("c4"));
assert_eq!(simplify(expr), expected);
// !(!c3) --> c3
let expr = -(-col("c3"));
let expected = col("c3");
assert_eq!(simplify(expr), expected);
}
#[test]
fn test_simplify_null_and_false() {
let expr = and(lit_bool_null(), lit(false));
let expr_eq = lit(false);
assert_eq!(simplify(expr), expr_eq);
}
#[test]
fn test_simplify_divide_null_by_null() {
let null = lit(ScalarValue::Int32(None));
let expr_plus = null.clone() / null.clone();
let expr_eq = null;
assert_eq!(simplify(expr_plus), expr_eq);
}
#[test]
fn test_simplify_simplify_arithmetic_expr() {
let expr_plus = lit(1) + lit(1);
assert_eq!(simplify(expr_plus), lit(2));
}
#[test]
fn test_simplify_simplify_eq_expr() {
let expr_eq = binary_expr(lit(1), Operator::Eq, lit(1));
assert_eq!(simplify(expr_eq), lit(true));
}
#[test]
fn test_simplify_log() {
// Log(c3, 1) ===> 0
{
let expr = log(col("c3_non_null"), lit(1));
let expected = lit(0i64);
assert_eq!(simplify(expr), expected);
}
// Log(c3, c3) ===> 1
{
let expr = log(col("c3_non_null"), col("c3_non_null"));
let expected = lit(1i64);
assert_eq!(simplify(expr), expected);
}
// Log(c3, Power(c3, c4)) ===> c4
{
let expr = log(
col("c3_non_null"),
power(col("c3_non_null"), col("c4_non_null")),
);
let expected = col("c4_non_null");
assert_eq!(simplify(expr), expected);
}
// Log(c3, c4) ===> Log(c3, c4)
{
let expr = log(col("c3_non_null"), col("c4_non_null"));
let expected = log(col("c3_non_null"), col("c4_non_null"));
assert_eq!(simplify(expr), expected);
}
}
#[test]
fn test_simplify_power() {
// Power(c3, 0) ===> 1
{
let expr = power(col("c3_non_null"), lit(0));
let expected = lit(1i64);
assert_eq!(simplify(expr), expected);
}
// Power(c3, 1) ===> c3
{
let expr = power(col("c3_non_null"), lit(1));
let expected = col("c3_non_null");
assert_eq!(simplify(expr), expected);
}
// Power(c3, Log(c3, c4)) ===> c4
{
let expr = power(
col("c3_non_null"),
log(col("c3_non_null"), col("c4_non_null")),
);
let expected = col("c4_non_null");
assert_eq!(simplify(expr), expected);
}
// Power(c3, c4) ===> Power(c3, c4)
{
let expr = power(col("c3_non_null"), col("c4_non_null"));
let expected = power(col("c3_non_null"), col("c4_non_null"));
assert_eq!(simplify(expr), expected);
}
}
#[test]
fn test_simplify_concat_ws() {
let null = lit(ScalarValue::Utf8(None));
// the delimiter is not a literal
{
let expr = concat_ws(col("c"), vec![lit("a"), null.clone(), lit("b")]);
let expected = concat_ws(col("c"), vec![lit("a"), lit("b")]);
assert_eq!(simplify(expr), expected);
}
// the delimiter is an empty string
{
let expr = concat_ws(lit(""), vec![col("a"), lit("c"), lit("b")]);
let expected = concat(&[col("a"), lit("cb")]);
assert_eq!(simplify(expr), expected);
}
// the delimiter is a not-empty string
{
let expr = concat_ws(
lit("-"),
vec![
null.clone(),
col("c0"),
lit("hello"),
null.clone(),
lit("rust"),
col("c1"),
lit(""),
lit(""),
null,
],
);
let expected = concat_ws(
lit("-"),
vec![col("c0"), lit("hello-rust"), col("c1"), lit("-")],
);
assert_eq!(simplify(expr), expected)
}
}
#[test]
fn test_simplify_concat_ws_with_null() {
let null = lit(ScalarValue::Utf8(None));
// null delimiter -> null
{
let expr = concat_ws(null.clone(), vec![col("c1"), col("c2")]);
assert_eq!(simplify(expr), null);
}
// filter out null args
{
let expr = concat_ws(lit("|"), vec![col("c1"), null.clone(), col("c2")]);
let expected = concat_ws(lit("|"), vec![col("c1"), col("c2")]);
assert_eq!(simplify(expr), expected);
}
// nested test
{
let sub_expr = concat_ws(null.clone(), vec![col("c1"), col("c2")]);
let expr = concat_ws(lit("|"), vec![sub_expr, col("c3")]);
assert_eq!(simplify(expr), concat_ws(lit("|"), vec![col("c3")]));
}
// null delimiter (nested)
{
let sub_expr = concat_ws(null.clone(), vec![col("c1"), col("c2")]);
let expr = concat_ws(sub_expr, vec![col("c3"), col("c4")]);
assert_eq!(simplify(expr), null);
}
}
#[test]
fn test_simplify_concat() {
let null = lit(ScalarValue::Utf8(None));
let expr = concat(&[
null.clone(),
col("c0"),
lit("hello "),
null.clone(),
lit("rust"),
col("c1"),
lit(""),
null,
]);
let expected = concat(&[col("c0"), lit("hello rust"), col("c1")]);
assert_eq!(simplify(expr), expected)
}
#[test]
fn test_simplify_regex() {
// malformed regex
assert_contains!(
try_simplify(regex_match(col("c1"), lit("foo{")))
.unwrap_err()
.to_string(),
"regex parse error"
);
// unsupported cases
assert_no_change(regex_match(col("c1"), lit("foo.*")));
assert_no_change(regex_match(col("c1"), lit("(foo)")));
assert_no_change(regex_match(col("c1"), lit("^foo")));
assert_no_change(regex_match(col("c1"), lit("foo$")));
assert_no_change(regex_match(col("c1"), lit("%")));
assert_no_change(regex_match(col("c1"), lit("_")));
assert_no_change(regex_match(col("c1"), lit("f%o")));
assert_no_change(regex_match(col("c1"), lit("f_o")));
// empty cases
assert_change(regex_match(col("c1"), lit("")), lit(true));
assert_change(regex_not_match(col("c1"), lit("")), lit(false));
assert_change(regex_imatch(col("c1"), lit("")), lit(true));
assert_change(regex_not_imatch(col("c1"), lit("")), lit(false));
// single character
assert_change(regex_match(col("c1"), lit("x")), like(col("c1"), "%x%"));
// single word
assert_change(regex_match(col("c1"), lit("foo")), like(col("c1"), "%foo%"));
// regular expressions that match an exact literal
assert_change(regex_match(col("c1"), lit("^$")), col("c1").eq(lit("")));
assert_change(
regex_not_match(col("c1"), lit("^$")),
col("c1").not_eq(lit("")),
);
assert_change(
regex_match(col("c1"), lit("^foo$")),
col("c1").eq(lit("foo")),
);
assert_change(
regex_not_match(col("c1"), lit("^foo$")),
col("c1").not_eq(lit("foo")),
);
// regular expressions that match exact captured literals
assert_change(
regex_match(col("c1"), lit("^(foo|bar)$")),
col("c1").eq(lit("foo")).or(col("c1").eq(lit("bar"))),
);
assert_change(
regex_not_match(col("c1"), lit("^(foo|bar)$")),
col("c1")
.not_eq(lit("foo"))
.and(col("c1").not_eq(lit("bar"))),
);
assert_change(
regex_match(col("c1"), lit("^(foo)$")),
col("c1").eq(lit("foo")),
);
assert_change(
regex_match(col("c1"), lit("^(foo|bar|baz)$")),
((col("c1").eq(lit("foo"))).or(col("c1").eq(lit("bar"))))
.or(col("c1").eq(lit("baz"))),
);
assert_change(
regex_match(col("c1"), lit("^(foo|bar|baz|qux)$")),
col("c1")
.in_list(vec![lit("foo"), lit("bar"), lit("baz"), lit("qux")], false),
);
assert_change(
regex_match(col("c1"), lit("^(fo_o)$")),
col("c1").eq(lit("fo_o")),
);
assert_change(
regex_match(col("c1"), lit("^(fo_o)$")),
col("c1").eq(lit("fo_o")),
);
assert_change(
regex_match(col("c1"), lit("^(fo_o|ba_r)$")),
col("c1").eq(lit("fo_o")).or(col("c1").eq(lit("ba_r"))),
);
assert_change(
regex_not_match(col("c1"), lit("^(fo_o|ba_r)$")),
col("c1")
.not_eq(lit("fo_o"))
.and(col("c1").not_eq(lit("ba_r"))),
);
assert_change(
regex_match(col("c1"), lit("^(fo_o|ba_r|ba_z)$")),
((col("c1").eq(lit("fo_o"))).or(col("c1").eq(lit("ba_r"))))
.or(col("c1").eq(lit("ba_z"))),
);
assert_change(
regex_match(col("c1"), lit("^(fo_o|ba_r|baz|qu_x)$")),
col("c1").in_list(
vec![lit("fo_o"), lit("ba_r"), lit("baz"), lit("qu_x")],
false,
),
);
// regular expressions that mismatch captured literals
assert_no_change(regex_match(col("c1"), lit("(foo|bar)")));
assert_no_change(regex_match(col("c1"), lit("(foo|bar)*")));
assert_no_change(regex_match(col("c1"), lit("(fo_o|b_ar)")));
assert_no_change(regex_match(col("c1"), lit("(foo|ba_r)*")));
assert_no_change(regex_match(col("c1"), lit("(fo_o|ba_r)*")));
assert_no_change(regex_match(col("c1"), lit("^(foo|bar)*")));
assert_no_change(regex_match(col("c1"), lit("^foo|bar$")));
assert_no_change(regex_match(col("c1"), lit("^(foo)(bar)$")));
assert_no_change(regex_match(col("c1"), lit("^")));
assert_no_change(regex_match(col("c1"), lit("$")));
assert_no_change(regex_match(col("c1"), lit("$^")));
assert_no_change(regex_match(col("c1"), lit("$foo^")));
// OR-chain
assert_change(
regex_match(col("c1"), lit("foo|bar|baz")),
like(col("c1"), "%foo%")
.or(like(col("c1"), "%bar%"))
.or(like(col("c1"), "%baz%")),
);
assert_change(
regex_match(col("c1"), lit("foo|x|baz")),
like(col("c1"), "%foo%")
.or(like(col("c1"), "%x%"))
.or(like(col("c1"), "%baz%")),
);
assert_change(
regex_not_match(col("c1"), lit("foo|bar|baz")),
not_like(col("c1"), "%foo%")
.and(not_like(col("c1"), "%bar%"))
.and(not_like(col("c1"), "%baz%")),
);
// both anchored expressions (translated to equality) and unanchored
assert_change(
regex_match(col("c1"), lit("foo|^x$|baz")),
like(col("c1"), "%foo%")
.or(col("c1").eq(lit("x")))
.or(like(col("c1"), "%baz%")),
);
assert_change(
regex_not_match(col("c1"), lit("foo|^bar$|baz")),
not_like(col("c1"), "%foo%")
.and(col("c1").not_eq(lit("bar")))
.and(not_like(col("c1"), "%baz%")),
);
// Too many patterns (MAX_REGEX_ALTERNATIONS_EXPANSION)
assert_no_change(regex_match(col("c1"), lit("foo|bar|baz|blarg|bozo|etc")));
}
#[track_caller]
fn assert_no_change(expr: Expr) {
let optimized = simplify(expr.clone());
assert_eq!(expr, optimized);
}
#[track_caller]
fn assert_change(expr: Expr, expected: Expr) {
let optimized = simplify(expr);
assert_eq!(optimized, expected);
}
fn regex_match(left: Expr, right: Expr) -> Expr {
Expr::BinaryExpr(BinaryExpr {
left: Box::new(left),
op: Operator::RegexMatch,
right: Box::new(right),
})
}
fn regex_not_match(left: Expr, right: Expr) -> Expr {
Expr::BinaryExpr(BinaryExpr {
left: Box::new(left),
op: Operator::RegexNotMatch,
right: Box::new(right),
})
}
fn regex_imatch(left: Expr, right: Expr) -> Expr {
Expr::BinaryExpr(BinaryExpr {
left: Box::new(left),
op: Operator::RegexIMatch,
right: Box::new(right),
})
}
fn regex_not_imatch(left: Expr, right: Expr) -> Expr {
Expr::BinaryExpr(BinaryExpr {
left: Box::new(left),
op: Operator::RegexNotIMatch,
right: Box::new(right),
})
}
fn like(expr: Expr, pattern: &str) -> Expr {
Expr::Like(Like {
negated: false,
expr: Box::new(expr),
pattern: Box::new(lit(pattern)),
escape_char: None,
case_insensitive: false,
})
}
fn not_like(expr: Expr, pattern: &str) -> Expr {
Expr::Like(Like {
negated: true,
expr: Box::new(expr),
pattern: Box::new(lit(pattern)),
escape_char: None,
case_insensitive: false,
})
}
fn ilike(expr: Expr, pattern: &str) -> Expr {
Expr::Like(Like {
negated: false,
expr: Box::new(expr),
pattern: Box::new(lit(pattern)),
escape_char: None,
case_insensitive: true,
})
}
fn not_ilike(expr: Expr, pattern: &str) -> Expr {
Expr::Like(Like {
negated: true,
expr: Box::new(expr),
pattern: Box::new(lit(pattern)),
escape_char: None,
case_insensitive: true,
})
}
// ------------------------------
// ----- Simplifier tests -------
// ------------------------------
fn try_simplify(expr: Expr) -> Result<Expr> {
let schema = expr_test_schema();
let execution_props = ExecutionProps::new();
let simplifier = ExprSimplifier::new(
SimplifyContext::new(&execution_props).with_schema(schema),
);
simplifier.simplify(expr)
}
fn simplify(expr: Expr) -> Expr {
try_simplify(expr).unwrap()
}
fn expr_test_schema() -> DFSchemaRef {
Arc::new(
DFSchema::new_with_metadata(
vec![
DFField::new_unqualified("c1", DataType::Utf8, true),
DFField::new_unqualified("c2", DataType::Boolean, true),
DFField::new_unqualified("c3", DataType::Int64, true),
DFField::new_unqualified("c4", DataType::UInt32, true),
DFField::new_unqualified("c1_non_null", DataType::Utf8, false),
DFField::new_unqualified("c2_non_null", DataType::Boolean, false),
DFField::new_unqualified("c3_non_null", DataType::Int64, false),
DFField::new_unqualified("c4_non_null", DataType::UInt32, false),
],
HashMap::new(),
)
.unwrap(),
)
}
#[test]
fn simplify_expr_null_comparison() {
// x = null is always null
assert_eq!(
simplify(lit(true).eq(lit(ScalarValue::Boolean(None)))),
lit(ScalarValue::Boolean(None)),
);
// null != null is always null
assert_eq!(
simplify(
lit(ScalarValue::Boolean(None)).not_eq(lit(ScalarValue::Boolean(None)))
),
lit(ScalarValue::Boolean(None)),
);
// x != null is always null
assert_eq!(
simplify(col("c2").not_eq(lit(ScalarValue::Boolean(None)))),
lit(ScalarValue::Boolean(None)),
);
// null = x is always null
assert_eq!(
simplify(lit(ScalarValue::Boolean(None)).eq(col("c2"))),
lit(ScalarValue::Boolean(None)),
);
}
#[test]
fn simplify_expr_is_not_null() {
assert_eq!(
simplify(Expr::IsNotNull(Box::new(col("c1")))),
Expr::IsNotNull(Box::new(col("c1")))
);
// 'c1_non_null IS NOT NULL' is always true
assert_eq!(
simplify(Expr::IsNotNull(Box::new(col("c1_non_null")))),
lit(true)
);
}
#[test]
fn simplify_expr_is_null() {
assert_eq!(
simplify(Expr::IsNull(Box::new(col("c1")))),
Expr::IsNull(Box::new(col("c1")))
);
// 'c1_non_null IS NULL' is always false
assert_eq!(
simplify(Expr::IsNull(Box::new(col("c1_non_null")))),
lit(false)
);
}
#[test]
fn simplify_expr_is_unknown() {
assert_eq!(simplify(col("c2").is_unknown()), col("c2").is_unknown(),);
// 'c2_non_null is unknown' is always false
assert_eq!(simplify(col("c2_non_null").is_unknown()), lit(false));
}
#[test]
fn simplify_expr_is_not_known() {
assert_eq!(
simplify(col("c2").is_not_unknown()),
col("c2").is_not_unknown()
);
// 'c2_non_null is not unknown' is always true
assert_eq!(simplify(col("c2_non_null").is_not_unknown()), lit(true));
}
#[test]
fn simplify_expr_eq() {
let schema = expr_test_schema();
assert_eq!(col("c2").get_type(&schema).unwrap(), DataType::Boolean);
// true = true -> true
assert_eq!(simplify(lit(true).eq(lit(true))), lit(true));
// true = false -> false
assert_eq!(simplify(lit(true).eq(lit(false))), lit(false),);
// c2 = true -> c2
assert_eq!(simplify(col("c2").eq(lit(true))), col("c2"));
// c2 = false => !c2
assert_eq!(simplify(col("c2").eq(lit(false))), col("c2").not(),);
}
#[test]
fn simplify_expr_eq_skip_nonboolean_type() {
let schema = expr_test_schema();
// When one of the operand is not of boolean type, folding the
// other boolean constant will change return type of
// expression to non-boolean.
//
// Make sure c1 column to be used in tests is not boolean type
assert_eq!(col("c1").get_type(&schema).unwrap(), DataType::Utf8);
// don't fold c1 = foo
assert_eq!(simplify(col("c1").eq(lit("foo"))), col("c1").eq(lit("foo")),);
}
#[test]
fn simplify_expr_not_eq() {
let schema = expr_test_schema();
assert_eq!(col("c2").get_type(&schema).unwrap(), DataType::Boolean);
// c2 != true -> !c2
assert_eq!(simplify(col("c2").not_eq(lit(true))), col("c2").not(),);
// c2 != false -> c2
assert_eq!(simplify(col("c2").not_eq(lit(false))), col("c2"),);
// test constant
assert_eq!(simplify(lit(true).not_eq(lit(true))), lit(false),);
assert_eq!(simplify(lit(true).not_eq(lit(false))), lit(true),);
}
#[test]
fn simplify_expr_not_eq_skip_nonboolean_type() {
let schema = expr_test_schema();
// when one of the operand is not of boolean type, folding the
// other boolean constant will change return type of
// expression to non-boolean.
assert_eq!(col("c1").get_type(&schema).unwrap(), DataType::Utf8);
assert_eq!(
simplify(col("c1").not_eq(lit("foo"))),
col("c1").not_eq(lit("foo")),
);
}
#[test]
fn simplify_expr_case_when_then_else() {
// CASE WHEN c2 != false THEN "ok" == "not_ok" ELSE c2 == true
// -->
// CASE WHEN c2 THEN false ELSE c2
// -->
// false
assert_eq!(
simplify(Expr::Case(Case::new(
None,
vec![(
Box::new(col("c2").not_eq(lit(false))),
Box::new(lit("ok").eq(lit("not_ok"))),
)],
Some(Box::new(col("c2").eq(lit(true)))),
))),
col("c2").not().and(col("c2")) // #1716
);
// CASE WHEN c2 != false THEN "ok" == "ok" ELSE c2
// -->
// CASE WHEN c2 THEN true ELSE c2
// -->
// c2
//
// Need to call simplify 2x due to
// https://github.com/apache/arrow-datafusion/issues/1160
assert_eq!(
simplify(simplify(Expr::Case(Case::new(
None,
vec![(
Box::new(col("c2").not_eq(lit(false))),
Box::new(lit("ok").eq(lit("ok"))),
)],
Some(Box::new(col("c2").eq(lit(true)))),
)))),
col("c2").or(col("c2").not().and(col("c2"))) // #1716
);
// CASE WHEN ISNULL(c2) THEN true ELSE c2
// -->
// ISNULL(c2) OR c2
//
// Need to call simplify 2x due to
// https://github.com/apache/arrow-datafusion/issues/1160
assert_eq!(
simplify(simplify(Expr::Case(Case::new(
None,
vec![(Box::new(col("c2").is_null()), Box::new(lit(true)),)],
Some(Box::new(col("c2"))),
)))),
col("c2")
.is_null()
.or(col("c2").is_not_null().and(col("c2")))
);
// CASE WHEN c1 then true WHEN c2 then false ELSE true
// --> c1 OR (NOT(c1) AND c2 AND FALSE) OR (NOT(c1 OR c2) AND TRUE)
// --> c1 OR (NOT(c1) AND NOT(c2))
// --> c1 OR NOT(c2)
//
// Need to call simplify 2x due to
// https://github.com/apache/arrow-datafusion/issues/1160
assert_eq!(
simplify(simplify(Expr::Case(Case::new(
None,
vec![
(Box::new(col("c1")), Box::new(lit(true)),),
(Box::new(col("c2")), Box::new(lit(false)),),
],
Some(Box::new(lit(true))),
)))),
col("c1").or(col("c1").not().and(col("c2").not()))
);
// CASE WHEN c1 then true WHEN c2 then true ELSE false
// --> c1 OR (NOT(c1) AND c2 AND TRUE) OR (NOT(c1 OR c2) AND FALSE)
// --> c1 OR (NOT(c1) AND c2)
// --> c1 OR c2
//
// Need to call simplify 2x due to
// https://github.com/apache/arrow-datafusion/issues/1160
assert_eq!(
simplify(simplify(Expr::Case(Case::new(
None,
vec![
(Box::new(col("c1")), Box::new(lit(true)),),
(Box::new(col("c2")), Box::new(lit(false)),),
],
Some(Box::new(lit(true))),
)))),
col("c1").or(col("c1").not().and(col("c2").not()))
);
}
#[test]
fn simplify_expr_bool_or() {
// col || true is always true
assert_eq!(simplify(col("c2").or(lit(true))), lit(true),);
// col || false is always col
assert_eq!(simplify(col("c2").or(lit(false))), col("c2"),);
// true || null is always true
assert_eq!(simplify(lit(true).or(lit_bool_null())), lit(true),);
// null || true is always true
assert_eq!(simplify(lit_bool_null().or(lit(true))), lit(true),);
// false || null is always null
assert_eq!(simplify(lit(false).or(lit_bool_null())), lit_bool_null(),);
// null || false is always null
assert_eq!(simplify(lit_bool_null().or(lit(false))), lit_bool_null(),);
// ( c1 BETWEEN Int32(0) AND Int32(10) ) OR Boolean(NULL)
// it can be either NULL or TRUE depending on the value of `c1 BETWEEN Int32(0) AND Int32(10)`
// and should not be rewritten
let expr = col("c1").between(lit(0), lit(10));
let expr = expr.or(lit_bool_null());
let result = simplify(expr);
let expected_expr = or(
and(col("c1").gt_eq(lit(0)), col("c1").lt_eq(lit(10))),
lit_bool_null(),
);
assert_eq!(expected_expr, result);
}
#[test]
fn simplify_inlist() {
assert_eq!(simplify(in_list(col("c1"), vec![], false)), lit(false));
assert_eq!(simplify(in_list(col("c1"), vec![], true)), lit(true));
assert_eq!(
simplify(in_list(col("c1"), vec![lit(1)], false)),
col("c1").eq(lit(1))
);
assert_eq!(
simplify(in_list(col("c1"), vec![lit(1)], true)),
col("c1").not_eq(lit(1))
);
// more complex expressions can be simplified if list contains
// one element only
assert_eq!(
simplify(in_list(col("c1") * lit(10), vec![lit(2)], false)),
(col("c1") * lit(10)).eq(lit(2))
);
assert_eq!(
simplify(in_list(col("c1"), vec![lit(1), lit(2)], false)),
col("c1").eq(lit(1)).or(col("c1").eq(lit(2)))
);
assert_eq!(
simplify(in_list(col("c1"), vec![lit(1), lit(2)], true)),
col("c1").not_eq(lit(1)).and(col("c1").not_eq(lit(2)))
);
let subquery = Arc::new(test_table_scan_with_name("test").unwrap());
assert_eq!(
simplify(in_list(
col("c1"),
vec![scalar_subquery(subquery.clone())],
false
)),
in_subquery(col("c1"), subquery.clone())
);
assert_eq!(
simplify(in_list(
col("c1"),
vec![scalar_subquery(subquery.clone())],
true
)),
not_in_subquery(col("c1"), subquery)
);
let subquery1 =
scalar_subquery(Arc::new(test_table_scan_with_name("test1").unwrap()));
let subquery2 =
scalar_subquery(Arc::new(test_table_scan_with_name("test2").unwrap()));
// c1 NOT IN (<subquery1>, <subquery2>) -> c1 != <subquery1> AND c1 != <subquery2>
assert_eq!(
simplify(in_list(
col("c1"),
vec![subquery1.clone(), subquery2.clone()],
true
)),
col("c1")
.not_eq(subquery1.clone())
.and(col("c1").not_eq(subquery2.clone()))
);
// c1 IN (<subquery1>, <subquery2>) -> c1 == <subquery1> OR c1 == <subquery2>
assert_eq!(
simplify(in_list(
col("c1"),
vec![subquery1.clone(), subquery2.clone()],
false
)),
col("c1").eq(subquery1).or(col("c1").eq(subquery2))
);
// c1 NOT IN (1, 2, 3, 4) OR c1 NOT IN (5, 6, 7, 8) ->
// c1 NOT IN (1, 2, 3, 4) OR c1 NOT IN (5, 6, 7, 8)
let expr = in_list(col("c1"), vec![lit(1), lit(2), lit(3), lit(4)], true).or(
in_list(col("c1"), vec![lit(5), lit(6), lit(7), lit(8)], true),
);
assert_eq!(simplify(expr.clone()), expr);
}
#[test]
fn simplify_large_or() {
let expr = (0..5)
.map(|i| col("c1").eq(lit(i)))
.fold(lit(false), |acc, e| acc.or(e));
assert_eq!(
simplify(expr),
in_list(col("c1"), (0..5).map(lit).collect(), false),
);
}
#[test]
fn simplify_expr_bool_and() {
// col & true is always col
assert_eq!(simplify(col("c2").and(lit(true))), col("c2"),);
// col & false is always false
assert_eq!(simplify(col("c2").and(lit(false))), lit(false),);
// true && null is always null
assert_eq!(simplify(lit(true).and(lit_bool_null())), lit_bool_null(),);
// null && true is always null
assert_eq!(simplify(lit_bool_null().and(lit(true))), lit_bool_null(),);
// false && null is always false
assert_eq!(simplify(lit(false).and(lit_bool_null())), lit(false),);
// null && false is always false
assert_eq!(simplify(lit_bool_null().and(lit(false))), lit(false),);
// c1 BETWEEN Int32(0) AND Int32(10) AND Boolean(NULL)
// it can be either NULL or FALSE depending on the value of `c1 BETWEEN Int32(0) AND Int32(10)`
// and the Boolean(NULL) should remain
let expr = col("c1").between(lit(0), lit(10));
let expr = expr.and(lit_bool_null());
let result = simplify(expr);
let expected_expr = and(
and(col("c1").gt_eq(lit(0)), col("c1").lt_eq(lit(10))),
lit_bool_null(),
);
assert_eq!(expected_expr, result);
}
#[test]
fn simplify_expr_between() {
// c2 between 3 and 4 is c2 >= 3 and c2 <= 4
let expr = col("c2").between(lit(3), lit(4));
assert_eq!(
simplify(expr),
and(col("c2").gt_eq(lit(3)), col("c2").lt_eq(lit(4)))
);
// c2 not between 3 and 4 is c2 < 3 or c2 > 4
let expr = col("c2").not_between(lit(3), lit(4));
assert_eq!(
simplify(expr),
or(col("c2").lt(lit(3)), col("c2").gt(lit(4)))
);
}
#[test]
fn test_like_and_ilke() {
// test non-null values
let expr = like(col("c1"), "%");
assert_eq!(simplify(expr), lit(true));
let expr = not_like(col("c1"), "%");
assert_eq!(simplify(expr), lit(false));
let expr = ilike(col("c1"), "%");
assert_eq!(simplify(expr), lit(true));
let expr = not_ilike(col("c1"), "%");
assert_eq!(simplify(expr), lit(false));
// test null values
let null = lit(ScalarValue::Utf8(None));
let expr = like(null.clone(), "%");
assert_eq!(simplify(expr), lit_bool_null());
let expr = not_like(null.clone(), "%");
assert_eq!(simplify(expr), lit_bool_null());
let expr = ilike(null.clone(), "%");
assert_eq!(simplify(expr), lit_bool_null());
let expr = not_ilike(null, "%");
assert_eq!(simplify(expr), lit_bool_null());
}
}