1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254
|
/* Copyright (c) 2015, 2025, Oracle and/or its affiliates.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License, version 2.0,
as published by the Free Software Foundation.
This program is designed to work with certain software (including
but not limited to OpenSSL) that is licensed under separate terms,
as designated in a particular file or component or in included license
documentation. The authors of MySQL hereby grant you an additional
permission to link the program and your derivative works with the
separately licensed software that they have either included with
the program or referenced in the documentation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License, version 2.0, for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
// JSON function items.
#include "sql/item_json_func.h"
#include <assert.h>
#include <stdint.h>
#include <string.h>
#include <algorithm> // std::fill
#include <cassert>
#include <limits>
#include <memory>
#include <new>
#include <string>
#include <utility>
#include "decimal.h"
#include "field_types.h" // enum_field_types
#include "lex_string.h"
#include "m_ctype.h"
#include "m_string.h"
#include "my_alloc.h"
#include "my_sys.h"
#include "mysql/mysql_lex_string.h"
#include "mysqld_error.h"
#include "prealloced_array.h" // Prealloced_array
#include "scope_guard.h"
#include "sql-common/json_dom.h"
#include "sql-common/json_path.h"
#include "sql-common/json_syntax_check.h"
#include "sql/current_thd.h" // current_thd
#include "sql/error_handler.h"
#include "sql/field.h"
#include "sql/item_cmpfunc.h" // Item_func_like
#include "sql/item_create.h"
#include "sql/item_subselect.h"
#include "sql/json_diff.h"
#include "sql/json_schema.h"
#include "sql/my_decimal.h"
#include "sql/parser_yystype.h"
#include "sql/psi_memory_key.h" // key_memory_JSON
#include "sql/sql_class.h" // THD
#include "sql/sql_const.h"
#include "sql/sql_error.h"
#include "sql/sql_exception_handler.h" // handle_std_exception
#include "sql/sql_time.h" // field_type_to_timestamp_type
#include "sql/system_variables.h"
#include "sql/table.h"
#include "sql/table_function.h"
#include "sql/thd_raii.h"
#include "sql/thr_malloc.h"
#include "template_utils.h" // down_cast
class PT_item_list;
/** Helper routines */
bool ensure_utf8mb4(const String &val, String *buf, const char **resptr,
size_t *reslength, bool require_string) {
const CHARSET_INFO *cs = val.charset();
if (cs == &my_charset_bin) {
if (require_string)
my_error(ER_INVALID_JSON_CHARSET, MYF(0), my_charset_bin.csname);
return true;
}
const char *s = val.ptr();
size_t ss = val.length();
if (my_charset_same(cs, &my_charset_utf8mb4_bin) ||
my_charset_same(cs, &my_charset_utf8mb3_bin) ||
!std::strcmp(cs->csname, "ascii")) {
/*
Character data is directly converted to JSON if the character
set is utf8mb4 or a subset.
*/
} else { // If not, we convert, possibly with loss (best effort).
uint dummy_errors;
if (buf->copy(val.ptr(), val.length(), val.charset(),
&my_charset_utf8mb4_bin, &dummy_errors)) {
return true; /* purecov: inspected */
}
assert(buf->charset() == &my_charset_utf8mb4_bin);
s = buf->ptr();
ss = buf->length();
}
*resptr = s;
*reslength = ss;
return false;
}
/**
Parse a JSON dom out of an argument to a JSON function.
@param[in] res Pointer to string value of arg.
@param[in,out] dom If non-null, we want any text parsed DOM
returned at the location pointed to
@param[in] require_str_or_json If true, generate an error if other types
used as input
@param[in] error_handler Pointer to a function that should handle
reporting of parsing error.
@param[in] depth_handler Pointer to a function that should handle error
occurred when depth is exceeded.
@returns false if the arg parsed as valid JSON, true otherwise
*/
bool parse_json(const String &res, Json_dom_ptr *dom, bool require_str_or_json,
const JsonParseErrorHandler &error_handler,
const JsonDocumentDepthHandler &depth_handler) {
char buff[MAX_FIELD_WIDTH];
String utf8_res(buff, sizeof(buff), &my_charset_utf8mb4_bin);
const char *safep; // contents of res, possibly converted
size_t safe_length; // length of safep
if (ensure_utf8mb4(res, &utf8_res, &safep, &safe_length,
require_str_or_json)) {
return true;
}
if (!dom) {
assert(!require_str_or_json);
return !is_valid_json_syntax(safep, safe_length, nullptr, nullptr,
depth_handler);
}
*dom = Json_dom::parse(safep, safe_length, error_handler, depth_handler);
return *dom == nullptr;
}
/**
Get correct blob type of given Field.
A helper function for get_normalized_field_type().
@param arg the field to get blob type of
@returns
correct blob type
*/
static enum_field_types get_real_blob_type(const Field *arg) {
assert(arg);
return blob_type_from_pack_length(arg->pack_length() -
portable_sizeof_char_ptr);
}
/**
Get correct blob type of given Item.
A helper function for get_normalized_field_type().
@param arg the item to get blob type of
@returns
correct blob type
*/
static enum_field_types get_real_blob_type(const Item *arg) {
assert(arg);
/*
TINYTEXT, TEXT, MEDIUMTEXT, and LONGTEXT have type
MYSQL_TYPE_BLOB. We want to treat them like strings. We check
the collation to see if the blob is really a string.
*/
if (arg->collation.collation != &my_charset_bin) return MYSQL_TYPE_VARCHAR;
if (arg->type() == Item::FIELD_ITEM)
return get_real_blob_type((down_cast<const Item_field *>(arg))->field);
return arg->data_type();
}
/**
Get the field type of an item. This function returns the same value
as arg->data_type() in most cases, but in some cases it may return
another field type in order to ensure that the item gets handled the
same way as items of a different type.
*/
static enum_field_types get_normalized_field_type(const Item *arg) {
enum_field_types ft = arg->data_type();
switch (ft) {
case MYSQL_TYPE_TINY_BLOB:
case MYSQL_TYPE_BLOB:
case MYSQL_TYPE_MEDIUM_BLOB:
case MYSQL_TYPE_LONG_BLOB:
return get_real_blob_type(arg);
default:
break;
}
return ft;
}
bool get_json_object_member_name(const THD *thd, Item *arg_item, String *value,
String *utf8_res, const char **safep,
size_t *safe_length) {
String *const res = arg_item->val_str(value);
if (thd->is_error()) return true;
if (arg_item->null_value) {
my_error(ER_JSON_DOCUMENT_NULL_KEY, MYF(0));
return true;
}
if (ensure_utf8mb4(*res, utf8_res, safep, safe_length, true)) {
return true;
}
return false;
}
/**
A helper method that checks whether or not the given argument can be converted
to JSON. The function only checks the type of the given item, and doesn't do
any parsing or further checking of the item.
@param item The item to be checked
@retval true The item is possibly convertible to JSON
@retval false The item is not convertible to JSON
*/
static bool is_convertible_to_json(const Item *item) {
const enum_field_types field_type = get_normalized_field_type(item);
switch (field_type) {
case MYSQL_TYPE_NULL:
case MYSQL_TYPE_JSON:
return true;
case MYSQL_TYPE_STRING:
case MYSQL_TYPE_VAR_STRING:
case MYSQL_TYPE_VARCHAR:
case MYSQL_TYPE_BLOB:
case MYSQL_TYPE_LONG_BLOB:
case MYSQL_TYPE_MEDIUM_BLOB:
case MYSQL_TYPE_TINY_BLOB:
if (item->type() == Item::FIELD_ITEM) {
const Item_field *fi = down_cast<const Item_field *>(item);
const Field *field = fi->field;
if (field->is_flag_set(ENUM_FLAG) || field->is_flag_set(SET_FLAG)) {
return false;
}
}
return true;
default:
return false;
}
}
/**
Checks if an Item is of a type that is convertible to JSON. An error is raised
if it is not convertible.
*/
static bool check_convertible_to_json(const Item *item, int argument_number,
const char *function_name) {
if (!is_convertible_to_json(item)) {
my_error(ER_INVALID_TYPE_FOR_JSON, MYF(0), argument_number, function_name);
return true;
}
return false;
}
/**
Helper method for Item_func_json_* methods. Check if a JSON item or
JSON text is valid and, for the latter, optionally construct a DOM
tree (i.e. only if valid).
@param[in] args Item_func::args alias
@param[in] arg_idx Index (0-based) of argument into the args array
@param[out] value Alias for @code Item_func_json_*::m_value @endcode
@param[in] func_name Name of the user-invoked JSON_ function
@param[in,out] dom If non-null, we want any text parsed DOM
returned at the location pointed to
@param[in] require_str_or_json
If true, generate an error if other types used
as input
@param[out] valid true if a valid JSON value was found (or NULL),
else false
@returns true iff syntax error *and* dom != null, else false
*/
static bool json_is_valid(Item **args, uint arg_idx, String *value,
const char *func_name, Json_dom_ptr *dom,
bool require_str_or_json, bool *valid) {
Item *const arg_item = args[arg_idx];
enum_field_types field_type = get_normalized_field_type(arg_item);
if (!is_convertible_to_json(arg_item)) {
if (require_str_or_json) {
*valid = false;
my_error(ER_INVALID_TYPE_FOR_JSON, MYF(0), arg_idx + 1, func_name);
return true;
}
*valid = false;
return false;
} else if (field_type == MYSQL_TYPE_NULL) {
if (arg_item->update_null_value()) return true;
assert(arg_item->null_value);
*valid = true;
return false;
} else if (field_type == MYSQL_TYPE_JSON) {
Json_wrapper w;
// Also sets the null_value flag
*valid = !arg_item->val_json(&w);
return !*valid;
} else {
String *const res = arg_item->val_str(value);
if (current_thd->is_error()) return true;
if (arg_item->null_value) {
*valid = true;
return false;
}
bool parse_error = false;
const bool failure = parse_json(
*res, dom, require_str_or_json,
[&parse_error, arg_idx, func_name](const char *parse_err,
size_t err_offset) {
my_error(ER_INVALID_JSON_TEXT_IN_PARAM, MYF(0), arg_idx + 1,
func_name, parse_err, err_offset, "");
parse_error = true;
},
JsonDocumentDefaultDepthHandler);
*valid = !failure;
return parse_error;
}
}
bool parse_path(const String &path_value, bool forbid_wildcards,
Json_path *json_path) {
const char *path_chars = path_value.ptr();
size_t path_length = path_value.length();
StringBuffer<STRING_BUFFER_USUAL_SIZE> res(&my_charset_utf8mb4_bin);
if (ensure_utf8mb4(path_value, &res, &path_chars, &path_length, true)) {
return true;
}
// OK, we have a string encoded in utf-8. Does it parse?
size_t bad_idx = 0;
if (parse_path(path_length, path_chars, json_path, &bad_idx,
JsonDocumentDefaultDepthHandler)) {
/*
Issue an error message. The last argument is no longer used, but kept to
avoid changing error message format.
*/
my_error(ER_INVALID_JSON_PATH, MYF(0), bad_idx, "");
return true;
}
if (forbid_wildcards && json_path->can_match_many()) {
my_error(ER_INVALID_JSON_PATH_WILDCARD, MYF(0));
return true;
}
return false;
}
/**
Parse a oneOrAll argument.
@param[in] candidate The string to compare to "one" or "all"
@param[in] func_name The name of the calling function
@returns ooa_one, ooa_all, or ooa_error, based on the match
*/
static enum_one_or_all_type parse_one_or_all(const String *candidate,
const char *func_name) {
/*
First convert the candidate to utf8mb4.
A buffer of four bytes is enough to hold the candidate in the common
case ("one" or "all" + terminating NUL character).
We can ignore conversion errors here. If a conversion error should
happen, the converted string will contain a question mark, and we will
correctly raise an error later because no string with a question mark
will match "one" or "all".
*/
StringBuffer<4> utf8str;
uint errors;
if (utf8str.copy(candidate->ptr(), candidate->length(), candidate->charset(),
&my_charset_utf8mb4_bin, &errors))
return ooa_error; /* purecov: inspected */
const char *str = utf8str.c_ptr_safe();
if (!my_strcasecmp(&my_charset_utf8mb4_general_ci, str, "all"))
return ooa_all;
if (!my_strcasecmp(&my_charset_utf8mb4_general_ci, str, "one"))
return ooa_one;
my_error(ER_JSON_BAD_ONE_OR_ALL_ARG, MYF(0), func_name);
return ooa_error;
}
/**
Parse and cache a (possibly constant) oneOrAll argument.
@param[in] thd THD handle.
@param[in] arg The oneOrAll arg passed to the JSON function.
@param[in] cached_ooa Previous result of parsing this arg.
@param[in] func_name The name of the calling JSON function.
@returns ooa_one, ooa_all, ooa_null or ooa_error, based on the match
*/
static enum_one_or_all_type parse_and_cache_ooa(
const THD *thd, Item *arg, enum_one_or_all_type *cached_ooa,
const char *func_name) {
if (arg->const_for_execution()) {
if (*cached_ooa != ooa_uninitialized) {
return *cached_ooa;
}
}
StringBuffer<16> buffer; // larger than common case: three characters + '\0'
String *const one_or_all = arg->val_str(&buffer);
if (thd->is_error()) {
*cached_ooa = ooa_error;
} else if (arg->null_value) {
*cached_ooa = ooa_null;
} else {
*cached_ooa = parse_one_or_all(one_or_all, func_name);
}
return *cached_ooa;
}
/** Json_path_cache */
Json_path_cache::Json_path_cache(THD *thd, uint size)
: m_paths(key_memory_JSON), m_arg_idx_to_vector_idx(thd->mem_root, size) {
reset_cache();
}
Json_path_cache::~Json_path_cache() = default;
bool Json_path_cache::parse_and_cache_path(const THD *thd, Item **args,
uint arg_idx,
bool forbid_wildcards) {
Item *arg = args[arg_idx];
const bool is_constant = arg->const_for_execution();
Path_cell &cell = m_arg_idx_to_vector_idx[arg_idx];
if (is_constant && cell.m_status != enum_path_status::UNINITIALIZED) {
// nothing to do if it has already been parsed
assert(cell.m_status == enum_path_status::OK_NOT_NULL ||
cell.m_status == enum_path_status::OK_NULL);
return false;
}
if (cell.m_status == enum_path_status::UNINITIALIZED) {
cell.m_index = m_paths.size();
if (m_paths.emplace_back(key_memory_JSON))
return true; /* purecov: inspected */
} else {
// re-parsing a non-constant path for the next row
m_paths[cell.m_index].clear();
}
const String *path_value = arg->val_str(&m_path_value);
if (thd->is_error()) return true;
if (arg->null_value) {
cell.m_status = enum_path_status::OK_NULL;
return false;
}
if (parse_path(*path_value, forbid_wildcards, &m_paths[cell.m_index]))
return true;
cell.m_status = enum_path_status::OK_NOT_NULL;
return false;
}
const Json_path *Json_path_cache::get_path(uint arg_idx) const {
const Path_cell &cell = m_arg_idx_to_vector_idx[arg_idx];
if (cell.m_status != enum_path_status::OK_NOT_NULL) {
return nullptr;
}
return &m_paths[cell.m_index];
}
void Json_path_cache::reset_cache() {
std::fill(m_arg_idx_to_vector_idx.begin(), m_arg_idx_to_vector_idx.end(),
Path_cell());
m_paths.clear();
}
/** JSON_*() support methods */
void Item_json_func::cleanup() {
Item_func::cleanup();
m_path_cache.reset_cache();
}
longlong Item_func_json_valid::val_int() {
assert(fixed == 1);
try {
bool ok;
if (json_is_valid(args, 0, &m_value, func_name(), nullptr, false, &ok)) {
return error_int();
}
null_value = args[0]->null_value;
if (null_value || !ok) return 0;
return 1;
} catch (...) {
/* purecov: begin inspected */
handle_std_exception(func_name());
return error_int();
/* purecov: end */
}
}
static bool evaluate_constant_json_schema(
THD *thd, Item *json_schema,
unique_ptr_destroy_only<const Json_schema_validator>
*cached_schema_validator,
Item **ref) {
assert(is_convertible_to_json(json_schema));
const char *func_name = down_cast<const Item_func *>(*ref)->func_name();
if (json_schema->const_item()) {
String schema_buffer;
String *schema_string = json_schema->val_str(&schema_buffer);
if (thd->is_error()) return true;
if (json_schema->null_value) {
*ref = new (thd->mem_root) Item_null((*ref)->item_name);
if (*ref == nullptr) return true;
} else {
*cached_schema_validator =
create_json_schema_validator(thd->mem_root, schema_string->ptr(),
schema_string->length(), func_name);
if (*cached_schema_validator == nullptr) {
return true;
}
}
}
return false;
}
bool Item_func_json_schema_valid::fix_fields(THD *thd, Item **ref) {
if (Item_bool_func::fix_fields(thd, ref)) return true;
// Both arguments must have types that are convertible to JSON.
for (uint i = 0; i < arg_count; ++i)
if (check_convertible_to_json(args[i], i + 1, func_name())) return true;
return evaluate_constant_json_schema(thd, args[0], &m_cached_schema_validator,
ref);
}
void Item_func_json_schema_valid::cleanup() { Item_bool_func::cleanup(); }
Item_func_json_schema_valid::Item_func_json_schema_valid(const POS &pos,
Item *a, Item *b)
: Item_bool_func(pos, a, b) {}
Item_func_json_schema_valid::~Item_func_json_schema_valid() = default;
static bool do_json_schema_validation(
const THD *thd, Item *json_schema, Item *json_document,
const char *func_name, const Json_schema_validator *cached_schema_validator,
bool *null_value, bool *validation_result,
Json_schema_validation_report *validation_report) {
assert(is_convertible_to_json(json_document));
String document_buffer;
String *document_string = json_document->val_str(&document_buffer);
if (thd->is_error()) return true;
if (json_document->null_value) {
*null_value = true;
return false;
}
if (cached_schema_validator != nullptr) {
assert(json_schema->const_item());
if (cached_schema_validator->is_valid_json_schema(
document_string->ptr(), document_string->length(), func_name,
validation_result, validation_report)) {
return true;
}
} else {
// Fields that are a part of constant tables (i.e. primary key lookup) are
// not reported as constant items during fix fields. So while we won't set
// up the cached schema validator during fix_fields, the item will appear as
// const here, and thus failing the assertion if we don't take constant
// tables into account.
assert(!json_schema->const_item() ||
(json_schema->real_item()->type() == Item::FIELD_ITEM &&
down_cast<const Item_field *>(json_schema->real_item())
->table_ref->table->const_table));
assert(is_convertible_to_json(json_schema));
String schema_buffer;
String *schema_string = json_schema->val_str(&schema_buffer);
if (thd->is_error()) return true;
if (json_schema->null_value) {
*null_value = true;
return false;
}
if (is_valid_json_schema(document_string->ptr(), document_string->length(),
schema_string->ptr(), schema_string->length(),
func_name, validation_result, validation_report)) {
return true;
}
}
*null_value = false;
return false;
}
bool Item_func_json_schema_valid::val_bool() {
assert(fixed);
bool validation_result = false;
if (m_in_check_constraint_exec_ctx) {
Json_schema_validation_report validation_report;
if (do_json_schema_validation(current_thd, args[0], args[1], func_name(),
m_cached_schema_validator.get(), &null_value,
&validation_result, &validation_report)) {
return error_bool();
}
if (!null_value && !validation_result) {
my_error(ER_JSON_SCHEMA_VALIDATION_ERROR_WITH_DETAILED_REPORT, MYF(0),
validation_report.human_readable_reason().c_str());
}
} else {
if (do_json_schema_validation(current_thd, args[0], args[1], func_name(),
m_cached_schema_validator.get(), &null_value,
&validation_result, nullptr)) {
return error_bool();
}
}
assert(is_nullable() || !null_value);
return validation_result;
}
bool Item_func_json_schema_validation_report::fix_fields(THD *thd, Item **ref) {
if (Item_json_func::fix_fields(thd, ref)) return true;
// Both arguments must have types that are convertible to JSON.
for (uint i = 0; i < arg_count; ++i)
if (check_convertible_to_json(args[i], i + 1, func_name())) return true;
return evaluate_constant_json_schema(thd, args[0], &m_cached_schema_validator,
ref);
}
void Item_func_json_schema_validation_report::cleanup() {
Item_json_func::cleanup();
}
Item_func_json_schema_validation_report::
Item_func_json_schema_validation_report(THD *thd, const POS &pos,
PT_item_list *a)
: Item_json_func(thd, pos, a) {}
Item_func_json_schema_validation_report::
~Item_func_json_schema_validation_report() = default;
bool Item_func_json_schema_validation_report::val_json(Json_wrapper *wr) {
assert(fixed);
bool validation_result = false;
Json_schema_validation_report validation_report;
if (do_json_schema_validation(current_thd, args[0], args[1], func_name(),
m_cached_schema_validator.get(), &null_value,
&validation_result, &validation_report)) {
return error_json();
}
assert(is_nullable() || !null_value);
std::unique_ptr<Json_object> result(new (std::nothrow) Json_object());
if (result == nullptr) return error_json(); // OOM
Json_boolean *json_validation_result =
new (std::nothrow) Json_boolean(validation_result);
if (result->add_alias("valid", json_validation_result)) return error_json();
if (!validation_result) {
Json_string *json_human_readable_reason = new (std::nothrow)
Json_string(validation_report.human_readable_reason());
if (result->add_alias("reason", json_human_readable_reason))
return error_json(); // OOM
Json_string *json_schema_location =
new (std::nothrow) Json_string(validation_report.schema_location());
if (result->add_alias("schema-location", json_schema_location))
return error_json(); // OOM
Json_string *json_schema_failed_keyword = new (std::nothrow)
Json_string(validation_report.schema_failed_keyword());
if (result->add_alias("schema-failed-keyword", json_schema_failed_keyword))
return error_json(); // OOM
Json_string *json_document_location =
new (std::nothrow) Json_string(validation_report.document_location());
if (result->add_alias("document-location", json_document_location))
return error_json(); // OOM
}
*wr = Json_wrapper(std::move(result));
return false;
}
typedef Prealloced_array<size_t, 16> Sorted_index_array;
/**
Sort the elements of a JSON array and remove duplicates.
@param[in] orig the original JSON array
@param[out] v vector that will be filled with the indexes of the array
elements in increasing order
@return false on success, true on error
*/
bool sort_and_remove_dups(const Json_wrapper &orig, Sorted_index_array *v) {
if (v->reserve(orig.length())) return true; /* purecov: inspected */
for (size_t i = 0; i < orig.length(); i++) v->push_back(i);
// Sort the array...
const auto less = [&orig](size_t idx1, size_t idx2) {
return orig[idx1].compare(orig[idx2]) < 0;
};
std::sort(v->begin(), v->end(), less);
// ... and remove duplicates.
const auto equal = [&orig](size_t idx1, size_t idx2) {
return orig[idx1].compare(orig[idx2]) == 0;
};
v->erase(std::unique(v->begin(), v->end(), equal), v->end());
return false;
}
/**
Check if one Json_wrapper contains all the elements of another
Json_wrapper.
@param[in] thd THD handle
@param[in] doc_wrapper the containing document
@param[in] containee_wr the possibly contained document
@param[out] result true if doc_wrapper contains containee_wr,
false otherwise
@retval false on success
@retval true on failure
*/
static bool contains_wr(const THD *thd, const Json_wrapper &doc_wrapper,
const Json_wrapper &containee_wr, bool *result) {
if (doc_wrapper.type() == enum_json_type::J_OBJECT) {
if (containee_wr.type() != enum_json_type::J_OBJECT ||
containee_wr.length() > doc_wrapper.length()) {
*result = false;
return false;
}
for (const auto &c_oi : Json_object_wrapper(containee_wr)) {
Json_wrapper d_wr = doc_wrapper.lookup(c_oi.first);
if (d_wr.type() == enum_json_type::J_ERROR) {
// No match for this key. Give up.
*result = false;
return false;
}
// key is the same, now compare values
if (contains_wr(thd, d_wr, c_oi.second, result))
return true; /* purecov: inspected */
if (!*result) {
// Value didn't match, give up.
return false;
}
}
// All members in containee_wr found a match in doc_wrapper.
*result = true;
return false;
}
if (doc_wrapper.type() == enum_json_type::J_ARRAY) {
const Json_wrapper *wr = &containee_wr;
Json_wrapper a_wr;
if (containee_wr.type() != enum_json_type::J_ARRAY) {
// auto-wrap scalar or object in an array for uniform treatment later
Json_wrapper scalar = containee_wr;
Json_array_ptr array(new (std::nothrow) Json_array());
if (array == nullptr || array->append_alias(scalar.clone_dom()))
return true; /* purecov: inspected */
a_wr = Json_wrapper(std::move(array));
wr = &a_wr;
}
// Indirection vectors containing the original indices
Sorted_index_array d(key_memory_JSON);
Sorted_index_array c(key_memory_JSON);
// Sort both vectors, so we can compare efficiently
if (sort_and_remove_dups(doc_wrapper, &d) || sort_and_remove_dups(*wr, &c))
return true; /* purecov: inspected */
size_t doc_i = 0;
for (size_t c_i = 0; c_i < c.size(); c_i++) {
Json_wrapper candidate = (*wr)[c[c_i]];
if (candidate.type() == enum_json_type::J_ARRAY) {
bool found = false;
/*
We do not increase doc_i here, use a tmp. We might need to check again
against doc_i: this allows duplicates in the candidate.
*/
for (size_t tmp = doc_i; tmp < d.size(); tmp++) {
auto d_wr = doc_wrapper[d[tmp]];
const auto dtype = d_wr.type();
// Skip past all non-arrays.
if (dtype < enum_json_type::J_ARRAY) {
/*
Remember the position so that we don't need to skip past
these elements again for the next candidate.
*/
doc_i = tmp;
continue;
}
/*
No more potential matches for this candidate if we've
moved past all the arrays.
*/
if (dtype > enum_json_type::J_ARRAY) break;
if (contains_wr(thd, d_wr, candidate, result))
return true; /* purecov: inspected */
if (*result) {
found = true;
break;
}
}
if (!found) {
*result = false;
return false;
}
} else {
bool found = false;
size_t tmp = doc_i;
while (tmp < d.size()) {
auto d_wr = doc_wrapper[d[tmp]];
const auto dtype = d_wr.type();
if (dtype == enum_json_type::J_ARRAY ||
dtype == enum_json_type::J_OBJECT) {
if (contains_wr(thd, d_wr, candidate, result))
return true; /* purecov: inspected */
if (*result) {
found = true;
break;
}
} else if (d_wr.compare(candidate) == 0) {
found = true;
break;
}
tmp++;
}
if (doc_i == d.size() || !found) {
*result = false;
return false;
}
}
}
*result = true;
return false;
}
*result = (doc_wrapper.compare(containee_wr) == 0);
return false;
}
void Item_func_json_contains::cleanup() {
Item_int_func::cleanup();
m_path_cache.reset_cache();
}
longlong Item_func_json_contains::val_int() {
assert(fixed);
THD *const thd = current_thd;
try {
Json_wrapper doc_wrapper;
// arg 0 is the document
if (get_json_wrapper(args, 0, &m_doc_value, func_name(), &doc_wrapper) ||
args[0]->null_value) {
null_value = true;
return 0;
}
Json_wrapper containee_wr;
// arg 1 is the possible containee
if (get_json_wrapper(args, 1, &m_doc_value, func_name(), &containee_wr) ||
args[1]->null_value) {
null_value = true;
return 0;
}
if (arg_count == 3) {
// path is specified
if (m_path_cache.parse_and_cache_path(thd, args, 2, true))
return error_int();
const Json_path *path = m_path_cache.get_path(2);
if (path == nullptr) {
null_value = true;
return 0;
}
Json_wrapper_vector v(key_memory_JSON);
if (doc_wrapper.seek(*path, path->leg_count(), &v, true, false))
return error_int(); /* purecov: inspected */
if (v.size() == 0) {
null_value = true;
return 0;
}
bool ret;
if (contains_wr(thd, v[0], containee_wr, &ret))
return error_int(); /* purecov: inspected */
null_value = false;
return ret;
} else {
bool ret;
if (contains_wr(thd, doc_wrapper, containee_wr, &ret))
return error_int(); /* purecov: inspected */
null_value = false;
return ret;
}
} catch (...) {
/* purecov: begin inspected */
handle_std_exception(func_name());
return error_int();
/* purecov: end */
}
}
void Item_func_json_contains_path::cleanup() {
Item_int_func::cleanup();
m_path_cache.reset_cache();
m_cached_ooa = ooa_uninitialized;
}
longlong Item_func_json_contains_path::val_int() {
assert(fixed == 1);
longlong result = 0;
null_value = false;
Json_wrapper wrapper;
Json_wrapper_vector hits(key_memory_JSON);
try {
// arg 0 is the document
if (get_json_wrapper(args, 0, &m_doc_value, func_name(), &wrapper) ||
args[0]->null_value) {
null_value = true;
return 0;
}
// arg 1 is the oneOrAll flag
bool require_all;
const THD *const thd = current_thd;
switch (parse_and_cache_ooa(thd, args[1], &m_cached_ooa, func_name())) {
case ooa_all: {
require_all = true;
break;
}
case ooa_one: {
require_all = false;
break;
}
case ooa_null: {
null_value = true;
return 0;
}
default: {
return error_int();
}
}
// the remaining args are paths
for (uint32 i = 2; i < arg_count; ++i) {
if (m_path_cache.parse_and_cache_path(thd, args, i, false))
return error_int();
const Json_path *path = m_path_cache.get_path(i);
if (path == nullptr) {
null_value = true;
return 0;
}
hits.clear();
if (wrapper.seek(*path, path->leg_count(), &hits, true, true))
return error_int(); /* purecov: inspected */
if (hits.size() > 0) {
result = 1;
if (!require_all) {
break;
}
} else {
if (require_all) {
result = 0;
break;
}
}
}
} catch (...) {
/* purecov: begin inspected */
handle_std_exception(func_name());
return error_int();
/* purecov: end */
}
return result;
}
bool json_value(Item *arg, Json_wrapper *result, bool *has_value) {
if (arg->data_type() == MYSQL_TYPE_NULL) {
if (arg->update_null_value()) return true;
assert(arg->null_value);
*has_value = true;
return false;
}
// Give up if this is not a JSON value (including typed arrays)
if (arg->data_type() != MYSQL_TYPE_JSON && !arg->returns_array()) {
*has_value = false;
return false;
}
*has_value = true;
const bool error = arg->val_json(result);
return error;
}
bool get_json_wrapper(Item **args, uint arg_idx, String *str,
const char *func_name, Json_wrapper *wrapper) {
Item *const arg = args[arg_idx];
bool has_value;
if (json_value(arg, wrapper, &has_value)) {
return true;
}
// If the value was handled, return with success
if (has_value) {
return false;
}
/*
Otherwise, it's a non-JSON type, so we need to see if we can
convert it to JSON.
*/
/* Is this a JSON text? */
Json_dom_ptr dom; //@< we'll receive a DOM here from a successful text parse
bool valid;
if (json_is_valid(args, arg_idx, str, func_name, &dom, true, &valid))
return true;
if (!valid) {
my_error(ER_INVALID_TYPE_FOR_JSON, MYF(0), arg_idx + 1, func_name);
return true;
}
if (arg->null_value) {
return false;
}
assert(dom);
*wrapper = Json_wrapper(std::move(dom));
return false;
}
/**
Extended type ids so that JSON_TYPE() can give useful type
names to certain sub-types of J_OPAQUE.
*/
enum class enum_json_opaque_type {
J_OPAQUE_BLOB = static_cast<int>(enum_json_type::J_ERROR) + 1,
J_OPAQUE_BIT,
J_OPAQUE_GEOMETRY
};
/**
Maps the enumeration value of type enum_json_type into a string.
For example:
json_type_string_map[J_OBJECT] == "OBJECT"
*/
static constexpr const char *json_type_string_map[] = {
"NULL",
"DECIMAL",
"INTEGER",
"UNSIGNED INTEGER",
"DOUBLE",
"STRING",
"OBJECT",
"ARRAY",
"BOOLEAN",
"DATE",
"TIME",
"DATETIME",
"TIMESTAMP",
"OPAQUE",
"ERROR",
// OPAQUE types with special names
"BLOB",
"BIT",
"GEOMETRY",
};
/// A constexpr version of std::strlen.
static constexpr uint32 strlen_const(const char *str) {
return *str == '\0' ? 0 : 1 + strlen_const(str + 1);
}
/// Find the length of the longest string in a range.
static constexpr uint32 longest_string(const char *const *begin,
const char *const *end) {
return begin == end
? 0
: std::max(strlen_const(*begin), longest_string(begin + 1, end));
}
/**
The maximum length of a string in json_type_string_map including
a final zero char.
*/
static constexpr uint32 typelit_max_length =
longest_string(
json_type_string_map,
json_type_string_map + array_elements(json_type_string_map)) +
1;
bool Item_func_json_type::resolve_type(THD *thd) {
if (param_type_is_default(thd, 0, 1, MYSQL_TYPE_JSON)) return true;
set_nullable(true);
m_value.set_charset(&my_charset_utf8mb4_bin);
set_data_type_string(typelit_max_length, &my_charset_utf8mb4_bin);
return false;
}
/**
Compute an index into json_type_string_map
to be applied to certain sub-types of J_OPAQUE.
@param field_type The refined field type of the opaque value.
@return an index into json_type_string_map
*/
static uint opaque_index(enum_field_types field_type) {
switch (field_type) {
case MYSQL_TYPE_VARCHAR:
case MYSQL_TYPE_TINY_BLOB:
case MYSQL_TYPE_MEDIUM_BLOB:
case MYSQL_TYPE_LONG_BLOB:
case MYSQL_TYPE_BLOB:
case MYSQL_TYPE_VAR_STRING:
case MYSQL_TYPE_STRING:
return static_cast<uint>(enum_json_opaque_type::J_OPAQUE_BLOB);
case MYSQL_TYPE_BIT:
return static_cast<uint>(enum_json_opaque_type::J_OPAQUE_BIT);
case MYSQL_TYPE_GEOMETRY: {
/**
Should not get here. This path should be orphaned by the
work done on implicit CASTing of geometry values to geojson
objects. However, that work was done late in the project
cycle for WL#7909. Do something sensible in case we missed
something.
FIXME.
*/
/* purecov: begin deadcode */
assert(false);
return static_cast<uint>(enum_json_opaque_type::J_OPAQUE_GEOMETRY);
/* purecov: end */
}
default:
return static_cast<uint>(enum_json_type::J_OPAQUE);
}
}
String *Item_func_json_type::val_str(String *) {
assert(fixed == 1);
try {
Json_wrapper wr;
if (get_json_wrapper(args, 0, &m_value, func_name(), &wr) ||
args[0]->null_value) {
null_value = true;
return nullptr;
}
const enum_json_type type = wr.type();
uint typename_idx = static_cast<uint>(type);
if (type == enum_json_type::J_OPAQUE) {
typename_idx = opaque_index(wr.field_type());
}
m_value.length(0);
if (m_value.append(json_type_string_map[typename_idx]))
return error_str(); /* purecov: inspected */
} catch (...) {
/* purecov: begin inspected */
handle_std_exception(func_name());
return error_str();
/* purecov: end */
}
null_value = false;
return &m_value;
}
static String *val_string_from_json(Item_func *item, String *buffer) {
Json_wrapper wr;
if (item->val_json(&wr)) return item->error_str();
if (item->null_value) return nullptr;
buffer->length(0);
if (wr.to_string(buffer, true, item->func_name(),
JsonDocumentDefaultDepthHandler))
return item->error_str();
item->null_value = false;
return buffer;
}
String *Item_json_func::val_str(String *) {
assert(fixed);
return val_string_from_json(this, &m_string_buffer);
}
static bool get_date_from_json(Item_func *item, MYSQL_TIME *ltime,
my_time_flags_t) {
Json_wrapper wr;
if (item->val_json(&wr)) return true;
if (item->null_value) return true;
return wr.coerce_date(ltime, item->func_name());
}
bool Item_json_func::get_date(MYSQL_TIME *ltime, my_time_flags_t flags) {
return get_date_from_json(this, ltime, flags);
}
static bool get_time_from_json(Item_func *item, MYSQL_TIME *ltime) {
Json_wrapper wr;
if (item->val_json(&wr)) return true;
if (item->null_value) return true;
return wr.coerce_time(ltime, item->func_name());
}
bool Item_json_func::get_time(MYSQL_TIME *ltime) {
return get_time_from_json(this, ltime);
}
longlong val_int_from_json(Item_func *item) {
Json_wrapper wr;
if (item->val_json(&wr)) return 0;
if (item->null_value) return 0;
return wr.coerce_int(item->func_name());
}
longlong Item_json_func::val_int() { return val_int_from_json(this); }
static double val_real_from_json(Item_func *item) {
Json_wrapper wr;
if (item->val_json(&wr)) return 0.0;
if (item->null_value) return 0.0;
return wr.coerce_real(item->func_name());
}
double Item_json_func::val_real() { return val_real_from_json(this); }
static my_decimal *val_decimal_from_json(Item_func *item,
my_decimal *decimal_value) {
Json_wrapper wr;
if (item->val_json(&wr)) {
return item->error_decimal(decimal_value);
}
if (item->null_value) return nullptr;
return wr.coerce_decimal(decimal_value, item->func_name());
}
my_decimal *Item_json_func::val_decimal(my_decimal *decimal_value) {
return val_decimal_from_json(this, decimal_value);
}
/**
Create a new Json_scalar object, either in memory owned by a
Json_scalar_holder object or on the heap.
@param[in,out] scalar the Json_scalar_holder in which to create the new
Json_scalar, or `nullptr` if it should be created
on the heap
@param[in,out] dom pointer to the Json_scalar if it's created on the heap
@param[in] args the arguments to pass to T's constructor
@tparam T the type of object to create; a subclass of Json_scalar
@tparam Args type of the arguments to pass to T's constructor
@retval false if successful
@retval true if memory could not be allocated
*/
template <typename T, typename... Args>
static bool create_scalar(Json_scalar_holder *scalar, Json_dom_ptr *dom,
Args &&...args) {
if (scalar != nullptr) {
scalar->emplace<T>(std::forward<Args>(args)...);
return false;
}
*dom = create_dom_ptr<T>(std::forward<Args>(args)...);
return dom == nullptr;
}
/**
Get a JSON value from an SQL scalar value.
@param[in] arg the function argument
@param[in] calling_function the name of the calling function
@param[in,out] value a scratch area
@param[in,out] tmp temporary scratch space for converting strings to
the correct charset; only used if accept_string is
true and conversion is needed
@param[out] wr the retrieved JSON value
@param[in,out] scalar pointer to pre-allocated memory that can be
borrowed by the result wrapper to hold the scalar
result. If the pointer is NULL, memory will be
allocated on the heap.
@param[in] scalar_string
if true, interpret SQL strings as scalar JSON
strings.
if false, interpret SQL strings as JSON objects.
If conversion fails, return the string as a
scalar JSON string instead.
@return false if we could get a value or NULL, otherwise true
*/
bool sql_scalar_to_json(Item *arg, const char *calling_function, String *value,
String *tmp, Json_wrapper *wr,
Json_scalar_holder *scalar, bool scalar_string) {
enum_field_types field_type = get_normalized_field_type(arg);
/*
Most items and fields have same actual and resolved types, however e.g
a dynamic parameter will usually have a different type (integer, string...)
*/
if (field_type == MYSQL_TYPE_JSON) {
field_type = arg->actual_data_type();
}
Json_dom_ptr dom;
switch (field_type) {
case MYSQL_TYPE_INT24:
case MYSQL_TYPE_LONG:
case MYSQL_TYPE_SHORT:
case MYSQL_TYPE_TINY:
case MYSQL_TYPE_LONGLONG:
case MYSQL_TYPE_YEAR: {
longlong i = arg->val_int();
if (current_thd->is_error()) return true;
if (arg->null_value) return false;
if (arg->unsigned_flag) {
if (create_scalar<Json_uint>(scalar, &dom, i))
return true; /* purecov: inspected */
} else {
if (create_scalar<Json_int>(scalar, &dom, i))
return true; /* purecov: inspected */
}
break;
}
case MYSQL_TYPE_DATE:
case MYSQL_TYPE_DATETIME:
case MYSQL_TYPE_TIMESTAMP:
case MYSQL_TYPE_TIME: {
longlong dt = arg->val_temporal_by_field_type();
if (current_thd->is_error()) return true;
if (arg->null_value) return false;
MYSQL_TIME t;
TIME_from_longlong_datetime_packed(&t, dt);
t.time_type = field_type_to_timestamp_type(field_type);
if (create_scalar<Json_datetime>(scalar, &dom, t, field_type))
return true; /* purecov: inspected */
break;
}
case MYSQL_TYPE_NEWDECIMAL: {
my_decimal m;
my_decimal *r = arg->val_decimal(&m);
if (current_thd->is_error()) return true;
if (arg->null_value) return false;
assert(r != nullptr);
if (create_scalar<Json_decimal>(scalar, &dom, *r))
return true; /* purecov: inspected */
break;
}
case MYSQL_TYPE_DOUBLE:
case MYSQL_TYPE_FLOAT: {
double d = arg->val_real();
if (current_thd->is_error()) return true;
if (arg->null_value) return false;
if (create_scalar<Json_double>(scalar, &dom, d))
return true; /* purecov: inspected */
break;
}
case MYSQL_TYPE_GEOMETRY: {
uint32 geometry_srid;
String *swkb = arg->val_str(tmp);
if (current_thd->is_error()) return true;
if (arg->null_value) return false;
bool retval = geometry_to_json(wr, swkb, calling_function, INT_MAX32,
false, false, false, &geometry_srid);
/**
Scalar processing is irrelevant. Geometry types are converted
to JSON objects.
*/
return retval;
}
case MYSQL_TYPE_BLOB:
case MYSQL_TYPE_BIT:
case MYSQL_TYPE_LONG_BLOB:
case MYSQL_TYPE_MEDIUM_BLOB:
case MYSQL_TYPE_TINY_BLOB: {
String *oo = arg->val_str(value);
if (current_thd->is_error()) return true;
if (arg->null_value) return false;
if (create_scalar<Json_opaque>(scalar, &dom, field_type, oo->ptr(),
oo->length()))
return true; /* purecov: inspected */
break;
}
case MYSQL_TYPE_VAR_STRING:
case MYSQL_TYPE_VARCHAR:
case MYSQL_TYPE_ENUM:
case MYSQL_TYPE_SET:
case MYSQL_TYPE_STRING: {
/*
Wrong charset or Json syntax error (the latter: only if !accept_string,
in which case a binary character set is our only hope for success).
*/
String *res = arg->val_str(value);
if (current_thd->is_error()) return true;
if (arg->null_value) return false;
const CHARSET_INFO *cs = res->charset();
if (cs == &my_charset_bin || cs->mbminlen > 1) {
/*
When charset is always multi-byte, store string as OPAQUE value to
preserve binary encoding. This case is used my multi-valued index,
when it's created over char field with such charset. SE (InnoDB)
expect correct binary encoding of such strings. This is similar to
preserving precision in decimal values for multi-valued index.
To keep such converted strings apart from other values, they are
encoded as having MYSQL_TYPE_VAR_STRING which currently isn't used
in server.
*/
if (cs->mbminlen > 1) field_type = MYSQL_TYPE_VAR_STRING;
// BINARY or similar
if (create_scalar<Json_opaque>(scalar, &dom, field_type, res->ptr(),
res->length()))
return true; /* purecov: inspected */
break;
} else {
const char *s = res->ptr();
size_t ss = res->length();
if (ensure_utf8mb4(*res, tmp, &s, &ss, true)) {
return true;
}
if (scalar_string) {
if (create_scalar<Json_string>(scalar, &dom, s, ss))
return true; /* purecov: inspected */
} else {
JsonParseDefaultErrorHandler parse_handler(calling_function, 0);
dom = Json_dom::parse(s, ss, parse_handler,
JsonDocumentDefaultDepthHandler);
if (dom == nullptr) return true;
}
}
break;
}
case MYSQL_TYPE_DECIMAL: // pre 5.0
my_error(ER_NOT_SUPPORTED_YET, MYF(0), "old decimal type");
return true;
case MYSQL_TYPE_NULL:
// May occur for a parameter that is NULL
assert(arg->null_value);
return false;
case MYSQL_TYPE_JSON:
assert(false); /* purecov: inspected */
// fall-through
default:
my_error(ER_INVALID_CAST_TO_JSON, MYF(0));
return true;
}
// Exactly one of scalar and dom should be used.
assert((scalar == nullptr) != (dom == nullptr));
assert(scalar == nullptr || scalar->get() != nullptr);
if (scalar != nullptr) {
/*
The DOM object lives in memory owned by the caller. Tell the
wrapper that it's not the owner.
*/
*wr = Json_wrapper(scalar->get(), true);
return false;
}
*wr = Json_wrapper(std::move(dom));
return false;
}
// see the contract for this function in item_json_func.h
bool get_json_atom_wrapper(Item **args, uint arg_idx,
const char *calling_function, String *value,
String *tmp, Json_wrapper *wr,
Json_scalar_holder *scalar, bool accept_string) {
bool result = false;
Item *const arg = args[arg_idx];
// First, try to handle simple cases: NULL value and JSON type
bool has_value = false;
if (json_value(arg, wr, &has_value)) {
return true;
}
if (has_value) {
return false;
}
try {
// boolean operators should produce boolean values
if (arg->is_bool_func()) {
const bool boolean_value = arg->val_int() != 0;
if (current_thd->is_error()) return true;
Json_dom_ptr boolean_dom;
if (create_scalar<Json_boolean>(scalar, &boolean_dom, boolean_value))
return true; /* purecov: inspected */
if (scalar != nullptr) {
/*
The DOM object lives in memory owned by the caller. Tell the
wrapper that it's not the owner.
*/
*wr = Json_wrapper(scalar->get());
wr->set_alias();
return false;
}
*wr = Json_wrapper(std::move(boolean_dom));
return false;
}
/*
Allow other types as first-class or opaque JSON values.
But how to determine what the type is? We do a best effort...
*/
result = sql_scalar_to_json(arg, calling_function, value, tmp, wr, scalar,
accept_string);
} catch (...) {
/* purecov: begin inspected */
handle_std_exception(calling_function);
return true;
/* purecov: end */
}
return result;
}
bool get_atom_null_as_null(Item **args, uint arg_idx,
const char *calling_function, String *value,
String *tmp, Json_wrapper *wr) {
if (get_json_atom_wrapper(args, arg_idx, calling_function, value, tmp, wr,
nullptr, true))
return true;
if (args[arg_idx]->null_value) {
*wr = Json_wrapper(new (std::nothrow) Json_null());
}
return false;
}
bool Item_typecast_json::val_json(Json_wrapper *wr) {
assert(fixed == 1);
Json_dom_ptr dom; //@< if non-null we want a DOM from parse
if (args[0]->data_type() == MYSQL_TYPE_NULL) {
null_value = true;
return false;
}
if (args[0]->data_type() == MYSQL_TYPE_JSON) {
bool has_value;
if (json_value(args[0], wr, &has_value)) return error_json();
assert(has_value);
null_value = args[0]->null_value;
return false;
}
bool valid;
if (json_is_valid(args, 0, &m_value, func_name(), &dom, false, &valid))
return error_json();
if (valid) {
if (args[0]->null_value) {
null_value = true;
return false;
}
// We were able to parse a JSON value from a string.
assert(dom);
// Pass on the DOM wrapped
*wr = Json_wrapper(std::move(dom));
null_value = false;
return false;
}
// Not a non-binary string, nor a JSON value, wrap the rest
if (get_json_atom_wrapper(args, 0, func_name(), &m_value,
&m_conversion_buffer, wr, nullptr, true))
return error_json();
null_value = args[0]->null_value;
return false;
}
void Item_typecast_json::print(const THD *thd, String *str,
enum_query_type query_type) const {
str->append(STRING_WITH_LEN("cast("));
args[0]->print(thd, str, query_type);
str->append(STRING_WITH_LEN(" as "));
str->append(cast_type());
str->append(')');
}
longlong Item_func_json_length::val_int() {
assert(fixed == 1);
longlong result = 0;
Json_wrapper wrapper;
try {
if (get_json_wrapper(args, 0, &m_doc_value, func_name(), &wrapper) ||
args[0]->null_value) {
null_value = true;
return 0;
}
} catch (...) {
/* purecov: begin inspected */
handle_std_exception(func_name());
return error_int();
/* purecov: end */
}
result = wrapper.length();
null_value = false;
return result;
}
longlong Item_func_json_depth::val_int() {
assert(fixed);
Json_wrapper wrapper;
try {
if (get_json_wrapper(args, 0, &m_doc_value, func_name(), &wrapper))
return error_int();
} catch (...) {
/* purecov: begin inspected */
handle_std_exception(func_name());
return error_int();
/* purecov: end */
}
null_value = args[0]->null_value;
if (null_value) return 0;
const Json_dom *dom = wrapper.to_dom();
return dom == nullptr ? error_int() : dom->depth();
}
bool Item_func_json_keys::val_json(Json_wrapper *wr) {
assert(fixed == 1);
Json_wrapper wrapper;
try {
if (get_json_wrapper(args, 0, &m_doc_value, func_name(), &wrapper))
return error_json();
if (args[0]->null_value) {
null_value = true;
return false;
}
if (arg_count > 1) {
if (m_path_cache.parse_and_cache_path(current_thd, args, 1, true))
return error_json();
const Json_path *path = m_path_cache.get_path(1);
if (path == nullptr) {
null_value = true;
return false;
}
Json_wrapper_vector hits(key_memory_JSON);
if (wrapper.seek(*path, path->leg_count(), &hits, false, true))
return error_json(); /* purecov: inspected */
if (hits.size() != 1) {
null_value = true;
return false;
}
wrapper = std::move(hits[0]);
}
if (wrapper.type() != enum_json_type::J_OBJECT) {
null_value = true;
return false;
}
// We have located a JSON object value, now collect its keys
// and return them as a JSON array.
Json_array_ptr res(new (std::nothrow) Json_array());
if (res == nullptr) return error_json(); /* purecov: inspected */
for (const auto &i : Json_object_wrapper(wrapper)) {
const MYSQL_LEX_CSTRING &key = i.first;
if (res->append_alias(new (std::nothrow)
Json_string(key.str, key.length)))
return error_json(); /* purecov: inspected */
}
*wr = Json_wrapper(std::move(res));
} catch (...) {
/* purecov: begin inspected */
handle_std_exception(func_name());
return error_json();
/* purecov: end */
}
null_value = false;
return false;
}
bool Item_func_json_extract::val_json(Json_wrapper *wr) {
assert(fixed == 1);
try {
Json_wrapper w;
// multiple paths means multiple possible matches
bool could_return_multiple_matches = (arg_count > 2);
// collect results here
Json_wrapper_vector v(key_memory_JSON);
if (get_json_wrapper(args, 0, &m_doc_value, func_name(), &w))
return error_json();
if (args[0]->null_value) {
null_value = true;
return false;
}
const THD *const thd = current_thd;
for (uint32 i = 1; i < arg_count; ++i) {
if (m_path_cache.parse_and_cache_path(thd, args, i, false))
return error_json();
const Json_path *path = m_path_cache.get_path(i);
if (path == nullptr) {
null_value = true;
return false;
}
could_return_multiple_matches |= path->can_match_many();
if (w.seek(*path, path->leg_count(), &v, true, false))
return error_json(); /* purecov: inspected */
}
if (v.size() == 0) {
null_value = true;
return false;
}
if (could_return_multiple_matches) {
Json_array_ptr a(new (std::nothrow) Json_array());
if (a == nullptr) return error_json(); /* purecov: inspected */
for (Json_wrapper &ww : v) {
if (a->append_clone(ww.to_dom()))
return error_json(); /* purecov: inspected */
}
*wr = Json_wrapper(std::move(a));
} else // one path, no ellipsis or wildcard
{
// there should only be one match
assert(v.size() == 1);
*wr = std::move(v[0]);
}
} catch (...) {
/* purecov: begin inspected */
handle_std_exception(func_name());
return error_json();
/* purecov: end */
}
null_value = false;
return false;
}
bool Item_func_json_extract::eq(const Item *item, bool binary_cmp) const {
if (this == item) return true;
if (item->type() != FUNC_ITEM) return false;
const auto item_func = down_cast<const Item_func *>(item);
if (arg_count != item_func->arg_count ||
strcmp(func_name(), item_func->func_name()) != 0)
return false;
auto cmp = [binary_cmp](const Item *arg1, const Item *arg2) {
/*
JSON_EXTRACT doesn't care about the collation of its arguments. String
literal arguments are considered equal if they have the same character
set and binary contents, even if their collations differ.
*/
const bool ignore_collation =
binary_cmp ||
(arg1->type() == STRING_ITEM &&
my_charset_same(arg1->collation.collation, arg2->collation.collation));
return ItemsAreEqual(arg1, arg2, ignore_collation);
};
const auto item_json = down_cast<const Item_func_json_extract *>(item);
return std::equal(args, args + arg_count, item_json->args, cmp);
}
bool Item_func_modify_json_in_path::resolve_type(THD *thd) {
if (Item_json_func::resolve_type(thd)) return true;
if (param_type_is_default(thd, 0, 1, MYSQL_TYPE_JSON)) return true;
if (param_type_is_default(thd, 1, -1, 2, MYSQL_TYPE_VARCHAR)) return true;
if (param_type_is_default(thd, 2, -1, 2, MYSQL_TYPE_JSON)) return true;
for (uint i = 2; i < arg_count; i += 2) {
args[i]->mark_json_as_scalar();
}
not_null_tables_cache = calculate_not_null_tables();
return false;
}
void Item_func_modify_json_in_path::update_used_tables() {
Item_json_func::update_used_tables();
not_null_tables_cache = calculate_not_null_tables();
}
table_map Item_func_modify_json_in_path::calculate_not_null_tables() const {
// If the first argument (the JSON document) is NULL, the function returns
// NULL.
table_map tables = args[0]->not_null_tables();
// If any of the JSON path arguments is NULL, the function returns NULL.
for (uint i = 1; i < arg_count; i += 2) {
tables |= args[i]->not_null_tables();
}
return tables;
}
#ifndef NDEBUG
/**
Is this a path that could possibly return the root node of a JSON document?
A path that returns the root node must be on one of the following forms:
- the root ('$'), or
- a sequence of array cells at index 0 or `last` that any non-array element
at the top level could have been autowrapped to, i.e. '$[0]' or
'$[0][0]...[0]'.
@see Json_path_leg::is_autowrap
@param begin the beginning of the path
@param end the end of the path (exclusive)
@return true if the path may match the root, false otherwise
*/
static bool possible_root_path(const Json_path_iterator &begin,
const Json_path_iterator &end) {
auto is_autowrap = [](const Json_path_leg *leg) {
return leg->is_autowrap();
};
return std::all_of(begin, end, is_autowrap);
}
#endif // NDEBUG
bool Item_func_json_array_append::val_json(Json_wrapper *wr) {
assert(fixed == 1);
try {
Json_wrapper docw;
if (get_json_wrapper(args, 0, &m_doc_value, func_name(), &docw))
return error_json();
if (args[0]->null_value) {
null_value = true;
return false;
}
const THD *thd = current_thd;
for (uint32 i = 1; i < arg_count; i += 2) {
// Need a DOM to be able to manipulate arrays
Json_dom *doc = docw.to_dom();
if (!doc) return error_json(); /* purecov: inspected */
if (m_path_cache.parse_and_cache_path(thd, args, i, true))
return error_json();
const Json_path *path = m_path_cache.get_path(i);
if (path == nullptr) {
null_value = true;
return false;
}
Json_dom_vector hits(key_memory_JSON);
if (doc->seek(*path, path->leg_count(), &hits, true, true))
return error_json(); /* purecov: inspected */
if (hits.empty()) continue;
// Paths with wildcards and ranges are rejected, so expect one hit.
assert(hits.size() == 1);
Json_dom *hit = hits[0];
Json_wrapper valuew;
if (get_atom_null_as_null(args, i + 1, func_name(), &m_value,
&m_conversion_buffer, &valuew))
return error_json();
Json_dom_ptr val_dom(valuew.to_dom());
valuew.set_alias(); // we have taken over the DOM
if (hit->json_type() == enum_json_type::J_ARRAY) {
Json_array *arr = down_cast<Json_array *>(hit);
if (arr->append_alias(std::move(val_dom)))
return error_json(); /* purecov: inspected */
} else {
Json_array_ptr arr(new (std::nothrow) Json_array());
if (arr == nullptr || arr->append_clone(hit) ||
arr->append_alias(std::move(val_dom))) {
return error_json(); /* purecov: inspected */
}
/*
This value will replace the old document we found using path, since
we did an auto-wrap. If this is root, this is trivial, but if it's
inside an array or object, we need to find the parent DOM to be
able to replace it in situ.
*/
Json_container *parent = hit->parent();
if (parent == nullptr) // root
{
assert(possible_root_path(path->begin(), path->end()));
docw = Json_wrapper(std::move(arr));
} else {
parent->replace_dom_in_container(hit, std::move(arr));
}
}
}
// docw still owns the augmented doc, so hand it over to result
*wr = std::move(docw);
} catch (...) {
/* purecov: begin inspected */
handle_std_exception(func_name());
return error_json();
/* purecov: end */
}
null_value = false;
return false;
}
bool Item_func_json_insert::val_json(Json_wrapper *wr) {
assert(fixed == 1);
try {
Json_wrapper docw;
if (get_json_wrapper(args, 0, &m_doc_value, func_name(), &docw))
return error_json();
if (args[0]->null_value) {
null_value = true;
return false;
}
const THD *thd = current_thd;
for (uint32 i = 1; i < arg_count; i += 2) {
// Need a DOM to be able to manipulate arrays and objects
Json_dom *doc = docw.to_dom();
if (!doc) return error_json(); /* purecov: inspected */
if (m_path_cache.parse_and_cache_path(thd, args, i, true))
return error_json();
const Json_path *path = m_path_cache.get_path(i);
if (path == nullptr) {
null_value = true;
return false;
}
// Cannot insert the root element.
if (path->leg_count() == 0) continue;
Json_dom_vector hits(key_memory_JSON);
if (doc->seek(*path, path->leg_count(), &hits, true, true))
return error_json(); /* purecov: inspected */
// If it already exists, there is nothing to do.
if (!hits.empty()) continue;
/*
Need to look one step up the path: if we are specifying an array slot
we need to find the array. If we are specifying an object element, we
need to find the object. In both cases so we can insert into them.
Seek again without considering the last path leg.
*/
const Json_path_leg *leg = path->last_leg();
if (doc->seek(*path, path->leg_count() - 1, &hits, true, true))
return error_json(); /* purecov: inspected */
if (hits.empty()) {
// no unique object found at parent position, so bail out
continue;
}
// We found *something* at that parent path
Json_wrapper valuew;
if (get_atom_null_as_null(args, i + 1, func_name(), &m_value,
&m_conversion_buffer, &valuew)) {
return error_json();
}
// Paths with wildcards and ranges are rejected, so expect one hit.
assert(hits.size() == 1);
Json_dom *hit = hits[0];
// What did we specify in the path, object or array?
if (leg->get_type() == jpl_array_cell) {
// We specified an array, what did we find at that position?
if (hit->json_type() == enum_json_type::J_ARRAY) {
// We found an array, so either prepend or append.
Json_array *arr = down_cast<Json_array *>(hit);
size_t pos = leg->first_array_index(arr->size()).position();
if (arr->insert_alias(pos, valuew.clone_dom()))
return error_json(); /* purecov: inspected */
} else if (!leg->is_autowrap()) {
/*
Found a scalar or object and we didn't specify position 0 or last:
auto-wrap it and either prepend or append.
*/
size_t pos = leg->first_array_index(1).position();
Json_array_ptr newarr(new (std::nothrow) Json_array());
if (newarr == nullptr ||
newarr->append_clone(hit) /* auto-wrap this */ ||
newarr->insert_alias(pos, valuew.clone_dom())) {
return error_json(); /* purecov: inspected */
}
/*
Now we need this value to replace the old document we found using
path. If this is root, this is trivial, but if it's inside an
array or object, we need to find the parent DOM to be able to
replace it in situ.
*/
Json_container *parent = hit->parent();
if (parent == nullptr) // root
{
assert(possible_root_path(path->begin(), path->end() - 1));
docw = Json_wrapper(std::move(newarr));
} else {
parent->replace_dom_in_container(hit, std::move(newarr));
}
}
} else if (leg->get_type() == jpl_member &&
hit->json_type() == enum_json_type::J_OBJECT) {
Json_object *o = down_cast<Json_object *>(hit);
if (o->add_clone(leg->get_member_name(), valuew.to_dom()))
return error_json(); /* purecov: inspected */
}
} // end of loop through paths
// docw still owns the augmented doc, so hand it over to result
*wr = std::move(docw);
} catch (...) {
/* purecov: begin inspected */
handle_std_exception(func_name());
return error_json();
/* purecov: end */
}
null_value = false;
return false;
}
bool Item_func_json_array_insert::val_json(Json_wrapper *wr) {
assert(fixed == 1);
try {
Json_wrapper docw;
if (get_json_wrapper(args, 0, &m_doc_value, func_name(), &docw))
return error_json();
if (args[0]->null_value) {
null_value = true;
return false;
}
const THD *thd = current_thd;
for (uint32 i = 1; i < arg_count; i += 2) {
// Need a DOM to be able to manipulate arrays and objects
Json_dom *doc = docw.to_dom();
if (!doc) return error_json(); /* purecov: inspected */
if (m_path_cache.parse_and_cache_path(thd, args, i, true))
return error_json();
const Json_path *path = m_path_cache.get_path(i);
if (path == nullptr) {
null_value = true;
return false;
}
// the path must end in a cell identifier
if (path->leg_count() == 0 ||
path->last_leg()->get_type() != jpl_array_cell) {
my_error(ER_INVALID_JSON_PATH_ARRAY_CELL, MYF(0));
return error_json();
}
/*
Need to look one step up the path: we need to find the array.
Seek without the last path leg.
*/
Json_dom_vector hits(key_memory_JSON);
const Json_path_leg *leg = path->last_leg();
if (doc->seek(*path, path->leg_count() - 1, &hits, false, true))
return error_json(); /* purecov: inspected */
if (hits.empty()) {
// no unique object found at parent position, so bail out
continue;
}
// We found *something* at that parent path
// Paths with wildcards and ranges are rejected, so expect one hit.
assert(hits.size() == 1);
Json_dom *hit = hits[0];
// NOP if parent is not an array
if (hit->json_type() != enum_json_type::J_ARRAY) continue;
Json_wrapper valuew;
if (get_atom_null_as_null(args, i + 1, func_name(), &m_value,
&m_conversion_buffer, &valuew)) {
return error_json();
}
// Insert the value at that location.
Json_array *arr = down_cast<Json_array *>(hit);
assert(leg->get_type() == jpl_array_cell);
size_t pos = leg->first_array_index(arr->size()).position();
if (arr->insert_alias(pos, valuew.clone_dom()))
return error_json(); /* purecov: inspected */
} // end of loop through paths
// docw still owns the augmented doc, so hand it over to result
*wr = std::move(docw);
} catch (...) {
/* purecov: begin inspected */
handle_std_exception(func_name());
return error_json();
/* purecov: end */
}
null_value = false;
return false;
}
/**
Clone a source path to a target path, stripping out legs which are made
redundant by the auto-wrapping rule from the WL#7909 spec and further
extended in the WL#9831 spec:
"If an array cell path leg or an array range path leg is evaluated against a
non-array value, the result of the evaluation is the same as if the non-array
value had been wrapped in a single-element array."
@see Json_path_leg::is_autowrap
@param[in] source_path The original path.
@param[in,out] target_path The clone to be filled in.
@param[in] doc The document to seek through.
@returns True if an error occurred. False otherwise.
*/
static bool clone_without_autowrapping(const Json_path *source_path,
Json_path_clone *target_path,
Json_wrapper *doc) {
Json_wrapper_vector hits(key_memory_JSON);
target_path->clear();
for (const Json_path_leg *path_leg : *source_path) {
if (path_leg->is_autowrap()) {
/*
We have a partial path of the form
pathExpression[0]
So see if pathExpression identifies a non-array value.
*/
hits.clear();
if (doc->seek(*target_path, target_path->leg_count(), &hits, false, true))
return true; /* purecov: inspected */
if (!hits.empty() && hits[0].type() != enum_json_type::J_ARRAY) {
/*
pathExpression identifies a non-array value.
We satisfy the conditions of the rule above.
So we can throw away the [0] leg.
*/
continue;
}
}
// The rule above is NOT satisfied. So add the leg.
if (target_path->append(path_leg)) return true; /* purecov: inspected */
}
return false;
}
void Item_json_func::mark_for_partial_update(const Field_json *field) {
assert(supports_partial_update(field));
m_partial_update_column = field;
// Peel off the Item_view_ref if we are updating an updatable view.
Item *arg0 = args[0]->real_item();
// supports_partial_update() returns true only when args[0] is an Item_field
// or a subclass of Item_json_func (or a view ref wrapping any of those), so
// we can safely assume it has one of those types when we get here.
if (arg0->type() == FIELD_ITEM) {
assert(down_cast<Item_field *>(arg0)->field == field);
} else {
down_cast<Item_json_func *>(arg0)->mark_for_partial_update(field);
}
}
bool Item_json_func::supports_partial_update(const Field_json *field) const {
if (!can_use_in_partial_update()) return false;
/*
This JSON_SET, JSON_REPLACE or JSON_REMOVE expression might be used for
partial update if the first argument is a JSON column which is the same as
the target column of the update operation, or if the first argument is
another JSON_SET, JSON_REPLACE or JSON_REMOVE expression which has the
target column as its first argument.
*/
Item *arg0 = args[0];
if (arg0->type() == Item::REF_ITEM &&
down_cast<Item_ref *>(arg0)->ref_type() == Item_ref::VIEW_REF) {
// If the target table is an updatable view, look at the column in the base
// table.
arg0 = arg0->real_item();
}
if (arg0->type() == FIELD_ITEM)
return down_cast<const Item_field *>(arg0)->field == field;
return arg0->supports_partial_update(field);
}
static void disable_logical_diffs(const Field_json *field) {
field->table->disable_logical_diffs_for_current_row(field);
}
static void disable_binary_diffs(const Field_json *field) {
field->table->disable_binary_diffs_for_current_row(field);
}
/**
Common implementation for JSON_SET and JSON_REPLACE
*/
bool Item_func_json_set_replace::val_json(Json_wrapper *wr) {
const THD *thd = current_thd;
// Should we collect binary or logical diffs? We'll see later...
bool binary_diffs = false;
bool logical_diffs = false;
try {
Json_wrapper docw;
if (get_json_wrapper(args, 0, &m_doc_value, func_name(), &docw))
return error_json();
/*
Check if this function is called from an UPDATE statement in a way
that could make partial update possible. For example:
UPDATE t SET json_col = JSON_REPLACE(json_col, '$.pet', 'rabbit')
If partial update was disabled for this column while evaluating the
first argument, don't attempt to perform partial update here.
*/
TABLE *table = nullptr;
if (m_partial_update_column != nullptr) {
table = m_partial_update_column->table;
binary_diffs = table->is_binary_diff_enabled(m_partial_update_column);
logical_diffs = table->is_logical_diff_enabled(m_partial_update_column);
}
if (args[0]->null_value) goto return_null;
String *partial_update_buffer = nullptr;
if (binary_diffs) {
partial_update_buffer = table->get_partial_update_buffer();
// Reset the buffer in the innermost call.
if (args[0]->real_item()->type() == FIELD_ITEM)
partial_update_buffer->length(0);
}
for (uint32 i = 1; i < arg_count; i += 2) {
if (m_path_cache.parse_and_cache_path(thd, args, i, true))
return error_json();
const Json_path *current_path = m_path_cache.get_path(i);
if (current_path == nullptr) goto return_null;
// Clone the path, stripping off redundant auto-wrapping.
if (clone_without_autowrapping(current_path, &m_path, &docw)) {
return error_json();
}
Json_wrapper valuew;
if (get_atom_null_as_null(args, i + 1, func_name(), &m_value,
&m_conversion_buffer, &valuew))
return error_json();
if (binary_diffs) {
bool partially_updated = false;
bool replaced_path = false;
if (docw.attempt_binary_update(m_partial_update_column, m_path, &valuew,
!m_json_set, partial_update_buffer,
&partially_updated, &replaced_path))
return error_json(); /* purecov: inspected */
if (partially_updated) {
if (logical_diffs && replaced_path)
table->add_logical_diff(m_partial_update_column, m_path,
enum_json_diff_operation::REPLACE, &valuew);
/*
Partial update of the binary value was successful, and docw has
been updated accordingly. Go on to updating the next path.
*/
continue;
}
binary_diffs = false;
disable_binary_diffs(m_partial_update_column);
}
// Need a DOM to be able to manipulate arrays and objects
Json_dom *doc = docw.to_dom();
if (!doc) return error_json(); /* purecov: inspected */
Json_dom_vector hits(key_memory_JSON);
if (doc->seek(m_path, m_path.leg_count(), &hits, false, true))
return error_json(); /* purecov: inspected */
if (hits.empty()) {
// Replace semantics, so skip if the path is not present.
if (!m_json_set) continue;
/*
Need to look one step up the path: if we are specifying an array slot
we need to find the array. If we are specifying an object element, we
need to find the object. In both cases so we can insert into them.
Remove the first path leg and search again.
*/
const Json_path_leg *leg = m_path.last_leg();
if (doc->seek(m_path, m_path.leg_count() - 1, &hits, false, true))
return error_json(); /* purecov: inspected */
if (hits.empty()) {
// no unique object found at parent position, so bail out
continue;
}
// We don't allow wildcards in the path, so there can only be one hit.
assert(hits.size() == 1);
Json_dom *hit = hits[0];
// We now have either an array or an object in the parent's path
if (leg->get_type() == jpl_array_cell) {
if (hit->json_type() == enum_json_type::J_ARRAY) {
/*
The array element was not found, so either prepend or
append the new value.
*/
Json_array *arr = down_cast<Json_array *>(hit);
size_t pos = leg->first_array_index(arr->size()).position();
if (arr->insert_alias(pos, valuew.clone_dom()))
return error_json(); /* purecov: inspected */
if (logical_diffs)
table->add_logical_diff(m_partial_update_column, m_path,
enum_json_diff_operation::INSERT,
&valuew);
} else {
/*
Found a scalar or object, auto-wrap it and make it the first
element in a new array, unless the new value specifies position
0, in which case the old value should get replaced. Don't expect
array position to be 0 here, though, as such legs should have
been removed by the call to clone_without_autowrapping() above.
*/
assert(!leg->is_autowrap());
Json_array_ptr newarr = create_dom_ptr<Json_array>();
size_t pos = leg->first_array_index(1).position();
if (newarr == nullptr || newarr->append_clone(hit) ||
newarr->insert_alias(pos, valuew.clone_dom())) {
return error_json(); /* purecov: inspected */
}
/*
Now we need this value to replace the old document we found
using path. If this is root, this is trivial, but if it's
inside an array or object, we need to find the parent DOM to be
able to replace it in situ.
*/
Json_container *parent = hit->parent();
if (parent == nullptr) // root
{
docw = Json_wrapper(std::move(newarr));
// No point in partial update when we replace the entire document.
if (logical_diffs) {
disable_logical_diffs(m_partial_update_column);
logical_diffs = false;
}
} else {
if (logical_diffs) {
Json_wrapper array_wrapper(newarr.get());
array_wrapper.set_alias();
table->add_logical_diff(
m_partial_update_column, hit->get_location(),
enum_json_diff_operation::REPLACE, &array_wrapper);
}
parent->replace_dom_in_container(hit, std::move(newarr));
}
}
} else if (leg->get_type() == jpl_member &&
hit->json_type() == enum_json_type::J_OBJECT) {
Json_object *o = down_cast<Json_object *>(hit);
if (o->add_clone(leg->get_member_name(), valuew.to_dom()))
return error_json(); /* purecov: inspected */
if (logical_diffs)
table->add_logical_diff(m_partial_update_column, m_path,
enum_json_diff_operation::INSERT, &valuew);
}
} else {
// We found one value, so replace semantics.
assert(hits.size() == 1);
Json_dom *child = hits[0];
Json_container *parent = child->parent();
if (parent == nullptr) {
Json_dom_ptr dom = valuew.clone_dom();
if (dom == nullptr) return error_json(); /* purecov: inspected */
docw = Json_wrapper(std::move(dom));
// No point in partial update when we replace the entire document.
if (logical_diffs) {
disable_logical_diffs(m_partial_update_column);
logical_diffs = false;
}
} else {
Json_dom_ptr dom = valuew.clone_dom();
if (!dom) return error_json(); /* purecov: inspected */
parent->replace_dom_in_container(child, std::move(dom));
if (logical_diffs)
table->add_logical_diff(m_partial_update_column, m_path,
enum_json_diff_operation::REPLACE, &valuew);
}
} // if: found 1 else more values
} // do: functions argument list run-though
// docw still owns the augmented doc, so hand it over to result
*wr = std::move(docw);
} catch (...) {
/* purecov: begin inspected */
handle_std_exception(func_name());
return error_json();
/* purecov: end */
}
null_value = false;
return false;
return_null:
/*
When we return NULL, there is no point in doing partial update, as the
entire document changes anyway. Disable binary and logical diffs.
*/
if (binary_diffs) disable_binary_diffs(m_partial_update_column);
if (logical_diffs) disable_logical_diffs(m_partial_update_column);
null_value = true;
return false;
}
bool Item_func_json_array::val_json(Json_wrapper *wr) {
assert(fixed == 1);
try {
Json_array *arr = new (std::nothrow) Json_array();
if (!arr) return error_json(); /* purecov: inspected */
Json_wrapper docw(arr);
for (uint32 i = 0; i < arg_count; ++i) {
Json_wrapper valuew;
if (get_atom_null_as_null(args, i, func_name(), &m_value,
&m_conversion_buffer, &valuew)) {
return error_json();
}
Json_dom_ptr val_dom(valuew.to_dom());
valuew.set_alias(); // release the DOM
if (arr->append_alias(std::move(val_dom)))
return error_json(); /* purecov: inspected */
}
// docw still owns the augmented doc, so hand it over to result
*wr = std::move(docw);
} catch (...) {
/* purecov: begin inspected */
handle_std_exception(func_name());
return error_json();
/* purecov: end */
}
null_value = false;
return false;
}
bool Item_func_json_row_object::val_json(Json_wrapper *wr) {
assert(fixed == 1);
try {
Json_object *object = new (std::nothrow) Json_object();
if (!object) return error_json(); /* purecov: inspected */
Json_wrapper docw(object);
const THD *thd = current_thd;
for (uint32 i = 0; i < arg_count; ++i) {
/*
arguments come in pairs. we have already verified that there
are an even number of args.
*/
uint32 key_idx = i++;
uint32 value_idx = i;
// key
Item *key_item = args[key_idx];
char buff[MAX_FIELD_WIDTH];
String utf8_res(buff, sizeof(buff), &my_charset_utf8mb4_bin);
const char *safep; // contents of key_item, possibly converted
size_t safe_length; // length of safep
if (get_json_object_member_name(thd, key_item, &tmp_key_value, &utf8_res,
&safep, &safe_length))
return error_json();
std::string key(safep, safe_length);
// value
Json_wrapper valuew;
if (get_atom_null_as_null(args, value_idx, func_name(), &m_value,
&m_conversion_buffer, &valuew)) {
return error_json();
}
Json_dom_ptr val_dom(valuew.to_dom());
valuew.set_alias(); // we have taken over the DOM
if (object->add_alias(key, std::move(val_dom)))
return error_json(); /* purecov: inspected */
}
// docw still owns the augmented doc, so hand it over to result
*wr = std::move(docw);
} catch (...) {
/* purecov: begin inspected */
handle_std_exception(func_name());
return error_json();
/* purecov: end */
}
null_value = false;
return false;
}
bool Item_func_json_search::fix_fields(THD *thd, Item **items) {
if (Item_json_func::fix_fields(thd, items)) return true;
// Fabricate a LIKE node
m_source_string_item = new Item_string(&my_charset_utf8mb4_bin);
if (m_source_string_item == nullptr) {
return true; /* purecov: inspected */
}
Item *like_string_item = args[2];
// Get the escape character, if any
if (arg_count > 3) {
Item *escape_item = args[3];
/*
For a standalone LIKE expression,
the escape clause only has to be constant during execution.
However, we require a stronger condition: it must be constant.
That means that we can evaluate the escape clause at resolution time
and copy the results from the JSON_SEARCH() args into the arguments
for the LIKE node which we're fabricating.
*/
if (!escape_item->const_item()) {
my_error(ER_WRONG_ARGUMENTS, MYF(0), "ESCAPE");
return true;
}
m_like_node =
new Item_func_like(m_source_string_item, like_string_item, escape_item);
} else {
m_like_node = new Item_func_like(m_source_string_item, like_string_item);
}
if (m_like_node == nullptr) return true; /* purecov: inspected */
Item *like = m_like_node;
if (m_like_node->fix_fields(thd, &like)) return true;
// Don't expect the LIKE node to be replaced during resolving.
assert(like == m_like_node);
// resolving the LIKE node may overwrite its arguments
Item **resolved_like_args = m_like_node->arguments();
m_source_string_item = down_cast<Item_string *>(resolved_like_args[0]);
return false;
}
void Item_func_json_search::cleanup() {
Item_json_func::cleanup();
m_cached_ooa = ooa_uninitialized;
}
typedef Prealloced_array<std::string, 16> String_set;
/**
Recursive function to find the string values, nested inside
a json document, which satisfy the LIKE condition. As matches
are found, their path locations are added to an evolving
vector of matches.
@param[in] wrapper A subdocument of the original document.
@param[in] path The path location of the subdocument
@param[in,out] matches The evolving vector of matches.
@param[in,out] duplicates Sorted set of paths found already, which is used
to avoid inserting duplicates into @a matches.
@param[in] one_match If true, then terminate search after first match.
@param[in] like_node The LIKE node that's evaluated on the string values.
@param[in] source_string The input string item of the LIKE node.
@retval false on success
@retval true on failure
*/
static bool find_matches(const Json_wrapper &wrapper, String *path,
Json_dom_vector *matches, String_set *duplicates,
bool one_match, Item *like_node,
Item_string *source_string) {
switch (wrapper.type()) {
case enum_json_type::J_STRING: {
if (one_match && !matches->empty()) {
return false;
}
// Evaluate the LIKE node on the JSON string.
const char *data = wrapper.get_data();
uint len = static_cast<uint>(wrapper.get_data_length());
source_string->set_str_with_copy(data, len, &my_charset_utf8mb4_bin);
if (like_node->val_int()) {
// Got a match with the LIKE node. Save the path of the JSON string.
std::pair<String_set::iterator, bool> res =
duplicates->insert_unique(std::string(path->ptr(), path->length()));
if (res.second) {
Json_string *jstr = new (std::nothrow) Json_string(*res.first);
if (!jstr || matches->push_back(jstr))
return true; /* purecov: inspected */
}
}
break;
}
case enum_json_type::J_OBJECT: {
const size_t path_length = path->length();
for (const auto &jwot : Json_object_wrapper(wrapper)) {
// recurse with the member added to the path
const MYSQL_LEX_CSTRING &key = jwot.first;
if (Json_path_leg(key.str, key.length).to_string(path) ||
find_matches(jwot.second, path, matches, duplicates, one_match,
like_node, source_string))
return true; /* purecov: inspected */
path->length(path_length); // restore the path
if (one_match && !matches->empty()) {
return false;
}
}
break;
}
case enum_json_type::J_ARRAY: {
const size_t path_length = path->length();
for (size_t idx = 0; idx < wrapper.length(); idx++) {
// recurse with the array index added to the path
if (Json_path_leg(idx).to_string(path) ||
find_matches(wrapper[idx], path, matches, duplicates, one_match,
like_node, source_string))
return true; /* purecov: inspected */
path->length(path_length); // restore the path
if (one_match && !matches->empty()) {
return false;
}
}
break;
}
default: {
break;
}
} // end switch on wrapper type
return false;
}
bool Item_func_json_search::val_json(Json_wrapper *wr) {
assert(fixed == 1);
Json_dom_vector matches(key_memory_JSON);
try {
/*
The "duplicates" set is used by find_matches() to track which
paths it has added to "matches", so that it doesn't return the
same path multiple times if JSON_SEARCH is called with wildcard
paths or multiple path arguments.
*/
String_set duplicates(key_memory_JSON);
Json_wrapper docw;
// arg 0 is the document
if (get_json_wrapper(args, 0, &m_doc_value, func_name(), &docw))
return error_json();
if (args[0]->null_value) {
null_value = true;
return false;
}
// arg 1 is the oneOrAll arg
THD *const thd = current_thd;
bool one_match;
switch (parse_and_cache_ooa(thd, args[1], &m_cached_ooa, func_name())) {
case ooa_all: {
one_match = false;
break;
}
case ooa_one: {
one_match = true;
break;
}
case ooa_null: {
null_value = true;
return false;
}
default: {
return error_json();
}
}
// arg 2 is the search string
// arg 3 is the optional escape character
// the remaining arguments are path expressions
StringBuffer<STRING_BUFFER_USUAL_SIZE> path_str;
if (arg_count < 5) // no user-supplied path expressions
{
path_str.append('$');
if (find_matches(docw, &path_str, &matches, &duplicates, one_match,
m_like_node, m_source_string_item))
return error_json(); /* purecov: inspected */
} else // user-supplied path expressions
{
Json_wrapper_vector hits(key_memory_JSON);
// validate the user-supplied path expressions
for (uint32 i = 4; i < arg_count; ++i) {
if (m_path_cache.parse_and_cache_path(thd, args, i, false))
return error_json();
if (m_path_cache.get_path(i) == nullptr) {
null_value = true;
return false;
}
}
// find the matches for each of the user-supplied path expressions
for (uint32 i = 4; i < arg_count; ++i) {
if (one_match && (matches.size() > 0)) {
break;
}
const Json_path *path = m_path_cache.get_path(i);
/*
If there are wildcards in the path, then we need to
compute the full path to the subdocument. We can only
do this on doms.
*/
if (path->can_match_many()) {
Json_dom *dom = docw.to_dom();
if (!dom) return error_json(); /* purecov: inspected */
Json_dom_vector dom_hits(key_memory_JSON);
if (dom->seek(*path, path->leg_count(), &dom_hits, false, false))
return error_json(); /* purecov: inspected */
for (Json_dom *subdocument : dom_hits) {
if (one_match && (matches.size() > 0)) {
break;
}
path_str.length(0);
if (subdocument->get_location().to_string(&path_str))
return error_json(); /* purecov: inspected */
Json_wrapper subdocument_wrapper(subdocument);
subdocument_wrapper.set_alias();
if (find_matches(subdocument_wrapper, &path_str, &matches,
&duplicates, one_match, m_like_node,
m_source_string_item))
return error_json(); /* purecov: inspected */
} // end of loop through hits
} else // no wildcards in the path
{
if (one_match && (matches.size() > 0)) break;
hits.clear();
if (docw.seek(*path, path->leg_count(), &hits, false, false))
return error_json(); /* purecov: inspected */
if (hits.empty()) continue;
assert(hits.size() == 1); // no wildcards
path_str.length(0);
if (path->to_string(&path_str))
return error_json(); /* purecov: inspected */
if (find_matches(hits[0], &path_str, &matches, &duplicates, one_match,
m_like_node, m_source_string_item))
return error_json(); /* purecov: inspected */
} // end if the user-supplied path expression has wildcards
} // end of loop through user-supplied path expressions
} // end if there are user-supplied path expressions
} catch (...) {
/* purecov: begin inspected */
handle_std_exception(func_name());
return error_json();
/* purecov: end */
}
if (matches.size() == 0) {
null_value = true;
return false;
} else if (matches.size() == 1) {
*wr = Json_wrapper(matches[0]);
} else {
Json_array_ptr array(new (std::nothrow) Json_array());
if (array == nullptr) return error_json(); /* purecov: inspected */
for (auto match : matches) {
if (array->append_alias(match))
return error_json(); /* purecov: inspected */
}
*wr = Json_wrapper(std::move(array));
}
null_value = false;
return false;
}
bool Item_func_json_remove::val_json(Json_wrapper *wr) {
assert(fixed == 1);
Json_wrapper wrapper;
uint32 path_count = arg_count - 1;
null_value = false;
// Should we collect binary or logical diffs? We'll see later...
bool binary_diffs = false;
bool logical_diffs = false;
TABLE *table = nullptr;
try {
if (get_json_wrapper(args, 0, &m_doc_value, func_name(), &wrapper))
return error_json();
/*
Check if this function is called from an UPDATE statement in a way that
could make partial update possible. For example:
UPDATE t SET json_col = JSON_REMOVE(json_col, '$.name')
If partial update was disabled for this column while evaluating the
first argument, don't attempt to perform partial update here.
*/
if (m_partial_update_column != nullptr) {
table = m_partial_update_column->table;
binary_diffs = table->is_binary_diff_enabled(m_partial_update_column);
logical_diffs = table->is_logical_diff_enabled(m_partial_update_column);
}
if (args[0]->null_value) {
if (binary_diffs) disable_binary_diffs(m_partial_update_column);
if (logical_diffs) disable_logical_diffs(m_partial_update_column);
null_value = true;
return false;
}
const THD *const thd = current_thd;
for (uint path_idx = 0; path_idx < path_count; ++path_idx) {
if (m_path_cache.parse_and_cache_path(thd, args, path_idx + 1, true))
return error_json();
if (m_path_cache.get_path(path_idx + 1) == nullptr) {
if (binary_diffs) disable_binary_diffs(m_partial_update_column);
if (logical_diffs) disable_logical_diffs(m_partial_update_column);
null_value = true;
return false;
}
}
} catch (...) {
/* purecov: begin inspected */
handle_std_exception(func_name());
return error_json();
/* purecov: end */
}
for (uint path_idx = 0; path_idx < path_count; ++path_idx) {
const Json_path *path = m_path_cache.get_path(path_idx + 1);
if (path->leg_count() == 0) {
my_error(ER_JSON_VACUOUS_PATH, MYF(0));
return error_json();
}
}
// good document, good paths. do some work
Json_dom *dom = nullptr;
String *partial_update_buffer = nullptr;
if (binary_diffs) {
assert(!wrapper.is_dom());
partial_update_buffer = table->get_partial_update_buffer();
// Reset the buffer in the innermost call.
if (args[0]->real_item()->type() == FIELD_ITEM)
partial_update_buffer->length(0);
} else {
// If we cannot do binary update, let's work on the DOM instead.
dom = wrapper.to_dom();
if (dom == nullptr) return error_json(); /* purecov: inspected */
}
// remove elements identified by the paths, one after the other
Json_dom_vector hits(key_memory_JSON);
Json_path_clone path(key_memory_JSON);
for (uint path_idx = 0; path_idx < path_count; ++path_idx) {
if (clone_without_autowrapping(m_path_cache.get_path(path_idx + 1), &path,
&wrapper))
return error_json(); /* purecov: inspected */
// Cannot remove the root of the document.
if (path.leg_count() == 0) continue;
if (binary_diffs) {
bool found_path = false;
if (wrapper.binary_remove(m_partial_update_column, path,
partial_update_buffer, &found_path))
return error_json(); /* purecov: inspected */
if (!found_path) continue;
} else {
const Json_path_leg *last_leg = path.last_leg();
hits.clear();
if (dom->seek(path, path.leg_count() - 1, &hits, false, true))
return error_json(); /* purecov: inspected */
if (hits.empty()) continue; // nothing to do
assert(hits.size() == 1);
Json_dom *parent = hits[0];
if (parent->json_type() == enum_json_type::J_OBJECT) {
auto object = down_cast<Json_object *>(parent);
if (last_leg->get_type() != jpl_member ||
!object->remove(last_leg->get_member_name()))
continue;
} else if (parent->json_type() == enum_json_type::J_ARRAY) {
auto array = down_cast<Json_array *>(parent);
if (last_leg->get_type() != jpl_array_cell) continue;
Json_array_index idx = last_leg->first_array_index(array->size());
if (!idx.within_bounds() || !array->remove(idx.position())) continue;
} else {
// Nothing to do. Only objects and arrays can contain values to remove.
continue;
}
}
if (logical_diffs)
table->add_logical_diff(m_partial_update_column, path,
enum_json_diff_operation::REMOVE, nullptr);
} // end of loop through all paths
// wrapper still owns the pruned doc, so hand it over to result
*wr = std::move(wrapper);
return false;
}
Item_func_json_merge::Item_func_json_merge(THD *thd, const POS &pos,
PT_item_list *a)
: Item_func_json_merge_preserve(thd, pos, a) {
push_deprecated_warn(thd, "JSON_MERGE",
"JSON_MERGE_PRESERVE/JSON_MERGE_PATCH");
}
bool Item_func_json_merge_preserve::val_json(Json_wrapper *wr) {
assert(fixed == 1);
Json_dom_ptr result_dom;
try {
for (uint idx = 0; idx < arg_count; idx++) {
Json_wrapper next_wrapper;
if (get_json_wrapper(args, idx, &m_value, func_name(), &next_wrapper))
return error_json();
if (args[idx]->null_value) {
null_value = true;
return false;
}
/*
Grab the next DOM, release it from its wrapper, and merge it
into the previous DOM.
*/
Json_dom_ptr next_dom(next_wrapper.to_dom());
next_wrapper.set_alias();
if (next_dom == nullptr) return error_json(); /* purecov: inspected */
if (idx == 0)
result_dom = std::move(next_dom);
else
result_dom = merge_doms(std::move(result_dom), std::move(next_dom));
if (result_dom == nullptr) return error_json(); /* purecov: inspected */
}
} catch (...) {
/* purecov: begin inspected */
handle_std_exception(func_name());
return error_json();
/* purecov: end */
}
*wr = Json_wrapper(std::move(result_dom));
null_value = false;
return false;
}
String *Item_func_json_quote::val_str(String *str) {
assert(fixed == 1);
String *res = args[0]->val_str(str);
if (!res) {
null_value = true;
return nullptr;
}
try {
const char *safep;
size_t safep_size;
switch (args[0]->data_type()) {
case MYSQL_TYPE_STRING:
case MYSQL_TYPE_VAR_STRING:
case MYSQL_TYPE_VARCHAR:
case MYSQL_TYPE_BLOB:
case MYSQL_TYPE_LONG_BLOB:
case MYSQL_TYPE_MEDIUM_BLOB:
case MYSQL_TYPE_TINY_BLOB:
break;
default:
my_error(ER_INCORRECT_TYPE, MYF(0), "1", func_name());
return error_str();
}
if (ensure_utf8mb4(*res, &m_value, &safep, &safep_size, true)) {
null_value = true;
return nullptr;
}
/*
One of the string buffers (str or m_value) is no longer in use
and can be reused as the result buffer. Which of them it is,
depends on whether or not ensure_utf8mb4() needed to do charset
conversion. Make res point to the available buffer.
*/
if (safep == m_value.ptr()) {
/*
ensure_utf8mb4() converted the input string to utf8mb4 by
copying it into m_value. str is now available for reuse as
result buffer.
*/
res = str;
} else {
/*
Conversion to utf8mb4 was not needed, so ensure_utf8mb4() did
not touch the m_value buffer, and the input string still lives
in res. Use m_value as result buffer.
*/
assert(safep == res->ptr());
res = &m_value;
}
res->length(0);
res->set_charset(&my_charset_utf8mb4_bin);
if (double_quote(safep, safep_size, res))
return error_str(); /* purecov: inspected */
} catch (...) {
/* purecov: begin inspected */
handle_std_exception(func_name());
return error_str();
/* purecov: end */
}
null_value = false;
return res;
}
String *Item_func_json_unquote::val_str(String *str) {
assert(fixed == 1);
try {
if (args[0]->data_type() == MYSQL_TYPE_JSON) {
Json_wrapper wr;
if (get_json_wrapper(args, 0, str, func_name(), &wr)) {
return error_str();
}
if (args[0]->null_value) {
null_value = true;
return nullptr;
}
m_value.length(0);
if (wr.to_string(&m_value, false, func_name(),
JsonDocumentDefaultDepthHandler)) {
return error_str();
}
null_value = false;
// String pointer may be null.
if (m_value.is_empty()) return make_empty_result();
return &m_value;
}
String *res = args[0]->val_str(str);
if (!res) {
null_value = true;
return nullptr;
}
/*
We only allow a string argument, so get rid of any other
type arguments.
*/
switch (args[0]->data_type()) {
case MYSQL_TYPE_STRING:
case MYSQL_TYPE_VAR_STRING:
case MYSQL_TYPE_VARCHAR:
case MYSQL_TYPE_BLOB:
case MYSQL_TYPE_LONG_BLOB:
case MYSQL_TYPE_MEDIUM_BLOB:
case MYSQL_TYPE_TINY_BLOB:
break;
default:
my_error(ER_INCORRECT_TYPE, MYF(0), "1", func_name());
return error_str();
}
const char *utf8text;
size_t utf8len;
if (ensure_utf8mb4(*res, &m_conversion_buffer, &utf8text, &utf8len, true))
return error_str();
String *utf8str = (res->ptr() == utf8text) ? res : &m_conversion_buffer;
assert(utf8text == utf8str->ptr());
if (utf8len < 2 || utf8text[0] != '"' || utf8text[utf8len - 1] != '"') {
null_value = false;
// Return string unchanged, but convert to utf8mb4 if needed.
if (res == utf8str) {
return res;
}
if (str->copy(utf8text, utf8len, collation.collation))
return error_str(); /* purecov: inspected */
return str;
}
Json_dom_ptr dom;
JsonParseDefaultErrorHandler parse_handler(func_name(), 0);
if (parse_json(*utf8str, &dom, true, parse_handler,
JsonDocumentDefaultDepthHandler)) {
return error_str();
}
/*
Extract the internal string representation as a MySQL string
*/
assert(dom->json_type() == enum_json_type::J_STRING);
Json_wrapper wr(std::move(dom));
if (str->copy(wr.get_data(), wr.get_data_length(), collation.collation))
return error_str(); /* purecov: inspected */
} catch (...) {
/* purecov: begin inspected */
handle_std_exception(func_name());
return error_str();
/* purecov: end */
}
null_value = false;
return str;
}
String *Item_func_json_pretty::val_str(String *str) {
assert(fixed);
try {
Json_wrapper wr;
if (get_json_wrapper(args, 0, str, func_name(), &wr)) return error_str();
null_value = args[0]->null_value;
if (null_value) return nullptr;
str->length(0);
if (wr.to_pretty_string(str, func_name(), JsonDocumentDefaultDepthHandler))
return error_str(); /* purecov: inspected */
return str;
}
/* purecov: begin inspected */
catch (...) {
handle_std_exception(func_name());
return error_str();
}
/* purecov: end */
}
longlong Item_func_json_storage_size::val_int() {
assert(fixed);
/*
If the input is a reference to a JSON column, return the actual storage
size of the value in the table.
*/
if (args[0]->type() == FIELD_ITEM &&
args[0]->data_type() == MYSQL_TYPE_JSON) {
null_value = args[0]->is_null();
if (null_value) return 0;
return down_cast<Item_field *>(args[0])->field->data_length();
}
/*
Otherwise, return the size required to store the argument if it were
serialized to the binary JSON format.
*/
Json_wrapper wrapper;
StringBuffer<STRING_BUFFER_USUAL_SIZE> buffer;
try {
if (get_json_wrapper(args, 0, &buffer, func_name(), &wrapper))
return error_int();
}
/* purecov: begin inspected */
catch (...) {
handle_std_exception(func_name());
return error_int();
}
/* purecov: end */
null_value = args[0]->null_value;
if (null_value) return 0;
if (wrapper.to_binary(current_thd, &buffer))
return error_int(); /* purecov: inspected */
return buffer.length();
}
longlong Item_func_json_storage_free::val_int() {
assert(fixed);
Json_wrapper wrapper;
try {
StringBuffer<STRING_BUFFER_USUAL_SIZE> buffer;
if (get_json_wrapper(args, 0, &buffer, func_name(), &wrapper))
return error_int();
}
/* purecov: begin inspected */
catch (...) {
handle_std_exception(func_name());
return error_int();
}
/* purecov: end */
null_value = args[0]->null_value;
if (null_value) return 0;
size_t space;
if (wrapper.get_free_space(&space))
return error_int(); /* purecov: inspected */
return space;
}
bool Item_func_json_merge_patch::val_json(Json_wrapper *wr) {
assert(fixed);
try {
if (get_json_wrapper(args, 0, &m_value, func_name(), wr))
return error_json();
null_value = args[0]->null_value;
Json_wrapper patch_wr;
for (uint i = 1; i < arg_count; ++i) {
if (get_json_wrapper(args, i, &m_value, func_name(), &patch_wr))
return error_json();
if (args[i]->null_value) {
/*
The patch is unknown, so the result so far is unknown. We
cannot return NULL immediately, since a later patch can give
a known result. This is because the result of a merge
operation is the patch itself if the patch is not an object,
regardless of what the target document is.
*/
null_value = true;
continue;
}
/*
If a patch is not an object, the result of the merge operation
is the patch itself. So just set the result to this patch and
go on to the next patch.
*/
if (patch_wr.type() != enum_json_type::J_OBJECT) {
*wr = std::move(patch_wr);
null_value = false;
continue;
}
/*
The target document is unknown, and we cannot tell the result
from the patch alone when the patch is an object, so go on to
the next patch.
*/
if (null_value) continue;
/*
Get the DOM representation of the target document. It should
be an object, and we will use an empty object if it is not.
*/
Json_object_ptr target_dom;
if (wr->type() == enum_json_type::J_OBJECT) {
target_dom.reset(down_cast<Json_object *>(wr->to_dom()));
wr->set_alias();
} else {
target_dom = create_dom_ptr<Json_object>();
}
if (target_dom == nullptr) return error_json(); /* purecov: inspected */
// Get the DOM representation of the patch object.
Json_object_ptr patch_dom(down_cast<Json_object *>(patch_wr.to_dom()));
patch_wr.set_alias();
// Apply the patch on the target document.
if (patch_dom == nullptr || target_dom->merge_patch(std::move(patch_dom)))
return error_json(); /* purecov: inspected */
// Move the result of the merge operation into the result wrapper.
*wr = Json_wrapper(std::move(target_dom));
null_value = false;
}
return false;
}
/* purecov: begin inspected */
catch (...) {
handle_std_exception(func_name());
return error_json();
}
/* purecov: end */
}
/**
Sets the data type of an Item_func_array_cast or Item_func_json_value based on
the Cast_type.
@param item the Item whose data type to set
@param cast_type the type of cast
@param length the declared length of the target type
@param decimals the declared precision of the target type
@param charset the character set of the target type (nullptr if not
specified)
*/
static void set_data_type_from_cast_type(Item *item, Cast_target cast_type,
unsigned length, unsigned decimals,
const CHARSET_INFO *charset) {
switch (cast_type) {
case ITEM_CAST_SIGNED_INT:
item->set_data_type_longlong();
item->unsigned_flag = false;
return;
case ITEM_CAST_UNSIGNED_INT:
item->set_data_type_longlong();
item->unsigned_flag = true;
return;
case ITEM_CAST_DATE:
item->set_data_type_date();
return;
case ITEM_CAST_YEAR:
item->set_data_type_year();
return;
case ITEM_CAST_TIME:
item->set_data_type_time(decimals);
return;
case ITEM_CAST_DATETIME:
item->set_data_type_datetime(decimals);
return;
case ITEM_CAST_DECIMAL:
item->set_data_type_decimal(length, decimals);
return;
case ITEM_CAST_CHAR:
// If no character set is specified, the JSON default character set is
// used.
if (charset == nullptr)
item->set_data_type_string(length, &my_charset_utf8mb4_0900_bin);
else
item->set_data_type_string(length, charset);
return;
case ITEM_CAST_JSON:
// JSON_VALUE(... RETURNING JSON) is supported, CAST(... AS JSON ARRAY) is
// not supported.
assert(!item->returns_array());
item->set_data_type_json();
return;
case ITEM_CAST_DOUBLE:
item->set_data_type_double();
return;
case ITEM_CAST_FLOAT:
item->set_data_type_float();
return;
// JSON_VALUE(... RETURNING <geometry type>) is not supported
case ITEM_CAST_POINT:
my_error(ER_INVALID_CAST_TO_GEOMETRY, MYF(0), "JSON", "POINT");
return;
case ITEM_CAST_LINESTRING:
my_error(ER_INVALID_CAST_TO_GEOMETRY, MYF(0), "JSON", "LINESTRING");
return;
case ITEM_CAST_POLYGON:
my_error(ER_INVALID_CAST_TO_GEOMETRY, MYF(0), "JSON", "POLYGON");
return;
case ITEM_CAST_MULTIPOINT:
my_error(ER_INVALID_CAST_TO_GEOMETRY, MYF(0), "JSON", "MULTIPOINT");
return;
case ITEM_CAST_MULTILINESTRING:
my_error(ER_INVALID_CAST_TO_GEOMETRY, MYF(0), "JSON", "MULTILINESTRING");
return;
case ITEM_CAST_MULTIPOLYGON:
my_error(ER_INVALID_CAST_TO_GEOMETRY, MYF(0), "JSON", "MULTIPOLYGON");
return;
case ITEM_CAST_GEOMETRYCOLLECTION:
my_error(ER_INVALID_CAST_TO_GEOMETRY, MYF(0), "JSON",
"GEOMETRYCOLLECTION");
return;
}
assert(false); /* purecov: deadcode */
}
Item_func_array_cast::Item_func_array_cast(const POS &pos, Item *a,
Cast_target type, uint len_arg,
uint dec_arg,
const CHARSET_INFO *cs_arg)
: Item_func(pos, a), cast_type(type) {
set_data_type_from_cast_type(this, type, len_arg, dec_arg, cs_arg);
}
Item_func_array_cast::~Item_func_array_cast() = default;
bool Item_func_array_cast::val_json(Json_wrapper *wr) {
try {
String data_buf;
if (get_json_wrapper(args, 0, &data_buf, func_name(), wr))
return error_json();
null_value = args[0]->null_value;
return false;
/* purecov: begin inspected */
} catch (...) {
handle_std_exception(func_name());
return error_json();
}
/* purecov: end */
}
bool Item_func_array_cast::fix_fields(THD *thd, Item **ref) {
// Prohibit use of CAST AS ARRAY outside of functional index expressions.
if (!m_is_allowed) {
my_error(ER_NOT_SUPPORTED_YET, MYF(0),
"Use of CAST( .. AS .. ARRAY) outside of functional index in "
"CREATE(non-SELECT)/ALTER TABLE or in general expressions");
return true;
}
if (m_result_array == nullptr) {
Prepared_stmt_arena_holder ps_arena_holder(thd);
m_result_array.reset(::new (thd->mem_root) Json_array);
if (m_result_array == nullptr) return true;
}
return Item_func::fix_fields(thd, ref);
}
/**
Prints the target type of a cast operation (either CAST or JSON_VALUE).
@param cast_type the cast type
@param item the Item in which the cast operation is performed
@param[out] str the string to print to
*/
static void print_cast_type(Cast_target cast_type, const Item *item,
String *str) {
const unsigned decimals = item->decimals;
switch (cast_type) {
case ITEM_CAST_SIGNED_INT:
str->append(STRING_WITH_LEN("signed"));
return;
case ITEM_CAST_UNSIGNED_INT:
str->append(STRING_WITH_LEN("unsigned"));
return;
case ITEM_CAST_DATE:
str->append(STRING_WITH_LEN("date"));
return;
case ITEM_CAST_YEAR:
str->append(STRING_WITH_LEN("year"));
return;
case ITEM_CAST_TIME:
str->append(STRING_WITH_LEN("time"));
if (decimals > 0) str->append_parenthesized(decimals);
return;
case ITEM_CAST_DATETIME:
str->append(STRING_WITH_LEN("datetime"));
if (decimals > 0) str->append_parenthesized(decimals);
return;
case ITEM_CAST_DECIMAL:
// length and dec are already set
str->append(STRING_WITH_LEN("decimal("));
str->append_ulonglong(my_decimal_length_to_precision(
item->max_length, decimals, item->unsigned_flag));
str->append(STRING_WITH_LEN(", "));
str->append_ulonglong(decimals);
str->append(')');
return;
case ITEM_CAST_CHAR: {
const CHARSET_INFO *const cs = item->collation.collation;
if (cs == &my_charset_bin) {
str->append(STRING_WITH_LEN("binary"));
str->append_parenthesized(item->max_length);
} else {
str->append(STRING_WITH_LEN("char"));
str->append_parenthesized(item->max_char_length());
if (cs != &my_charset_utf8mb4_0900_bin) {
str->append(STRING_WITH_LEN(" character set "));
str->append(cs->csname);
}
}
return;
}
case ITEM_CAST_JSON:
str->append(STRING_WITH_LEN("json"));
return;
case ITEM_CAST_FLOAT:
str->append(STRING_WITH_LEN("float"));
return;
case ITEM_CAST_DOUBLE:
str->append(STRING_WITH_LEN("double"));
return;
/* purecov: begin inspected */
case ITEM_CAST_POINT:
str->append(STRING_WITH_LEN("point"));
return;
case ITEM_CAST_LINESTRING:
str->append(STRING_WITH_LEN("linestring"));
return;
case ITEM_CAST_POLYGON:
str->append(STRING_WITH_LEN("polygon"));
return;
case ITEM_CAST_MULTIPOINT:
str->append(STRING_WITH_LEN("multipoint"));
return;
case ITEM_CAST_MULTILINESTRING:
str->append(STRING_WITH_LEN("multilinestring"));
return;
case ITEM_CAST_MULTIPOLYGON:
str->append(STRING_WITH_LEN("multipolygon"));
return;
case ITEM_CAST_GEOMETRYCOLLECTION:
str->append(STRING_WITH_LEN("geometrycollection"));
return;
/* purecov: end */
}
assert(false); /* purecov: deadcode */
}
void Item_func_array_cast::print(const THD *thd, String *str,
enum_query_type query_type) const {
str->append(STRING_WITH_LEN("cast("));
args[0]->print(thd, str, query_type);
str->append(STRING_WITH_LEN(" as "));
print_cast_type(cast_type, this, str);
str->append(STRING_WITH_LEN(" array)"));
}
bool Item_func_array_cast::resolve_type(THD *) {
set_nullable(true);
return false;
}
static enum Item_result json_cast_result_type(Cast_target cast_type) {
switch (cast_type) {
case ITEM_CAST_SIGNED_INT:
case ITEM_CAST_YEAR:
case ITEM_CAST_UNSIGNED_INT:
return INT_RESULT;
case ITEM_CAST_DATE:
case ITEM_CAST_TIME:
case ITEM_CAST_DATETIME:
case ITEM_CAST_CHAR:
case ITEM_CAST_JSON:
return STRING_RESULT;
case ITEM_CAST_DECIMAL:
return DECIMAL_RESULT;
case ITEM_CAST_FLOAT:
case ITEM_CAST_DOUBLE:
return REAL_RESULT;
/* purecov: begin inspected */
case ITEM_CAST_POINT:
case ITEM_CAST_LINESTRING:
case ITEM_CAST_POLYGON:
case ITEM_CAST_MULTIPOINT:
case ITEM_CAST_MULTILINESTRING:
case ITEM_CAST_MULTIPOLYGON:
case ITEM_CAST_GEOMETRYCOLLECTION:
return INVALID_RESULT;
/* purecov: end */
}
assert(false); /* purecov: deadcode */
return INT_RESULT;
}
enum Item_result Item_func_array_cast::result_type() const {
return json_cast_result_type(cast_type);
}
type_conversion_status Item_func_array_cast::save_in_field_inner(Field *field,
bool) {
// Array of any type is stored as JSON.
Json_wrapper wr;
if (val_json(&wr)) return TYPE_ERR_BAD_VALUE;
if (null_value) return set_field_to_null(field);
field->set_notnull();
return down_cast<Field_typed_array *>(field)->store_array(
&wr, m_result_array.get());
}
void Item_func_array_cast::cleanup() { Item_func::cleanup(); }
/// Converts the "data type" used by Item to a "real type" used by Field.
static enum_field_types data_type_to_real_type(enum_field_types data_type) {
// Only temporal types have different "data type" and "real type".
switch (data_type) {
case MYSQL_TYPE_DATE:
return MYSQL_TYPE_NEWDATE;
case MYSQL_TYPE_TIME:
return MYSQL_TYPE_TIME2;
case MYSQL_TYPE_DATETIME:
return MYSQL_TYPE_DATETIME2;
default:
return data_type;
}
}
Field *Item_func_array_cast::tmp_table_field(TABLE *table) {
auto array_field = new (*THR_MALLOC) Field_typed_array(
data_type_to_real_type(data_type()), unsigned_flag, max_length, decimals,
nullptr, nullptr, 0, 0, "", table->s, 4, collation.collation);
if (array_field == nullptr) return nullptr;
array_field->init(table);
return array_field;
}
bool Field_typed_array::coerce_json_value(const Json_wrapper *wr, bool no_error,
Json_wrapper *coerced) const {
Json_wrapper saved;
THD *thd = current_thd;
// Save JSON value to the conversion field
if (wr->type() == enum_json_type::J_NULL) {
Json_dom_ptr elt;
if (!coerced) return false;
*coerced = Json_wrapper(create_dom_ptr<Json_null>());
return false;
}
String value, tmp;
/*
If caller isn't interested in the result, then it's a check on whether
the value is coercible at all. In such case don't throw an error, just
return 'true' when value isn't coercible.
*/
if (save_json_to_field(thd, m_conv_item->field, wr, no_error)) return true;
// The calling_function arg below isn't needed as it's used only for
// geometry and geometry arrays aren't supported
if (sql_scalar_to_json(m_conv_item, "<typed array>", &value, &tmp, &saved,
nullptr, true))
return true;
if (!coerced) return false;
*coerced = std::move(saved);
return false;
}
longlong Item_func_json_overlaps::val_int() {
int res = 0;
null_value = false;
try {
String m_doc_value;
Json_wrapper wr_a, wr_b;
Json_wrapper *doc_a = &wr_a;
Json_wrapper *doc_b = &wr_b;
// arg 0 is the document 1
if (get_json_wrapper(args, 0, &m_doc_value, func_name(), doc_a) ||
args[0]->null_value) {
null_value = true;
return 0;
}
// arg 1 is the document 2
if (get_json_wrapper(args, 1, &m_doc_value, func_name(), doc_b) ||
args[1]->null_value) {
null_value = true;
return 0;
}
// Handle case when doc_a is non-array and doc_b is array
if (doc_a->type() != enum_json_type::J_ARRAY &&
doc_b->type() == enum_json_type::J_ARRAY)
std::swap(doc_a, doc_b);
// Search in longer array
if (doc_a->type() == enum_json_type::J_ARRAY &&
doc_b->type() == enum_json_type::J_ARRAY &&
doc_b->length() > doc_a->length())
std::swap(doc_a, doc_b);
switch (doc_a->type()) {
case enum_json_type::J_ARRAY: {
uint b_length = doc_b->length();
Json_array *arr = down_cast<Json_array *>(doc_a->to_dom());
// Use array auto-wrap to address whole object/scalar
if (doc_b->type() != enum_json_type::J_ARRAY) b_length = 1;
// Sort array and use binary search to lookup values
arr->sort();
for (uint i = 0; i < b_length; i++) {
res = arr->binary_search((*doc_b)[i].to_dom());
if (res) break;
}
break;
}
case enum_json_type::J_OBJECT: {
// Objects can't overlap with a scalar and object vs array is
// handled above
if (doc_b->type() != enum_json_type::J_OBJECT) return 0;
for (const auto &i : Json_object_wrapper(*doc_a)) {
Json_wrapper elt_b = doc_b->lookup(i.first);
// Not found
if (elt_b.type() == enum_json_type::J_ERROR) continue;
if ((res = (!elt_b.compare(i.second)))) break;
}
break;
}
default:
// When both args are scalars behave like =
return !doc_a->compare(*doc_b);
}
/* purecov: begin inspected */
} catch (...) {
handle_std_exception(func_name());
return error_int();
/* purecov: end */
}
return res;
}
/**
Return field Item that can be used for index lookups.
JSON_OVERLAPS can be optimized using index in following cases
JSON_OVERLAPS([json expr], [const json array])
JSON_OVERLAPS([const json array], [json expr])
If there's a functional index matching [json expr], the latter will be
substituted for the GC field of the index. This function returns such a field
so that the optimizer can generate range access for the index over that field.
@returns
Item_field field that can be used to generate index access
NULL when no such field
*/
Item *Item_func_json_overlaps::key_item() const {
for (uint i = 0; i < arg_count; i++)
if (args[i]->type() == Item::FIELD_ITEM && args[i]->returns_array())
return args[i];
return nullptr;
}
longlong Item_func_member_of::val_int() {
null_value = false;
try {
String m_doc_value;
String conv_buf;
Json_wrapper doc_a, doc_b;
bool is_doc_b_sorted = false;
// arg 0 is the value to lookup
if (get_json_atom_wrapper(args, 0, func_name(), &m_doc_value, &conv_buf,
&doc_a, nullptr, true) ||
args[0]->null_value) {
null_value = true;
return 0;
}
// arg 1 is the array to look up value in
if (get_json_wrapper(args, 1, &m_doc_value, func_name(), &doc_b) ||
args[1]->null_value) {
null_value = true;
return 0;
}
// If it's cached as JSON, pre-sort array (only) for faster lookups
if (args[1]->type() == Item::CACHE_ITEM &&
args[1]->data_type() == MYSQL_TYPE_JSON) {
Item_cache_json *cache = down_cast<Item_cache_json *>(args[1]);
if (!(is_doc_b_sorted = cache->is_sorted())) {
cache->sort();
if (cache->val_json(&doc_b)) return error_int();
is_doc_b_sorted = true;
}
}
null_value = false;
if (doc_b.type() != enum_json_type::J_ARRAY)
return (!doc_a.compare(doc_b));
else if (is_doc_b_sorted) {
Json_array *arr = down_cast<Json_array *>(doc_b.to_dom());
return arr->binary_search(doc_a.to_dom());
} else {
for (uint i = 0; i < doc_b.length(); i++) {
Json_wrapper elt = doc_b[i];
if (!doc_a.compare(elt)) return true;
}
}
/* purecov: begin inspected */
} catch (...) {
handle_std_exception(func_name());
return error_int();
/* purecov: end */
}
return false;
}
void Item_func_member_of::print(const THD *thd, String *str,
enum_query_type query_type) const {
args[0]->print(thd, str, query_type);
str->append(STRING_WITH_LEN(" member of ("));
args[1]->print(thd, str, query_type);
str->append(')');
}
/**
Check if a JSON value is a JSON OPAQUE, and if it can be printed in the field
as a non base64 value.
This is currently used by JSON_TABLE to see if we can print the JSON value in
a field without having to encode it in base64.
@param field_to_store_in The field we want to store the JSON value in
@param json_data The JSON value we want to store.
@returns
true The JSON value can be stored without encoding it in base64
false The JSON value can not be stored without encoding it, or it is not a
JSON OPAQUE value.
*/
static bool can_store_json_value_unencoded(const Field *field_to_store_in,
const Json_wrapper *json_data) {
return (field_to_store_in->type() == MYSQL_TYPE_VARCHAR ||
field_to_store_in->type() == MYSQL_TYPE_BLOB ||
field_to_store_in->type() == MYSQL_TYPE_STRING) &&
json_data->type() == enum_json_type::J_OPAQUE &&
(json_data->field_type() == MYSQL_TYPE_STRING ||
json_data->field_type() == MYSQL_TYPE_VARCHAR);
}
/**
Save JSON to a given field
Value is saved in type-aware manner. Into a JSON-typed column any JSON
data could be saved. Into an SQL scalar field only a scalar could be
saved. If data being saved isn't scalar or can't be coerced to the target
type, an error is returned.
@param thd Thread handler
@param field Field to save data to
@param w JSON data to save
@param no_error If true, don't raise an error when the value cannot be
converted to the target type
@returns
false ok
true coercion error occur
*/
bool save_json_to_field(THD *thd, Field *field, const Json_wrapper *w,
bool no_error) {
field->set_notnull();
if (field->type() == MYSQL_TYPE_JSON) {
Field_json *fld = down_cast<Field_json *>(field);
return (fld->store_json(w) != TYPE_OK);
}
const enum_coercion_error cr_error = no_error ? CE_WARNING : CE_ERROR;
if (w->type() == enum_json_type::J_ARRAY ||
w->type() == enum_json_type::J_OBJECT) {
if (!no_error)
my_error(ER_WRONG_JSON_TABLE_VALUE, MYF(0), field->field_name);
return true;
}
auto truncated_fields_guard =
create_scope_guard([thd, saved = thd->check_for_truncated_fields]() {
thd->check_for_truncated_fields = saved;
});
thd->check_for_truncated_fields =
no_error ? CHECK_FIELD_IGNORE : CHECK_FIELD_ERROR_FOR_NULL;
bool err = false;
switch (field->result_type()) {
case INT_RESULT: {
longlong value =
w->coerce_int(field->field_name, cr_error, &err, nullptr);
// If the Json_wrapper holds a numeric value, grab the signedness from it.
// If not, grab the signedness from the column where we are storing the
// value.
bool value_unsigned;
if (w->type() == enum_json_type::J_INT) {
value_unsigned = false;
} else if (w->type() == enum_json_type::J_UINT) {
value_unsigned = true;
} else {
value_unsigned = field->is_unsigned();
}
if (!err)
err = field->store(value, value_unsigned) >= TYPE_WARN_OUT_OF_RANGE;
break;
}
case STRING_RESULT: {
MYSQL_TIME ltime;
bool date_time_handled = false;
/*
Here we explicitly check for DATE/TIME to reduce overhead by
avoiding encoding data into string in JSON code and decoding it
back from string in Field code.
Ensure that date is saved to a date column, and time into time
column. Don't mix.
*/
if (is_temporal_type_with_date(field->type())) {
switch (w->type()) {
case enum_json_type::J_DATE:
case enum_json_type::J_DATETIME:
case enum_json_type::J_TIMESTAMP:
date_time_handled = true;
err = w->coerce_date(<ime, "JSON_TABLE", cr_error);
break;
default:
break;
}
} else if (field->type() == MYSQL_TYPE_TIME &&
w->type() == enum_json_type::J_TIME) {
date_time_handled = true;
err = w->coerce_time(<ime, "JSON_TABLE", cr_error);
}
if (date_time_handled) {
err = err || field->store_time(<ime);
break;
}
// Initialize with an explicit empty string pointer,
// instead of the default nullptr.
// The reason is that we pass str.ptr() to Field::store()
// which may end up calling memmove() which may have
// __attribute__((nonnull)) on its 'src' argument.
String str{"", 0, /* charset= */ nullptr};
if (can_store_json_value_unencoded(field, w)) {
str.set(w->get_data(), w->get_data_length(), field->charset());
} else {
err = w->to_string(&str, false, "JSON_TABLE",
JsonDocumentDefaultDepthHandler);
}
if (!err && (field->store(str.ptr(), str.length(), str.charset()) >=
TYPE_WARN_OUT_OF_RANGE))
err = true;
break;
}
case REAL_RESULT: {
double value = w->coerce_real(field->field_name, cr_error, &err);
if (!err && (field->store(value) >= TYPE_WARN_OUT_OF_RANGE)) err = true;
break;
}
case DECIMAL_RESULT: {
my_decimal value;
w->coerce_decimal(&value, field->field_name, cr_error, &err);
if (!err && (field->store_decimal(&value) >= TYPE_WARN_OUT_OF_RANGE))
err = true;
break;
}
case ROW_RESULT:
default:
// Shouldn't happen
assert(0);
}
if (err && !no_error)
my_error(ER_JT_VALUE_OUT_OF_RANGE, MYF(0), field->field_name);
return err;
}
struct Item_func_json_value::Default_value {
int64_t integer_default;
const MYSQL_TIME *temporal_default;
LEX_CSTRING string_default;
const my_decimal *decimal_default;
std::unique_ptr<Json_dom> json_default;
double real_default;
};
Item_func_json_value::Item_func_json_value(
const POS &pos, Item *arg, Item *path, const Cast_type &cast_type,
unsigned length, unsigned precision, Json_on_response_type on_empty_type,
Item *on_empty_default, Json_on_response_type on_error_type,
Item *on_error_default)
: Item_func(pos, arg, path, on_empty_default, on_error_default),
m_path_json(key_memory_JSON),
m_on_empty(on_empty_type),
m_on_error(on_error_type),
m_cast_target(cast_type.target) {
set_data_type_from_cast_type(this, m_cast_target, length, precision,
cast_type.charset);
}
Item_func_json_value::~Item_func_json_value() = default;
enum Item_result Item_func_json_value::result_type() const {
return json_cast_result_type(m_cast_target);
}
bool Item_func_json_value::resolve_type(THD *) {
// The path must be a character literal, so it's never NULL.
assert(!args[1]->is_nullable());
// The DEFAULT values are character literals, so they are never NULL if they
// are specified.
assert(m_on_empty != Json_on_response_type::DEFAULT ||
!args[2]->is_nullable());
assert(m_on_error != Json_on_response_type::DEFAULT ||
!args[3]->is_nullable());
// JSON_VALUE can return NULL if its first argument is nullable, or if NULL
// ON EMPTY or NULL ON ERROR is specified or implied, or if the extracted JSON
// value is the JSON null literal.
set_nullable(true);
return false;
}
/**
Checks if a decimal value is within the range of the data type of an Item. It
is considered within range if it can be converted to the data type without
losing any leading significant digits.
*/
static bool decimal_within_range(const Item *item, const my_decimal *decimal) {
assert(item->data_type() == MYSQL_TYPE_NEWDECIMAL);
return decimal_intg(decimal) <= item->decimal_int_part();
}
unique_ptr_destroy_only<Item_func_json_value::Default_value>
Item_func_json_value::create_json_value_default(THD *thd, Item *item) {
MEM_ROOT *const mem_root = thd->mem_root;
auto default_value = make_unique_destroy_only<Default_value>(mem_root);
if (default_value == nullptr) return nullptr;
// Evaluate the defaults under strict mode, so that an error is raised if the
// default value cannot be converted to the target type without warnings.
Strict_error_handler strict_handler{
Strict_error_handler::ENABLE_SET_SELECT_STRICT_ERROR_HANDLER};
auto strict_handler_guard =
create_scope_guard([thd, saved_sql_mode = thd->variables.sql_mode]() {
thd->pop_internal_handler();
thd->variables.sql_mode = saved_sql_mode;
});
thd->push_internal_handler(&strict_handler);
thd->variables.sql_mode |=
MODE_STRICT_ALL_TABLES | MODE_NO_ZERO_DATE | MODE_NO_ZERO_IN_DATE;
thd->variables.sql_mode &= ~MODE_INVALID_DATES;
// Check that the default value is within the range of the return type.
switch (m_cast_target) {
case ITEM_CAST_SIGNED_INT:
case ITEM_CAST_UNSIGNED_INT: {
StringBuffer<STRING_BUFFER_USUAL_SIZE> string_buffer;
const String *string_value = item->val_str(&string_buffer);
if (thd->is_error()) return nullptr;
assert(string_value != nullptr);
const CHARSET_INFO *const cs = string_value->charset();
const char *const start = string_value->ptr();
const char *const end_of_string = start + string_value->length();
const char *end_of_number = end_of_string;
int error = 0;
const int64_t value =
cs->cset->strtoll10(cs, start, &end_of_number, &error);
if (end_of_number != end_of_string) {
ErrConvString err(string_value);
my_error(ER_TRUNCATED_WRONG_VALUE, MYF(0),
unsigned_flag ? "INTEGER UNSIGNED" : "INTEGER SIGNED",
err.ptr());
return nullptr;
}
if (error > 0 ||
(!unsigned_flag && error == 0 &&
static_cast<uint64_t>(value) > INT64_MAX) ||
(unsigned_flag && error == -1)) {
my_error(ER_DATA_OUT_OF_RANGE, MYF(0),
unsigned_flag ? "UNSIGNED DEFAULT" : "SIGNED DEFAULT",
func_name());
return nullptr;
}
default_value->integer_default = value;
break;
}
case ITEM_CAST_DATE: {
MYSQL_TIME *ltime = new (mem_root) MYSQL_TIME;
if (ltime == nullptr) return nullptr;
if (item->get_date(ltime, 0)) return nullptr;
assert(!thd->is_error());
default_value->temporal_default = ltime;
break;
}
case ITEM_CAST_YEAR: {
StringBuffer<STRING_BUFFER_USUAL_SIZE> string_buffer;
const String *string_value = item->val_str(&string_buffer);
if (thd->is_error()) return nullptr;
assert(string_value != nullptr);
const CHARSET_INFO *const cs = string_value->charset();
const char *const start = string_value->ptr();
const char *const end_of_string = start + string_value->length();
const char *end_of_number = end_of_string;
int error = 0;
const int64_t value =
cs->cset->strtoll10(cs, start, &end_of_number, &error);
if (end_of_number != end_of_string) {
ErrConvString err(string_value);
my_error(ER_TRUNCATED_WRONG_VALUE, MYF(0), "YEAR", err.ptr());
return nullptr;
}
if (error != 0 || (value > 2155) || (value < 1901 && value != 0)) {
my_error(ER_DATA_OUT_OF_RANGE, MYF(0), "YEAR", func_name());
return nullptr;
}
default_value->integer_default = value;
break;
}
case ITEM_CAST_TIME: {
MYSQL_TIME *ltime = new (mem_root) MYSQL_TIME;
if (ltime == nullptr) return nullptr;
if (item->get_time(ltime)) return nullptr;
assert(!thd->is_error());
if (actual_decimals(ltime) > decimals) {
my_error(ER_DATA_OUT_OF_RANGE, MYF(0), "TIME DEFAULT", func_name());
return nullptr;
}
default_value->temporal_default = ltime;
break;
}
case ITEM_CAST_DATETIME: {
MYSQL_TIME *ltime = new (mem_root) MYSQL_TIME;
if (ltime == nullptr) return nullptr;
if (item->get_date(ltime, TIME_DATETIME_ONLY)) return nullptr;
assert(!thd->is_error());
if (actual_decimals(ltime) > decimals) {
my_error(ER_DATA_OUT_OF_RANGE, MYF(0), "TIME DEFAULT", func_name());
return nullptr;
}
default_value->temporal_default = ltime;
break;
}
case ITEM_CAST_CHAR: {
StringBuffer<STRING_BUFFER_USUAL_SIZE> string_buffer;
const String *string_value = item->val_str(&string_buffer);
if (thd->is_error()) return nullptr;
assert(string_value != nullptr);
if (string_value->numchars() > max_char_length()) {
my_error(ER_DATA_OUT_OF_RANGE, MYF(0), "CHAR DEFAULT", func_name());
return nullptr;
}
if (my_charset_same(collation.collation, string_value->charset())) {
default_value->string_default = {string_value->dup(mem_root),
string_value->length()};
if (default_value->string_default.str == nullptr) return nullptr;
} else {
String converted_string;
unsigned errors;
if (converted_string.copy(string_value->ptr(), string_value->length(),
string_value->charset(), collation.collation,
&errors))
return nullptr; /* purecov: inspected */
if (errors > 0) {
my_error(ER_DATA_OUT_OF_RANGE, MYF(0), "CHAR DEFAULT", func_name());
return nullptr;
}
default_value->string_default = {converted_string.dup(mem_root),
converted_string.length()};
if (default_value->string_default.str == nullptr) return nullptr;
}
break;
}
case ITEM_CAST_DECIMAL: {
my_decimal *buffer = new (mem_root) my_decimal;
if (buffer == nullptr) return nullptr;
const my_decimal *value = item->val_decimal(buffer);
if (thd->is_error()) return nullptr;
if (!decimal_within_range(this, value) || value->frac > decimals) {
my_error(ER_DATA_OUT_OF_RANGE, MYF(0), "DECIMAL DEFAULT", func_name());
return nullptr;
}
default_value->decimal_default = value;
break;
}
case ITEM_CAST_JSON: {
StringBuffer<STRING_BUFFER_USUAL_SIZE> string_buffer;
const String *string_value = item->val_str(&string_buffer);
if (thd->is_error()) return nullptr;
assert(string_value != nullptr);
JsonParseDefaultErrorHandler parse_handler(func_name(), 0);
if (parse_json(*string_value, &default_value->json_default, true,
parse_handler, JsonDocumentDefaultDepthHandler)) {
my_error(ER_INVALID_DEFAULT, MYF(0), func_name());
return nullptr;
}
break;
}
case ITEM_CAST_FLOAT: {
const double value = item->val_real();
if (thd->is_error()) return nullptr;
if (value > std::numeric_limits<float>::max() ||
value < std::numeric_limits<float>::lowest()) {
my_error(ER_DATA_OUT_OF_RANGE, MYF(0), "FLOAT DEFAULT", func_name());
return nullptr;
}
// The value is within range of FLOAT. Finally, cast it to float to get
// rid of any extra (double) precision that doesn't fit in a FLOAT.
default_value->real_default = static_cast<float>(value);
break;
}
case ITEM_CAST_DOUBLE: {
const double value = item->val_real();
if (thd->is_error()) return nullptr;
default_value->real_default = value;
break;
}
/* purecov: begin inspected */
case ITEM_CAST_POINT:
my_error(ER_INVALID_CAST_TO_GEOMETRY, MYF(0), "JSON", "POINT");
return nullptr;
case ITEM_CAST_LINESTRING:
my_error(ER_INVALID_CAST_TO_GEOMETRY, MYF(0), "JSON", "LINESTRING");
return nullptr;
case ITEM_CAST_POLYGON:
my_error(ER_INVALID_CAST_TO_GEOMETRY, MYF(0), "JSON", "POLYGON");
return nullptr;
case ITEM_CAST_MULTIPOINT:
my_error(ER_INVALID_CAST_TO_GEOMETRY, MYF(0), "JSON", "MULTIPOINT");
return nullptr;
case ITEM_CAST_MULTILINESTRING:
my_error(ER_INVALID_CAST_TO_GEOMETRY, MYF(0), "JSON", "MULTILINESTRING");
return nullptr;
case ITEM_CAST_MULTIPOLYGON:
my_error(ER_INVALID_CAST_TO_GEOMETRY, MYF(0), "JSON", "MULTIPOLYGON");
return nullptr;
case ITEM_CAST_GEOMETRYCOLLECTION:
my_error(ER_INVALID_CAST_TO_GEOMETRY, MYF(0), "JSON",
"GEOMETRYCOLLECTION");
return nullptr;
/* purecov: end */
}
return default_value;
}
bool Item_func_json_value::fix_fields(THD *thd, Item **ref) {
if (Item_func::fix_fields(thd, ref)) return true;
if (check_convertible_to_json(args[0], 1, func_name())) return true;
assert(args[1]->basic_const_item());
const String *path = args[1]->val_str(nullptr);
assert(path != nullptr);
if (parse_path(*path, false, &m_path_json)) return true;
if (m_on_empty == Json_on_response_type::DEFAULT &&
m_default_empty == nullptr) {
assert(args[2]->basic_const_item());
Prepared_stmt_arena_holder ps_arena_holder(thd);
m_default_empty = create_json_value_default(thd, args[2]);
if (m_default_empty == nullptr) return true;
}
if (m_on_error == Json_on_response_type::DEFAULT &&
m_default_error == nullptr) {
assert(args[3]->basic_const_item());
Prepared_stmt_arena_holder ps_arena_holder(thd);
m_default_error = create_json_value_default(thd, args[3]);
if (m_default_error == nullptr) return true;
}
return false;
}
void Item_func_json_value::print(const THD *thd, String *str,
enum_query_type query_type) const {
str->append(STRING_WITH_LEN("json_value("));
args[0]->print(thd, str, query_type);
str->append(STRING_WITH_LEN(", "));
args[1]->print(thd, str, query_type);
str->append(STRING_WITH_LEN(" returning "));
print_cast_type(m_cast_target, this, str);
// ON EMPTY
print_on_empty_or_error(thd, str, query_type, /*on_empty=*/true, m_on_empty,
args[2]);
// ON ERROR
print_on_empty_or_error(thd, str, query_type, /*on_empty=*/false, m_on_error,
args[3]);
str->append(')');
}
/**
Checks if two Json_on_response_type values represent the same response.
Implicit responses are equal to NULL ON EMPTY/ERROR.
*/
static bool same_response_type(Json_on_response_type type1,
Json_on_response_type type2) {
return type1 == type2 || ((type1 == Json_on_response_type::IMPLICIT ||
type1 == Json_on_response_type::NULL_VALUE) &&
(type2 == Json_on_response_type::IMPLICIT ||
type2 == Json_on_response_type::NULL_VALUE));
}
bool Item_func_json_value::eq(const Item *item, bool binary_cmp) const {
if (!Item_func::eq(item, binary_cmp)) return false;
const auto other = down_cast<const Item_func_json_value *>(item);
if (other->m_cast_target != m_cast_target) return false;
if (other->max_length != max_length) return false;
if (other->decimals != decimals) return false;
if (!same_response_type(other->m_on_empty, m_on_empty)) return false;
if (!same_response_type(other->m_on_error, m_on_error)) return false;
return true;
}
/**
Handles conversion errors for JSON_VALUE according to the ON ERROR clause.
Called when the conversion of the extracted JSON value cannot be converted to
the target type without truncation or data loss.
If ERROR ON ERROR is specified, an error is raised, and true is returned.
If NULL ON ERROR is specified (explicitly or implicitly), the item's
null_value is set to true, and false is returned.
If DEFAULT ... ON ERROR is specified, the item's null_value is set to false,
and false is returned. It is up to the caller to return the correct default
value.
@param on_error the type of response to give to the error
@param type the data type returned by the JSON_VALUE expression
@param[in,out] item the Item representing the JSON_VALUE expression
@retval true for ERROR ON ERROR (my_error() is called before returning)
@retval false if DEFAULT .. ON ERROR or NULL ON ERROR was given
*/
static bool handle_json_value_conversion_error(Json_on_response_type on_error,
const char *type,
Item_func_json_value *item) {
// Should have returned earlier if the value is NULL.
assert(!item->null_value);
switch (on_error) {
case Json_on_response_type::ERROR: {
my_error(ER_DATA_OUT_OF_RANGE, MYF(0), type, item->func_name());
return true;
}
case Json_on_response_type::DEFAULT:
item->null_value = false;
break;
case Json_on_response_type::NULL_VALUE:
case Json_on_response_type::IMPLICIT:
assert(item->is_nullable());
item->null_value = true;
break;
}
return false;
}
bool Item_func_json_value::extract_json_value(
Json_wrapper *json, const Default_value **return_default) {
*return_default = nullptr;
try {
Json_wrapper doc;
assert(is_convertible_to_json(args[0])); // Checked in fix_fields().
if (args[0]->data_type() == MYSQL_TYPE_JSON) {
if (args[0]->val_json(&doc)) return true;
null_value = args[0]->null_value;
if (null_value) {
assert(is_nullable());
return false;
}
} else {
String buffer;
const String *doc_string = args[0]->val_str(&buffer);
null_value = args[0]->null_value;
if (null_value) {
assert(is_nullable());
return false;
}
Json_dom_ptr dom;
bool parse_error = false;
{
THD *thd = current_thd;
// For all other modes than ERROR ON ERROR, downgrade parse errors to
// warnings.
Ignore_json_syntax_handler error_handler(
thd, m_on_error != Json_on_response_type::ERROR);
const char *json_func_name = func_name();
if (parse_json(
*doc_string, &dom, true,
[json_func_name, &parse_error](const char *parse_err,
size_t err_offset) {
my_error(ER_INVALID_JSON_TEXT_IN_PARAM, MYF(0), 1,
json_func_name, parse_err, err_offset, "");
parse_error = true;
},
JsonDocumentDefaultDepthHandler) &&
thd->is_error())
return error_json();
}
// Invoke the ON ERROR clause if a parse error was raised.
if (parse_error) {
// ERROR ON ERROR will have returned above.
assert(m_on_error != Json_on_response_type::ERROR);
if (m_on_error == Json_on_response_type::DEFAULT) {
*return_default = m_default_error.get();
return false;
} else {
assert(m_on_error == Json_on_response_type::IMPLICIT ||
m_on_error == Json_on_response_type::NULL_VALUE);
assert(is_nullable());
null_value = true;
return false;
}
}
assert(dom != nullptr);
doc = Json_wrapper(std::move(dom));
}
Json_wrapper_vector v(key_memory_JSON);
if (doc.seek(m_path_json, m_path_json.leg_count(), &v, true, false))
return error_json(); /* purecov: inspected */
if (v.size() == 1) {
*json = std::move(v[0]);
if (json->type() == enum_json_type::J_NULL) {
/*
SQL:2016 : following the rule of JSON_VALUE we come to:
9.36 Parsing JSON text GenRule 3-a-iii-3-A-III
then to
9.40 Casting an SQL/JSON sequence to an SQL type GenRule 4-b-ii,
So, JSON null literal -> SQL/JSON null -> SQL NULL.
*/
null_value = true;
}
return false;
}
// Invoke the ON EMPTY clause if no value was found.
if (v.empty()) {
switch (m_on_empty) {
case Json_on_response_type::DEFAULT:
*return_default = m_default_empty.get();
return false;
case Json_on_response_type::ERROR:
my_error(ER_MISSING_JSON_VALUE, MYF(0), func_name());
return error_json();
case Json_on_response_type::IMPLICIT:
case Json_on_response_type::NULL_VALUE:
assert(is_nullable());
null_value = true;
return false;
}
}
// Otherwise, we have multiple matches. Invoke the ON ERROR clause.
assert(v.size() > 1);
switch (m_on_error) {
case Json_on_response_type::ERROR:
my_error(ER_MULTIPLE_JSON_VALUES, MYF(0), func_name());
return error_json();
case Json_on_response_type::NULL_VALUE:
case Json_on_response_type::IMPLICIT:
assert(is_nullable());
null_value = true;
break;
case Json_on_response_type::DEFAULT:
*return_default = m_default_error.get();
break;
}
return false;
/* purecov: begin inspected */
} catch (...) {
handle_std_exception(func_name());
return error_json();
/* purecov: end */
}
}
bool Item_func_json_value::val_json(Json_wrapper *wr) {
assert(fixed);
assert(m_cast_target == ITEM_CAST_JSON);
const Default_value *return_default = nullptr;
if (extract_json_value(wr, &return_default)) return error_json();
if (return_default != nullptr) {
assert(!null_value);
*wr = Json_wrapper(return_default->json_default.get(), true);
}
return false;
}
String *Item_func_json_value::val_str(String *buffer) {
assert(fixed);
switch (m_cast_target) {
case ITEM_CAST_SIGNED_INT:
case ITEM_CAST_UNSIGNED_INT:
case ITEM_CAST_YEAR:
return val_string_from_int(buffer);
case ITEM_CAST_DATE:
return val_string_from_date(buffer);
case ITEM_CAST_TIME:
return val_string_from_time(buffer);
case ITEM_CAST_DATETIME:
return val_string_from_datetime(buffer);
case ITEM_CAST_CHAR:
return extract_string_value(buffer);
case ITEM_CAST_DECIMAL:
return val_string_from_decimal(buffer);
case ITEM_CAST_JSON:
return val_string_from_json(this, buffer);
case ITEM_CAST_FLOAT:
case ITEM_CAST_DOUBLE:
return val_string_from_real(buffer);
/* purecov: begin inspected */
case ITEM_CAST_POINT:
my_error(ER_INVALID_CAST_TO_GEOMETRY, MYF(0), "JSON", "POINT");
return nullptr;
case ITEM_CAST_LINESTRING:
my_error(ER_INVALID_CAST_TO_GEOMETRY, MYF(0), "JSON", "LINESTRING");
return nullptr;
case ITEM_CAST_POLYGON:
my_error(ER_INVALID_CAST_TO_GEOMETRY, MYF(0), "JSON", "POLYGON");
return nullptr;
case ITEM_CAST_MULTIPOINT:
my_error(ER_INVALID_CAST_TO_GEOMETRY, MYF(0), "JSON", "MULTIPOINT");
return nullptr;
case ITEM_CAST_MULTILINESTRING:
my_error(ER_INVALID_CAST_TO_GEOMETRY, MYF(0), "JSON", "MULTILINESTRING");
return nullptr;
case ITEM_CAST_MULTIPOLYGON:
my_error(ER_INVALID_CAST_TO_GEOMETRY, MYF(0), "JSON", "MULTIPOLYGON");
return nullptr;
case ITEM_CAST_GEOMETRYCOLLECTION:
my_error(ER_INVALID_CAST_TO_GEOMETRY, MYF(0), "JSON",
"GEOMETRYCOLLECTION");
return nullptr;
/* purecov: end */
}
assert(false); /* purecov: deadcode */
return nullptr;
}
double Item_func_json_value::val_real() {
assert(fixed);
switch (m_cast_target) {
case ITEM_CAST_SIGNED_INT:
case ITEM_CAST_DATE:
case ITEM_CAST_YEAR:
case ITEM_CAST_TIME:
case ITEM_CAST_DATETIME:
return static_cast<double>(val_int());
case ITEM_CAST_UNSIGNED_INT:
return static_cast<double>(val_uint());
case ITEM_CAST_CHAR:
return val_real_from_string();
case ITEM_CAST_DECIMAL:
return val_real_from_decimal();
case ITEM_CAST_JSON:
return val_real_from_json(this);
case ITEM_CAST_FLOAT:
case ITEM_CAST_DOUBLE:
return extract_real_value();
/* purecov: begin inspected */
case ITEM_CAST_POINT:
my_error(ER_INVALID_CAST_TO_GEOMETRY, MYF(0), "JSON", "POINT");
return 0.0;
case ITEM_CAST_LINESTRING:
my_error(ER_INVALID_CAST_TO_GEOMETRY, MYF(0), "JSON", "LINESTRING");
return 0.0;
case ITEM_CAST_POLYGON:
my_error(ER_INVALID_CAST_TO_GEOMETRY, MYF(0), "JSON", "POLYGON");
return 0.0;
case ITEM_CAST_MULTIPOINT:
my_error(ER_INVALID_CAST_TO_GEOMETRY, MYF(0), "JSON", "MULTIPOINT");
return 0.0;
case ITEM_CAST_MULTILINESTRING:
my_error(ER_INVALID_CAST_TO_GEOMETRY, MYF(0), "JSON", "MULTILINESTRING");
return 0.0;
case ITEM_CAST_MULTIPOLYGON:
my_error(ER_INVALID_CAST_TO_GEOMETRY, MYF(0), "JSON", "MULTIPOLYGON");
return 0.0;
case ITEM_CAST_GEOMETRYCOLLECTION:
my_error(ER_INVALID_CAST_TO_GEOMETRY, MYF(0), "JSON",
"GEOMETRYCOLLECTION");
return 0.0;
/* purecov: end */
}
assert(false); /* purecov: deadcode */
return 0.0;
}
longlong Item_func_json_value::val_int() {
assert(fixed);
switch (m_cast_target) {
case ITEM_CAST_SIGNED_INT:
case ITEM_CAST_UNSIGNED_INT:
return extract_integer_value();
case ITEM_CAST_YEAR:
return extract_year_value();
case ITEM_CAST_DATE:
return val_int_from_date();
case ITEM_CAST_TIME:
return val_int_from_time();
case ITEM_CAST_DATETIME:
return val_int_from_datetime();
case ITEM_CAST_CHAR:
return val_int_from_string();
case ITEM_CAST_DECIMAL:
return val_int_from_decimal();
case ITEM_CAST_JSON:
return val_int_from_json(this);
case ITEM_CAST_FLOAT:
case ITEM_CAST_DOUBLE:
return val_int_from_real();
/* purecov: begin inspected */
case ITEM_CAST_POINT:
my_error(ER_INVALID_CAST_TO_GEOMETRY, MYF(0), "JSON", "POINT");
return 0;
case ITEM_CAST_LINESTRING:
my_error(ER_INVALID_CAST_TO_GEOMETRY, MYF(0), "JSON", "LINESTRING");
return 0;
case ITEM_CAST_POLYGON:
my_error(ER_INVALID_CAST_TO_GEOMETRY, MYF(0), "JSON", "POLYGON");
return 0;
case ITEM_CAST_MULTIPOINT:
my_error(ER_INVALID_CAST_TO_GEOMETRY, MYF(0), "JSON", "MULTIPOINT");
return 0;
case ITEM_CAST_MULTILINESTRING:
my_error(ER_INVALID_CAST_TO_GEOMETRY, MYF(0), "JSON", "MULTILINESTRING");
return 0;
case ITEM_CAST_MULTIPOLYGON:
my_error(ER_INVALID_CAST_TO_GEOMETRY, MYF(0), "JSON", "MULTIPOLYGON");
return 0;
case ITEM_CAST_GEOMETRYCOLLECTION:
my_error(ER_INVALID_CAST_TO_GEOMETRY, MYF(0), "JSON",
"GEOMETRYCOLLECTION");
return 0;
/* purecov: end */
}
assert(false); /* purecov: deadcode */
return 0;
}
my_decimal *Item_func_json_value::val_decimal(my_decimal *value) {
assert(fixed);
switch (m_cast_target) {
case ITEM_CAST_SIGNED_INT:
case ITEM_CAST_UNSIGNED_INT:
case ITEM_CAST_YEAR:
return val_decimal_from_int(value);
case ITEM_CAST_DATE:
case ITEM_CAST_DATETIME:
return val_decimal_from_date(value);
case ITEM_CAST_TIME:
return val_decimal_from_time(value);
case ITEM_CAST_CHAR:
return val_decimal_from_string(value);
case ITEM_CAST_DECIMAL:
return extract_decimal_value(value);
case ITEM_CAST_JSON:
return val_decimal_from_json(this, value);
case ITEM_CAST_FLOAT:
case ITEM_CAST_DOUBLE:
return val_decimal_from_real(value);
/* purecov: begin inspected */
case ITEM_CAST_POINT:
my_error(ER_INVALID_CAST_TO_GEOMETRY, MYF(0), "JSON", "POINT");
return nullptr;
case ITEM_CAST_LINESTRING:
my_error(ER_INVALID_CAST_TO_GEOMETRY, MYF(0), "JSON", "LINESTRING");
return nullptr;
case ITEM_CAST_POLYGON:
my_error(ER_INVALID_CAST_TO_GEOMETRY, MYF(0), "JSON", "POLYGON");
return nullptr;
case ITEM_CAST_MULTIPOINT:
my_error(ER_INVALID_CAST_TO_GEOMETRY, MYF(0), "JSON", "MULTIPOINT");
return nullptr;
case ITEM_CAST_MULTILINESTRING:
my_error(ER_INVALID_CAST_TO_GEOMETRY, MYF(0), "JSON", "MULTILINESTRING");
return nullptr;
case ITEM_CAST_MULTIPOLYGON:
my_error(ER_INVALID_CAST_TO_GEOMETRY, MYF(0), "JSON", "MULTIPOLYGON");
return nullptr;
case ITEM_CAST_GEOMETRYCOLLECTION:
my_error(ER_INVALID_CAST_TO_GEOMETRY, MYF(0), "JSON",
"GEOMETRYCOLLECTION");
return nullptr;
/* purecov: end */
}
assert(false); /* purecov: deadcode */
return nullptr;
}
bool Item_func_json_value::get_date(MYSQL_TIME *ltime, my_time_flags_t flags) {
assert(fixed);
switch (m_cast_target) {
case ITEM_CAST_SIGNED_INT:
case ITEM_CAST_UNSIGNED_INT:
return get_date_from_int(ltime, flags);
case ITEM_CAST_DATE:
case ITEM_CAST_YEAR:
return extract_date_value(ltime);
case ITEM_CAST_DATETIME:
return extract_datetime_value(ltime);
case ITEM_CAST_TIME:
return get_date_from_time(ltime);
case ITEM_CAST_CHAR:
return get_date_from_string(ltime, flags);
case ITEM_CAST_DECIMAL:
return get_date_from_decimal(ltime, flags);
case ITEM_CAST_JSON:
return get_date_from_json(this, ltime, flags);
case ITEM_CAST_FLOAT:
case ITEM_CAST_DOUBLE:
return get_date_from_real(ltime, flags);
/* purecov: begin inspected */
case ITEM_CAST_POINT:
my_error(ER_INVALID_CAST_TO_GEOMETRY, MYF(0), "JSON", "POINT");
return true;
case ITEM_CAST_LINESTRING:
my_error(ER_INVALID_CAST_TO_GEOMETRY, MYF(0), "JSON", "LINESTRING");
return true;
case ITEM_CAST_POLYGON:
my_error(ER_INVALID_CAST_TO_GEOMETRY, MYF(0), "JSON", "POLYGON");
return true;
case ITEM_CAST_MULTIPOINT:
my_error(ER_INVALID_CAST_TO_GEOMETRY, MYF(0), "JSON", "MULTIPOINT");
return true;
case ITEM_CAST_MULTILINESTRING:
my_error(ER_INVALID_CAST_TO_GEOMETRY, MYF(0), "JSON", "MULTILINESTRING");
return true;
case ITEM_CAST_MULTIPOLYGON:
my_error(ER_INVALID_CAST_TO_GEOMETRY, MYF(0), "JSON", "MULTIPOLYGON");
return true;
case ITEM_CAST_GEOMETRYCOLLECTION:
my_error(ER_INVALID_CAST_TO_GEOMETRY, MYF(0), "JSON",
"GEOMETRYCOLLECTION");
return true;
/* purecov: end */
}
assert(false); /* purecov: deadcode */
return true;
}
bool Item_func_json_value::get_time(MYSQL_TIME *ltime) {
assert(fixed);
switch (m_cast_target) {
case ITEM_CAST_SIGNED_INT:
case ITEM_CAST_YEAR:
case ITEM_CAST_UNSIGNED_INT:
return get_time_from_int(ltime);
case ITEM_CAST_DATE:
return get_time_from_date(ltime);
case ITEM_CAST_TIME:
return extract_time_value(ltime);
case ITEM_CAST_DATETIME:
return get_time_from_datetime(ltime);
case ITEM_CAST_CHAR:
return get_time_from_string(ltime);
case ITEM_CAST_DECIMAL:
return get_time_from_decimal(ltime);
case ITEM_CAST_JSON:
return get_time_from_json(this, ltime);
case ITEM_CAST_FLOAT:
case ITEM_CAST_DOUBLE:
return get_time_from_real(ltime);
/* purecov: begin inspected */
case ITEM_CAST_POINT:
my_error(ER_INVALID_CAST_TO_GEOMETRY, MYF(0), "JSON", "POINT");
return true;
case ITEM_CAST_LINESTRING:
my_error(ER_INVALID_CAST_TO_GEOMETRY, MYF(0), "JSON", "LINESTRING");
return true;
case ITEM_CAST_POLYGON:
my_error(ER_INVALID_CAST_TO_GEOMETRY, MYF(0), "JSON", "POLYGON");
return true;
case ITEM_CAST_MULTIPOINT:
my_error(ER_INVALID_CAST_TO_GEOMETRY, MYF(0), "JSON", "MULTIPOINT");
return true;
case ITEM_CAST_MULTILINESTRING:
my_error(ER_INVALID_CAST_TO_GEOMETRY, MYF(0), "JSON", "MULTILINESTRING");
return true;
case ITEM_CAST_MULTIPOLYGON:
my_error(ER_INVALID_CAST_TO_GEOMETRY, MYF(0), "JSON", "MULTIPOLYGON");
return true;
case ITEM_CAST_GEOMETRYCOLLECTION:
my_error(ER_INVALID_CAST_TO_GEOMETRY, MYF(0), "JSON",
"GEOMETRYCOLLECTION");
return true;
/* purecov: end */
}
assert(false); /* purecov: deadcode */
return true;
}
int64_t Item_func_json_value::extract_integer_value() {
assert(m_cast_target == ITEM_CAST_SIGNED_INT ||
m_cast_target == ITEM_CAST_UNSIGNED_INT);
assert(unsigned_flag == (m_cast_target == ITEM_CAST_UNSIGNED_INT));
Json_wrapper wr;
const Default_value *return_default = nullptr;
if (extract_json_value(&wr, &return_default)) return error_int();
if (null_value) {
assert(is_nullable());
return 0;
}
if (return_default != nullptr) {
assert(!null_value);
return return_default->integer_default;
}
bool err = false;
bool unsigned_val = false;
const int64_t value =
wr.coerce_int(func_name(), CE_IGNORE, &err, &unsigned_val);
if (!err && (unsigned_flag == unsigned_val || value >= 0)) return value;
if (handle_json_value_conversion_error(
m_on_error, unsigned_flag ? "UNSIGNED" : "SIGNED", this))
return error_int();
if (null_value) return 0;
return m_default_error->integer_default;
}
int64_t Item_func_json_value::extract_year_value() {
assert(m_cast_target == ITEM_CAST_YEAR);
assert(unsigned_flag == false);
Json_wrapper wr;
const Default_value *return_default = nullptr;
if (extract_json_value(&wr, &return_default)) return error_int();
if (null_value) {
assert(is_nullable());
return 0;
}
if (return_default != nullptr) {
assert(!null_value);
return return_default->integer_default;
}
bool err = false;
bool unsigned_val = false;
const int64_t value =
wr.coerce_int(func_name(), CE_IGNORE, &err, &unsigned_val);
if (!err && ((value == 0) || (value > 1900 && value <= 2155))) return value;
if (handle_json_value_conversion_error(m_on_error, "YEAR", this))
return error_int();
if (null_value) return 0;
return m_default_error->integer_default;
}
bool Item_func_json_value::extract_date_value(MYSQL_TIME *ltime) {
assert(m_cast_target == ITEM_CAST_DATE || m_cast_target == ITEM_CAST_YEAR);
Json_wrapper wr;
const Default_value *return_default = nullptr;
if (extract_json_value(&wr, &return_default) || null_value) {
set_zero_time(ltime, MYSQL_TIMESTAMP_DATE);
return true;
}
if (return_default != nullptr) {
*ltime = *return_default->temporal_default;
return false;
}
if (!wr.coerce_date(ltime, func_name(), CE_IGNORE)) return false;
if (handle_json_value_conversion_error(m_on_error, "DATE", this) ||
null_value) {
set_zero_time(ltime, MYSQL_TIMESTAMP_DATE);
return true;
}
*ltime = *m_default_error->temporal_default;
return false;
}
bool Item_func_json_value::extract_time_value(MYSQL_TIME *ltime) {
assert(m_cast_target == ITEM_CAST_TIME);
Json_wrapper wr;
const Default_value *return_default = nullptr;
if (extract_json_value(&wr, &return_default) || null_value) {
set_zero_time(ltime, MYSQL_TIMESTAMP_TIME);
return true;
}
if (return_default != nullptr) {
*ltime = *return_default->temporal_default;
return false;
}
if (!wr.coerce_time(ltime, func_name(), CE_IGNORE)) return false;
if (handle_json_value_conversion_error(m_on_error, "TIME", this) ||
null_value) {
set_zero_time(ltime, MYSQL_TIMESTAMP_TIME);
return true;
}
*ltime = *m_default_error->temporal_default;
return false;
}
bool Item_func_json_value::extract_datetime_value(MYSQL_TIME *ltime) {
assert(m_cast_target == ITEM_CAST_DATETIME);
Json_wrapper wr;
const Default_value *return_default = nullptr;
if (extract_json_value(&wr, &return_default) || null_value) {
set_zero_time(ltime, MYSQL_TIMESTAMP_DATETIME);
return true;
}
if (return_default != nullptr) {
*ltime = *return_default->temporal_default;
return false;
}
if (!wr.coerce_date(ltime, func_name(), CE_IGNORE, TIME_DATETIME_ONLY))
return false;
if (handle_json_value_conversion_error(m_on_error, "DATETIME", this) ||
null_value) {
set_zero_time(ltime, MYSQL_TIMESTAMP_DATETIME);
return true;
}
*ltime = *m_default_error->temporal_default;
return false;
}
my_decimal *Item_func_json_value::extract_decimal_value(my_decimal *value) {
assert(m_cast_target == ITEM_CAST_DECIMAL);
Json_wrapper wr;
const Default_value *return_default = nullptr;
if (extract_json_value(&wr, &return_default) || null_value) {
return error_decimal(value);
}
if (return_default != nullptr) {
*value = *return_default->decimal_default;
return value;
}
bool err = false;
wr.coerce_decimal(value, func_name(), CE_IGNORE, &err);
if (!err && decimal_within_range(this, value)) return value;
if (handle_json_value_conversion_error(m_on_error, "DECIMAL", this) ||
null_value) {
return error_decimal(value);
}
*value = *m_default_error->decimal_default;
return value;
}
String *Item_func_json_value::extract_string_value(String *buffer) {
assert(m_cast_target == ITEM_CAST_CHAR);
Json_wrapper wr;
const Default_value *return_default = nullptr;
if (extract_json_value(&wr, &return_default)) return error_str();
if (null_value) return null_return_str();
if (return_default != nullptr) {
buffer->set(return_default->string_default.str,
return_default->string_default.length, collation.collation);
return buffer;
}
// Return the unquoted result
buffer->length(0);
if (wr.to_string(buffer, false, func_name(), JsonDocumentDefaultDepthHandler))
return error_str();
if (buffer->is_empty()) return make_empty_result();
unsigned conversion_errors = 0;
if (!my_charset_same(collation.collation, buffer->charset())) {
// The string should be returned in a different character set. Convert it.
String converted_string;
if (converted_string.copy(buffer->ptr(), buffer->length(),
buffer->charset(), collation.collation,
&conversion_errors))
return error_str(); /* purecov: inspected */
assert(converted_string.charset() == collation.collation);
buffer->swap(converted_string);
}
// If the string fits in the return type, return it.
if (conversion_errors == 0 && buffer->numchars() <= max_char_length())
return buffer;
// Otherwise, handle the error.
if (handle_json_value_conversion_error(m_on_error, "STRING", this))
return error_str();
if (null_value) return null_return_str();
buffer->set(m_default_error->string_default.str,
m_default_error->string_default.length, collation.collation);
return buffer;
}
double Item_func_json_value::extract_real_value() {
assert(m_cast_target == ITEM_CAST_FLOAT || m_cast_target == ITEM_CAST_DOUBLE);
Json_wrapper wr;
const Default_value *return_default = nullptr;
if (extract_json_value(&wr, &return_default)) return error_real();
if (null_value) {
assert(is_nullable());
return 0.0;
}
if (return_default != nullptr) return return_default->real_default;
bool err = false;
double value = wr.coerce_real(func_name(), CE_IGNORE, &err);
if (!err) {
if (data_type() == MYSQL_TYPE_FLOAT) {
// Remove any extra (double) precision.
return static_cast<float>(value);
} else {
return value;
}
}
if (handle_json_value_conversion_error(
m_on_error, data_type() == MYSQL_TYPE_DOUBLE ? "DOUBLE" : "FLOAT",
this))
return error_real();
if (null_value) return 0.0;
return m_default_error->real_default;
}
|