1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957 7958 7959 7960 7961 7962 7963 7964 7965 7966 7967 7968 7969 7970 7971 7972 7973 7974 7975 7976 7977 7978 7979 7980 7981 7982 7983 7984 7985 7986 7987 7988 7989 7990 7991 7992 7993 7994 7995 7996 7997 7998 7999 8000 8001 8002 8003 8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015 8016 8017 8018 8019 8020 8021 8022 8023 8024 8025 8026 8027 8028 8029 8030 8031 8032 8033 8034 8035 8036 8037 8038 8039 8040 8041 8042 8043 8044 8045 8046 8047 8048 8049 8050 8051 8052 8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 8097 8098 8099 8100 8101 8102 8103 8104 8105 8106 8107 8108 8109 8110 8111 8112 8113 8114 8115 8116 8117 8118 8119 8120 8121 8122 8123 8124 8125 8126 8127 8128 8129 8130 8131 8132 8133 8134 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 8160 8161 8162 8163 8164 8165 8166 8167 8168 8169 8170 8171 8172 8173 8174 8175 8176 8177 8178 8179 8180 8181 8182 8183 8184 8185 8186 8187 8188 8189 8190 8191 8192 8193 8194 8195 8196 8197 8198 8199 8200 8201 8202 8203 8204 8205 8206 8207 8208 8209 8210 8211 8212 8213 8214 8215 8216 8217 8218 8219 8220 8221 8222 8223 8224 8225 8226 8227 8228 8229 8230 8231 8232 8233 8234 8235 8236 8237 8238 8239 8240 8241 8242 8243 8244 8245 8246 8247 8248 8249 8250 8251 8252 8253 8254 8255 8256 8257 8258 8259 8260 8261 8262 8263 8264 8265 8266 8267 8268 8269 8270 8271 8272 8273 8274 8275 8276 8277 8278 8279 8280 8281 8282 8283 8284 8285 8286 8287 8288 8289 8290 8291 8292 8293 8294 8295 8296 8297 8298 8299 8300 8301 8302 8303 8304 8305 8306 8307 8308 8309 8310 8311 8312 8313 8314 8315 8316 8317 8318 8319 8320 8321 8322 8323 8324 8325 8326 8327 8328 8329 8330 8331 8332 8333 8334 8335 8336 8337 8338 8339 8340 8341 8342 8343 8344 8345 8346 8347 8348 8349 8350 8351 8352 8353 8354 8355 8356 8357 8358 8359 8360 8361 8362 8363 8364 8365 8366 8367 8368 8369 8370 8371 8372 8373 8374 8375 8376 8377 8378 8379 8380 8381 8382 8383 8384 8385 8386 8387 8388 8389 8390 8391 8392 8393 8394 8395 8396 8397 8398 8399 8400 8401 8402 8403 8404 8405 8406 8407 8408 8409 8410 8411 8412 8413 8414 8415 8416 8417 8418 8419 8420 8421 8422 8423 8424 8425 8426 8427 8428 8429 8430 8431 8432 8433 8434 8435 8436 8437 8438 8439 8440 8441 8442 8443 8444 8445 8446 8447 8448 8449 8450 8451 8452 8453 8454 8455 8456 8457 8458 8459 8460 8461 8462 8463 8464 8465 8466 8467 8468 8469 8470 8471 8472 8473 8474 8475 8476 8477 8478 8479 8480 8481 8482 8483 8484 8485 8486 8487 8488 8489 8490 8491 8492 8493 8494 8495 8496 8497 8498 8499 8500 8501 8502 8503 8504 8505 8506 8507 8508 8509 8510 8511 8512 8513 8514 8515 8516 8517 8518 8519 8520 8521 8522 8523 8524 8525 8526 8527 8528 8529 8530 8531 8532 8533 8534 8535 8536 8537 8538 8539 8540 8541 8542 8543 8544 8545 8546 8547 8548 8549 8550 8551 8552 8553 8554 8555 8556 8557 8558 8559 8560 8561 8562 8563 8564 8565 8566 8567 8568 8569 8570 8571 8572 8573 8574 8575 8576 8577 8578 8579 8580 8581 8582 8583 8584 8585 8586 8587 8588 8589 8590 8591 8592 8593 8594 8595 8596 8597 8598 8599 8600 8601 8602 8603 8604 8605 8606 8607 8608 8609 8610 8611 8612 8613 8614 8615 8616 8617 8618 8619 8620 8621 8622 8623 8624 8625 8626 8627 8628 8629 8630 8631 8632 8633 8634 8635 8636 8637 8638 8639 8640 8641 8642 8643 8644 8645 8646 8647 8648 8649 8650 8651 8652 8653 8654 8655 8656 8657 8658 8659 8660 8661 8662 8663 8664 8665 8666 8667 8668 8669 8670 8671 8672 8673 8674 8675 8676 8677 8678 8679 8680 8681 8682 8683 8684 8685 8686 8687 8688 8689 8690 8691 8692 8693 8694 8695 8696 8697 8698 8699 8700 8701 8702 8703 8704 8705 8706 8707 8708 8709 8710 8711 8712 8713 8714 8715 8716 8717 8718 8719 8720 8721 8722 8723 8724 8725 8726 8727 8728 8729 8730 8731 8732 8733 8734 8735 8736 8737 8738 8739 8740 8741 8742 8743 8744 8745 8746 8747 8748 8749 8750 8751 8752 8753 8754 8755 8756 8757 8758 8759 8760 8761 8762 8763 8764 8765 8766 8767 8768 8769 8770 8771 8772 8773 8774 8775 8776 8777 8778 8779 8780 8781 8782 8783 8784 8785 8786 8787 8788 8789 8790 8791 8792 8793 8794 8795 8796 8797 8798 8799 8800 8801 8802 8803 8804 8805 8806 8807 8808 8809 8810 8811 8812 8813 8814 8815 8816 8817 8818 8819 8820 8821 8822 8823 8824 8825 8826 8827 8828 8829 8830 8831 8832 8833 8834 8835 8836 8837 8838 8839 8840 8841 8842 8843 8844 8845 8846 8847 8848 8849 8850 8851 8852 8853 8854 8855 8856 8857 8858 8859 8860 8861 8862 8863 8864 8865 8866 8867 8868 8869 8870 8871 8872 8873 8874 8875 8876 8877 8878 8879 8880 8881 8882 8883 8884 8885 8886 8887 8888 8889 8890 8891 8892 8893 8894 8895 8896 8897 8898 8899 8900 8901 8902 8903 8904 8905 8906 8907 8908 8909 8910 8911 8912 8913 8914 8915 8916 8917 8918 8919 8920 8921 8922 8923 8924 8925 8926 8927 8928 8929 8930 8931 8932 8933 8934 8935 8936 8937 8938 8939 8940 8941 8942 8943 8944 8945 8946 8947 8948 8949 8950 8951 8952 8953 8954 8955 8956 8957 8958 8959 8960 8961 8962 8963 8964 8965 8966 8967 8968 8969 8970 8971 8972 8973 8974 8975 8976 8977 8978 8979 8980 8981 8982 8983 8984 8985 8986 8987 8988 8989 8990 8991 8992 8993 8994 8995 8996 8997 8998 8999 9000 9001 9002 9003 9004 9005 9006 9007 9008 9009 9010 9011 9012 9013 9014 9015 9016 9017 9018 9019 9020 9021 9022 9023 9024 9025 9026 9027 9028 9029 9030 9031 9032 9033 9034 9035 9036 9037 9038 9039 9040 9041 9042 9043 9044 9045 9046 9047 9048 9049 9050 9051 9052 9053 9054 9055 9056 9057 9058 9059 9060 9061 9062 9063 9064 9065 9066 9067 9068 9069 9070 9071 9072 9073 9074 9075 9076 9077 9078 9079 9080 9081 9082 9083 9084 9085 9086 9087 9088 9089 9090 9091 9092 9093 9094 9095 9096 9097 9098 9099 9100 9101 9102 9103 9104 9105 9106 9107 9108 9109 9110 9111 9112 9113 9114 9115 9116 9117 9118 9119 9120 9121 9122 9123 9124 9125 9126 9127 9128 9129 9130 9131 9132 9133 9134 9135 9136 9137 9138 9139 9140 9141 9142 9143 9144 9145 9146 9147 9148 9149 9150 9151 9152 9153 9154 9155 9156 9157 9158 9159 9160 9161 9162 9163 9164 9165 9166 9167 9168 9169 9170 9171 9172 9173 9174 9175 9176 9177 9178 9179 9180 9181 9182 9183 9184 9185 9186 9187 9188 9189 9190 9191 9192 9193 9194 9195 9196 9197 9198 9199 9200 9201 9202 9203 9204 9205 9206 9207 9208 9209 9210 9211 9212 9213 9214 9215 9216 9217 9218 9219 9220 9221 9222 9223 9224 9225 9226 9227 9228 9229 9230 9231 9232 9233 9234 9235 9236 9237 9238 9239 9240 9241 9242 9243 9244 9245 9246 9247 9248 9249 9250 9251 9252 9253 9254 9255 9256 9257 9258 9259 9260 9261 9262 9263 9264 9265 9266 9267 9268 9269 9270 9271 9272 9273 9274 9275 9276 9277 9278 9279 9280 9281 9282 9283 9284 9285 9286 9287 9288 9289 9290 9291 9292 9293 9294 9295 9296 9297 9298 9299 9300 9301 9302 9303 9304 9305 9306 9307 9308 9309 9310 9311 9312 9313 9314 9315 9316 9317 9318 9319 9320 9321 9322 9323 9324 9325 9326 9327 9328 9329 9330 9331 9332 9333 9334 9335 9336 9337 9338 9339 9340 9341 9342 9343 9344 9345 9346 9347 9348 9349 9350 9351 9352 9353 9354 9355 9356 9357 9358 9359 9360 9361 9362 9363 9364 9365 9366 9367 9368 9369 9370 9371 9372 9373 9374 9375 9376 9377 9378 9379 9380 9381 9382 9383 9384 9385 9386 9387 9388 9389 9390 9391 9392 9393 9394 9395 9396 9397 9398 9399 9400 9401 9402 9403 9404 9405 9406 9407 9408 9409 9410 9411 9412 9413 9414 9415 9416 9417 9418 9419 9420 9421 9422 9423 9424 9425 9426 9427 9428 9429 9430 9431 9432 9433 9434 9435 9436 9437 9438 9439 9440 9441 9442 9443 9444 9445 9446 9447 9448 9449 9450 9451 9452 9453 9454 9455 9456 9457 9458 9459 9460 9461 9462 9463 9464 9465 9466 9467 9468 9469 9470 9471 9472 9473 9474 9475 9476 9477 9478 9479 9480 9481 9482 9483 9484 9485 9486 9487 9488 9489 9490 9491 9492 9493 9494 9495 9496 9497 9498 9499 9500 9501 9502 9503 9504 9505 9506 9507 9508 9509 9510 9511 9512 9513 9514 9515 9516 9517 9518 9519 9520 9521 9522 9523 9524 9525 9526 9527 9528 9529 9530 9531 9532 9533 9534 9535 9536 9537 9538 9539 9540 9541 9542 9543 9544 9545 9546 9547 9548 9549 9550 9551 9552 9553 9554 9555 9556 9557 9558 9559 9560 9561 9562 9563 9564 9565 9566 9567 9568 9569 9570 9571 9572 9573 9574 9575 9576 9577 9578 9579 9580 9581 9582 9583 9584 9585 9586 9587 9588 9589 9590 9591 9592 9593 9594 9595 9596 9597 9598 9599 9600 9601 9602 9603 9604 9605 9606 9607 9608 9609 9610 9611 9612 9613 9614 9615 9616 9617 9618 9619 9620 9621 9622 9623 9624 9625 9626 9627 9628 9629 9630 9631 9632 9633 9634 9635 9636 9637 9638 9639 9640 9641 9642 9643 9644 9645 9646 9647 9648 9649 9650 9651 9652 9653 9654 9655 9656 9657 9658 9659 9660 9661 9662 9663 9664 9665 9666 9667 9668 9669 9670 9671 9672 9673 9674 9675 9676 9677 9678 9679 9680 9681 9682 9683 9684 9685 9686 9687 9688 9689 9690 9691 9692 9693 9694 9695 9696 9697 9698 9699 9700 9701 9702 9703 9704 9705 9706 9707 9708 9709 9710 9711 9712 9713 9714 9715 9716 9717 9718 9719 9720 9721 9722 9723 9724 9725 9726 9727 9728 9729 9730 9731 9732 9733 9734 9735 9736 9737 9738 9739 9740 9741 9742 9743 9744 9745 9746 9747 9748 9749 9750 9751 9752 9753 9754 9755 9756 9757 9758 9759 9760 9761 9762 9763 9764 9765 9766 9767 9768 9769 9770 9771 9772 9773 9774 9775 9776 9777 9778 9779 9780 9781 9782 9783 9784 9785 9786 9787 9788 9789 9790 9791 9792 9793 9794 9795 9796 9797 9798 9799 9800 9801 9802 9803 9804 9805 9806 9807 9808 9809 9810 9811 9812 9813 9814 9815 9816 9817 9818 9819 9820 9821 9822 9823 9824 9825 9826 9827 9828 9829 9830 9831 9832 9833 9834 9835 9836 9837 9838 9839 9840 9841 9842 9843 9844 9845 9846 9847 9848 9849 9850 9851 9852 9853 9854 9855 9856 9857 9858 9859 9860 9861 9862 9863 9864 9865 9866 9867 9868 9869 9870 9871 9872 9873 9874 9875 9876 9877 9878 9879 9880 9881 9882 9883 9884 9885 9886 9887 9888 9889 9890 9891 9892 9893 9894 9895 9896 9897 9898 9899 9900 9901 9902 9903 9904 9905 9906 9907 9908 9909 9910 9911 9912 9913 9914 9915 9916 9917 9918 9919 9920 9921 9922 9923 9924 9925 9926 9927 9928 9929 9930 9931 9932 9933 9934 9935 9936 9937 9938 9939 9940 9941 9942 9943 9944 9945 9946 9947 9948 9949 9950 9951 9952 9953 9954 9955 9956 9957 9958 9959 9960 9961 9962 9963 9964 9965 9966 9967 9968 9969 9970 9971 9972 9973 9974 9975 9976 9977 9978 9979 9980 9981 9982 9983 9984 9985 9986 9987 9988 9989 9990 9991 9992 9993 9994 9995 9996 9997 9998 9999 10000 10001 10002 10003 10004 10005 10006 10007 10008 10009 10010 10011 10012 10013 10014 10015 10016 10017 10018 10019 10020 10021 10022 10023 10024 10025 10026 10027 10028 10029 10030 10031 10032 10033 10034 10035 10036 10037 10038 10039 10040 10041 10042 10043 10044 10045 10046 10047 10048 10049 10050 10051 10052 10053 10054 10055 10056 10057 10058 10059 10060 10061 10062 10063 10064 10065 10066 10067 10068 10069 10070 10071 10072 10073 10074 10075 10076 10077 10078 10079 10080 10081 10082 10083 10084 10085 10086 10087 10088 10089 10090 10091 10092 10093 10094 10095 10096 10097 10098 10099 10100 10101 10102 10103 10104 10105 10106 10107 10108 10109 10110 10111 10112 10113 10114 10115 10116 10117 10118 10119 10120 10121 10122 10123 10124 10125 10126 10127 10128 10129 10130 10131 10132 10133 10134 10135 10136 10137 10138 10139 10140 10141 10142 10143 10144 10145 10146 10147 10148 10149 10150 10151 10152 10153 10154 10155 10156 10157 10158 10159 10160 10161 10162 10163 10164 10165 10166 10167 10168 10169 10170 10171 10172 10173 10174 10175 10176 10177 10178 10179 10180 10181 10182 10183 10184 10185 10186 10187 10188 10189 10190 10191 10192 10193 10194 10195 10196 10197 10198 10199 10200 10201 10202 10203 10204 10205 10206 10207 10208 10209 10210 10211 10212 10213 10214 10215 10216 10217 10218 10219 10220 10221 10222 10223 10224 10225 10226 10227 10228 10229 10230 10231 10232 10233 10234 10235 10236 10237 10238 10239 10240 10241 10242 10243 10244 10245 10246 10247 10248 10249 10250 10251 10252 10253 10254 10255 10256 10257 10258 10259 10260 10261 10262 10263 10264 10265 10266 10267 10268 10269 10270 10271 10272 10273 10274 10275 10276 10277 10278 10279 10280 10281 10282 10283 10284 10285 10286 10287 10288 10289 10290 10291 10292 10293 10294 10295 10296 10297 10298 10299 10300 10301 10302 10303 10304 10305 10306 10307 10308 10309 10310 10311 10312 10313 10314 10315 10316 10317 10318 10319 10320 10321 10322 10323 10324 10325 10326 10327 10328 10329 10330 10331 10332 10333 10334 10335 10336 10337 10338 10339 10340 10341 10342 10343 10344 10345 10346 10347 10348 10349 10350 10351 10352 10353 10354 10355 10356 10357 10358 10359 10360 10361 10362 10363 10364 10365 10366 10367 10368 10369 10370 10371 10372 10373 10374 10375 10376 10377 10378 10379 10380 10381 10382 10383 10384 10385 10386 10387 10388 10389 10390 10391 10392 10393 10394 10395 10396 10397 10398 10399 10400 10401 10402 10403 10404 10405 10406 10407 10408 10409 10410 10411 10412 10413 10414 10415 10416 10417 10418 10419 10420 10421 10422 10423 10424 10425 10426 10427 10428 10429 10430 10431 10432 10433 10434 10435 10436 10437 10438 10439 10440 10441 10442 10443 10444 10445 10446 10447 10448 10449 10450 10451 10452 10453 10454 10455 10456 10457 10458 10459 10460 10461 10462 10463 10464 10465 10466 10467 10468 10469 10470 10471 10472 10473 10474 10475 10476 10477 10478 10479 10480 10481 10482 10483 10484 10485 10486 10487 10488 10489 10490 10491 10492 10493 10494 10495 10496 10497 10498 10499 10500 10501 10502 10503 10504 10505 10506 10507 10508 10509 10510 10511 10512 10513 10514 10515 10516 10517 10518 10519 10520 10521 10522 10523 10524 10525 10526 10527 10528 10529 10530 10531 10532 10533 10534 10535 10536 10537 10538 10539 10540 10541 10542 10543 10544 10545 10546 10547 10548 10549 10550 10551 10552 10553 10554 10555 10556 10557 10558 10559 10560 10561 10562 10563 10564 10565 10566 10567 10568 10569 10570 10571 10572 10573 10574 10575 10576 10577 10578 10579 10580 10581 10582 10583 10584 10585 10586 10587 10588 10589 10590 10591 10592 10593 10594 10595 10596 10597 10598 10599 10600 10601 10602 10603 10604 10605 10606 10607 10608 10609 10610 10611 10612 10613 10614 10615 10616 10617 10618 10619 10620 10621 10622 10623 10624 10625 10626 10627 10628 10629 10630 10631 10632 10633 10634 10635 10636 10637 10638 10639 10640 10641 10642 10643 10644 10645 10646 10647 10648 10649 10650 10651 10652 10653 10654 10655 10656 10657 10658 10659 10660 10661 10662 10663 10664 10665 10666 10667 10668 10669 10670 10671 10672 10673 10674 10675 10676 10677 10678 10679 10680 10681 10682 10683 10684 10685 10686 10687 10688 10689 10690 10691 10692 10693 10694 10695 10696 10697 10698 10699 10700 10701 10702 10703 10704 10705 10706 10707 10708 10709 10710 10711 10712 10713 10714 10715 10716 10717 10718 10719 10720 10721 10722 10723 10724 10725 10726 10727 10728 10729 10730 10731 10732 10733 10734 10735 10736 10737 10738 10739 10740 10741 10742 10743 10744 10745 10746 10747 10748 10749 10750 10751 10752 10753 10754 10755 10756 10757 10758 10759 10760 10761 10762 10763 10764 10765 10766 10767 10768 10769 10770 10771 10772 10773 10774 10775 10776 10777 10778 10779 10780 10781 10782 10783 10784 10785 10786 10787 10788 10789 10790 10791 10792 10793 10794 10795 10796 10797 10798 10799 10800 10801 10802 10803 10804 10805 10806 10807 10808 10809 10810 10811 10812 10813 10814 10815 10816 10817 10818 10819 10820 10821 10822 10823 10824 10825 10826 10827 10828 10829 10830 10831 10832 10833 10834 10835 10836 10837 10838 10839 10840 10841 10842 10843 10844 10845 10846 10847 10848 10849 10850 10851 10852 10853 10854 10855 10856 10857 10858 10859 10860 10861 10862 10863 10864 10865 10866 10867 10868 10869 10870 10871 10872 10873 10874 10875 10876 10877 10878 10879 10880 10881 10882 10883 10884 10885 10886 10887 10888 10889 10890 10891 10892 10893 10894 10895 10896 10897 10898 10899 10900 10901 10902 10903 10904 10905 10906 10907 10908 10909 10910 10911 10912 10913 10914 10915 10916 10917 10918 10919 10920 10921 10922 10923 10924 10925 10926 10927 10928 10929 10930 10931 10932 10933 10934 10935 10936 10937 10938 10939 10940 10941 10942 10943 10944 10945 10946 10947 10948 10949 10950 10951 10952 10953 10954 10955 10956 10957 10958 10959 10960 10961 10962 10963 10964 10965 10966 10967 10968 10969 10970 10971 10972 10973 10974 10975 10976 10977 10978 10979 10980 10981 10982 10983 10984 10985 10986 10987 10988 10989 10990 10991 10992 10993 10994 10995 10996 10997 10998 10999 11000 11001 11002 11003 11004 11005 11006 11007 11008 11009 11010 11011 11012 11013 11014 11015 11016 11017 11018 11019 11020 11021 11022 11023 11024 11025 11026 11027 11028 11029 11030 11031 11032 11033 11034 11035 11036 11037 11038 11039 11040 11041 11042 11043 11044 11045 11046 11047 11048 11049 11050 11051 11052 11053 11054 11055 11056 11057 11058 11059 11060 11061 11062 11063 11064 11065 11066 11067 11068 11069 11070 11071 11072 11073 11074 11075 11076 11077 11078 11079 11080 11081 11082 11083 11084 11085 11086 11087 11088 11089 11090 11091 11092 11093 11094 11095 11096 11097 11098 11099 11100 11101 11102 11103 11104 11105 11106 11107 11108 11109 11110 11111 11112 11113 11114 11115 11116 11117 11118 11119 11120 11121 11122 11123 11124 11125 11126 11127 11128 11129 11130 11131 11132 11133 11134 11135 11136 11137 11138 11139 11140 11141 11142 11143 11144 11145 11146 11147 11148 11149 11150 11151 11152 11153 11154 11155 11156 11157 11158 11159 11160 11161 11162 11163 11164 11165 11166 11167 11168 11169 11170 11171 11172 11173 11174 11175 11176 11177 11178 11179 11180 11181 11182 11183 11184 11185 11186 11187 11188 11189 11190 11191 11192 11193 11194 11195 11196 11197 11198 11199 11200 11201 11202 11203 11204 11205 11206 11207 11208 11209 11210 11211 11212 11213 11214 11215 11216 11217 11218 11219 11220 11221 11222 11223 11224 11225 11226 11227 11228 11229 11230 11231 11232 11233 11234 11235 11236 11237 11238 11239 11240 11241 11242 11243 11244 11245 11246 11247 11248 11249 11250 11251 11252 11253 11254 11255 11256 11257 11258 11259 11260 11261 11262 11263 11264 11265 11266 11267 11268 11269 11270 11271 11272 11273 11274 11275 11276 11277 11278 11279 11280 11281 11282 11283 11284 11285 11286 11287 11288 11289 11290 11291 11292 11293 11294 11295 11296 11297 11298 11299 11300 11301 11302 11303 11304 11305 11306 11307 11308 11309 11310 11311 11312 11313 11314 11315 11316 11317 11318 11319 11320 11321 11322 11323 11324 11325 11326 11327 11328 11329 11330 11331 11332 11333 11334 11335 11336 11337 11338 11339 11340 11341 11342 11343 11344 11345 11346 11347 11348 11349 11350 11351 11352 11353 11354 11355 11356 11357 11358 11359 11360 11361 11362 11363 11364 11365 11366 11367 11368 11369 11370 11371 11372 11373 11374 11375 11376 11377 11378 11379 11380 11381 11382 11383 11384 11385 11386 11387 11388 11389 11390 11391 11392 11393 11394 11395 11396 11397 11398 11399 11400 11401 11402 11403 11404 11405 11406 11407 11408 11409 11410 11411 11412 11413 11414 11415 11416 11417 11418 11419 11420 11421 11422 11423 11424 11425 11426 11427 11428 11429 11430 11431 11432 11433 11434 11435 11436 11437 11438 11439 11440 11441 11442 11443 11444 11445 11446 11447 11448 11449 11450 11451 11452 11453 11454 11455 11456 11457 11458 11459 11460 11461 11462 11463 11464 11465 11466 11467 11468 11469 11470 11471 11472 11473 11474 11475 11476 11477 11478 11479 11480 11481 11482 11483 11484 11485 11486 11487 11488 11489 11490 11491 11492 11493 11494 11495 11496 11497 11498 11499 11500 11501 11502 11503 11504 11505 11506 11507 11508 11509 11510 11511 11512 11513 11514 11515 11516 11517 11518 11519 11520 11521 11522 11523 11524 11525 11526 11527 11528 11529 11530 11531 11532 11533 11534 11535 11536 11537 11538 11539 11540 11541 11542 11543 11544 11545 11546 11547 11548 11549 11550 11551 11552 11553 11554 11555 11556 11557 11558 11559 11560 11561 11562 11563 11564 11565 11566 11567 11568 11569 11570 11571 11572 11573 11574 11575 11576 11577 11578 11579 11580 11581 11582 11583 11584 11585 11586 11587 11588 11589 11590 11591 11592 11593 11594 11595 11596 11597 11598 11599 11600 11601 11602 11603 11604 11605 11606 11607 11608 11609 11610 11611 11612 11613 11614 11615 11616 11617 11618 11619 11620 11621 11622 11623 11624 11625 11626 11627 11628 11629 11630 11631 11632 11633 11634 11635 11636 11637 11638 11639 11640 11641 11642 11643 11644 11645 11646 11647 11648 11649 11650 11651 11652 11653 11654 11655 11656 11657 11658 11659 11660 11661 11662 11663 11664 11665 11666 11667 11668 11669 11670 11671 11672 11673 11674 11675 11676 11677 11678 11679 11680 11681 11682 11683 11684 11685 11686 11687 11688 11689 11690 11691 11692 11693 11694 11695 11696 11697 11698 11699 11700 11701 11702 11703 11704 11705 11706 11707 11708 11709 11710 11711 11712 11713 11714 11715 11716 11717 11718 11719 11720 11721 11722 11723 11724 11725 11726 11727 11728 11729 11730 11731 11732 11733 11734 11735 11736 11737 11738 11739 11740 11741 11742 11743 11744 11745 11746 11747 11748 11749 11750 11751 11752 11753 11754 11755 11756 11757 11758 11759 11760 11761 11762 11763 11764 11765 11766 11767 11768 11769 11770 11771 11772 11773 11774 11775 11776 11777 11778 11779 11780 11781 11782 11783 11784 11785 11786 11787 11788 11789 11790 11791 11792 11793 11794 11795 11796 11797 11798 11799 11800 11801 11802 11803 11804 11805 11806 11807 11808 11809 11810 11811 11812 11813 11814 11815 11816 11817 11818 11819 11820 11821 11822 11823 11824 11825 11826 11827 11828 11829 11830 11831 11832 11833 11834 11835 11836 11837 11838 11839 11840 11841 11842 11843 11844 11845 11846 11847 11848 11849 11850 11851 11852 11853 11854 11855 11856 11857 11858 11859 11860 11861 11862 11863 11864 11865 11866 11867 11868 11869 11870 11871 11872 11873 11874 11875 11876 11877 11878 11879 11880 11881 11882 11883 11884 11885 11886 11887 11888 11889 11890 11891 11892 11893 11894 11895 11896 11897 11898 11899 11900 11901 11902 11903 11904 11905 11906 11907 11908 11909 11910 11911 11912 11913 11914 11915 11916 11917 11918 11919 11920 11921 11922 11923 11924 11925 11926 11927 11928 11929 11930 11931 11932 11933 11934 11935 11936 11937 11938 11939 11940 11941 11942 11943 11944 11945 11946 11947 11948 11949 11950 11951 11952 11953 11954 11955 11956 11957 11958 11959 11960 11961 11962 11963 11964 11965 11966 11967 11968 11969 11970 11971 11972 11973 11974 11975 11976 11977 11978 11979 11980 11981 11982 11983 11984 11985 11986 11987 11988 11989 11990 11991 11992 11993 11994 11995 11996 11997 11998 11999 12000 12001 12002 12003 12004 12005 12006 12007 12008 12009 12010 12011 12012 12013 12014 12015 12016 12017 12018 12019 12020 12021 12022 12023 12024 12025 12026 12027 12028 12029 12030 12031 12032 12033 12034 12035 12036 12037 12038 12039 12040 12041 12042 12043 12044 12045 12046 12047 12048 12049 12050 12051 12052 12053 12054 12055 12056 12057 12058 12059 12060 12061 12062 12063 12064 12065 12066 12067 12068 12069 12070 12071 12072 12073 12074 12075 12076 12077 12078 12079 12080 12081 12082 12083 12084 12085 12086 12087 12088 12089 12090 12091 12092 12093 12094 12095 12096 12097 12098 12099 12100 12101 12102 12103 12104 12105 12106 12107 12108 12109 12110 12111 12112 12113 12114 12115 12116 12117 12118 12119 12120 12121 12122 12123 12124 12125 12126 12127 12128 12129 12130 12131 12132 12133 12134 12135 12136 12137 12138 12139 12140 12141 12142 12143 12144 12145 12146 12147 12148 12149 12150 12151 12152 12153 12154 12155 12156 12157 12158 12159 12160 12161 12162 12163 12164 12165 12166 12167 12168 12169 12170 12171 12172 12173 12174 12175 12176 12177 12178 12179 12180 12181 12182 12183 12184 12185 12186 12187 12188 12189 12190 12191 12192 12193 12194 12195 12196 12197 12198 12199 12200 12201 12202 12203 12204 12205 12206 12207 12208 12209 12210 12211 12212 12213 12214 12215 12216 12217 12218 12219 12220 12221 12222 12223 12224 12225 12226 12227 12228 12229 12230 12231 12232 12233 12234 12235 12236 12237 12238 12239 12240 12241 12242 12243 12244 12245 12246 12247 12248 12249 12250 12251 12252 12253 12254 12255 12256 12257 12258 12259 12260 12261 12262 12263 12264 12265 12266 12267 12268 12269 12270 12271 12272 12273 12274 12275 12276 12277 12278 12279 12280 12281 12282 12283 12284 12285 12286 12287 12288 12289 12290 12291 12292 12293 12294 12295 12296 12297 12298 12299 12300 12301 12302 12303 12304 12305 12306 12307 12308 12309 12310 12311 12312 12313 12314 12315 12316 12317 12318 12319 12320 12321 12322 12323 12324 12325 12326 12327 12328 12329 12330 12331 12332 12333 12334 12335 12336 12337 12338 12339 12340 12341 12342 12343 12344 12345 12346 12347 12348 12349 12350 12351 12352 12353 12354 12355 12356 12357 12358 12359 12360 12361 12362 12363 12364 12365 12366 12367 12368 12369 12370 12371 12372 12373 12374 12375 12376 12377 12378 12379 12380 12381 12382 12383 12384 12385 12386 12387 12388 12389 12390 12391 12392 12393 12394 12395 12396 12397 12398 12399 12400 12401 12402 12403 12404 12405 12406 12407 12408 12409 12410 12411 12412 12413 12414 12415 12416 12417 12418 12419 12420 12421 12422 12423 12424 12425 12426 12427 12428 12429 12430 12431 12432 12433 12434 12435 12436 12437 12438 12439 12440 12441 12442 12443 12444 12445 12446 12447 12448 12449 12450 12451 12452 12453 12454 12455 12456 12457 12458 12459 12460 12461 12462 12463 12464 12465 12466 12467 12468 12469 12470 12471 12472 12473 12474 12475 12476 12477 12478 12479 12480 12481 12482 12483 12484 12485 12486 12487 12488 12489 12490 12491 12492 12493 12494 12495 12496 12497 12498 12499 12500 12501 12502 12503 12504 12505 12506 12507 12508 12509 12510 12511 12512 12513 12514 12515 12516 12517 12518 12519 12520 12521 12522 12523 12524 12525 12526 12527 12528 12529 12530 12531 12532 12533 12534 12535 12536 12537 12538 12539 12540 12541 12542 12543 12544 12545 12546 12547 12548 12549 12550 12551 12552 12553 12554 12555 12556 12557 12558 12559 12560 12561 12562 12563 12564 12565 12566 12567 12568 12569 12570 12571 12572 12573 12574 12575 12576 12577 12578 12579 12580 12581 12582 12583 12584 12585 12586 12587 12588 12589 12590 12591 12592 12593 12594 12595 12596 12597 12598 12599 12600 12601 12602 12603 12604 12605 12606 12607 12608 12609 12610 12611 12612 12613 12614 12615 12616 12617 12618 12619 12620 12621 12622 12623 12624 12625 12626 12627 12628 12629 12630 12631 12632 12633 12634 12635 12636 12637 12638 12639 12640 12641 12642 12643 12644 12645 12646 12647 12648 12649 12650 12651 12652 12653 12654 12655 12656 12657 12658 12659 12660 12661 12662 12663 12664 12665 12666 12667 12668 12669 12670 12671 12672 12673 12674 12675 12676 12677 12678 12679 12680 12681 12682 12683 12684 12685 12686 12687 12688 12689 12690 12691 12692 12693 12694 12695 12696 12697 12698 12699 12700 12701 12702 12703 12704 12705 12706 12707 12708 12709 12710 12711 12712 12713 12714 12715 12716 12717 12718 12719 12720 12721 12722 12723 12724 12725 12726 12727 12728 12729 12730 12731 12732 12733 12734 12735 12736 12737 12738 12739 12740 12741 12742 12743 12744 12745 12746 12747 12748 12749 12750 12751 12752 12753 12754 12755 12756 12757 12758 12759 12760 12761 12762 12763 12764 12765 12766 12767 12768 12769 12770 12771 12772 12773 12774 12775 12776 12777 12778 12779 12780 12781 12782 12783 12784 12785 12786 12787 12788 12789 12790 12791 12792 12793 12794 12795 12796 12797 12798 12799 12800 12801 12802 12803 12804 12805 12806 12807 12808 12809 12810 12811 12812 12813 12814 12815 12816 12817 12818 12819 12820 12821 12822 12823 12824 12825 12826 12827 12828 12829 12830 12831 12832 12833 12834 12835 12836 12837 12838 12839 12840 12841 12842 12843 12844 12845 12846 12847 12848 12849 12850 12851 12852 12853 12854 12855 12856 12857 12858 12859 12860 12861 12862 12863 12864 12865 12866 12867 12868 12869 12870 12871 12872 12873 12874 12875 12876 12877 12878 12879 12880 12881 12882 12883 12884 12885 12886 12887 12888 12889 12890 12891 12892 12893 12894 12895 12896 12897 12898 12899 12900 12901 12902 12903 12904 12905 12906 12907 12908 12909 12910 12911 12912 12913 12914 12915 12916 12917 12918 12919 12920 12921 12922 12923 12924 12925 12926 12927 12928 12929 12930 12931 12932 12933 12934 12935 12936 12937 12938 12939 12940 12941 12942 12943 12944 12945 12946 12947 12948 12949 12950 12951 12952 12953 12954 12955 12956 12957 12958 12959 12960 12961 12962 12963 12964 12965 12966 12967 12968 12969 12970 12971 12972 12973 12974 12975 12976 12977 12978 12979 12980 12981 12982 12983 12984 12985 12986 12987 12988 12989 12990 12991 12992 12993 12994 12995 12996 12997 12998 12999 13000 13001 13002 13003 13004 13005 13006 13007 13008 13009 13010 13011 13012 13013 13014 13015 13016 13017 13018 13019 13020 13021 13022 13023 13024 13025 13026 13027 13028 13029 13030 13031 13032 13033 13034 13035 13036 13037 13038 13039 13040 13041 13042 13043 13044 13045 13046 13047 13048 13049 13050 13051 13052 13053 13054 13055 13056 13057 13058 13059 13060 13061 13062 13063 13064 13065 13066 13067 13068 13069 13070 13071 13072 13073 13074 13075 13076 13077 13078 13079 13080 13081 13082 13083 13084 13085 13086 13087 13088 13089 13090 13091 13092 13093 13094 13095 13096 13097 13098 13099 13100 13101 13102 13103 13104 13105 13106 13107 13108 13109 13110 13111 13112 13113 13114 13115 13116 13117 13118 13119 13120 13121 13122 13123 13124 13125 13126 13127 13128 13129 13130 13131 13132 13133 13134 13135 13136 13137 13138 13139 13140 13141 13142 13143 13144 13145 13146 13147 13148 13149 13150 13151 13152 13153 13154 13155 13156 13157 13158 13159 13160 13161 13162 13163 13164 13165 13166 13167 13168 13169 13170 13171 13172 13173 13174 13175 13176 13177 13178 13179 13180 13181 13182 13183 13184 13185 13186 13187 13188 13189 13190 13191 13192 13193 13194 13195 13196 13197 13198 13199 13200 13201 13202 13203 13204 13205 13206 13207 13208 13209 13210 13211 13212 13213 13214 13215 13216 13217 13218 13219 13220 13221 13222 13223 13224 13225 13226 13227 13228 13229 13230 13231 13232 13233 13234 13235 13236 13237 13238 13239 13240 13241 13242 13243 13244 13245 13246 13247 13248 13249 13250 13251 13252 13253 13254 13255 13256 13257 13258 13259 13260 13261 13262 13263 13264 13265 13266 13267 13268 13269 13270 13271 13272 13273 13274 13275 13276 13277 13278 13279 13280 13281 13282 13283 13284 13285 13286 13287 13288 13289 13290 13291 13292 13293 13294 13295 13296 13297 13298 13299 13300 13301 13302 13303 13304 13305 13306 13307 13308 13309 13310 13311 13312 13313 13314 13315 13316 13317 13318 13319 13320 13321 13322 13323 13324 13325 13326 13327 13328 13329 13330 13331 13332 13333 13334 13335 13336 13337 13338 13339 13340 13341 13342 13343 13344 13345 13346 13347 13348 13349 13350 13351 13352 13353 13354 13355 13356 13357 13358 13359 13360 13361 13362 13363 13364 13365 13366 13367 13368 13369 13370 13371 13372 13373 13374 13375 13376 13377 13378 13379 13380 13381 13382 13383 13384 13385 13386 13387 13388 13389 13390 13391 13392 13393 13394 13395 13396 13397 13398 13399 13400 13401 13402 13403 13404 13405 13406 13407 13408 13409 13410 13411 13412 13413 13414 13415 13416 13417 13418 13419 13420 13421 13422 13423 13424 13425 13426 13427 13428 13429 13430 13431 13432 13433 13434 13435 13436 13437 13438 13439 13440 13441 13442 13443 13444 13445 13446 13447 13448 13449 13450 13451 13452 13453 13454 13455 13456 13457 13458 13459 13460 13461 13462 13463 13464 13465 13466 13467 13468 13469 13470 13471 13472 13473 13474 13475 13476 13477 13478 13479 13480 13481 13482 13483 13484 13485 13486 13487 13488 13489 13490 13491 13492 13493 13494 13495 13496 13497 13498 13499 13500 13501 13502 13503 13504 13505 13506 13507 13508 13509 13510 13511 13512 13513 13514 13515 13516 13517 13518 13519 13520 13521 13522 13523 13524 13525 13526 13527 13528 13529 13530 13531 13532 13533 13534 13535 13536 13537 13538 13539 13540 13541 13542 13543 13544 13545 13546 13547 13548 13549 13550 13551 13552 13553 13554 13555 13556 13557 13558 13559 13560 13561 13562 13563 13564 13565 13566 13567 13568 13569 13570 13571 13572 13573 13574 13575 13576 13577 13578 13579 13580 13581 13582 13583 13584 13585 13586 13587 13588 13589 13590 13591 13592 13593 13594 13595 13596 13597 13598 13599 13600 13601 13602 13603 13604 13605 13606 13607 13608 13609 13610 13611 13612 13613 13614 13615 13616 13617 13618 13619 13620 13621 13622 13623 13624 13625 13626 13627 13628 13629 13630 13631 13632 13633 13634 13635 13636 13637 13638 13639 13640 13641 13642 13643 13644 13645 13646 13647 13648 13649 13650 13651 13652 13653 13654 13655 13656 13657 13658 13659 13660 13661 13662 13663 13664 13665 13666 13667 13668 13669 13670 13671 13672 13673 13674 13675 13676 13677 13678 13679 13680 13681 13682 13683 13684 13685 13686 13687 13688 13689 13690 13691 13692 13693 13694 13695 13696 13697 13698 13699 13700 13701 13702 13703 13704 13705 13706 13707 13708 13709 13710 13711 13712 13713 13714 13715 13716 13717 13718 13719 13720 13721 13722 13723 13724 13725 13726 13727 13728 13729 13730 13731 13732 13733 13734 13735 13736 13737 13738 13739 13740 13741 13742 13743 13744 13745 13746 13747 13748 13749 13750 13751 13752 13753 13754 13755 13756 13757 13758 13759 13760 13761 13762 13763 13764 13765 13766 13767 13768 13769 13770 13771 13772 13773 13774 13775 13776 13777 13778 13779 13780 13781 13782 13783 13784 13785 13786 13787 13788 13789 13790 13791 13792 13793 13794 13795 13796 13797 13798 13799 13800 13801 13802 13803 13804 13805 13806 13807 13808 13809 13810 13811 13812 13813 13814 13815 13816 13817 13818 13819 13820 13821 13822 13823 13824 13825 13826 13827 13828 13829 13830 13831 13832 13833 13834 13835 13836 13837 13838 13839 13840 13841 13842 13843 13844 13845 13846 13847 13848 13849 13850 13851 13852 13853 13854 13855 13856 13857 13858 13859 13860 13861 13862 13863 13864 13865 13866 13867 13868 13869 13870 13871 13872 13873 13874 13875 13876 13877 13878 13879 13880 13881 13882 13883 13884 13885 13886 13887 13888 13889 13890 13891 13892 13893 13894 13895 13896 13897 13898 13899 13900 13901 13902 13903 13904 13905 13906 13907 13908 13909 13910 13911 13912 13913 13914 13915 13916 13917 13918 13919 13920 13921 13922 13923 13924 13925 13926 13927 13928 13929 13930 13931 13932 13933 13934 13935 13936 13937 13938 13939 13940 13941 13942 13943 13944 13945 13946 13947 13948 13949 13950 13951 13952 13953 13954 13955 13956 13957 13958 13959 13960 13961 13962 13963 13964 13965 13966 13967 13968 13969 13970 13971 13972 13973 13974 13975 13976 13977 13978 13979 13980 13981 13982 13983 13984 13985 13986 13987 13988 13989 13990 13991 13992 13993 13994 13995 13996 13997 13998 13999 14000 14001 14002 14003 14004 14005 14006 14007 14008 14009 14010 14011 14012 14013 14014 14015 14016 14017 14018 14019 14020 14021 14022 14023 14024 14025 14026 14027 14028 14029 14030 14031 14032 14033 14034 14035 14036 14037 14038 14039 14040 14041 14042 14043 14044 14045 14046 14047 14048 14049 14050 14051 14052 14053 14054 14055 14056 14057 14058 14059 14060 14061 14062 14063 14064 14065 14066 14067 14068 14069 14070 14071 14072 14073 14074 14075 14076 14077 14078 14079 14080 14081 14082 14083 14084 14085 14086 14087 14088 14089 14090 14091 14092 14093 14094 14095 14096 14097 14098 14099 14100 14101 14102 14103 14104 14105 14106 14107 14108 14109 14110 14111 14112 14113 14114 14115 14116 14117 14118 14119 14120 14121 14122 14123 14124 14125 14126 14127 14128 14129 14130 14131 14132 14133 14134 14135 14136 14137 14138 14139 14140 14141 14142 14143 14144 14145 14146 14147 14148 14149 14150 14151 14152 14153 14154 14155 14156 14157 14158 14159 14160 14161 14162 14163 14164 14165 14166 14167 14168 14169 14170 14171 14172 14173 14174 14175 14176 14177 14178 14179 14180 14181 14182 14183 14184 14185 14186 14187 14188 14189 14190 14191 14192 14193 14194 14195 14196 14197 14198 14199 14200 14201 14202 14203 14204 14205 14206 14207 14208 14209 14210 14211 14212 14213 14214 14215 14216 14217 14218 14219 14220 14221 14222 14223 14224 14225 14226 14227 14228 14229 14230 14231 14232 14233 14234 14235 14236 14237 14238 14239 14240 14241 14242 14243 14244 14245 14246 14247 14248 14249 14250 14251 14252 14253 14254 14255 14256 14257 14258 14259 14260 14261 14262 14263 14264 14265 14266 14267 14268 14269 14270 14271 14272 14273 14274 14275 14276 14277 14278 14279 14280 14281 14282 14283 14284 14285 14286 14287 14288 14289 14290 14291 14292 14293 14294 14295 14296 14297 14298 14299 14300 14301 14302 14303 14304 14305 14306 14307 14308 14309 14310 14311 14312 14313 14314 14315 14316 14317 14318 14319 14320 14321 14322 14323 14324 14325 14326 14327 14328 14329 14330 14331 14332 14333 14334 14335 14336 14337 14338 14339 14340 14341 14342 14343 14344 14345 14346 14347 14348 14349 14350 14351 14352 14353 14354 14355 14356 14357 14358 14359 14360 14361 14362 14363 14364 14365 14366 14367 14368 14369 14370 14371 14372 14373 14374 14375 14376 14377 14378 14379 14380 14381 14382 14383 14384 14385 14386 14387 14388 14389 14390 14391 14392 14393 14394 14395 14396 14397 14398 14399 14400 14401 14402 14403 14404 14405 14406 14407 14408 14409 14410 14411 14412 14413 14414 14415 14416 14417 14418 14419 14420 14421 14422 14423 14424 14425 14426 14427 14428 14429 14430 14431 14432 14433 14434 14435 14436 14437 14438 14439 14440 14441 14442 14443 14444 14445 14446 14447 14448 14449 14450 14451 14452 14453 14454 14455 14456 14457 14458 14459 14460 14461 14462 14463 14464 14465 14466 14467 14468 14469 14470 14471 14472 14473 14474 14475 14476 14477 14478 14479 14480 14481 14482 14483 14484 14485 14486 14487 14488 14489 14490 14491 14492 14493 14494 14495 14496 14497 14498 14499 14500 14501 14502 14503 14504 14505 14506 14507 14508 14509 14510 14511 14512 14513 14514 14515 14516 14517 14518 14519 14520 14521 14522 14523 14524 14525 14526 14527 14528 14529 14530 14531 14532 14533 14534 14535 14536 14537 14538 14539 14540 14541 14542 14543 14544 14545 14546 14547 14548 14549 14550 14551 14552 14553 14554 14555 14556 14557 14558 14559 14560 14561 14562 14563 14564 14565 14566 14567 14568 14569 14570 14571 14572 14573 14574 14575 14576 14577 14578 14579 14580 14581 14582 14583 14584 14585 14586 14587 14588 14589 14590 14591 14592 14593 14594 14595 14596 14597 14598 14599 14600 14601 14602 14603 14604 14605 14606 14607 14608 14609 14610 14611 14612 14613 14614 14615 14616 14617 14618 14619 14620 14621 14622 14623 14624 14625 14626 14627 14628 14629 14630 14631 14632 14633 14634 14635 14636 14637 14638 14639 14640 14641 14642 14643 14644 14645 14646 14647 14648 14649 14650 14651 14652 14653 14654 14655 14656 14657 14658 14659 14660 14661 14662 14663 14664 14665 14666 14667 14668 14669 14670 14671 14672 14673 14674 14675 14676 14677 14678 14679 14680 14681 14682 14683 14684 14685 14686 14687 14688 14689 14690 14691 14692 14693 14694 14695 14696 14697 14698 14699 14700 14701 14702 14703 14704 14705 14706 14707 14708 14709 14710 14711 14712 14713 14714 14715 14716 14717 14718 14719 14720 14721 14722 14723 14724 14725 14726 14727 14728 14729 14730 14731 14732 14733 14734 14735 14736 14737 14738 14739 14740 14741 14742 14743 14744 14745 14746 14747 14748 14749 14750 14751 14752 14753 14754 14755 14756 14757 14758 14759 14760 14761 14762 14763 14764 14765 14766 14767 14768 14769 14770 14771 14772 14773 14774 14775 14776 14777 14778 14779 14780 14781 14782 14783 14784 14785 14786 14787 14788 14789 14790 14791 14792 14793 14794 14795 14796 14797 14798 14799 14800 14801 14802 14803 14804 14805 14806 14807 14808 14809 14810 14811 14812 14813 14814 14815 14816 14817 14818 14819 14820 14821 14822 14823 14824 14825 14826 14827 14828 14829 14830 14831 14832 14833 14834 14835 14836 14837 14838 14839 14840 14841 14842 14843 14844 14845 14846 14847 14848 14849 14850 14851 14852 14853 14854 14855 14856 14857 14858 14859 14860 14861 14862 14863 14864 14865 14866 14867 14868 14869 14870 14871 14872 14873 14874 14875 14876 14877 14878 14879 14880 14881 14882 14883 14884 14885 14886 14887 14888 14889 14890 14891 14892 14893 14894 14895 14896 14897 14898 14899 14900 14901 14902 14903 14904 14905 14906 14907 14908 14909 14910 14911 14912 14913 14914 14915 14916 14917 14918 14919 14920 14921 14922 14923 14924 14925 14926 14927 14928 14929 14930 14931 14932 14933 14934 14935 14936 14937 14938 14939 14940 14941 14942 14943 14944 14945 14946 14947 14948 14949 14950 14951 14952 14953 14954 14955 14956 14957 14958 14959 14960 14961 14962 14963 14964 14965 14966 14967 14968 14969 14970 14971 14972 14973 14974 14975 14976 14977 14978 14979 14980 14981 14982 14983 14984 14985 14986 14987 14988 14989 14990 14991 14992 14993 14994 14995 14996 14997 14998 14999 15000 15001 15002 15003 15004 15005 15006 15007 15008 15009 15010 15011 15012 15013 15014 15015 15016 15017 15018 15019 15020 15021 15022 15023 15024 15025 15026 15027 15028 15029 15030 15031 15032 15033 15034 15035 15036 15037 15038 15039 15040 15041 15042 15043 15044 15045 15046 15047 15048 15049 15050 15051 15052 15053 15054 15055 15056 15057 15058 15059 15060 15061 15062 15063 15064 15065 15066 15067 15068 15069 15070 15071 15072 15073 15074 15075 15076 15077 15078 15079 15080 15081 15082 15083 15084 15085 15086 15087 15088 15089 15090 15091 15092 15093 15094 15095 15096 15097 15098 15099 15100 15101 15102 15103 15104 15105 15106 15107 15108 15109 15110 15111 15112 15113 15114 15115 15116 15117 15118 15119 15120 15121 15122 15123 15124 15125 15126 15127 15128 15129 15130 15131 15132 15133 15134 15135 15136 15137 15138 15139 15140 15141 15142 15143 15144 15145 15146 15147 15148 15149 15150 15151 15152 15153 15154 15155 15156 15157 15158 15159 15160 15161 15162 15163 15164 15165 15166 15167 15168 15169 15170 15171 15172 15173 15174 15175 15176 15177 15178 15179 15180 15181 15182 15183 15184 15185 15186 15187 15188 15189 15190 15191 15192 15193 15194 15195 15196 15197 15198 15199 15200 15201 15202 15203 15204 15205 15206 15207 15208 15209 15210 15211 15212 15213 15214 15215 15216 15217 15218 15219 15220 15221 15222 15223 15224 15225 15226 15227 15228 15229 15230 15231 15232 15233 15234 15235 15236 15237 15238 15239 15240 15241 15242 15243 15244 15245 15246 15247 15248 15249 15250 15251 15252 15253 15254 15255 15256 15257 15258 15259 15260 15261 15262 15263 15264 15265 15266 15267 15268 15269 15270 15271 15272 15273 15274 15275 15276 15277 15278 15279 15280 15281 15282 15283 15284 15285 15286 15287 15288 15289 15290 15291 15292 15293 15294 15295 15296 15297 15298 15299 15300 15301 15302 15303 15304 15305 15306 15307 15308 15309 15310 15311 15312 15313 15314 15315 15316 15317 15318 15319 15320 15321 15322 15323 15324 15325 15326 15327 15328 15329 15330 15331 15332 15333 15334 15335 15336 15337 15338 15339 15340 15341 15342 15343 15344 15345 15346 15347 15348 15349 15350 15351 15352 15353 15354 15355 15356 15357 15358 15359 15360 15361 15362 15363 15364 15365 15366 15367 15368 15369 15370 15371 15372 15373 15374 15375 15376 15377 15378 15379 15380 15381 15382 15383 15384 15385 15386 15387 15388 15389 15390 15391 15392 15393 15394 15395 15396 15397 15398 15399 15400 15401 15402 15403 15404 15405 15406 15407 15408 15409 15410 15411 15412 15413 15414 15415 15416 15417 15418 15419 15420 15421 15422 15423 15424 15425 15426 15427 15428 15429 15430 15431 15432 15433 15434 15435 15436 15437 15438 15439 15440 15441 15442 15443 15444 15445 15446 15447 15448 15449 15450 15451 15452 15453 15454 15455 15456 15457 15458 15459 15460 15461 15462 15463 15464 15465 15466 15467 15468 15469 15470 15471 15472 15473 15474 15475 15476 15477 15478 15479 15480 15481 15482 15483 15484 15485 15486 15487 15488 15489 15490 15491 15492 15493 15494 15495 15496 15497 15498 15499 15500 15501 15502 15503 15504 15505 15506 15507 15508 15509 15510 15511 15512 15513 15514 15515 15516 15517 15518 15519 15520 15521 15522 15523 15524 15525 15526 15527 15528 15529 15530 15531 15532 15533 15534 15535 15536 15537 15538 15539 15540 15541 15542 15543 15544 15545 15546 15547 15548 15549 15550 15551 15552 15553 15554 15555 15556 15557 15558 15559 15560 15561 15562 15563 15564 15565 15566 15567 15568 15569 15570 15571 15572 15573 15574 15575 15576 15577 15578 15579 15580 15581 15582 15583 15584 15585 15586 15587 15588 15589 15590 15591 15592 15593 15594 15595 15596 15597 15598 15599 15600 15601 15602 15603 15604 15605 15606 15607 15608 15609 15610 15611 15612 15613 15614 15615 15616 15617 15618 15619 15620 15621 15622 15623 15624 15625 15626 15627 15628 15629 15630 15631 15632 15633 15634 15635 15636 15637 15638 15639 15640 15641 15642 15643 15644 15645 15646 15647 15648 15649 15650 15651 15652 15653 15654 15655 15656 15657 15658 15659 15660 15661 15662 15663 15664 15665 15666 15667 15668 15669 15670 15671 15672 15673 15674 15675 15676 15677 15678 15679 15680 15681 15682 15683 15684 15685 15686 15687 15688 15689 15690 15691 15692 15693 15694 15695 15696 15697 15698 15699 15700 15701 15702 15703 15704 15705 15706 15707 15708 15709 15710 15711 15712 15713 15714 15715 15716 15717 15718 15719 15720 15721 15722 15723 15724 15725 15726 15727 15728 15729 15730 15731 15732 15733 15734 15735 15736 15737 15738 15739 15740 15741 15742 15743 15744 15745 15746 15747 15748 15749 15750 15751 15752 15753 15754 15755 15756 15757 15758 15759 15760 15761 15762 15763 15764 15765 15766 15767 15768 15769 15770 15771 15772 15773 15774 15775 15776 15777 15778 15779 15780 15781 15782 15783 15784 15785 15786 15787 15788 15789 15790 15791 15792 15793 15794 15795 15796 15797 15798 15799 15800 15801 15802 15803 15804 15805 15806 15807 15808 15809 15810 15811 15812 15813 15814 15815 15816 15817 15818 15819 15820 15821 15822 15823 15824 15825 15826 15827 15828 15829 15830 15831 15832 15833 15834 15835 15836 15837 15838 15839 15840 15841 15842 15843 15844 15845 15846 15847 15848 15849 15850 15851 15852 15853 15854 15855 15856 15857 15858 15859 15860 15861 15862 15863 15864 15865 15866 15867 15868 15869 15870 15871 15872 15873 15874 15875 15876 15877 15878 15879 15880 15881 15882 15883 15884 15885 15886 15887 15888 15889 15890 15891 15892 15893 15894 15895 15896 15897 15898 15899 15900 15901 15902 15903 15904 15905 15906 15907 15908 15909 15910 15911 15912 15913 15914 15915 15916 15917 15918 15919 15920 15921 15922 15923 15924 15925 15926 15927 15928 15929 15930 15931 15932 15933 15934 15935 15936 15937 15938 15939 15940 15941 15942 15943 15944 15945 15946 15947 15948 15949 15950 15951 15952 15953 15954 15955 15956 15957 15958 15959 15960 15961 15962 15963 15964 15965 15966 15967 15968 15969 15970 15971 15972 15973 15974 15975 15976 15977 15978 15979 15980 15981 15982 15983 15984 15985 15986 15987 15988 15989 15990 15991 15992 15993 15994 15995 15996 15997 15998 15999 16000 16001 16002 16003 16004 16005 16006 16007 16008 16009 16010 16011 16012 16013 16014 16015 16016 16017 16018 16019 16020 16021 16022 16023 16024 16025 16026 16027 16028 16029 16030 16031 16032 16033 16034 16035 16036 16037 16038 16039 16040 16041 16042 16043 16044 16045 16046 16047 16048 16049 16050 16051 16052 16053 16054 16055 16056 16057 16058 16059 16060 16061 16062 16063 16064 16065 16066 16067 16068 16069 16070 16071 16072 16073 16074 16075 16076 16077 16078 16079 16080 16081 16082 16083 16084 16085 16086 16087 16088 16089 16090 16091 16092 16093 16094 16095 16096 16097 16098 16099 16100 16101 16102 16103 16104 16105 16106 16107 16108 16109 16110 16111 16112 16113 16114 16115 16116 16117 16118 16119 16120 16121 16122 16123 16124 16125 16126 16127 16128 16129 16130 16131 16132 16133 16134 16135 16136 16137 16138 16139 16140 16141 16142 16143 16144 16145 16146 16147 16148 16149 16150 16151 16152 16153 16154 16155 16156 16157 16158 16159 16160 16161 16162 16163 16164 16165 16166 16167 16168 16169 16170 16171 16172 16173 16174 16175 16176 16177 16178 16179 16180 16181 16182 16183 16184 16185 16186 16187 16188 16189 16190 16191 16192 16193 16194 16195 16196 16197 16198 16199 16200 16201 16202 16203 16204 16205 16206 16207 16208 16209 16210 16211 16212 16213 16214 16215 16216 16217 16218 16219 16220 16221 16222 16223 16224 16225 16226 16227 16228 16229 16230 16231 16232 16233 16234 16235 16236 16237 16238 16239 16240 16241 16242 16243 16244 16245 16246 16247 16248 16249 16250 16251 16252 16253 16254 16255 16256 16257 16258 16259 16260 16261 16262 16263 16264 16265 16266 16267 16268 16269 16270 16271 16272 16273 16274 16275 16276 16277 16278 16279 16280 16281 16282 16283 16284 16285 16286 16287 16288 16289 16290 16291 16292 16293 16294 16295 16296 16297 16298 16299 16300 16301 16302 16303 16304 16305 16306 16307 16308 16309 16310 16311 16312 16313 16314 16315 16316 16317 16318 16319 16320 16321 16322 16323 16324 16325 16326 16327 16328 16329 16330 16331 16332 16333 16334 16335 16336 16337 16338 16339 16340 16341 16342 16343 16344 16345 16346 16347 16348 16349 16350 16351 16352 16353 16354 16355 16356 16357 16358 16359 16360 16361 16362 16363 16364 16365 16366 16367 16368 16369 16370 16371 16372 16373 16374 16375 16376 16377 16378 16379 16380 16381 16382 16383 16384 16385 16386 16387 16388 16389 16390 16391 16392 16393 16394 16395 16396 16397 16398 16399 16400 16401 16402 16403 16404 16405 16406 16407 16408 16409 16410 16411 16412 16413 16414 16415 16416 16417 16418 16419 16420 16421 16422 16423 16424 16425 16426 16427 16428 16429 16430 16431 16432 16433 16434 16435 16436 16437 16438 16439 16440 16441 16442 16443 16444 16445 16446 16447 16448 16449 16450 16451 16452 16453 16454 16455 16456 16457 16458 16459 16460 16461 16462 16463 16464 16465 16466 16467 16468 16469 16470 16471 16472 16473 16474 16475 16476 16477 16478 16479 16480 16481 16482 16483 16484 16485 16486 16487 16488 16489 16490 16491 16492 16493 16494 16495 16496 16497 16498 16499 16500 16501 16502 16503 16504 16505 16506 16507 16508 16509 16510 16511 16512 16513 16514 16515 16516 16517 16518 16519 16520 16521 16522 16523 16524 16525 16526 16527 16528 16529 16530 16531 16532 16533 16534 16535 16536 16537 16538 16539 16540 16541 16542 16543 16544 16545 16546 16547 16548 16549 16550 16551 16552 16553 16554 16555 16556 16557 16558 16559 16560 16561 16562 16563 16564 16565 16566 16567 16568 16569 16570 16571 16572 16573 16574 16575 16576 16577 16578 16579 16580 16581 16582 16583 16584 16585 16586 16587 16588 16589 16590 16591 16592 16593 16594 16595 16596 16597 16598 16599 16600 16601 16602 16603 16604 16605 16606 16607 16608 16609 16610 16611 16612 16613 16614 16615 16616 16617 16618 16619 16620 16621 16622 16623 16624 16625 16626 16627 16628 16629 16630 16631 16632 16633 16634 16635 16636 16637 16638 16639 16640 16641 16642 16643 16644 16645 16646 16647 16648 16649 16650 16651 16652 16653 16654 16655 16656 16657 16658 16659 16660 16661 16662 16663 16664 16665 16666 16667 16668 16669 16670 16671 16672 16673 16674 16675 16676 16677 16678 16679 16680 16681 16682 16683 16684 16685 16686 16687 16688 16689 16690 16691 16692 16693 16694 16695 16696 16697 16698 16699 16700 16701 16702 16703 16704 16705 16706 16707 16708 16709 16710 16711 16712 16713 16714 16715 16716 16717 16718 16719 16720 16721 16722 16723 16724 16725 16726 16727 16728 16729 16730 16731 16732 16733 16734 16735 16736 16737 16738 16739 16740 16741 16742 16743 16744 16745 16746 16747 16748 16749 16750 16751 16752 16753 16754 16755 16756 16757 16758 16759 16760 16761 16762 16763 16764 16765 16766 16767 16768 16769 16770 16771 16772 16773 16774 16775 16776 16777 16778 16779 16780 16781 16782 16783 16784 16785 16786 16787 16788 16789 16790 16791 16792 16793 16794 16795 16796 16797 16798 16799 16800 16801 16802 16803 16804 16805 16806 16807 16808 16809 16810 16811 16812 16813 16814 16815 16816 16817 16818 16819 16820 16821 16822 16823 16824 16825 16826 16827 16828 16829 16830 16831 16832 16833 16834 16835 16836 16837 16838 16839 16840 16841 16842 16843 16844 16845 16846 16847 16848 16849 16850 16851 16852 16853 16854 16855 16856 16857 16858 16859 16860 16861 16862 16863 16864 16865 16866 16867 16868 16869 16870 16871 16872 16873 16874 16875 16876 16877 16878 16879 16880 16881 16882 16883 16884 16885 16886 16887 16888 16889 16890 16891 16892 16893 16894 16895 16896 16897 16898 16899 16900 16901 16902 16903 16904 16905 16906 16907 16908 16909 16910 16911 16912 16913 16914 16915 16916 16917 16918 16919 16920 16921 16922 16923 16924 16925 16926 16927 16928 16929 16930 16931 16932 16933 16934 16935 16936 16937 16938 16939 16940 16941 16942 16943 16944 16945 16946 16947 16948 16949 16950 16951 16952 16953 16954 16955 16956 16957 16958 16959 16960 16961 16962 16963 16964 16965 16966 16967 16968 16969 16970 16971 16972 16973 16974 16975 16976 16977 16978 16979 16980 16981 16982 16983 16984 16985 16986 16987 16988 16989 16990 16991 16992 16993 16994 16995 16996 16997 16998 16999 17000 17001 17002 17003 17004 17005 17006 17007 17008 17009 17010 17011 17012 17013 17014 17015 17016 17017 17018 17019 17020 17021 17022 17023 17024 17025 17026 17027 17028 17029 17030 17031 17032 17033 17034 17035 17036 17037 17038 17039 17040 17041 17042 17043 17044 17045 17046 17047 17048 17049 17050 17051 17052 17053 17054 17055 17056 17057 17058 17059 17060 17061 17062 17063 17064 17065 17066 17067 17068 17069 17070 17071 17072 17073 17074 17075 17076 17077 17078 17079 17080 17081 17082 17083 17084 17085 17086 17087 17088 17089 17090 17091 17092 17093 17094 17095 17096 17097 17098 17099 17100 17101 17102 17103 17104 17105 17106 17107 17108 17109 17110 17111 17112 17113 17114 17115 17116 17117 17118 17119 17120 17121 17122 17123 17124 17125 17126 17127 17128 17129 17130 17131 17132 17133 17134 17135 17136 17137 17138 17139 17140 17141 17142 17143 17144 17145 17146 17147 17148 17149 17150 17151 17152 17153 17154 17155 17156 17157 17158 17159 17160 17161 17162 17163 17164 17165 17166 17167 17168 17169 17170 17171 17172 17173 17174 17175 17176 17177 17178 17179 17180 17181 17182 17183 17184 17185 17186 17187 17188 17189 17190 17191 17192 17193 17194 17195 17196 17197 17198 17199 17200 17201 17202 17203 17204 17205 17206 17207 17208 17209 17210 17211 17212 17213 17214 17215 17216 17217 17218 17219 17220 17221 17222 17223 17224 17225 17226 17227 17228 17229 17230 17231 17232 17233 17234 17235 17236 17237 17238 17239 17240 17241 17242 17243 17244 17245 17246 17247 17248 17249 17250 17251 17252 17253 17254 17255 17256 17257 17258 17259 17260 17261 17262 17263 17264 17265 17266 17267 17268 17269 17270 17271 17272 17273 17274 17275 17276 17277 17278 17279 17280 17281 17282 17283 17284 17285 17286 17287 17288 17289 17290 17291 17292 17293 17294 17295 17296 17297 17298 17299 17300 17301 17302 17303 17304 17305 17306 17307 17308 17309 17310 17311 17312 17313 17314 17315 17316 17317 17318 17319 17320 17321 17322 17323 17324 17325 17326 17327 17328 17329 17330 17331 17332 17333 17334 17335 17336 17337 17338 17339 17340 17341 17342 17343 17344 17345 17346 17347 17348 17349 17350 17351 17352 17353 17354 17355 17356 17357 17358 17359 17360 17361 17362 17363 17364 17365 17366 17367 17368 17369 17370 17371 17372 17373 17374 17375 17376 17377 17378 17379 17380 17381 17382 17383 17384 17385 17386 17387 17388 17389 17390 17391 17392 17393 17394 17395 17396 17397 17398 17399 17400 17401 17402 17403 17404 17405 17406 17407 17408 17409 17410 17411 17412 17413 17414 17415 17416 17417 17418 17419 17420 17421 17422 17423 17424 17425 17426 17427 17428 17429 17430 17431 17432 17433 17434 17435 17436 17437 17438 17439 17440 17441 17442 17443 17444 17445 17446 17447 17448 17449 17450 17451 17452 17453 17454 17455 17456 17457 17458 17459 17460 17461 17462 17463 17464 17465 17466 17467 17468 17469 17470 17471 17472 17473 17474 17475 17476 17477 17478 17479 17480 17481 17482 17483 17484 17485 17486 17487 17488 17489 17490 17491 17492 17493 17494 17495 17496 17497 17498 17499 17500 17501 17502 17503 17504 17505 17506 17507 17508 17509 17510 17511 17512 17513 17514 17515 17516 17517 17518 17519 17520 17521 17522 17523 17524 17525 17526 17527 17528 17529 17530 17531 17532 17533 17534 17535 17536 17537 17538 17539 17540 17541 17542 17543 17544 17545 17546 17547 17548 17549 17550 17551 17552 17553 17554 17555 17556 17557 17558 17559 17560 17561 17562 17563 17564 17565 17566 17567 17568 17569 17570 17571 17572 17573 17574 17575 17576 17577 17578 17579 17580 17581 17582 17583 17584 17585 17586 17587 17588 17589 17590 17591 17592 17593 17594 17595 17596 17597 17598 17599 17600 17601 17602 17603 17604 17605 17606 17607 17608 17609 17610 17611 17612 17613 17614 17615 17616 17617 17618 17619 17620 17621 17622 17623 17624 17625 17626 17627 17628 17629 17630 17631 17632 17633 17634 17635 17636 17637 17638 17639 17640 17641 17642 17643 17644 17645 17646 17647 17648 17649 17650 17651 17652 17653 17654 17655 17656 17657 17658 17659 17660 17661 17662 17663 17664 17665 17666 17667 17668 17669 17670 17671 17672 17673 17674 17675 17676 17677 17678 17679 17680 17681 17682 17683 17684 17685 17686 17687 17688 17689 17690 17691 17692 17693 17694 17695 17696 17697 17698 17699 17700 17701 17702 17703 17704 17705 17706 17707 17708 17709 17710 17711 17712 17713 17714 17715 17716 17717 17718 17719 17720 17721 17722 17723 17724 17725 17726 17727 17728 17729 17730 17731 17732 17733 17734 17735 17736 17737 17738 17739 17740 17741 17742 17743 17744 17745 17746 17747 17748 17749 17750 17751 17752 17753 17754 17755 17756 17757 17758 17759 17760 17761 17762 17763 17764 17765 17766 17767 17768 17769 17770 17771 17772 17773 17774 17775 17776 17777 17778 17779 17780 17781 17782 17783 17784 17785 17786 17787 17788 17789 17790 17791 17792 17793 17794 17795 17796 17797 17798 17799 17800 17801 17802 17803 17804 17805 17806 17807 17808 17809 17810 17811 17812 17813 17814 17815 17816 17817 17818 17819 17820 17821 17822 17823 17824 17825 17826 17827 17828 17829 17830 17831 17832 17833 17834 17835 17836 17837 17838 17839 17840 17841 17842 17843 17844 17845 17846 17847 17848 17849 17850 17851 17852 17853 17854 17855 17856 17857 17858 17859 17860 17861 17862 17863 17864 17865 17866 17867 17868 17869 17870 17871 17872 17873 17874 17875 17876 17877 17878 17879 17880 17881 17882 17883 17884 17885 17886 17887 17888 17889 17890 17891 17892 17893 17894 17895 17896 17897 17898 17899 17900 17901 17902 17903 17904 17905 17906 17907 17908 17909 17910 17911 17912 17913 17914 17915 17916 17917 17918 17919 17920 17921 17922 17923 17924 17925 17926 17927 17928 17929 17930 17931 17932 17933 17934 17935 17936 17937 17938 17939 17940 17941 17942 17943 17944 17945 17946 17947 17948 17949 17950 17951 17952 17953 17954 17955 17956 17957 17958 17959 17960 17961 17962 17963 17964 17965 17966 17967 17968 17969 17970 17971 17972 17973 17974 17975 17976 17977 17978 17979 17980 17981 17982 17983 17984 17985 17986 17987 17988 17989 17990 17991 17992 17993 17994 17995 17996 17997 17998 17999 18000 18001 18002 18003 18004 18005 18006 18007 18008 18009 18010 18011 18012 18013 18014 18015 18016 18017 18018 18019 18020 18021 18022 18023 18024 18025 18026 18027 18028 18029 18030 18031 18032 18033 18034 18035 18036 18037 18038 18039 18040 18041 18042 18043 18044 18045 18046 18047 18048 18049 18050 18051 18052 18053 18054 18055 18056 18057 18058 18059 18060 18061 18062 18063 18064 18065 18066 18067 18068 18069 18070 18071 18072 18073 18074 18075 18076 18077 18078 18079 18080 18081 18082 18083 18084 18085 18086 18087 18088 18089 18090 18091 18092 18093 18094 18095 18096 18097 18098 18099 18100 18101 18102 18103 18104 18105 18106 18107 18108 18109 18110 18111 18112 18113 18114 18115 18116 18117 18118 18119 18120 18121 18122 18123 18124 18125 18126 18127 18128 18129 18130 18131 18132 18133 18134 18135 18136 18137 18138 18139 18140 18141 18142 18143 18144 18145 18146 18147 18148 18149 18150 18151 18152 18153 18154 18155 18156 18157 18158 18159 18160 18161 18162 18163 18164 18165 18166 18167 18168 18169 18170 18171 18172 18173 18174 18175 18176 18177 18178 18179 18180 18181 18182 18183 18184 18185 18186 18187 18188 18189 18190 18191 18192 18193 18194 18195 18196 18197 18198 18199 18200 18201 18202 18203 18204 18205 18206 18207 18208 18209 18210 18211 18212 18213 18214 18215 18216 18217 18218 18219 18220 18221 18222 18223 18224 18225 18226 18227 18228 18229 18230 18231 18232 18233 18234 18235 18236 18237 18238 18239 18240 18241 18242 18243 18244 18245 18246 18247 18248 18249 18250 18251 18252 18253 18254 18255 18256 18257 18258 18259 18260 18261 18262 18263 18264 18265 18266 18267 18268 18269 18270 18271 18272 18273 18274 18275 18276 18277 18278 18279 18280 18281 18282 18283 18284 18285 18286 18287 18288 18289 18290 18291 18292 18293 18294 18295 18296 18297 18298 18299 18300 18301 18302 18303 18304 18305 18306 18307 18308 18309 18310 18311 18312 18313 18314 18315 18316 18317 18318 18319 18320 18321 18322 18323 18324 18325 18326 18327 18328 18329 18330 18331 18332 18333 18334 18335 18336 18337 18338 18339 18340 18341 18342 18343 18344 18345 18346 18347 18348 18349 18350 18351 18352 18353 18354 18355 18356 18357 18358 18359 18360 18361 18362 18363 18364 18365 18366 18367 18368 18369 18370 18371 18372 18373 18374 18375 18376 18377 18378 18379 18380 18381 18382 18383 18384 18385 18386 18387 18388 18389 18390 18391 18392 18393 18394 18395 18396 18397 18398 18399 18400 18401 18402 18403 18404 18405 18406 18407 18408 18409 18410 18411 18412 18413 18414 18415 18416 18417 18418 18419 18420 18421 18422 18423 18424 18425 18426 18427 18428 18429 18430 18431 18432 18433 18434 18435 18436 18437 18438 18439 18440 18441 18442 18443 18444 18445 18446 18447 18448 18449 18450 18451 18452 18453 18454 18455 18456 18457 18458 18459 18460 18461 18462 18463 18464 18465 18466 18467 18468 18469 18470 18471 18472 18473 18474 18475 18476 18477 18478 18479 18480 18481 18482 18483 18484 18485 18486 18487 18488 18489 18490 18491 18492 18493 18494 18495 18496 18497 18498 18499 18500 18501 18502 18503 18504 18505 18506 18507 18508 18509 18510 18511 18512 18513 18514 18515 18516 18517 18518 18519 18520 18521 18522 18523 18524 18525 18526 18527 18528 18529 18530 18531 18532 18533 18534 18535 18536 18537 18538 18539 18540 18541 18542 18543 18544 18545 18546 18547 18548 18549 18550 18551 18552 18553 18554 18555 18556 18557 18558 18559 18560 18561 18562 18563 18564 18565 18566 18567 18568 18569 18570 18571 18572 18573 18574 18575 18576 18577 18578 18579 18580 18581 18582 18583 18584 18585 18586 18587 18588 18589 18590 18591 18592 18593 18594 18595 18596 18597 18598 18599 18600 18601 18602 18603 18604 18605 18606 18607 18608 18609 18610 18611 18612 18613 18614 18615 18616 18617 18618 18619 18620 18621 18622 18623 18624 18625 18626 18627 18628 18629 18630 18631 18632 18633 18634 18635 18636 18637 18638 18639 18640 18641 18642 18643 18644 18645 18646 18647 18648 18649 18650 18651 18652 18653 18654 18655 18656 18657 18658 18659 18660 18661 18662 18663 18664 18665 18666 18667 18668 18669 18670 18671 18672 18673 18674 18675 18676 18677 18678 18679 18680 18681 18682 18683 18684 18685 18686 18687 18688 18689 18690 18691 18692 18693 18694 18695 18696 18697 18698 18699 18700 18701 18702 18703 18704 18705 18706 18707 18708 18709 18710 18711 18712 18713 18714 18715 18716 18717 18718 18719 18720 18721 18722 18723 18724 18725 18726 18727 18728 18729 18730 18731 18732 18733 18734 18735 18736 18737 18738 18739 18740 18741 18742 18743 18744 18745 18746 18747 18748 18749 18750 18751 18752 18753 18754 18755 18756 18757 18758 18759 18760 18761 18762 18763 18764 18765 18766 18767 18768 18769 18770 18771 18772 18773 18774 18775 18776 18777 18778 18779 18780 18781 18782 18783 18784 18785 18786 18787 18788 18789 18790 18791 18792 18793 18794 18795 18796 18797 18798 18799 18800 18801 18802 18803 18804 18805 18806 18807 18808 18809 18810 18811 18812 18813 18814 18815 18816 18817 18818 18819 18820 18821 18822 18823 18824 18825 18826 18827 18828 18829 18830 18831 18832 18833 18834 18835 18836 18837 18838 18839 18840 18841 18842 18843 18844 18845 18846 18847 18848 18849 18850 18851 18852 18853 18854 18855 18856 18857 18858 18859 18860 18861 18862 18863 18864 18865 18866 18867 18868 18869 18870 18871 18872 18873 18874 18875 18876 18877 18878 18879 18880 18881 18882 18883 18884 18885 18886 18887 18888 18889 18890 18891 18892 18893 18894 18895 18896 18897 18898 18899 18900 18901 18902 18903 18904 18905 18906 18907 18908 18909 18910 18911 18912 18913 18914 18915 18916 18917 18918 18919 18920 18921 18922 18923 18924 18925 18926 18927 18928 18929 18930 18931 18932 18933 18934 18935 18936 18937 18938 18939 18940 18941 18942 18943 18944 18945 18946 18947 18948 18949 18950 18951 18952 18953 18954 18955 18956 18957 18958 18959 18960 18961 18962 18963 18964 18965 18966 18967 18968 18969 18970 18971 18972 18973 18974 18975 18976 18977 18978 18979 18980 18981 18982 18983 18984 18985 18986 18987 18988 18989 18990 18991 18992 18993 18994 18995 18996 18997 18998 18999 19000 19001 19002 19003 19004 19005 19006 19007 19008 19009 19010 19011 19012 19013 19014 19015 19016 19017 19018 19019 19020 19021 19022 19023 19024 19025 19026 19027 19028 19029 19030 19031 19032 19033 19034 19035 19036 19037 19038 19039 19040 19041 19042 19043 19044 19045 19046 19047 19048 19049 19050 19051 19052 19053 19054 19055 19056 19057 19058 19059 19060 19061 19062 19063 19064 19065 19066 19067 19068 19069 19070 19071 19072 19073 19074 19075 19076 19077 19078 19079 19080 19081 19082 19083 19084 19085 19086 19087 19088 19089 19090 19091 19092 19093 19094 19095 19096 19097 19098 19099 19100 19101 19102 19103 19104 19105 19106 19107 19108 19109 19110 19111 19112 19113 19114 19115 19116 19117 19118 19119 19120 19121 19122 19123 19124 19125 19126 19127 19128 19129 19130 19131 19132 19133 19134 19135 19136 19137 19138 19139 19140 19141 19142 19143 19144 19145 19146 19147 19148 19149 19150 19151 19152 19153 19154 19155 19156 19157 19158 19159 19160 19161 19162 19163 19164 19165 19166 19167 19168 19169 19170 19171 19172 19173 19174 19175 19176 19177 19178 19179 19180 19181 19182 19183 19184 19185 19186 19187 19188 19189 19190 19191 19192 19193 19194 19195 19196 19197 19198 19199 19200 19201 19202 19203 19204 19205 19206 19207 19208 19209 19210 19211 19212 19213 19214 19215 19216 19217 19218 19219 19220 19221 19222 19223 19224 19225 19226 19227 19228 19229 19230 19231 19232 19233 19234 19235 19236 19237 19238 19239 19240 19241 19242 19243 19244 19245 19246 19247 19248 19249 19250 19251 19252 19253 19254 19255 19256 19257 19258 19259 19260 19261 19262 19263 19264 19265 19266 19267 19268 19269 19270 19271 19272 19273 19274 19275 19276 19277 19278 19279 19280 19281 19282 19283 19284 19285 19286 19287 19288 19289 19290 19291 19292 19293 19294 19295 19296 19297 19298 19299 19300 19301 19302 19303 19304 19305 19306 19307 19308 19309 19310 19311 19312 19313 19314 19315 19316 19317 19318 19319 19320 19321 19322 19323 19324 19325 19326 19327 19328 19329 19330 19331 19332 19333 19334 19335 19336 19337 19338 19339 19340 19341 19342 19343 19344 19345 19346 19347 19348 19349 19350 19351 19352 19353 19354 19355 19356 19357 19358 19359 19360 19361 19362 19363 19364 19365 19366 19367 19368 19369 19370 19371 19372 19373 19374 19375 19376 19377 19378 19379 19380 19381 19382 19383 19384 19385 19386 19387 19388 19389 19390 19391 19392 19393 19394 19395 19396 19397 19398 19399 19400 19401 19402 19403 19404 19405 19406 19407 19408 19409 19410 19411 19412 19413 19414 19415 19416 19417 19418 19419 19420 19421 19422 19423 19424 19425 19426 19427 19428 19429 19430 19431 19432 19433 19434 19435 19436 19437 19438 19439 19440 19441 19442 19443 19444 19445 19446 19447 19448 19449 19450 19451 19452 19453 19454 19455 19456 19457 19458 19459 19460 19461 19462 19463 19464 19465 19466 19467 19468 19469 19470 19471 19472 19473 19474 19475 19476 19477 19478 19479 19480 19481 19482 19483 19484 19485 19486 19487 19488 19489 19490 19491 19492 19493 19494 19495 19496 19497 19498 19499 19500 19501 19502 19503 19504 19505 19506 19507 19508 19509 19510 19511 19512 19513 19514 19515 19516 19517 19518 19519 19520 19521 19522 19523 19524 19525 19526 19527 19528 19529 19530 19531 19532 19533 19534 19535 19536 19537 19538 19539 19540 19541 19542 19543 19544 19545 19546 19547 19548 19549 19550 19551 19552 19553 19554 19555 19556 19557 19558 19559 19560 19561 19562 19563 19564 19565 19566 19567 19568 19569 19570 19571 19572 19573 19574 19575 19576 19577 19578 19579 19580 19581 19582 19583 19584 19585 19586 19587 19588 19589 19590 19591 19592 19593 19594 19595 19596 19597 19598 19599 19600 19601 19602 19603 19604 19605 19606 19607 19608 19609 19610 19611 19612 19613 19614 19615 19616 19617 19618 19619 19620 19621 19622 19623 19624 19625 19626 19627 19628 19629 19630 19631 19632 19633 19634 19635 19636 19637 19638 19639 19640 19641 19642 19643 19644 19645 19646 19647 19648 19649 19650 19651 19652 19653 19654 19655 19656 19657 19658 19659 19660 19661 19662 19663 19664 19665 19666 19667 19668 19669 19670 19671 19672 19673 19674 19675 19676 19677 19678 19679 19680 19681 19682 19683 19684 19685 19686 19687 19688 19689 19690 19691 19692 19693 19694 19695 19696 19697 19698 19699 19700 19701 19702 19703 19704 19705 19706 19707 19708 19709 19710 19711 19712 19713 19714 19715 19716 19717 19718 19719 19720 19721 19722 19723 19724 19725 19726 19727 19728 19729 19730 19731 19732 19733 19734 19735 19736 19737 19738 19739 19740 19741 19742 19743 19744 19745 19746 19747 19748 19749 19750 19751 19752 19753 19754 19755 19756 19757 19758 19759 19760 19761 19762 19763 19764 19765 19766 19767 19768 19769 19770 19771 19772 19773 19774 19775 19776 19777 19778 19779 19780 19781 19782 19783 19784 19785 19786 19787 19788 19789 19790 19791 19792 19793 19794 19795 19796 19797 19798 19799 19800 19801 19802 19803 19804 19805 19806 19807 19808 19809 19810 19811 19812 19813 19814 19815 19816 19817 19818 19819 19820 19821 19822 19823 19824 19825 19826 19827 19828 19829 19830 19831 19832 19833 19834 19835 19836 19837 19838 19839 19840 19841 19842 19843 19844 19845 19846 19847 19848 19849 19850 19851 19852 19853 19854 19855 19856 19857 19858 19859 19860 19861 19862 19863 19864 19865 19866 19867 19868 19869 19870 19871 19872 19873 19874 19875 19876 19877 19878 19879 19880 19881 19882 19883 19884 19885 19886 19887 19888 19889 19890 19891
|
/*
Copyright (c) 2000, 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
*/
/* drop and alter of tables */
#include "sql/sql_table.h"
#include <assert.h>
#include <errno.h>
#include <fcntl.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <atomic>
#include <functional>
#include <memory>
#include <optional>
#include <string>
#include <string_view>
#include <type_traits>
/* HAVE_PSI_*_INTERFACE */
#include "my_psi_config.h" // IWYU pragma: keep
/* drop_table_share with WITH_LOCK_ORDER */
#include "mysql/psi/psi_table.h" // IWYU pragma: keep
/* PSI_TABLE_CALL() with WITH_LOCK_ORDER */
#include "decimal.h"
#include "field_types.h" // enum_field_types
#include "lex_string.h"
#include "libbinlogevents/include/binlog_event.h"
#include "m_ctype.h"
#include "m_string.h" // my_stpncpy
#include "map_helpers.h"
#include "mem_root_deque.h"
#include "my_alloc.h"
#include "my_base.h"
#include "my_bitmap.h"
#include "my_check_opt.h" // T_EXTEND
#include "my_checksum.h"
#include "my_compiler.h"
#include "my_dbug.h"
#include "my_io.h"
#include "my_loglevel.h"
#include "my_psi_config.h"
#include "my_sqlcommand.h"
#include "my_sys.h"
#include "my_systime.h"
#include "my_thread_local.h"
#include "my_time.h"
#include "mysql/components/services/bits/psi_bits.h"
#include "mysql/components/services/bits/psi_stage_bits.h"
#include "mysql/components/services/log_builtins.h"
#include "mysql/components/services/log_shared.h"
#include "mysql/plugin.h"
#include "mysql/psi/mysql_mutex.h"
#include "mysql/psi/mysql_stage.h"
#include "mysql/psi/mysql_table.h" // IWYU pragma: keep
#include "mysql_com.h"
#include "mysql_time.h"
#include "mysqld_error.h" // ER_*
#include "pfs_table_provider.h"
#include "prealloced_array.h"
#include "scope_guard.h"
#include "sql/auth/auth_acls.h"
#include "sql/auth/auth_common.h" // check_fk_parent_table_access
#include "sql/binlog.h" // mysql_bin_log
#include "sql/create_field.h"
#include "sql/current_thd.h"
#include "sql/dd/cache/dictionary_client.h" // dd::cache::Dictionary_client
#include "sql/dd/collection.h"
#include "sql/dd/dd.h" // dd::get_dictionary
#include "sql/dd/dd_schema.h" // dd::schema_exists
#include "sql/dd/dd_table.h" // dd::drop_table, dd::update_keys...
#include "sql/dd/dictionary.h" // dd::Dictionary
#include "sql/dd/properties.h" // dd::Properties
#include "sql/dd/sdi_api.h" // dd::sdi::drop_sdis
#include "sql/dd/string_type.h"
#include "sql/dd/types/abstract_table.h"
#include "sql/dd/types/check_constraint.h" // dd::Check_constraint
#include "sql/dd/types/column.h"
#include "sql/dd/types/foreign_key.h" // dd::Foreign_key
#include "sql/dd/types/foreign_key_element.h" // dd::Foreign_key_element
#include "sql/dd/types/index.h" // dd::Index
#include "sql/dd/types/index_element.h" // dd::Index_element
#include "sql/dd/types/partition.h" // dd::Partition
#include "sql/dd/types/schema.h"
#include "sql/dd/types/table.h" // dd::Table
#include "sql/dd/types/trigger.h"
#include "sql/dd_sql_view.h" // update_referencing_views_metadata
#include "sql/dd_table_share.h" // open_table_def
#include "sql/debug_sync.h" // DEBUG_SYNC
#include "sql/derror.h" // ER_THD
#include "sql/enum_query_type.h"
#include "sql/error_handler.h" // Drop_table_error_handler
#include "sql/field.h"
#include "sql/field_common_properties.h"
#include "sql/filesort.h" // Filesort
#include "sql/gis/srid.h"
#include "sql/handler.h"
#include "sql/histograms/histogram.h"
#include "sql/item.h"
#include "sql/item_timefunc.h" // Item_func_now_local
#include "sql/iterators/row_iterator.h"
#include "sql/join_optimizer/access_path.h"
#include "sql/join_optimizer/bit_utils.h"
#include "sql/key.h" // KEY
#include "sql/key_spec.h" // Key_part_spec
#include "sql/lock.h" // mysql_lock_remove, lock_tablespace_names
#include "sql/locked_tables_list.h"
#include "sql/log.h"
#include "sql/log_event.h" // Query_log_event
#include "sql/mdl.h"
#include "sql/mem_root_array.h"
#include "sql/my_decimal.h"
#include "sql/mysqld.h" // lower_case_table_names
#include "sql/partition_element.h"
#include "sql/partition_info.h" // partition_info
#include "sql/partitioning/partition_handler.h" // Partition_handler
#include "sql/protocol.h"
#include "sql/psi_memory_key.h"
#include "sql/query_options.h"
#include "sql/rpl_gtid.h"
#include "sql/rpl_rli.h" // rli_slave etc
#include "sql/session_tracker.h"
#include "sql/sql_alter.h"
#include "sql/sql_backup_lock.h" // acquire_shared_backup_lock
#include "sql/sql_base.h" // lock_table_names
#include "sql/sql_bitmap.h"
#include "sql/sql_check_constraint.h" // Sql_check_constraint_spec*
#include "sql/sql_class.h" // THD
#include "sql/sql_const.h"
#include "sql/sql_constraint.h" // Constraint_type_resolver
#include "sql/sql_db.h" // get_default_db_collation
#include "sql/sql_error.h"
#include "sql/sql_executor.h" // unique_ptr_destroy_only<RowIterator>
#include "sql/sql_gipk.h"
#include "sql/sql_handler.h"
#include "sql/sql_lex.h"
#include "sql/sql_list.h"
#include "sql/sql_parse.h" // test_if_data_home_dir
#include "sql/sql_partition.h"
#include "sql/sql_plist.h"
#include "sql/sql_plugin.h"
#include "sql/sql_plugin_ref.h"
#include "sql/sql_resolver.h" // setup_order
#include "sql/sql_show.h"
#include "sql/sql_tablespace.h" // validate_tablespace_name
#include "sql/sql_time.h" // make_truncated_value_warning
#include "sql/sql_trigger.h" // change_trigger_table_name
#include "sql/srs_fetcher.h"
#include "sql/stateless_allocator.h"
#include "sql/strfunc.h" // find_type2
#include "sql/system_variables.h"
#include "sql/table.h"
#include "sql/thd_raii.h"
#include "sql/thr_malloc.h"
#include "sql/transaction.h" // trans_commit_stmt
#include "sql/transaction_info.h"
#include "sql/trigger.h"
#include "sql/xa.h"
#include "sql_string.h"
#include "template_utils.h"
#include "thr_lock.h"
#include "typelib.h"
namespace dd {
class View;
} // namespace dd
using binary_log::checksum_crc32;
using std::max;
using std::min;
using std::string;
using std::to_string;
/** Don't pack string keys shorter than this (if PACK_KEYS=1 isn't used). */
static constexpr const int KEY_DEFAULT_PACK_LENGTH{8};
/* Max number of enumeration values */
static constexpr const int MAX_ENUM_VALUES{65535};
#define ER_THD_OR_DEFAULT(thd, X) \
((thd) ? ER_THD_NONCONST(thd, X) : ER_DEFAULT_NONCONST(X))
const char *primary_key_name = "PRIMARY";
namespace {
bool is_temp_table(const HA_CREATE_INFO &ci) {
return (ci.options & HA_LEX_CREATE_TMP_TABLE);
}
bool is_engine_specified(const HA_CREATE_INFO &ci) {
assert((ci.used_fields & HA_CREATE_USED_ENGINE) == 0 ||
ci.db_type != nullptr);
return (ci.used_fields & HA_CREATE_USED_ENGINE);
}
handlerton *default_handlerton(THD *thd, const HA_CREATE_INFO &ci) {
return is_temp_table(ci) ? ha_default_temp_handlerton(thd)
: ha_default_handlerton(thd);
}
handlerton *requested_handlerton(THD *thd, const HA_CREATE_INFO &ci) {
return is_engine_specified(ci) ? ci.db_type : default_handlerton(thd, ci);
}
struct Handlerton_pair {
handlerton *requested;
handlerton *alternate;
};
using Viability_error_emitter = std::function<void(const char *engine_name)>;
using Viability_substitution_warning_emitter = std::function<void(
THD *, const char *requested_engine_name,
const char *substituted_engine_name, const char *table_name)>;
struct Viability {
bool value{true};
Viability_error_emitter emit_error;
Viability_substitution_warning_emitter emit_substitution_warning;
Viability() = default;
Viability(Viability_error_emitter &&error_emitter,
Viability_substitution_warning_emitter &&warning_emitter)
: value{false},
emit_error{std::move(error_emitter)},
emit_substitution_warning{std::move(warning_emitter)} {
assert(emit_error);
assert(emit_substitution_warning);
}
};
Viability get_viability(const handlerton &hton, const HA_CREATE_INFO &ci) {
DBUG_TRACE;
if (ha_is_externally_disabled(hton)) {
return {[](const char *en) {
my_error(ER_DISABLED_STORAGE_ENGINE, MYF(0), en);
},
[](THD *t, const char *ren, const char *sen, const char *tn) {
push_warning_printf(t, Sql_condition::SL_WARNING,
ER_DISABLED_STORAGE_ENGINE,
ER_THD(t, ER_DISABLED_STORAGE_ENGINE), ren);
push_warning_printf(
t, Sql_condition::SL_WARNING, ER_WARN_USING_OTHER_HANDLER,
ER_THD(t, ER_WARN_USING_OTHER_HANDLER), sen, tn);
}};
}
if (is_temp_table(ci) &&
ha_check_storage_engine_flag(&hton, HTON_TEMPORARY_NOT_SUPPORTED)) {
return {
[](const char *en) {
my_error(ER_ILLEGAL_HA_CREATE_OPTION, MYF(0), en, "TEMPORARY");
},
[](THD *, const char *, const char *,
const char *) { /* Nothing, no warning emitted in this case */ }};
}
return {};
}
handlerton *get_viable_handlerton_for_create_impl(THD *thd,
const char *table_name,
const HA_CREATE_INFO &ci,
Handlerton_pair hp) {
DBUG_TRACE;
assert(hp.requested != nullptr);
auto viability = get_viability(*hp.requested, ci);
if (viability.value) {
return hp.requested;
}
assert(viability.emit_error);
const char *en = ha_resolve_storage_engine_name(hp.requested);
if (hp.alternate == nullptr) {
viability.emit_error(en);
return nullptr;
}
auto alt_viability = get_viability(*hp.alternate, ci);
const char *an = ha_resolve_storage_engine_name(hp.alternate);
if (!alt_viability.value) {
viability.emit_error(en);
return nullptr;
}
viability.emit_substitution_warning(thd, en, an, table_name);
return hp.alternate;
}
/**
Check if source is enabled AND NOT explicitly disabled (listed in the
disabled_storages_engines system variable.
If not; falls back to the default (tmp) storage engine if substitution
is allowed, unless this is also disabled.
Otherwise, if substitution does take place, ER_DISABLED_STORAGE_ENGINE and
ER_USING_OTHER_HANDLER are emitted as warnings.
For temporary tables the above also applies, and in addition the source
handlerton is checked to see if it supports temporary tables.
Note that this substitution is allowed even when no_substitution is ON, but
will fail if the default handlerton for temporary tables is disabled or does
not support temporary tables (unlikely).
@param thd Thread handler.
@param table_name Table name.
@param ci create info struct from parser.
@param source Handlerton requested by query.
@retval source if this is viable.
@retval The default hton if viable and engine substitution is allowed.
@retval The default temp hton if viable and a temporary table and source
does not support temporary tables.
@retval nullptr if error (source not viable and substitution
not possible).
*/
handlerton *get_viable_handlerton_for_create_like(THD *thd,
const char *table_name,
const HA_CREATE_INFO &ci,
handlerton *source) {
return get_viable_handlerton_for_create_impl(
thd, table_name, ci,
{source, is_engine_substitution_allowed(thd) || is_temp_table(ci)
? default_handlerton(thd, ci)
: nullptr});
}
/**
Does nothing (returns existing) unless ALTER changes the ENGINE. The
handlerton for the specified ENGINE is considered viable if it is enabled AND
NOT explicitly disabled (listed in the disabled_storages_engines system
variable).
If the specified handleton is not viable it falls back to existing if
substitution is allowed. existing is used without further checking,
and ER_UNKNOWN_STORAGE_ENGINE is emitted as warning.
@param thd Thread handler.
@param ci create info struct from parser.
@param existing Handlerton requested by query.
@retval existing if ENGINE is not specified or is the same as existing, or if
ENGINE is not viable and substitution is permitted.
@retval Handlerton of specified engine if this is viable.
@retval nullptr if error (specified engine not viable and substitution
not permitted).
*/
handlerton *get_viable_handlerton_for_alter(THD *thd, const HA_CREATE_INFO &ci,
handlerton *existing) {
DBUG_TRACE;
if (!is_engine_specified(ci) || ci.db_type == existing) return existing;
Handlerton_pair hp = {
ci.db_type, is_engine_substitution_allowed(thd) ? existing : nullptr};
assert(hp.requested != nullptr);
auto viability = get_viability(*hp.requested, ci);
if (viability.value) {
return hp.requested;
}
const char *en = ha_resolve_storage_engine_name(hp.requested);
if (hp.alternate == nullptr) {
viability.emit_error(en);
return nullptr;
}
push_warning_printf(thd, Sql_condition::SL_WARNING, ER_UNKNOWN_STORAGE_ENGINE,
ER_THD(thd, ER_UNKNOWN_STORAGE_ENGINE), en);
return hp.alternate;
}
} // namespace
/**
Checks if the handlerton for the specified ENGINE is enabled AND NOT
explicitly disabled (listed in the disabled_storages_engines system
variable). In the case of temporary tables the handlerton must also support
those to be viable.
When returning a handlerton different from the one specified
ER_DISABLED_STORAGE_ENGINE and ER_USING_OTHER_HANDLER are emitted as
warnings.
@param thd Thread handler.
@param table_name Table name.
@param ci create_info struct from parser.
@retval Handlerton for specified ENGINE if this is viable.
@retval The default (tmp) handlerton if viable and engine substitution is
allowed.
@retval nullptr if error (specified ENGINE not viable and substitution
not permitted).
*/
handlerton *get_viable_handlerton_for_create(THD *thd, const char *table_name,
const HA_CREATE_INFO &ci) {
return get_viable_handlerton_for_create_impl(
thd, table_name, ci,
{requested_handlerton(thd, ci),
(is_engine_specified(ci) && is_engine_substitution_allowed(thd))
? default_handlerton(thd, ci)
: nullptr});
}
static bool check_if_keyname_exists(const char *name, KEY *start, KEY *end);
static const char *make_unique_key_name(const char *field_name, KEY *start,
KEY *end);
static const dd::Index *find_fk_supporting_key(handlerton *hton,
const dd::Table *table_def,
const dd::Foreign_key *fk);
static const dd::Index *find_fk_parent_key(handlerton *hton,
const dd::Index *supporting_key,
const dd::Table *parent_table_def,
const dd::Foreign_key *fk);
static int copy_data_between_tables(
THD *thd, PSI_stage_progress *psi, TABLE *from, TABLE *to,
List<Create_field> &create, ha_rows *copied, ha_rows *deleted,
Alter_info::enum_enable_or_disable keys_onoff, Alter_table_ctx *alter_ctx);
static bool prepare_blob_field(THD *thd, Create_field *sql_field,
bool convert_character_set);
static bool check_engine(const char *db_name, const char *table_name,
HA_CREATE_INFO *create_info);
static bool prepare_set_field(THD *thd, Create_field *sql_field);
static bool prepare_enum_field(THD *thd, Create_field *sql_field);
static uint blob_length_by_type(enum_field_types type);
static const Create_field *get_field_by_index(Alter_info *alter_info, uint idx);
static bool generate_check_constraint_name(THD *thd, const char *table_name,
uint ordinal_number,
LEX_STRING &name,
bool skip_validation);
static bool push_check_constraint_mdl_request_to_list(
THD *thd, const char *db, const char *cc_name,
MDL_request_list &cc_mdl_request_list);
static bool prepare_check_constraints_for_create_like_table(
THD *thd, Table_ref *src_table, Table_ref *table, Alter_info *alter_info);
static bool prepare_check_constraints_for_alter(THD *thd, const TABLE *table,
Alter_info *alter_info,
Alter_table_ctx *alter_tbl_ctx);
static void set_check_constraints_alter_mode(dd::Table *table,
Alter_info *alter_info);
static void reset_check_constraints_alter_mode(dd::Table *table);
static bool adjust_check_constraint_names_for_old_table_version(
THD *thd, const char *old_table_db, dd::Table *old_table);
static bool is_any_check_constraints_evaluation_required(
const Alter_info *alter_info);
static bool check_if_field_used_by_generated_column_or_default(
TABLE *table, const Field *field, const Alter_info *alter_info);
/**
RAII class to control the atomic DDL commit on slave.
A slave context flag responsible to mark the DDL as committed is
raised and kept for the entirety of DDL commit block.
While DDL commits the slave info table won't take part
in its transaction.
*/
class Disable_slave_info_update_guard {
Relay_log_info *m_rli;
bool m_flag;
public:
Disable_slave_info_update_guard(THD *thd)
: m_rli(thd->rli_slave), m_flag(false) {
if (!thd->slave_thread) {
assert(!m_rli);
return;
}
assert(m_rli->current_event);
m_flag = static_cast<Query_log_event *>(thd->rli_slave->current_event)
->has_ddl_committed;
static_cast<Query_log_event *>(m_rli->current_event)->has_ddl_committed =
true;
}
~Disable_slave_info_update_guard() {
if (m_rli) {
static_cast<Query_log_event *>(m_rli->current_event)->has_ddl_committed =
m_flag;
}
}
};
static bool trans_intermediate_ddl_commit(THD *thd, bool error) {
// Must be used for intermediate (but not final) DDL commits.
Implicit_substatement_state_guard substatement_guard(thd);
if (error) {
trans_rollback_stmt(thd);
// Full rollback in case we have THD::transaction_rollback_request.
trans_rollback(thd);
return true;
}
return trans_commit_stmt(thd) || trans_commit(thd);
}
/**
@brief Helper function for explain_filename
@param thd Thread handle
@param to_p Explained name in system_charset_info
@param end_p End of the to_p buffer
@param name Name to be converted
@param name_len Length of the name, in bytes
*/
static char *add_identifier(THD *thd, char *to_p, const char *end_p,
const char *name, size_t name_len) {
size_t res;
uint errors;
const char *conv_name;
char tmp_name[FN_REFLEN];
char conv_string[FN_REFLEN];
int quote;
DBUG_TRACE;
if (!name[name_len])
conv_name = name;
else {
my_stpnmov(tmp_name, name, name_len);
tmp_name[name_len] = 0;
conv_name = tmp_name;
}
res = strconvert(&my_charset_filename, conv_name, system_charset_info,
conv_string, FN_REFLEN, &errors);
if (!res || errors) {
DBUG_PRINT("error", ("strconvert of '%s' failed with %u (errors: %u)",
conv_name, static_cast<uint>(res), errors));
conv_name = name;
} else {
DBUG_PRINT("info", ("conv '%s' -> '%s'", conv_name, conv_string));
conv_name = conv_string;
}
quote = thd ? get_quote_char_for_identifier(thd, conv_name, res - 1) : '`';
if (quote != EOF && (end_p - to_p > 2)) {
*(to_p++) = (char)quote;
while (*conv_name && (end_p - to_p - 1) > 0) {
uint length = my_mbcharlen(system_charset_info, *conv_name);
if (!length) length = 1;
if (length == 1 && *conv_name == (char)quote) {
if ((end_p - to_p) < 3) break;
*(to_p++) = (char)quote;
*(to_p++) = *(conv_name++);
} else if (((long)length) < (end_p - to_p)) {
to_p = my_stpnmov(to_p, conv_name, length);
conv_name += length;
} else
break; /* string already filled */
}
if (end_p > to_p) {
*(to_p++) = (char)quote;
if (end_p > to_p)
*to_p = 0; /* terminate by NUL, but do not include it in the count */
}
} else
to_p = my_stpnmov(to_p, conv_name, end_p - to_p);
return to_p;
}
/**
@brief Explain a path name by split it to database, table etc.
@details Break down the path name to its logic parts
(database, table, partition, subpartition).
filename_to_tablename cannot be used on partitions, due to the @#P@# part.
There can be up to 6 '#', @#P@# for partition, @#SP@# for subpartition
and @#TMP@# or @#REN@# for temporary or renamed partitions.
This should be used when something should be presented to a user in a
diagnostic, error etc. when it would be useful to know what a particular
file [and directory] means. Such as SHOW ENGINE STATUS, error messages etc.
@param thd Thread handle
@param from Path name in my_charset_filename
Null terminated in my_charset_filename, normalized
to use '/' as directory separation character.
@param to Explained name in system_charset_info
@param to_length Size of to buffer
@param explain_mode Requested output format.
EXPLAIN_ALL_VERBOSE ->
[Database `db`, ]Table `tbl`[,[ Temporary| Renamed]
Partition `p` [, Subpartition `sp`]]
EXPLAIN_PARTITIONS_VERBOSE -> `db`.`tbl`
[[ Temporary| Renamed] Partition `p`
[, Subpartition `sp`]]
EXPLAIN_PARTITIONS_AS_COMMENT -> `db`.`tbl` |*
[,[ Temporary| Renamed] Partition `p`
[, Subpartition `sp`]] *|
(| is really a /, and it is all in one line)
@retval Length of returned string
*/
size_t explain_filename(THD *thd, const char *from, char *to, size_t to_length,
enum_explain_filename_mode explain_mode) {
char *to_p = to;
char *end_p = to_p + to_length;
const char *db_name = nullptr;
size_t db_name_len = 0;
const char *table_name;
size_t table_name_len = 0;
const char *part_name = nullptr;
size_t part_name_len = 0;
const char *subpart_name = nullptr;
size_t subpart_name_len = 0;
enum enum_part_name_type { NORMAL, TEMP, RENAMED } part_type = NORMAL;
const char *tmp_p;
DBUG_TRACE;
DBUG_PRINT("enter", ("from '%s'", from));
tmp_p = from;
table_name = from;
/*
If '/' then take last directory part as database.
'/' is the directory separator, not FN_LIB_CHAR
*/
while ((tmp_p = strchr(tmp_p, '/'))) {
db_name = table_name;
/* calculate the length */
db_name_len = tmp_p - db_name;
tmp_p++;
table_name = tmp_p;
}
tmp_p = table_name;
/* Look if there are partition tokens in the table name. */
while ((tmp_p = strchr(tmp_p, '#'))) {
tmp_p++;
switch (tmp_p[0]) {
case 'P':
case 'p':
if (tmp_p[1] == '#') {
part_name = tmp_p + 2;
tmp_p += 2;
}
break;
case 'S':
case 's':
if ((tmp_p[1] == 'P' || tmp_p[1] == 'p') && tmp_p[2] == '#') {
part_name_len = tmp_p - part_name - 1;
subpart_name = tmp_p + 3;
tmp_p += 3;
}
break;
case 'T':
case 't':
if ((tmp_p[1] == 'M' || tmp_p[1] == 'm') &&
(tmp_p[2] == 'P' || tmp_p[2] == 'p') && tmp_p[3] == '#' &&
!tmp_p[4]) {
part_type = TEMP;
tmp_p += 4;
}
break;
case 'R':
case 'r':
if ((tmp_p[1] == 'E' || tmp_p[1] == 'e') &&
(tmp_p[2] == 'N' || tmp_p[2] == 'n') && tmp_p[3] == '#' &&
!tmp_p[4]) {
part_type = RENAMED;
tmp_p += 4;
}
break;
default:
/* Not partition name part. */
;
}
}
if (part_name) {
table_name_len = part_name - table_name - 3;
if (subpart_name)
subpart_name_len = strlen(subpart_name);
else
part_name_len = strlen(part_name);
if (part_type != NORMAL) {
if (subpart_name)
subpart_name_len -= 5;
else
part_name_len -= 5;
}
} else
table_name_len = strlen(table_name);
if (db_name) {
if (explain_mode == EXPLAIN_ALL_VERBOSE) {
to_p = my_stpncpy(to_p, ER_THD_OR_DEFAULT(thd, ER_DATABASE_NAME),
end_p - to_p);
*(to_p++) = ' ';
to_p = add_identifier(thd, to_p, end_p, db_name, db_name_len);
to_p = my_stpncpy(to_p, ", ", end_p - to_p);
} else {
to_p = add_identifier(thd, to_p, end_p, db_name, db_name_len);
to_p = my_stpncpy(to_p, ".", end_p - to_p);
}
}
if (explain_mode == EXPLAIN_ALL_VERBOSE) {
to_p =
my_stpncpy(to_p, ER_THD_OR_DEFAULT(thd, ER_TABLE_NAME), end_p - to_p);
*(to_p++) = ' ';
to_p = add_identifier(thd, to_p, end_p, table_name, table_name_len);
} else
to_p = add_identifier(thd, to_p, end_p, table_name, table_name_len);
if (part_name) {
if (explain_mode == EXPLAIN_PARTITIONS_AS_COMMENT)
to_p = my_stpncpy(to_p, " /* ", end_p - to_p);
else if (explain_mode == EXPLAIN_PARTITIONS_VERBOSE)
to_p = my_stpncpy(to_p, " ", end_p - to_p);
else
to_p = my_stpncpy(to_p, ", ", end_p - to_p);
if (part_type != NORMAL) {
if (part_type == TEMP)
to_p = my_stpncpy(to_p, ER_THD_OR_DEFAULT(thd, ER_TEMPORARY_NAME),
end_p - to_p);
else
to_p = my_stpncpy(to_p, ER_THD_OR_DEFAULT(thd, ER_RENAMED_NAME),
end_p - to_p);
to_p = my_stpncpy(to_p, " ", end_p - to_p);
}
to_p = my_stpncpy(to_p, ER_THD_OR_DEFAULT(thd, ER_PARTITION_NAME),
end_p - to_p);
*(to_p++) = ' ';
to_p = add_identifier(thd, to_p, end_p, part_name, part_name_len);
if (subpart_name) {
to_p = my_stpncpy(to_p, ", ", end_p - to_p);
to_p = my_stpncpy(to_p, ER_THD_OR_DEFAULT(thd, ER_SUBPARTITION_NAME),
end_p - to_p);
*(to_p++) = ' ';
to_p = add_identifier(thd, to_p, end_p, subpart_name, subpart_name_len);
}
if (explain_mode == EXPLAIN_PARTITIONS_AS_COMMENT)
to_p = my_stpncpy(to_p, " */", end_p - to_p);
}
DBUG_PRINT("exit", ("to '%s'", to));
return static_cast<size_t>(to_p - to);
}
/*
Translate a file name to a table name (WL #1324).
SYNOPSIS
filename_to_tablename()
from The file name in my_charset_filename.
to OUT The table name in system_charset_info.
to_length The size of the table name buffer.
stay_quiet Silence the errors.
has_errors OUT True, if there are errors.
RETURN
Table name length.
*/
size_t filename_to_tablename(const char *from, char *to, size_t to_length,
bool stay_quiet, bool *has_errors) {
uint errors;
size_t res;
DBUG_TRACE;
DBUG_PRINT("enter", ("from '%s'", from));
if (has_errors != nullptr) *has_errors = false;
if (strlen(from) >= tmp_file_prefix_length &&
!memcmp(from, tmp_file_prefix, tmp_file_prefix_length)) {
/* Temporary table name. */
res = (my_stpnmov(to, from, to_length) - to);
} else {
res = strconvert(&my_charset_filename, from, system_charset_info, to,
to_length, &errors);
if (errors) // Old 5.0 name
{
if (has_errors != nullptr) *has_errors = true;
if (!stay_quiet) {
LogErr(ERROR_LEVEL, ER_INVALID_OR_OLD_TABLE_OR_DB_NAME, from);
}
/*
TODO: add a stored procedure for fix table and database names,
and mention its name in error log.
*/
}
}
DBUG_PRINT("exit", ("to '%s'", to));
return res;
}
/*
Translate a table name to a file name (WL #1324).
SYNOPSIS
tablename_to_filename()
from The table name in system_charset_info.
to OUT The file name in my_charset_filename.
to_length The size of the file name buffer.
RETURN
File name length.
*/
size_t tablename_to_filename(const char *from, char *to, size_t to_length) {
uint errors;
size_t length;
DBUG_TRACE;
DBUG_PRINT("enter", ("from '%s'", from));
length = strconvert(system_charset_info, from, &my_charset_filename, to,
to_length, &errors);
if (check_if_legal_tablename(to) && length + 4 < to_length) {
memcpy(to + length, "@@@", 4);
length += 3;
}
DBUG_PRINT("exit", ("to '%s'", to));
return length;
}
/*
@brief Creates path to a file: mysql_data_dir/db/table.ext
@param buff Where to write result in my_charset_filename.
This may be the same as table_name.
@param bufflen buff size
@param db Database name in system_charset_info.
@param table_name Table name in system_charset_info.
@param ext File extension.
@param flags FN_FROM_IS_TMP or FN_TO_IS_TMP or FN_IS_TMP
table_name is temporary, do not change.
@param was_truncated points to location that will be
set to true if path was truncated,
to false otherwise.
@note
Uses database and table name, and extension to create
a file name in mysql_data_dir. Database and table
names are converted from system_charset_info into "fscs".
Unless flags indicate a temporary table name.
'db' is always converted.
'ext' is not converted.
The conversion suppression is required for ALTER TABLE. This
statement creates intermediate tables. These are regular
(non-temporary) tables with a temporary name. Their path names must
be derivable from the table name. So we cannot use
build_tmptable_filename() for them.
@return
path length
*/
size_t build_table_filename(char *buff, size_t bufflen, const char *db,
const char *table_name, const char *ext, uint flags,
bool *was_truncated) {
char tbbuff[FN_REFLEN], dbbuff[FN_REFLEN];
size_t tab_len, db_len;
DBUG_TRACE;
DBUG_PRINT("enter", ("db: '%s' table_name: '%s' ext: '%s' flags: %x", db,
table_name, ext, flags));
if (flags & FN_IS_TMP) // FN_FROM_IS_TMP | FN_TO_IS_TMP
tab_len = my_stpnmov(tbbuff, table_name, sizeof(tbbuff)) - tbbuff;
else
tab_len = tablename_to_filename(table_name, tbbuff, sizeof(tbbuff));
db_len = tablename_to_filename(db, dbbuff, sizeof(dbbuff));
char *end = buff + bufflen;
/* Don't add FN_ROOTDIR if mysql_data_home already includes it */
char *pos = my_stpnmov(buff, mysql_data_home, bufflen);
size_t rootdir_len = strlen(FN_ROOTDIR);
if (pos - rootdir_len >= buff &&
memcmp(pos - rootdir_len, FN_ROOTDIR, rootdir_len) != 0)
pos = my_stpnmov(pos, FN_ROOTDIR, end - pos);
else
rootdir_len = 0;
pos = strxnmov(pos, end - pos, dbbuff, FN_ROOTDIR, NullS);
pos = strxnmov(pos, end - pos, tbbuff, ext, NullS);
/**
Mark OUT param if path gets truncated.
Most of functions which invoke this function are sure that the
path will not be truncated. In case some functions are not sure,
we can use 'was_truncated' OUTPARAM
*/
*was_truncated = false;
if (pos == end && (bufflen < mysql_data_home_len + rootdir_len + db_len +
strlen(FN_ROOTDIR) + tab_len + strlen(ext)))
*was_truncated = true;
DBUG_PRINT("exit", ("buff: '%s'", buff));
return pos - buff;
}
/**
Create path to a temporary table, like mysql_tmpdir/@#sql1234_12_1
(i.e. to its .FRM file but without an extension).
@param thd The thread handle.
@param buff Where to write result in my_charset_filename.
@param bufflen buff size
@note
Uses current_pid, thread_id, and tmp_table counter to create
a file name in mysql_tmpdir.
@return Path length.
*/
size_t build_tmptable_filename(THD *thd, char *buff, size_t bufflen) {
DBUG_TRACE;
char *p = my_stpnmov(buff, mysql_tmpdir, bufflen);
assert(sizeof(my_thread_id) == 4);
snprintf(p, bufflen - (p - buff), "/%s%lx_%x_%x", tmp_file_prefix,
current_pid, thd->thread_id(), thd->tmp_table++);
if (lower_case_table_names) {
/* Convert all except tmpdir to lower case */
my_casedn_str(files_charset_info, p);
}
size_t length = unpack_filename(buff, buff);
DBUG_PRINT("exit", ("buff: '%s'", buff));
return length;
}
/**
Create a dd::Table-object specifying the temporary table
definition, but do not put it into the Data Dictionary. The created
dd::Table-instance is returned via tmp_table_def out-parameter.
The temporary table is also created in the storage engine, depending
on the 'no_ha_table' argument.
@param thd Thread handler
@param path Name of file (including database)
@param sch_obj Schema.
@param db Schema name.
Cannot use dd::Schema::name() directly due to LCTN.
@param table_name Table name
@param create_info create info parameters
@param create_fields Fields to create
@param keys number of keys to create
@param key_info Keys to create
@param keys_onoff Enable or disable keys.
@param check_cons_spec List of check constraint specification.
@param file Handler to use
@param no_ha_table Indicates that only definitions needs to be created
and not a table in the storage engine.
@param[out] binlog_to_trx_cache
Which binlog cache should be used?
If true => trx cache
If false => stmt cache
@param[out] tmp_table_def Data-dictionary object for temporary table
which was created. Is not set if no_ha_table
was false.
@retval false ok
@retval true error
*/
static bool rea_create_tmp_table(
THD *thd, const char *path, const dd::Schema &sch_obj, const char *db,
const char *table_name, HA_CREATE_INFO *create_info,
List<Create_field> &create_fields, uint keys, KEY *key_info,
Alter_info::enum_enable_or_disable keys_onoff,
const Sql_check_constraint_spec_list *check_cons_spec, handler *file,
bool no_ha_table, bool *binlog_to_trx_cache,
std::unique_ptr<dd::Table> *tmp_table_def) {
DBUG_TRACE;
std::unique_ptr<dd::Table> tmp_table_ptr =
dd::create_tmp_table(thd, sch_obj, table_name, create_info, create_fields,
key_info, keys, keys_onoff, check_cons_spec, file);
if (!tmp_table_ptr) return true;
if (no_ha_table) {
*tmp_table_def = std::move(tmp_table_ptr);
return false;
}
// Create the table in the storage engine.
if (ha_create_table(thd, path, db, table_name, create_info, false, false,
tmp_table_ptr.get())) {
return true;
}
/*
Open a table (skipping table cache) and add it into
THD::temporary_tables list.
*/
TABLE *table = open_table_uncached(thd, path, db, table_name, true, true,
*tmp_table_ptr.get());
if (!table) {
(void)rm_temporary_table(thd, create_info->db_type, path,
tmp_table_ptr.get());
return true;
}
// Transfer ownership of dd::Table object to TABLE_SHARE.
table->s->tmp_table_def = tmp_table_ptr.release();
thd->thread_specific_used = true;
if (binlog_to_trx_cache != nullptr)
*binlog_to_trx_cache = table->file->has_transactions();
return false;
}
/**
Create table definition in the Data Dictionary. The table is also
created in the storage engine, depending on the 'no_ha_table' argument.
@param thd Thread handler
@param path Name of file (including database)
@param sch_obj Schema.
@param db Schema name.
Cannot use dd::Schema::name() directly due to
LCTN.
@param table_name Table name
@param create_info create info parameters
@param create_fields Fields to create
@param keys number of keys to create
@param key_info Keys to create
@param keys_onoff Enable or disable keys.
@param fk_keys Number of foreign keys to create
@param fk_key_info Foreign keys to create
@param check_cons_spec List of check constraint specifications.
@param file Handler to use
@param no_ha_table Indicates that only definitions needs to be
created and not a table in the storage engine.
@param do_not_store_in_dd Indicates that we should postpone storing table
object in the data-dictionary. Requires SE
supporting atomic DDL and no_ha_table flag set.
@param part_info Reference to partitioning data structure.
@param[out] binlog_to_trx_cache
Which binlog cache should be used?
If true => trx cache
If false => stmt cache
@param[out] table_def_ptr dd::Table object describing the table
created if do_not_store_in_dd option was
used. Not set otherwise.
@param[out] post_ddl_ht Set to handlerton for table's SE, if this SE
supports atomic DDL, so caller can call SE
post DDL hook after committing transaction.
@note For engines supporting atomic DDL the caller must rollback
both statement and transaction on failure. This must be done
before any further accesses to DD. @sa dd::create_table().
@retval false ok
@retval true error
*/
static bool rea_create_base_table(
THD *thd, const char *path, const dd::Schema &sch_obj, const char *db,
const char *table_name, HA_CREATE_INFO *create_info,
List<Create_field> &create_fields, uint keys, KEY *key_info,
Alter_info::enum_enable_or_disable keys_onoff, uint fk_keys,
FOREIGN_KEY *fk_key_info,
const Sql_check_constraint_spec_list *check_cons_spec, handler *file,
bool no_ha_table, bool do_not_store_in_dd, partition_info *part_info,
bool *binlog_to_trx_cache, std::unique_ptr<dd::Table> *table_def_ptr,
handlerton **post_ddl_ht) {
DBUG_TRACE;
std::unique_ptr<dd::Table> table_def_res = dd::create_table(
thd, sch_obj, table_name, create_info, create_fields, key_info, keys,
keys_onoff, fk_key_info, fk_keys, check_cons_spec, file);
if (!table_def_res) return true;
dd::cache::Dictionary_client::Auto_releaser releaser(thd->dd_client());
dd::Table *table_def = nullptr;
if (do_not_store_in_dd) {
/*
Clean up code assumes that SE supports atomic DDL if do_not_store_in_dd
was requested, so we can simply rollback our changes.
ha_create_table() won't work correctly if dd::Table object is not stored
in the data-dictionary.
For data-dictionary tables we rely on Dictionary_client::store() to update
their table definition.
*/
assert(create_info->db_type->flags & HTON_SUPPORTS_ATOMIC_DDL);
assert(no_ha_table);
assert(!dd::get_dictionary()->get_dd_table(db, table_name));
*table_def_ptr = std::move(table_def_res);
table_def = table_def_ptr->get();
} else {
bool result = thd->dd_client()->store(table_def_res.get());
if (!(create_info->db_type->flags & HTON_SUPPORTS_ATOMIC_DDL) &&
!thd->is_plugin_fake_ddl())
result = trans_intermediate_ddl_commit(thd, result);
if (result) return true;
if (thd->dd_client()->acquire_for_modification(db, table_name, &table_def))
return true;
}
if (no_ha_table) {
if (part_info) {
/*
For partitioned tables we can't find some problems with table
until table is opened. Therefore in order to disallow creation
of corrupted tables we have to try to open table as the part
of its creation process.
In cases when both .FRM and SE part of table are created table
is implicitly open in ha_create_table() call.
In cases when we create .FRM without SE part we have to open
table explicitly.
*/
TABLE table;
TABLE_SHARE share;
init_tmp_table_share(thd, &share, db, 0, table_name, path, nullptr);
bool result = open_table_def(thd, &share, *table_def) ||
open_table_from_share(thd, &share, "", 0, (uint)READ_ALL, 0,
&table, true, nullptr);
/*
Assert that the change list is empty as no partition function currently
needs to modify item tree. May need call THD::rollback_item_tree_changes
later before calling closefrm if the change list is not empty.
*/
assert(thd->change_list.is_empty());
if (!result) (void)closefrm(&table, false);
free_table_share(&share);
if (result) {
/*
If changes were committed remove table from DD.
We ignore the errors returned from there functions
as we anyway report error.
*/
if (!(create_info->db_type->flags & HTON_SUPPORTS_ATOMIC_DDL)) {
bool drop_result = dd::drop_table(thd, db, table_name, *table_def);
(void)trans_intermediate_ddl_commit(thd, drop_result);
}
return true;
}
}
return false;
}
if ((create_info->db_type->flags & HTON_SUPPORTS_ATOMIC_DDL) &&
create_info->db_type->post_ddl)
*post_ddl_ht = create_info->db_type;
if (ha_create_table(thd, path, db, table_name, create_info, false, false,
table_def)) {
/*
Remove table from data-dictionary if it was added and rollback
won't do this automatically.
*/
if (!(create_info->db_type->flags & HTON_SUPPORTS_ATOMIC_DDL)) {
/*
We ignore error from dd_drop_table() as we anyway
return 'true' failure below.
*/
bool result = dd::drop_table(thd, db, table_name, *table_def);
if (!thd->is_plugin_fake_ddl())
(void)trans_intermediate_ddl_commit(thd, result);
}
return true;
}
/*
If the SE supports atomic DDL, we can use the trx binlog cache.
Otherwise we must use the statement cache.
*/
if (binlog_to_trx_cache != nullptr)
*binlog_to_trx_cache =
(create_info->db_type->flags & HTON_SUPPORTS_ATOMIC_DDL);
return false;
}
/*
SYNOPSIS
write_bin_log()
thd Thread object
clear_error is clear_error to be called
query Query to log
query_length Length of query
is_trans if the event changes either
a trans or non-trans engine.
RETURN VALUES
NONE
DESCRIPTION
Write the binlog if open, routine used in multiple places in this
file
*/
int write_bin_log(THD *thd, bool clear_error, const char *query,
size_t query_length, bool is_trans) {
int error = 0;
if (mysql_bin_log.is_open()) {
int errcode = 0;
if (clear_error)
thd->clear_error();
else
errcode = query_error_code(thd, true);
error = thd->binlog_query(THD::STMT_QUERY_TYPE, query, query_length,
is_trans, false, false, errcode);
}
return error;
}
bool lock_trigger_names(THD *thd, Table_ref *tables) {
for (Table_ref *table = tables; table; table = table->next_global) {
if (table->open_type == OT_TEMPORARY_ONLY ||
(table->open_type == OT_TEMPORARY_OR_BASE && is_temporary_table(table)))
continue;
dd::cache::Dictionary_client::Auto_releaser releaser(thd->dd_client());
const dd::Table *table_obj = nullptr;
if (thd->dd_client()->acquire(table->db, table->table_name, &table_obj)) {
// Error is reported by the dictionary subsystem.
return true;
}
if (table_obj == nullptr) continue;
for (const dd::Trigger *trigger : table_obj->triggers()) {
if (acquire_exclusive_mdl_for_trigger(thd, table->db,
trigger->name().c_str()))
return true;
}
}
return false;
}
/**
Add MDL requests for specified lock type on all tables referenced by the
given dd::Table object to the list. Also add the referenced table names to
the foreign key invalidator, to be used at a later stage to invalidate the
dd::Table objects.
@param thd Thread handle.
@param table_def dd::Table object.
@param lock_type Type of MDL requests to add.
@param hton Handlerton for table's storage engine.
@param[in,out] mdl_requests List to which MDL requests are to be added.
@param[in,out] fk_invalidator Object keeping track of which dd::Table
objects to invalidate.
@retval operation outcome, false if no error.
*/
static bool collect_fk_parents_for_all_fks(
THD *thd, const dd::Table *table_def, handlerton *hton,
enum_mdl_type lock_type, MDL_request_list *mdl_requests,
Foreign_key_parents_invalidator *fk_invalidator) {
for (const dd::Foreign_key *fk : table_def->foreign_keys()) {
char buff_db[NAME_LEN + 1];
char buff_table[NAME_LEN + 1];
my_stpncpy(buff_db, fk->referenced_table_schema_name().c_str(), NAME_LEN);
my_stpncpy(buff_table, fk->referenced_table_name().c_str(), NAME_LEN);
/*
In lower-case-table-names == 2 mode we store original versions of table
and db names in the data-dictionary. Hence they need to be lowercased
to produce correct MDL key for them and for other uses.
*/
if (lower_case_table_names == 2) {
my_casedn_str(system_charset_info, buff_db);
my_casedn_str(system_charset_info, buff_table);
}
MDL_request *mdl_request = new (thd->mem_root) MDL_request;
if (mdl_request == nullptr) return true;
MDL_REQUEST_INIT(mdl_request, MDL_key::TABLE, buff_db, buff_table,
lock_type, MDL_STATEMENT);
mdl_requests->push_front(mdl_request);
mdl_request = new (thd->mem_root) MDL_request;
if (mdl_request == nullptr) return true;
MDL_REQUEST_INIT(mdl_request, MDL_key::SCHEMA, buff_db, "",
MDL_INTENTION_EXCLUSIVE, MDL_STATEMENT);
mdl_requests->push_front(mdl_request);
if (fk_invalidator) fk_invalidator->add(buff_db, buff_table, hton);
}
return false;
}
/**
Add MDL requests for specified lock type on all tables referencing
the given table.
@param thd Thread handle.
@param table_def dd::Table object describing the table.
@param lock_type Type of MDL requests to add.
@param[in,out] mdl_requests List to which MDL requests are to be added.
@retval operation outcome, false if no error.
*/
static bool collect_fk_children(THD *thd, const dd::Table *table_def,
enum_mdl_type lock_type,
MDL_request_list *mdl_requests) {
for (const dd::Foreign_key_parent *fk : table_def->foreign_key_parents()) {
char buff_db[NAME_LEN + 1];
char buff_table[NAME_LEN + 1];
my_stpncpy(buff_db, fk->child_schema_name().c_str(), NAME_LEN);
my_stpncpy(buff_table, fk->child_table_name().c_str(), NAME_LEN);
/*
In lower-case-table-names == 2 mode we store original versions of table
and db names in the data-dictionary. Hence they need to be lowercased
to produce correct MDL key for them and for other uses.
*/
if (lower_case_table_names == 2) {
my_casedn_str(system_charset_info, buff_db);
my_casedn_str(system_charset_info, buff_table);
}
MDL_request *mdl_request = new (thd->mem_root) MDL_request;
if (mdl_request == nullptr) return true;
MDL_REQUEST_INIT(mdl_request, MDL_key::TABLE, buff_db, buff_table,
lock_type, MDL_STATEMENT);
mdl_requests->push_front(mdl_request);
mdl_request = new (thd->mem_root) MDL_request;
if (mdl_request == nullptr) return true;
MDL_REQUEST_INIT(mdl_request, MDL_key::SCHEMA, buff_db, "",
MDL_INTENTION_EXCLUSIVE, MDL_STATEMENT);
mdl_requests->push_front(mdl_request);
}
return false;
}
/**
Add MDL requests for exclusive lock on all foreign key names on the given
table to the list.
@param thd Thread context.
@param db Table's schema name.
@param table_def Table definition.
@param[in,out] mdl_requests List to which MDL requests are to be added.
@retval operation outcome, false if no error.
*/
static bool collect_fk_names(THD *thd, const char *db,
const dd::Table *table_def,
MDL_request_list *mdl_requests) {
for (const dd::Foreign_key *fk : table_def->foreign_keys()) {
/*
Since foreign key names are case-insensitive we need to lowercase them
before passing to MDL subsystem.
*/
char fk_name[NAME_LEN + 1];
strmake(fk_name, fk->name().c_str(), NAME_LEN);
my_casedn_str(system_charset_info, fk_name);
MDL_request *mdl_request = new (thd->mem_root) MDL_request;
if (mdl_request == nullptr) return true;
MDL_REQUEST_INIT(mdl_request, MDL_key::FOREIGN_KEY, db, fk_name,
MDL_EXCLUSIVE, MDL_STATEMENT);
mdl_requests->push_front(mdl_request);
}
return false;
}
bool rm_table_do_discovery_and_lock_fk_tables(THD *thd, Table_ref *tables) {
MEM_ROOT mdl_reqs_root(key_memory_rm_db_mdl_reqs_root, MEM_ROOT_BLOCK_SIZE);
MDL_request_list mdl_requests;
for (Table_ref *table = tables; table; table = table->next_local) {
if (table->open_type != OT_BASE_ONLY && is_temporary_table(table)) continue;
dd::cache::Dictionary_client::Auto_releaser releaser(thd->dd_client());
const dd::Abstract_table *abstract_table_def = nullptr;
if (thd->dd_client()->acquire(table->db, table->table_name,
&abstract_table_def))
return true;
if (!abstract_table_def) {
/*
If table is missing try to discover it from some storage engine
as it might have foreign keys.
*/
int result = ha_create_table_from_engine(
thd, table->db,
(lower_case_table_names == 2) ? table->alias : table->table_name);
if (result > 0) {
// Error during discovery, error should be reported already.
return true;
} else if (result == 0) {
// Table was discovered. Re-try to retrieve its definition.
if (thd->dd_client()->acquire(table->db, table->table_name,
&abstract_table_def))
return true;
} else // result < 0
{
// No table was found.
}
}
if (!abstract_table_def ||
abstract_table_def->type() != dd::enum_table_type::BASE_TABLE)
continue;
const dd::Table *table_def =
dynamic_cast<const dd::Table *>(abstract_table_def);
/*
Ensure that we don't hold memory used by MDL_requests after locks
have been acquired. This reduces memory usage in cases when we have
DROP DATABASE that needs to drop lots of different objects.
*/
MEM_ROOT *save_thd_mem_root = thd->mem_root;
auto restore_thd_mem_root =
create_scope_guard([&]() { thd->mem_root = save_thd_mem_root; });
thd->mem_root = &mdl_reqs_root;
if (collect_fk_parents_for_all_fks(thd, table_def, nullptr, MDL_EXCLUSIVE,
&mdl_requests, nullptr))
return true;
if (collect_fk_children(thd, table_def, MDL_EXCLUSIVE, &mdl_requests))
return true;
if (collect_fk_names(thd, table->db, table_def, &mdl_requests)) return true;
}
if (!mdl_requests.is_empty() &&
thd->mdl_context.acquire_locks(&mdl_requests,
thd->variables.lock_wait_timeout))
return true;
return false;
}
void Foreign_key_parents_invalidator::add(
const char *db_name, const char *table_name, handlerton *hton,
enum_invalidation_type invalidation_type) {
m_parent_map.insert(typename Parent_map::value_type(
typename Parent_map::key_type(db_name, table_name),
typename Parent_map::mapped_type(hton, invalidation_type)));
}
void Foreign_key_parents_invalidator::mark_for_reopen_if_added(
const char *db_name, const char *table_name) {
auto parent_it =
m_parent_map.find(typename Parent_map::key_type(db_name, table_name));
if (parent_it != m_parent_map.end()) {
parent_it->second.second =
enum_invalidation_type::INVALIDATE_AND_MARK_FOR_REOPEN;
}
}
void Foreign_key_parents_invalidator::invalidate(THD *thd) {
for (auto parent_it : m_parent_map) {
if (parent_it.second.second ==
enum_invalidation_type::INVALIDATE_AND_CLOSE_TABLE) {
// Invalidate Table and Table Definition Caches too.
mysql_ha_flush_table(thd, parent_it.first.first.c_str(),
parent_it.first.second.c_str());
close_all_tables_for_name(thd, parent_it.first.first.c_str(),
parent_it.first.second.c_str(), false);
} else {
assert(parent_it.second.second ==
enum_invalidation_type::INVALIDATE_AND_MARK_FOR_REOPEN);
tdc_remove_table(thd, TDC_RT_MARK_FOR_REOPEN,
parent_it.first.first.c_str(),
parent_it.first.second.c_str(), false);
}
/*
TODO: Should revisit the way we do invalidation to avoid
suppressing errors, which is necessary since it's done after
commit. For now, we use an error handler.
*/
Dummy_error_handler error_handler;
thd->push_internal_handler(&error_handler);
bool ignored [[maybe_unused]];
ignored = thd->dd_client()->invalidate(parent_it.first.first.c_str(),
parent_it.first.second.c_str());
DBUG_EXECUTE_IF("fail_while_invalidating_fk_parents",
{ my_error(ER_LOCK_DEADLOCK, MYF(0)); });
thd->pop_internal_handler();
// And storage engine internal dictionary cache as well.
#ifdef DISABLED_UNTIL_WL9533
/*
TODO: Simply removing entries from InnoDB internal cache breaks
its FK checking logic at the moment. This is to be solved
as part of WL#9533. We might have to replace invalidation
with cache update to do this.
*/
if ((parent_it.second)->dict_cache_reset)
((parent_it.second))
->dict_cache_reset(parent_it.first.first.c_str(),
parent_it.first.second.c_str());
#endif
}
m_parent_map.clear();
}
/*
delete (drop) tables.
SYNOPSIS
mysql_rm_table()
thd Thread handle
tables List of tables to delete
if_exists If 1, don't give error if one table doesn't exists
NOTES
Will delete all tables that can be deleted and give a compact error
messages for tables that could not be deleted.
If a table is in use, we will wait for all users to free the table
before dropping it
Wait if global_read_lock (FLUSH TABLES WITH READ LOCK) is set, but
not if under LOCK TABLES.
RETURN
false OK. In this case ok packet is sent to user
true Error
*/
bool mysql_rm_table(THD *thd, Table_ref *tables, bool if_exists,
bool drop_temporary) {
bool error;
Drop_table_error_handler err_handler;
Table_ref *table;
uint have_non_tmp_table = 0;
DBUG_TRACE;
// DROP table is not allowed in the XA_IDLE or XA_PREPARED transaction states.
if (thd->get_transaction()->xid_state()->check_xa_idle_or_prepared(true)) {
return true;
}
/*
DROP tables need to have their logging format determined if
in MIXED mode and dropping a TEMP table.
*/
if (thd->decide_logging_format(tables)) {
return true;
}
/* Disable drop of enabled log tables, must be done before name locking */
for (table = tables; table; table = table->next_local) {
if (query_logger.check_if_log_table(table, true)) {
my_error(ER_BAD_LOG_STATEMENT, MYF(0), "DROP");
return true;
}
}
if (!drop_temporary) {
if (!thd->locked_tables_mode) {
if (lock_table_names(thd, tables, nullptr,
thd->variables.lock_wait_timeout, 0) ||
lock_trigger_names(thd, tables))
return true;
DEBUG_SYNC(thd, "mysql_rm_table_after_lock_table_names");
for (table = tables; table; table = table->next_local) {
if (is_temporary_table(table)) continue;
/* Here we are sure that a non-tmp table exists */
have_non_tmp_table = 1;
}
} else {
bool acquire_backup_lock = false;
for (table = tables; table; table = table->next_local)
if (is_temporary_table(table)) {
/*
A temporary table.
Don't try to find a corresponding MDL lock or assign it
to table->mdl_request.ticket. There can't be metadata
locks for temporary tables: they are local to the session.
Later in this function we release the MDL lock only if
table->mdl_requeset.ticket is not NULL. Thus here we
ensure that we won't release the metadata lock on the base
table locked with LOCK TABLES as a side effect of temporary
table drop.
*/
assert(table->mdl_request.ticket == nullptr);
} else {
/*
Not a temporary table.
Since 'tables' list can't contain duplicates (this is ensured
by parser) it is safe to cache pointer to the TABLE instances
in its elements.
*/
table->table = find_table_for_mdl_upgrade(thd, table->db,
table->table_name, false);
if (!table->table) return true;
table->mdl_request.ticket = table->table->mdl_ticket;
if (wait_while_table_is_used(thd, table->table,
HA_EXTRA_FORCE_REOPEN))
return true;
/* Here we are sure that a non-tmp table exists */
have_non_tmp_table = 1;
if (!acquire_backup_lock) acquire_backup_lock = true;
}
if (acquire_backup_lock &&
acquire_shared_backup_lock(thd, thd->variables.lock_wait_timeout))
return true;
}
if (rm_table_do_discovery_and_lock_fk_tables(thd, tables)) return true;
if (lock_check_constraint_names(thd, tables)) return true;
}
std::vector<MDL_ticket *> safe_to_release_mdl;
{
// This Auto_releaser needs to go out of scope before we start releasing
// metadata locks below. Otherwise we end up having acquired objects for
// which we no longer have any locks held.
dd::cache::Dictionary_client::Auto_releaser releaser(thd->dd_client());
std::set<handlerton *> post_ddl_htons;
Foreign_key_parents_invalidator fk_invalidator;
bool not_used;
/* mark for close and remove all cached entries */
thd->push_internal_handler(&err_handler);
error = mysql_rm_table_no_locks(thd, tables, if_exists, drop_temporary,
false, ¬_used, &post_ddl_htons,
&fk_invalidator, &safe_to_release_mdl);
thd->pop_internal_handler();
}
if (!drop_temporary) {
/*
Under LOCK TABLES we should release meta-data locks on the tables
which were dropped.
Leave LOCK TABLES mode if we managed to drop all tables which were
locked. Additional check for 'non_temp_tables_count' is to avoid
leaving LOCK TABLES mode if we have dropped only temporary tables.
*/
if (thd->locked_tables_mode) {
/*
First we need to reopen tables which data-dictionary entries were
updated/invalidated (and thus they were closed) due to fact that
they participate in the same FKs as tables which were dropped.
*/
if (thd->locked_tables_list.reopen_tables(thd)) error = true;
if (thd->lock && thd->lock->table_count == 0 && have_non_tmp_table > 0) {
thd->mdl_context.release_statement_locks();
thd->locked_tables_list.unlock_locked_tables(thd);
} else {
for (MDL_ticket *mdl_ticket : safe_to_release_mdl) {
/*
Under LOCK TABLES we may have several instances of table open
and locked and therefore have to remove several metadata lock
requests associated with them.
*/
thd->mdl_context.release_all_locks_for_name(mdl_ticket);
}
}
}
}
if (error) return true;
if (thd->lex->drop_temporary && thd->in_multi_stmt_transaction_mode()) {
/*
When autocommit is disabled, dropping temporary table sets this flag
to start transaction in any case (regardless of binlog=on/off,
binlog format and transactional/non-transactional engine) to make
behavior consistent.
*/
thd->server_status |= SERVER_STATUS_IN_TRANS;
}
if (thd->variables.binlog_format == BINLOG_FORMAT_STMT &&
thd->lex->drop_temporary && (thd->in_sub_stmt & SUB_STMT_FUNCTION) &&
thd->binlog_evt_union.do_union) {
/*
This does not write the query into binary log, it just sets
thd->binlog_evt_union.unioned_events to true for writing
its top function call to the binary log on function exit
in mixed mode and statement mode. So this does not cause
any error.
*/
write_bin_log(thd, true, thd->query().str, thd->query().length, true);
}
my_ok(thd);
return false;
}
/**
Runtime context for DROP TABLES statement.
*/
class Drop_tables_ctx {
public:
Drop_tables_ctx(bool if_exists_arg, bool drop_temporary_arg,
bool drop_database_arg)
: if_exists(if_exists_arg),
drop_temporary(drop_temporary_arg),
drop_database(drop_database_arg),
base_atomic_tables(PSI_INSTRUMENT_ME),
base_non_atomic_tables(PSI_INSTRUMENT_ME),
tmp_trans_tables(PSI_INSTRUMENT_ME),
tmp_trans_tables_to_binlog(PSI_INSTRUMENT_ME),
tmp_non_trans_tables(PSI_INSTRUMENT_ME),
tmp_non_trans_tables_to_binlog(PSI_INSTRUMENT_ME),
nonexistent_tables(PSI_INSTRUMENT_ME),
views(PSI_INSTRUMENT_ME),
dropped_non_atomic(PSI_INSTRUMENT_ME),
gtid_and_table_groups_state(NO_GTID_MANY_TABLE_GROUPS) {
/* DROP DATABASE implies if_exists and absence of drop_temporary. */
assert(!drop_database || (if_exists && !drop_temporary));
}
/* Parameters of DROP TABLES statement. */
const bool if_exists;
const bool drop_temporary;
const bool drop_database;
/* Different table groups of tables to be dropped. */
Prealloced_array<Table_ref *, 1> base_atomic_tables;
Prealloced_array<Table_ref *, 1> base_non_atomic_tables;
Prealloced_array<Table_ref *, 1> tmp_trans_tables;
Prealloced_array<Table_ref *, 1> tmp_trans_tables_to_binlog;
Prealloced_array<Table_ref *, 1> tmp_non_trans_tables;
Prealloced_array<Table_ref *, 1> tmp_non_trans_tables_to_binlog;
Prealloced_array<Table_ref *, 1> nonexistent_tables;
Prealloced_array<Table_ref *, 1> views;
/* Methods which simplify checking state of the above groups. */
bool has_base_atomic_tables() const { return base_atomic_tables.size() != 0; }
bool has_base_non_atomic_tables() const {
return base_non_atomic_tables.size() != 0;
}
bool has_tmp_trans_tables() const { return tmp_trans_tables.size() != 0; }
bool has_tmp_trans_tables_to_binlog() const {
return tmp_trans_tables_to_binlog.size() != 0;
}
bool has_tmp_non_trans_tables() const {
return tmp_non_trans_tables.size() != 0;
}
bool has_tmp_non_trans_tables_to_binlog() const {
return tmp_non_trans_tables_to_binlog.size() != 0;
}
bool has_any_nonexistent_tables() const {
return nonexistent_tables.size() != 0;
}
bool has_base_nonexistent_tables() const {
return !drop_temporary && nonexistent_tables.size() != 0;
}
bool has_tmp_nonexistent_tables() const {
return drop_temporary && nonexistent_tables.size() != 0;
}
bool has_views() const { return views.size() != 0; }
/**
Base tables in SE which do not support atomic DDL which we managed to
drop so far.
*/
Prealloced_array<Table_ref *, 1> dropped_non_atomic;
bool has_dropped_non_atomic() const { return dropped_non_atomic.size() != 0; }
/**
In which situation regarding GTID mode and different types
of tables to be dropped we are.
TODO: consider splitting into 2 orthogonal enum/bools.
*/
enum {
NO_GTID_MANY_TABLE_GROUPS,
NO_GTID_SINGLE_TABLE_GROUP,
GTID_MANY_TABLE_GROUPS,
GTID_SINGLE_TABLE_GROUP
} gtid_and_table_groups_state;
/* Methods to simplify querying the above state. */
bool has_no_gtid_many_table_groups() const {
return gtid_and_table_groups_state == NO_GTID_MANY_TABLE_GROUPS;
}
bool has_no_gtid_single_table_group() const {
return gtid_and_table_groups_state == NO_GTID_SINGLE_TABLE_GROUP;
}
bool has_gtid_many_table_groups() const {
return gtid_and_table_groups_state == GTID_MANY_TABLE_GROUPS;
}
bool has_gtid_single_table_group() const {
return gtid_and_table_groups_state == GTID_SINGLE_TABLE_GROUP;
}
};
/**
Auxiliary function which appends to the string table identifier with proper
quoting and schema part if necessary.
*/
static void append_table_ident(const THD *thd, String *to,
const Table_ref *table, bool force_db) {
// Don't write the database name if it is the current one.
if (thd->db().str == nullptr || strcmp(table->db, thd->db().str) != 0 ||
force_db) {
append_identifier(thd, to, table->db, table->db_length, system_charset_info,
thd->charset());
to->append(".");
}
append_identifier(thd, to, table->table_name, table->table_name_length,
system_charset_info, thd->charset());
}
/**
Auxiliary function which appends to the string schema and table name for
the table (without quoting).
*/
static void append_table_name(String *to, const Table_ref *table) {
to->append(String(table->db, system_charset_info));
to->append('.');
to->append(String(table->table_name, system_charset_info));
}
/**
Auxiliary class which is used to construct synthesized DROP TABLES
statements for the binary log during execution of DROP TABLES statement.
*/
class Drop_tables_query_builder {
public:
Drop_tables_query_builder(THD *thd, bool temporary, bool if_exists,
bool is_trans, bool no_db)
: m_bin_log_is_open(mysql_bin_log.is_open()),
m_thd(thd),
m_is_trans(is_trans),
m_no_db(no_db) {
if (m_bin_log_is_open) {
m_built_query.set_charset(system_charset_info);
m_built_query.append("DROP ");
if (temporary) m_built_query.append("TEMPORARY ");
m_built_query.append("TABLE ");
if (if_exists) m_built_query.append("IF EXISTS ");
}
}
/*
Constructor for the most common case:
- base tables
- write to binlog trx cache
- Database exists
*/
Drop_tables_query_builder(THD *thd, bool if_exists)
: m_bin_log_is_open(mysql_bin_log.is_open()),
m_thd(thd),
m_is_trans(true),
m_no_db(false) {
if (m_bin_log_is_open) {
m_built_query.set_charset(system_charset_info);
m_built_query.append("DROP TABLE ");
if (if_exists) m_built_query.append("IF EXISTS ");
}
}
private:
void add_table_impl(const Table_ref *table) {
append_table_ident(m_thd, &m_built_query, table, m_no_db);
m_built_query.append(",");
m_thd->add_to_binlog_accessed_dbs(table->db);
}
public:
void add_table(const Table_ref *table) {
if (m_bin_log_is_open) add_table_impl(table);
}
void add_array(const Prealloced_array<Table_ref *, 1> &tables) {
if (m_bin_log_is_open) {
for (Table_ref *table : tables) add_table_impl(table);
}
}
bool write_bin_log() {
if (m_bin_log_is_open) {
/* Chop off the last comma */
m_built_query.chop();
m_built_query.append(" /* generated by server */");
/*
We can't use ::write_bin_log() here as this method is sometimes used
in case when DROP TABLES statement is supposed to report an error.
And ::write_bin_log() either resets error in DA or uses it for binlog
event (which we would like to avoid too).
*/
if (m_thd->binlog_query(THD::STMT_QUERY_TYPE, m_built_query.ptr(),
m_built_query.length(), m_is_trans,
false /* direct */, m_no_db /* suppress_use */,
0 /* errcode */))
return true;
}
return false;
}
private:
bool m_bin_log_is_open;
THD *m_thd;
bool m_is_trans;
bool m_no_db;
String m_built_query;
};
/**
Auxiliary function which prepares for DROP TABLES execution by sorting
tables to be dropped into groups according to their types.
*/
static bool rm_table_sort_into_groups(THD *thd, Drop_tables_ctx *drop_ctx,
Table_ref *tables) {
/*
Sort tables into groups according to type of handling they require:
1) Base tables and views. Further divided into the following groups:
a) Base tables in storage engines which don't support atomic DDL.
Their drop can't be rolled back in case of crash or error.
So we drop each such table individually and write to binlog
a single-table DROP TABLE statement corresponding to this
action right after it. This increases chances of SE,
data-dictionary and binary log being in sync if crash occurs.
This also handles case of error/statement being killed in
a natural way - by the time when error occurs we already
have logged all drops which were successful. So we don't
need to write the whole failed statement with error code
to binary log.
b) Base tables in SEs which support atomic DDL.
Their drop can be rolled back, so we drop them in SE, remove
from data-dictionary and write corresponding statement to the
binary log in one atomic transaction all together.
c) Views.
Have to be dropped when this function is called as part of
DROP DATABASE implementation. Dropping them requires
data-dictionary update only, so can be done atomically
with b).
d) Non-existent tables.
In the absence of IF EXISTS clause cause statement failure.
We do this check before dropping any tables to get nice atomic
behavior for most common failure scenario even for tables which
don't support atomic DDL.
When IF EXISTS clause is present notes are generated instead of
error. We assume that non-existing tables support atomic DDL and
write such tables to binary log together with tables from group b)
(after all no-op can be rolled back!) to get a nice single DROP
TABLES statement in the binlog in the default use-case. It is not
a big problem if this assumption turns out to be false on slave.
The statement still will be applied correctly (but crash-safeness
will be sacrificed).
2) Temporary tables.
To avoid problems due to shadowing base tables should be always
binlogged as DROP TEMPORARY TABLE.
Their drop can't be rolled back even for transactional SEs, on the
other hand it can't fail once first simple checks are done. So it
makes sense to drop them after base tables.
Unlike for base tables, it is possible to drop database in which some
connection has temporary tables open. So we can end-up in situation
when connection's default database is no more, but still the connection
has some temporary tables in it. It is possible to drop such tables,
but we should be careful when binlogging such drop.
Using "USE db_which_is_no_more;" before DROP TEMPORARY TABLES will
break replication.
Temporary tables are further divided into the following groups:
a) Temporary tables in non-transactional SE
b) Temporary tables in transactional SE
DROP TEMPORARY TABLES does not commit an ongoing transaction. So in
some circumstances we must binlog changes to non-transactional tables
ahead of transaction, while changes to transactional tables should be
binlogged as part of transaction.
c) Non-existent temporary tables.
Can be non-empty only if DROP TEMPORARY TABLES was used (otherwise
all non-existent tables go to group 1.d)).
Similarly to group 1.d) if IF EXISTS clause is absent causes
statement failure. Otherwise note is generated for each such table.
The non-existing temporary tables are logged together with
transactional ones (group 2.b)), if any transactional tables exist
or if there is only non-existing tables; otherwise are logged
together with non-transactional ones (group 2.a)).
This logic ensures that:
- On master, transactional and non-transactional tables are
written to different statements.
- Therefore, slave will never see statements containing both
transactional and non-transactional temporary tables.
- Since non-existing temporary tables are logged together with
whatever type of temporary tables that exist, the slave thus
writes any statement as just one statement. I.e., the slave
never splits a statement into two. This is crucial when GTIDs
are enabled, since otherwise the statement, which already has
a GTID, would need two different GTIDs.
*/
for (Table_ref *table = tables; table; table = table->next_local) {
/*
Check THD::killed flag, so we can abort potentially lengthy loop.
This can be relevant for DROP DATABASE, for example.
*/
if (thd->killed) return true;
if (table->open_type != OT_BASE_ONLY) {
/* DROP DATABASE doesn't deal with temporary tables. */
assert(!drop_ctx->drop_database);
if (!is_temporary_table(table)) {
// A temporary table was not found.
if (drop_ctx->drop_temporary) {
drop_ctx->nonexistent_tables.push_back(table);
continue;
}
/*
Not DROP TEMPORARY and no matching temporary table.
Continue with base tables.
*/
} else {
/*
A temporary table was found and can be successfully dropped.
The fact that this temporary table is used by an outer statement
should be detected and reported as error earlier.
*/
assert(table->table->query_id == thd->query_id);
if (table->table->file->has_transactions()) {
drop_ctx->tmp_trans_tables.push_back(table);
if (table->table->should_binlog_drop_if_temp())
drop_ctx->tmp_trans_tables_to_binlog.push_back(table);
} else {
drop_ctx->tmp_non_trans_tables.push_back(table);
if (table->table->should_binlog_drop_if_temp())
drop_ctx->tmp_non_trans_tables_to_binlog.push_back(table);
}
continue;
}
}
/* We should not try to drop active log tables. Callers enforce this. */
assert(query_logger.check_if_log_table(table, true) == QUERY_LOG_NONE);
dd::cache::Dictionary_client::Auto_releaser releaser(thd->dd_client());
const dd::Abstract_table *abstract_table_def = nullptr;
if (thd->dd_client()->acquire(table->db, table->table_name,
&abstract_table_def)) {
/* Error should have been reported by data-dictionary subsystem. */
return true;
}
if (!abstract_table_def)
drop_ctx->nonexistent_tables.push_back(table);
else if (abstract_table_def->type() == dd::enum_table_type::BASE_TABLE) {
const dd::Table *table_def =
dynamic_cast<const dd::Table *>(abstract_table_def);
handlerton *hton{nullptr};
if (dd::table_storage_engine(thd, table_def, &hton)) return true;
/*
We don't have SEs which support FKs and don't support atomic DDL.
If we ever to support such engines we need to adjust code that checks
if we can drop parent table to correctly handle such SEs.
*/
assert(!(hton->flags & HTON_SUPPORTS_FOREIGN_KEYS) ||
(hton->flags & HTON_SUPPORTS_ATOMIC_DDL));
if (hton->flags & HTON_SUPPORTS_ATOMIC_DDL || thd->is_plugin_fake_ddl())
drop_ctx->base_atomic_tables.push_back(table);
else
drop_ctx->base_non_atomic_tables.push_back(table);
} else // View
{
if (!drop_ctx->drop_database) {
/*
Historically, DROP TABLES treats situation when we have a view
instead of table to be dropped as non-existent table.
*/
drop_ctx->nonexistent_tables.push_back(table);
} else
drop_ctx->views.push_back(table);
}
}
return false;
}
/**
Auxiliary function which evaluates in which situation DROP TABLES
is regarding GTID and different table groups.
*/
static bool rm_table_eval_gtid_and_table_groups_state(
THD *thd, Drop_tables_ctx *drop_ctx) {
if (thd->variables.gtid_next.type == ASSIGNED_GTID) {
/*
This statement has been assigned GTID.
In this case we need to take special care about group handling
and commits, as statement can't be logged/split into several
statements in this case.
Three different situations are possible in this case:
- "normal" when we have one GTID assigned and one group
to go as single statement to binary logs
- "prohibited" when we have one GTID assigned and two
kinds of temporary tables or mix of temporary and
base tables
- "awkward" when we have one GTID but several groups or
several tables in non-atomic base group (1.a).
*/
if (drop_ctx->drop_database) {
/* DROP DATABASE doesn't drop any temporary tables. */
assert(!drop_ctx->has_tmp_trans_tables());
assert(!drop_ctx->has_tmp_non_trans_tables());
if (!drop_ctx->has_base_non_atomic_tables()) {
/*
Normal case. This is DROP DATABASE and we don't have any tables in
SEs which don't support atomic DDL. Remaining tables, views,
routines and events can be dropped atomically and atomically logged
as a single DROP DATABASE statement by the caller.
*/
drop_ctx->gtid_and_table_groups_state =
Drop_tables_ctx::GTID_SINGLE_TABLE_GROUP;
} else {
/*
Awkward case. We have GTID assigned for DROP DATABASE and it needs
to drop table in SE which doesn't support atomic DDL.
Most probably we are replicating from older (pre-5.8) master or tables
on master and slave have different SEs.
We try to handle situation in the following way - if the whole
statement succeeds caller will log all changes as a single DROP
DATABASE under GTID provided. In case of failure we will emit special
error saying that statement can't be logged correctly and manual
intervention is required.
*/
drop_ctx->gtid_and_table_groups_state =
Drop_tables_ctx::GTID_MANY_TABLE_GROUPS;
}
} else {
/* Only DROP DATABASE drops views. */
assert(!drop_ctx->has_views());
if ((drop_ctx->has_tmp_trans_tables_to_binlog() &&
drop_ctx->has_tmp_non_trans_tables_to_binlog()) ||
((drop_ctx->has_base_non_atomic_tables() ||
drop_ctx->has_base_atomic_tables() ||
drop_ctx->has_base_nonexistent_tables()) &&
(drop_ctx->has_tmp_trans_tables_to_binlog() ||
drop_ctx->has_tmp_non_trans_tables_to_binlog()))) {
/*
Prohibited case. We have either both kinds of temporary tables or
mix of non-temporary and temporary tables.
Normally, such DROP TEMPORARY TABLES or DROP TABLES statements are
written into the binary log at least in two pieces. This is, of
course, impossible with a single GTID assigned.
Executing such statements with a GTID assigned is prohibited at
least since 5.7, so should not create new problems with backward
compatibility and cross-version replication.
(Writing deletion of different kinds of temporary and/or base tables
as single multi-table DROP TABLES under single GTID might be
theoretically possible in some cases, but has its own problems).
*/
my_error(ER_GTID_UNSAFE_BINLOG_SPLITTABLE_STATEMENT_AND_ASSIGNED_GTID,
MYF(0));
return true;
}
if (drop_ctx->base_non_atomic_tables.size() == 1 &&
!drop_ctx->has_base_atomic_tables() &&
!drop_ctx->has_base_nonexistent_tables()) {
/*
Normal case. Single base table in SE which don't support atomic DDL
so it will be logged as a single-table DROP TABLES statement.
Other groups are empty.
*/
assert(!drop_ctx->has_tmp_trans_tables());
assert(!drop_ctx->has_tmp_non_trans_tables());
assert(!drop_ctx->has_tmp_nonexistent_tables());
drop_ctx->gtid_and_table_groups_state =
Drop_tables_ctx::GTID_SINGLE_TABLE_GROUP;
} else if ((drop_ctx->has_base_atomic_tables() ||
drop_ctx->has_base_nonexistent_tables()) &&
!drop_ctx->has_base_non_atomic_tables()) {
/*
Normal case. Several base tables which can be dropped atomically.
Can be logged as one atomic multi-table DROP TABLES statement.
Other groups are empty.
*/
assert(!drop_ctx->has_tmp_trans_tables_to_binlog());
assert(!drop_ctx->has_tmp_non_trans_tables_to_binlog());
drop_ctx->gtid_and_table_groups_state =
Drop_tables_ctx::GTID_SINGLE_TABLE_GROUP;
} else if (drop_ctx->has_tmp_trans_tables() ||
(!drop_ctx->has_tmp_non_trans_tables() &&
drop_ctx->has_tmp_nonexistent_tables())) {
/*
Normal case. Some temporary transactional tables (and/or possibly
some non-existent temporary tables) to be logged as one multi-table
DROP TEMPORARY TABLES statement.
Other groups are empty.
*/
assert(!drop_ctx->has_base_non_atomic_tables());
assert(!drop_ctx->has_base_atomic_tables() &&
!drop_ctx->has_base_nonexistent_tables());
assert(!drop_ctx->has_tmp_non_trans_tables_to_binlog());
drop_ctx->gtid_and_table_groups_state =
Drop_tables_ctx::GTID_SINGLE_TABLE_GROUP;
} else if (drop_ctx->has_tmp_non_trans_tables()) {
/*
Normal case. Some temporary non-transactional tables (and possibly
some non-existent temporary tables) to be logged as one multi-table
DROP TEMPORARY TABLES statement.
Other groups are empty.
*/
assert(!drop_ctx->has_base_non_atomic_tables());
assert(!drop_ctx->has_base_atomic_tables() &&
!drop_ctx->has_base_nonexistent_tables());
assert(!drop_ctx->has_tmp_trans_tables());
drop_ctx->gtid_and_table_groups_state =
Drop_tables_ctx::GTID_SINGLE_TABLE_GROUP;
} else {
/*
Awkward case. We have several tables from non-atomic group 1.a, or
tables from both atomic (1.b, 1.c, 1.d) and non-atomic groups.
Most probably we are replicating from older (pre-5.8) master or tables
on master and slave have different SEs.
We try to handle this situation gracefully by writing single
multi-table DROP TABLES statement including tables from all groups
under GTID provided. Of course this means that we are not crash-safe
in this case. But we can't be fully crash-safe in cases when
non-atomic tables are involved anyway.
Note that temporary tables groups still should be empty in this case.
*/
assert(!drop_ctx->has_tmp_trans_tables());
assert(!drop_ctx->has_tmp_non_trans_tables());
drop_ctx->gtid_and_table_groups_state =
Drop_tables_ctx::GTID_MANY_TABLE_GROUPS;
}
}
} else {
/*
This statement has no GTID assigned. We can handle any mix of
groups in this case. However full atomicity is guaranteed only
in certain scenarios.
*/
if (drop_ctx->drop_database) {
/* DROP DATABASE doesn't drop any temporary tables. */
assert(!drop_ctx->has_tmp_trans_tables());
assert(!drop_ctx->has_tmp_non_trans_tables());
if (!drop_ctx->has_base_non_atomic_tables()) {
/*
Fully atomic case. This is DROP DATABASE and we don't have any
tables in SEs which don't support atomic DDL. Remaining tables,
views, routines and events can be dropped atomically and atomically
logged as a single DROP DATABASE statement by the caller.
*/
drop_ctx->gtid_and_table_groups_state =
Drop_tables_ctx::NO_GTID_SINGLE_TABLE_GROUP;
} else {
/*
Non-atomic case. This is DROP DATABASE which needs to drop some
tables in SE which doesn't support atomic DDL. To improve
crash-safety we log separate DROP TABLE IF EXISTS for each such
table dropped. Remaining tables, views, routines and events are
dropped atomically and atomically logged as a single DROP DATABASE
statement by the caller.
*/
drop_ctx->gtid_and_table_groups_state =
Drop_tables_ctx::NO_GTID_MANY_TABLE_GROUPS;
}
} else {
/* Only DROP DATABASE drops views. */
assert(!drop_ctx->has_views());
if (drop_ctx->base_non_atomic_tables.size() == 1 &&
!drop_ctx->has_base_atomic_tables() &&
!drop_ctx->has_base_nonexistent_tables() &&
!drop_ctx->has_tmp_trans_tables() &&
!drop_ctx->has_tmp_non_trans_tables()) {
/*
Simple non-atomic case. Single base table in SE which don't
support atomic DDL so it will be logged as a single-table
DROP TABLES statement. Other groups are empty.
*/
assert(!drop_ctx->has_tmp_nonexistent_tables());
drop_ctx->gtid_and_table_groups_state =
Drop_tables_ctx::NO_GTID_SINGLE_TABLE_GROUP;
} else if ((drop_ctx->has_base_atomic_tables() ||
drop_ctx->has_base_nonexistent_tables()) &&
!drop_ctx->has_base_non_atomic_tables() &&
!drop_ctx->has_tmp_trans_tables() &&
!drop_ctx->has_tmp_non_trans_tables()) {
/*
Fully atomic case. Several base tables which can be dropped
atomically. Can be logged as one atomic multi-table DROP TABLES
statement. Other groups are empty.
*/
assert(!drop_ctx->has_tmp_nonexistent_tables());
drop_ctx->gtid_and_table_groups_state =
Drop_tables_ctx::NO_GTID_SINGLE_TABLE_GROUP;
} else if (!drop_ctx->has_base_non_atomic_tables() &&
!drop_ctx->has_base_atomic_tables() &&
!drop_ctx->has_base_nonexistent_tables()) {
/* No base tables to be dropped. */
if (drop_ctx->has_tmp_trans_tables() &&
drop_ctx->has_tmp_non_trans_tables()) {
/*
Complex case with temporary tables. We have both transactional
and non-transactional temporary tables and no base tables at all.
We will log separate DROP TEMPORARY TABLES statements for each of
two groups.
*/
drop_ctx->gtid_and_table_groups_state =
Drop_tables_ctx::NO_GTID_MANY_TABLE_GROUPS;
} else {
/*
Simple case with temporary tables. We have either only
transactional or non-transactional temporary tables.
Possibly some non-existent temporary tables.
We can log our statement as a single DROP TEMPORARY TABLES
statement.
*/
assert((drop_ctx->has_tmp_trans_tables() &&
!drop_ctx->has_tmp_non_trans_tables()) ||
(!drop_ctx->has_tmp_trans_tables() &&
drop_ctx->has_tmp_non_trans_tables()) ||
(!drop_ctx->has_tmp_trans_tables() &&
!drop_ctx->has_tmp_non_trans_tables() &&
drop_ctx->has_tmp_nonexistent_tables()));
drop_ctx->gtid_and_table_groups_state =
Drop_tables_ctx::NO_GTID_SINGLE_TABLE_GROUP;
}
} else {
/*
Complex non-atomic case. We have several tables from non-atomic
group 1.a, or tables from both atomic (1.b, 1.c, 1.d) and non-atomic
groups, or mix of base and temporary tables.
Our statement will be written to binary log as several DROP TABLES and
DROP TEMPORARY TABLES statements.
*/
drop_ctx->gtid_and_table_groups_state =
Drop_tables_ctx::NO_GTID_MANY_TABLE_GROUPS;
}
}
}
return false;
}
/**
Check if DROP TABLES or DROP DATABASE statement going to violate
some foreign key constraint by dropping its parent table without
dropping child at the same time.
*/
static bool rm_table_check_fks(THD *thd, Drop_tables_ctx *drop_ctx) {
/*
In FOREIGN_KEY_CHECKS=0 mode it is allowed to drop parent without
dropping child at the same time, so we return early.
In FOREIGN_KEY_CHECKS=1 mode we need to check if we are about to
drop parent table without dropping child table.
*/
if (thd->variables.option_bits & OPTION_NO_FOREIGN_KEY_CHECKS) return false;
// Earlier we assert that only SEs supporting atomic DDL support FKs.
for (Table_ref *table : drop_ctx->base_atomic_tables) {
dd::cache::Dictionary_client::Auto_releaser releaser(thd->dd_client());
const dd::Table *table_def = nullptr;
if (thd->dd_client()->acquire(table->db, table->table_name, &table_def))
return true;
assert(table_def != nullptr);
if (table_def && table_def->hidden() == dd::Abstract_table::HT_HIDDEN_SE) {
my_error(ER_NO_SUCH_TABLE, MYF(0), table->db, table->table_name);
assert(true);
return true;
}
for (const dd::Foreign_key_parent *fk : table_def->foreign_key_parents()) {
if (drop_ctx->drop_database) {
/*
In case of DROP DATABASE list of tables to be dropped can be huge.
We avoid scanning it by assuming that DROP DATABASE will drop all
tables in the database and no tables from other databases.
*/
if (my_strcasecmp(table_alias_charset, fk->child_schema_name().c_str(),
table->db) != 0) {
my_error(ER_FK_CANNOT_DROP_PARENT, MYF(0), table->table_name,
fk->fk_name().c_str(), fk->child_table_name().c_str());
return true;
}
} else {
if (my_strcasecmp(table_alias_charset, fk->child_schema_name().c_str(),
table->db) == 0 &&
my_strcasecmp(table_alias_charset, fk->child_table_name().c_str(),
table->table_name) == 0)
continue;
bool child_dropped = false;
for (Table_ref *dropped : drop_ctx->base_atomic_tables) {
if (my_strcasecmp(table_alias_charset,
fk->child_schema_name().c_str(),
dropped->db) == 0 &&
my_strcasecmp(table_alias_charset, fk->child_table_name().c_str(),
dropped->table_name) == 0) {
child_dropped = true;
break;
}
}
if (!child_dropped) {
my_error(ER_FK_CANNOT_DROP_PARENT, MYF(0), table->table_name,
fk->fk_name().c_str(), fk->child_table_name().c_str());
return true;
}
}
}
}
return false;
}
/**
Update the unique constraint names for FKs which reference table
being dropped.
@param thd Thread handle.
@param parent_table_db Schema name for table being dropped.
@param parent_table_name Name of the table being dropped.
@param parent_table_def dd::Table object representing the dropped table.
@param hton Handlerton for table's storage engine.
@retval operation outcome, false if no error.
*/
static bool adjust_fk_children_for_parent_drop(
THD *thd, const char *parent_table_db, const char *parent_table_name,
const dd::Table *parent_table_def, handlerton *hton [[maybe_unused]]) {
for (const dd::Foreign_key_parent *parent_fk :
parent_table_def->foreign_key_parents()) {
if (my_strcasecmp(table_alias_charset,
parent_fk->child_schema_name().c_str(),
parent_table_db) == 0 &&
my_strcasecmp(table_alias_charset,
parent_fk->child_table_name().c_str(),
parent_table_name) == 0)
continue;
dd::Table *child_table_def = nullptr;
if (thd->dd_client()->acquire_for_modification(
parent_fk->child_schema_name().c_str(),
parent_fk->child_table_name().c_str(), &child_table_def))
return true;
if (child_table_def == nullptr) continue;
for (dd::Foreign_key *fk : *(child_table_def->foreign_keys())) {
if (my_strcasecmp(table_alias_charset,
fk->referenced_table_schema_name().c_str(),
parent_table_db) == 0 &&
my_strcasecmp(table_alias_charset,
fk->referenced_table_name().c_str(),
parent_table_name) == 0) {
// Note: Setting "" is interpreted as NULL.
fk->set_unique_constraint_name("");
}
}
if (thd->dd_client()->update(child_table_def)) return true;
char buff_db[NAME_LEN + 1];
char buff_table[NAME_LEN + 1];
my_stpncpy(buff_db, parent_fk->child_schema_name().c_str(), NAME_LEN);
my_stpncpy(buff_table, parent_fk->child_table_name().c_str(), NAME_LEN);
/*
In lower-case-table-names == 2 mode we store original versions of
table and db names in the data-dictionary. Hence they need to be
lowercased to be used with Table and Table Definition Caches.
*/
if (lower_case_table_names == 2) {
my_casedn_str(system_charset_info, buff_db);
my_casedn_str(system_charset_info, buff_table);
}
mysql_ha_flush_table(thd, buff_db, buff_table);
close_all_tables_for_name(thd, buff_db, buff_table, false);
#ifdef DISABLED_UNTIL_WL9533
/*
TODO: Simply removing entries from InnoDB internal cache breaks
its FK checking logic at the moment. This is to be solved
as part of WL#9533. We might have to replace invalidation
with cache update to do this.Also we might have to postpone
such invalidation/update until statement commit time.
*/
if (hton->dict_cache_reset)
hton->dict_cache_reset(parent_fk->child_schema_name().c_str(),
parent_fk->child_table_name().c_str());
#endif
}
return false;
}
/**
* Validates the ALTER TABLE command with respect to any secondary engine
* operations.
*
* @param alter_info Alter table operations.
* @param create_info Table option changes.
* @param table The table that is being altered.
*
* @return True if invalid, false otherwise.
*/
static bool validate_secondary_engine_option(THD *thd,
const Alter_info &alter_info,
const HA_CREATE_INFO &create_info,
const TABLE &table) {
// Validation necessary only for tables with a secondary engine defined.
if (!table.s->has_secondary_engine()) return false;
// Changing table option is the only valid ALTER TABLE operation.
constexpr uint64_t supported_alter_operations = Alter_info::ALTER_OPTIONS;
// The only table option that may be changed is SECONDARY_ENGINE.
constexpr uint64_t supported_table_options = HA_CREATE_USED_SECONDARY_ENGINE;
// Do not report an error if:
// (a) Current DDL is setting the secondary engine, OR
// (b) Secondary engine supports DDLs
if ((alter_info.flags & ~supported_alter_operations ||
create_info.used_fields & ~supported_table_options) &&
!ha_secondary_engine_supports_ddl(thd, table.s->secondary_engine)) {
my_error(ER_SECONDARY_ENGINE_DDL, MYF(0));
return true;
}
// Secondary engine of a table must be set to NULL before it can be redefined.
if (create_info.secondary_engine.str != nullptr) {
my_error(ER_SECONDARY_ENGINE, MYF(0),
"Table already has a secondary engine defined");
return true;
}
// Check if this statement sets the primary engine. In this case we have to
// reject the DDL.
if ((alter_info.flags & Alter_info::ALTER_OPTIONS) &&
(create_info.used_fields & HA_CREATE_USED_ENGINE)) {
my_error(ER_SECONDARY_ENGINE, MYF(0),
"Cannot change the primary engine of a table with a defined "
"secondary engine");
return true;
}
return false;
}
/**
* Loads a table from its primary engine into its secondary engine.
*
* @note An MDL_EXCLUSIVE lock on the table must have been acquired prior to
* calling this function to ensure that all currently running DML statements
* commit before load begins.
*
* @param thd Thread handler.
* @param table Table in primary storage engine.
*
* @return True if error, false otherwise.
*/
static bool secondary_engine_load_table(THD *thd, const TABLE &table) {
assert(thd->mdl_context.owns_equal_or_stronger_lock(
MDL_key::TABLE, table.s->db.str, table.s->table_name.str, MDL_EXCLUSIVE));
assert(table.s->has_secondary_engine());
// At least one column must be loaded into the secondary engine.
if (bitmap_bits_set(table.read_set) == 0) {
my_error(ER_SECONDARY_ENGINE, MYF(0),
"All columns marked as NOT SECONDARY");
return true;
}
// The defined secondary engine must be the name of a valid storage engine.
plugin_ref plugin =
ha_resolve_by_name(thd, &table.s->secondary_engine, false);
if ((plugin == nullptr) || !plugin_is_ready(table.s->secondary_engine,
MYSQL_STORAGE_ENGINE_PLUGIN)) {
push_warning_printf(
thd, Sql_condition::SL_WARNING, ER_UNKNOWN_STORAGE_ENGINE,
ER_THD(thd, ER_UNKNOWN_STORAGE_ENGINE), table.s->secondary_engine.str);
return false;
}
// The engine must support being used as a secondary engine.
handlerton *hton = plugin_data<handlerton *>(plugin);
if (!(hton->flags & HTON_IS_SECONDARY_ENGINE)) {
my_error(ER_SECONDARY_ENGINE, MYF(0),
"Unsupported secondary storage engine");
return true;
}
// Get handler to the secondary engine into which the table will be loaded.
const bool is_partitioned = table.s->m_part_info != nullptr;
unique_ptr_destroy_only<handler> handler(
get_new_handler(table.s, is_partitioned, thd->mem_root, hton));
DBUG_EXECUTE_IF("before_secondary_engine_load_start", {
const char action[] =
"now SIGNAL before_load_start WAIT_FOR metadata_check_done";
assert(!debug_sync_set_action(thd, STRING_WITH_LEN(action)));
});
// Load table from primary into secondary engine and add to change
// propagation if that is enabled.
return handler->ha_load_table(table);
}
/**
* Unloads a table from its secondary engine.
*
* @note An MDL_EXCLUSIVE or stronger lock on the table must have been acquired
* prior to calling this function to ensure that queries already offloaded to
* the secondary engine finished execution before unloading the table.
*
* @param thd Thread handler.
* @param db_name Database name.
* @param table_name Table name.
* @param table_def Table definition.
* @param error_if_not_loaded If true and the table is not loaded in the
* secondary engine, this function will return an
* error. If false, this function will not return an
* error if the table is not loaded in the secondary
* engine.
*
* @return True if error, false otherwise.
*/
static bool secondary_engine_unload_table(THD *thd, const char *db_name,
const char *table_name,
const dd::Table &table_def,
bool error_if_not_loaded) {
assert(thd->mdl_context.owns_equal_or_stronger_lock(
MDL_key::TABLE, db_name, table_name, MDL_EXCLUSIVE));
// Nothing to unload if table has no secondary engine defined.
LEX_CSTRING secondary_engine;
if (!table_def.options().exists("secondary_engine") ||
table_def.options().get("secondary_engine", &secondary_engine,
thd->mem_root))
return false;
// Get handlerton of secondary engine. It may happen that no handlerton is
// found either if the defined secondary engine is invalid (if so, the table
// was never loaded either) or if the secondary engine has been uninstalled
// after tables were loaded into it (in which case the tables have already
// been unloaded).
plugin_ref plugin = ha_resolve_by_name(thd, &secondary_engine, false);
if ((plugin == nullptr) ||
!plugin_is_ready(secondary_engine, MYSQL_STORAGE_ENGINE_PLUGIN)) {
if (error_if_not_loaded) {
push_warning_printf(
thd, Sql_condition::SL_WARNING, ER_UNKNOWN_STORAGE_ENGINE,
ER_THD(thd, ER_UNKNOWN_STORAGE_ENGINE), secondary_engine.str);
}
return false;
}
handlerton *hton = plugin_data<handlerton *>(plugin);
if (hton == nullptr) {
if (error_if_not_loaded)
my_error(ER_SECONDARY_ENGINE, MYF(0),
"Table is not loaded on a secondary engine");
return error_if_not_loaded;
}
// The defined secondary engine is a valid storage engine. However, if the
// engine is not a valid secondary engine, no tables have been loaded and
// there is nothing to be done.
if (!(hton->flags & HTON_IS_SECONDARY_ENGINE)) return false;
// Get handler for table in secondary engine.
const bool is_partitioned = table_def.partition_type() != dd::Table::PT_NONE;
unique_ptr_destroy_only<handler> handler(
get_new_handler(nullptr, is_partitioned, thd->mem_root, hton));
if (handler == nullptr) return true;
// Unload table from secondary engine.
return handler->ha_unload_table(db_name, table_name, error_if_not_loaded) > 0;
}
/**
Auxiliary function which drops single base table.
@param thd Thread handler.
@param drop_ctx DROP TABLES runtime context.
@param table Table to drop.
@param atomic Indicates whether table to be dropped is in SE
which supports atomic DDL, so changes to the
data-dictionary should not be committed.
@param[in,out] post_ddl_htons Set of handlertons for tables in SEs supporting
atomic DDL for which post-DDL hook needs to
be called after statement commit or rollback.
@param[in,out] fk_invalidator Object keeping track of which dd::Table
objects need to be invalidated since the
correspond to the parent tables for FKs
on a table being dropped.
@param[in,out] safe_to_release_mdl Under LOCK TABLES set of metadata locks
on tables dropped which is safe to
release after DROP operation.
@param foreach_table_root MEM_ROOT which can be used for allocating
objects which lifetime is limited to dropping
of single table.
@sa mysql_rm_table_no_locks().
@retval False - ok
@retval True - error
*/
static bool drop_base_table(THD *thd, const Drop_tables_ctx &drop_ctx,
Table_ref *table, bool atomic,
std::set<handlerton *> *post_ddl_htons,
Foreign_key_parents_invalidator *fk_invalidator,
std::vector<MDL_ticket *> *safe_to_release_mdl,
MEM_ROOT *foreach_table_root) {
char path[FN_REFLEN + 1];
/* Check that we have an exclusive lock on the table to be dropped. */
assert(thd->mdl_context.owns_equal_or_stronger_lock(
MDL_key::TABLE, table->db, table->table_name, MDL_EXCLUSIVE));
/*
Good point to check if we were killed for non-atomic tables group.
All previous tables are dropped both in SE and data-dictionary and
corresponding DROP TABLE statements are written to binary log.
We didn't do anything for the current table yet.
For atomic tables the exact place of this check should not matter.
*/
if (thd->killed) return true;
const dd::Table *table_def = nullptr;
if (thd->dd_client()->acquire(table->db, table->table_name, &table_def))
return true;
assert(table_def != nullptr);
if (table_def && table_def->hidden() == dd::Abstract_table::HT_HIDDEN_SE) {
my_error(ER_NO_SUCH_TABLE, MYF(0), table->db, table->table_name);
assert(true);
return true;
}
// Drop table from secondary engine.
if (secondary_engine_unload_table(thd, table->db, table->table_name,
*table_def, false))
return true; /* purecov: inspected */
handlerton *hton{nullptr};
if (dd::table_storage_engine(thd, table_def, &hton)) {
assert(false);
return true;
}
histograms::results_map results;
bool histogram_error =
histograms::drop_all_histograms(thd, *table, *table_def, results);
DBUG_EXECUTE_IF("fail_after_drop_histograms", {
my_error(ER_UNABLE_TO_DROP_COLUMN_STATISTICS, MYF(0), "dummy_column",
table->db, table->table_name);
histogram_error = true;
});
if (histogram_error) {
/*
Do a rollback request, so that we avoid commit from being called at a
later stage.
*/
thd->transaction_rollback_request = true;
return true;
}
if (thd->locked_tables_mode) {
/*
Under LOCK TABLES we still have table open at this point.
Close it and remove all instances from Table/Table Definition
cache.
Note that we won't try to reopen tables in storage engines
supporting atomic DDL those removal will be later rolled back
thanks to some error. Such situations should be fairly rare.
*/
close_all_tables_for_name(thd, table->db, table->table_name, true);
/*
Find out if it is going to be safe to release MDL after dropping
table under LOCK TABLES. It is not if we are dropping parent and
leave child table around and locked.
*/
bool safe_to_release = true;
if (!table_def->foreign_key_parents().empty()) {
// We don't have SEs which support FKs and not atomic DDL at the moment.
assert(atomic);
for (const dd::Foreign_key_parent *fk :
table_def->foreign_key_parents()) {
if (my_strcasecmp(table_alias_charset, fk->child_schema_name().c_str(),
table->db) == 0 &&
my_strcasecmp(table_alias_charset, fk->child_table_name().c_str(),
table->table_name) == 0)
continue;
bool child_dropped = false;
for (Table_ref *dropped : drop_ctx.base_atomic_tables) {
if (my_strcasecmp(table_alias_charset,
fk->child_schema_name().c_str(),
dropped->db) == 0 &&
my_strcasecmp(table_alias_charset, fk->child_table_name().c_str(),
dropped->table_name) == 0) {
child_dropped = true;
break;
}
}
if (!child_dropped) {
char buff_db[NAME_LEN + 1];
char buff_table[NAME_LEN + 1];
my_stpncpy(buff_db, fk->child_schema_name().c_str(), NAME_LEN);
my_stpncpy(buff_table, fk->child_table_name().c_str(), NAME_LEN);
/*
In lower-case-table-names == 2 mode we store original versions of
table and db names in the data-dictionary. Hence they need to be
lowercased to produce correct MDL key.
*/
if (lower_case_table_names == 2) {
/* purecov: begin inspected */
my_casedn_str(system_charset_info, buff_db);
my_casedn_str(system_charset_info, buff_table);
/* purecov: end */
}
if (thd->mdl_context.owns_equal_or_stronger_lock(
MDL_key::TABLE, buff_db, buff_table,
MDL_SHARED_NO_READ_WRITE)) {
/*
Child is not going to be dropped and locked in mode which
requires foreign key checks. It is not safe to release MDL.
*/
safe_to_release = false;
break;
}
}
}
}
if (safe_to_release)
safe_to_release_mdl->push_back(table->mdl_request.ticket);
} else {
tdc_remove_table(thd, TDC_RT_REMOVE_ALL, table->db, table->table_name,
false);
}
/*
If the table being dropped is a internal temporary table that was
created by ALTER TABLE, we need to mark it as internal tmp table.
This will enable us to build the filename as we build during ALTER
TABLE.
*/
if (table_def->hidden() == dd::Abstract_table::HT_HIDDEN_DDL)
table->internal_tmp_table = true;
(void)build_table_filename(path, sizeof(path) - 1, table->db,
table->table_name, "",
table->internal_tmp_table ? FN_IS_TMP : 0);
/*
Use memory root that is freed right after table processing for allocating
dummy handler object for calling handler::delete_table() in order to avoid
gobbling up memory when lots of tables are deleted.
*/
MEM_ROOT *save_thd_mem_root = thd->mem_root;
thd->mem_root = foreach_table_root;
int error = ha_delete_table(thd, hton, path, table->db, table->table_name,
table_def, !drop_ctx.drop_database);
thd->mem_root = save_thd_mem_root;
/*
Table was present in data-dictionary but is missing in storage engine.
This situation can occur for SEs which don't support atomic DDL due
to crashes. In this case we allow table removal from data-dictionary
and reporting success if IF EXISTS clause was specified.
Such situation should not be possible for SEs supporting atomic DDL,
but we still play safe even in this case and allow table removal.
*/
assert(!atomic || (error != ENOENT && error != HA_ERR_NO_SUCH_TABLE));
if ((error == ENOENT || error == HA_ERR_NO_SUCH_TABLE) &&
drop_ctx.if_exists) {
error = 0;
thd->clear_error();
}
if (atomic && hton->post_ddl) post_ddl_htons->insert(hton);
if (error) {
if (error == HA_ERR_ROW_IS_REFERENCED)
my_error(ER_ROW_IS_REFERENCED, MYF(0));
else if (error == HA_ERR_TOO_MANY_CONCURRENT_TRXS)
my_error(HA_ERR_TOO_MANY_CONCURRENT_TRXS, MYF(0));
else {
String tbl_name;
append_table_name(&tbl_name, table);
my_error(((error == ENOENT || error == HA_ERR_NO_SUCH_TABLE)
? ER_ENGINE_CANT_DROP_MISSING_TABLE
: ER_ENGINE_CANT_DROP_TABLE),
MYF(0), tbl_name.c_ptr());
}
return true;
}
#ifdef HAVE_PSI_SP_INTERFACE
remove_all_triggers_from_perfschema(table->db, *table_def);
#endif
/*
Remove table from data-dictionary and immediately commit this change
if we are removing table in SE which does not support atomic DDL.
This way chances of SE and data-dictionary getting out of sync in
case of crash are reduced.
Things will go bad if we will fail to delete table from data-dictionary
as table is already gone in SE. But this should be really rare situation
(OOM, out of disk space, bugs). Also user can fix it by running DROP TABLE
IF EXISTS on the same table again.
Don't commit the changes if table belongs to SE supporting atomic DDL.
*/
if (adjust_fk_children_for_parent_drop(thd, table->db, table->table_name,
table_def, hton) ||
adjust_fk_parents(thd, table->db, table->table_name, false, nullptr))
return true;
for (const dd::Foreign_key *fk : table_def->foreign_keys()) {
if (my_strcasecmp(table_alias_charset,
fk->referenced_table_schema_name().c_str(),
table->db) == 0 &&
my_strcasecmp(table_alias_charset, fk->referenced_table_name().c_str(),
table->table_name) == 0)
continue;
char buff_db[NAME_LEN + 1];
char buff_table[NAME_LEN + 1];
my_stpncpy(buff_db, fk->referenced_table_schema_name().c_str(), NAME_LEN);
my_stpncpy(buff_table, fk->referenced_table_name().c_str(), NAME_LEN);
/*
In lower-case-table-names == 2 mode we store original versions of table
and db names in the data-dictionary. Hence they need to be lowercased
before being used for TDC invalidation.
*/
if (lower_case_table_names == 2) {
my_casedn_str(system_charset_info, buff_db);
my_casedn_str(system_charset_info, buff_table);
}
// We don't have any SEs which support FKs but do not support atomic DDL.
assert(atomic);
fk_invalidator->add(buff_db, buff_table, hton);
}
dd::Schema_MDL_locker mdl_locker(thd);
if (mdl_locker.ensure_locked(table->db)) return true;
bool result = dd::drop_table(thd, table->db, table->table_name, *table_def);
if (!atomic) result = trans_intermediate_ddl_commit(thd, result);
/*
In DROP DATABASE we can safely skip updating dependent views belonging
to the same database if we know that they will be dropped atomically
with our table.
*/
result |= mark_referencing_views_invalid(thd, table,
(drop_ctx.drop_database && atomic),
!atomic, foreach_table_root);
return result;
}
/**
Execute the drop of a normal or temporary table.
@param thd Thread handler
@param tables Tables to drop
@param if_exists If set, don't give an error if table doesn't exists.
In this case we give an warning of level 'NOTE'
@param drop_temporary Only drop temporary tables
@param drop_database This is DROP DATABASE statement. Drop views
and handle binary logging in a special way.
@param[out] dropped_non_atomic_flag Indicates whether we have dropped some
tables in SEs which don't support atomic
DDL.
@param[out] post_ddl_htons Set of handlertons for tables in SEs supporting
atomic DDL for which post-DDL hook needs to
be called after statement commit or rollback.
@param[out] fk_invalidator Set of parent tables which participate in FKs
together with tables dropped and which entries
in DD cache need to be invalidated as result
of DROP operation.
@param[out] safe_to_release_mdl Under LOCK TABLES set of metadata locks on
tables dropped which is safe to release
after DROP operation.
@retval False - ok
@retval True - error
@note This function assumes that metadata locks have already been taken.
It is also assumed that the tables have been removed from TDC.
@note This function assumes that temporary tables to be dropped have
been pre-opened using corresponding table list elements.
@todo When logging to the binary log, we should log
tmp_tables and transactional tables as separate statements if we
are in a transaction; This is needed to get these tables into the
cached binary log that is only written on COMMIT.
The current code only writes DROP statements that only uses temporary
tables to the cache binary log. This should be ok on most cases, but
not all.
*/
bool mysql_rm_table_no_locks(THD *thd, Table_ref *tables, bool if_exists,
bool drop_temporary, bool drop_database,
bool *dropped_non_atomic_flag,
std::set<handlerton *> *post_ddl_htons,
Foreign_key_parents_invalidator *fk_invalidator,
std::vector<MDL_ticket *> *safe_to_release_mdl) {
dd::cache::Dictionary_client::Auto_releaser releaser(thd->dd_client());
Drop_tables_ctx drop_ctx(if_exists, drop_temporary, drop_database);
std::vector<MDL_ticket *> safe_to_release_mdl_atomic;
bool default_db_doesnt_exist = false;
DBUG_TRACE;
*dropped_non_atomic_flag = false;
if (rm_table_sort_into_groups(thd, &drop_ctx, tables)) return true;
/*
Figure out in which situation we are regarding GTID and different
table groups.
*/
if (rm_table_eval_gtid_and_table_groups_state(thd, &drop_ctx)) return true;
if (!drop_ctx.if_exists && drop_ctx.has_any_nonexistent_tables()) {
/*
No IF EXISTS clause and some non-existing tables.
Fail before dropping any tables. This gives us nice "atomic" (succeed
or don't drop anything) behavior for most common failure scenario even
for tables which don't support atomic DDL.
Do this check after getting full list of missing tables to produce
better error message.
*/
String wrong_tables;
for (Table_ref *table : drop_ctx.nonexistent_tables) {
if (wrong_tables.length()) wrong_tables.append(',');
append_table_name(&wrong_tables, table);
}
my_error(ER_BAD_TABLE_ERROR, MYF(0), wrong_tables.c_ptr());
return true;
}
/* Check if we are about to violate any foreign keys. */
if (rm_table_check_fks(thd, &drop_ctx)) return true;
if (drop_ctx.if_exists && drop_ctx.has_any_nonexistent_tables()) {
for (Table_ref *table : drop_ctx.nonexistent_tables) {
String tbl_name;
append_table_name(&tbl_name, table);
push_warning_printf(thd, Sql_condition::SL_NOTE, ER_BAD_TABLE_ERROR,
ER_THD(thd, ER_BAD_TABLE_ERROR), tbl_name.c_ptr());
}
}
/* Non-existent temporary tables with IF EXISTS do not need any
further processing */
if (drop_ctx.if_exists && drop_ctx.has_tmp_nonexistent_tables()) {
drop_ctx.nonexistent_tables.clear();
/* If such tables were all we had, there is nothing else to do */
if (!drop_ctx.has_base_atomic_tables() &&
!drop_ctx.has_base_non_atomic_tables() &&
!drop_ctx.has_tmp_trans_tables() &&
!drop_ctx.has_tmp_non_trans_tables() && !drop_ctx.has_views()) {
return false;
}
}
/*
Check early if default database exists. We don't want code responsible
for dropping temporary tables fail due to this check after some tables
were dropped already.
*/
if (thd->db().str != nullptr) {
bool exists = false;
if (dd::schema_exists(thd, thd->db().str, &exists)) return true;
default_db_doesnt_exist = !exists;
}
MEM_ROOT foreach_table_root(key_memory_rm_table_foreach_root,
MEM_ROOT_BLOCK_SIZE);
if (drop_ctx.has_base_non_atomic_tables()) {
/*
Handle base tables in storage engines which don't support atomic DDL.
Their drop can't be rolled back in case of crash or error. So we drop
each such table individually and write to binlog a single-table DROP
TABLE statement corresponding to this action right after it.
This increases chances of SE, data-dictionary and binary log being in
sync if crash occurs.
This also handles case of error/statement being killed in a natural
way - by the time when error occurs we already have logged all drops
which were successful. So we don't need to write the whole failed
statement with error code to binary log.
Note that we process non-atomic tables before atomic ones in order to
avoid situations when DROP TABLES for mixed set of tables will fail
and leave changes to atomic, "transactional" tables around.
*/
for (Table_ref *table : drop_ctx.base_non_atomic_tables) {
if (drop_base_table(thd, drop_ctx, table, false /* non-atomic */, nullptr,
nullptr, safe_to_release_mdl, &foreach_table_root))
goto err_with_rollback;
*dropped_non_atomic_flag = true;
drop_ctx.dropped_non_atomic.push_back(table);
if (!drop_ctx.has_gtid_many_table_groups()) {
/*
We don't have GTID assigned, or we have GTID assigned and this is
single-table DROP TABLE for this specific table.
Write single-table DROP TABLE statement to binary log.
Do this even if table was dropped as part of DROP DATABASE statement,
as this descreases chance of things getting out of sync in case of
crash.
*/
if (drop_ctx.drop_database) {
if (mysql_bin_log.is_open()) {
String built_query;
built_query.set_charset(system_charset_info);
built_query.append("DROP TABLE IF EXISTS ");
append_identifier(thd, &built_query, table->table_name,
table->table_name_length, system_charset_info,
thd->charset());
built_query.append(" /* generated by server */");
thd->add_to_binlog_accessed_dbs(table->db);
Query_log_event qinfo(thd, built_query.ptr(), built_query.length(),
false, true, false, 0);
qinfo.db = table->db;
qinfo.db_len = table->db_length;
if (mysql_bin_log.write_event(&qinfo)) goto err_with_rollback;
}
} else {
Drop_tables_query_builder built_query(
thd, false /* no TEMPORARY */, drop_ctx.if_exists,
false /* stmt binlog cache */, false /* db exists */);
built_query.add_table(table);
if (built_query.write_bin_log()) goto err_with_rollback;
}
if (drop_ctx.has_no_gtid_single_table_group() ||
drop_ctx.has_gtid_single_table_group()) {
/*
This was a single-table DROP TABLE for this specific table.
Commit change to binary log and/or mark GTID as executed instead.
In theory, we also can update slave info atomically with binlog/
GTID changes,
*/
if (trans_commit_stmt(thd) || trans_commit_implicit(thd))
goto err_with_rollback;
} else {
/*
We don't have GTID assigned and this is not single-table
DROP TABLE. Commit change to binary log (if there was any)
and get GTID assigned for our single-table change. Do not
release ANONYMOUS_GTID ownership yet as there can be more
tables to drop and corresponding statements to write to
binary log. Do not update slave info as there might be more
groups.
*/
assert(drop_ctx.has_no_gtid_many_table_groups());
thd->is_commit_in_middle_of_statement = true;
bool error = (trans_commit_stmt(thd) || trans_commit_implicit(thd));
thd->is_commit_in_middle_of_statement = false;
if (error) goto err_with_rollback;
}
} else {
/*
We have GTID assigned and several tables from SEs which don't support
atomic DDL, or tables in different groups. Postpone writing to binary
log/marking GTID as executed until all tables are processed.
Nothing to commit here as change to data-dictionary is already
committed earlier.
*/
}
foreach_table_root.ClearForReuse();
}
}
if (drop_ctx.has_base_atomic_tables() || drop_ctx.has_views() ||
drop_ctx.has_base_nonexistent_tables()) {
/*
Handle base tables in SEs which support atomic DDL, as well as views
and non-existent tables.
Drop all these objects in SE and data-dictionary in a single atomic
transaction. Write corresponding multi-table DROP TABLE statement to
the binary log as part of the same transaction.
*/
DEBUG_SYNC(thd, "rm_table_no_locks_before_delete_table");
DBUG_EXECUTE_IF("sleep_before_no_locks_delete_table", my_sleep(100000););
DBUG_EXECUTE_IF("rm_table_no_locks_abort_before_atomic_tables", {
my_error(ER_UNKNOWN_ERROR, MYF(0));
goto err_with_rollback;
});
for (Table_ref *table : drop_ctx.base_atomic_tables) {
if (drop_base_table(thd, drop_ctx, table, true /* atomic */,
post_ddl_htons, fk_invalidator,
&safe_to_release_mdl_atomic, &foreach_table_root)) {
goto err_with_rollback;
}
foreach_table_root.ClearForReuse();
}
DBUG_EXECUTE_IF("rm_table_no_locks_abort_after_atomic_tables", {
my_error(ER_UNKNOWN_ERROR, MYF(0));
goto err_with_rollback;
});
for (Table_ref *table : drop_ctx.views) {
/* Check that we have an exclusive lock on the view to be dropped. */
assert(thd->mdl_context.owns_equal_or_stronger_lock(
MDL_key::TABLE, table->db, table->table_name, MDL_EXCLUSIVE));
tdc_remove_table(thd, TDC_RT_REMOVE_ALL, table->db, table->table_name,
false);
const dd::View *view = nullptr;
if (thd->dd_client()->acquire(table->db, table->table_name, &view))
goto err_with_rollback;
/*
Since we drop views here only if called by DROP DATABASE:
- We can safely skip marking depending views as invalid if they
belong to the same database.
- No need to log anything.
*/
assert(drop_ctx.drop_database);
if (thd->dd_client()->drop(view) ||
mark_referencing_views_invalid(thd, table, true, false,
&foreach_table_root))
goto err_with_rollback;
foreach_table_root.ClearForReuse();
}
#ifndef NDEBUG
for (Table_ref *table : drop_ctx.nonexistent_tables) {
/*
Check that we have an exclusive lock on the table which we were
supposed drop.
*/
assert(thd->mdl_context.owns_equal_or_stronger_lock(
MDL_key::TABLE, table->db, table->table_name, MDL_EXCLUSIVE));
}
#endif
DEBUG_SYNC(thd, "rm_table_no_locks_before_binlog");
int error = 0;
if (drop_ctx.drop_database) {
/*
This is DROP DATABASE.
If we don't have GTID assigned removal of tables from this group will be
logged as DROP DATABASE and committed atomically, together with removal
of events and stored routines, by the caller.
The same thing should happen if we have GTID assigned and tables only
from this group.
If we have GTID assigned and mix of tables from SEs which support atomic
DDL and which don't support it we will still behave in similar way.
If the whole statement succeeds removal of tables from all groups will
be logged as single DROP DATABASE statement. In case of failure we will
report special error, but in addition it makes sense to rollback all
changes to tables in SEs supporting atomic DDL.
So do nothing here in all three cases described above.
*/
} else if (!drop_ctx.has_gtid_many_table_groups()) {
/*
We don't have GTID assigned, or we have GTID assigned and our DROP
TABLES only drops table from this group, so we have fully atomic
multi-table DROP TABLES statement.
If we have not dropped any tables at all (we have only non-existing
tables) we don't have transaction started. We can't use binlog's
trx cache in this case as it requires active transaction with valid
XID.
*/
Drop_tables_query_builder built_query(
thd, false /* no TEMPORARY */, drop_ctx.if_exists,
/* stmt or trx cache. */
drop_ctx.has_base_atomic_tables(), false /* db exists */);
built_query.add_array(drop_ctx.base_atomic_tables);
built_query.add_array(drop_ctx.nonexistent_tables);
thd->thread_specific_used = true;
if (built_query.write_bin_log()) goto err_with_rollback;
if (drop_ctx.has_no_gtid_single_table_group() ||
drop_ctx.has_gtid_single_table_group()) {
/*
This is fully atomic multi-table DROP TABLES.
Commit changes to SEs, data-dictionary and binary log/or
and mark GTID as executed/update slave info tables atomically.
*/
error = (trans_commit_stmt(thd) || trans_commit_implicit(thd));
} else {
/*
We don't have GTID assigned and this is not fully-atomic DROP TABLES.
Commit changes to SE, data-dictionary and binary log and get GTID
assigned for our changes.
Do not release ANONYMOUS_GTID ownership and update slave info yet
as there can be more tables (e.g. temporary) to drop and corresponding
statements to write to binary log.
*/
assert(drop_ctx.has_no_gtid_many_table_groups());
thd->is_commit_in_middle_of_statement = true;
error = (trans_commit_stmt(thd) || trans_commit_implicit(thd));
thd->is_commit_in_middle_of_statement = false;
}
if (!error && thd->locked_tables_mode)
safe_to_release_mdl->insert(safe_to_release_mdl->end(),
safe_to_release_mdl_atomic.begin(),
safe_to_release_mdl_atomic.end());
} else {
/*
We have GTID assigned, some tables from SEs which don't support
atomic DDL and some from SEs which do.
Postpone writing to binary log and marking GTID as executed until
later stage. We also postpone committing removal of tables in SEs
supporting atomic DDL and corresponding changes to the data-
dictionary until the same stage. This allows to minimize change
difference between SEs/data-dictionary and binary log in case of
crash.
If crash occurs binary log won't contain any traces about removal
of tables in both SEs support and not-supporting atomic DDL.
And only tables in SEs not supporting atomic DDL will be missing
from SEs and the data-dictionary. Since removal of tables in SEs
supporting atomic DDL will be rolled back during recovery.
*/
}
if (error) goto err_with_rollback;
}
if (!drop_ctx.drop_database && drop_ctx.has_gtid_many_table_groups()) {
/*
We DROP TABLES statement with GTID assigned and either several tables
from SEs which don't support atomic DDL, or at least one table from
such SE and some tables from SEs which do support atomic DDL.
We have postponed write to binlog earlier. Now it is time to do it.
If we don't have active transaction at this point (i.e. no tables
in SE supporting atomic DDL were dropped) we can't use binlog's trx
cache for this. as it requires active transaction with valid XID.
If we have active transaction (i.e. some tables in SE supporting
atomic DDL were dropped) we have to use trx cache to ensure that
our transaction is properly recovered in case of crash/restart.
*/
Drop_tables_query_builder built_query(
thd, false /* no TEMPORARY */, drop_ctx.if_exists,
/* trx or stmt cache */
drop_ctx.has_base_atomic_tables(), false /* db exists */);
built_query.add_array(drop_ctx.base_non_atomic_tables);
built_query.add_array(drop_ctx.base_atomic_tables);
built_query.add_array(drop_ctx.nonexistent_tables);
if (built_query.write_bin_log()) goto err_with_rollback;
/*
Commit our changes to the binary log (if any) and mark GTID
as executed. This also commits removal of tables in SEs
supporting atomic DDL from SE and the data-dictionary.
In theory, we can update slave info atomically with binlog/GTID
changes here.
*/
if (trans_commit_stmt(thd) || trans_commit_implicit(thd))
goto err_with_rollback;
if (thd->locked_tables_mode)
safe_to_release_mdl->insert(safe_to_release_mdl->end(),
safe_to_release_mdl_atomic.begin(),
safe_to_release_mdl_atomic.end());
}
if (!drop_ctx.drop_database) {
/*
Unless this is DROP DATABASE removal of tables in SEs
supporting foreign keys is already committed at this point.
So we can invalidate cache entries for parent tables.
*/
fk_invalidator->invalidate(thd);
}
/*
Dropping of temporary tables cannot be rolled back. On the other hand it
can't fail at this stage. So to get nice error handling behavior
(either fully succeed or fail and do nothing (if there are no tables
which don't support atomic DDL)) we process such tables after we are
done with base tables.
DROP TEMPORARY TABLES does not commit an ongoing transaction. So in
some circumstances we must binlog changes to non-transactional
ahead of transaction (so we need to tell binlog that these changes
are non-transactional), while changes to transactional tables
should be binlogged as part of transaction.
*/
if (drop_ctx.has_tmp_non_trans_tables()) {
for (auto *table : drop_ctx.tmp_non_trans_tables) {
/*
Don't check THD::killed flag. We can't rollback deletion of
temporary table, so aborting on KILL will make DROP TABLES
less atomic.
OTOH it is unlikely that we have many temporary tables to drop
so being immune to KILL is not that horrible in most cases.
*/
drop_temporary_table(thd, table);
}
thd->get_transaction()->mark_dropped_temp_table(Transaction_ctx::STMT);
}
if (drop_ctx.has_tmp_non_trans_tables_to_binlog()) {
assert(drop_ctx.has_tmp_non_trans_tables());
/*
Handle non-transactional temporary tables.
*/
/* DROP DATABASE doesn't deal with temporary tables. */
assert(!drop_ctx.drop_database);
/*
If default database does not exist, set
'is_drop_tmp_if_exists_with_no_defaultdb flag to 'true',
so that the 'DROP TEMPORARY TABLE IF EXISTS' command is logged
with a fully-qualified table name and we don't write "USE db"
prefix.
*/
const bool is_drop_tmp_if_exists_with_no_defaultdb =
(drop_ctx.if_exists && default_db_doesnt_exist);
Drop_tables_query_builder built_query(
thd, true /* DROP TEMPORARY */, drop_ctx.if_exists,
false /* stmt cache */, is_drop_tmp_if_exists_with_no_defaultdb);
built_query.add_array(drop_ctx.tmp_non_trans_tables_to_binlog);
/*
If there are no transactional temporary tables to be dropped
add non-existent tables to this group. This ensures that on
slave we won't split DROP TEMPORARY TABLES even if some tables
are missing on it (which is no-no for GTID mode).
*/
if (drop_ctx.drop_temporary && !drop_ctx.has_tmp_trans_tables())
built_query.add_array(drop_ctx.nonexistent_tables);
thd->thread_specific_used = true;
if (built_query.write_bin_log()) goto err_with_rollback;
if (!drop_ctx.has_gtid_single_table_group()) {
/*
We don't have GTID assigned. If we are not inside of transaction
commit transaction in binary log to get one for our statement.
*/
if (mysql_bin_log.is_open() && !thd->in_active_multi_stmt_transaction()) {
/*
The single purpose of this hack is to generate GTID for the DROP
TEMPORARY TABLES statement we just have written.
Some notes about it:
*) if the binary log is closed GTIDs are not generated, so there is
no point in the below "commit".
*) thd->in_active_multi_stmt_transaction() is true means that there
is an active transaction with some changes to transactional tables
and in binlog transactional cache. Doing "commit" in such a case
will commit these changes in SE and flush binlog's cache to disk,
so can not be allowed.
OTOH, when thd->in_active_multi_stmt_transaction() false and
thd->in_multi_stmt_transaction_mode() is true there is
transaction from user's point of view. However there were no
changes to transactional tables to commit (all changes were only
to non-transactional tables) and nothing in binlog transactional
cache (all changes to non-transactional tables were written to
binlog directly). Calling "commit" in this case won't do anything
besides generating GTID and can be allowed.
*) We use MYSQL_BIN_LOG::commit() and not trans_commit_implicit(),
for example, because we don't want to end user's explicitly
started transaction.
*) In theory we can allow to update slave info here by not raising
THD::is_commit_in_middle_of_statement flag if we are in
no-GTID-single-group case. However there is little benefit from
it as dropping of temporary tables should not fail.
TODO: Consider if there is some better way to achieve this.
For example, can we use trans_commit_implicit() to split
out temporary parts from DROP TABLES statement or when
splitting DROP TEMPORARY TABLES and there is no explicit
user transaction. And just write two temporary parts
to appropriate caches in case when DROP TEMPORARY is used
inside of user's transaction?
*/
thd->is_commit_in_middle_of_statement = true;
bool error = mysql_bin_log.commit(thd, true);
thd->is_commit_in_middle_of_statement = false;
if (error) goto err_with_rollback;
}
} else {
/*
We have GTID assigned. Rely on commit at the end of statement or
transaction to flush changes to binary log and mark GTID as executed.
*/
}
}
if (drop_ctx.has_tmp_trans_tables()) {
for (auto *table : drop_ctx.tmp_trans_tables) {
/*
Don't check THD::killed flag. We can't rollback deletion of
temporary table, so aborting on KILL will make DROP TABLES
less atomic.
OTOH it is unlikely that we have many temporary tables to drop
so being immune to KILL is not that horrible in most cases.
*/
drop_temporary_table(thd, table);
}
thd->get_transaction()->mark_dropped_temp_table(Transaction_ctx::STMT);
}
if (drop_ctx.has_tmp_trans_tables_to_binlog() ||
(!drop_ctx.has_tmp_non_trans_tables() &&
drop_ctx.has_tmp_nonexistent_tables())) {
/*
Handle transactional temporary tables (and possibly non-existent
temporary tables if they were not handled earlier).
*/
/* DROP DATABASE doesn't deal with temporary tables. */
assert(!drop_ctx.drop_database);
/*
If default database does not exist, set
'is_drop_tmp_if_exists_with_no_defaultdb flag to 'true',
so that the 'DROP TEMPORARY TABLE IF EXISTS' command is logged
with a fully-qualified table name and we don't write "USE db"
prefix.
If we are executing DROP TABLES (without TEMPORARY clause) we
can't use binlog's trx cache, as it requires activetransaction
with valid XID. Luckily, trx cache is not strictly necessary in
this case and DROP TEMPORARY TABLES where it is really needed is
exempted from this rule.
*/
const bool is_drop_tmp_if_exists_with_no_defaultdb =
(drop_ctx.if_exists && default_db_doesnt_exist);
Drop_tables_query_builder built_query(
thd, true /* DROP TEMPORARY */, drop_ctx.if_exists,
drop_ctx.drop_temporary /* trx/stmt cache */,
is_drop_tmp_if_exists_with_no_defaultdb);
built_query.add_array(drop_ctx.tmp_trans_tables_to_binlog);
/*
Add non-existent temporary tables to this group if there are some
and they were not handled earlier.
This ensures that on slave we won't split DROP TEMPORARY TABLES
even if some tables are missing on it (which is no-no for GTID mode).
*/
if (drop_ctx.drop_temporary)
built_query.add_array(drop_ctx.nonexistent_tables);
thd->thread_specific_used = true;
if (built_query.write_bin_log()) goto err_with_rollback;
if (!drop_ctx.has_gtid_single_table_group()) {
/*
We don't have GTID assigned. If we are not inside of transaction
commit transaction in binary log to get one for our statement.
*/
if (mysql_bin_log.is_open() && !thd->in_active_multi_stmt_transaction()) {
/*
See the rationale for the hack with "commit" above.
*/
thd->is_commit_in_middle_of_statement = true;
bool error = mysql_bin_log.commit(thd, true);
thd->is_commit_in_middle_of_statement = false;
if (error) goto err_with_rollback;
}
} else {
/*
We have GTID assigned. Rely on commit at the end of statement or
transaction to flush changes to binary log and mark GTID as executed.
*/
}
}
if (!drop_ctx.drop_database) {
for (handlerton *hton : *post_ddl_htons) hton->post_ddl(thd);
}
return false;
err_with_rollback:
if (!drop_ctx.drop_database) {
/*
Be consistent with successful case. Roll back statement
and call post-DDL hooks within this function.
Note that this will rollback deletion of tables in SEs
supporting atomic DDL only. Tables in engines which
don't support atomic DDL are completely gone at this
point.
*/
if (drop_ctx.has_gtid_many_table_groups() &&
drop_ctx.has_dropped_non_atomic()) {
/*
So far we have been postponing writing DROP TABLES statement for
tables in engines not supporting atomic DDL. We are going to write
it now and let it to consume GTID assigned. Hence rollback of
tables deletion of in SEs supporting atomic DDL should not rollback
GTID. Use guard class to disable this.
*/
Implicit_substatement_state_guard substatement_guard(thd);
trans_rollback_stmt(thd);
/*
Full rollback in case we have THD::transaction_rollback_request
and to synchronize DD state in cache and on disk (as statement
rollback doesn't clear DD cache of modified uncommitted objects).
*/
trans_rollback(thd);
} else {
trans_rollback_stmt(thd);
/*
Full rollback in case we have THD::transaction_rollback_request
and to synchronize DD state in cache and on disk (as statement
rollback doesn't clear DD cache of modified uncommitted objects).
*/
trans_rollback(thd);
}
for (handlerton *hton : *post_ddl_htons) hton->post_ddl(thd);
if (drop_ctx.has_gtid_many_table_groups() &&
drop_ctx.has_dropped_non_atomic()) {
/*
We have some tables dropped in SEs which don't support atomic DDL for
which there were no binlog events written so far. Now we are going to
write DROP TABLES statement for them and mark GTID as executed.
This is not totally correct since original statement is only partially
executed, but is consistent with 5.7 behavior.
TODO: Long-term we probably should generate new slave-based GTID for
this event, or report special error about partial execution.
We don't have active transaction at this point so we can't use binlog's
trx cache for this. It requires active transaction with valid XID.
*/
Drop_tables_query_builder built_query(
thd, false /* no TEMPORARY */, drop_ctx.if_exists,
false /* stmt cache*/, false /* db exists */);
built_query.add_array(drop_ctx.dropped_non_atomic);
(void)built_query.write_bin_log();
// Write statement to binary log and mark GTID as executed.
// We need to turn off updating of slave info
// without conflicting with GTID update.
{
Disable_slave_info_update_guard substatement_guard(thd);
(void)trans_commit_stmt(thd);
(void)trans_commit_implicit(thd);
}
}
}
return true;
}
/**
Quickly remove a table.
@param thd Thread context.
@param base The handlerton handle.
@param db The database name.
@param table_name The table name.
@param flags Flags for build_table_filename().
@note In case when NO_DD_COMMIT flag was used, the caller must rollback
both statement and transaction on failure. This is necessary to
revert results of handler::ha_delete_table() call in case when
update to the data-dictionary which follows it fails. Also this must
be done before any further accesses to DD. @sa dd::drop_table().
@return False in case of success, True otherwise.
*/
bool quick_rm_table(THD *thd, handlerton *base, const char *db,
const char *table_name, uint flags) {
DBUG_TRACE;
// Build the schema qualified table name, to be submitted to the handler.
char path[FN_REFLEN + 1];
(void)build_table_filename(path, sizeof(path) - 1, db, table_name, "", flags);
const dd::Table *table_def = nullptr;
if (thd->dd_client()->acquire(db, table_name, &table_def)) return true;
/* We try to remove non-existing tables in some scenarios. */
if (!table_def) return false;
if (ha_delete_table(thd, base, path, db, table_name, table_def, false))
return true;
// Remove the table object from the data dictionary. If this fails, the
// DD operation is already rolled back, and we must return with an error.
// Note that the DD operation is done after invoking the SE. This is
// because the DDL code will handle situations where a table is present
// in the DD while missing from the SE, but not the opposite.
if (!dd::get_dictionary()->is_dd_table_name(db, table_name)) {
bool result = dd::drop_table(thd, db, table_name, *table_def);
if (!(flags & NO_DD_COMMIT))
result = trans_intermediate_ddl_commit(thd, result);
if (result) {
assert(thd->is_error() || thd->killed);
return true;
}
}
return false;
}
/*
Sort keys according to the following properties, in decreasing order of
importance:
- PRIMARY KEY
- UNIQUE with all columns NOT NULL
- UNIQUE without partial segments
- UNIQUE
- without fulltext columns
- without virtual generated columns
This allows us to
- check for duplicate key values faster (PK and UNIQUE are first)
- prioritize PKs
- be sure that, if there is no PK, the set of UNIQUE keys candidate for
promotion starts at number 0, and we can choose #0 as PK (it is required
that PK has number 0).
*/
namespace {
struct sort_keys {
bool operator()(const KEY &a, const KEY &b) const {
// std::sort may compare an element to itself:
if (&a == &b) return false;
// Sort UNIQUE before not UNIQUE.
if ((a.flags ^ b.flags) & HA_NOSAME) return a.flags & HA_NOSAME;
if (a.flags & HA_NOSAME) {
// Sort UNIQUE NOT NULL keys before other UNIQUE keys.
if ((a.flags ^ b.flags) & HA_NULL_PART_KEY)
return b.flags & HA_NULL_PART_KEY;
// Sort PRIMARY KEY before other UNIQUE NOT NULL.
if (a.name == primary_key_name) return true;
if (b.name == primary_key_name) return false;
// Sort keys don't containing partial segments before others.
if ((a.flags ^ b.flags) & HA_KEY_HAS_PART_KEY_SEG)
return b.flags & HA_KEY_HAS_PART_KEY_SEG;
}
if ((a.flags ^ b.flags) & HA_FULLTEXT) return b.flags & HA_FULLTEXT;
if ((a.flags ^ b.flags) & HA_VIRTUAL_GEN_KEY)
return b.flags & HA_VIRTUAL_GEN_KEY;
/*
Prefer original key order. usable_key_parts contains here
the original key position.
*/
return a.usable_key_parts < b.usable_key_parts;
}
};
} // namespace
/*
Check TYPELIB (set or enum) for duplicates
SYNOPSIS
check_duplicates_in_interval()
thd Thread handle
set_or_name "SET" or "ENUM" string for warning message
name name of the checked column
typelib list of values for the column
dup_val_count returns count of duplicate elements
DESCRIPTION
This function prints an warning for each value in list
which has some duplicates on its right
RETURN VALUES
0 ok
1 Error
*/
static bool check_duplicates_in_interval(THD *thd, const char *set_or_name,
const char *name, TYPELIB *typelib,
const CHARSET_INFO *cs,
uint *dup_val_count) {
TYPELIB tmp = *typelib;
const char **cur_value = typelib->type_names;
unsigned int *cur_length = typelib->type_lengths;
*dup_val_count = 0;
for (; tmp.count > 1; cur_value++, cur_length++) {
tmp.type_names++;
tmp.type_lengths++;
tmp.count--;
if (find_type2(&tmp, *cur_value, *cur_length, cs)) {
ErrConvString err(*cur_value, *cur_length, cs);
if (thd->is_strict_mode()) {
my_error(ER_DUPLICATED_VALUE_IN_TYPE, MYF(0), name, err.ptr(),
set_or_name);
return true;
}
push_warning_printf(thd, Sql_condition::SL_NOTE,
ER_DUPLICATED_VALUE_IN_TYPE,
ER_THD(thd, ER_DUPLICATED_VALUE_IN_TYPE), name,
err.ptr(), set_or_name);
(*dup_val_count)++;
}
}
return false;
}
/**
Prepare a create_table instance for packing
@param thd Thread handle
@param [in,out] sql_field field to prepare for packing
@param table_flags table flags
@return true if error, false if ok
*/
bool prepare_pack_create_field(THD *thd, Create_field *sql_field,
longlong table_flags) {
unsigned int dup_val_count;
DBUG_TRACE;
assert(sql_field->charset);
sql_field->is_nullable = true;
sql_field->is_zerofill = false;
sql_field->is_unsigned = false;
switch (sql_field->sql_type) {
case MYSQL_TYPE_GEOMETRY:
if (!(table_flags & HA_CAN_GEOMETRY)) {
my_error(ER_CHECK_NOT_IMPLEMENTED, MYF(0), "GEOMETRY");
return true;
}
[[fallthrough]];
case MYSQL_TYPE_BLOB:
case MYSQL_TYPE_MEDIUM_BLOB:
case MYSQL_TYPE_TINY_BLOB:
case MYSQL_TYPE_LONG_BLOB:
case MYSQL_TYPE_JSON:
assert(sql_field->auto_flags == Field::NONE ||
sql_field->auto_flags == Field::GENERATED_FROM_EXPRESSION);
break;
case MYSQL_TYPE_VARCHAR:
if (table_flags & HA_NO_VARCHAR) {
/* Convert VARCHAR to CHAR because handler is not yet up to date */
sql_field->sql_type = MYSQL_TYPE_VAR_STRING;
if (sql_field->max_display_width_in_codepoints() >
MAX_FIELD_CHARLENGTH) {
my_error(ER_TOO_BIG_FIELDLENGTH, MYF(0), sql_field->field_name,
static_cast<ulong>(MAX_FIELD_CHARLENGTH));
return true;
}
}
break;
case MYSQL_TYPE_STRING:
break;
case MYSQL_TYPE_ENUM:
assert(sql_field->auto_flags == Field::NONE ||
sql_field->auto_flags == Field::GENERATED_FROM_EXPRESSION);
if (check_duplicates_in_interval(thd, "ENUM", sql_field->field_name,
sql_field->interval, sql_field->charset,
&dup_val_count))
return true;
if (sql_field->interval->count > MAX_ENUM_VALUES) {
my_error(ER_TOO_BIG_ENUM, MYF(0), sql_field->field_name);
return true;
}
break;
case MYSQL_TYPE_SET:
assert(sql_field->auto_flags == Field::NONE ||
sql_field->auto_flags == Field::GENERATED_FROM_EXPRESSION);
if (check_duplicates_in_interval(thd, "SET", sql_field->field_name,
sql_field->interval, sql_field->charset,
&dup_val_count))
return true;
/* Check that count of unique members is not more then 64 */
if (sql_field->interval->count - dup_val_count > sizeof(longlong) * 8) {
my_error(ER_TOO_BIG_SET, MYF(0), sql_field->field_name);
return true;
}
break;
case MYSQL_TYPE_DATE: // Rest of string types
case MYSQL_TYPE_NEWDATE:
case MYSQL_TYPE_TIME:
case MYSQL_TYPE_DATETIME:
case MYSQL_TYPE_TIME2:
case MYSQL_TYPE_DATETIME2:
case MYSQL_TYPE_NULL:
case MYSQL_TYPE_BIT:
break;
case MYSQL_TYPE_TIMESTAMP:
case MYSQL_TYPE_TIMESTAMP2:
case MYSQL_TYPE_NEWDECIMAL:
default:
if (sql_field->flags & ZEROFILL_FLAG) sql_field->is_zerofill = true;
if (sql_field->flags & UNSIGNED_FLAG) sql_field->is_unsigned = true;
break;
}
if (sql_field->flags & NOT_NULL_FLAG) sql_field->is_nullable = false;
// Array fields are JSON fields, so override pack length
sql_field->pack_length_override =
sql_field->is_array ? (4 + portable_sizeof_char_ptr) : 0;
return false;
}
TYPELIB *create_typelib(MEM_ROOT *mem_root, Create_field *field_def) {
if (!field_def->interval_list.elements) return nullptr;
TYPELIB *result =
reinterpret_cast<TYPELIB *>(mem_root->Alloc(sizeof(TYPELIB)));
if (!result) return nullptr;
result->count = field_def->interval_list.elements;
result->name = "";
// Allocate type_names and type_lengths as one block.
size_t nbytes = (sizeof(char *) + sizeof(uint)) * (result->count + 1);
if (!(result->type_names =
reinterpret_cast<const char **>(mem_root->Alloc(nbytes))))
return nullptr;
result->type_lengths =
reinterpret_cast<uint *>(result->type_names + result->count + 1);
List_iterator<String> it(field_def->interval_list);
for (uint i = 0; i < result->count; i++) {
size_t dummy;
String *tmp = it++;
if (String::needs_conversion(tmp->length(), tmp->charset(),
field_def->charset, &dummy)) {
uint cnv_errs;
String conv;
conv.copy(tmp->ptr(), tmp->length(), tmp->charset(), field_def->charset,
&cnv_errs);
result->type_names[i] = strmake_root(mem_root, conv.ptr(), conv.length());
result->type_lengths[i] = conv.length();
} else {
result->type_names[i] = tmp->ptr();
result->type_lengths[i] = tmp->length();
}
// Strip trailing spaces.
size_t length = field_def->charset->cset->lengthsp(
field_def->charset, result->type_names[i], result->type_lengths[i]);
result->type_lengths[i] = length;
(const_cast<char *>(result->type_names[i]))[length] = '\0';
}
result->type_names[result->count] = nullptr; // End marker (char*)
result->type_lengths[result->count] = 0; // End marker (uint)
field_def->interval_list.clear(); // Don't need interval_list anymore
return result;
}
/**
Prepare an instance of Create_field for field creation
(fill all necessary attributes). Only used for stored programs.
@param[in] thd Thread handle
@param[out] field_def An instance of initialized create_field
@return Error status.
*/
bool prepare_sp_create_field(THD *thd, Create_field *field_def) {
if (field_def->sql_type == MYSQL_TYPE_SET) {
if (prepare_set_field(thd, field_def)) return true;
} else if (field_def->sql_type == MYSQL_TYPE_ENUM) {
if (prepare_enum_field(thd, field_def)) return true;
} else if (field_def->sql_type == MYSQL_TYPE_BIT)
field_def->treat_bit_as_char = true;
if (prepare_blob_field(thd, field_def, false)) return true;
return prepare_pack_create_field(thd, field_def, HA_CAN_GEOMETRY);
}
/**
Get the character set from field object generated by the parser, using
default values when not set.
@param sql_field The sql_field object
@param create_info Info generated by parser
@return character set
*/
const CHARSET_INFO *get_sql_field_charset(const Create_field *sql_field,
const HA_CREATE_INFO *create_info) {
const CHARSET_INFO *cs = sql_field->charset != nullptr
? sql_field->charset
: create_info->default_table_charset;
/*
The hidden ARRAY typed column that backs the multi-valued index, and is
implemented as a JSON column, can only use the character sets
my_charset_utf8mb4_0900_bin or binary. This column's charset should not
be changed when altering the table_charset.
(See Field_typed_array for more details).
Also table_charset must not affect the BLOB fields, so don't allow to change
my_charset_bin to something else.
*/
if (sql_field->is_array || cs == &my_charset_bin) return cs;
/*
table_charset is set only in ALTER TABLE t1 CONVERT TO CHARACTER SET csname
when we want to change character set for all varchar/char columns.
*/
if (create_info->table_charset != nullptr) return create_info->table_charset;
return cs;
}
/**
Modifies the first column definition whose SQL type is TIMESTAMP
by adding the features DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP.
@param column_definitions The list of column definitions, in the physical
order in which they appear in the table.
*/
void promote_first_timestamp_column(List<Create_field> *column_definitions) {
List_iterator<Create_field> it(*column_definitions);
Create_field *column_definition;
while ((column_definition = it++) != nullptr) {
if (column_definition->sql_type == MYSQL_TYPE_TIMESTAMP || // TIMESTAMP
column_definition->sql_type == MYSQL_TYPE_TIMESTAMP2) // ms TIMESTAMP
{
if ((column_definition->flags & NOT_NULL_FLAG) != 0 && // NOT NULL,
column_definition->constant_default ==
nullptr && // no constant default
column_definition->gcol_info == nullptr && // not a generated column
column_definition->auto_flags == Field::NONE) // no function default
{
DBUG_PRINT("info", ("First TIMESTAMP column '%s' was promoted to "
"DEFAULT CURRENT_TIMESTAMP ON UPDATE "
"CURRENT_TIMESTAMP",
column_definition->field_name));
column_definition->auto_flags =
Field::DEFAULT_NOW | Field::ON_UPDATE_NOW;
}
return;
}
}
}
/**
Check if there is a duplicate key. Report a warning for every duplicate key.
@param thd Thread context.
@param error_schema_name Schema name of the table used for error reporting.
@param error_table_name Table name used for error reporting.
@param key Key to be checked.
@param key_info Array with all keys for the table.
@param key_count Number of keys in the table.
@param alter_info Alter_info structure describing ALTER TABLE.
@note Unlike has_index_def_changed() and similar code in
mysql_compare_tables() this function compares KEY objects for the same
table/created by the same mysql_prepare_create(). Hence difference in
field number comparison. We also differentiate UNIQUE and PRIMARY keys.
@retval false Ok.
@retval true Error.
*/
static bool check_duplicate_key(THD *thd, const char *error_schema_name,
const char *error_table_name, const KEY *key,
const KEY *key_info, uint key_count,
Alter_info *alter_info) {
const KEY *k;
const KEY *k_end = key_info + key_count;
/* This function should not be called for PRIMARY or generated keys. */
assert(key->name != primary_key_name && !(key->flags & HA_GENERATED_KEY));
for (k = key_info; k != k_end; k++) {
// Looking for a similar key...
if (k == key) {
/*
Since the duplicate index might exist before or after
the modified key in the list, we continue the
comparison with rest of the keys in case of DROP COLUMN
operation.
*/
if (alter_info->flags & Alter_info::ALTER_DROP_COLUMN)
continue;
else
break;
}
/*
Treat key as not duplicate if:
- it is generated (as it will be automagically removed if duplicate later)
- has different type (Instead of differentiating between PRIMARY and
UNIQUE keys we simply skip check for PRIMARY keys. The fact that we
have only one primary key for the table is checked elsewhere.)
- has different algorithm
- has different number of key parts
*/
if ((k->flags & HA_GENERATED_KEY) ||
((key->flags & HA_KEYFLAG_MASK) != (k->flags & HA_KEYFLAG_MASK)) ||
(k->name == primary_key_name) || (key->algorithm != k->algorithm) ||
(key->user_defined_key_parts != k->user_defined_key_parts)) {
// Keys are different.
continue;
}
/*
Keys 'key' and 'k' might be identical.
Check that the keys have identical columns in the same order.
*/
const KEY_PART_INFO *key_part;
const KEY_PART_INFO *key_part_end =
key->key_part + key->user_defined_key_parts;
const KEY_PART_INFO *k_part;
bool all_columns_are_identical = true;
for (key_part = key->key_part, k_part = k->key_part;
key_part < key_part_end; key_part++, k_part++) {
/*
Key definition is different if we are using a different field,
if the used key part length is different or key parts has different
direction. Note since both KEY objects come from
mysql_prepare_create_table() we can compare field numbers directly.
*/
if ((key_part->length != k_part->length) ||
(key_part->fieldnr != k_part->fieldnr) ||
(key_part->key_part_flag != k_part->key_part_flag)) {
all_columns_are_identical = false;
break;
}
}
// Report a warning if we have two identical keys.
if (all_columns_are_identical) {
push_warning_printf(thd, Sql_condition::SL_WARNING, ER_DUP_INDEX,
ER_THD(thd, ER_DUP_INDEX), key->name,
error_schema_name, error_table_name);
if (thd->is_error()) {
// An error was reported.
return true;
}
break;
}
}
return false;
}
/**
Scan the indexes of the new table (including the added ones), and check
if the field is referred by any index.
@param field Field in old table.
@param new_field Field in new table (create field).
@param ha_alter_info Alter inplace info structure.
@retval true Field changes collation, and is indexed.
@retval false Otherwise.
*/
static bool is_field_part_of_index(const Field &field [[maybe_unused]],
const Create_field &new_field,
Alter_inplace_info *ha_alter_info) {
assert(new_field.field == &field);
const KEY *new_key_end =
ha_alter_info->key_info_buffer + ha_alter_info->key_count;
for (const KEY *new_key = ha_alter_info->key_info_buffer;
new_key < new_key_end; new_key++) {
/*
If the key of the new table has a part which referring to the create
field submitted, then mark this as a change of the stored column type.
This will prohibit performing this as an inplace operation.
*/
const KEY_PART_INFO *end =
new_key->key_part + new_key->user_defined_key_parts;
for (const KEY_PART_INFO *new_part = new_key->key_part; new_part < end;
new_part++) {
if (get_field_by_index(ha_alter_info->alter_info, new_part->fieldnr) ==
&new_field)
return true;
}
}
return false;
}
/**
Scan the fields used in partition expressions of the new table (including
the added ones), and check if the field is used by a partitioning
expression.
*/
static bool is_field_part_of_partition_expression(
const Field &field, Alter_inplace_info *ha_alter_info) {
if (ha_alter_info->modified_part_info == nullptr) return false;
for (Field **ptr = ha_alter_info->modified_part_info->full_part_field_array;
*ptr; ptr++) {
if (*ptr == &field) return true;
assert((*ptr)->field_index() != field.field_index());
}
return false;
}
/**
Helper function which allows to detect column types for which we historically
used key packing (optimization implemented only by MyISAM) under erroneous
assumption that they have BLOB type.
*/
static bool is_phony_blob(enum_field_types sql_type, uint decimals) {
const uint FIELDFLAG_BLOB = 1024;
const uint FIELDFLAG_DEC_SHIFT = 8;
return (sql_type == MYSQL_TYPE_NEWDECIMAL || sql_type == MYSQL_TYPE_DOUBLE ||
sql_type == MYSQL_TYPE_DECIMAL) &&
(((decimals << FIELDFLAG_DEC_SHIFT) & FIELDFLAG_BLOB) != 0);
}
static bool prepare_set_field(THD *thd, Create_field *sql_field) {
DBUG_TRACE;
assert(sql_field->sql_type == MYSQL_TYPE_SET);
/*
Create typelib from interval_list, and if necessary
convert strings from client character set to the
column character set.
*/
if (!sql_field->interval) {
/*
Create the typelib in runtime memory - we will free the
occupied memory at the same time when we free this
sql_field -- at the end of execution.
*/
sql_field->interval = create_typelib(thd->mem_root, sql_field);
}
// Comma is an invalid character for SET names
char comma_buf[4]; /* 4 bytes for utf32 */
int comma_length = sql_field->charset->cset->wc_mb(
sql_field->charset, ',', reinterpret_cast<uchar *>(comma_buf),
reinterpret_cast<uchar *>(comma_buf) + sizeof(comma_buf));
assert(comma_length > 0);
for (uint i = 0; i < sql_field->interval->count; i++) {
if (sql_field->charset->coll->strstr(sql_field->charset,
sql_field->interval->type_names[i],
sql_field->interval->type_lengths[i],
comma_buf, comma_length, nullptr, 0)) {
ErrConvString err(sql_field->interval->type_names[i],
sql_field->interval->type_lengths[i],
sql_field->charset);
my_error(ER_ILLEGAL_VALUE_FOR_TYPE, MYF(0), "set", err.ptr());
return true;
}
}
if (sql_field->constant_default != nullptr) {
const char *not_used;
uint not_used2;
bool not_found = false;
String str;
String *def = sql_field->constant_default->val_str(&str);
if (def == nullptr) /* SQL "NULL" maps to NULL */
{
if ((sql_field->flags & NOT_NULL_FLAG) != 0) {
my_error(ER_INVALID_DEFAULT, MYF(0), sql_field->field_name);
return true;
}
/* else, NULL is an allowed value */
(void)find_set(sql_field->interval, nullptr, 0, sql_field->charset,
¬_used, ¬_used2, ¬_found);
} else /* not NULL */
{
(void)find_set(sql_field->interval, def->ptr(), def->length(),
sql_field->charset, ¬_used, ¬_used2, ¬_found);
}
if (not_found) {
my_error(ER_INVALID_DEFAULT, MYF(0), sql_field->field_name);
return true;
}
}
return false;
}
static bool prepare_enum_field(THD *thd, Create_field *sql_field) {
DBUG_TRACE;
assert(sql_field->sql_type == MYSQL_TYPE_ENUM);
/*
Create typelib from interval_list, and if necessary
convert strings from client character set to the
column character set.
*/
if (!sql_field->interval) {
/*
Create the typelib in runtime memory - we will free the
occupied memory at the same time when we free this
sql_field -- at the end of execution.
*/
sql_field->interval = create_typelib(thd->mem_root, sql_field);
}
if (sql_field->constant_default != nullptr) {
String str;
String *def = sql_field->constant_default->val_str(&str);
if (def == nullptr) /* SQL "NULL" maps to NULL */
{
if ((sql_field->flags & NOT_NULL_FLAG) != 0) {
my_error(ER_INVALID_DEFAULT, MYF(0), sql_field->field_name);
return true;
}
/* else, the defaults yield the correct length for NULLs. */
} else /* not NULL */
{
def->length(sql_field->charset->cset->lengthsp(
sql_field->charset, def->ptr(), def->length()));
if (find_type2(sql_field->interval, def->ptr(), def->length(),
sql_field->charset) == 0) /* not found */
{
my_error(ER_INVALID_DEFAULT, MYF(0), sql_field->field_name);
return true;
}
}
}
return false;
}
bool prepare_create_field(THD *thd, const char *error_schema_name,
const char *error_table_name,
HA_CREATE_INFO *create_info,
List<Create_field> *create_list,
int *select_field_pos, handler *file,
Create_field *sql_field, int field_no) {
DBUG_TRACE;
assert(create_list);
const CHARSET_INFO *save_cs;
/* Set field charset. */
save_cs = sql_field->charset = get_sql_field_charset(sql_field, create_info);
if (sql_field->flags & BINCMP_FLAG) {
// e.g. CREATE TABLE t1 (a CHAR(1) BINARY);
if (!(sql_field->charset = get_charset_by_csname(sql_field->charset->csname,
MY_CS_BINSORT, MYF(0)))) {
char tmp[65];
strmake(strmake(tmp, save_cs->csname, sizeof(tmp) - 4),
STRING_WITH_LEN("_bin"));
my_error(ER_UNKNOWN_COLLATION, MYF(0), tmp);
return true;
}
/*
Now that we have sql_field->charset set properly,
we don't need the BINCMP_FLAG any longer.
*/
sql_field->flags &= ~BINCMP_FLAG;
}
/*
Convert the default value from client character
set into the column character set if necessary.
*/
if (sql_field->constant_default &&
save_cs != sql_field->constant_default->collation.collation &&
(sql_field->sql_type == MYSQL_TYPE_VAR_STRING ||
sql_field->sql_type == MYSQL_TYPE_STRING ||
sql_field->sql_type == MYSQL_TYPE_SET ||
sql_field->sql_type == MYSQL_TYPE_ENUM)) {
/*
Starting from 5.1 we work here with a copy of Create_field
created by the caller, not with the instance that was
originally created during parsing. It's OK to create
a temporary item and initialize with it a member of the
copy -- this item will be thrown away along with the copy
at the end of execution, and thus not introduce a dangling
pointer in the parsed tree of a prepared statement or a
stored procedure statement.
*/
sql_field->constant_default =
sql_field->constant_default->safe_charset_converter(thd, save_cs);
if (sql_field->constant_default == nullptr) {
/* Could not convert */
my_error(ER_INVALID_DEFAULT, MYF(0), sql_field->field_name);
return true;
}
}
if (sql_field->sql_type == MYSQL_TYPE_SET) {
if (prepare_set_field(thd, sql_field)) return true;
} else if (sql_field->sql_type == MYSQL_TYPE_ENUM) {
if (prepare_enum_field(thd, sql_field)) return true;
} else if (sql_field->sql_type == MYSQL_TYPE_BIT) {
if (file->ha_table_flags() & HA_CAN_BIT_FIELD) {
create_info->null_bits +=
sql_field->max_display_width_in_codepoints() & 7;
sql_field->treat_bit_as_char = false;
} else
sql_field->treat_bit_as_char = true;
}
bool convert_to_character_set =
(create_info->used_fields & HA_CREATE_USED_CHARSET);
if (prepare_blob_field(thd, sql_field, convert_to_character_set)) {
return true;
}
if (!(sql_field->flags & NOT_NULL_FLAG)) create_info->null_bits++;
if (check_column_name(to_lex_cstring(sql_field->field_name))) {
my_error(ER_WRONG_COLUMN_NAME, MYF(0), sql_field->field_name);
return true;
}
// Validate field comment string
std::string invalid_sub_str;
if (is_invalid_string(
LEX_CSTRING{sql_field->comment.str, sql_field->comment.length},
system_charset_info, invalid_sub_str)) {
// Provide contextual information
std::string qualified_field_name = std::string(error_schema_name) + "." +
std::string(error_table_name) + "." +
std::string(sql_field->field_name);
my_error(ER_COMMENT_CONTAINS_INVALID_STRING, MYF(0), "field",
qualified_field_name.c_str(), system_charset_info->csname,
invalid_sub_str.c_str());
return true;
}
if (validate_comment_length(thd, sql_field->comment.str,
&sql_field->comment.length, COLUMN_COMMENT_MAXLEN,
ER_TOO_LONG_FIELD_COMMENT, sql_field->field_name))
return true;
// If this column has an SRID specified, check if the SRID actually exists
// in the data dictionary.
if (sql_field->m_srid.has_value() && sql_field->m_srid.value() != 0) {
bool exists = false;
if (Srs_fetcher::srs_exists(thd, sql_field->m_srid.value(), &exists)) {
// An error has already been raised
return true; /* purecov: deadcode */
}
if (!exists) {
my_error(ER_SRS_NOT_FOUND, MYF(0), sql_field->m_srid.value());
return true;
}
}
/* Check if we have used the same field name before */
Create_field *dup_field;
List_iterator<Create_field> it(*create_list);
for (int dup_no = 0; (dup_field = it++) != sql_field; dup_no++) {
if (my_strcasecmp(system_charset_info, sql_field->field_name,
dup_field->field_name) == 0) {
/*
If this was a CREATE ... SELECT statement, accept a field
redefinition if we are changing a field in the SELECT part
*/
if (field_no < (*select_field_pos) || dup_no >= (*select_field_pos)) {
// If one of the columns is a functional index column, but not both,
// return an error saying that the column name is in use. The reason we
// only raise an error if one, but not both, is a functional index
// column, is that we want to report a "duplicate key name"-error if the
// user renames a functional index to an existing functional index name:
//
// CREATE TABLE t1 (
// col1 INT
// , INDEX idx ((col1 + 1))
// , INDEX idx2 ((col1 + 2)));
//
// ALTER TABLE t1 RENAME INDEX idx TO idx2;
//
// Note that duplicate names for regular indexes are detected later, so
// we don't bother checking those here.
if ((is_field_for_functional_index(dup_field) !=
is_field_for_functional_index(sql_field))) {
std::string error_description;
error_description.append("The column name '");
error_description.append(sql_field->field_name);
error_description.append("' is already in use by a hidden column");
my_error(ER_INTERNAL_ERROR, MYF(0), error_description.c_str());
return true;
}
if (!is_field_for_functional_index(dup_field) &&
!is_field_for_functional_index(sql_field)) {
my_error(ER_DUP_FIELDNAME, MYF(0), sql_field->field_name);
return true;
}
} else {
/* Field redefined */
/*
If we are replacing a BIT field, revert the increment
of null_bits that was done above.
*/
if (sql_field->sql_type == MYSQL_TYPE_BIT &&
file->ha_table_flags() & HA_CAN_BIT_FIELD) {
create_info->null_bits -=
sql_field->max_display_width_in_codepoints() & 7;
}
sql_field->constant_default = dup_field->constant_default;
sql_field->sql_type = dup_field->sql_type;
/*
If we are replacing a field with a BIT field, we need
to initialize treat_bit_as_char. Note that we do not need to
increment null_bits here as this dup_field
has already been processed.
*/
if (sql_field->sql_type == MYSQL_TYPE_BIT) {
sql_field->treat_bit_as_char =
!(file->ha_table_flags() & HA_CAN_BIT_FIELD);
}
sql_field->charset =
(dup_field->charset ? dup_field->charset
: create_info->default_table_charset);
sql_field->set_max_display_width_from_create_field(*dup_field);
sql_field->decimals = dup_field->decimals;
sql_field->auto_flags = dup_field->auto_flags;
/*
We're making one field from two, the result field will have
dup_field->flags as flags. If we've incremented null_bits
because of sql_field->flags, decrement it back.
*/
if (!(sql_field->flags & NOT_NULL_FLAG)) create_info->null_bits--;
sql_field->flags = dup_field->flags;
sql_field->interval = dup_field->interval;
sql_field->gcol_info = dup_field->gcol_info;
sql_field->m_default_val_expr = dup_field->m_default_val_expr;
sql_field->stored_in_db = dup_field->stored_in_db;
sql_field->hidden = dup_field->hidden;
it.remove(); // Remove first (create) definition
(*select_field_pos)--;
break;
}
}
}
/* Don't pack rows in old tables if the user has requested this */
if ((sql_field->flags & BLOB_FLAG) ||
(sql_field->sql_type == MYSQL_TYPE_VARCHAR &&
create_info->row_type != ROW_TYPE_FIXED))
create_info->table_options |= HA_OPTION_PACK_RECORD;
if (prepare_pack_create_field(thd, sql_field, file->ha_table_flags()))
return true;
return false;
}
static void calculate_field_offsets(List<Create_field> *create_list) {
assert(create_list);
List_iterator<Create_field> it(*create_list);
size_t record_offset = 0;
bool has_vgc = false;
Create_field *sql_field;
while ((sql_field = it++)) {
sql_field->offset = record_offset;
/*
For now skip fields that are not physically stored in the database
(generated fields) and update their offset later (see the next loop).
*/
if (sql_field->stored_in_db)
record_offset += sql_field->pack_length();
else
has_vgc = true;
}
/* Update generated fields' offset*/
if (has_vgc) {
it.rewind();
while ((sql_field = it++)) {
if (!sql_field->stored_in_db) {
sql_field->offset = record_offset;
record_offset += sql_field->pack_length();
}
}
}
}
/**
Count keys and key segments. Note that FKs are ignored.
Also mark redundant keys to be ignored.
@param[in,out] key_list List of keys to count and possibly mark as ignored.
@param[out] key_count Returned number of keys counted (excluding FK).
@param[out] key_parts Returned number of key segments (excluding FK).
@param[out] fk_key_count Returned number of foreign keys.
@param[in,out] redundant_keys Array where keys to be ignored will be marked.
@param[in] se_index_flags Storage's flags for index support
*/
static bool count_keys(const Mem_root_array<Key_spec *> &key_list,
uint *key_count, uint *key_parts, uint *fk_key_count,
Mem_root_array<bool> *redundant_keys,
handler::Table_flags se_index_flags) {
*key_count = 0;
*key_parts = 0;
for (size_t key_counter = 0; key_counter < key_list.size(); key_counter++) {
const Key_spec *key = key_list[key_counter];
for (size_t key2_counter = 0;
key2_counter < key_list.size() && key_list[key2_counter] != key;
key2_counter++) {
const Key_spec *key2 = key_list[key2_counter];
/*
foreign_key_prefix(key, key2) returns 0 if key or key2, or both, is
'generated', and a generated key is a prefix of the other key.
Then we do not need the generated shorter key.
KEYTYPE_SPATIAL and KEYTYPE_FULLTEXT cannot be used as
supporting keys for foreign key constraints even if the
generated key is prefix of such a key.
*/
if ((key2->type != KEYTYPE_FOREIGN && key->type != KEYTYPE_FOREIGN &&
key2->type != KEYTYPE_SPATIAL && key2->type != KEYTYPE_FULLTEXT &&
!redundant_keys->at(key2_counter) &&
!foreign_key_prefix(key, key2))) {
/* TODO: issue warning message */
/* mark that the generated key should be ignored */
if (!key2->generated ||
(key->generated && key->columns.size() < key2->columns.size()))
(*redundant_keys)[key_counter] = true;
else {
(*redundant_keys)[key2_counter] = true;
(*key_parts) -= key2->columns.size();
(*key_count)--;
}
break;
}
}
if (!redundant_keys->at(key_counter)) {
if (key->type == KEYTYPE_FOREIGN)
(*fk_key_count)++;
else {
uint mv_key_parts = 0;
(*key_count)++;
(*key_parts) += key->columns.size();
for (uint i = 0; i < key->columns.size(); i++) {
const Key_part_spec *kp = key->columns[i];
if (!kp->is_ascending() && !(se_index_flags & HA_DESCENDING_INDEX)) {
my_error(ER_CHECK_NOT_IMPLEMENTED, MYF(0), "descending indexes");
return true;
}
if (kp->has_expression() && kp->get_expression()->returns_array()) {
if (mv_key_parts++) {
my_error(ER_NOT_SUPPORTED_YET, MYF(0),
"more than one multi-valued key part per index");
return true;
}
if (!(se_index_flags & HA_MULTI_VALUED_KEY_SUPPORT)) {
my_error(ER_CHECK_NOT_IMPLEMENTED, MYF(0),
"multi-valued indexes");
return true;
}
if (kp->is_explicit()) {
my_error(ER_WRONG_USAGE, MYF(0), "multi-valued index",
"explicit index order");
return true;
}
}
}
}
}
}
return false;
}
static bool prepare_key_column(THD *thd, HA_CREATE_INFO *create_info,
List<Create_field> *create_list,
const Key_spec *key, const Key_part_spec *column,
const size_t column_nr, KEY *key_info,
KEY_PART_INFO *key_part_info,
const handler *file, int *auto_increment,
const CHARSET_INFO **ft_key_charset) {
DBUG_TRACE;
/*
Find the matching table column.
*/
uint field = 0;
Create_field *sql_field = nullptr;
assert(create_list);
for (Create_field &it : *create_list) {
if ((column->has_expression() || !is_hidden_by_system(&it)) &&
my_strcasecmp(system_charset_info, column->get_field_name(),
it.field_name) == 0) {
sql_field = ⁢
break;
}
field++;
}
if (sql_field == nullptr) {
my_error(ER_KEY_COLUMN_DOES_NOT_EXITS, MYF(0), column->get_field_name());
return true;
}
Functional_index_error_handler functional_index_error_handler(
sql_field, {key->name.str, key->name.length}, thd);
/*
Virtual generated column checks.
*/
if (sql_field->is_virtual_gcol()) {
const char *errmsg = nullptr;
if (key->type == KEYTYPE_FULLTEXT) {
errmsg = "Fulltext index on virtual generated column";
functional_index_error_handler.force_error_code(
ER_FULLTEXT_FUNCTIONAL_INDEX);
} else if (key->type == KEYTYPE_SPATIAL ||
sql_field->sql_type == MYSQL_TYPE_GEOMETRY) {
errmsg = "Spatial index on virtual generated column";
functional_index_error_handler.force_error_code(
ER_SPATIAL_FUNCTIONAL_INDEX);
} else if (key->type == KEYTYPE_PRIMARY) {
errmsg = "Defining a virtual generated column as primary key";
functional_index_error_handler.force_error_code(
ER_FUNCTIONAL_INDEX_PRIMARY_KEY);
}
if (errmsg) {
my_error(ER_UNSUPPORTED_ACTION_ON_GENERATED_COLUMN, MYF(0), errmsg);
return true;
}
/* Check if the storage engine supports indexes on virtual columns. */
if (!(file->ha_table_flags() & HA_CAN_INDEX_VIRTUAL_GENERATED_COLUMN)) {
my_error(ER_ILLEGAL_HA_CREATE_OPTION, MYF(0),
ha_resolve_storage_engine_name(file->ht),
"Index on virtual generated column");
return true;
}
key_info->flags |= HA_VIRTUAL_GEN_KEY;
}
// JSON columns cannot be used as keys.
if (sql_field->sql_type == MYSQL_TYPE_JSON) {
my_error(ER_JSON_USED_AS_KEY, MYF(0), column->get_field_name());
return true;
}
if (sql_field->auto_flags & Field::NEXT_NUMBER) {
if (column_nr == 0 || (file->ha_table_flags() & HA_AUTO_PART_KEY))
(*auto_increment)--; // Field is used
}
/*
Check for duplicate columns.
*/
for (const Key_part_spec *dup_column : key->columns) {
if (dup_column == column) break;
if (!my_strcasecmp(system_charset_info, column->get_field_name(),
dup_column->get_field_name())) {
my_error(ER_DUP_FIELDNAME, MYF(0), column->get_field_name());
return true;
}
}
uint column_length;
if (key->type == KEYTYPE_FULLTEXT) {
if ((sql_field->sql_type != MYSQL_TYPE_STRING &&
sql_field->sql_type != MYSQL_TYPE_VARCHAR &&
!is_blob(sql_field->sql_type)) ||
sql_field->charset == &my_charset_bin ||
sql_field->charset->mbminlen > 1 || // ucs2 doesn't work yet
(*ft_key_charset && sql_field->charset != *ft_key_charset)) {
my_error(ER_BAD_FT_COLUMN, MYF(0), column->get_field_name());
return true;
}
*ft_key_charset = sql_field->charset;
/*
for fulltext keys keyseg length is 1 for blobs (it's ignored in ft
code anyway, and 0 (set to column width later) for char's. it has
to be correct col width for char's, as char data are not prefixed
with length (unlike blobs, where ft code takes data length from a
data prefix, ignoring column->length).
*/
column_length = is_blob(sql_field->sql_type);
} else {
switch (sql_field->sql_type) {
case MYSQL_TYPE_GEOMETRY:
/* All indexes on geometry columns are R-tree indexes. */
if (key->columns.size() > 1) {
my_error(ER_TOO_MANY_KEY_PARTS, MYF(0), 1);
return true;
}
key_info->flags |= HA_SPATIAL;
if (key->key_create_info.is_algorithm_explicit &&
key_info->algorithm != HA_KEY_ALG_RTREE) {
assert(key->key_create_info.algorithm == HA_KEY_ALG_HASH ||
key->key_create_info.algorithm == HA_KEY_ALG_BTREE);
my_error(ER_INDEX_TYPE_NOT_SUPPORTED_FOR_SPATIAL_INDEX, MYF(0),
key->key_create_info.algorithm == HA_KEY_ALG_HASH ? "HASH"
: "BTREE");
return true;
}
key_info->algorithm = HA_KEY_ALG_RTREE;
[[fallthrough]];
case MYSQL_TYPE_TINY_BLOB:
case MYSQL_TYPE_MEDIUM_BLOB:
case MYSQL_TYPE_LONG_BLOB:
case MYSQL_TYPE_BLOB:
case MYSQL_TYPE_JSON:
case MYSQL_TYPE_VAR_STRING:
case MYSQL_TYPE_STRING:
case MYSQL_TYPE_VARCHAR:
case MYSQL_TYPE_ENUM:
case MYSQL_TYPE_SET:
column_length =
column->get_prefix_length() * sql_field->charset->mbmaxlen;
break;
default:
column_length = column->get_prefix_length();
}
if (key->type == KEYTYPE_SPATIAL ||
key_info->algorithm == HA_KEY_ALG_RTREE ||
sql_field->sql_type == MYSQL_TYPE_GEOMETRY) {
if (column_length) {
my_error(ER_WRONG_SUB_KEY, MYF(0));
return true;
}
if (sql_field->sql_type != MYSQL_TYPE_GEOMETRY) {
my_error(ER_SPATIAL_MUST_HAVE_GEOM_COL, MYF(0));
return true;
}
if (key_info->flags & HA_NOSAME) {
my_error(ER_SPATIAL_UNIQUE_INDEX, MYF(0));
return true;
}
if (column->is_explicit()) {
my_error(ER_WRONG_USAGE, MYF(0), "spatial/fulltext/hash index",
"explicit index order");
return true;
}
/*
If the field is without an SRID specification, issue a warning telling
the user that this index will not be used by the optimizer (useless
spatial index). We do however have to allow creating such index in
order to support dump/restore from older MySQL versions to new
versions.
NOTE: At this stage of ALTER TABLE/CREATE INDEX/whatever DDL, we may
have copied all existing indexes into key list. Thus, this function may
run for indexes that already exists. The variable
"check_for_duplicate_indexes" will however be set to "false" for indexes
that already are created, so we use this variable to distinguish between
indexes that are to be created, and those that already are created.
*/
if (key->check_for_duplicate_indexes && !sql_field->m_srid.has_value()) {
push_warning_printf(
thd, Sql_condition::SL_WARNING, WARN_USELESS_SPATIAL_INDEX,
ER_THD(thd, WARN_USELESS_SPATIAL_INDEX), sql_field->field_name);
}
/*
4 is: (Xmin,Xmax,Ymin,Ymax), this is for 2D case
Lately we'll extend this code to support more dimensions
*/
column_length = 4 * sizeof(double);
}
if (is_blob(sql_field->sql_type)) {
if (!(file->ha_table_flags() & HA_CAN_INDEX_BLOBS)) {
my_error(ER_BLOB_USED_AS_KEY, MYF(0), column->get_field_name());
return true;
}
if (!column_length) {
my_error(ER_BLOB_KEY_WITHOUT_LENGTH, MYF(0), column->get_field_name());
return true;
}
}
if (key->type == KEYTYPE_PRIMARY) {
/*
Set NO_DEFAULT_VALUE_FLAG for the PRIMARY KEY column if default
values is not explicitly provided for the column in CREATE TABLE
statement and it is not an AUTO_INCREMENT field.
Default values for TIMESTAMP/DATETIME needs special handling as:
a) If default is explicitly specified (lets say this as case 1) :
DEFAULT CURRENT_TIMESTAMP
DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
MySQL does not set sql_field->def flag , but sets
Field::DEFAULT_NOW in Create_info::auto_flags.
This flags are also set during timestamp column promotion (case2)
When explicit_defaults_for_timestamp is not set, the behavior
expected in both case1 and case2 is to retain the defaults even
when the column participates in PRIMARY KEY. When
explicit_defaults_for_timestamp is set, the promotion logic
is disabled and the above mentioned flag is not used implicitly.
b) If explicit_defaults_for_timestamp variable is not set:
Default value assigned due to first timestamp column promotion is
retained.
Default constant value assigned due to implicit promotion of second
timestamp column is removed.
*/
if (!sql_field->constant_default &&
!(sql_field->flags & AUTO_INCREMENT_FLAG) &&
!(real_type_with_now_as_default(sql_field->sql_type) &&
(sql_field->auto_flags & Field::DEFAULT_NOW)) &&
!(sql_field->m_default_val_expr &&
(sql_field->auto_flags & Field::GENERATED_FROM_EXPRESSION))) {
sql_field->flags |= NO_DEFAULT_VALUE_FLAG;
}
/*
Emitting error when field is a part of primary key and is
explicitly requested to be NULL by the user.
*/
if ((sql_field->flags & EXPLICIT_NULL_FLAG)) {
my_error(ER_PRIMARY_CANT_HAVE_NULL, MYF(0));
return true;
}
}
if (!(sql_field->flags & NOT_NULL_FLAG)) {
if (key->type == KEYTYPE_PRIMARY) {
/* Implicitly set primary key fields to NOT NULL for ISO conf. */
sql_field->flags |= NOT_NULL_FLAG;
sql_field->is_nullable = false;
create_info->null_bits--;
} else {
key_info->flags |= HA_NULL_PART_KEY;
if (!(file->ha_table_flags() & HA_NULL_IN_KEY)) {
my_error(ER_NULL_COLUMN_IN_INDEX, MYF(0), column->get_field_name());
return true;
}
if (key->type == KEYTYPE_SPATIAL ||
sql_field->sql_type == MYSQL_TYPE_GEOMETRY) {
my_error(ER_SPATIAL_CANT_HAVE_NULL, MYF(0));
return true;
}
}
}
} // key->type != KEYTYPE_FULLTEXT
key_part_info->fieldnr = field;
key_part_info->offset = static_cast<uint16>(sql_field->offset);
key_part_info->key_part_flag |= column->is_ascending() ? 0 : HA_REVERSE_SORT;
size_t key_part_length = sql_field->key_length();
if (column_length) {
if (is_blob(sql_field->sql_type)) {
key_part_length = column_length;
/*
There is a possibility that the given prefix length is less
than the engine max key part length, but still greater
than the BLOB field max size. We handle this case
using the max_field_size variable below.
*/
size_t max_field_size = blob_length_by_type(sql_field->sql_type);
if (key_part_length > max_field_size ||
key_part_length > file->max_key_length() ||
key_part_length > file->max_key_part_length(create_info)) {
// Given prefix length is too large, adjust it.
key_part_length =
min(file->max_key_length(), file->max_key_part_length(create_info));
if (max_field_size)
key_part_length = min(key_part_length, max_field_size);
if (key->type == KEYTYPE_MULTIPLE) {
/* not a critical problem */
push_warning_printf(thd, Sql_condition::SL_WARNING, ER_TOO_LONG_KEY,
ER_THD(thd, ER_TOO_LONG_KEY),
static_cast<int>(key_part_length));
/* Align key length to multibyte char boundary */
key_part_length -= key_part_length % sql_field->charset->mbmaxlen;
/*
If SQL_MODE is STRICT, then report error, else report warning
and continue execution.
*/
if (thd->is_error()) return true;
} else {
my_error(ER_TOO_LONG_KEY, MYF(0), key_part_length);
if (thd->is_error()) return true;
}
}
} // is_blob
// Catch invalid use of partial keys
else if (sql_field->sql_type != MYSQL_TYPE_GEOMETRY &&
// is the key partial?
column_length != key_part_length &&
// is prefix length bigger than field length?
(column_length > key_part_length ||
// can the field have a partial key?
!Field::type_can_have_key_part(sql_field->sql_type) ||
// does the storage engine allow prefixed search?
((file->ha_table_flags() & HA_NO_PREFIX_CHAR_KEYS) &&
// and is this a 'unique' key?
(key_info->flags & HA_NOSAME)))) {
my_error(ER_WRONG_SUB_KEY, MYF(0));
return true;
} else if (!(file->ha_table_flags() & HA_NO_PREFIX_CHAR_KEYS))
key_part_length = column_length;
} // column_length
else if (key_part_length == 0) {
if (is_field_for_functional_index(sql_field)) {
// In case this is a functional index, print a more friendly error
// message.
Item *expression = column->get_expression();
auto flags =
enum_query_type(QT_NO_DB | QT_NO_TABLE | QT_FORCE_INTRODUCERS);
String out;
expression->print(thd, &out, flags);
// Append a NULL-terminator, since Item::print does not necessarily add
// one.
out.append('\0');
my_error(ER_WRONG_KEY_COLUMN_FUNCTIONAL_INDEX, MYF(0), out.ptr());
} else {
my_error(ER_WRONG_KEY_COLUMN, MYF(0), column->get_field_name());
}
return true;
}
if (key_part_length > file->max_key_part_length(create_info) &&
key->type != KEYTYPE_FULLTEXT) {
key_part_length = file->max_key_part_length(create_info);
if (key->type == KEYTYPE_MULTIPLE) {
/* not a critical problem */
push_warning_printf(thd, Sql_condition::SL_WARNING, ER_TOO_LONG_KEY,
ER_THD(thd, ER_TOO_LONG_KEY),
static_cast<int>(key_part_length));
/* Align key length to multibyte char boundary */
key_part_length -= key_part_length % sql_field->charset->mbmaxlen;
/*
If SQL_MODE is STRICT, then report error, else report warning
and continue execution.
*/
if (thd->is_error()) return true;
} else if ((thd->lex->alter_info->flags & Alter_info::ALTER_OPTIONS) &&
(create_info->used_fields & HA_CREATE_USED_CHARSET)) {
my_error(ER_COLUMN_CHANGE_SIZE, MYF(0), sql_field->field_name,
sql_field->field->table->s->table_name.str, key->name.str,
key_part_length);
return true;
} else {
my_error(ER_TOO_LONG_KEY, MYF(0), key_part_length);
if (thd->is_error()) return true;
}
}
key_part_info->length = static_cast<uint16>(key_part_length);
/*
Use packed keys for long strings on the first column
Due to incorrect usage of sql_field->pack_flag & FIELDFLAG_BLOB check
we have used packing for some columns which are not strings or BLOBs
(see also is_phony_blob()). Since changing this would mean breaking
binary compatibility for MyISAM tables with indexes on such columns
we mimic this buggy behavior here.
*/
if ((create_info->db_type->flags & HTON_SUPPORTS_PACKED_KEYS) &&
!((create_info->table_options & HA_OPTION_NO_PACK_KEYS)) &&
(key_part_length >= KEY_DEFAULT_PACK_LENGTH &&
(sql_field->sql_type == MYSQL_TYPE_STRING ||
sql_field->sql_type == MYSQL_TYPE_VARCHAR ||
is_blob(sql_field->sql_type) ||
is_phony_blob(sql_field->sql_type, sql_field->decimals)))) {
if ((column_nr == 0 &&
(is_blob(sql_field->sql_type) ||
is_phony_blob(sql_field->sql_type, sql_field->decimals))) ||
sql_field->sql_type == MYSQL_TYPE_VARCHAR)
key_info->flags |= HA_BINARY_PACK_KEY;
else
key_info->flags |= HA_PACK_KEY;
}
/*
Check if the key segment is partial, set the key flag
accordingly. Note that fulltext indexes ignores prefixes.
*/
if (key->type != KEYTYPE_FULLTEXT &&
key_part_length != sql_field->key_length()) {
key_info->flags |= HA_KEY_HAS_PART_KEY_SEG;
key_part_info->key_part_flag |= HA_PART_KEY_SEG;
}
key_info->key_length += key_part_length;
return false;
}
/**
Check if candidate parent/supporting key contains exactly the same
columns as the foreign key, possibly, in different order. Also check
that columns usage by key is acceptable, i.e. key is not over column
prefix.
@tparam F Function class which returns foreign key's
referenced or referencing (depending on whether
we check candidate parent or supporting key)
column name by its index.
@param alter_info Alter_info describing columns in parent or
child table.
@param fk_col_count Number of columns in the foreign key.
@param fk_columns Object of F type bound to the specific foreign key
for which parent/supporting key check is carried
out.
@param key KEY object describing candidate parent/supporting
key.
@sa fk_is_key_exact_match_any_order(uint, F, dd::Index).
@retval True - Key is proper parent/supporting key for the foreign key.
@retval False - Key can't be parent/supporting key for the foreign key.
*/
template <class F>
static bool fk_is_key_exact_match_any_order(Alter_info *alter_info,
uint fk_col_count,
const F &fk_columns,
const KEY *key) {
if (fk_col_count != key->user_defined_key_parts) return false;
for (uint i = 0; i < key->user_defined_key_parts; i++) {
// Prefix parts are considered non-matching.
if (key->key_part[i].key_part_flag & HA_PART_KEY_SEG) return false;
const Create_field *col =
get_field_by_index(alter_info, key->key_part[i].fieldnr);
uint j = 0;
while (j < fk_col_count) {
if (my_strcasecmp(system_charset_info, col->field_name, fk_columns(j)) ==
0)
break;
j++;
}
if (j == fk_col_count) return false;
/*
Foreign keys over virtual columns are not allowed.
This is checked at earlier stage.
*/
assert(!col->is_virtual_gcol());
}
return true;
}
/**
Count how many elements from the start of the candidate parent/supporting
key match elements at the start of the foreign key (prefix parts are
considered non-matching).
@tparam F Function class which returns foreign key's
referenced or referencing (depending on whether
we check candidate parent or supporting key)
column name by its index.
@param alter_info Alter_info describing columns in parent or
child table.
@param fk_col_count Number of columns in the foreign key.
@param fk_columns Object of F type bound to the specific foreign key
for which parent/supporting key check is carried
out.
@param key KEY object describing candidate parent/supporting
key.
@param hidden_cols_key If non-nullptr, points to KEY object representing
primary key for the table, which columns are added
to the candidate parent key and should be taken
into account when considering this parent key.
@sa fk_key_prefix_match_count(uint, F, dd::Index, bool).
@retval Number of matching columns.
*/
template <class F>
static uint fk_key_prefix_match_count(Alter_info *alter_info, uint fk_col_count,
const F &fk_columns, const KEY *key,
const KEY *hidden_cols_key) {
uint col_idx = 0;
for (; col_idx < key->user_defined_key_parts; ++col_idx) {
if (col_idx == fk_col_count) break;
// Prefix parts are considered non-matching.
if (key->key_part[col_idx].key_part_flag & HA_PART_KEY_SEG) break;
const Create_field *col =
get_field_by_index(alter_info, key->key_part[col_idx].fieldnr);
if (my_strcasecmp(system_charset_info, col->field_name,
fk_columns(col_idx)) != 0)
break;
/*
Foreign keys over virtual columns are not allowed.
This is checked at earlier stage.
*/
assert(!col->is_virtual_gcol());
}
if (col_idx < fk_col_count && col_idx == key->user_defined_key_parts &&
hidden_cols_key) {
/*
We have not found all foreign key columns and have not encountered
unsuitable columns so far. Continue counting columns from hidden
part of the key if it exists.
*/
for (uint add_col_idx = 0;
add_col_idx < hidden_cols_key->user_defined_key_parts; ++add_col_idx) {
if (col_idx == fk_col_count) break;
KEY_PART_INFO *add_key_part = hidden_cols_key->key_part + add_col_idx;
/*
Hidden part of the key doesn't include columns already in the key,
unless they are used as prefix columns (which is impossible here).
*/
if (std::any_of(key->key_part,
key->key_part + key->user_defined_key_parts,
[add_key_part](const KEY_PART_INFO &key_part) {
return key_part.fieldnr == add_key_part->fieldnr;
}))
continue;
/*
prepare_self_ref_fk_parent_key() ensures that we can't meet
primary keys with prefix parts here.
*/
assert(!(add_key_part->key_part_flag & HA_PART_KEY_SEG));
const Create_field *col =
get_field_by_index(alter_info, add_key_part->fieldnr);
if (my_strcasecmp(system_charset_info, col->field_name,
fk_columns(col_idx)) != 0)
break;
assert(!col->is_virtual_gcol());
++col_idx;
}
}
return col_idx;
}
/**
Check if candidate parent/supporting key contains all columns from the
foreign key at its start and in the same order it is in the foreign key.
Also check that columns usage by key is acceptable, i.e. key is not over
column prefix.
@tparam F Function class which returns foreign key's
referenced or referencing (depending on whether
we check candidate parent or supporting key)
column name by its index.
@param alter_info Alter_info describing columns in parent or
child table.
@param fk_col_count Number of columns in the foreign key.
@param fk_columns Object of F type bound to the specific foreign key
for which parent/supporting key check is carried
out.
@param key KEY object describing candidate parent/supporting
key.
@param hidden_cols_key If non-nullptr, points to KEY object representing
primary key for the table, which columns are added
to the candidate parent key and should be taken
into account when considering this parent key.
@sa fk_key_is_full_prefix_match(uint, F, dd::Index, bool).
@retval True - Key is proper parent/supporting key for the foreign key.
@retval False - Key can't be parent/supporting key for the foreign key.
*/
template <class F>
static bool fk_key_is_full_prefix_match(Alter_info *alter_info,
uint fk_col_count, const F &fk_columns,
const KEY *key,
const KEY *hidden_cols_key) {
/*
The index may have more elements, but must start with the same
elements as the FK.
*/
if (fk_col_count >
key->user_defined_key_parts +
(hidden_cols_key ? hidden_cols_key->user_defined_key_parts : 0))
return false;
uint match_count = fk_key_prefix_match_count(
alter_info, fk_col_count, fk_columns, key, hidden_cols_key);
return (match_count == fk_col_count);
}
/**
Check if parent key for self-referencing foreign key exists, set
foreign key's unique constraint name accordingly. Emit error if
no parent key found.
@note Prefer unique key if possible. If parent key is non-unique
unique constraint name is set to NULL.
@note Explicitly skip the supporting index as a candidate parent
index to maintain previous behavior for engines that require
the two indexes to be different.
@param hton Handlerton for table's storage engine.
@param alter_info Alter_info object describing parent table.
@param key_info_buffer Array describing keys in parent table.
@param key_count Number of keys in parent table.
@param supporting_key Pointer to KEY representing the supporting
index.
@param old_fk_table dd::Table object from which pre-existing
FK comes from. nullptr if this FK is newly
added.
@param[in,out] fk FOREIGN_KEY object describing the FK, its
unique_index_name member will be updated
if matching unique constraint is found.
@retval Operation result. False if success.
*/
static bool prepare_self_ref_fk_parent_key(
handlerton *hton, Alter_info *alter_info, const KEY *key_info_buffer,
const uint key_count, const KEY *supporting_key,
const dd::Table *old_fk_table, FOREIGN_KEY *fk) {
auto fk_columns_lambda = [fk](uint i) { return fk->fk_key_part[i].str; };
for (const KEY *key = key_info_buffer; key < key_info_buffer + key_count;
key++) {
// We can't use FULLTEXT or SPATIAL indexes.
if (key->flags & (HA_FULLTEXT | HA_SPATIAL)) continue;
if (hton->foreign_keys_flags &
HTON_FKS_NEED_DIFFERENT_PARENT_AND_SUPPORTING_KEYS) {
/*
The storage engine does not support using the same index for both the
supporting index and the parent index. In this case, the supporting
index cannot be a candidate parent index, and must be skipped.
*/
if (key == supporting_key) continue;
}
if (hton->foreign_keys_flags & HTON_FKS_WITH_PREFIX_PARENT_KEYS) {
/*
Engine supports unique and non unique-parent keys which contain full
foreign key as its prefix. Example: InnoDB.
Primary and unique keys are sorted before non-unique keys.
So if there is suitable unique parent key we will always find
it before encountering any non-unique keys.
*/
const KEY *hidden_cols_key = nullptr;
if (hton->foreign_keys_flags & HTON_FKS_WITH_EXTENDED_PARENT_KEYS) {
/*
Engine considers hidden part of key (columns from primary key
which are implicitly added to secondary keys) when determines
if it can serve as parent. Example: InnoDB.
Since KEY objects do not contain information about hidden parts
of the keys at this point, we have to figure out list of hidden
columns based on KEY object for explicit or implicit primary key.
For the sake of consistency with non-self-referencing case we
exclude primary keys with prefix elements from our consideration.
Thanks to the way keys are sorted, to find primary key it is
enough to check if the first key in key array satisfies
requirements on candidate key (unique, without null, prefix or
virtual parts). This also automatically excludes explicit primary
keys with prefix parts.
*/
if (key != key_info_buffer && (key_info_buffer->flags & HA_NOSAME) &&
!(key_info_buffer->flags &
(HA_NULL_PART_KEY | HA_KEY_HAS_PART_KEY_SEG |
HA_VIRTUAL_GEN_KEY)))
hidden_cols_key = key_info_buffer;
}
if (fk_key_is_full_prefix_match(alter_info, fk->key_parts,
fk_columns_lambda, key,
hidden_cols_key)) {
/*
We only store names of PK or UNIQUE keys in UNIQUE_CONSTRAINT_NAME.
InnoDB allows non-unique indexes as parent keys for which NULL is
stored.
*/
if (key->flags & HA_NOSAME)
fk->unique_index_name = key->name;
else
fk->unique_index_name = nullptr;
return false;
}
} else {
/*
Default case. Engine only supports unique parent keys which
contain exactly the same columns as foreign key, possibly
in different order. Example: NDB.
*/
if ((key->flags & HA_NOSAME) &&
fk_is_key_exact_match_any_order(alter_info, fk->key_parts,
fk_columns_lambda, key)) {
fk->unique_index_name = key->name;
return false;
}
}
}
// No matching parent key!
if (old_fk_table == nullptr) {
// This is new foreign key for which parent key is missing.
my_error(ER_FK_NO_INDEX_PARENT, MYF(0), fk->name, fk->ref_table.str);
} else {
/*
Old foreign key for which parent key or supporting key must have
been dropped by this ALTER TABLE. Some analysis is needed to determine
what has been dropped.
Find old foreign key definition first.
*/
auto same_name = [fk](const dd::Foreign_key *el) {
return my_strcasecmp(system_charset_info, fk->name, el->name().c_str()) ==
0;
};
auto old_fk = std::find_if(old_fk_table->foreign_keys().begin(),
old_fk_table->foreign_keys().end(), same_name);
assert(old_fk != old_fk_table->foreign_keys().end());
/*
Then, unless the SE supports it, we need to find the old
supporting key, to avoid selecting the incorrect parent key, and to
make sure we determine whether the supporting or the parent key was
dropped. This is done as follows:
- If the name of the old and new supporting key is the same,
then we have either dropped the parent key, or we have dropped
the supporting key and renamed another key to the supporting
key's name.
- If the name of the old and new supporting key is different,
then we have either dropped the supporting key, or we have dropped
the parent key and renamed the supporting key to a different name.
When finding the original key name, just getting the unique constraint
name won't work for non-unique parent keys. Ideally, we should be
using the handlerton of the old table version below, however, in
practice, the new table version's handlerton works just fine, since
we do not allow changing storage engines for tables with foreign keys.
*/
const char *dropped_key = "<unknown key name>";
if (hton->foreign_keys_flags &
HTON_FKS_NEED_DIFFERENT_PARENT_AND_SUPPORTING_KEYS) {
const dd::Index *old_sk =
find_fk_supporting_key(hton, old_fk_table, *old_fk);
const dd::Index *old_pk =
find_fk_parent_key(hton, old_sk, old_fk_table, *old_fk);
if (old_sk != nullptr && old_pk != nullptr) {
if (my_strcasecmp(system_charset_info, supporting_key->name,
old_sk->name().c_str()) == 0) {
dropped_key = old_pk->name().c_str();
auto renamed_to_sk = [supporting_key](const Alter_rename_key *key) {
return (my_strcasecmp(system_charset_info, supporting_key->name,
key->new_name) == 0);
};
if (std::any_of(alter_info->alter_rename_key_list.begin(),
alter_info->alter_rename_key_list.end(),
renamed_to_sk)) {
dropped_key = old_sk->name().c_str();
}
} else {
dropped_key = old_sk->name().c_str();
auto renamed_from_sk = [old_sk](const Alter_rename_key *key) {
return (my_strcasecmp(system_charset_info, old_sk->name().c_str(),
key->old_name) == 0);
};
if (std::any_of(alter_info->alter_rename_key_list.begin(),
alter_info->alter_rename_key_list.end(),
renamed_from_sk)) {
dropped_key = old_pk->name().c_str();
}
}
}
} else {
const dd::Index *old_pk =
find_fk_parent_key(hton, nullptr, old_fk_table, *old_fk);
if (old_pk) dropped_key = old_pk->name().c_str();
}
my_error(ER_DROP_INDEX_FK, MYF(0), dropped_key);
}
return true;
}
/**
Find supporting key for the foreign key.
@param hton Handlerton for table's storage engine.
@param alter_info Alter_info object describing child table.
@param key_info_buffer Array describing keys in child table.
@param key_count Number of keys in child table.
@param fk FOREIGN_KEY object describing the FK.
@sa find_fk_supporting_key(handlerton*, const dd::Table*,
const dd::Foreign_key*)
@retval non-nullptr - pointer to KEY object describing supporting key.
@retval nullptr - if no supporting key were found.
*/
static const KEY *find_fk_supporting_key(handlerton *hton,
Alter_info *alter_info,
const KEY *key_info_buffer,
const uint key_count,
const FOREIGN_KEY *fk) {
uint best_match_count = 0;
const KEY *best_match_key = nullptr;
auto fk_columns_lambda = [fk](uint i) { return fk->key_part[i].str; };
for (const KEY *key = key_info_buffer; key < key_info_buffer + key_count;
key++) {
// We can't use FULLTEXT or SPATIAL indexes.
if (key->flags & (HA_FULLTEXT | HA_SPATIAL)) continue;
if (key->algorithm == HA_KEY_ALG_HASH) {
if (hton->foreign_keys_flags & HTON_FKS_WITH_SUPPORTING_HASH_KEYS) {
/*
Storage engine supports hash keys as supporting keys for foreign
keys. Hash key should contain all foreign key columns and only
them (although in any order).
Example: NDB and unique/primary key with USING HASH clause.
*/
if (fk_is_key_exact_match_any_order(alter_info, fk->key_parts,
fk_columns_lambda, key))
return key;
}
} else {
if (hton->foreign_keys_flags & HTON_FKS_WITH_ANY_PREFIX_SUPPORTING_KEYS) {
/*
Storage engine supports non-hash keys which have common prefix
with the foreign key as supporting keys for it. If there are
several such keys, one which shares biggest prefix with FK is
chosen.
Example: NDB and non-unique keys, or unique/primary keys without
explicit USING HASH clause.
*/
uint match_count = fk_key_prefix_match_count(
alter_info, fk->key_parts, fk_columns_lambda, key, nullptr);
if (match_count > best_match_count) {
best_match_count = match_count;
best_match_key = key;
}
} else {
/*
Default case. Storage engine supports non-hash keys which contain
full foreign key as prefix as supporting key for it.
Example: InnoDB.
SQL-layer tries to automatically create such generated key when
foreign key is created.
*/
if (fk_key_is_full_prefix_match(alter_info, fk->key_parts,
fk_columns_lambda, key, nullptr))
return key;
}
}
}
return best_match_key;
}
/**
Make old table definition's foreign keys use temporary names.
This is needed to avoid problems with duplicate foreign key
names while we have two definitions of the same table.
@param thd Thread context.
@param db_name Database where old table definition resides.
@param backup_name Temporary name assigned to old table definition
during ALTER TABLE.
@returns False - Success, True - Failure.
*/
static bool adjust_foreign_key_names_for_old_table_version(
THD *thd, const char *db_name, const char *backup_name) {
dd::Table *table_def = nullptr;
MDL_request_list mdl_requests;
if (thd->dd_client()->acquire_for_modification(db_name, backup_name,
&table_def))
return true;
assert(table_def != nullptr);
for (dd::Foreign_key *fk : *table_def->foreign_keys()) {
char temp_fk_name[4 + 20 + 1];
snprintf(temp_fk_name, sizeof(temp_fk_name), "#fk_%llu",
(ulonglong)fk->id());
/*
Acquire metadata locks on temporary names before updating data-dictionary
just in case somebody tries to create foreign keys with names like
#fk_<number> concurrently.
*/
MDL_request *mdl_request = new (thd->mem_root) MDL_request;
if (mdl_request == nullptr) return true;
MDL_REQUEST_INIT(mdl_request, MDL_key::FOREIGN_KEY, db_name, temp_fk_name,
MDL_EXCLUSIVE, MDL_STATEMENT);
mdl_requests.push_front(mdl_request);
// Update dd::Foreign_key object but do not store it in data-dictionary yet.
fk->set_name(temp_fk_name);
}
assert(!mdl_requests.is_empty());
if (thd->mdl_context.acquire_locks(&mdl_requests,
thd->variables.lock_wait_timeout))
return true;
return thd->dd_client()->update(table_def);
}
/**
Find max value of number component among existing generated foreign
key names for the table.
@param table_name Table name (should be already in lowercase
if l_c_t_n > 0).
@param table_def Table definition.
@param hton Table storage engine.
@note We assume that generated names follow pattern:
(table name)(SE-specific or default FK name suffix)(number)
E.g. "table_name_ibfk_####" for InnoDB. This function is in sync
with generate_fk_name() and dd::rename_foreign_keys().
@note This function mimics dict_table_get_highest_foreign_id() from 5.7.
*/
static uint get_fk_max_generated_name_number(const char *table_name,
const dd::Table *table_def,
handlerton *hton) {
uint key_number = 0;
/*
There is no need to lowercase table_name as it is already supposed
to be in lowercase.
*/
size_t table_name_length = strlen(table_name);
const LEX_CSTRING &fk_name_suffix =
hton->fk_name_suffix.str ? hton->fk_name_suffix : FK_NAME_DEFAULT_SUFFIX;
for (const dd::Foreign_key *fk : table_def->foreign_keys()) {
/*
We assume that the name is generated if it starts with:
<table_name><SE-specific or default FK name suffix>
Note that unlike during RENAME TABLE handling, here, i.e. when
generating name for new constraints, we mimic InnoDB's behavior from
5.7 and ignore pre-existing generated names which have pre-4.0.18 format.
*/
if (dd::is_generated_foreign_key_name(table_name, table_name_length, hton,
*fk) &&
(fk->name().c_str()[table_name_length + fk_name_suffix.length] !=
'0')) {
char *end = nullptr;
uint nr = my_strtoull(
fk->name().c_str() + table_name_length + fk_name_suffix.length, &end,
10);
if (!*end && nr > key_number) key_number = nr;
}
}
return key_number;
}
/**
Generate a foreign key name and store it in buffer provided.
@note Foreign key names have to be unique for a given schema.
This function is used when the user has not specified
neither constraint name nor foreign key name.
@note We generated names according to the pattern:
(table name)(SE-specific or default FK name suffix)(counter)
The counter is 1-based and per table. The number chosen for the
counter is 1 higher than the highest number currently in use.
For InnoDB "_ibfk_" is used as suffix, so names are compatible
with names generated by InnoDB in 5.7. For NDB, suffix "_fk_"
is used and compatibility is not preserved (as in 5.7 NDB
uses radically different approach anyway).
@param name_buff Buffer for generated name.
@param name_buff_size Size of name buffer, if buffer
is too small generated name
will be truncated.
@param table_name Table name.
@param hton Table storage engine.
@param[in,out] fk_max_generated_name_number Max value of number component
among existing generated
foreign key names.
*/
static void generate_fk_name(char *name_buff, size_t name_buff_size,
const char *table_name, handlerton *hton,
uint *fk_max_generated_name_number) {
snprintf(name_buff, name_buff_size, "%s%s%u", table_name,
(hton->fk_name_suffix.str ? hton->fk_name_suffix.str
: FK_NAME_DEFAULT_SUFFIX.str),
++*fk_max_generated_name_number);
}
/**
Generate a foreign key name, allocate memory from thread's current
memory root for it.
@note Foreign key names have to be unique for a given schema.
This function is used when the user has not specified
neither constraint name nor foreign key name.
@note We generated names according to the pattern:
(table name)(SE-specific or default FK name suffix)(counter)
The counter is 1-based and per table. The number chosen for the
counter is 1 higher than the highest number currently in use.
For InnoDB "_ibfk_" is used as suffix, so names are compatible
with names generated by InnoDB in 5.7. For NDB, suffix "_fk_"
is used and compatibility is not preserved (as in 5.7 NDB
uses radically different approach anyway).
@param table_name Table name.
@param hton Table storage engine.
@param[in,out] fk_max_generated_name_number Max value of number component
among existing generated foreign
key names.
@retval Generated name
*/
static const char *generate_fk_name(const char *table_name, handlerton *hton,
uint *fk_max_generated_name_number) {
// The below buffer should be sufficient for any generated name.
char name[NAME_LEN + MAX_FK_NAME_SUFFIX_LENGTH + 10 + 1];
generate_fk_name(name, sizeof(name), table_name, hton,
fk_max_generated_name_number);
return sql_strdup(name);
}
/**
Check if candidate parent/supporting key contains exactly the same
columns as the foreign key, possibly, in different order. Also check
that columns usage by key is acceptable, i.e. key is not over column
prefix.
@tparam F Function class which returns foreign key's
referenced or referencing (depending on whether
we check candidate parent or supporting key)
column name by its index.
@param fk_col_count Number of columns in the foreign key.
@param fk_columns Object of F type bound to the specific foreign key
for which parent/supporting key check is carried
out.
@param idx dd::Index object describing candidate parent/
supporting key.
@sa fk_is_key_exact_match_any_order(Alter_info, uint, F, KEY).
@retval True - Key is proper parent/supporting key for the foreign key.
@retval False - Key can't be parent/supporting key for the foreign key.
*/
template <class F>
static bool fk_is_key_exact_match_any_order(uint fk_col_count,
const F &fk_columns,
const dd::Index *idx) {
/*
Skip keys which have less elements (including hidden ones)
than foreign key right away.
*/
if (fk_col_count > idx->elements().size()) return false;
uint col_matched = 0;
for (const dd::Index_element *idx_el : idx->elements()) {
if (idx_el->is_hidden()) continue;
uint j = 0;
while (j < fk_col_count) {
if (my_strcasecmp(system_charset_info, idx_el->column().name().c_str(),
fk_columns(j)) == 0)
break;
j++;
}
if (j == fk_col_count) return false;
/*
Foreign keys over virtual columns are not allowed.
This is checked at earlier stage.
*/
assert(!idx_el->column().is_virtual());
/*
Prefix keys are not allowed/considered non-matching.
There is a special provision which allows to treat unique keys on
POINT and BLOB columns with prefix length equal to real column
length as candidate/primary keys. However, since InnoDB doesn't
allow columns of such types in FKs, we don't need similar provision
here. So we can simply use dd::Index_element::is_prefix().
Calling Index_element::is_prefix() can be a bit expensive so
we do this after checking if foreign key has matching column
(foreign key column list is likely to be small).
*/
if (idx_el->is_prefix()) return false;
++col_matched;
}
return (col_matched == fk_col_count);
}
/**
Count how many elements from the start of the candidate parent/supporting
key match elements at the start of the foreign key (prefix parts are
considered non-matching).
@tparam F Function class which returns foreign key's
referenced or referencing (depending on whether
we check candidate parent or supporting key)
column name by its index.
@param fk_col_count Number of columns in the foreign key.
@param fk_columns Object of F type bound to the specific foreign key
for which parent/supporting key check is carried
out.
@param idx dd::Index object describing candidate parent/
supporting key.
@param use_hidden Use hidden elements of the key as well.
@sa fk_key_prefix_match_count(Alter_info, uint, F, KEY, KEY).
@retval Number of matching columns.
*/
template <class F>
static uint fk_key_prefix_match_count(uint fk_col_count, const F &fk_columns,
const dd::Index *idx, bool use_hidden) {
uint fk_col_idx = 0;
for (const dd::Index_element *idx_el : idx->elements()) {
if (fk_col_idx == fk_col_count) break;
if (!use_hidden && idx_el->is_hidden()) continue;
if (my_strcasecmp(system_charset_info, idx_el->column().name().c_str(),
fk_columns(fk_col_idx)) != 0)
break;
/*
Foreign keys over virtual columns are not allowed.
This is checked at earlier stage.
*/
assert(!idx_el->column().is_virtual());
/*
Prefix parts are considered non-matching.
There is a special provision which allows to treat unique keys on
POINT and BLOB columns with prefix length equal to real column
length as candidate/primary keys. However, since InnoDB doesn't
allow columns of such types in FKs, we don't need similar provision
here. So we can simply use dd::Index_element::is_prefix().
Calling Index_element::is_prefix() can be a bit expensive so
we do this after checking column name.
InnoDB doesn't set correct length for hidden index elements so
we simply assume that they use the full columns. We avoid calling
this code when it is not correct, see find_fk_parent_key().
*/
if (!idx_el->is_hidden() && idx_el->is_prefix()) break;
++fk_col_idx;
}
return fk_col_idx;
}
/**
Check if candidate parent/supporting key contains all columns from the
foreign key at its start and in the same order it is in the foreign key.
Also check that columns usage by key is acceptable, i.e. key is not over
column prefix.
@tparam F Function class which returns foreign key's
referenced or referencing (depending on whether
we check candidate parent or supporting key)
column name by its index.
@param fk_col_count Number of columns in the foreign key.
@param fk_columns Object of F type bound to the specific foreign key
for which parent/supporting key check is carried
out.
@param idx dd::Index object describing candidate parent/
supporting key.
@param use_hidden Use hidden elements of the key as well.
@sa fk_key_is_full_prefix_match(Alter_info, uint, F, KEY, KEY).
@retval True - Key is proper parent/supporting key for the foreign key.
@retval False - Key can't be parent/supporting key for the foreign key.
*/
template <class F>
static bool fk_key_is_full_prefix_match(uint fk_col_count, const F &fk_columns,
const dd::Index *idx, bool use_hidden) {
// The index must have at least same amount of elements as the foreign key.
if (fk_col_count > idx->elements().size()) return false;
uint match_count =
fk_key_prefix_match_count(fk_col_count, fk_columns, idx, use_hidden);
return (match_count == fk_col_count);
}
/**
Find parent key which matches the foreign key. Prefer unique key if possible.
@tparam F Function class which returns foreign key's column
name by its index.
@param hton Handlerton for tables' storage engine. Used to
figure out what kind of parent keys are supported
by the storage engine..
@param supporting_key Supporting key of the child. Needed to skip
supporting keys as candidate parent keys for
self referencing FKs.
@param parent_table_def dd::Table object describing the parent table.
@param fk_col_count Number of columns in the foreign key.
@param fk_columns Object of F type bound to the specific foreign key
for which parent key check is carried out.
@retval non-nullptr - pointer to dd::Index object describing the parent key.
@retval nullptr - if no parent key were found.
*/
template <class F>
static const dd::Index *find_fk_parent_key(handlerton *hton,
const dd::Index *supporting_key,
const dd::Table *parent_table_def,
uint fk_col_count,
const F &fk_columns) {
bool use_hidden = false;
if (hton->foreign_keys_flags & HTON_FKS_WITH_EXTENDED_PARENT_KEYS) {
assert(hton->foreign_keys_flags & HTON_FKS_WITH_PREFIX_PARENT_KEYS);
/*
Engine considers hidden part of key (columns from primary key
which are implicitly added to secondary keys) when determines
if it can serve as parent. Example: InnoDB.
Note that InnoDB doesn't correctly set length of these hidden
elements of keys, so we assume that they always cover the whole
column. To be able to do this we need to exclude primary keys
with prefix elements [sic!] from consideration. This means that
we won't support some exotic parent key scenarios which were
supported in 5.7. For example:
CREATE TABLE t1 (a INT, b CHAR(100), c int, KEY(c),
PRIMARY KEY (a, b(10)));
CREATE TABLE t2 (fk1 int, fk2 int,
FOREIGN KEY (fk1, fk2) REFERENCES t1 (c, a));
*/
dd::Table::Index_collection::const_iterator first_idx_it =
std::find_if(parent_table_def->indexes().cbegin(),
parent_table_def->indexes().cend(),
[](const dd::Index *i) { return !i->is_hidden(); });
if (first_idx_it != parent_table_def->indexes().cend()) {
/*
Unlike similar check in prepare_self_ref_fk_parent_key() call
to dd::Index::is_candidate_key() is not cheap, so we try to
avoid it unless absolutely necessary. As result we try to use
hidden columns even for tables without implicit primary key,
which works fine (since such tables won't have any hidden
columns matching foreign key columns).
*/
if ((*first_idx_it)->type() != dd::Index::IT_PRIMARY ||
(*first_idx_it)->is_candidate_key())
use_hidden = true;
}
}
for (const dd::Index *idx : parent_table_def->indexes()) {
// We can't use FULLTEXT or SPATIAL indexes.
if (idx->type() == dd::Index::IT_FULLTEXT ||
idx->type() == dd::Index::IT_SPATIAL)
continue;
if (hton->foreign_keys_flags &
HTON_FKS_NEED_DIFFERENT_PARENT_AND_SUPPORTING_KEYS) {
/*
The storage engine does not support using the same index for both the
supporting index and the parent index. In this case, the supporting
index cannot be a candidate parent index, and must be skipped.
*/
if (idx == supporting_key) continue;
}
// We also can't use hidden indexes.
if (idx->is_hidden()) continue;
if (hton->foreign_keys_flags & HTON_FKS_WITH_PREFIX_PARENT_KEYS) {
/*
Engine supports unique and non unique-parent keys which contain full
foreign key as its prefix. Example: InnoDB.
Primary and unique keys are sorted before non-unique keys.
So if there is suitable unique parent key we will always find
it before any non-unique key.
*/
if (fk_key_is_full_prefix_match(fk_col_count, fk_columns, idx,
use_hidden))
return idx;
} else {
/*
Default case. Engine only supports unique parent keys which
contain exactly the same columns as foreign key, possibly
in different order. Example: NDB.
*/
if ((idx->type() == dd::Index::IT_PRIMARY ||
idx->type() == dd::Index::IT_UNIQUE) &&
fk_is_key_exact_match_any_order(fk_col_count, fk_columns, idx))
return idx;
}
}
return nullptr;
}
/**
Find supporting key for the foreign key.
@param hton Handlerton for tables' storage engine. Used to
figure out what kind of supporting keys are
allowed by the storage engine.
@param table_def dd::Table object describing the child table.
@param fk dd::Foreign_key object describing the foreign
key.
@sa find_fk_supporting_key(handlerton*, Alter_info*, const KEY*, uint,
const FOREIGN_KEY*)
@retval non-nullptr - pointer to dd::Index object describing supporting key.
@retval nullptr - if no supporting key were found.
*/
static const dd::Index *find_fk_supporting_key(handlerton *hton,
const dd::Table *table_def,
const dd::Foreign_key *fk) {
uint best_match_count = 0;
const dd::Index *best_match_idx = nullptr;
auto fk_columns_lambda = [fk](uint i) {
return fk->elements()[i]->column().name().c_str();
};
for (const dd::Index *idx : table_def->indexes()) {
// We can't use FULLTEXT or SPATIAL indexes.
if (idx->type() == dd::Index::IT_FULLTEXT ||
idx->type() == dd::Index::IT_SPATIAL)
continue;
// We also can't use hidden indexes.
if (idx->is_hidden()) continue;
if (idx->algorithm() == dd::Index::IA_HASH) {
if (hton->foreign_keys_flags & HTON_FKS_WITH_SUPPORTING_HASH_KEYS) {
/*
Storage engine supports hash keys as supporting keys for foreign
keys. Hash key should contain all foreign key columns and only
them (although in any order).
Example: NDB and unique/primary key with USING HASH clause.
*/
if (fk_is_key_exact_match_any_order(fk->elements().size(),
fk_columns_lambda, idx))
return idx;
}
} else {
if (hton->foreign_keys_flags & HTON_FKS_WITH_ANY_PREFIX_SUPPORTING_KEYS) {
/*
Storage engine supports non-hash keys which have common prefix
with the foreign key as supporting keys for it. If there are
several such keys, one which shares biggest prefix with FK is
chosen.
Example: NDB and non-unique keys, or unique/primary keys without
explicit USING HASH clause.
*/
uint match_count = fk_key_prefix_match_count(
fk->elements().size(), fk_columns_lambda, idx, false);
if (match_count > best_match_count) {
best_match_count = match_count;
best_match_idx = idx;
}
} else {
/*
Default case. Storage engine supports non-hash keys which contain
full foreign key as prefix as supporting key for it.
Example: InnoDB.
SQL-layer tries to automatically create such generated key when
foreign key is created.
*/
if (fk_key_is_full_prefix_match(fk->elements().size(),
fk_columns_lambda, idx, false))
return idx;
}
}
}
return best_match_idx;
}
/*
Check if parent key for foreign key exists, set foreign key's unique
constraint name accordingly. Emit error if no parent key found.
@note Prefer unique key if possible. If parent key is non-unique
unique constraint name is set to NULL.
@note CREATE TABLE and ALTER TABLE code use this function for
non-self-referencing foreign keys.
@sa prepare_fk_parent_key(handlerton, dd::Table, dd::Table, dd::Table,
dd::Foreign_key)
@param hton Handlerton for tables' storage engine.
@param parent_table_def dd::Table object describing parent table.
@param fk[in,out] FOREIGN_KEY object describing the FK, its
unique_index_name member will be updated
if matching unique constraint is found.
@retval Operation result. False if success.
*/
static bool prepare_fk_parent_key(handlerton *hton,
const dd::Table *parent_table_def,
FOREIGN_KEY *fk) {
auto fk_columns_lambda = [fk](uint i) { return fk->fk_key_part[i].str; };
/*
Here, it is safe to pass nullptr as supporting key, since this
function is not called for self referencing foreign keys.
*/
const dd::Index *parent_key = find_fk_parent_key(
hton, nullptr, parent_table_def, fk->key_parts, fk_columns_lambda);
if (parent_key != nullptr) {
/*
We only store names of PRIMARY/UNIQUE keys in unique_index_name,
even though InnoDB allows non-unique indexes as parent keys.
*/
if (parent_key->type() == dd::Index::IT_PRIMARY ||
parent_key->type() == dd::Index::IT_UNIQUE) {
fk->unique_index_name = parent_key->name().c_str();
} else {
assert(fk->unique_index_name == nullptr);
}
return false;
}
my_error(ER_FK_NO_INDEX_PARENT, MYF(0), fk->name, fk->ref_table.str);
return true;
}
/**
Find parent key which matches the foreign key. Prefer unique key if possible.
@param hton Handlerton for tables' storage engine.
@param supporting_key Supporting key of the child. Needed to skip
supporting keys as candidate parent keys for
self referencing FKs.
@param parent_table_def dd::Table object describing the parent table.
@param fk dd::Foreign_key object describing the foreign key.
@retval non-nullptr - pointer to dd::Index object describing the parent key.
@retval nullptr - if no parent key were found.
*/
static const dd::Index *find_fk_parent_key(handlerton *hton,
const dd::Index *supporting_key,
const dd::Table *parent_table_def,
const dd::Foreign_key *fk) {
auto fk_columns_lambda = [fk](uint i) {
return fk->elements()[i]->referenced_column_name().c_str();
};
return find_fk_parent_key(hton, supporting_key, parent_table_def,
fk->elements().size(), fk_columns_lambda);
}
bool prepare_fk_parent_key(handlerton *hton, const dd::Table *parent_table_def,
const dd::Table *old_parent_table_def,
const dd::Table *old_child_table_def,
bool is_self_referencing_fk, dd::Foreign_key *fk) {
const dd::Index *supporting_key = nullptr;
/*
For self referencing foreign keys, we should identify the supporting
key to make sure it is not considered as a candidate parent key,
unless the SE supports this. This function will be called for self
referencing foreign keys only during upgrade from 5.7.
*/
if (is_self_referencing_fk &&
(hton->foreign_keys_flags &
HTON_FKS_NEED_DIFFERENT_PARENT_AND_SUPPORTING_KEYS)) {
supporting_key = find_fk_supporting_key(hton, parent_table_def, fk);
}
const dd::Index *parent_key =
find_fk_parent_key(hton, supporting_key, parent_table_def, fk);
if (parent_key == nullptr) {
// No matching parent key in new table definition.
if (old_parent_table_def == nullptr) {
/*
No old version of parent table definition. This must be CREATE
TABLE or RENAME TABLE (or possibly ALTER TABLE RENAME).
*/
my_error(ER_FK_NO_INDEX_PARENT, MYF(0), fk->name().c_str(),
fk->referenced_table_name().c_str());
} else {
/*
This is ALTER TABLE which dropped parent key.
To report error we find original foreign key definition first.
*/
assert(old_child_table_def != nullptr);
auto same_name = [fk](const dd::Foreign_key *el) {
return my_strcasecmp(system_charset_info, fk->name().c_str(),
el->name().c_str()) == 0;
};
auto old_fk =
std::find_if(old_child_table_def->foreign_keys().begin(),
old_child_table_def->foreign_keys().end(), same_name);
assert(old_fk != old_child_table_def->foreign_keys().end());
/*
This function is normally called only for non-self referencing foreign
keys. The only exception is during upgrade from 5.7, in which case
old_parent_table_def == nullptr, which means that a different execution
path is taken above. Hence, it is safe to submit nullptr as the
supporting key in the call to find_fk_parent_key() below.
*/
assert(!is_self_referencing_fk);
/*
And then try to find original parent key name. Just getting
unique constraint name won't work for non-unique parent key.
Ideally we should be using handlerton of old table version
below, however, in practice, new table version's handlerton
works just fine, since we do not allow changing of storage
engines for tables with foreign keys.
*/
const dd::Index *old_pk =
find_fk_parent_key(hton, nullptr, old_parent_table_def, *old_fk);
my_error(ER_DROP_INDEX_FK, MYF(0),
old_pk ? old_pk->name().c_str() : "<unknown key name>");
}
return true;
}
/*
If parent key is not PRIMARY/UNIQUE set UNIQUE_CONSTRAINT_NAME to
NULL value. This is done by setting the name to "", which is
interpreted as NULL when it is stored to the DD tables.
*/
if (parent_key->type() == dd::Index::IT_PRIMARY ||
parent_key->type() == dd::Index::IT_UNIQUE) {
fk->set_unique_constraint_name(parent_key->name().c_str());
} else {
fk->set_unique_constraint_name("");
}
return false;
}
/**
Helper which builds Ha_fk_column_type describing column type from
its Create_field object.
@sa fill_dd_columns_from_create_fields().
*/
static void fill_ha_fk_column_type(Ha_fk_column_type *fk_column_type,
const Create_field *field) {
fk_column_type->type = dd::get_new_field_type(field->sql_type);
fk_column_type->char_length = field->max_display_width_in_bytes();
fk_column_type->field_charset = field->charset;
fk_column_type->elements_count = field->interval ? field->interval->count : 0;
fk_column_type->numeric_scale = 0;
dd::get_field_numeric_scale(field, &fk_column_type->numeric_scale);
fk_column_type->is_unsigned = field->is_unsigned;
}
/**
Helper which builds Ha_fk_column_type describing column type from
its dd::Column object.
*/
static bool fill_ha_fk_column_type(Ha_fk_column_type *fk_column_type,
const dd::Column *column) {
fk_column_type->type = column->type();
fk_column_type->char_length = column->char_length();
fk_column_type->field_charset = dd_get_mysql_charset(column->collation_id());
if (fk_column_type->field_charset == nullptr) {
my_printf_error(ER_UNKNOWN_COLLATION,
"invalid collation id %llu for table %s, column %s", MYF(0),
column->collation_id(), column->table().name().c_str(),
column->name().c_str());
return true;
}
fk_column_type->elements_count = column->elements_count();
fk_column_type->numeric_scale = column->numeric_scale();
fk_column_type->is_unsigned = column->is_unsigned();
return false;
}
/**
Prepare FOREIGN_KEY struct with info about a foreign key.
@param thd Thread handle.
@param create_info Create info from parser.
@param alter_info Alter_info structure describing ALTER TABLE.
@param db Database name.
@param table_name Table name.
@param is_partitioned Indicates whether table is partitioned.
@param key_info_buffer Array of indexes.
@param key_count Number of indexes.
@param fk_info_all FOREIGN_KEY array with foreign keys which were
already processed.
@param fk_number Number of foreign keys which were already
processed.
@param se_supports_fks Indicates whether SE supports FKs.
If not only basic FK validation is
performed.
@param find_parent_key Indicates whether we need to lookup name of unique
constraint in parent table for the FK.
@param[in,out] fk_key Parser info about new FK to
prepare.
@param[in,out] fk_max_generated_name_number Max value of number component
among existing generated foreign
key names.
@param[out] fk_info Struct to populate.
@retval true if error (error reported), false otherwise.
*/
static bool prepare_foreign_key(THD *thd, HA_CREATE_INFO *create_info,
Alter_info *alter_info, const char *db,
const char *table_name, bool is_partitioned,
KEY *key_info_buffer, uint key_count,
const FOREIGN_KEY *fk_info_all, uint fk_number,
bool se_supports_fks, bool find_parent_key,
Foreign_key_spec *fk_key,
uint *fk_max_generated_name_number,
FOREIGN_KEY *fk_info) {
DBUG_TRACE;
// FKs are not supported for temporary tables.
if (create_info->options & HA_LEX_CREATE_TMP_TABLE) {
my_error(ER_CANNOT_ADD_FOREIGN, MYF(0), table_name);
return true;
}
// FKs are not supported with CREATE TABLE ... START TRANSACTION.
if (create_info->m_transactional_ddl) {
my_error(ER_FOREIGN_KEY_WITH_ATOMIC_CREATE_SELECT, MYF(0));
return true;
}
// Validate checks (among other things) that index prefixes are
// not used and that generated columns are not used with
// SET NULL and ON UPDATE CASCASE. Since this cannot change once
// the FK has been made, it is enough to check it for new FKs.
if (fk_key->validate(thd, table_name, alter_info->create_list)) return true;
if (!se_supports_fks) return false;
if (fk_key->has_explicit_name) {
assert(fk_key->name.str);
fk_info->name = fk_key->name.str;
} else {
fk_info->name = generate_fk_name(table_name, create_info->db_type,
fk_max_generated_name_number);
/*
Update Foreign_key_spec::name member as some storage engines
(e.g. NDB) rely on this information. To make this safe for
prepared statement re-execution we have to employ
Foreign_key_spec::has_explicit_name. Solving this issue in a
better way requires change of approach which NDB uses to get
info about added foreign keys.
*/
fk_key->name.str = thd->stmt_arena->mem_strdup(fk_info->name);
fk_key->name.length = strlen(fk_info->name);
// Length of generated name should be checked as well.
if (check_string_char_length(to_lex_cstring(fk_info->name), "",
NAME_CHAR_LEN, system_charset_info, true)) {
my_error(ER_TOO_LONG_IDENT, MYF(0), fk_info->name);
return true;
}
}
/*
Check that we are not creating several foreign keys with the same
name over same table. This is mostly to avoid expensive phases of
ALTER TABLE in such a case. Without this check the problem will be
detected at the later stage when info about foreign keys is stored
in data-dictionary.
*/
for (uint fk_idx = 0; fk_idx < fk_number; fk_idx++) {
if (!my_strcasecmp(system_charset_info, fk_info_all[fk_idx].name,
fk_info->name)) {
my_error(ER_FK_DUP_NAME, MYF(0), fk_info->name);
return true;
}
}
fk_info->key_parts = fk_key->columns.size();
/*
In --lower-case-table-names=2 mode we are to use lowercased versions of
parent db and table names for acquiring MDL and lookup, but still need
to store their original versions in the data-dictionary.
*/
if (lower_case_table_names == 2) {
fk_info->ref_db = fk_key->orig_ref_db;
fk_info->ref_table = fk_key->orig_ref_table;
} else {
fk_info->ref_db = fk_key->ref_db;
fk_info->ref_table = fk_key->ref_table;
}
fk_info->delete_opt = fk_key->delete_opt;
fk_info->update_opt = fk_key->update_opt;
fk_info->match_opt = fk_key->match_opt;
fk_info->key_part = reinterpret_cast<LEX_CSTRING *>(
thd->mem_calloc(sizeof(LEX_CSTRING) * fk_key->columns.size()));
fk_info->fk_key_part = reinterpret_cast<LEX_CSTRING *>(
thd->mem_calloc(sizeof(LEX_CSTRING) * fk_key->columns.size()));
Prealloced_array<Create_field *, 1> referencing_fields(PSI_INSTRUMENT_ME);
for (size_t column_nr = 0; column_nr < fk_key->ref_columns.size();
column_nr++) {
const Key_part_spec *col = fk_key->columns[column_nr];
/* Check that referencing column exists and is not virtual. */
List_iterator<Create_field> find_it(alter_info->create_list);
Create_field *find;
while ((find = find_it++)) {
if (my_strcasecmp(system_charset_info, col->get_field_name(),
find->field_name) == 0) {
break;
}
}
if (find == nullptr) {
/*
In practice this should not happen as wrong column name is caught
during generated index processing and error with good enough message
is reported. So we don't fuss about error message here.
*/
my_error(ER_CANNOT_ADD_FOREIGN, MYF(0));
return true;
}
if (find->is_virtual_gcol()) {
my_error(ER_FK_CANNOT_USE_VIRTUAL_COLUMN, MYF(0), fk_info->name,
col->get_field_name());
return true;
}
/*
Foreign keys with SET NULL as one of referential actions do not
make sense if any of referencing columns are non-nullable, so
we prohibit them.
*/
if ((fk_info->delete_opt == FK_OPTION_SET_NULL ||
fk_info->update_opt == FK_OPTION_SET_NULL) &&
find->flags & NOT_NULL_FLAG) {
my_error(ER_FK_COLUMN_NOT_NULL, MYF(0), col->get_field_name(),
fk_info->name);
return true;
}
/*
Check constraints evaluation is done before writing row to the storage
engine but foreign key referential actions SET NULL, UPDATE CASCADE and
SET DEFAULT are executed by the engine. Check constraints can not be
evaluated for the these foreign key referential actions, so prohibit
them.
*/
if (fk_info->delete_opt == FK_OPTION_SET_NULL ||
fk_info->delete_opt == FK_OPTION_DEFAULT ||
fk_info->update_opt == FK_OPTION_SET_NULL ||
fk_info->update_opt == FK_OPTION_DEFAULT ||
fk_info->update_opt == FK_OPTION_CASCADE) {
for (auto &cc_spec : alter_info->check_constraint_spec_list) {
if (cc_spec->expr_refers_column(find->field_name)) {
my_error(ER_CHECK_CONSTRAINT_CLAUSE_USING_FK_REFER_ACTION_COLUMN,
MYF(0), find->field_name, cc_spec->name.str, fk_info->name);
return true;
}
}
}
referencing_fields.push_back(find);
/*
Unlike for referenced columns, for referencing columns it doesn't matter
which version of column name (i.e. coming from FOREIGN KEY clause or
coming from table definition, they can differ in case) is stored in
FOREIGN_KEY structure. Information about referencing columns is stored
as their IDs in the data dictionary and as pointer to dd::Column object
in in-memory representation.
*/
fk_info->key_part[column_nr].str = col->get_field_name();
fk_info->key_part[column_nr].length = std::strlen(col->get_field_name());
/*
Save version of referenced column name coming from FOREIGN KEY clause.
Later we will replace it with version of name coming from parent table
definition if possible (these versions can differ in case).
*/
const Key_part_spec *fk_col = fk_key->ref_columns[column_nr];
fk_info->fk_key_part[column_nr].str = fk_col->get_field_name();
fk_info->fk_key_part[column_nr].length =
std::strlen(fk_col->get_field_name());
}
if (find_parent_key) {
/*
Check if we are trying to add foreign key to partitioned table
and table's storage engine doesn't support foreign keys over
partitioned tables.
*/
if (is_partitioned &&
(!create_info->db_type->partition_flags ||
create_info->db_type->partition_flags() & HA_CANNOT_PARTITION_FK)) {
my_error(ER_FOREIGN_KEY_ON_PARTITIONED, MYF(0));
return true;
}
const KEY *supporting_key = find_fk_supporting_key(
create_info->db_type, alter_info, key_info_buffer, key_count, fk_info);
if (supporting_key == nullptr) {
/*
Since we always add generated supporting key when adding new
foreign key the failure to find key above is likely to mean
that generated key was auto-converted to spatial key or it is
some other corner case.
*/
my_error(ER_FK_NO_INDEX_CHILD, MYF(0), fk_info->name, table_name);
return true;
}
if (my_strcasecmp(table_alias_charset, fk_info->ref_db.str, db) == 0 &&
my_strcasecmp(table_alias_charset, fk_info->ref_table.str,
table_name) == 0) {
// FK which references the same table on which it is defined.
for (uint i = 0; i < fk_info->key_parts; i++) {
List_iterator_fast<Create_field> field_it(alter_info->create_list);
const Create_field *field;
// Check that referenced column exists and is non-virtual.
while ((field = field_it++)) {
if (my_strcasecmp(system_charset_info, field->field_name,
fk_info->fk_key_part[i].str) == 0)
break;
}
if (field == nullptr) {
my_error(ER_FK_NO_COLUMN_PARENT, MYF(0), fk_info->fk_key_part[i].str,
fk_info->name, fk_info->ref_table.str);
return true;
}
if (field->is_virtual_gcol()) {
my_error(ER_FK_CANNOT_USE_VIRTUAL_COLUMN, MYF(0), fk_info->name,
fk_info->fk_key_part[i].str);
return true;
}
// Check that types of referencing and referenced columns are
// compatible.
if (create_info->db_type->check_fk_column_compat) {
Ha_fk_column_type child_column_type, parent_column_type;
fill_ha_fk_column_type(&child_column_type, referencing_fields[i]);
fill_ha_fk_column_type(&parent_column_type, field);
if (!create_info->db_type->check_fk_column_compat(
&child_column_type, &parent_column_type, true)) {
my_error(ER_FK_INCOMPATIBLE_COLUMNS, MYF(0),
fk_info->key_part[i].str, fk_info->fk_key_part[i].str,
fk_info->name);
return true;
}
}
/*
Be compatible with 5.7. Use version of referenced column name
coming from parent table definition and not the one that was
used in FOREIGN KEY clause.
*/
fk_info->fk_key_part[i].str = field->field_name;
fk_info->fk_key_part[i].length = std::strlen(field->field_name);
}
if (prepare_self_ref_fk_parent_key(create_info->db_type, alter_info,
key_info_buffer, key_count,
supporting_key, nullptr, fk_info))
return true;
} else {
/*
FK which references other table than one on which it is defined.
Check that table exists and its storage engine as the first step.
*/
const dd::Table *parent_table_def = nullptr;
if (thd->dd_client()->acquire(fk_info->ref_db.str, fk_info->ref_table.str,
&parent_table_def))
return true;
handlerton *parent_hton = nullptr;
if (parent_table_def != nullptr &&
dd::table_storage_engine(thd, parent_table_def, &parent_hton))
return true;
if (parent_table_def == nullptr || create_info->db_type != parent_hton) {
if (!(thd->variables.option_bits & OPTION_NO_FOREIGN_KEY_CHECKS)) {
my_error(ER_FK_CANNOT_OPEN_PARENT, MYF(0), fk_info->ref_table.str);
return true;
}
/*
Missing parent table is legitimate case in FOREIGN_KEY_CHECKS=0 mode.
FOREIGN_KEY::unique_index_name should be already set to value which
corresponds to NULL value in FOREIGN_KEYS.UNIQUE_CONSTRAINT_NAME
column.
For compatibility reasons we treat difference in parent SE in the same
way as missing parent table.
*/
assert(fk_info->unique_index_name == nullptr);
} else {
/*
Check that parent table is not partitioned or storage engine
supports foreign keys over partitioned tables.
*/
if (parent_table_def->partition_type() != dd::Table::PT_NONE &&
(!parent_hton->partition_flags ||
parent_hton->partition_flags() & HA_CANNOT_PARTITION_FK)) {
my_error(ER_FOREIGN_KEY_ON_PARTITIONED, MYF(0));
return true;
}
/* Then check that referenced columns exist and are non-virtual. */
for (uint i = 0; i < fk_info->key_parts; i++) {
const char *ref_column_name = fk_info->fk_key_part[i].str;
auto same_column_name = [ref_column_name](const dd::Column *c) {
return my_strcasecmp(system_charset_info, c->name().c_str(),
ref_column_name) == 0;
};
auto ref_column =
std::find_if(parent_table_def->columns().begin(),
parent_table_def->columns().end(), same_column_name);
if (ref_column == parent_table_def->columns().end()) {
my_error(ER_FK_NO_COLUMN_PARENT, MYF(0), ref_column_name,
fk_info->name, fk_info->ref_table.str);
return true;
}
if ((*ref_column)->is_virtual()) {
my_error(ER_FK_CANNOT_USE_VIRTUAL_COLUMN, MYF(0), fk_info->name,
ref_column_name);
return true;
}
// Check that types of referencing and referenced columns are
// compatible.
if (create_info->db_type->check_fk_column_compat) {
Ha_fk_column_type child_column_type, parent_column_type;
fill_ha_fk_column_type(&child_column_type, referencing_fields[i]);
if (fill_ha_fk_column_type(&parent_column_type, *ref_column))
return true;
if (!create_info->db_type->check_fk_column_compat(
&child_column_type, &parent_column_type, true)) {
my_error(ER_FK_INCOMPATIBLE_COLUMNS, MYF(0),
fk_info->key_part[i].str, ref_column_name,
fk_info->name);
return true;
}
}
/*
Be compatible with 5.7. Use version of referenced column name
coming from parent table definition and not the one that was
used in FOREIGN KEY clause.
*/
fk_info->fk_key_part[i].str = (*ref_column)->name().c_str();
fk_info->fk_key_part[i].length = (*ref_column)->name().length();
}
if (prepare_fk_parent_key(create_info->db_type, parent_table_def,
fk_info))
return true;
}
}
} else {
assert(fk_info->unique_index_name == nullptr);
}
return false;
}
/**
Check that pre-existing self-referencing foreign key or an orphan
non-self-referencing foreign key become non-orphan/adopted self-referencing
foreign key as a result of table rename operation will be valid after ALTER
TABLE, i.e. that table has parent index and types of child and parent
columns are compatible. Also update DD.UNIQUE_CONSTRAINT_NAME accordingly.
@param thd Thread context..
@param create_info HA_CREATE_INFO describing table.
@param alter_info Alter_info structure describing
table.
@param key_info Array of indexes.
@param key_count Number of indexes.
@param supporting_key Supporting key for the foreign key.
@param existing_fks_table dd::Table object for table version
from which pre-existing foreign keys
come from. Needed for error
reporting.
@param referencing_fields List of foreign key referencing fields.
@param[in,out] fk FOREIGN_KEY object describing
pre-existing foreign key.
@retval true if error (error reported), false otherwise.
*/
static bool prepare_preexisting_self_ref_foreign_key(
THD *thd, HA_CREATE_INFO *create_info, Alter_info *alter_info,
KEY *key_info, uint key_count, const KEY *supporting_key,
const dd::Table *existing_fks_table, FOREIGN_KEY *fk,
const Prealloced_array<Create_field *, 1> &referencing_fields) {
Create_field *sql_field;
List_iterator<Create_field> it(alter_info->create_list);
// Check that types of child and parent columns are still compatible.
if (create_info->db_type->check_fk_column_compat) {
for (size_t j = 0; j < fk->key_parts; j++) {
it.rewind();
while ((sql_field = it++)) {
if (my_strcasecmp(system_charset_info, fk->fk_key_part[j].str,
sql_field->field_name) == 0)
break;
}
// We already have checked that referenced column exists.
assert(sql_field != nullptr);
Ha_fk_column_type child_column_type, parent_column_type;
fill_ha_fk_column_type(&child_column_type, referencing_fields[j]);
fill_ha_fk_column_type(&parent_column_type, sql_field);
/*
Allow charset discrepancies between child and parent columns
in FOREIGN_KEY_CHECKS=0 mode. This provides a way to change
charset of column which participates in a foreign key without
dropping the latter.
We allow such discrepancies even for foreign keys that has same
table as child and parent in order to be consistent with general
case, in which there is no way to change charset of both child
and parent columns simultaneously.
We do not allow creation of same discrepancies when adding
new foreign key using CREATE/ALTER TABLE or adding new parent
for existing orphan foreign key using CREATE/RENAME TABLE.
*/
if (!create_info->db_type->check_fk_column_compat(
&child_column_type, &parent_column_type,
!(thd->variables.option_bits & OPTION_NO_FOREIGN_KEY_CHECKS))) {
my_error(ER_FK_INCOMPATIBLE_COLUMNS, MYF(0), fk->key_part[j].str,
fk->fk_key_part[j].str, fk->name);
return true;
}
}
}
/*
Check that foreign key still has matching parent key and adjust
DD.UNIQUE_CONSTRAINT_NAME accordingly.
*/
if (prepare_self_ref_fk_parent_key(create_info->db_type, alter_info, key_info,
key_count, supporting_key,
existing_fks_table, fk))
return true;
return false;
}
/**
Check that pre-existing foreign key will be still valid after ALTER TABLE,
i.e. that table still has supporting index and types of child and parent
columns are still compatible. Also if necessary check that there is parent
index and update DD.UNIQUE_CONSTRAINT_NAME accordingly.
@param thd Thread context..
@param create_info HA_CREATE_INFO describing table.
@param alter_info Alter_info structure describing
ALTER TABLE.
@param schema_name Table schema name.
@param table_name Table name.
@param key_info Array of indexes.
@param key_count Number of indexes.
@param existing_fks_table dd::Table object for table version
from which pre-existing foreign keys
come from. Needed for error
reporting.
@param[in,out] fk FOREIGN_KEY object describing
pre-existing foreign key.
@retval true if error (error reported), false otherwise.
*/
static bool prepare_preexisting_foreign_key(
THD *thd, HA_CREATE_INFO *create_info, Alter_info *alter_info,
const char *schema_name, const char *table_name, KEY *key_info,
uint key_count, const dd::Table *existing_fks_table, FOREIGN_KEY *fk) {
Create_field *sql_field;
List_iterator<Create_field> it(alter_info->create_list);
Prealloced_array<Create_field *, 1> referencing_fields(PSI_INSTRUMENT_ME);
for (size_t j = 0; j < fk->key_parts; j++) {
it.rewind();
while ((sql_field = it++)) {
if (my_strcasecmp(system_charset_info, fk->key_part[j].str,
sql_field->field_name) == 0)
break;
}
// We already have checked that referencing column exists.
assert(sql_field != nullptr);
// Save Create_field to be used in type compatibility check later.
referencing_fields.push_back(sql_field);
/*
Check if this foreign key has SET NULL as one of referential actions
and one of its referencing columns became non-nullable.
We do this check here rather than in transfer_preexisting_foreign_keys()
in order to avoid complicated handling of case when column becomes
non-nullable implicitly because it is part of PRIMARY KEY added.
*/
if ((fk->delete_opt == FK_OPTION_SET_NULL ||
fk->update_opt == FK_OPTION_SET_NULL) &&
(sql_field->flags & NOT_NULL_FLAG)) {
my_error(ER_FK_COLUMN_NOT_NULL, MYF(0), fk->key_part[j].str, fk->name);
return true;
}
/*
Check constraints evaluation is done before writing row to the storage
engine but foreign key referential actions SET NULL, UPDATE CASCADE and
SET DEFAULT are executed by the engine. Check constraints can not be
evaluated for the these foreign key referential actions, so we prohibit
them.
*/
if (fk->delete_opt == FK_OPTION_SET_NULL ||
fk->delete_opt == FK_OPTION_DEFAULT ||
fk->update_opt == FK_OPTION_SET_NULL ||
fk->update_opt == FK_OPTION_DEFAULT ||
fk->update_opt == FK_OPTION_CASCADE) {
for (auto &cc_spec : alter_info->check_constraint_spec_list) {
if (cc_spec->expr_refers_column(sql_field->field_name)) {
my_error(ER_CHECK_CONSTRAINT_CLAUSE_USING_FK_REFER_ACTION_COLUMN,
MYF(0), sql_field->field_name, cc_spec->name.str, fk->name);
return true;
}
}
}
}
// Check that we still have supporting index on child table.
const KEY *supporting_key = find_fk_supporting_key(
create_info->db_type, alter_info, key_info, key_count, fk);
if (supporting_key == nullptr) {
/*
If there is no supporting index, it must have been dropped by
this ALTER TABLE. Find old foreign key definition and supporting
index which matched it in old table definition in order to report
nice error.
*/
auto same_name = [fk](const dd::Foreign_key *el) {
return my_strcasecmp(system_charset_info, fk->name, el->name().c_str()) ==
0;
};
auto old_fk =
std::find_if(existing_fks_table->foreign_keys().begin(),
existing_fks_table->foreign_keys().end(), same_name);
assert(old_fk != existing_fks_table->foreign_keys().end());
const dd::Index *old_key = find_fk_supporting_key(
create_info->db_type, existing_fks_table, *old_fk);
my_error(ER_DROP_INDEX_FK, MYF(0),
old_key ? old_key->name().c_str() : "<unknown key name>");
return true;
}
if (my_strcasecmp(table_alias_charset, fk->ref_db.str, schema_name) == 0 &&
my_strcasecmp(table_alias_charset, fk->ref_table.str, table_name) == 0) {
// Pre-existing foreign key which has same table as parent and child.
// TODO: Run this check only in cases when column type is really changed in
// order to avoid unnecessary work.
if (prepare_preexisting_self_ref_foreign_key(
thd, create_info, alter_info, key_info, key_count, supporting_key,
existing_fks_table, fk, referencing_fields))
return true;
} else if (alter_info->new_table_name.str != nullptr &&
my_strcasecmp(table_alias_charset, fk->ref_db.str,
alter_info->new_db_name.str) == 0 &&
my_strcasecmp(table_alias_charset, fk->ref_table.str,
alter_info->new_table_name.str) == 0) {
/*
Pre-existing orphan non-self-referencing foreign key become
non-orphan/adopted self-referencing foreign key as a result of table
rename operation.
*/
if (prepare_preexisting_self_ref_foreign_key(
thd, create_info, alter_info, key_info, key_count, supporting_key,
nullptr, fk, referencing_fields))
return true;
} else {
/*
Pre-existing foreign key with different tables as child and parent.
There is no need to update DD.UNIQUE_CONSTRAINT_NAME.
Parent table definition is needed to check column types compatibility.
Skip check if parent table doesn't exist or uses wrong engine.
*/
if (create_info->db_type->check_fk_column_compat) {
const dd::Table *parent_table_def = nullptr;
if (thd->dd_client()->acquire(fk->ref_db.str, fk->ref_table.str,
&parent_table_def))
return true;
handlerton *parent_hton = nullptr;
if (parent_table_def != nullptr &&
dd::table_storage_engine(thd, parent_table_def, &parent_hton))
return true;
if (parent_table_def != nullptr && create_info->db_type == parent_hton) {
for (size_t j = 0; j < fk->key_parts; j++) {
const char *ref_column_name = fk->fk_key_part[j].str;
auto same_column_name = [ref_column_name](const dd::Column *c) {
return my_strcasecmp(system_charset_info, c->name().c_str(),
ref_column_name) == 0;
};
auto ref_column =
std::find_if(parent_table_def->columns().begin(),
parent_table_def->columns().end(), same_column_name);
assert(ref_column != parent_table_def->columns().end());
Ha_fk_column_type child_column_type, parent_column_type;
fill_ha_fk_column_type(&child_column_type, referencing_fields[j]);
if (fill_ha_fk_column_type(&parent_column_type, *ref_column))
return true;
/*
See comment in prepare_preexisting_self_ref_foreign_key() about
allowing charset discrepancies between child and parent columns in
FOREIGN_KEY_CHECKS=0 mode.
*/
if (!create_info->db_type->check_fk_column_compat(
&child_column_type, &parent_column_type,
!(thd->variables.option_bits &
OPTION_NO_FOREIGN_KEY_CHECKS))) {
my_error(ER_FK_INCOMPATIBLE_COLUMNS, MYF(0), fk->key_part[j].str,
ref_column_name, fk->name);
return true;
}
}
}
}
}
return false;
}
static bool prepare_key(
THD *thd, const char *error_schema_name, const char *error_table_name,
HA_CREATE_INFO *create_info, List<Create_field> *create_list,
const Key_spec *key, KEY **key_info_buffer, KEY *key_info,
KEY_PART_INFO **key_part_info, Mem_root_array<const KEY *> &keys_to_check,
uint key_number, const handler *file, int *auto_increment) {
DBUG_TRACE;
assert(create_list);
assert(key_info->flags == 0); // No flags should be set yet
/*
General checks.
*/
if (key->columns.size() > file->max_key_parts() &&
key->type != KEYTYPE_SPATIAL) {
my_error(ER_TOO_MANY_KEY_PARTS, MYF(0), file->max_key_parts());
return true;
}
if (check_string_char_length(key->name, "", NAME_CHAR_LEN,
system_charset_info, true)) {
my_error(ER_TOO_LONG_IDENT, MYF(0), key->name.str);
return true;
}
if (key->name.str && (key->type != KEYTYPE_PRIMARY) &&
!my_strcasecmp(system_charset_info, key->name.str, primary_key_name)) {
my_error(ER_WRONG_NAME_FOR_INDEX, MYF(0), key->name.str);
return true;
}
/* Create the key name based on the first column (if not given) */
if (key->type == KEYTYPE_PRIMARY)
key_info->name = primary_key_name;
else if (key->name.str)
key_info->name = key->name.str;
else {
const Key_part_spec *first_col = key->columns[0];
List_iterator<Create_field> it(*create_list);
Create_field *sql_field;
while ((sql_field = it++) &&
my_strcasecmp(system_charset_info, first_col->get_field_name(),
sql_field->field_name))
;
if (!sql_field) {
my_error(ER_KEY_COLUMN_DOES_NOT_EXITS, MYF(0),
first_col->get_field_name());
return true;
}
key_info->name =
make_unique_key_name(sql_field->field_name, *key_info_buffer, key_info);
}
if (key->type != KEYTYPE_PRIMARY &&
check_if_keyname_exists(key_info->name, *key_info_buffer, key_info)) {
my_error(ER_DUP_KEYNAME, MYF(0), key_info->name);
return true;
}
if (!key_info->name || check_column_name(to_lex_cstring(key_info->name))) {
my_error(ER_WRONG_NAME_FOR_INDEX, MYF(0), key_info->name);
return true;
}
key_info->comment.length = key->key_create_info.comment.length;
key_info->comment.str = key->key_create_info.comment.str;
// Validate index comment string
std::string invalid_sub_str;
if (is_invalid_string({key_info->comment.str, key_info->comment.length},
system_charset_info, invalid_sub_str)) {
my_error(ER_COMMENT_CONTAINS_INVALID_STRING, MYF(0), "index",
(std::string(error_schema_name) + "." +
std::string(error_table_name) + "." + std::string(key->name.str))
.c_str(),
system_charset_info->csname, invalid_sub_str.c_str());
return true;
}
if (validate_comment_length(thd, key_info->comment.str,
&key_info->comment.length, INDEX_COMMENT_MAXLEN,
ER_TOO_LONG_INDEX_COMMENT, key_info->name))
return true;
if (key_info->comment.length > 0) key_info->flags |= HA_USES_COMMENT;
key_info->engine_attribute = key->key_create_info.m_engine_attribute;
if (key_info->engine_attribute.length > 0)
key_info->flags |= HA_INDEX_USES_ENGINE_ATTRIBUTE;
key_info->secondary_engine_attribute =
key->key_create_info.m_secondary_engine_attribute;
if (key_info->secondary_engine_attribute.length > 0)
key_info->flags |= HA_INDEX_USES_SECONDARY_ENGINE_ATTRIBUTE;
#ifndef NDEBUG
decltype(key_info->flags) flags_before_switch = key_info->flags;
#endif /* NDEBUG */
switch (key->type) {
case KEYTYPE_MULTIPLE:
break;
case KEYTYPE_FULLTEXT:
if (!(file->ha_table_flags() & HA_CAN_FULLTEXT)) {
my_error(ER_TABLE_CANT_HANDLE_FT, MYF(0));
return true;
}
key_info->flags |= HA_FULLTEXT;
if (key->key_create_info.parser_name.str) {
key_info->parser_name = key->key_create_info.parser_name;
key_info->flags |= HA_USES_PARSER;
} else
key_info->parser_name = NULL_CSTR;
break;
case KEYTYPE_SPATIAL:
if (!(file->ha_table_flags() & HA_CAN_RTREEKEYS)) {
my_error(ER_TABLE_CANT_HANDLE_SPKEYS, MYF(0));
return true;
}
if (key->columns.size() != 1) {
my_error(ER_TOO_MANY_KEY_PARTS, MYF(0), 1);
return true;
}
key_info->flags |= HA_SPATIAL;
break;
case KEYTYPE_PRIMARY:
case KEYTYPE_UNIQUE:
key_info->flags |= HA_NOSAME;
break;
default:
assert(false);
return true;
}
// Verify that no bits set before switch have been cleared.
assert((key_info->flags & flags_before_switch) == flags_before_switch);
if (key->generated) key_info->flags |= HA_GENERATED_KEY;
key_info->algorithm = key->key_create_info.algorithm;
key_info->user_defined_key_parts = key->columns.size();
key_info->actual_key_parts = key_info->user_defined_key_parts;
key_info->key_part = *key_part_info;
key_info->usable_key_parts = key_number;
key_info->is_algorithm_explicit = false;
key_info->is_visible = key->key_create_info.is_visible;
/*
Make SPATIAL to be RTREE by default
SPATIAL only on BLOB or at least BINARY, this
actually should be replaced by special GEOM type
in near future when new frm file is ready
checking for proper key parts number:
*/
if (key_info->flags & HA_SPATIAL) {
assert(!key->key_create_info.is_algorithm_explicit);
key_info->algorithm = HA_KEY_ALG_RTREE;
} else if (key_info->flags & HA_FULLTEXT) {
assert(!key->key_create_info.is_algorithm_explicit);
key_info->algorithm = HA_KEY_ALG_FULLTEXT;
} else {
if (key->key_create_info.is_algorithm_explicit) {
if (key->key_create_info.algorithm != HA_KEY_ALG_RTREE) {
/*
If key algorithm was specified explicitly check if it is
supported by SE.
*/
if (file->is_index_algorithm_supported(
key->key_create_info.algorithm)) {
key_info->is_algorithm_explicit = true;
key_info->algorithm = key->key_create_info.algorithm;
} else {
/*
If explicit algorithm is not supported by SE, replace it with
default one. Don't mark key algorithm as explicitly specified
in this case.
*/
key_info->algorithm = file->get_default_index_algorithm();
push_warning_printf(
thd, Sql_condition::SL_NOTE, ER_UNSUPPORTED_INDEX_ALGORITHM,
ER_THD(thd, ER_UNSUPPORTED_INDEX_ALGORITHM),
((key->key_create_info.algorithm == HA_KEY_ALG_HASH) ? "HASH"
: "BTREE"));
}
}
} else {
/*
If key algorithm was not explicitly specified used default one for
this SE. Interesting side-effect of this is that ALTER TABLE will
cause index rebuild if SE default changes.
Assert that caller doesn't use any non-default algorithm in this
case as such setting is ignored anyway.
*/
assert(key->key_create_info.algorithm == HA_KEY_ALG_SE_SPECIFIC);
key_info->algorithm = file->get_default_index_algorithm();
}
}
/*
Take block size from key part or table part
TODO: Add warning if block size changes. We can't do it here, as
this may depend on the size of the key
*/
key_info->block_size =
(key->key_create_info.block_size ? key->key_create_info.block_size
: create_info->key_block_size);
if (key_info->block_size) key_info->flags |= HA_USES_BLOCK_SIZE;
const CHARSET_INFO *ft_key_charset = nullptr; // for FULLTEXT
key_info->key_length = 0;
for (size_t column_nr = 0; column_nr < key->columns.size();
column_nr++, (*key_part_info)++) {
if (prepare_key_column(thd, create_info, create_list, key,
key->columns[column_nr], column_nr, key_info,
*key_part_info, file, auto_increment,
&ft_key_charset))
return true;
}
key_info->actual_flags = key_info->flags;
if (key_info->key_length > file->max_key_length() &&
key->type != KEYTYPE_FULLTEXT) {
my_error(ER_TOO_LONG_KEY, MYF(0), file->max_key_length());
if (thd->is_error()) // May be silenced - see Bug#20629014
return true;
}
/*
We only check for duplicate indexes if it is requested and the key is
not auto-generated and non-PRIMARY.
Check is requested if the key was explicitly created or altered
(Index is altered/column associated with it is dropped) by the user
(unless it's a foreign key).
The fact that we have only one PRIMARY key for the table is checked
elsewhere.
At this point we simply add qualifying keys to the list, so we can
perform check later when we properly construct KEY objects for all
keys.
*/
if (key->check_for_duplicate_indexes && !key->generated &&
key->type != KEYTYPE_PRIMARY) {
if (keys_to_check.push_back(key_info)) return true;
}
return false;
}
/**
Primary/unique key check. Checks that:
- If the storage engine requires it, that there is an index that is
candidate for promotion.
- If such a promotion occurs, checks that the candidate index is not
declared invisible.
@param file The storage engine handler.
@param key_info_buffer All indexes in the table.
@param key_count Number of indexes.
@retval false OK.
@retval true An error occurred and my_error() was called.
*/
static bool check_promoted_index(const handler *file,
const KEY *key_info_buffer, uint key_count) {
bool has_unique_key = false;
const KEY *end = key_info_buffer + key_count;
for (const KEY *k = key_info_buffer; k < end && !has_unique_key; ++k)
if (!(k->flags & HA_NULL_PART_KEY) && (k->flags & HA_NOSAME)) {
has_unique_key = true;
if (!k->is_visible) {
my_error(ER_PK_INDEX_CANT_BE_INVISIBLE, MYF(0));
return true;
}
}
if (!has_unique_key && (file->ha_table_flags() & HA_REQUIRE_PRIMARY_KEY)) {
my_error(ER_REQUIRES_PRIMARY_KEY, MYF(0));
return true;
}
return false;
}
namespace {
/**
This class is used as an input argument to Item::walk, and takes care of
replacing the field pointer in Item_field with pointers to a
Create_field_wrapper. This allows us to get the metadata for a column that
isn't created yet (Create_field).
*/
class Replace_field_processor_arg {
public:
Replace_field_processor_arg(THD *thd, List<Create_field> *fields,
const HA_CREATE_INFO *create_info,
const char *functional_index_name)
: m_thd(thd),
m_fields(fields),
m_create_info(create_info),
m_functional_index_name(functional_index_name) {}
const HA_CREATE_INFO *create_info() const { return m_create_info; }
const THD *thd() const { return m_thd; }
List<Create_field> const *fields() const { return m_fields; }
const char *functional_index_name() const { return m_functional_index_name; }
private:
THD *m_thd;
List<Create_field> *m_fields;
const HA_CREATE_INFO *m_create_info;
const char *m_functional_index_name;
};
} // namespace
bool Item_field::replace_field_processor(uchar *arg) {
Replace_field_processor_arg *targ =
pointer_cast<Replace_field_processor_arg *>(arg);
if (field_name == nullptr) {
// Ideally we should be able to handle the function DEFAULT() as well,
// but that seems rather difficult since it relies on having a TABLE object
// available (which we obviously don't have during CREATE TABLE). So
// disallow that function for now.
assert(type() == Item::INSERT_VALUE_ITEM ||
type() == Item::DEFAULT_VALUE_ITEM);
my_error(ER_FUNCTIONAL_INDEX_FUNCTION_IS_NOT_ALLOWED, MYF(0),
targ->functional_index_name());
return true;
}
const Create_field *create_field = nullptr;
for (const Create_field &create_field_it : *targ->fields()) {
if (my_strcasecmp(system_charset_info, field_name,
create_field_it.field_name) == 0) {
create_field = &create_field_it;
break;
}
}
if (create_field) {
field = new (targ->thd()->mem_root) Create_field_wrapper(create_field);
switch (create_field->sql_type) {
case MYSQL_TYPE_TINY_BLOB:
case MYSQL_TYPE_MEDIUM_BLOB:
case MYSQL_TYPE_LONG_BLOB:
case MYSQL_TYPE_BLOB: {
assert(create_field->charset != nullptr);
set_data_type_string(blob_length_by_type(create_field->sql_type),
create_field->charset);
break;
}
case MYSQL_TYPE_STRING:
case MYSQL_TYPE_VARCHAR: {
assert(create_field->charset != nullptr);
set_data_type_string(create_field->max_display_width_in_codepoints(),
create_field->charset);
break;
}
case MYSQL_TYPE_NEWDECIMAL: {
uint precision = my_decimal_length_to_precision(
create_field->max_display_width_in_codepoints(),
create_field->decimals, create_field->is_unsigned);
set_data_type_decimal(precision, create_field->decimals);
break;
}
case MYSQL_TYPE_DATETIME2: {
set_data_type_datetime(create_field->decimals);
break;
}
case MYSQL_TYPE_TIMESTAMP2: {
set_data_type_timestamp(create_field->decimals);
break;
}
case MYSQL_TYPE_NEWDATE: {
set_data_type_date();
break;
}
case MYSQL_TYPE_TIME2: {
set_data_type_time(create_field->decimals);
break;
}
case MYSQL_TYPE_YEAR: {
set_data_type_year();
break;
}
case MYSQL_TYPE_INT24:
case MYSQL_TYPE_TINY:
case MYSQL_TYPE_SHORT:
case MYSQL_TYPE_LONG:
case MYSQL_TYPE_LONGLONG:
case MYSQL_TYPE_BIT: {
fix_char_length(create_field->max_display_width_in_codepoints());
set_data_type(create_field->sql_type);
collation.set_numeric();
break;
}
case MYSQL_TYPE_DOUBLE: {
set_data_type_double();
decimals = create_field->decimals;
break;
}
case MYSQL_TYPE_FLOAT: {
set_data_type_float();
decimals = create_field->decimals;
break;
}
case MYSQL_TYPE_JSON: {
set_data_type_json();
break;
}
case MYSQL_TYPE_GEOMETRY: {
set_data_type_geometry();
break;
}
case MYSQL_TYPE_ENUM: {
set_data_type(create_field->sql_type);
collation.collation = create_field->charset;
fix_char_length(create_field->max_display_width_in_codepoints());
break;
}
case MYSQL_TYPE_SET: {
set_data_type(create_field->sql_type);
collation.collation = create_field->charset;
fix_char_length(create_field->max_display_width_in_codepoints());
break;
}
default: {
assert(false); /* purecov: deadcode */
}
}
fixed = true;
} else {
// If the field could not be found, it means that we have added a reference
// to a non-existing field. Report an error and return.
my_error(ER_BAD_FIELD_ERROR, MYF(0), field_name, "functional index");
return true;
}
unsigned_flag = create_field->sql_type == MYSQL_TYPE_BIT ||
field->is_flag_set(UNSIGNED_FLAG);
set_nullable(create_field->is_nullable);
field->field_length = max_length;
return false;
}
/**
Check if the given key name exists in the array of keys. The lookup is
case insensitive.
@param keys the array to check for the key name in
@param key_name the key name to look for.
@param key_to_ignore a pointer to the key we don't want to check against. This
is used when checking for duplicate functional index names.
@retval true if the key name exists in the array
@retval false if the key name doesn't exist in the array
*/
static bool key_name_exists(const Mem_root_array<Key_spec *> &keys,
const std::string &key_name,
const Key_spec *key_to_ignore) {
for (Key_spec *key_spec : keys) {
if (key_spec == key_to_ignore) {
continue;
}
if (key_spec->name.str != nullptr &&
my_strcasecmp(system_charset_info, key_name.c_str(),
key_spec->name.str) == 0) {
return true;
}
}
return false;
}
/// Checks if a column with the given name exists in a list of fields.
static bool column_name_exists(const List<Create_field> &fields,
const string &column_name) {
for (const Create_field &field : fields) {
if (my_strcasecmp(system_charset_info, column_name.c_str(),
field.field_name) == 0) {
return true;
}
}
return false;
}
/**
Create a name for the hidden generated column that represents the functional
key part.
The name is a string on the form `!hidden!index_name!key_part!counter`. The
counter is usually 0, but is incremented until a unique name is found, in the
unlikely event that there is another column with the same name. The index_name
part may be truncated to make sure the column name does not exceed the maximum
column name length (NAME_CHAR_LEN).
@param key_name the name of the index.
@param key_part_number the key part number, starting from zero.
@param fields the other columns in the table
@param mem_root the MEM_ROOT where the column name should be allocated.
@returns the name for the hidden generated column, allocated on the supplied
MEM_ROOT
*/
static const char *make_functional_index_column_name(
std::string_view key_name, unsigned key_part_number,
const List<Create_field> &fields, MEM_ROOT *mem_root) {
// Loop until we have found a unique name. We'll usually find one in the first
// iteration, but if there are user-defined columns using the same naming
// scheme, we might need to increment the counter to avoid collisions. We're
// guaranteed to find a unique name in at most fields.size() + 1 iterations.
for (unsigned count = 0;; ++count) {
assert(count <= fields.size());
string name("!hidden!");
name += key_name;
string suffix("!");
suffix += to_string(key_part_number);
suffix += '!';
suffix += to_string(count);
// If the name is so long that we hit the NAME_CHAR_LEN limit, truncate the
// index name part, so that there is enough room to add the suffix with the
// key part number and the counter. (If we had truncated the counter, we
// could loop forever because the generated name is the same in each
// iteration.)
name.resize(min(name.size(), NAME_CHAR_LEN - suffix.size()));
name.append(suffix);
assert(name.size() <= NAME_CHAR_LEN);
if (column_name_exists(fields, name)) {
continue;
}
return strmake_root(mem_root, name.data(), name.size());
}
}
/**
Whether or not we have a replication setup, _and_ the master sorts
functional index columns last in the table. Sorting said columns last was
introduced in version 8.0.18, and this function helps us keep consistent
behavior in a OLD->NEW replication setup.
@returns false if we have a replication setup, _and_ the server is on a old
version that doesn't sort functional index columns last.
*/
static bool is_not_slave_or_master_sorts_functional_index_columns_last(
uint32_t master_version) {
// From version 8.0.18, the server will sort functional index columns last in
// the table.
return master_version >= 80018 && master_version != UNKNOWN_SERVER_VERSION;
}
/**
Prepares a functional index by adding a hidden indexed generated column for
the key part.
A functional index is implemented as a hidden generated column over the
expression specified in the index, and the hidden generated column is then
indexed. This function adds a hidden generated column to the Create_list,
and updates the key specification to point to this new column. The generated
column is given a name that is a hash of the key name and the key part number.
@param thd The thread handler
@param key_spec The index that contains the key part.-
@param alter_info A structure describing the changes to be carried out. This
structure will be updated with the new generated column.
@param kp The specification of the key part. This contains the expression we
will create a generated column for, and it will be updated to point
at the newly created generated column.
@param key_part_number The number of the key part.
@param create_info A structure describing the table to be created
@returns The newly added Create_field on success, of nullptr in case of errors
*/
static Create_field *add_functional_index_to_create_list(
THD *thd, Key_spec *key_spec, Alter_info *alter_info, Key_part_spec *kp,
uint key_part_number, HA_CREATE_INFO *create_info) {
// A functional index cannot be a primary key
if (key_spec->type == KEYTYPE_PRIMARY) {
my_error(ER_FUNCTIONAL_INDEX_PRIMARY_KEY, MYF(0));
return nullptr;
}
// If the key isn't given a name explicitly by the user, we must auto-generate
// a name here. "Normal" indexes will be given a name in prepare_key(), but
// that is too late for functional indexes since we want the hidden generated
// column name to be based on the index name.
if (key_spec->name.str == nullptr) {
std::string key_name;
int count = 2;
key_name.assign("functional_index");
while (key_name_exists(alter_info->key_list, key_name, nullptr)) {
key_name.assign("functional_index_");
key_name.append(std::to_string(count++));
}
key_spec->name.length = key_name.size();
key_spec->name.str = strmake_root(thd->stmt_arena->mem_root,
key_name.c_str(), key_name.size());
}
// First we need to resolve the expression in the functional index so that we
// know the correct collation, data type, length etc...
const Access_bitmask saved_privilege = thd->want_privilege;
thd->want_privilege = SELECT_ACL;
{
// Create a scope guard so that we are guaranteed that the privileges are
// set back to the original value.
auto handler_guard = create_scope_guard(
[thd, saved_privilege]() { thd->want_privilege = saved_privilege; });
Functional_index_error_handler error_handler(
{key_spec->name.str, key_spec->name.length}, thd);
const Prepared_stmt_arena_holder ps_arena_holder(thd);
Item *expr = kp->get_expression();
if (expr->type() == Item::FIELD_ITEM) {
my_error(ER_FUNCTIONAL_INDEX_ON_FIELD, MYF(0));
return nullptr;
}
if (pre_validate_value_generator_expr(
kp->get_expression(), key_spec->name.str, VGS_GENERATED_COLUMN)) {
return nullptr;
}
Replace_field_processor_arg replace_field_argument(
thd, &alter_info->create_list, create_info, key_spec->name.str);
if (expr->walk(&Item::replace_field_processor, enum_walk::PREFIX,
reinterpret_cast<uchar *>(&replace_field_argument))) {
return nullptr;
}
if (kp->resolve_expression(thd)) return nullptr;
}
const char *field_name = make_functional_index_column_name(
{key_spec->name.str, key_spec->name.length}, key_part_number,
alter_info->create_list, thd->stmt_arena->mem_root);
Item *item = kp->get_expression();
// Ensure that we aren't trying to index a field
assert(item->type() != Item::FIELD_ITEM);
TABLE tmp_table;
TABLE_SHARE share;
tmp_table.s = &share;
init_tmp_table_share(thd, &share, "", 0, "", "", nullptr);
tmp_table.s->db_create_options = 0;
tmp_table.s->db_low_byte_first = false;
tmp_table.set_not_started();
Create_field *cr = generate_create_field(thd, item, &tmp_table);
if (cr == nullptr) {
return nullptr; /* purecov: deadcode */
}
if (is_blob(cr->sql_type)) {
my_error(ER_FUNCTIONAL_INDEX_ON_LOB, MYF(0));
return nullptr;
}
// Don't even bother trying to create a non-conformant table.
if (alter_info->create_list.is_empty()) {
my_error(ER_TABLE_MUST_HAVE_A_VISIBLE_COLUMN, MYF(0));
return nullptr;
}
cr->field_name = field_name;
cr->field = nullptr;
cr->hidden = dd::Column::enum_hidden_type::HT_HIDDEN_SQL;
cr->stored_in_db = false;
Value_generator *gcol_info = new (thd->mem_root) Value_generator();
gcol_info->expr_item = kp->get_expression();
gcol_info->set_field_stored(false);
gcol_info->set_field_type(cr->sql_type);
cr->gcol_info = gcol_info;
if (is_not_slave_or_master_sorts_functional_index_columns_last(
thd->variables.original_server_version)) {
// Ensure that we insert the new hidden column in the correct place. That
// is, hidden generated columns for functional indexes should be placed at
// the end, sorted on their column name.
List_iterator<Create_field> insert_iterator(alter_info->create_list);
for (const Create_field ¤t : alter_info->create_list) {
if (is_field_for_functional_index(¤t)) {
if (my_strcasecmp(system_charset_info, cr->field_name,
current.field_name) < 0) {
break;
}
}
insert_iterator++;
}
// insert_iterator points to the last element where the field name is
// "less than" the new Create_fields field name. So the correct place to
// insert the new Create_field is _after_ the element that insert_iterator
// points to.
assert(!insert_iterator.is_before_first());
insert_iterator.after(cr);
} else {
// If the master doesn't sort functional index columns last, the slave
// shouldn't do it either.
alter_info->create_list.push_back(cr);
}
alter_info->flags |= Alter_info::ALTER_ADD_COLUMN;
kp->set_name_and_prefix_length(field_name, 0);
return cr;
}
/**
Check if the given column exists in the create list.
@param column_name the column name to look for.
@param create_list the create list where the search is performed.
@retval true the column exists in the create list.
@retval false the column does not exist in the create list.
*/
static bool column_exists_in_create_list(const char *column_name,
List<Create_field> &create_list) {
for (const auto &it : create_list) {
if (my_strcasecmp(system_charset_info, column_name, it.field_name) == 0) {
return true;
}
}
return false;
}
// Prepares the table and key structures for table creation.
bool mysql_prepare_create_table(
THD *thd, const char *error_schema_name, const char *error_table_name,
HA_CREATE_INFO *create_info, Alter_info *alter_info, handler *file,
bool is_partitioned, KEY **key_info_buffer, uint *key_count,
FOREIGN_KEY **fk_key_info_buffer, uint *fk_key_count,
FOREIGN_KEY *existing_fks, uint existing_fks_count,
const dd::Table *existing_fks_table, uint fk_max_generated_name_number,
int select_field_count, bool find_parent_keys) {
DBUG_TRACE;
/*
Validation of table properties.
*/
LEX_STRING *connect_string = &create_info->connect_string;
if (connect_string->length != 0 &&
connect_string->length > CONNECT_STRING_MAXLEN &&
(system_charset_info->cset->charpos(
system_charset_info, connect_string->str,
(connect_string->str + connect_string->length),
CONNECT_STRING_MAXLEN) < connect_string->length)) {
my_error(ER_WRONG_STRING_LENGTH, MYF(0), connect_string->str, "CONNECTION",
CONNECT_STRING_MAXLEN);
return true;
}
LEX_STRING *compress = &create_info->compress;
if (compress->length != 0 && compress->length > TABLE_COMMENT_MAXLEN &&
system_charset_info->cset->charpos(
system_charset_info, compress->str, compress->str + compress->length,
TABLE_COMMENT_MAXLEN) < compress->length) {
my_error(ER_WRONG_STRING_LENGTH, MYF(0), compress->str, "COMPRESSION",
TABLE_COMMENT_MAXLEN);
return true;
}
LEX_STRING *encrypt_type = &create_info->encrypt_type;
if (encrypt_type->length != 0 &&
encrypt_type->length > TABLE_COMMENT_MAXLEN &&
system_charset_info->cset->charpos(
system_charset_info, encrypt_type->str,
encrypt_type->str + encrypt_type->length,
TABLE_COMMENT_MAXLEN) < encrypt_type->length) {
my_error(ER_WRONG_STRING_LENGTH, MYF(0), encrypt_type->str, "ENCRYPTION",
TABLE_COMMENT_MAXLEN);
return true;
}
// Validate table comment string
std::string invalid_sub_str;
if (is_invalid_string({create_info->comment.str, create_info->comment.length},
system_charset_info, invalid_sub_str)) {
my_error(
ER_COMMENT_CONTAINS_INVALID_STRING, MYF(0), "table",
(std::string(error_schema_name) + "." + std::string(error_table_name))
.c_str(),
system_charset_info->csname, invalid_sub_str.c_str());
return true;
}
if (validate_comment_length(
thd, create_info->comment.str, &create_info->comment.length,
TABLE_COMMENT_MAXLEN, ER_TOO_LONG_TABLE_COMMENT, error_table_name)) {
return true;
}
if (alter_info->create_list.elements > MAX_FIELDS) {
my_error(ER_TOO_MANY_FIELDS, MYF(0));
return true;
}
/*
Checks which previously were done during .FRM creation.
TODO: Check if the old .FRM limitations still make sense
with the new DD.
*/
/* Fix this when we have new .frm files; Current limit is 4G rows (QQ) */
constexpr ulonglong u32max = UINT_MAX32;
if (create_info->max_rows > UINT_MAX32) {
// Values larger than uint32_max are capped to uint32_max.
// Emit a warning about this.
push_warning_printf(thd, Sql_condition::SL_WARNING, ER_VALUE_OUT_OF_RANGE,
ER_THD(thd, ER_VALUE_OUT_OF_RANGE), "max_rows",
create_info->max_rows, 0ULL, u32max, u32max);
create_info->max_rows = UINT_MAX32;
}
if (create_info->min_rows > UINT_MAX32) {
// Values larger than uint32_max are capped to uint32_max.
// Emit a warning about this.
push_warning_printf(thd, Sql_condition::SL_WARNING, ER_VALUE_OUT_OF_RANGE,
ER_THD(thd, ER_VALUE_OUT_OF_RANGE), "min_rows",
create_info->min_rows, 0ULL, u32max, u32max);
create_info->min_rows = UINT_MAX32;
}
if (create_info->row_type == ROW_TYPE_DYNAMIC)
create_info->table_options |= HA_OPTION_PACK_RECORD;
/*
Prepare fields, which must be done before calling
add_functional_index_to_create_list(). The reason is that
prepare_create_field() sets several properties of all Create_fields, such as
character set. We need the character set in order to get the correct
display width for each Create_field, which is in turn needed to resolve the
correct data type/length for each hidden generated column added by
add_functional_index_to_create_list().
*/
int select_field_pos = alter_info->create_list.elements - select_field_count;
create_info->null_bits = 0;
int field_no = 0;
Create_field *sql_field;
List_iterator<Create_field> it(alter_info->create_list);
for (; (sql_field = it++); field_no++) {
if (prepare_create_field(thd, error_schema_name, error_table_name,
create_info, &alter_info->create_list,
&select_field_pos, file, sql_field, field_no))
return true;
}
// Go through all functional key parts. For each functional key part, resolve
// the expression and add a hidden generated column to the create list.
for (Key_spec *key : alter_info->key_list) {
if (key->type == KEYTYPE_FOREIGN) continue;
for (size_t j = 0; j < key->columns.size(); ++j) {
Key_part_spec *key_part_spec = key->columns[j];
// In the case of procedures, the Key_part_spec may both have an
// expression and a field name assigned to it. But the hidden generated
// will not exist in the create list, so we will have to add it.
if (!key_part_spec->has_expression() ||
(key_part_spec->get_field_name() != nullptr &&
column_exists_in_create_list(key_part_spec->get_field_name(),
alter_info->create_list))) {
continue;
}
Create_field *new_create_field = add_functional_index_to_create_list(
thd, key, alter_info, key_part_spec, j, create_info);
if (new_create_field == nullptr) {
return true;
}
// Call prepare_create_field on the Create_field that was added by
// add_functional_index_to_create_list().
assert(is_field_for_functional_index(new_create_field));
if (prepare_create_field(thd, error_schema_name, error_table_name,
create_info, &alter_info->create_list,
&select_field_pos, file, new_create_field,
++field_no)) {
return true;
}
}
}
// Now that we have all the Create_fields available, calculate the offsets
// for each column.
calculate_field_offsets(&alter_info->create_list);
/*
Auto increment and blob checks.
*/
int auto_increment = 0;
int blob_columns = 0;
it.rewind();
while ((sql_field = it++)) {
if (sql_field->auto_flags & Field::NEXT_NUMBER) auto_increment++;
switch (sql_field->sql_type) {
case MYSQL_TYPE_GEOMETRY:
case MYSQL_TYPE_BLOB:
case MYSQL_TYPE_MEDIUM_BLOB:
case MYSQL_TYPE_TINY_BLOB:
case MYSQL_TYPE_LONG_BLOB:
case MYSQL_TYPE_JSON:
blob_columns++;
break;
default:
if (sql_field->is_array) blob_columns++;
break;
}
}
if (auto_increment > 1) {
my_error(ER_WRONG_AUTO_KEY, MYF(0));
return true;
}
if (auto_increment && (file->ha_table_flags() & HA_NO_AUTO_INCREMENT)) {
my_error(ER_TABLE_CANT_HANDLE_AUTO_INCREMENT, MYF(0));
return true;
}
if (blob_columns && (file->ha_table_flags() & HA_NO_BLOBS)) {
my_error(ER_TABLE_CANT_HANDLE_BLOB, MYF(0));
return true;
}
/*
CREATE TABLE[with auto_increment column] SELECT is unsafe as the rows
inserted in the created table depends on the order of the rows fetched
from the select tables. This order may differ on master and slave. We
therefore mark it as unsafe.
*/
if (select_field_count > 0 && auto_increment)
thd->lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_CREATE_SELECT_AUTOINC);
/*
Count keys and key segments.
Also mark redundant keys to be ignored.
*/
uint key_parts;
Mem_root_array<bool> redundant_keys(thd->mem_root,
alter_info->key_list.size(), false);
if (count_keys(alter_info->key_list, key_count, &key_parts, fk_key_count,
&redundant_keys, file->ha_table_flags()))
return true;
if (*key_count > file->max_keys()) {
my_error(ER_TOO_MANY_KEYS, MYF(0), file->max_keys());
return true;
}
/*
Make KEY objects for the keys in the new table.
*/
KEY *key_info;
(*key_info_buffer) = key_info = (KEY *)sql_calloc(sizeof(KEY) * (*key_count));
KEY_PART_INFO *key_part_info =
(KEY_PART_INFO *)sql_calloc(sizeof(KEY_PART_INFO) * key_parts);
if (!*key_info_buffer || !key_part_info) return true; // Out of memory
Mem_root_array<const KEY *> keys_to_check(thd->mem_root);
if (keys_to_check.reserve(*key_count)) return true; // Out of memory
uint key_number = 0;
bool primary_key = false;
// First prepare non-foreign keys so that they are ready when
// we prepare foreign keys.
for (size_t i = 0; i < alter_info->key_list.size(); i++) {
if (redundant_keys[i]) continue; // Skip redundant keys
const Key_spec *key = alter_info->key_list[i];
if (key->type == KEYTYPE_PRIMARY) {
if (primary_key) {
my_error(ER_MULTIPLE_PRI_KEY, MYF(0));
return true;
}
primary_key = true;
}
if (key->type != KEYTYPE_FOREIGN) {
if (prepare_key(thd, error_schema_name, error_table_name, create_info,
&alter_info->create_list, key, key_info_buffer, key_info,
&key_part_info, keys_to_check, key_number, file,
&auto_increment))
return true;
key_info++;
key_number++;
}
}
// If the table is created without PK, we must check if this has
// been disabled and return error. Limit the effect of sql_require_primary_key
// to only those SEs that can participate in replication.
if (!primary_key && !thd->is_dd_system_thread() &&
!thd->is_initialize_system_thread() &&
(file->ha_table_flags() &
(HA_BINLOG_ROW_CAPABLE | HA_BINLOG_STMT_CAPABLE)) != 0 &&
thd->variables.sql_require_primary_key) {
my_error(ER_TABLE_WITHOUT_PK, MYF(0));
return true;
}
/*
At this point all KEY objects are for indexes are fully constructed.
So we can check for duplicate indexes for keys for which it was requested.
*/
const KEY **dup_check_key;
for (dup_check_key = keys_to_check.begin();
dup_check_key != keys_to_check.end(); dup_check_key++) {
if (check_duplicate_key(thd, error_schema_name, error_table_name,
*dup_check_key, *key_info_buffer, *key_count,
alter_info))
return true;
}
if (!primary_key && check_promoted_index(file, *key_info_buffer, *key_count))
return true;
/*
Any auto increment columns not found during prepare_key?
*/
if (auto_increment > 0) {
my_error(ER_WRONG_AUTO_KEY, MYF(0));
return true;
}
/* Sort keys in optimized order */
std::sort(*key_info_buffer, *key_info_buffer + *key_count, sort_keys());
/*
Normal keys are done, now prepare foreign keys.
We do this after sorting normal keys to get predictable behavior
when searching for parent keys for self-referencing foreign keys.
*/
bool se_supports_fks =
(create_info->db_type->flags & HTON_SUPPORTS_FOREIGN_KEYS);
assert(se_supports_fks || existing_fks_count == 0);
(*fk_key_count) += existing_fks_count;
FOREIGN_KEY *fk_key_info;
(*fk_key_info_buffer) = fk_key_info =
(FOREIGN_KEY *)sql_calloc(sizeof(FOREIGN_KEY) * (*fk_key_count));
if (!fk_key_info) return true; // Out of memory
// Copy pre-existing foreign keys.
if (existing_fks_count > 0)
memcpy(*fk_key_info_buffer, existing_fks,
existing_fks_count * sizeof(FOREIGN_KEY));
uint fk_number = existing_fks_count;
fk_key_info += existing_fks_count;
/*
Check if we are trying to add partitioning to the table with existing
foreign keys and table's storage engine doesn't support foreign keys
over partitioned tables.
*/
if (is_partitioned && existing_fks_count > 0 &&
(!create_info->db_type->partition_flags ||
create_info->db_type->partition_flags() & HA_CANNOT_PARTITION_FK)) {
my_error(ER_FOREIGN_KEY_ON_PARTITIONED, MYF(0));
return true;
}
/*
Check that definitions of existing foreign keys are not broken by this
ALTER TABLE. Update FOREIGN_KEY::unique_constraint_name if necessary.
*/
for (FOREIGN_KEY *fk = *fk_key_info_buffer;
fk < (*fk_key_info_buffer) + existing_fks_count; fk++) {
if (prepare_preexisting_foreign_key(
thd, create_info, alter_info, error_schema_name, error_table_name,
*key_info_buffer, *key_count, existing_fks_table, fk))
return true;
}
// Prepare new foreign keys.
for (size_t i = 0; i < alter_info->key_list.size(); i++) {
if (redundant_keys[i]) continue; // Skip redundant keys
Key_spec *key = alter_info->key_list[i];
if (key->type == KEYTYPE_FOREIGN) {
if (prepare_foreign_key(thd, create_info, alter_info, error_schema_name,
error_table_name, is_partitioned,
*key_info_buffer, *key_count, *fk_key_info_buffer,
fk_number, se_supports_fks, find_parent_keys,
down_cast<Foreign_key_spec *>(key),
&fk_max_generated_name_number, fk_key_info))
return true;
if (se_supports_fks) {
fk_key_info++;
fk_number++;
}
}
}
/*
Check if STRICT SQL mode is active and server is not started with
--explicit-defaults-for-timestamp. Below check was added to prevent implicit
default 0 value of timestamp. When explicit-defaults-for-timestamp server
option is removed, whole set of check can be removed.
Note that this check must be after KEYs have been created as this
can cause the NOT_NULL_FLAG to be set.
*/
if (thd->variables.sql_mode & MODE_NO_ZERO_DATE &&
!thd->variables.explicit_defaults_for_timestamp) {
it.rewind();
while ((sql_field = it++)) {
if (!sql_field->constant_default && !sql_field->gcol_info &&
is_timestamp_type(sql_field->sql_type) &&
(sql_field->flags & NOT_NULL_FLAG) &&
!(sql_field->auto_flags & Field::DEFAULT_NOW)) {
/*
An error should be reported if:
- there is no explicit DEFAULT clause (default column value);
- this is a TIMESTAMP column;
- the column is not NULL;
- this is not the DEFAULT CURRENT_TIMESTAMP column.
And from checks before while loop,
- STRICT SQL mode is active;
- server is not started with --explicit-defaults-for-timestamp
In other words, an error should be reported if
- STRICT SQL mode is active;
- the column definition is equivalent to
'column_name TIMESTAMP DEFAULT 0'.
*/
my_error(ER_INVALID_DEFAULT, MYF(0), sql_field->field_name);
return true;
}
}
}
// Check that we have at least one visible column.
bool has_visible_column = false;
it.rewind();
while ((sql_field = it++)) {
if (sql_field->hidden == dd::Column::enum_hidden_type::HT_VISIBLE) {
has_visible_column = true;
break;
}
}
if (!has_visible_column) {
my_error(ER_TABLE_MUST_HAVE_A_VISIBLE_COLUMN, MYF(0));
return true;
}
/* If fixed row records, we need one bit to check for deleted rows */
if (!(create_info->table_options & HA_OPTION_PACK_RECORD))
create_info->null_bits++;
ulong data_offset = (create_info->null_bits + 7) / 8;
size_t reclength = data_offset;
it.rewind();
while ((sql_field = it++)) {
size_t length = sql_field->pack_length();
if (sql_field->offset + data_offset + length > reclength)
reclength = sql_field->offset + data_offset + length;
}
if (reclength > file->max_record_length()) {
my_error(ER_TOO_BIG_ROWSIZE, MYF(0),
static_cast<long>(file->max_record_length()));
return true;
}
return false;
}
/**
@brief check comment length of table, column, index and partition
@details If comment length is more than the standard length
truncate it and store the comment length up to the standard
comment length size
@param thd Thread handle
@param comment_str Comment string
@param[in,out] comment_len Comment length
@param max_len Maximum allowed comment length
@param err_code Error message
@param comment_name Type of comment
@return Operation status
@retval true Error found
@retval false On success
*/
bool validate_comment_length(THD *thd, const char *comment_str,
size_t *comment_len, uint max_len, uint err_code,
const char *comment_name) {
size_t length = 0;
DBUG_TRACE;
if (comment_str == nullptr) {
assert(*comment_len == 0);
return false;
}
size_t tmp_len = system_charset_info->cset->charpos(
system_charset_info, comment_str, comment_str + *comment_len, max_len);
if (tmp_len < *comment_len) {
if (thd->is_strict_mode()) {
my_error(err_code, MYF(0), comment_name, static_cast<ulong>(max_len));
return true;
}
char warn_buff[MYSQL_ERRMSG_SIZE];
length =
snprintf(warn_buff, sizeof(warn_buff), ER_THD_NONCONST(thd, err_code),
comment_name, static_cast<ulong>(max_len));
/* do not push duplicate warnings */
if (!thd->get_stmt_da()->has_sql_condition(warn_buff, length))
push_warning(thd, Sql_condition::SL_WARNING, err_code, warn_buff);
*comment_len = tmp_len;
}
return false;
}
/*
Set table default charset, if not set
SYNOPSIS
set_table_default_charset()
create_info Table create information
DESCRIPTION
If the table character set was not given explicitly,
let's fetch the database default character set and
apply it to the table.
*/
static bool set_table_default_charset(THD *thd, HA_CREATE_INFO *create_info,
const dd::Schema &schema) {
/*
If the table character set was not given explicitly,
let's fetch the database default character set and
apply it to the table.
*/
if (create_info->default_table_charset == nullptr) {
if (get_default_db_collation(schema, &create_info->default_table_charset))
return true;
} else {
assert((create_info->used_fields & HA_CREATE_USED_CHARSET) == 0 ||
(create_info->used_fields & HA_CREATE_USED_DEFAULT_CHARSET) ||
create_info->default_table_charset == create_info->table_charset);
if ((create_info->used_fields & HA_CREATE_USED_DEFAULT_CHARSET) &&
!(create_info->used_fields & HA_CREATE_USED_DEFAULT_COLLATE) &&
create_info->default_table_charset == &my_charset_utf8mb4_0900_ai_ci) {
create_info->default_table_charset =
thd->variables.default_collation_for_utf8mb4;
// ALTER TABLE ... CONVERT TO CHARACTER SET ...
if (create_info->used_fields & HA_CREATE_USED_CHARSET) {
create_info->table_charset = create_info->default_table_charset;
}
}
}
if (create_info->default_table_charset == nullptr)
create_info->default_table_charset = thd->collation();
return false;
}
/*
Extend long VARCHAR fields to blob & prepare field if it's a blob
SYNOPSIS
prepare_blob_field()
sql_field Field to check
RETURN
0 ok
1 Error (sql_field can't be converted to blob)
In this case the error is given
*/
static bool prepare_blob_field(THD *thd, Create_field *sql_field,
bool convert_character_set) {
DBUG_TRACE;
// Skip typed array fields
if (sql_field->is_array) return false;
if (sql_field->max_display_width_in_bytes() > MAX_FIELD_VARCHARLENGTH &&
!(sql_field->flags & BLOB_FLAG)) {
/* Convert long VARCHAR columns to TEXT or BLOB */
char warn_buff[MYSQL_ERRMSG_SIZE];
if (sql_field->constant_default || thd->is_strict_mode()) {
my_error(ER_TOO_BIG_FIELDLENGTH, MYF(0), sql_field->field_name,
static_cast<ulong>(MAX_FIELD_VARCHARLENGTH /
sql_field->charset->mbmaxlen));
return true;
}
sql_field->sql_type =
get_blob_type_from_length(sql_field->max_display_width_in_bytes());
sql_field->flags |= BLOB_FLAG;
snprintf(warn_buff, sizeof(warn_buff), ER_THD(thd, ER_AUTO_CONVERT),
sql_field->field_name,
(sql_field->charset == &my_charset_bin) ? "VARBINARY" : "VARCHAR",
(sql_field->charset == &my_charset_bin) ? "BLOB" : "TEXT");
push_warning(thd, Sql_condition::SL_NOTE, ER_AUTO_CONVERT, warn_buff);
}
/*
If the user has given a length to the BLOB/TEXT column explicitly, we make
sure that we choose the most appropriate data type. For instance, "TEXT(63)
CHARACTER SET utf8mb4" is automatically converted to TINYTEXT since TINYTEXT
can hold 255 _bytes_ of data (which is enough for 63 _characters_ of
utf8mb4).
Also, if we are changing the character set to a character set that requires
more storage per character, we might need to change the column to a bigger
type in order to not loose any data. Consider the following example:
CREATE TABLE t1 (a TINYTEXT CHARACTER SET latin1);
ALTER TABLE t1 CONVERT TO CHARACTER SET utf8mb4;
TINYTEXT can store up to 255 _bytes_ of data, and since "latin1" requires
one byte per character the user can store 255 _characters_ into this column.
If we are changing the character set to utf8mb4, each character suddenly
requires 4 bytes of storage. So an existing string in the column "a" that
is 255 characters long now suddenly requires 1020 _bytes_ of storage. This
does not fit into TINYTEXT, so we need to switch the data type to TEXT in
order not to loose any existing data (TEXT can store up to 65536 _bytes_ of
data, which is 16384 _characters_ of utf8mb4 data).
*/
if ((sql_field->flags & BLOB_FLAG) &&
(sql_field->sql_type == FIELD_TYPE_BLOB ||
sql_field->sql_type == FIELD_TYPE_TINY_BLOB ||
sql_field->sql_type == FIELD_TYPE_MEDIUM_BLOB)) {
if (sql_field->explicit_display_width()) {
sql_field->sql_type =
get_blob_type_from_length(sql_field->max_display_width_in_bytes());
} else if (convert_character_set && sql_field->field != nullptr) {
// If sql_field->field == nullptr, it means that we are doing a "CONVERT
// TO CHARACTER SET" _and_ adding a new column in the same statement.
// The new column will have the new correct character set, so we don't
// need to do anything for that column here.
const size_t max_codepoints_old_field =
sql_field->field->char_length() /
sql_field->field->charset()->mbmaxlen;
const size_t max_bytes_new_field =
max_codepoints_old_field * sql_field->charset->mbmaxlen;
sql_field->sql_type = get_blob_type_from_length(max_bytes_new_field);
}
}
return false;
}
/**
Struct for representing the result of checking if a table exists
before trying to create it. The result has two different
dimensions; if the table actually exists, and if an error
occurred. If the table exists m_error will still be false if this is
CREATE IF NOT EXISTS.
*/
struct Table_exists_result {
/** true if the table already exists */
bool m_table_exists;
/** true if my_error() has been called and an error must be propagated. */
bool m_error;
};
/**
Check if table already exists.
@param thd thread handle
@param schema_name schema name.
@param table_name table name.
@param alias alt representation of table_name.
@param ha_lex_create_tmp_table true if creating a tmp table.
@param ha_create_if_not_exists true if this is CREATE IF NOT EXISTS.
@param internal_tmp_table true if this is an internal tmp table.
@return false if successful, true otherwise.
*/
static Table_exists_result check_if_table_exists(
THD *thd, const char *schema_name, const char *table_name,
const char *alias, bool ha_lex_create_tmp_table,
bool ha_create_if_not_exists, bool internal_tmp_table) {
if (ha_lex_create_tmp_table &&
find_temporary_table(thd, schema_name, table_name)) {
if (ha_create_if_not_exists) {
push_warning_printf(thd, Sql_condition::SL_NOTE, ER_TABLE_EXISTS_ERROR,
ER_THD(thd, ER_TABLE_EXISTS_ERROR), alias);
return {true, false};
}
my_error(ER_TABLE_EXISTS_ERROR, MYF(0), alias);
return {true, true};
}
if (!internal_tmp_table && !ha_lex_create_tmp_table &&
!dd::get_dictionary()->is_dd_table_name(schema_name, table_name)) {
const dd::Abstract_table *at = nullptr;
if (thd->dd_client()->acquire(schema_name, table_name, &at)) {
return {false, true};
}
if (at != nullptr) {
if (ha_create_if_not_exists) {
push_warning_printf(thd, Sql_condition::SL_NOTE, ER_TABLE_EXISTS_ERROR,
ER_THD(thd, ER_TABLE_EXISTS_ERROR), alias);
return {true, false};
}
my_error(ER_TABLE_EXISTS_ERROR, MYF(0), table_name);
return {true, true};
}
}
/*
Check that table with given name does not already
exist in any storage engine. In such a case it should
be discovered and the error ER_TABLE_EXISTS_ERROR be returned
unless user specified CREATE TABLE IF EXISTS
An exclusive metadata lock ensures that no
one else is attempting to discover the table. Since
it's not on disk as a frm file, no one could be using it!
*/
if (!ha_lex_create_tmp_table &&
!dd::get_dictionary()->is_dd_table_name(schema_name, table_name)) {
int retcode = ha_table_exists_in_engine(thd, schema_name, table_name);
DBUG_PRINT("info", ("exists_in_engine: %u", retcode));
switch (retcode) {
case HA_ERR_NO_SUCH_TABLE:
/* Normal case, no table exists. we can go and create it */
break;
case HA_ERR_TABLE_EXIST:
DBUG_PRINT("info", ("Table existed in handler"));
if (ha_create_if_not_exists) {
push_warning_printf(thd, Sql_condition::SL_NOTE,
ER_TABLE_EXISTS_ERROR,
ER_THD(thd, ER_TABLE_EXISTS_ERROR), alias);
return {true, false};
}
my_error(ER_TABLE_EXISTS_ERROR, MYF(0), table_name);
return {true, true};
break;
default:
DBUG_PRINT("info", ("error: %u from storage engine", retcode));
my_error(retcode, MYF(0), table_name);
return {true, true};
}
}
return {false, false};
}
/**
Create a table
@param thd Thread object
@param schema DD schema object
@param db Database
@param table_name Table name
@param error_table_name The real table name in case table_name is a
temporary table (ALTER). Used for error messages and for checking whether the
table is a white listed system table.
@param path Path to table (i.e. to its .FRM file without
the extension).
@param create_info Create information (like MAX_ROWS)
@param alter_info Description of fields and keys for new table
@param internal_tmp_table Set to true if this is an internal temporary table
(From ALTER TABLE)
@param select_field_count Number of fields coming from SELECT part of
CREATE TABLE ... SELECT statement. Must be zero
for standard create of table.
@param find_parent_keys Indicates whether we need to lookup name of unique
constraint in parent table for foreign keys.
@param no_ha_table Indicates that only .FRM file (and PAR file if
table is partitioned) needs to be created and not a table in the storage
engine.
@param do_not_store_in_dd Indicates that we should postpone storing table
object in the data-dictionary. Requires SE
supporting atomic DDL and no_ha_table flag set.
@param[out] is_trans Identifies the type of engine where the table
was created: either trans or non-trans.
@param[out] key_info Array of KEY objects describing keys in table
which was created.
@param[out] key_count Number of keys in table which was created.
@param keys_onoff Enable or disable keys.
@param[out] fk_key_info Array of FOREIGN_KEY objects describing foreign
keys in table which was created.
@param[out] fk_key_count Number of foreign keys in table which was created.
@param[in] existing_fk_info Array of FOREIGN_KEY objects for foreign keys
which already existed in the table
(in case of ALTER TABLE).
@param[in] existing_fk_count Number of pre-existing foreign keys.
@param[in] existing_fk_table dd::Table object for table version from which
pre-existing foreign keys come from. Needed
for error reporting.
@param[in] fk_max_generated_name_number Max value of number component among
existing generated foreign key names.
@param[out] table_def Data-dictionary object describing the table
created if do_not_store_in_dd option was
used or because the table is temporary and
was not open due to no_ha_table. Not set
otherwise.
@param[out] post_ddl_ht Set to handlerton for table's SE, if this SE
supports atomic DDL, so caller can call SE
post DDL hook after committing transaction.
If one creates a temporary table, this is automatically opened
Note that this function assumes that caller already have taken
exclusive metadata lock on table being created or used some other
way to ensure that concurrent operations won't intervene.
mysql_create_table() is a wrapper that can be used for this.
@note On failure, for engines supporting atomic DDL, the caller must
rollback statement and transaction before doing anything else.
@retval false OK
@retval true error
*/
static bool create_table_impl(
THD *thd, const dd::Schema &schema, const char *db, const char *table_name,
const char *error_table_name, const char *path, HA_CREATE_INFO *create_info,
Alter_info *alter_info, bool internal_tmp_table, uint select_field_count,
bool find_parent_keys, bool no_ha_table, bool do_not_store_in_dd,
bool *is_trans, KEY **key_info, uint *key_count,
Alter_info::enum_enable_or_disable keys_onoff, FOREIGN_KEY **fk_key_info,
uint *fk_key_count, FOREIGN_KEY *existing_fk_info, uint existing_fk_count,
const dd::Table *existing_fk_table, uint fk_max_generated_name_number,
std::unique_ptr<dd::Table> *table_def, handlerton **post_ddl_ht) {
DBUG_TRACE;
DBUG_PRINT("enter", ("db: '%s' table: '%s' tmp: %d", db, table_name,
internal_tmp_table));
if (check_engine(db, table_name, create_info)) return true;
// Secondary engine cannot be defined for temporary tables.
if (create_info->secondary_engine.str != nullptr &&
create_info->options & HA_LEX_CREATE_TMP_TABLE) {
my_error(ER_SECONDARY_ENGINE, MYF(0), "Temporary tables not supported");
return true;
}
if (set_table_default_charset(thd, create_info, schema)) return true;
const char *alias = table_case_name(create_info, table_name);
partition_info *part_info = thd->work_part_info;
std::unique_ptr<handler, Destroy_only<handler>> file(get_new_handler(
(TABLE_SHARE *)nullptr,
(part_info ||
(create_info->db_type->partition_flags &&
(create_info->db_type->partition_flags() & HA_USE_AUTO_PARTITION))),
thd->mem_root, create_info->db_type));
if (file.get() == nullptr) {
mem_alloc_error(sizeof(handler));
return true;
}
if (!part_info && create_info->db_type->partition_flags &&
(create_info->db_type->partition_flags() & HA_USE_AUTO_PARTITION)) {
Partition_handler *part_handler = file->get_partition_handler();
assert(part_handler != nullptr);
/*
Table is not defined as a partitioned table but the engine handles
all tables as partitioned. The handler will set up the partition info
object with the default settings.
*/
thd->work_part_info = part_info = new (thd->mem_root) partition_info();
if (!part_info) {
mem_alloc_error(sizeof(partition_info));
return true;
}
part_handler->set_auto_partitions(part_info);
part_info->default_engine_type = create_info->db_type;
part_info->is_auto_partitioned = true;
}
if (part_info) {
/*
The table has been specified as a partitioned table.
If this is part of an ALTER TABLE the handler will be the partition
handler but we need to specify the default handler to use for
partitions also in the call to check_partition_info. We transport
this information in the default_db_type variable, it is either
DB_TYPE_DEFAULT or the engine set in the ALTER TABLE command.
*/
handlerton *engine_type;
List_iterator<partition_element> part_it(part_info->partitions);
partition_element *part_elem;
while ((part_elem = part_it++)) {
if (part_elem->part_comment) {
size_t comment_len = strlen(part_elem->part_comment);
// Validate partition comment string
std::string invalid_sub_str;
if (is_invalid_string({part_elem->part_comment, comment_len},
system_charset_info, invalid_sub_str)) {
my_error(ER_COMMENT_CONTAINS_INVALID_STRING, MYF(0), "partition",
(std::string(db) + "." + std::string(error_table_name) +
"." + std::string(part_elem->partition_name))
.c_str(),
system_charset_info->csname, invalid_sub_str.c_str());
return true;
}
if (validate_comment_length(thd, part_elem->part_comment, &comment_len,
TABLE_PARTITION_COMMENT_MAXLEN,
ER_TOO_LONG_TABLE_PARTITION_COMMENT,
part_elem->partition_name))
return true;
part_elem->part_comment[comment_len] = '\0';
}
if (part_elem->subpartitions.elements) {
List_iterator<partition_element> sub_it(part_elem->subpartitions);
partition_element *subpart_elem;
while ((subpart_elem = sub_it++)) {
if (subpart_elem->part_comment) {
size_t comment_len = strlen(subpart_elem->part_comment);
// Validate subpartition comment string
std::string invalid_sub_str;
if (is_invalid_string({subpart_elem->part_comment, comment_len},
system_charset_info, invalid_sub_str)) {
my_error(ER_COMMENT_CONTAINS_INVALID_STRING, MYF(0),
"subpartition",
(std::string(db) + "." + std::string(error_table_name) +
"." + std::string(part_elem->partition_name) + "." +
std::string(subpart_elem->partition_name))
.c_str(),
system_charset_info->csname, invalid_sub_str.c_str());
return true;
}
if (validate_comment_length(thd, subpart_elem->part_comment,
&comment_len,
TABLE_PARTITION_COMMENT_MAXLEN,
ER_TOO_LONG_TABLE_PARTITION_COMMENT,
subpart_elem->partition_name))
return true;
subpart_elem->part_comment[comment_len] = '\0';
}
}
}
}
if (create_info->options & HA_LEX_CREATE_TMP_TABLE) {
my_error(ER_PARTITION_NO_TEMPORARY, MYF(0));
return true;
}
if (create_info->used_fields & HA_CREATE_USED_ENGINE) {
part_info->default_engine_type = create_info->db_type;
} else {
if (part_info->default_engine_type == nullptr) {
part_info->default_engine_type =
ha_checktype(thd, DB_TYPE_DEFAULT, false, false);
}
}
DBUG_PRINT("info",
("db_type = %s create_info->db_type = %s",
ha_resolve_storage_engine_name(part_info->default_engine_type),
ha_resolve_storage_engine_name(create_info->db_type)));
if (part_info->check_partition_info(thd, &engine_type, file.get(),
create_info, false))
return true;
part_info->default_engine_type = engine_type;
if (!engine_type->partition_flags) {
/*
The handler assigned to the table cannot handle partitioning.
*/
my_error(ER_CHECK_NOT_IMPLEMENTED, MYF(0), "native partitioning");
return true;
}
if (create_info->db_type != engine_type) {
/*
We come here when we don't use a partitioned handler.
Since we use a partitioned table it must be "native partitioned".
We have switched engine from defaults, most likely only specified
engines in partition clauses.
*/
file.reset(get_new_handler((TABLE_SHARE *)nullptr, true, thd->mem_root,
engine_type));
if (file.get() == nullptr) {
mem_alloc_error(sizeof(handler));
return true;
}
create_info->db_type = engine_type;
}
}
Table_exists_result ter = check_if_table_exists(
thd, db, table_name, alias,
(create_info->options & HA_LEX_CREATE_TMP_TABLE),
(create_info->options & HA_LEX_CREATE_IF_NOT_EXISTS), internal_tmp_table);
if (ter.m_error) {
return true;
}
if (ter.m_table_exists) {
return false;
}
/* Suppress key length errors if this is a white listed table. */
Key_length_error_handler error_handler;
bool is_whitelisted_table =
(create_info->options & HA_LEX_CREATE_TMP_TABLE) !=
HA_LEX_CREATE_TMP_TABLE &&
(thd->is_server_upgrade_thread() ||
create_info->db_type->db_type == DB_TYPE_INNODB) &&
(dd::get_dictionary()->is_dd_table_name(db, error_table_name) ||
dd::get_dictionary()->is_system_table_name(db, error_table_name));
if (is_whitelisted_table) thd->push_internal_handler(&error_handler);
bool prepare_error = mysql_prepare_create_table(
thd, db, error_table_name, create_info, alter_info, file.get(),
(part_info != nullptr), key_info, key_count, fk_key_info, fk_key_count,
existing_fk_info, existing_fk_count, existing_fk_table,
fk_max_generated_name_number, select_field_count, find_parent_keys);
if (is_whitelisted_table) thd->pop_internal_handler();
if (prepare_error) return true;
THD_STAGE_INFO(thd, stage_creating_table);
{
size_t dirlen;
char dirpath[FN_REFLEN];
/*
data_file_name and index_file_name include the table name without
extension. Mostly this does not refer to an existing file. When
comparing data_file_name or index_file_name against the data
directory, we try to resolve all symbolic links. On some systems,
we use realpath(3) for the resolution. This returns ENOENT if the
resolved path does not refer to an existing file. my_realpath()
does then copy the requested path verbatim, without symlink
resolution. Thereafter the comparison can fail even if the
requested path is within the data directory. E.g. if symlinks to
another file system are used. To make realpath(3) return the
resolved path, we strip the table name and compare the directory
path only. If the directory doesn't exist either, table creation
will fail anyway.
*/
if (create_info->data_file_name) {
dirname_part(dirpath, create_info->data_file_name, &dirlen);
if (test_if_data_home_dir(dirpath)) {
my_error(ER_WRONG_ARGUMENTS, MYF(0), "DATA DIRECTORY");
return true;
}
}
if (create_info->index_file_name) {
dirname_part(dirpath, create_info->index_file_name, &dirlen);
if (test_if_data_home_dir(dirpath)) {
my_error(ER_WRONG_ARGUMENTS, MYF(0), "INDEX DIRECTORY");
return true;
}
}
}
if (check_partition_dirs(thd->lex->part_info)) return true;
if (thd->variables.sql_mode & MODE_NO_DIR_IN_CREATE) {
if (create_info->data_file_name)
push_warning_printf(thd, Sql_condition::SL_WARNING, WARN_OPTION_IGNORED,
ER_THD(thd, WARN_OPTION_IGNORED), "DATA DIRECTORY");
if (create_info->index_file_name)
push_warning_printf(thd, Sql_condition::SL_WARNING, WARN_OPTION_IGNORED,
ER_THD(thd, WARN_OPTION_IGNORED), "INDEX DIRECTORY");
create_info->data_file_name = create_info->index_file_name = nullptr;
}
if (thd->variables.keep_files_on_create)
create_info->options |= HA_CREATE_KEEP_FILES;
/*
Create table definitions.
If "no_ha_table" is false also create table in storage engine.
*/
if (create_info->options & HA_LEX_CREATE_TMP_TABLE) {
if (rea_create_tmp_table(thd, path, schema, db, table_name, create_info,
alter_info->create_list, *key_count, *key_info,
keys_onoff,
&alter_info->check_constraint_spec_list,
file.get(), no_ha_table, is_trans, table_def))
return true;
} else {
if (rea_create_base_table(thd, path, schema, db, table_name, create_info,
alter_info->create_list, *key_count, *key_info,
keys_onoff, *fk_key_count, *fk_key_info,
&alter_info->check_constraint_spec_list,
file.get(), no_ha_table, do_not_store_in_dd,
part_info, is_trans, table_def, post_ddl_ht))
return true;
}
THD_STAGE_INFO(thd, stage_after_create);
if ((create_info->options & HA_LEX_CREATE_TMP_TABLE) &&
thd->in_multi_stmt_transaction_mode()) {
/*
When autocommit is disabled, creating temporary table sets this
flag to start transaction in any case (regardless of binlog=on/off,
binlog format and transactional/non-transactional engine) to make
behavior consistent.
*/
thd->server_status |= SERVER_STATUS_IN_TRANS;
}
return false;
}
/*
This function disallows requests to use general tablespace for the table
with ENCRYPTION clause different from the general tablespace's encryption
type.
@param thd Thread
@param create_info Metadata of the table.
@returns true on failure, false on success.
*/
static bool validate_table_encryption(THD *thd, HA_CREATE_INFO *create_info) {
// Study if this table uses general tablespaces and if any one is encrypted.
bool uses_general_tablespace = false;
bool uses_encrypted_tablespace = false;
dd::Encrypt_result result =
dd::is_tablespace_encrypted(thd, create_info, &uses_general_tablespace);
if (result.error) return true;
if (uses_general_tablespace) {
uses_encrypted_tablespace = result.value;
} else if (!create_info->tablespace &&
create_info->db_type->get_tablespace_type_by_name) {
/*
No tablespace is explicitly specified. InnoDB can either use
file-per-table or general tablespace based on 'innodb_file_per_table'
setting, so ask SE about it.
*/
Tablespace_type tt;
if (create_info->db_type->get_tablespace_type_by_name(
create_info->tablespace, &tt)) {
return true;
}
uses_general_tablespace = (tt != Tablespace_type::SPACE_TYPE_IMPLICIT);
}
/*
Stop if table's uses general tablespace and the requested encryption
type does not match the general tablespace encryption type.
*/
bool requested_type = dd::is_encrypted(create_info->encrypt_type);
if (uses_general_tablespace && requested_type != uses_encrypted_tablespace) {
my_error(ER_INVALID_ENCRYPTION_REQUEST, MYF(0),
requested_type ? "'encrypted'" : "'unencrypted'",
uses_encrypted_tablespace ? "'encrypted'" : "'unencrypted'");
return true;
}
return false;
}
static void warn_on_deprecated_float_auto_increment(
THD *thd, const Create_field &sql_field) {
if ((sql_field.flags & AUTO_INCREMENT_FLAG) &&
(sql_field.sql_type == MYSQL_TYPE_FLOAT ||
sql_field.sql_type == MYSQL_TYPE_DOUBLE)) {
push_warning_printf(thd, Sql_condition::SL_WARNING,
ER_WARN_DEPRECATED_FLOAT_AUTO_INCREMENT,
ER_THD(thd, ER_WARN_DEPRECATED_FLOAT_AUTO_INCREMENT),
sql_field.field_name);
}
}
static void warn_on_deprecated_float_precision(THD *thd,
const Create_field &sql_field) {
if (sql_field.decimals != DECIMAL_NOT_SPECIFIED) {
if (sql_field.sql_type == MYSQL_TYPE_FLOAT ||
sql_field.sql_type == MYSQL_TYPE_DOUBLE) {
push_warning(thd, Sql_condition::SL_WARNING,
ER_WARN_DEPRECATED_SYNTAX_NO_REPLACEMENT,
ER_THD(thd, ER_WARN_DEPRECATED_FLOAT_DIGITS));
}
}
}
static void warn_on_deprecated_float_unsigned(THD *thd,
const Create_field &sql_field) {
if ((sql_field.flags & UNSIGNED_FLAG) &&
(sql_field.sql_type == MYSQL_TYPE_FLOAT ||
sql_field.sql_type == MYSQL_TYPE_DOUBLE ||
sql_field.sql_type == MYSQL_TYPE_NEWDECIMAL)) {
push_warning(thd, Sql_condition::SL_WARNING,
ER_WARN_DEPRECATED_SYNTAX_NO_REPLACEMENT,
ER_THD(thd, ER_WARN_DEPRECATED_FLOAT_UNSIGNED));
}
}
static void warn_on_deprecated_zerofill(THD *thd,
const Create_field &sql_field) {
// The YEAR data type is implicitly ZEROFILL. Should only warn if it has been
// declared explicitly as ZEROFILL, but that cannot be determined at this
// point, so suppress the warning to avoid confusion.
if (sql_field.sql_type == MYSQL_TYPE_YEAR) return;
if (sql_field.flags & ZEROFILL_FLAG)
push_warning(thd, Sql_condition::SL_WARNING,
ER_WARN_DEPRECATED_SYNTAX_NO_REPLACEMENT,
ER_THD(thd, ER_WARN_DEPRECATED_ZEROFILL));
}
/**
Simple wrapper around create_table_impl() to be used
in various version of CREATE TABLE statement.
*/
bool mysql_create_table_no_lock(THD *thd, const char *db,
const char *table_name,
HA_CREATE_INFO *create_info,
Alter_info *alter_info, uint select_field_count,
bool find_parent_keys, bool *is_trans,
handlerton **post_ddl_ht) {
KEY *not_used_1;
uint not_used_2;
FOREIGN_KEY *not_used_3 = nullptr;
uint not_used_4 = 0;
std::unique_ptr<dd::Table> not_used_5;
char path[FN_REFLEN + 1];
if (create_info->options & HA_LEX_CREATE_TMP_TABLE)
build_tmptable_filename(thd, path, sizeof(path));
else {
bool was_truncated;
const char *alias = table_case_name(create_info, table_name);
build_table_filename(path, sizeof(path) - 1 - reg_ext_length, db, alias, "",
0, &was_truncated);
// Check truncation, will lead to overflow when adding extension
if (was_truncated) {
my_error(ER_IDENT_CAUSES_TOO_LONG_PATH, MYF(0), sizeof(path) - 1, path);
return true;
}
}
/*
Don't create the DD tables in the DDSE unless installing the DD.
*/
bool no_ha_table = false;
if (!opt_initialize && dd::get_dictionary()->is_dd_table_name(db, table_name))
no_ha_table = true;
// Check if the schema exists. We must make sure the schema is released
// and unlocked in the right order.
dd::Schema_MDL_locker mdl_locker(thd);
dd::cache::Dictionary_client::Auto_releaser releaser(thd->dd_client());
const dd::Schema *schema = nullptr;
if (mdl_locker.ensure_locked(db) || thd->dd_client()->acquire(db, &schema)) {
// Error is reported by the dictionary subsystem.
return true;
}
if (schema == nullptr) {
my_error(ER_BAD_DB_ERROR, MYF(0), db);
return true;
}
// Do not accept ENCRYPTION and AUTOEXTEND_SIZE clauses for
// temporary table.
if (create_info->options & HA_LEX_CREATE_TMP_TABLE) {
if (create_info->encrypt_type.length) {
my_error(ER_CANNOT_USE_ENCRYPTION_CLAUSE, MYF(0), "temporary");
return true;
}
if (create_info->m_implicit_tablespace_autoextend_size > 0) {
my_error(ER_CANNOT_USE_AUTOEXTEND_SIZE_CLAUSE, MYF(0), "temporary");
return true;
}
}
// Determine table encryption type, and check if user is allowed to create.
if (!(create_info->options & HA_LEX_CREATE_TMP_TABLE)) {
/*
Assume table as encrypted, if user did not explicitly state it and
we have a schema with default encryption enabled.
*/
if (!create_info->encrypt_type.length && schema->default_encryption()) {
create_info->encrypt_type = {strmake_root(thd->mem_root, "Y", 1), 1};
}
// Stop if it is invalid encryption clause, when using general tablespace.
if (validate_table_encryption(thd, create_info)) return true;
// Check table encryption privilege
if (create_info->encrypt_type.str || create_info->tablespace) {
/*
Check privilege only if request encryption type differ from schema
default encryption type.
*/
bool request_type = dd::is_encrypted(create_info->encrypt_type);
if (schema->default_encryption() != request_type) {
if (opt_table_encryption_privilege_check) {
if (check_table_encryption_admin_access(thd)) {
my_error(ER_CANNOT_SET_TABLE_ENCRYPTION, MYF(0));
return true;
}
} else if (schema->default_encryption() && !request_type) {
push_warning(thd, Sql_condition::SL_WARNING,
WARN_UNENCRYPTED_TABLE_IN_ENCRYPTED_DB,
ER_THD(thd, WARN_UNENCRYPTED_TABLE_IN_ENCRYPTED_DB));
}
}
}
}
for (const Create_field &sql_field : alter_info->create_list) {
warn_on_deprecated_float_auto_increment(thd, sql_field);
}
// Only needed for CREATE TABLE LIKE / SELECT, as warnings for
// pure CREATE TABLE is reported in the parser.
if (!thd->lex->query_block->field_list_is_empty()) {
for (const Create_field &sql_field : alter_info->create_list) {
warn_on_deprecated_float_precision(thd, sql_field);
warn_on_deprecated_float_unsigned(thd, sql_field);
warn_on_deprecated_zerofill(thd, sql_field);
}
}
if (thd->is_plugin_fake_ddl()) no_ha_table = true;
return create_table_impl(
thd, *schema, db, table_name, table_name, path, create_info, alter_info,
false, select_field_count, find_parent_keys, no_ha_table, false, is_trans,
¬_used_1, ¬_used_2, Alter_info::ENABLE, ¬_used_3, ¬_used_4,
nullptr, 0, nullptr, 0, ¬_used_5, post_ddl_ht);
}
typedef std::set<std::pair<dd::String_type, dd::String_type>>
Normalized_fk_children;
/**
Fetch names of all tables having a FK referring to the given table.
@param thd Thread handle.
@param parent_schema Schema name of the referenced table.
@param parent_name Name of the referenced table.
@param parent_engine Name of the referenced table's storage engine.
@param [out] fk_children Set of unique schema qualified names of
tables referring the given parent.
The children are fetched from the DD tables using uncommitted read. The
names are normalized, i.e., if l_c_t_n == 2, the names are lowercased.
@retval operation outcome, false if no error.
*/
static bool fetch_fk_children_uncached_uncommitted_normalized(
THD *thd, const char *parent_schema, const char *parent_name,
const char *parent_engine, Normalized_fk_children *fk_children) {
std::vector<dd::String_type> children_dbs, children_names;
if (thd->dd_client()->fetch_fk_children_uncached(
parent_schema, parent_name, parent_engine, true, &children_dbs,
&children_names))
return true;
auto db_it = children_dbs.begin();
auto names_it = children_names.begin();
while (db_it != children_dbs.end()) {
assert(names_it != children_names.end());
char buff_db[NAME_LEN + 1];
char buff_table[NAME_LEN + 1];
my_stpncpy(buff_db, db_it->c_str(), NAME_LEN);
my_stpncpy(buff_table, names_it->c_str(), NAME_LEN);
/*
In lower-case-table-names == 2 mode we store original versions of table
and db names in the data-dictionary. Hence they need to be lowercased
to produce correct MDL key for them and for other uses.
*/
if (lower_case_table_names == 2) {
my_casedn_str(system_charset_info, buff_db);
my_casedn_str(system_charset_info, buff_table);
}
fk_children->insert(
typename Normalized_fk_children::value_type(buff_db, buff_table));
++db_it;
++names_it;
}
return false;
}
bool collect_fk_children(THD *thd, const char *db, const char *arg_table_name,
handlerton *hton, enum_mdl_type lock_type,
MDL_request_list *mdl_requests) {
Normalized_fk_children fk_children;
if (fetch_fk_children_uncached_uncommitted_normalized(
thd, db, arg_table_name, ha_resolve_storage_engine_name(hton),
&fk_children))
return true;
for (auto fk_children_it : fk_children) {
const char *schema_name = fk_children_it.first.c_str();
const char *table_name = fk_children_it.second.c_str();
MDL_request *mdl_request = new (thd->mem_root) MDL_request;
if (mdl_request == nullptr) return true;
MDL_REQUEST_INIT(mdl_request, MDL_key::TABLE, schema_name, table_name,
lock_type, MDL_STATEMENT);
mdl_requests->push_front(mdl_request);
mdl_request = new (thd->mem_root) MDL_request;
if (mdl_request == nullptr) return true;
MDL_REQUEST_INIT(mdl_request, MDL_key::SCHEMA, schema_name, "",
MDL_INTENTION_EXCLUSIVE, MDL_STATEMENT);
mdl_requests->push_front(mdl_request);
}
return false;
}
static bool reload_fk_parents_for_single_table(THD *thd, const char *db,
const char *name) {
dd::Table *table = nullptr;
if (thd->dd_client()->acquire_for_modification(db, name, &table)) return true;
// Missing parent is allowed for tables created with F_K_C = 0.
if (table == nullptr) return false;
bool before_image_empty = table->foreign_key_parents().empty();
// Read uncommitted from the DD tables to reload the information.
if (table->reload_foreign_key_parents(thd)) return true;
bool after_image_empty = table->foreign_key_parents().empty();
/*
The changes are reflected in the uncommitted registry in the
dictionary client, which is removed upon rollback. Upon commit,
the corresponding object in the shared cache is invalidated. This
means that there will be an update of the DD tables which is not
necessary, and which also interferes with the use of the
Foreign_key_parents_invalidator.
TODO: In the long term, extend the Dictionary_client to support
caching changes that should not (or will not) be reflected
in the DD tables.
TODO: In the short term, we can improve this to avoid unnecessary
updates if the FK parent collection is unchanged. For now,
skip update if the collection is empty both before and after
reload.
*/
if (before_image_empty && after_image_empty) return false;
return thd->dd_client()->update(table);
}
bool adjust_fk_parents(THD *thd, const char *db, const char *name,
bool reload_self,
const Foreign_key_parents_invalidator *fk_invalidator) {
/*
Can't reload self in case of e.g. DROP. Otherwise, reload the
foreign key parents info in case we e.g. un-orphaned a child.
*/
if (reload_self && reload_fk_parents_for_single_table(thd, db, name))
return true;
/*
If an invalidator is submitted, use it to decide which tables should
have their FK parent info reloaded. This must be done e.g. for ALTER,
since e.g. the dropped FKs will not be present in the table's FK list
at this point.
*/
if (fk_invalidator != nullptr) {
for (auto parent : fk_invalidator->parents()) {
// Self referencing keys should be updated above if reload_self == true.
if ((my_strcasecmp(table_alias_charset, parent.first.first.c_str(), db) !=
0 ||
my_strcasecmp(table_alias_charset, parent.first.second.c_str(),
name) != 0) &&
reload_fk_parents_for_single_table(thd, parent.first.first.c_str(),
parent.first.second.c_str()))
return true;
}
return false;
}
/*
Otherwise, use the FK list in the table and reload FK parent info
for each parent.
*/
const dd::Table *table = nullptr;
if (thd->dd_client()->acquire(db, name, &table)) return true;
assert(table);
for (const dd::Foreign_key *fk : table->foreign_keys()) {
// Self referencing keys should be updated above if reload_self == true.
if ((my_strcasecmp(table_alias_charset,
fk->referenced_table_schema_name().c_str(), db) != 0 ||
my_strcasecmp(table_alias_charset, fk->referenced_table_name().c_str(),
name) != 0) &&
reload_fk_parents_for_single_table(
thd, fk->referenced_table_schema_name().c_str(),
fk->referenced_table_name().c_str()))
return true;
}
return false;
}
/**
Check if foreign key's parent table has a column compatible with foreign key's
referenced column.
@param[in] parent_table_def Data-dictionary object for parent table.
@param[in] fk Data-dictionary object for foreign key.
@param[in] fk_el Data-dictionary object for foreign key
element.
@param[in] hton Handlerton for table's storage engine.
@retval false Success.
@retval true Failure.
*/
static bool check_table_has_col_compatible_with_fk_ref_col(
const dd::Table *parent_table_def, const dd::Foreign_key *fk,
const dd::Foreign_key_element *fk_el, handlerton *hton) {
auto same_column_name = [fk_el](const dd::Column *c) {
return my_strcasecmp(system_charset_info, c->name().c_str(),
fk_el->referenced_column_name().c_str()) == 0;
};
auto ref_column =
std::find_if(parent_table_def->columns().begin(),
parent_table_def->columns().end(), same_column_name);
if (ref_column == parent_table_def->columns().end()) {
my_error(ER_FK_NO_COLUMN_PARENT, MYF(0),
fk_el->referenced_column_name().c_str(), fk->name().c_str(),
fk->referenced_table_name().c_str());
return true;
}
if ((*ref_column)->is_virtual()) {
my_error(ER_FK_CANNOT_USE_VIRTUAL_COLUMN, MYF(0), fk->name().c_str(),
fk_el->referenced_column_name().c_str());
return true;
}
// Check that type of referencing and referenced columns are compatible.
if (hton->check_fk_column_compat) {
Ha_fk_column_type child_column_type, parent_column_type;
if (fill_ha_fk_column_type(&child_column_type, &fk_el->column()) ||
fill_ha_fk_column_type(&parent_column_type, *ref_column))
return true;
if (!hton->check_fk_column_compat(&child_column_type, &parent_column_type,
true)) {
my_error(ER_FK_INCOMPATIBLE_COLUMNS, MYF(0),
fk_el->column().name().c_str(),
fk_el->referenced_column_name().c_str(), fk->name().c_str());
return true;
}
}
return false;
}
/**
Check if new definition of parent table is compatible with foreign keys
on child table which reference it. Update the unique constraint names and
referenced column names for the foreign keys accordingly.
@param thd Thread handle.
@param check_only Indicates that we only need to check parent key
existence and do not do real update.
@param check_charsets Indicates whether we need to check charsets of
columns participating in foreign keys.
@param child_table_db Child table schema name.
@param child_table_name Child table name.
@param parent_table_db Parent table schema name.
@param parent_table_name Parent table name.
@param hton Handlerton for tables' storage engine.
@param parent_table_def Table object representing the new version of
referenced table.
@param parent_alter_info Alter_info containing information about renames
of parent columns. Can be nullptr if there are
no such renames.
@param old_parent_table_def Table object representing the old version of
referenced table. Can be nullptr if this is
not ALTER TABLE. Used for error reporting.
@retval operation outcome, false if no error.
*/
static bool adjust_fk_child_after_parent_def_change(
THD *thd, bool check_only, bool check_charsets, const char *child_table_db,
const char *child_table_name, const char *parent_table_db,
const char *parent_table_name, handlerton *hton,
const dd::Table *parent_table_def, Alter_info *parent_alter_info,
const dd::Table *old_parent_table_def) {
dd::cache::Dictionary_client::Auto_releaser releaser(thd->dd_client());
dd::Table *child_table_def = nullptr;
const dd::Table *old_child_table_def = nullptr;
if (thd->dd_client()->acquire_for_modification(
child_table_db, child_table_name, &child_table_def))
return true;
if (child_table_def == nullptr) {
// Safety.
return false;
}
/*
Check if we are making parent table in a foreign key (possibly
previously orphan) a partitioned table and table's storage engine
doesn't support foreign keys over partitioned tables.
*/
if (parent_table_def->partition_type() != dd::Table::PT_NONE &&
(!hton->partition_flags ||
hton->partition_flags() & HA_CANNOT_PARTITION_FK)) {
my_error(ER_FOREIGN_KEY_ON_PARTITIONED, MYF(0));
return true;
}
if (old_parent_table_def != nullptr &&
thd->dd_client()->acquire(child_table_db, child_table_name,
&old_child_table_def))
return true;
assert(old_parent_table_def == nullptr || old_child_table_def != nullptr);
for (dd::Foreign_key *fk : *(child_table_def->foreign_keys())) {
if (my_strcasecmp(table_alias_charset,
fk->referenced_table_schema_name().c_str(),
parent_table_db) == 0 &&
my_strcasecmp(table_alias_charset, fk->referenced_table_name().c_str(),
parent_table_name) == 0) {
for (dd::Foreign_key_element *fk_el : *(fk->elements())) {
if (parent_alter_info) {
/*
The parent table is ALTERed. Check that referenced column was
not dropped and update foreign key definition with its new
name if it was renamed. The latter needs to be done before
searching for parent key.
*/
List_iterator<Create_field> find_it(parent_alter_info->create_list);
const Create_field *find;
if (check_only) {
/*
This is early stage of ALTER TABLE, so Alter_info::create_list is
fully available and we can use it both to check that column exists
and to handle column renames.
*/
while ((find = find_it++)) {
if (find->field &&
my_strcasecmp(system_charset_info,
fk_el->referenced_column_name().c_str(),
find->field->field_name) == 0) {
break;
}
}
if (find == nullptr) {
my_error(ER_FK_COLUMN_CANNOT_DROP_CHILD, MYF(0),
fk_el->referenced_column_name().c_str(),
fk->name().c_str(), fk->table().name().c_str());
return true;
}
/*
Column can't be made virtual as we don't allow ALTERs which make
stored columns virtual.
*/
assert(!find->is_virtual_gcol());
// Use new column name in foreign key definition if name was
// changed.
if (find->change != nullptr) {
fk_el->referenced_column_name(find->field_name);
}
/*
Check that types of child and parent columns are compatible.
*/
if (hton->check_fk_column_compat) {
Ha_fk_column_type child_column_type, parent_column_type;
if (fill_ha_fk_column_type(&child_column_type, &fk_el->column()))
return true;
fill_ha_fk_column_type(&parent_column_type, find);
if (!hton->check_fk_column_compat(&child_column_type,
&parent_column_type,
check_charsets)) {
my_error(ER_FK_INCOMPATIBLE_COLUMNS, MYF(0),
fk_el->column().name().c_str(),
fk_el->referenced_column_name().c_str(),
fk->name().c_str());
return true;
}
}
} else {
/*
This is late stage of ALTER TABLE. Some elements in
Alter_info::create_list are not fully valid. However,
those which are related to renaming of columns are,
so we can use them to update foreign key definitions.
Luckily, thanks to check at early stage of ALTER TABLE
we don't need to do anything else here.
*/
while ((find = find_it++)) {
if (find->change &&
my_strcasecmp(system_charset_info,
fk_el->referenced_column_name().c_str(),
find->change) == 0) {
fk_el->referenced_column_name(find->field_name);
break;
}
}
}
} else {
/*
We add parent table for previously orphan foreign key by doing
CREATE or RENAME TABLE. We need to check that it has columns
which match referenced columns in foreign key.
*/
if (check_table_has_col_compatible_with_fk_ref_col(parent_table_def,
fk, fk_el, hton))
return true;
}
}
/*
This function is never, and should never be, called for self referencing
foreign keys. Hence, we can submit 'false' for 'is_self_referenceing_fk'
in the call to prepare_fk_parent_key().
*/
assert(my_strcasecmp(table_alias_charset,
fk->referenced_table_schema_name().c_str(),
child_table_db) ||
my_strcasecmp(table_alias_charset,
fk->referenced_table_name().c_str(),
child_table_name));
if (prepare_fk_parent_key(hton, parent_table_def, old_parent_table_def,
old_child_table_def, false, fk))
return true;
}
}
if (!check_only && thd->dd_client()->update(child_table_def)) return true;
return false;
}
bool adjust_fk_children_after_parent_def_change(
THD *thd, bool check_charsets, const char *parent_table_db,
const char *parent_table_name, handlerton *hton,
const dd::Table *parent_table_def, Alter_info *parent_alter_info,
bool invalidate_tdc) {
Normalized_fk_children fk_children;
if (fetch_fk_children_uncached_uncommitted_normalized(
thd, parent_table_db, parent_table_name,
ha_resolve_storage_engine_name(hton), &fk_children))
return true;
for (auto fk_children_it : fk_children) {
const char *schema_name = fk_children_it.first.c_str();
const char *table_name = fk_children_it.second.c_str();
if (my_strcasecmp(table_alias_charset, schema_name, parent_table_db) == 0 &&
my_strcasecmp(table_alias_charset, table_name, parent_table_name) ==
0) {
// Safety. Self-referencing foreign keys are handled earlier.
continue;
}
/*
Since we always pass nullptr as old parent table definition pointer
to the below call, the error message reported by it might be not the
best one for the case when we call this function for ALTER TABLE
which drops parent key. But this does not matter as such errors
should have been normally detected and reported by earlier call
to check_fk_children_after_parent_def_change().
*/
if (adjust_fk_child_after_parent_def_change(
thd, false /* Update FKs. */, check_charsets, schema_name,
table_name, parent_table_db, parent_table_name, hton,
parent_table_def, parent_alter_info, nullptr))
return true;
if (invalidate_tdc) {
mysql_ha_flush_table(thd, schema_name, table_name);
close_all_tables_for_name(thd, schema_name, table_name, false);
}
#ifdef DISABLED_UNTIL_WL9533
/*
TODO: Simply removing entries from InnoDB internal cache breaks
its FK checking logic at the moment. This is to be solved
as part of WL#9533. We might have to replace invalidation
with cache update to do this.Also we might have to postpone
such invalidation/update until statement commit time.
*/
if (hton->dict_cache_reset) hton->dict_cache_reset(schema_name, table_name);
#endif
}
return false;
}
/**
Check if new definition of parent table is compatible with foreign keys which
reference it.
@param thd Thread handle.
@param parent_table_db Parent table schema name.
@param parent_table_name Parent table name.
@param hton Handlerton for tables' storage engine.
@param old_parent_table_def Table object representing the old version of
parent table.
@param new_parent_table_def Table object representing the new version of
parent table.
@param parent_alter_info Alter_info containing information about renames
of parent columns.
@retval operation outcome, false if no error.
*/
static bool check_fk_children_after_parent_def_change(
THD *thd, const char *parent_table_db, const char *parent_table_name,
handlerton *hton, const dd::Table *old_parent_table_def,
const dd::Table *new_parent_table_def, Alter_info *parent_alter_info) {
for (const dd::Foreign_key_parent *parent_fk :
old_parent_table_def->foreign_key_parents()) {
// Self-referencing FKs are handled separately.
if (my_strcasecmp(table_alias_charset,
parent_fk->child_schema_name().c_str(),
parent_table_db) == 0 &&
my_strcasecmp(table_alias_charset,
parent_fk->child_table_name().c_str(),
parent_table_name) == 0)
continue;
if (adjust_fk_child_after_parent_def_change(
thd, true, // Check only.
/*
Allow charset discrepancies between child and parent columns
in FOREIGN_KEY_CHECKS=0 mode. This provides a way to change
charset of column which participates in a foreign key without
dropping the latter (Note that in general case there is no way
to change charset of both child and parent columns
simultaneously).
We do not allow creation of same discrepancies when adding
new foreign key using CREATE/ALTER TABLE or adding new parent
for existing orphan foreign key using CREATE/RENAME TABLE.
*/
!(thd->variables.option_bits & OPTION_NO_FOREIGN_KEY_CHECKS),
parent_fk->child_schema_name().c_str(),
parent_fk->child_table_name().c_str(), parent_table_db,
parent_table_name, hton, new_parent_table_def, parent_alter_info,
old_parent_table_def))
return true;
}
return false;
}
/**
Check if new definition of parent table is compatible with foreign keys which
reference it and were previously orphan.
@param thd Thread handle.
@param parent_table_db Parent table schema name.
@param parent_table_name Parent table name.
@param old_parent_table_db Old parent table schema name, if table is
renamed.
@param old_parent_table_name Old parent table name, if table is renamed.
@param hton Handlerton for table's storage engine.
@param parent_table_def Table object representing the parent table.
@retval operation outcome, false if no error.
*/
static bool check_fk_children_after_parent_def_change(
THD *thd, const char *parent_table_db, const char *parent_table_name,
const char *old_parent_table_db, const char *old_parent_table_name,
handlerton *hton, const dd::Table *parent_table_def) {
Normalized_fk_children fk_children;
if (fetch_fk_children_uncached_uncommitted_normalized(
thd, parent_table_db, parent_table_name,
ha_resolve_storage_engine_name(hton), &fk_children))
return true;
for (auto fk_children_it : fk_children) {
const char *schema_name = fk_children_it.first.c_str();
const char *table_name = fk_children_it.second.c_str();
if (my_strcasecmp(table_alias_charset, schema_name, parent_table_db) == 0 &&
my_strcasecmp(table_alias_charset, table_name, parent_table_name) ==
0) {
// Safety. Self-referencing FKs are handled separately.
continue;
}
if (old_parent_table_name != nullptr) {
assert(old_parent_table_db != nullptr);
if (my_strcasecmp(table_alias_charset, schema_name,
old_parent_table_db) == 0 &&
my_strcasecmp(table_alias_charset, table_name,
old_parent_table_name) == 0) {
/*
In case of ALTER TABLE with RENAME clause, the above check involving
parent_table_db and parent_table_name will skip orphan FKs which
will become non-orphan/adopted self-referencing FKs as result of this
RENAME. Hence we need to do additional check using old_parent_table_db
and old_parent_table_name for non-orphan/adopted self-referencing FKs.
*/
continue;
}
}
if (adjust_fk_child_after_parent_def_change(
thd, true, // Check only.
true, // Check that charsets match.
schema_name, table_name, parent_table_db, parent_table_name, hton,
parent_table_def, nullptr, nullptr))
return true;
}
return false;
}
/**
Update the referenced schema- and/or table name for the referencing tables
when the referenced table is renamed.
@param thd Thread handle.
@param parent_table_db Old schema name.
@param parent_table_name Old table name.
@param hton Handlerton for table's storage engine.
@param new_db New schema name.
@param new_table_name New table name.
@retval operation outcome, false if no error.
*/
static bool adjust_fk_children_after_parent_rename(
THD *thd, const char *parent_table_db, const char *parent_table_name,
handlerton *hton, const char *new_db, const char *new_table_name) {
Normalized_fk_children fk_children;
if (fetch_fk_children_uncached_uncommitted_normalized(
thd, parent_table_db, parent_table_name,
ha_resolve_storage_engine_name(hton), &fk_children))
return true;
for (auto fk_children_it : fk_children) {
const char *schema_name = fk_children_it.first.c_str();
const char *table_name = fk_children_it.second.c_str();
if (my_strcasecmp(table_alias_charset, schema_name, parent_table_db) == 0 &&
my_strcasecmp(table_alias_charset, table_name, parent_table_name) ==
0) {
continue;
}
dd::Table *child_table_def = nullptr;
if (thd->dd_client()->acquire_for_modification(schema_name, table_name,
&child_table_def))
return true;
assert(child_table_def != nullptr);
for (dd::Foreign_key *fk : *(child_table_def->foreign_keys())) {
if (my_strcasecmp(table_alias_charset,
fk->referenced_table_schema_name().c_str(),
parent_table_db) == 0 &&
my_strcasecmp(table_alias_charset,
fk->referenced_table_name().c_str(),
parent_table_name) == 0) {
fk->set_referenced_table_schema_name(new_db);
fk->set_referenced_table_name(new_table_name);
}
}
if (thd->dd_client()->update(child_table_def)) return true;
mysql_ha_flush_table(thd, schema_name, table_name);
close_all_tables_for_name(thd, schema_name, table_name, false);
#ifdef DISABLED_UNTIL_WL9533
/*
TODO: Simply removing entries from InnoDB internal cache breaks
its FK checking logic at the moment. This is to be solved
as part of WL#9533. We might have to replace invalidation
with cache update to do this.Also we might have to postpone
such invalidation/update until statement commit time.
*/
if (hton->dict_cache_reset) hton->dict_cache_reset(schema_name, table_name);
#endif
}
return false;
}
bool collect_fk_parents_for_new_fks(
THD *thd, const char *db_name, const char *table_name,
const Alter_info *alter_info, enum_mdl_type lock_type, handlerton *hton,
MDL_request_list *mdl_requests,
Foreign_key_parents_invalidator *fk_invalidator) {
for (const Key_spec *key : alter_info->key_list) {
if (key->type == KEYTYPE_FOREIGN) {
const Foreign_key_spec *fk = down_cast<const Foreign_key_spec *>(key);
if (my_strcasecmp(table_alias_charset, fk->ref_db.str, db_name) == 0 &&
my_strcasecmp(table_alias_charset, fk->ref_table.str, table_name) ==
0)
continue;
MDL_request *mdl_request = new (thd->mem_root) MDL_request;
if (mdl_request == nullptr) return true;
MDL_REQUEST_INIT(mdl_request, MDL_key::TABLE, fk->ref_db.str,
fk->ref_table.str, lock_type, MDL_STATEMENT);
mdl_requests->push_front(mdl_request);
mdl_request = new (thd->mem_root) MDL_request;
if (mdl_request == nullptr) return true;
MDL_REQUEST_INIT(mdl_request, MDL_key::SCHEMA, fk->ref_db.str, "",
MDL_INTENTION_EXCLUSIVE, MDL_STATEMENT);
mdl_requests->push_front(mdl_request);
if (fk_invalidator)
fk_invalidator->add(fk->ref_db.str, fk->ref_table.str, hton);
}
}
return false;
}
bool collect_fk_names_for_new_fks(THD *thd, const char *db_name,
const char *table_name,
const Alter_info *alter_info,
handlerton *hton,
uint fk_max_generated_name_number,
MDL_request_list *mdl_requests) {
char table_name_lc[NAME_LEN + 1];
strmake(table_name_lc, table_name, NAME_LEN);
/*
Prepare lowercase version of table name unless it is in lower case
already. It is to be used for producing lowercase version of FK name
for acquiring metadata lock on it.
*/
if (lower_case_table_names == 0)
my_casedn_str(system_charset_info, table_name_lc);
for (size_t i = 0; i < alter_info->key_list.size(); i++) {
const Key_spec *key = alter_info->key_list[i];
if (key->type == KEYTYPE_FOREIGN) {
const Foreign_key_spec *fk = down_cast<const Foreign_key_spec *>(key);
if (fk->has_explicit_name) {
assert(fk->name.str);
/*
Since foreign key names are case-insensitive we need to lowercase
them before passing to MDL subsystem.
*/
char fk_name[NAME_LEN + 1];
strmake(fk_name, fk->name.str, NAME_LEN);
my_casedn_str(system_charset_info, fk_name);
MDL_request *mdl_request = new (thd->mem_root) MDL_request;
if (mdl_request == nullptr) return true;
MDL_REQUEST_INIT(mdl_request, MDL_key::FOREIGN_KEY, db_name, fk_name,
MDL_EXCLUSIVE, MDL_STATEMENT);
mdl_requests->push_front(mdl_request);
} else {
// The below buffer should be sufficient for any generated name.
char fk_name[NAME_LEN + MAX_FK_NAME_SUFFIX_LENGTH + 10 + 1];
/*
Note that the below code is in sync with generate_fk_name().
Use lower-cased version of table name to generate foreign key
name in lower-case.
Here we truncate generated name if it is too long. This is sufficient
for MDL purposes. Error will be reported later in this case.
*/
generate_fk_name(fk_name, sizeof(fk_name), table_name_lc, hton,
&fk_max_generated_name_number);
MDL_request *mdl_request = new (thd->mem_root) MDL_request;
if (mdl_request == nullptr) return true;
MDL_REQUEST_INIT(mdl_request, MDL_key::FOREIGN_KEY, db_name, fk_name,
MDL_EXCLUSIVE, MDL_STATEMENT);
mdl_requests->push_front(mdl_request);
}
}
}
return false;
}
/**
Implementation of SQLCOM_CREATE_TABLE.
Take the metadata locks (including a shared lock on the affected
schema) and create the table. Is written to be called from
mysql_execute_command(), to which it delegates the common parts
with other commands (i.e. implicit commit before and after,
close of thread tables.
*/
bool mysql_create_table(THD *thd, Table_ref *create_table,
HA_CREATE_INFO *create_info, Alter_info *alter_info) {
bool result = false;
bool is_trans = false;
uint not_used;
handlerton *post_ddl_ht = nullptr;
bool is_pk_generated = false;
Foreign_key_parents_invalidator fk_invalidator;
DBUG_TRACE;
handlerton *actual_hton = get_viable_handlerton_for_create(
thd, create_table->table_name, *create_info);
if (actual_hton == nullptr) return true;
create_info->db_type = actual_hton;
dd::cache::Dictionary_client::Auto_releaser releaser(thd->dd_client());
if (create_info->m_transactional_ddl) {
/*
Stop if START TRANSACTION is requested on table with engine that
does not support atomic DDL.
*/
if (!(create_info->db_type->flags & HTON_SUPPORTS_ATOMIC_DDL)) {
my_error(ER_NOT_ALLOWED_WITH_START_TRANSACTION, MYF(0),
"with engine that does not support atomic DDL.");
result = true;
goto end;
}
// Stop if START TRANSACTION is requested when creating temporary table.
if (create_info->options & HA_LEX_CREATE_TMP_TABLE) {
my_error(ER_NOT_ALLOWED_WITH_START_TRANSACTION, MYF(0),
"to create temporary tables.");
result = true;
goto end;
}
}
/*
Open or obtain "X" MDL lock on the table being created.
To check the existence of table, lock of type "S" is obtained on the table
and then it is upgraded to "X" if table does not exists.
*/
if (open_tables(thd, &thd->lex->query_tables, ¬_used, 0) ||
thd->decide_logging_format(thd->lex->query_tables)) {
result = true;
goto end;
}
/* Got lock. */
DEBUG_SYNC(thd, "locked_table_name");
/*
Do not acquire metadata locks on tables in FK relationships if
table (or view with the same name) exists. They are not necessary
as we won't perform any lookups on them or update of their metadata
in this case.
*/
if (!(create_table->table || create_table->is_view()) &&
!(create_info->options & HA_LEX_CREATE_TMP_TABLE) &&
(create_info->db_type->flags & HTON_SUPPORTS_FOREIGN_KEYS)) {
/*
CREATE TABLE fails under LOCK TABLES at open_tables() time if target
table doesn't exist already. So we don't need to handle LOCK TABLES
case here by checking that parent tables for new FKs are properly
locked and there are no orphan child tables for which table being
created will become parent.
*/
assert(thd->locked_tables_mode != LTM_LOCK_TABLES &&
thd->locked_tables_mode != LTM_PRELOCKED_UNDER_LOCK_TABLES);
MDL_request_list mdl_requests;
if (collect_fk_parents_for_new_fks(thd, create_table->db,
create_table->table_name, alter_info,
MDL_EXCLUSIVE, create_info->db_type,
&mdl_requests, &fk_invalidator) ||
(!dd::get_dictionary()->is_dd_table_name(create_table->db,
create_table->table_name) &&
collect_fk_children(thd, create_table->db, create_table->table_name,
create_info->db_type, MDL_EXCLUSIVE,
&mdl_requests)) ||
collect_fk_names_for_new_fks(thd, create_table->db,
create_table->table_name, alter_info,
create_info->db_type,
0, // No pre-existing FKs
&mdl_requests) ||
(!mdl_requests.is_empty() &&
thd->mdl_context.acquire_locks(&mdl_requests,
thd->variables.lock_wait_timeout))) {
result = true;
goto end;
}
}
// Prepare check constraints.
if (prepare_check_constraints_for_create(
thd, create_table->db, create_table->table_name, alter_info)) {
result = true;
goto end;
}
/*
Promote first timestamp column, when explicit_defaults_for_timestamp
is not set
*/
if (!thd->variables.explicit_defaults_for_timestamp)
promote_first_timestamp_column(&alter_info->create_list);
/*
If mode to generate invisible primary key is active then, generate primary
key for the table.
*/
if (is_generate_invisible_primary_key_mode_active(thd) &&
is_candidate_table_for_invisible_primary_key_generation(create_info,
alter_info)) {
if (validate_and_generate_invisible_primary_key(thd, alter_info)) {
result = true;
goto end;
}
is_pk_generated = true;
}
result = mysql_create_table_no_lock(
thd, create_table->db, create_table->table_name, create_info, alter_info,
0,
/*
We don't need to find parent keys for
FK constraints if table exists.
*/
!(create_table->table || create_table->is_view()), &is_trans,
&post_ddl_ht);
/*
Don't write statement if:
- Table creation has failed
- Row-based logging is used and we are creating a temporary table
Otherwise, the statement shall be binlogged.
*/
if (!result) {
/*
CREATE TEMPORARY TABLE doesn't terminate a transaction. Calling
stmt.mark_created_temp_table() guarantees the transaction can be binlogged
correctly.
*/
if (create_info->options & HA_LEX_CREATE_TMP_TABLE)
thd->get_transaction()->mark_created_temp_table(Transaction_ctx::STMT);
if (!thd->is_current_stmt_binlog_format_row() ||
(thd->is_current_stmt_binlog_format_row() &&
!(create_info->options & HA_LEX_CREATE_TMP_TABLE))) {
thd->add_to_binlog_accessed_dbs(create_table->db);
/*
If primary key is generated for a table then we create version of CREATE
TABLE statement which includes generated key and invisible column
definitions in explicit form by calling store_create_info(). This is
necessary to correctly binlog/replicate such statements, as we don't
write to binary log value of @@sql_generate_invisible_primary_key
variable, but rely on logging what really has been done instead.
*/
if ((create_table->table == nullptr && !create_table->is_view()) &&
is_pk_generated) {
/*
Open table to generate CREATE TABLE statement. For non-temporary
table we already have exclusive lock here.
*/
if (create_info->options & HA_LEX_CREATE_TMP_TABLE) {
result = open_temporary_table(thd, create_table);
} else {
Open_table_context ot_ctx(thd, MYSQL_OPEN_REOPEN);
result = open_table(thd, create_table, &ot_ctx);
// Play safe, remove uncommitted table share from the cache.
tdc_remove_table(thd, TDC_RT_REMOVE_NOT_OWN, create_table->db,
create_table->table_name, false);
}
if (!result) {
char buf[2048];
String query(buf, sizeof(buf), system_charset_info);
query.length(0);
result = store_create_info(thd, create_table, &query, create_info,
true /* show_database */,
false /* SHOW CREATE TABLE */);
assert(result == 0); // store_create_info() always return 0
// Write generated CREATE TABLE statement to binlog.
result =
write_bin_log(thd, true, query.ptr(), query.length(), is_trans);
/*
Handle TABLE instance created for the non-temporary table here to
avoid problems on transaction rollback. close_thread_table() at the
end of statement will take care about the TABLE instance created
for the temporary table.
*/
if (!(create_info->options & HA_LEX_CREATE_TMP_TABLE)) {
/*
close_thread_table() will take care about the TABLE instance we
might have created for the non-temporary table, unless we are
under LOCK TABLES. However, creation of non-temporary table is
not allowed under LOCK TABLES. So we can't get here under LOCK
TABLES.
*/
assert(!thd->locked_tables_mode);
close_thread_table(thd, &thd->open_tables);
create_table->table = nullptr;
}
}
} else {
result = write_bin_log(thd, true, thd->query().str, thd->query().length,
is_trans);
}
}
}
if (!(create_info->options & HA_LEX_CREATE_TMP_TABLE)) {
if (!(create_table->table || create_table->is_view()) && !result &&
(create_info->db_type->flags & HTON_SUPPORTS_FOREIGN_KEYS)) {
if (!dd::get_dictionary()->is_dd_table_name(create_table->db,
create_table->table_name)) {
const dd::Table *new_table = nullptr;
if (thd->dd_client()->acquire(create_table->db,
create_table->table_name, &new_table))
result = true;
else {
assert(new_table != nullptr);
// Check for usage of prefix key index in PARTITION BY KEY() function.
dd::warn_on_deprecated_prefix_key_partition(thd, create_table->db,
create_table->table_name,
new_table, false);
/*
If we are to support FKs for storage engines which don't support
atomic DDL we need to decide what to do for such SEs in case of
failure to update children definitions and adjust code accordingly.
*/
assert(is_trans);
if (adjust_fk_children_after_parent_def_change(
thd, create_table->db, create_table->table_name,
create_info->db_type, new_table, nullptr) ||
adjust_fk_parents(thd, create_table->db, create_table->table_name,
true, nullptr))
result = true;
}
}
}
// Update view metadata.
if (!result) {
Uncommitted_tables_guard uncommitted_tables(thd);
if (!create_table->table && !create_table->is_view())
uncommitted_tables.add_table(create_table);
result = update_referencing_views_metadata(thd, create_table, !is_trans,
&uncommitted_tables);
}
/*
Initialize the create select context with details required to perform
rollback and commit operation after the INSERT's are executed. The
context is freed once transaction is rolled back or committed.
We do it just before transaction commit, so that if there is some
error while creating a table, we can skip this initialization. One
reason to do it this way is that the open_tables() acquires S mdl lock
on table name and then later upgrade lock to X. If there is a error
before the lock upgrade, we would have held S mdl lock, but then
attempt to call tdc_remove_table() would assert during call to
m_transactional_ddl.rollback().
*/
if (!result && create_info->m_transactional_ddl) {
thd->m_transactional_ddl.init(create_table->db, create_table->table_name,
create_info->db_type);
}
/*
Unless we are executing CREATE TEMPORARY TABLE we need to commit
changes to the data-dictionary, SE and binary log and possibly run
handlerton's post-DDL hook.
Also, ignore implicit commit of transaction if we are processing
transactional DDL.
*/
if (!result && !thd->is_plugin_fake_ddl())
result = trans_commit_stmt(thd) ||
(create_info->m_transactional_ddl ? false
: trans_commit_implicit(thd));
if (result && !thd->is_plugin_fake_ddl()) {
trans_rollback_stmt(thd);
/*
Full rollback in case we have THD::transaction_rollback_request
and to synchronize DD state in cache and on disk (as statement
rollback doesn't clear DD cache of modified uncommitted objects).
*/
trans_rollback(thd);
}
/*
In case of CREATE TABLE post-DDL hook is mostly relevant for case
when statement is rolled back. In such cases it is responsibility
of this hook to cleanup files which might be left after failed
table creation attempt. Ignore calling post-DDL hoot if we are
processing transactional DDL.
*/
if (!create_info->m_transactional_ddl && post_ddl_ht)
post_ddl_ht->post_ddl(thd);
if (!result) {
/*
Don't try to invalidate on error as it might be caused by
failure to acquire locks needed for invalidation.
*/
fk_invalidator.invalidate(thd);
}
}
end:
return result;
}
/*
** Give the key name after the first field with an optional '_#' after
**/
static bool check_if_keyname_exists(const char *name, KEY *start, KEY *end) {
for (KEY *key = start; key != end; key++)
if (!my_strcasecmp(system_charset_info, name, key->name)) return true;
return false;
}
static const char *make_unique_key_name(const char *field_name, KEY *start,
KEY *end) {
// NOTE: This may not handle multi-byte characters properly
char buff[NAME_CHAR_LEN + 1];
if (!check_if_keyname_exists(field_name, start, end) &&
my_strcasecmp(system_charset_info, field_name, primary_key_name))
return field_name; // Use fieldname
// Reserve space for '_', two-digit sequence number and terminating null char:
char *buff_end = strmake(buff, field_name, sizeof(buff) - 4);
/*
2 digits support up to 100 keys, which is more than the normal MAX_INDEXES
limit (64).
*/
for (uint i = 2; i < 100; i++) {
*buff_end = '_';
longlong10_to_str(i, buff_end + 1, 10);
if (!check_if_keyname_exists(buff, start, end)) return sql_strdup(buff);
}
return "not_specified"; // Should never happen
}
/* Ignore errors related to invalid collation during rename table. */
class Rename_table_error_handler : public Internal_error_handler {
public:
bool handle_condition(THD *, uint sql_errno, const char *,
Sql_condition::enum_severity_level *,
const char *) override {
return (sql_errno == ER_UNKNOWN_COLLATION ||
sql_errno == ER_PLUGIN_IS_NOT_LOADED);
}
};
/****************************************************************************
** Alter a table definition
****************************************************************************/
/**
Rename histograms from an old table name to a new table name.
@param thd Thread handle
@param old_schema_name The old schema name
@param old_table_name The old table name
@param new_schema_name The new schema name
@param new_table_name The new table name
@return false on success, true on error
*/
static bool rename_histograms(THD *thd, const char *old_schema_name,
const char *old_table_name,
const char *new_schema_name,
const char *new_table_name) {
histograms::results_map results;
bool res =
histograms::rename_histograms(thd, old_schema_name, old_table_name,
new_schema_name, new_table_name, results);
DBUG_EXECUTE_IF("fail_after_rename_histograms", {
my_error(ER_UNABLE_TO_UPDATE_COLUMN_STATISTICS, MYF(0), "dummy_column",
old_schema_name, old_table_name);
res = true;
});
return res;
}
/**
Drop histograms from a given table.
This function will check if an ALTER TABLE statement will make a histogram
invalid:
- Removing columns
- Changing columns (data type, collation and such)
- Adding UNIQUE index
If such change is found, remove any existing histogram for these columns.
@param thd thread handler
@param table the table given in ALTER TABLE
@param alter_info the alter changes to be carried out by ALTER TABLE
@param create_info the alter changes to be carried out by ALTER TABLE
@param columns a list of columns to be changed or dropped
@param original_table_def the table definition, pre altering. Note that the
name returned by original_table_def->name() might
not be the same as table->table_name, since this may
be a backup table object with an auto-generated name
@param altered_table_def the table definition, post altering
@return false on success, true on error
*/
static bool alter_table_drop_histograms(THD *thd, Table_ref *table,
Alter_info *alter_info,
HA_CREATE_INFO *create_info,
histograms::columns_set &columns,
const dd::Table *original_table_def,
const dd::Table *altered_table_def) {
bool alter_drop_column =
(alter_info->flags &
(Alter_info::ALTER_DROP_COLUMN | Alter_info::ALTER_CHANGE_COLUMN));
bool convert_character_set =
(alter_info->flags & Alter_info::ALTER_OPTIONS) &&
(create_info->used_fields & HA_CREATE_USED_CHARSET);
bool encryption_enabled = false;
if (altered_table_def->options().exists("encrypt_type")) {
dd::String_type str;
(void)altered_table_def->options().get("encrypt_type", &str);
encryption_enabled =
0 != my_strcasecmp(system_charset_info, "n", str.c_str());
}
bool single_part_unique_index = false;
/*
Check if we are adding a single-part unique index for a column. If we are,
remove any existing histogram for that column.
*/
if (alter_info->flags & Alter_info::ALTER_ADD_INDEX) {
for (const auto key : altered_table_def->indexes()) {
/*
A key may have multiple elements, such as (DB_ROW_ID, column). So, check
if we only have a single visible element in the unique/primary key.
*/
auto not_hidden = [](const dd::Index_element *element) {
return !element->is_hidden();
};
if ((key->type() == dd::Index::IT_PRIMARY ||
key->type() == dd::Index::IT_UNIQUE) &&
std::count_if(key->elements().begin(), key->elements().end(),
not_hidden) == 1) {
single_part_unique_index = true;
const dd::Index_element *element = *std::find_if(
key->elements().begin(), key->elements().end(), not_hidden);
columns.emplace(element->column().name().c_str());
}
}
}
/*
If we are changing the character set, find all character columns. TEXT and
similar types will be converted similarly as a BLOB/LONG_BLOB etc. but with
a non-binary character set.
*/
if (convert_character_set) {
for (const auto column : altered_table_def->columns()) {
switch (column->type()) {
case dd::enum_column_types::STRING:
case dd::enum_column_types::VAR_STRING:
case dd::enum_column_types::VARCHAR:
case dd::enum_column_types::TINY_BLOB:
case dd::enum_column_types::MEDIUM_BLOB:
case dd::enum_column_types::LONG_BLOB:
case dd::enum_column_types::BLOB:
if (column->collation_id() != my_charset_bin.number)
columns.emplace(column->name().c_str());
break;
default:
continue;
}
}
}
if (alter_drop_column || convert_character_set || encryption_enabled ||
single_part_unique_index) {
histograms::results_map results;
bool res;
if (encryption_enabled)
res = histograms::drop_all_histograms(thd, *table, *original_table_def,
results);
else
res = histograms::drop_histograms(thd, *table, columns, false, results);
DBUG_EXECUTE_IF("fail_after_drop_histograms", {
my_error(ER_UNABLE_TO_DROP_COLUMN_STATISTICS, MYF(0), "dummy_column",
table->db, table->table_name);
res = true;
});
return res;
}
return false;
}
/**
Rename a table.
@param thd Thread handle
@param base The handlerton handle.
@param old_db The old database name.
@param old_name The old table name.
@param old_fk_db The old table db to be used for
identifying self-referencing FKs
which need to be updated.
@param old_fk_name The old table name to be used for
identifying generated FK names and
self-referencing FKs which need to
be updated.
@param new_schema DD object for the new schema.
@param new_db The new database name.
@param new_name The new table name.
@param flags flags
FN_FROM_IS_TMP old_name is temporary.
FN_TO_IS_TMP new_name is temporary.
NO_FK_CHECKS Don't check FK constraints during rename.
NO_DD_COMMIT Don't commit transaction after updating
data-dictionary.
NO_FK_RENAME Don't change generated foreign key names
during rename.
NO_CC_RENAME Don't change generated check constraint
names during rename.
@note Use of NO_DD_COMMIT flag only allowed for SEs supporting atomic DDL.
@note In case when NO_DD_COMMIT flag was used, the caller must rollback
both statement and transaction on failure. This is necessary to
revert results of handler::ha_rename_table() call in case when
update to the data-dictionary which follows it fails. Also this must
be done before any further accesses to DD.
@return false OK
@return true Error
*/
bool mysql_rename_table(THD *thd, handlerton *base, const char *old_db,
const char *old_name, const char *old_fk_db,
const char *old_fk_name, const dd::Schema &new_schema,
const char *new_db, const char *new_name, uint flags) {
DBUG_TRACE;
DBUG_PRINT("enter", ("old: '%s'.'%s' new: '%s'.'%s'", old_db, old_name,
new_db, new_name));
/*
Only SEs which support atomic DDL are allowed not to commit
changes to the data-dictionary.
*/
assert(!(flags & NO_DD_COMMIT) || (base->flags & HTON_SUPPORTS_ATOMIC_DDL));
/*
Check if the new_db database exists. The problem is that some
SE's may not verify if new_db database exists and they might
succeed renaming the table. Moreover, even the InnoDB engine
succeeds renaming the table without verifying if the new_db
database exists when innodb_file_per_table=0.
*/
// Check if we hit FN_REFLEN bytes along with file extension.
char from[FN_REFLEN + 1];
char to[FN_REFLEN + 1];
size_t length;
bool was_truncated;
build_table_filename(from, sizeof(from) - 1, old_db, old_name, "",
flags & FN_FROM_IS_TMP);
length = build_table_filename(to, sizeof(to) - 1, new_db, new_name, "",
flags & FN_TO_IS_TMP, &was_truncated);
if (was_truncated || length + reg_ext_length > FN_REFLEN) {
my_error(ER_IDENT_CAUSES_TOO_LONG_PATH, MYF(0), sizeof(to) - 1, to);
return true;
}
dd::cache::Dictionary_client::Auto_releaser releaser(thd->dd_client());
const dd::Table *from_table_def = nullptr;
dd::Table *to_table_def = nullptr;
if (thd->dd_client()->acquire(old_db, old_name, &from_table_def) ||
thd->dd_client()->acquire_for_modification(old_db, old_name,
&to_table_def))
return true;
Table_ddl_hton_notification_guard notification_guard{
thd,
&(thd->lex->query_block->get_table_list()->mdl_request.key),
ha_ddl_type::HA_RENAME_DDL,
old_db,
old_name,
new_db,
new_name};
if (notification_guard.notify()) return true;
// Tables with a defined secondary engine cannot be renamed, except if:
// (a) The renaming is only temporary, which may happen if e.g.,
// ALGORITHM=COPY is used, OR
// (b) The secondary storage engine supports DDL.
if (from_table_def->options().exists("secondary_engine") &&
!(flags & FN_IS_TMP)) {
LEX_CSTRING secondary_engine;
from_table_def->options().get("secondary_engine", &secondary_engine,
thd->mem_root);
if (!ha_secondary_engine_supports_ddl(thd, secondary_engine)) {
my_error(ER_SECONDARY_ENGINE_DDL, MYF(0));
return true;
}
}
// Set schema id, table name and hidden attribute.
to_table_def->set_schema_id(new_schema.id());
to_table_def->set_name(new_name);
to_table_def->set_hidden((flags & FN_TO_IS_TMP)
? dd::Abstract_table::HT_HIDDEN_DDL
: dd::Abstract_table::HT_VISIBLE);
/* Adjust parent table for self-referencing foreign keys. */
for (dd::Foreign_key *fk : *(to_table_def->foreign_keys())) {
if (my_strcasecmp(table_alias_charset,
fk->referenced_table_schema_name().c_str(),
old_fk_db) == 0 &&
my_strcasecmp(table_alias_charset, fk->referenced_table_name().c_str(),
old_fk_name) == 0) {
fk->set_referenced_table_schema_name(new_db);
fk->set_referenced_table_name(new_name);
}
}
/*
Unless suppressed update generated foreign key names
(as they have table_name<SE-specific or default suffix>#### format).
*/
if (!(flags & NO_FK_RENAME) &&
dd::rename_foreign_keys(thd, old_db, old_fk_name, base, new_db,
to_table_def))
return true;
if (!(flags & NO_CC_RENAME) &&
dd::rename_check_constraints(old_name, to_table_def))
return true;
// Get the handler for the table, and issue an error if we cannot load it.
handler *file =
(base == nullptr ? nullptr
: get_new_handler((TABLE_SHARE *)nullptr,
from_table_def->partition_type() !=
dd::Table::PT_NONE,
thd->mem_root, base));
if (!file) {
my_error(ER_STORAGE_ENGINE_NOT_LOADED, MYF(0), old_db, old_name);
return true;
}
/*
If lower_case_table_names == 2 (case-preserving but case-insensitive
file system) and the storage is not HA_FILE_BASED, we need to provide
a lowercase file name.
*/
char lc_from[FN_REFLEN + 1];
char lc_to[FN_REFLEN + 1];
char *from_base = from;
char *to_base = to;
if (lower_case_table_names == 2 &&
!(file->ha_table_flags() & HA_FILE_BASED)) {
char tmp_name[NAME_LEN + 1];
my_stpcpy(tmp_name, old_name);
my_casedn_str(files_charset_info, tmp_name);
build_table_filename(lc_from, sizeof(lc_from) - 1, old_db, tmp_name, "",
flags & FN_FROM_IS_TMP);
from_base = lc_from;
my_stpcpy(tmp_name, new_name);
my_casedn_str(files_charset_info, tmp_name);
build_table_filename(lc_to, sizeof(lc_to) - 1, new_db, tmp_name, "",
flags & FN_TO_IS_TMP);
to_base = lc_to;
}
/*
Temporarily disable foreign key checks, if requested, while the
handler is involved.
*/
ulonglong save_bits = thd->variables.option_bits;
if (flags & NO_FK_CHECKS)
thd->variables.option_bits |= OPTION_NO_FOREIGN_KEY_CHECKS;
Rename_table_error_handler error_handler;
thd->push_internal_handler(&error_handler);
int error =
file->ha_rename_table(from_base, to_base, from_table_def, to_table_def);
thd->pop_internal_handler();
thd->variables.option_bits = save_bits;
if (error != 0) {
if (error == HA_ERR_WRONG_COMMAND)
my_error(ER_NOT_SUPPORTED_YET, MYF(0), "ALTER TABLE");
else {
char errbuf[MYSYS_STRERROR_SIZE];
my_error(ER_ERROR_ON_RENAME, MYF(0), from, to, error,
my_strerror(errbuf, sizeof(errbuf), error));
}
destroy(file);
return true;
}
/*
Note that before WL#7743 we have renamed table in the data-dictionary
before renaming it in storage engine. However with WL#7743 engines
supporting atomic DDL are allowed to update dd::Table object describing
new version of table in handler::rename_table(). Hence it should saved
after this call.
So to avoid extra calls to DD layer and to keep code simple the
renaming of table in the DD was moved past rename in SE for all SEs.
From crash-safety point of view order doesn't matter for engines
supporting atomic DDL. And for engines which can't do atomic DDL in
either case there are scenarios in which DD and SE get out of sync.
*/
bool result = thd->dd_client()->update(to_table_def);
/*
Only rename histograms when this isn't a rename for temporary names
(we will never have a histogram for a temporary name).
Note that this won't catch "ALTER TABLE ... ALGORITHM=COPY" since the COPY
algorithm will first rename to a temporary name, and then to the final name.
That case is handled in the function mysql_alter_table.
*/
if (!result && !((flags & FN_TO_IS_TMP) || (flags & FN_FROM_IS_TMP))) {
result = rename_histograms(thd, old_db, old_name, new_db, new_name);
}
if (!(flags & NO_DD_COMMIT))
result = trans_intermediate_ddl_commit(thd, result);
if (result) {
/*
In cases when we are executing atomic DDL it is responsibility of the
caller to revert the changes to SE by rolling back transaction.
If storage engine supports atomic DDL but commit was requested by the
caller the above call to trans_intermediate_ddl_commit() will roll
back the transaction on failure and thus revert change to SE.
*/
if (!(flags & NO_DD_COMMIT))
(void)file->ha_rename_table(to_base, from_base, to_table_def,
const_cast<dd::Table *>(from_table_def));
destroy(file);
return true;
}
destroy(file);
#ifdef HAVE_PSI_TABLE_INTERFACE
/*
Remove the old table share from the pfs table share array. The new table
share will be created when the renamed table is first accessed.
*/
bool temp_table = (bool)is_prefix(old_name, tmp_file_prefix);
PSI_TABLE_CALL(drop_table_share)
(temp_table, old_db, static_cast<int>(strlen(old_db)), old_name,
static_cast<int>(strlen(old_name)));
#endif
return false;
}
/*
Create a table identical to the specified table
SYNOPSIS
mysql_create_like_table()
thd Thread object
table Table list element for target table
src_table Table list element for source table
create_info Create info
RETURN VALUES
false OK
true error
*/
bool mysql_create_like_table(THD *thd, Table_ref *table, Table_ref *src_table,
HA_CREATE_INFO *create_info) {
Alter_info local_alter_info(thd->mem_root);
Alter_table_ctx local_alter_ctx; // Not used
bool is_trans = false;
uint not_used;
Tablespace_hash_set tablespace_set(PSI_INSTRUMENT_ME);
handlerton *post_ddl_ht = nullptr;
dd::cache::Dictionary_client::Auto_releaser releaser(thd->dd_client());
DBUG_TRACE;
/*
We the open source table to get its description in HA_CREATE_INFO
and Alter_info objects. This also acquires a shared metadata lock
on this table which ensures that no concurrent DDL operation will
mess with it.
Also in case when we create non-temporary table open_tables()
call obtains an exclusive metadata lock on target table ensuring
that we can safely perform table creation.
Thus by holding both these locks we ensure that our statement is
properly isolated from all concurrent operations which matter.
CREATE LIKE needs to have the logging format determined if in
MIXED mode and creating LIKE a TEMP table.
*/
if (open_tables(thd, &thd->lex->query_tables, ¬_used, 0) ||
thd->decide_logging_format(thd->lex->query_tables))
return true;
src_table->table->use_all_columns();
const dd::Table *src_table_obj = nullptr;
if (!src_table->table->s->tmp_table) {
if (thd->dd_client()->acquire(src_table->db, src_table->table_name,
&src_table_obj)) {
return true;
}
// Should not happen, we know the table exists and can be opened.
assert(src_table_obj != nullptr);
}
DEBUG_SYNC(thd, "create_table_like_after_open");
/* Fill HA_CREATE_INFO and Alter_info with description of source table. */
HA_CREATE_INFO local_create_info;
local_create_info.db_type = get_viable_handlerton_for_create_like(
thd, table->table_name, *create_info, src_table->table->s->db_type());
if (local_create_info.db_type == nullptr) return true;
// This should be ok even if engine substitution has taken place since
// row_type denontes the desired row_type, and a different row_type may be
// assigned to real_row_type later.
local_create_info.row_type = src_table->table->s->row_type;
if (mysql_prepare_alter_table(thd, src_table_obj, src_table->table,
&local_create_info, &local_alter_info,
&local_alter_ctx))
return true;
if (prepare_check_constraints_for_create_like_table(thd, src_table, table,
&local_alter_info))
return true;
for (const Create_field &sql_field : local_alter_info.create_list) {
warn_on_deprecated_float_precision(thd, sql_field);
warn_on_deprecated_float_unsigned(thd, sql_field);
warn_on_deprecated_zerofill(thd, sql_field);
}
/*
During open_tables(), the target tablespace name(s) for a table being
created or altered should be locked. However, for 'CREATE TABLE ... LIKE',
the source table is not being created, yet its tablespace name should be
locked since it is used as the target tablespace name for the table being
created. The target tablespace name cannot be set before open_tables()
(which is how we handle this for e.g. CREATE TABLE ... TABLESPACE ...'),
since before open_tables(), the source table itself is not locked, which
means that a DDL operation may sneak in and change the tablespace of the
source table *after* we retrieved it from the .FRM file of the source
table, and *before* the source table itself is locked. Thus, we lock the
target tablespace here in a separate mdl lock acquisition phase after
open_tables(). Since the table is already opened (and locked), we retrieve
the tablespace name from the table share instead of reading it from the
.FRM file.
*/
/* Partition info is not handled by mysql_prepare_alter_table() call. */
if (src_table->table->part_info)
thd->work_part_info = src_table->table->part_info->get_clone(thd);
// Add the tablespace name, if used.
if (src_table->table->s->tablespace &&
strlen(src_table->table->s->tablespace) > 0) {
assert(
src_table->table->s->tmp_table ||
thd->mdl_context.owns_equal_or_stronger_lock(
MDL_key::TABLE, src_table->db, src_table->table_name, MDL_SHARED));
tablespace_set.insert(src_table->table->s->tablespace);
}
// Add tablespace names used under partition/subpartition definitions.
if (fill_partition_tablespace_names(src_table->table->part_info,
&tablespace_set))
return true;
/*
After we have identified the tablespace names, we iterate
over the names and acquire MDL lock for each of them.
*/
if (lock_tablespace_names(thd, &tablespace_set,
thd->variables.lock_wait_timeout, thd->mem_root)) {
return true;
}
/*
Adjust description of source table before using it for creation of
target table.
Similarly to SHOW CREATE TABLE we ignore MAX_ROWS attribute of
temporary table which represents I_S table.
*/
if (src_table->schema_table) local_create_info.max_rows = 0;
/* Set IF NOT EXISTS option as in the CREATE TABLE LIKE statement. */
local_create_info.options |=
create_info->options & HA_LEX_CREATE_IF_NOT_EXISTS;
/* Replace type of source table with one specified in the statement. */
local_create_info.options &= ~HA_LEX_CREATE_TMP_TABLE;
local_create_info.options |= create_info->options & HA_LEX_CREATE_TMP_TABLE;
/* Reset auto-increment counter for the new table. */
local_create_info.auto_increment_value = 0;
/*
Do not inherit values of DATA and INDEX DIRECTORY options from
the original table. This is documented behavior.
*/
local_create_info.data_file_name = local_create_info.index_file_name =
nullptr;
local_create_info.alias = create_info->alias;
/*
Keep tablespace, only if it was specified explicitly in CREATE
TABLE when source table was created.
*/
if (src_table_obj && !src_table_obj->is_explicit_tablespace()) {
local_create_info.tablespace = nullptr;
}
/*
Do not keep ENCRYPTION clause for unencrypted table.
We raise error if we are creating encrypted temporary table later.
*/
if (local_create_info.encrypt_type.str &&
!dd::is_encrypted(local_create_info.encrypt_type)) {
local_create_info.encrypt_type = {nullptr, 0};
}
/*
Lock the FK children, in case the new table introduces a missing parent.
*/
if (!(table->table || table->is_view()) &&
!(create_info->options & HA_LEX_CREATE_TMP_TABLE) &&
(local_create_info.db_type->flags & HTON_SUPPORTS_FOREIGN_KEYS)) {
/*
CREATE TABLE LIKE fails under LOCK TABLES at open_tables() time if
target table doesn't exist already. So we don't need to handle
LOCK TABLES case here by checking that parent tables for new FKs
are properly locked and there are no orphan child tables for which
table being created will become parent.
*/
assert(thd->locked_tables_mode != LTM_LOCK_TABLES &&
thd->locked_tables_mode != LTM_PRELOCKED_UNDER_LOCK_TABLES);
MDL_request_list mdl_requests;
if ((!dd::get_dictionary()->is_dd_table_name(table->db,
table->table_name) &&
collect_fk_children(thd, table->db, table->table_name,
local_create_info.db_type, MDL_EXCLUSIVE,
&mdl_requests)) ||
(!mdl_requests.is_empty() &&
thd->mdl_context.acquire_locks(&mdl_requests,
thd->variables.lock_wait_timeout)))
return true;
}
if (mysql_create_table_no_lock(
thd, table->db, table->table_name, &local_create_info,
&local_alter_info, 0,
false, // No FKs, no need to lookup parent keys
&is_trans, &post_ddl_ht))
goto err;
/*
Ensure that table or view does not exist and we have an exclusive lock on
target table if we are creating non-temporary table. In LOCK TABLES mode
the only way the table is locked, is if it already exists (since you cannot
LOCK TABLE a non-existing table). And the only way we then can end up here
is if IF EXISTS was used.
*/
assert(
table->table || table->is_view() ||
(create_info->options & HA_LEX_CREATE_TMP_TABLE) ||
(thd->locked_tables_mode != LTM_LOCK_TABLES &&
thd->mdl_context.owns_equal_or_stronger_lock(
MDL_key::TABLE, table->db, table->table_name, MDL_EXCLUSIVE)) ||
(thd->locked_tables_mode == LTM_LOCK_TABLES &&
(create_info->options & HA_LEX_CREATE_IF_NOT_EXISTS) &&
thd->mdl_context.owns_equal_or_stronger_lock(
MDL_key::TABLE, table->db, table->table_name, MDL_SHARED_NO_WRITE)));
DEBUG_SYNC(thd, "create_table_like_before_binlog");
/*
CREATE TEMPORARY TABLE doesn't terminate a transaction. Calling
stmt.mark_created_temp_table() guarantees the transaction can be binlogged
correctly.
*/
if (create_info->options & HA_LEX_CREATE_TMP_TABLE)
thd->get_transaction()->mark_created_temp_table(Transaction_ctx::STMT);
/*
We have to write the query before we unlock the tables.
*/
if (!thd->is_current_stmt_binlog_disabled() &&
thd->is_current_stmt_binlog_format_row()) {
/*
Since temporary tables are not replicated under row-based
replication, CREATE TABLE ... LIKE ... needs special
treatment. We have four cases to consider, according to the
following decision table:
==== ========= ========= ==============================
Case Target Source Write to binary log
==== ========= ========= ==============================
1 normal normal Original statement
2 normal temporary Generated statement
3 temporary normal Nothing
4 temporary temporary Nothing
==== ========= ========= ==============================
*/
if (!(create_info->options & HA_LEX_CREATE_TMP_TABLE)) {
if (src_table->table->s->tmp_table) // Case 2
{
char buf[2048];
String query(buf, sizeof(buf), system_charset_info);
query.length(0); // Have to zero it since constructor doesn't
Open_table_context ot_ctx(thd, MYSQL_OPEN_REOPEN);
bool new_table = false; // Whether newly created table is open.
/*
The condition avoids a crash as described in BUG#48506. Other
binlogging problems related to CREATE TABLE IF NOT EXISTS LIKE
when the existing object is a view will be solved by BUG 47442.
*/
if (!table->is_view()) {
if (!table->table) {
/*
In order for store_create_info() to work we need to open
destination table if it is not already open (i.e. if it
has not existed before). We don't need acquire metadata
lock in order to do this as we already hold exclusive
lock on this table. The table will be closed by
close_thread_table() at the end of this branch.
*/
bool result = open_table(thd, table, &ot_ctx);
/*
Play safe, ensure that we won't poison TDC/TC by storing
not-yet-committed table definition there.
*/
tdc_remove_table(thd, TDC_RT_REMOVE_NOT_OWN, table->db,
table->table_name, false);
if (result) goto err;
new_table = true;
}
/*
After opening a MERGE table add the children to the query list of
tables, so that children tables info can be used on "CREATE TABLE"
statement generation by the binary log.
Note that placeholders don't have the handler open.
*/
if (table->table->file->ha_extra(HA_EXTRA_ADD_CHILDREN_LIST)) {
if (new_table) {
assert(thd->open_tables == table->table);
close_thread_table(thd, &thd->open_tables);
table->table = nullptr;
}
goto err;
}
/*
As the reference table is temporary and may not exist on slave, we
must force the ENGINE to be present into CREATE TABLE.
*/
create_info->used_fields |= HA_CREATE_USED_ENGINE;
bool result [[maybe_unused]] = store_create_info(
thd, table, &query, create_info, true /* show_database */,
false /* SHOW CREATE TABLE */);
assert(result == 0); // store_create_info() always return 0
if (new_table) {
assert(thd->open_tables == table->table);
/*
When opening the table, we ignored the locked tables
(MYSQL_OPEN_GET_NEW_TABLE). Now we can close the table
without risking to close some locked table.
*/
close_thread_table(thd, &thd->open_tables);
table->table = nullptr;
}
if (write_bin_log(thd, true, query.ptr(), query.length(), is_trans))
goto err;
}
} else // Case 1
if (write_bin_log(thd, true, thd->query().str, thd->query().length,
is_trans))
goto err;
}
/*
Case 3 and 4 does nothing under RBR
*/
} else if (write_bin_log(thd, true, thd->query().str, thd->query().length,
is_trans))
goto err;
if (!(create_info->options & HA_LEX_CREATE_TMP_TABLE)) {
/*
Update the FK information for the children that were locked previously.
*/
if (!(table->table || table->is_view()) &&
!dd::get_dictionary()->is_dd_table_name(table->db, table->table_name) &&
(local_create_info.db_type->flags & HTON_SUPPORTS_FOREIGN_KEYS)) {
const dd::Table *new_table = nullptr;
if (thd->dd_client()->acquire(table->db, table->table_name, &new_table))
goto err;
else {
assert(new_table != nullptr);
/*
If we are to support FKs for storage engines which don't support
atomic DDL we need to decide what to do for such SEs in case of
failure to update children definitions and adjust code accordingly.
*/
assert(is_trans);
if (adjust_fk_children_after_parent_def_change(
thd, table->db, table->table_name, local_create_info.db_type,
new_table, nullptr) ||
adjust_fk_parents(thd, table->db, table->table_name, true, nullptr))
goto err;
}
}
/*
Update view metadata. Use nested block to ensure that TDC
invalidation happens before commit.
*/
{
Uncommitted_tables_guard uncommitted_tables(thd);
if (!table->table && !table->is_view())
uncommitted_tables.add_table(table);
if (update_referencing_views_metadata(thd, table, !is_trans,
&uncommitted_tables))
goto err;
}
if (trans_commit_stmt(thd) || trans_commit_implicit(thd)) goto err;
if (post_ddl_ht) post_ddl_ht->post_ddl(thd);
}
return false;
err:
if (!(create_info->options & HA_LEX_CREATE_TMP_TABLE)) {
trans_rollback_stmt(thd);
/*
Full rollback in case we have THD::transaction_rollback_request
and to synchronize DD state in cache and on disk (as statement
rollback doesn't clear DD cache of modified uncommitted objects).
*/
trans_rollback(thd);
if (post_ddl_ht) post_ddl_ht->post_ddl(thd);
}
return true;
}
/* table_list should contain just one table */
bool Sql_cmd_discard_import_tablespace::mysql_discard_or_import_tablespace(
THD *thd, Table_ref *table_list) {
Alter_table_prelocking_strategy alter_prelocking_strategy;
int error;
DBUG_TRACE;
/*
Note that DISCARD/IMPORT TABLESPACE always is the only operation in an
ALTER TABLE
*/
/*
DISCARD/IMPORT TABLESPACE do not respect ALGORITHM and LOCK clauses.
*/
if (m_alter_info->requested_lock != Alter_info::ALTER_TABLE_LOCK_DEFAULT) {
my_error(ER_ALTER_OPERATION_NOT_SUPPORTED, MYF(0),
"LOCK=NONE/SHARED/EXCLUSIVE", "LOCK=DEFAULT");
return true;
} else if (m_alter_info->requested_algorithm !=
Alter_info::ALTER_TABLE_ALGORITHM_DEFAULT) {
my_error(ER_ALTER_OPERATION_NOT_SUPPORTED, MYF(0),
"ALGORITHM=COPY/INPLACE/INSTANT", "ALGORITHM=DEFAULT");
return true;
}
THD_STAGE_INFO(thd, stage_discard_or_import_tablespace);
/*
Adjust values of table-level and metadata which was set in parser
for the case general ALTER TABLE.
*/
table_list->mdl_request.set_type(MDL_EXCLUSIVE);
table_list->set_lock({TL_WRITE, THR_DEFAULT});
/* Do not open views. */
table_list->required_type = dd::enum_table_type::BASE_TABLE;
if (open_and_lock_tables(thd, table_list, 0, &alter_prelocking_strategy)) {
/* purecov: begin inspected */
return true;
/* purecov: end */
}
if (table_list->table->part_info) {
/*
If not ALL is mentioned and there is at least one specified
[sub]partition name, use the specified [sub]partitions only.
*/
if (m_alter_info->partition_names.elements > 0 &&
!(m_alter_info->flags & Alter_info::ALTER_ALL_PARTITION)) {
table_list->partition_names = &m_alter_info->partition_names;
/* Set all [named] partitions as used. */
if (table_list->table->part_info->set_partition_bitmaps(table_list))
return true;
}
} else {
if (m_alter_info->partition_names.elements > 0 ||
m_alter_info->flags & Alter_info::ALTER_ALL_PARTITION) {
/* Don't allow DISCARD/IMPORT PARTITION on a nonpartitioned table */
my_error(ER_PARTITION_MGMT_ON_NONPARTITIONED, MYF(0));
return true;
}
}
bool is_non_tmp_table = (table_list->table->s->tmp_table == NO_TMP_TABLE);
handlerton *hton = table_list->table->s->db_type();
dd::cache::Dictionary_client::Auto_releaser releaser(thd->dd_client());
dd::Table *table_def = nullptr;
if (is_non_tmp_table) {
if (thd->dd_client()->acquire_for_modification(
table_list->db, table_list->table_name, &table_def))
return true;
/* Table was successfully opened above. */
assert(table_def != nullptr);
} else
table_def = table_list->table->s->tmp_table_def;
/*
Under LOCK TABLES we need to upgrade SNRW metadata lock to X lock
before doing discard or import of tablespace.
Skip this step for temporary tables as metadata locks are not
applicable for them.
Remember the ticket for the future downgrade.
*/
MDL_ticket *mdl_ticket = nullptr;
if (is_non_tmp_table &&
(thd->locked_tables_mode == LTM_LOCK_TABLES ||
thd->locked_tables_mode == LTM_PRELOCKED_UNDER_LOCK_TABLES)) {
mdl_ticket = table_list->table->mdl_ticket;
if (thd->mdl_context.upgrade_shared_lock(mdl_ticket, MDL_EXCLUSIVE,
thd->variables.lock_wait_timeout))
return true;
}
/*
The parser sets a flag in the Alter_info struct to indicate
whether this is DISCARD or IMPORT. The flag is used for two purposes:
1. To submit the appropriate parameter to the SE to indicate which
operation is to be performed (see the source code below).
2. To implement a callback function (the plugin API function
'thd_tablespace_op()') allowing the SEs supporting these
operations to check if we are doing a DISCARD or IMPORT, in order to
suppress errors otherwise being thrown when opening tables with a
missing tablespace.
*/
bool discard = (m_alter_info->flags & Alter_info::ALTER_DISCARD_TABLESPACE);
error = table_list->table->file->ha_discard_or_import_tablespace(discard,
table_def);
THD_STAGE_INFO(thd, stage_end);
if (error) {
table_list->table->file->print_error(error, MYF(0));
} else {
// When we have imported a tablespace we need to remove any old SDIs stored
// in it because new SDIs need not have the same keys as those found in the
// tablspace.
if ((m_alter_info->flags & Alter_info::ALTER_IMPORT_TABLESPACE)) {
// When we have imported tablespaces for individual partitions, we must
// limit SDI removal to the tablespaces for the mentioned partitions.
if (m_alter_info->partition_names.elements > 0) {
DBUG_PRINT("ddsdi", ("Import partition tablespace for query:%s",
thd->query().str));
const auto &pi = *table_list->table->part_info;
#ifndef NDEBUG
for (const auto &pn : *table_list->partition_names) {
DBUG_PRINT("ddsdi", ("Importing partition %s", pn.ptr()));
}
const auto &part_name_hash =
*static_cast<Partition_share *>(table_list->table->s->ha_share)
->partition_name_hash;
#endif /* NDEBUG */
uint pa_id = 0;
for (const auto &lp : *table_def->leaf_partitions()) {
#ifndef NDEBUG
// Verify that part_id corresponds to index in leaf partition vector.
auto part_def = find_or_nullptr(
part_name_hash,
std::string(lp->name().c_str(), lp->name().length()));
assert(part_def != nullptr);
assert(part_def->part_id == pa_id);
#endif /* NDEBUG */
DBUG_PRINT("ddsdi",
("Checking leaf partition %s, is_used(pa_id:%u):%s",
lp->name().c_str(), pa_id,
pi.is_partition_used(pa_id) ? "true" : "false"));
if (pi.is_partition_used(pa_id) &&
dd::sdi::drop_all_for_part(thd, lp)) {
error = 1;
break;
}
++pa_id;
}
} else {
assert(m_alter_info->partition_names.elements == 0);
// We get here when we have imported a table tablespace, or all
// partition tablespaces. In this case, we remove SDIs from all
// tablespaces associated with the table.
if (dd::sdi::drop_all_for_table(thd, table_def)) {
error = 1;
}
}
}
/*
Storage engine supporting atomic DDL can fully rollback discard/
import if any problem occurs. This will happen during statement
rollback.
In case of success we need to save dd::Table object which might
have been updated by SE. If this step or subsequent write to binary
log fail then statement rollback will also restore status quo ante.
*/
if (!error && is_non_tmp_table &&
(hton->flags & HTON_SUPPORTS_ATOMIC_DDL) &&
thd->dd_client()->update(table_def))
error = 1;
if (!error)
error = write_bin_log(thd, false, thd->query().str, thd->query().length,
(hton->flags & HTON_SUPPORTS_ATOMIC_DDL));
/*
TODO: In theory since we have updated table definition in the
data-dictionary above we need to remove its TABLE/TABLE_SHARE
from TDC now. However this makes InnoDB to produce too many
warnings about discarded tablespace which are not always well
justified. So this code should be enabled after InnoDB is
adjusted to be less verbose in these cases.
*/
#ifdef NEEDS_SUPPORT_FROM_INNODB
if (is_non_tmp_table)
close_all_tables_for_name(thd, table_list->table->s, false, nullptr);
table_list->table = nullptr; // Safety.
#endif
}
if (!error) error = trans_commit_stmt(thd) || trans_commit_implicit(thd);
if (error) {
trans_rollback_stmt(thd);
trans_rollback_implicit(thd);
}
if (is_non_tmp_table && (hton->flags & HTON_SUPPORTS_ATOMIC_DDL) &&
hton->post_ddl)
hton->post_ddl(thd);
if (thd->locked_tables_mode && thd->locked_tables_list.reopen_tables(thd))
error = 1;
if (mdl_ticket) mdl_ticket->downgrade_lock(MDL_SHARED_NO_READ_WRITE);
if (error == 0) {
my_ok(thd);
return false;
}
return true;
}
/**
* Loads a table into a secondary engine if SECONDARY_LOAD, unloads from
* secondary engine if SECONDARY_UNLOAD.
*
* @param thd Thread handler.
* @param table_list Table to load.
*
* @return True if error, false otherwise.
*/
bool Sql_cmd_secondary_load_unload::mysql_secondary_load_or_unload(
THD *thd, Table_ref *table_list) {
Alter_table_prelocking_strategy alter_prelocking_strategy;
// Because SECONDARY_LOAD and SECONDARY_UNLOAD are standalone alter table
// actions, it should be impossible to set ALGORITHM and LOCK.
assert(m_alter_info->requested_lock == Alter_info::ALTER_TABLE_LOCK_DEFAULT);
assert(m_alter_info->requested_algorithm ==
Alter_info::ALTER_TABLE_ALGORITHM_DEFAULT);
table_list->mdl_request.set_type(MDL_EXCLUSIVE);
// Always use isolation level READ_COMMITTED to ensure consistent view of
// table data during entire load operation. Higher isolation levels provide no
// benefits for this operation and could impact performance, so it's fine to
// downgrade from both REPEATABLE_READ and SERIALIZABLE.
const enum_tx_isolation orig_tx_isolation = thd->tx_isolation;
auto tx_isolation_guard = create_scope_guard(
[thd, orig_tx_isolation] { thd->tx_isolation = orig_tx_isolation; });
thd->tx_isolation = ISO_READ_COMMITTED;
// Open base table.
table_list->required_type = dd::enum_table_type::BASE_TABLE;
if (open_and_lock_tables(thd, table_list, 0, &alter_prelocking_strategy))
return true;
// Omit hidden generated columns and columns marked as NOT SECONDARY from
// read_set. It is the responsibility of the secondary engine handler to load
// only the columns included in the read_set.
bitmap_clear_all(table_list->table->read_set);
for (Field **field = table_list->table->field; *field != nullptr; ++field) {
// Skip hidden generated columns.
if (bitmap_is_set(&table_list->table->fields_for_functional_indexes,
(*field)->field_index()))
continue;
// Skip columns marked as NOT SECONDARY.
if ((*field)->is_flag_set(NOT_SECONDARY_FLAG)) continue;
// Mark column as eligible for loading.
table_list->table->mark_column_used(*field, MARK_COLUMNS_READ);
}
// SECONDARY_LOAD/SECONDARY_UNLOAD requires a secondary engine.
if (!table_list->table->s->has_secondary_engine()) {
my_error(ER_SECONDARY_ENGINE, MYF(0), "No secondary engine defined");
return true;
}
// It should not have been possible to define a temporary table with a
// secondary engine.
assert(table_list->table->s->tmp_table == NO_TMP_TABLE);
handlerton *hton = table_list->table->s->db_type();
assert(hton->flags & HTON_SUPPORTS_ATOMIC_DDL &&
hton->flags & HTON_SUPPORTS_SECONDARY_ENGINE &&
hton->post_ddl != nullptr);
// cache table name locally for future use
const size_t name_len = table_list->db_length +
table_list->table_name_length +
5; // for backticks, dot `db`.`tab`
// allocated on thread, freed-up on thread exit
char *full_tab_name = (char *)sql_calloc(name_len + 1); // for \0 at the end
sprintf(full_tab_name, "`%s`.`%s`", table_list->db, table_list->table_name);
full_tab_name[name_len] = '\0'; // may not needed, since inited with 0
dd::cache::Dictionary_client::Auto_releaser releaser(thd->dd_client());
dd::Table *table_def = nullptr;
if (thd->dd_client()->acquire_for_modification(
table_list->db, table_list->table_name, &table_def))
return true;
MDL_ticket *mdl_ticket = table_list->table->mdl_ticket;
auto downgrade_guard = create_scope_guard([mdl_ticket, thd] {
// Under LOCK TABLES, downgrade to MDL_SHARED_NO_READ_WRITE after all
// operations have completed.
if (secondary_engine_lock_tables_mode(*thd)) {
mdl_ticket->downgrade_lock(MDL_SHARED_NO_READ_WRITE);
}
});
if (thd->mdl_context.upgrade_shared_lock(mdl_ticket, MDL_EXCLUSIVE,
thd->variables.lock_wait_timeout))
return true;
// Cleanup that must be done regardless of commit or rollback.
auto cleanup = [thd, hton]() {
hton->post_ddl(thd);
return thd->locked_tables_mode &&
thd->locked_tables_list.reopen_tables(thd);
};
// This scope guard is responsible for rolling back the transaction in case of
// any errors.
auto rollback_guard = create_scope_guard([thd, cleanup] {
trans_rollback_stmt(thd);
trans_rollback_implicit(thd);
cleanup();
});
/* Currently, if the DDL rolls back after completing the secondary engine
* operation, then during undo only the secondary_flag update is undone, but
* the secondary engine operation (load/unload) is not undone. This creates
* a temporary inconsistency in the system where the secondary_load flag is
* not in sync with the actual status of the table in the secondary engine. */
// TODO: undo handling of secondary engine operation
// Load if SECONDARY_LOAD, unload if SECONDARY_UNLOAD
const bool is_load = m_alter_info->flags & Alter_info::ALTER_SECONDARY_LOAD;
// Initiate loading into or unloading from secondary engine.
if (is_load) {
DEBUG_SYNC(thd, "before_secondary_engine_load_table");
if (DBUG_EVALUATE_IF("sim_secload_fail",
(my_error(ER_SECONDARY_ENGINE, MYF(0),
"Simulated failure of secondary_load()"),
true),
false) ||
secondary_engine_load_table(thd, *table_list->table))
return true;
} else {
if (DBUG_EVALUATE_IF("sim_secunload_fail",
(my_error(ER_SECONDARY_ENGINE, MYF(0),
"Simulated failure of secondary_unload()"),
true),
false) ||
secondary_engine_unload_table(thd, table_list->db,
table_list->table_name, *table_def, true))
return true;
}
DBUG_PRINT("sec_load_unload", ("secondary engine %s succeeded for table %s",
(is_load ? "load" : "unload"), full_tab_name));
DBUG_EXECUTE_IF("sim_fail_before_metadata_update", {
DBUG_PRINT("sec_load_unload", ("Force exit before metadata update"));
my_error(
ER_SECONDARY_ENGINE, MYF(0),
"Simulated failure of sec_{un}load before secondary_load flag update");
return true;
});
// Update the secondary_load flag based on the current operation.
if (DBUG_EVALUATE_IF("sim_fail_metadata_update",
(my_error(ER_SECONDARY_ENGINE, MYF(0),
"Simulated failure during metadata update"),
true),
false) ||
table_def->options().set("secondary_load", is_load) ||
thd->dd_client()->update(table_def)) {
LogErr(ERROR_LEVEL, ER_SECONDARY_ENGINE_DDL_FAILED, full_tab_name,
(is_load ? "secondary_load" : "secondary_unload"),
"metadata update failed");
return true;
}
DBUG_PRINT("sec_load_unload", ("secondary_load flag %s for table %s",
(is_load ? "set" : "reset"), full_tab_name));
DBUG_EXECUTE_IF("sim_fail_before_write_bin_log", {
DBUG_PRINT("sec_load_unload", ("Force exit before binlog write"));
my_error(ER_SECONDARY_ENGINE, MYF(0),
"Simulated failure of sec_{un}load before write_bin_log()");
return true;
});
/* Write binlog to maintain replication consistency. Read-Replica's may not
* have binlog enabled. write_bin_log API takes care of such cases. */
if (DBUG_EVALUATE_IF("sim_fail_binlog_write",
(my_error(ER_SECONDARY_ENGINE, MYF(0),
"Simulated failure during binlog write"),
true),
false) ||
(write_bin_log(thd, true, thd->query().str, thd->query().length, true) !=
0)) {
LogErr(ERROR_LEVEL, ER_SECONDARY_ENGINE_DDL_FAILED, full_tab_name,
(is_load ? "secondary_load" : "secondary_unload"),
"binlog write failed");
return true;
}
DBUG_PRINT("sec_load_unload",
("binlog entry added for alter table %s secondary_%s",
full_tab_name, (is_load ? "load" : "unload")));
DBUG_EXECUTE_IF("sim_fail_after_write_bin_log", {
DBUG_PRINT("sec_load_unload", ("Force exit after binlog write"));
my_error(ER_SECONDARY_ENGINE, MYF(0),
"Simulated failure of sec_{un}load after write_bin_log()");
return true;
});
// Close primary table.
close_all_tables_for_name(thd, table_list->table->s, false, nullptr);
table_list->table = nullptr;
// Commit transaction if no errors.
if (DBUG_EVALUATE_IF("sim_fail_transaction_commit",
(my_error(ER_SECONDARY_ENGINE, MYF(0),
"Simulated failure during metadata update"),
true),
false) ||
trans_commit_stmt(thd) || trans_commit_implicit(thd)) {
LogErr(ERROR_LEVEL, ER_SECONDARY_ENGINE_DDL_FAILED, full_tab_name,
(is_load ? "secondary_load" : "secondary_unload"),
"transaction commit failed");
return true;
}
DBUG_PRINT("sec_load_unload",
("commit succeeded for alter table %s secondary_%s", full_tab_name,
(is_load ? "load" : "unload")));
// Transaction committed successfully, no rollback will be necessary.
rollback_guard.release();
if (cleanup()) return true;
my_ok(thd);
return false;
}
/**
Check if key is a candidate key, i.e. a unique index with no index
fields partial, nullable or virtual generated.
*/
static bool is_candidate_key(KEY *key) {
KEY_PART_INFO *key_part;
KEY_PART_INFO *key_part_end = key->key_part + key->user_defined_key_parts;
if (!(key->flags & HA_NOSAME) || (key->flags & HA_NULL_PART_KEY))
return false;
if (key->flags & HA_VIRTUAL_GEN_KEY) return false;
for (key_part = key->key_part; key_part < key_part_end; key_part++) {
if (key_part->key_part_flag & HA_PART_KEY_SEG) return false;
}
return true;
}
/**
Get Create_field object for newly created table by field index.
@param alter_info Alter_info describing newly created table.
@param idx Field index.
*/
static const Create_field *get_field_by_index(Alter_info *alter_info,
uint idx) {
List_iterator_fast<Create_field> field_it(alter_info->create_list);
uint field_idx = 0;
const Create_field *field;
while ((field = field_it++) && field_idx < idx) {
field_idx++;
}
return field;
}
/**
Look-up KEY object by index name using case-insensitive comparison.
@param key_name Index name.
@param key_start Start of array of KEYs for table.
@param key_end End of array of KEYs for table.
@note Skips indexes which are marked as renamed.
@note Case-insensitive comparison is necessary to correctly
handle renaming of keys.
@retval non-NULL - pointer to KEY object for index found.
@retval NULL - no index with such name found (or it is marked
as renamed).
*/
static KEY *find_key_ci(const char *key_name, KEY *key_start, KEY *key_end) {
for (KEY *key = key_start; key < key_end; key++) {
/* Skip already renamed keys. */
if (!(key->flags & HA_KEY_RENAMED) &&
!my_strcasecmp(system_charset_info, key_name, key->name))
return key;
}
return nullptr;
}
/**
Look-up KEY object by index name using case-sensitive comparison.
@param key_name Index name.
@param key_start Start of array of KEYs for table.
@param key_end End of array of KEYs for table.
@note Skips indexes which are marked as renamed.
@note Case-sensitive comparison is necessary to correctly
handle: ALTER TABLE t1 DROP KEY x, ADD KEY X(c).
where new and old index are identical except case
of their names (in this case index still needs
to be re-created to keep case of the name in .FRM
and storage-engine in sync).
@retval non-NULL - pointer to KEY object for index found.
@retval NULL - no index with such name found (or it is marked
as renamed).
*/
static KEY *find_key_cs(const char *key_name, KEY *key_start, KEY *key_end) {
for (KEY *key = key_start; key < key_end; key++) {
/* Skip renamed keys. */
if (!(key->flags & HA_KEY_RENAMED) && !strcmp(key_name, key->name))
return key;
}
return nullptr;
}
/**
Check if index has changed in a new version of table (ignore
possible rename of index). Also changes to the comment field
of the key is marked with a flag in the ha_alter_info.
@param[in,out] ha_alter_info Structure describing changes to be done
by ALTER TABLE and holding data used
during in-place alter.
@param table_key Description of key in old version of table.
@param new_key Description of key in new version of table.
@returns True - if index has changed, false -otherwise.
*/
static bool has_index_def_changed(Alter_inplace_info *ha_alter_info,
const KEY *table_key, const KEY *new_key) {
const KEY_PART_INFO *key_part, *new_part, *end;
const Create_field *new_field;
Alter_info *alter_info = ha_alter_info->alter_info;
/* Check that the key types are compatible between old and new tables. */
if ((table_key->algorithm != new_key->algorithm) ||
((table_key->flags & HA_KEYFLAG_MASK) !=
(new_key->flags & HA_KEYFLAG_MASK)) ||
(table_key->user_defined_key_parts != new_key->user_defined_key_parts))
return true;
/*
If an index comment is added/dropped/changed, then mark it for a
fast/INPLACE alteration.
*/
if ((table_key->comment.length != new_key->comment.length) ||
(table_key->comment.length &&
strcmp(table_key->comment.str, new_key->comment.str)))
ha_alter_info->handler_flags |= Alter_inplace_info::ALTER_INDEX_COMMENT;
/*
Check that the key parts remain compatible between the old and
new tables.
*/
end = table_key->key_part + table_key->user_defined_key_parts;
for (key_part = table_key->key_part, new_part = new_key->key_part;
key_part < end; key_part++, new_part++) {
new_field = get_field_by_index(alter_info, new_part->fieldnr);
/*
If there is a change in index length due to column expansion
like varchar(X) changed to varchar(X + N) and has a compatible
packed data representation, we mark it for fast/INPLACE change
in index definition. Some engines like InnoDB supports INPLACE
alter for such cases.
In other cases, key definition has changed if we are using a
different field or if the used key part length is different, or
key part direction has changed.
*/
if (key_part->length != new_part->length &&
ha_alter_info->alter_info->flags == Alter_info::ALTER_CHANGE_COLUMN &&
(key_part->field->is_equal(new_field) == IS_EQUAL_PACK_LENGTH)) {
ha_alter_info->handler_flags |=
Alter_inplace_info::ALTER_COLUMN_INDEX_LENGTH;
} else if (key_part->length != new_part->length)
return true;
if ((key_part->key_part_flag & HA_REVERSE_SORT) !=
(new_part->key_part_flag & HA_REVERSE_SORT))
return true;
/*
For prefix keys KEY_PART_INFO::field points to cloned Field
object with adjusted length. So below we have to check field
indexes instead of simply comparing pointers to Field objects.
*/
if (!new_field->field ||
new_field->field->field_index() != key_part->fieldnr - 1)
return true;
/*
Key definition has changed, if the key is converted from a
non-prefixed key to a prefixed key or vice-versa. This
is because InnoDB treats prefix keys differently from
full-column keys. Ignoring BLOBs since the key_length()
is not set correctly and also the prefix is ignored
for FULLTEXT keys.
Ex: When the column length is increased but the key part
length remains the same.
*/
if (!(new_field->flags & BLOB_FLAG) &&
(table_key->algorithm != HA_KEY_ALG_FULLTEXT)) {
bool old_part_key_seg = (key_part->key_part_flag & HA_PART_KEY_SEG);
bool new_part_key_seg = (new_field->key_length() != new_part->length);
if (old_part_key_seg ^ new_part_key_seg) return true;
}
}
return false;
}
/**
Compare original and new versions of a table and fill Alter_inplace_info
describing differences between those versions.
@param thd Thread
@param table The original table.
@param[in,out] ha_alter_info Data structure which already contains
basic information about create options,
field and keys for the new version of
table and which should be completed with
more detailed information needed for
in-place ALTER.
First argument 'table' contains information of the original
table, which includes all corresponding parts that the new
table has in arguments create_list, key_list and create_info.
Compare the changes between the original and new table definitions.
The result of this comparison is then passed to SE which determines
whether it can carry out these changes in-place.
Mark any changes detected in the ha_alter_flags.
We generally try to specify handler flags only if there are real
changes. But in cases when it is cumbersome to determine if some
attribute has really changed we might choose to set flag
pessimistically, for example, relying on parser output only.
If there are no data changes, but index changes, 'index_drop_buffer'
and/or 'index_add_buffer' are populated with offsets into
table->key_info or key_info_buffer respectively for the indexes
that need to be dropped and/or (re-)created.
Note that this function assumes that it is OK to change Alter_info
and HA_CREATE_INFO which it gets. It is caller who is responsible
for creating copies for this structures if he needs them unchanged.
@retval true error
@retval false success
*/
static bool fill_alter_inplace_info(THD *thd, TABLE *table,
Alter_inplace_info *ha_alter_info) {
Field **f_ptr, *field;
List_iterator_fast<Create_field> new_field_it;
Create_field *new_field;
uint candidate_key_count = 0;
Alter_info *alter_info = ha_alter_info->alter_info;
Prealloced_array<Field *, 1> gcols_with_unchanged_expr(PSI_INSTRUMENT_ME);
// Names of columns which default might have changed.
Prealloced_array<const char *, 1> cols_with_default_change(PSI_INSTRUMENT_ME);
// Old table version columns which were renamed or dropped.
Prealloced_array<const Field *, 1> dropped_or_renamed_cols(PSI_INSTRUMENT_ME);
DBUG_TRACE;
/* Allocate result buffers. */
if (!(ha_alter_info->index_drop_buffer =
(KEY **)thd->alloc(sizeof(KEY *) * table->s->keys)) ||
!(ha_alter_info->index_add_buffer =
(uint *)thd->alloc(sizeof(uint) * alter_info->key_list.size())) ||
!(ha_alter_info->index_rename_buffer = (KEY_PAIR *)thd->alloc(
sizeof(KEY_PAIR) * alter_info->alter_rename_key_list.size())) ||
!(ha_alter_info->index_altered_visibility_buffer = (KEY_PAIR *)thd->alloc(
sizeof(KEY_PAIR) * alter_info->alter_index_visibility_list.size())))
return true;
/* First we setup ha_alter_flags based on what was detected by parser. */
/*
Comparing new and old default values of column is cumbersome.
So instead of using such a comparison for detecting if default
has really changed we rely on flags set by parser to get an
approximate value for storage engine flag.
*/
if (alter_info->flags & (Alter_info::ALTER_CHANGE_COLUMN |
Alter_info::ALTER_CHANGE_COLUMN_DEFAULT))
ha_alter_info->handler_flags |= Alter_inplace_info::ALTER_COLUMN_DEFAULT;
if (alter_info->flags & Alter_info::ADD_FOREIGN_KEY)
ha_alter_info->handler_flags |= Alter_inplace_info::ADD_FOREIGN_KEY;
if (alter_info->flags & Alter_info::DROP_FOREIGN_KEY)
ha_alter_info->handler_flags |= Alter_inplace_info::DROP_FOREIGN_KEY;
if (alter_info->flags & Alter_info::ALTER_OPTIONS)
ha_alter_info->handler_flags |= Alter_inplace_info::CHANGE_CREATE_OPTION;
if (alter_info->flags & Alter_info::ALTER_RENAME)
ha_alter_info->handler_flags |= Alter_inplace_info::ALTER_RENAME;
/* Check partition changes */
if (alter_info->flags & Alter_info::ALTER_ADD_PARTITION)
ha_alter_info->handler_flags |= Alter_inplace_info::ADD_PARTITION;
if (alter_info->flags & Alter_info::ALTER_DROP_PARTITION)
ha_alter_info->handler_flags |= Alter_inplace_info::DROP_PARTITION;
if (alter_info->flags & Alter_info::ALTER_PARTITION)
ha_alter_info->handler_flags |= Alter_inplace_info::ALTER_PARTITION;
if (alter_info->flags & Alter_info::ALTER_COALESCE_PARTITION)
ha_alter_info->handler_flags |= Alter_inplace_info::COALESCE_PARTITION;
if (alter_info->flags & Alter_info::ALTER_REORGANIZE_PARTITION)
ha_alter_info->handler_flags |= Alter_inplace_info::REORGANIZE_PARTITION;
if (alter_info->flags & Alter_info::ALTER_TABLE_REORG)
ha_alter_info->handler_flags |= Alter_inplace_info::ALTER_TABLE_REORG;
if (alter_info->flags & Alter_info::ALTER_REMOVE_PARTITIONING)
ha_alter_info->handler_flags |=
Alter_inplace_info::ALTER_REMOVE_PARTITIONING;
if (alter_info->flags & Alter_info::ALTER_ALL_PARTITION)
ha_alter_info->handler_flags |= Alter_inplace_info::ALTER_ALL_PARTITION;
if (alter_info->flags & Alter_info::ALTER_REBUILD_PARTITION)
ha_alter_info->handler_flags |=
Alter_inplace_info::ALTER_REBUILD_PARTITION; /* purecov: deadcode */
/* Check for: ALTER TABLE FORCE, ALTER TABLE ENGINE and OPTIMIZE TABLE. */
if (alter_info->flags & Alter_info::ALTER_RECREATE)
ha_alter_info->handler_flags |= Alter_inplace_info::RECREATE_TABLE;
if (alter_info->with_validation == Alter_info::ALTER_WITH_VALIDATION)
ha_alter_info->handler_flags |= Alter_inplace_info::VALIDATE_VIRTUAL_COLUMN;
if (alter_info->flags & Alter_info::ADD_CHECK_CONSTRAINT)
ha_alter_info->handler_flags |= Alter_inplace_info::ADD_CHECK_CONSTRAINT;
if (alter_info->flags & Alter_info::DROP_CHECK_CONSTRAINT)
ha_alter_info->handler_flags |= Alter_inplace_info::DROP_CHECK_CONSTRAINT;
if (alter_info->flags & Alter_info::SUSPEND_CHECK_CONSTRAINT)
ha_alter_info->handler_flags |=
Alter_inplace_info::SUSPEND_CHECK_CONSTRAINT;
if (alter_info->flags & Alter_info::ALTER_COLUMN_VISIBILITY)
ha_alter_info->handler_flags |= Alter_inplace_info::ALTER_COLUMN_VISIBILITY;
/*
Go through fields in old version of table and detect changes to them.
We don't want to rely solely on Alter_info flags for this since:
a) new definition of column can be fully identical to the old one
despite the fact that this column is mentioned in MODIFY clause.
b) even if new column type differs from its old column from metadata
point of view, it might be identical from storage engine point
of view (e.g. when ENUM('a','b') is changed to ENUM('a','b',c')).
c) flags passed to storage engine contain more detailed information
about nature of changes than those provided from parser.
*/
uint old_field_index_without_vgc = 0;
for (f_ptr = table->field; (field = *f_ptr); f_ptr++) {
DBUG_PRINT("inplace", ("Existing field: %s", field->field_name));
/* Clear marker for renamed or dropped field
which we are going to set later. */
field->clear_flag(FIELD_IS_RENAMED);
field->clear_flag(FIELD_IS_DROPPED);
/* Use transformed info to evaluate flags for storage engine. */
uint new_field_index = 0;
uint new_field_index_without_vgc = 0;
new_field_it.init(alter_info->create_list);
while ((new_field = new_field_it++)) {
if (new_field->field == field) break;
if (new_field->stored_in_db) new_field_index_without_vgc++;
new_field_index++;
}
if (new_field) {
/* Field is not dropped. Evaluate changes bitmap for it. */
/*
Check if type of column has changed to some incompatible type.
*/
switch (field->is_equal(new_field)) {
case IS_EQUAL_NO:
DBUG_PRINT("inplace", ("Field %s: IS_EQUAL_NO for '%s'",
field->field_name, thd->query().str));
/* New column type is incompatible with old one. */
if (field->is_virtual_gcol())
ha_alter_info->handler_flags |=
Alter_inplace_info::ALTER_VIRTUAL_COLUMN_TYPE;
else
ha_alter_info->handler_flags |=
Alter_inplace_info::ALTER_STORED_COLUMN_TYPE;
break;
case IS_EQUAL_YES:
/*
New column is the same as the old one or the fully compatible with
it (for example, ENUM('a','b') was changed to ENUM('a','b','c')).
Such a change if any can ALWAYS be carried out by simply updating
data-dictionary without even informing storage engine.
No flag is set in this case.
*/
break;
case IS_EQUAL_PACK_LENGTH:
/*
New column type differs from the old one, but has compatible packed
data representation. Depending on storage engine, such a change can
be carried out by simply updating data dictionary without changing
actual data (for example, VARCHAR(300) is changed to VARCHAR(400)).
If the collation has changed, and the column is part of an index
or it is part of a partition expression, we must mark this as a
change in stored column type, which is usually rejected as inplace
operation by the SE.
*/
if (field->charset() != new_field->charset &&
(is_field_part_of_index(*field, *new_field, ha_alter_info) ||
is_field_part_of_partition_expression(*field, ha_alter_info))) {
ha_alter_info->handler_flags |=
Alter_inplace_info::ALTER_STORED_COLUMN_TYPE;
} else {
ha_alter_info->handler_flags |=
Alter_inplace_info::ALTER_COLUMN_EQUAL_PACK_LENGTH;
}
break;
default:
assert(0);
}
// Conversion to and from generated column is supported if stored:
if (field->is_gcol() != new_field->is_gcol()) {
assert((field->is_gcol() && !field->is_virtual_gcol()) ||
(new_field->is_gcol() && !new_field->is_virtual_gcol()));
ha_alter_info->handler_flags |=
Alter_inplace_info::ALTER_STORED_COLUMN_TYPE;
}
// Modification of generation expression is supported:
if (field->is_gcol() && new_field->is_gcol()) {
// Modification of storage attribute is not supported
assert(field->is_virtual_gcol() == new_field->is_virtual_gcol());
if (!field->gcol_expr_is_equal(new_field)) {
if (field->is_virtual_gcol())
ha_alter_info->handler_flags |=
Alter_inplace_info::ALTER_VIRTUAL_GCOL_EXPR;
else
ha_alter_info->handler_flags |=
Alter_inplace_info::ALTER_STORED_GCOL_EXPR;
} else {
gcols_with_unchanged_expr.push_back(field);
}
}
bool field_renamed;
/*
InnoDB data dictionary is case sensitive so we should use
string case sensitive comparison between fields.
Note: strcmp branch is to be removed in future when we fix it
in InnoDB.
*/
if (ha_alter_info->create_info->db_type->db_type == DB_TYPE_INNODB ||
ha_alter_info->create_info->db_type->db_type == DB_TYPE_NDBCLUSTER)
field_renamed = strcmp(field->field_name, new_field->field_name);
else
field_renamed = my_strcasecmp(system_charset_info, field->field_name,
new_field->field_name);
/* Check if field was renamed */
if (field_renamed) {
field->set_flag(FIELD_IS_RENAMED);
dropped_or_renamed_cols.push_back(field);
ha_alter_info->handler_flags |= Alter_inplace_info::ALTER_COLUMN_NAME;
}
/* Check that NULL behavior is same for old and new fields */
if (Overlaps(new_field->flags, NOT_NULL_FLAG) !=
field->is_flag_set(NOT_NULL_FLAG)) {
if (new_field->flags & NOT_NULL_FLAG)
ha_alter_info->handler_flags |=
Alter_inplace_info::ALTER_COLUMN_NOT_NULLABLE;
else
ha_alter_info->handler_flags |=
Alter_inplace_info::ALTER_COLUMN_NULLABLE;
}
/*
We do not detect changes to default values in this loop.
See comment above for more details.
*/
/*
Detect changes in column order.
Note that a stored column can't become virtual and vice versa
thanks to check in mysql_prepare_alter_table().
*/
if (field->stored_in_db) {
if (old_field_index_without_vgc != new_field_index_without_vgc)
ha_alter_info->handler_flags |=
Alter_inplace_info::ALTER_STORED_COLUMN_ORDER;
} else {
if (field->field_index() != new_field_index)
ha_alter_info->handler_flags |=
Alter_inplace_info::ALTER_VIRTUAL_COLUMN_ORDER;
}
/* Detect changes in storage type of column */
if (new_field->field_storage_type() != field->field_storage_type())
ha_alter_info->handler_flags |=
Alter_inplace_info::ALTER_COLUMN_STORAGE_TYPE;
/* Detect changes in column format of column */
if (new_field->column_format() != field->column_format())
ha_alter_info->handler_flags |=
Alter_inplace_info::ALTER_COLUMN_COLUMN_FORMAT;
/*
Columns which were mentioned in CHANGE/MODIFY COLUMN clause might
have changed their default, add their name to corresponding array.
*/
if (new_field->change)
cols_with_default_change.push_back(new_field->change);
} else {
/*
Field is not present in new version of table and therefore was dropped.
*/
assert(alter_info->flags & Alter_info::ALTER_DROP_COLUMN);
if (field->is_virtual_gcol()) {
ha_alter_info->handler_flags |= Alter_inplace_info::DROP_VIRTUAL_COLUMN;
ha_alter_info->virtual_column_drop_count++;
} else
ha_alter_info->handler_flags |= Alter_inplace_info::DROP_STORED_COLUMN;
field->set_flag(FIELD_IS_DROPPED);
dropped_or_renamed_cols.push_back(field);
}
if (field->stored_in_db) old_field_index_without_vgc++;
}
if (alter_info->flags & Alter_info::ALTER_ADD_COLUMN) {
new_field_it.init(alter_info->create_list);
while ((new_field = new_field_it++)) {
if (!new_field->field) {
/*
Field is not present in old version of table and therefore was added.
*/
if (new_field->is_virtual_gcol()) {
ha_alter_info->handler_flags |=
Alter_inplace_info::ADD_VIRTUAL_COLUMN;
ha_alter_info->virtual_column_add_count++;
} else if (new_field->gcol_info || new_field->m_default_val_expr)
ha_alter_info->handler_flags |=
Alter_inplace_info::ADD_STORED_GENERATED_COLUMN;
else
ha_alter_info->handler_flags |=
Alter_inplace_info::ADD_STORED_BASE_COLUMN;
}
}
/* One of these should be set since Alter_info::ALTER_ADD_COLUMN was set. */
assert(ha_alter_info->handler_flags &
(Alter_inplace_info::ADD_VIRTUAL_COLUMN |
Alter_inplace_info::ADD_STORED_BASE_COLUMN |
Alter_inplace_info::ADD_STORED_GENERATED_COLUMN));
}
/*
Add columns mentioned in SET/DROP DEFAULT clause to array of column names
which might have changed default.
*/
for (const Alter_column *alter : alter_info->alter_list) {
if (alter->change_type() == Alter_column::Type::SET_DEFAULT ||
alter->change_type() == Alter_column::Type::DROP_DEFAULT) {
cols_with_default_change.push_back(alter->name);
}
}
/*
Detect cases when we have generated columns that depend on columns
which were swapped (by renaming them) or replaced (by dropping and
then adding column with the same name). Also detect cases when
generated columns depend on the DEFAULT function on a column and
column default might have changed.
Storage engine might be unable to do such operation inplace as indexes
or value of stored generated columns might become invalid and require
re-evaluation by SQL-layer.
*/
for (Field *vfield : gcols_with_unchanged_expr) {
bool gcol_needs_reeval = false;
for (const char *col_name : cols_with_default_change) {
if (vfield->gcol_info->expr_item->walk(
&Item::check_gcol_depend_default_processor, enum_walk::POSTFIX,
reinterpret_cast<uchar *>(const_cast<char *>(col_name)))) {
gcol_needs_reeval = true;
break;
}
}
if (!gcol_needs_reeval && !dropped_or_renamed_cols.empty()) {
MY_BITMAP dependent_fields;
my_bitmap_map
bitbuf[bitmap_buffer_size(MAX_FIELDS) / sizeof(my_bitmap_map)];
bitmap_init(&dependent_fields, bitbuf, table->s->fields);
MY_BITMAP *save_old_read_set = table->read_set;
table->read_set = &dependent_fields;
Mark_field mark_fld(MARK_COLUMNS_TEMP);
vfield->gcol_info->expr_item->walk(&Item::mark_field_in_map,
enum_walk::PREFIX,
reinterpret_cast<uchar *>(&mark_fld));
for (const Field *dr_field : dropped_or_renamed_cols) {
if (bitmap_is_set(table->read_set, dr_field->field_index())) {
gcol_needs_reeval = true;
break;
}
}
table->read_set = save_old_read_set;
}
if (gcol_needs_reeval) {
if (vfield->is_virtual_gcol())
ha_alter_info->handler_flags |= Alter_inplace_info::VIRTUAL_GCOL_REEVAL;
else
ha_alter_info->handler_flags |= Alter_inplace_info::STORED_GCOL_REEVAL;
}
/*
Stop our search early if flags indicating re-evaluation of both
virtual and stored generated columns are already set.
*/
if ((ha_alter_info->handler_flags &
(Alter_inplace_info::VIRTUAL_GCOL_REEVAL |
Alter_inplace_info::STORED_GCOL_REEVAL)) ==
(Alter_inplace_info::VIRTUAL_GCOL_REEVAL |
Alter_inplace_info::STORED_GCOL_REEVAL))
break;
}
/*
Go through keys and check if the original ones are compatible
with new table.
*/
KEY *table_key;
KEY *table_key_end = table->key_info + table->s->keys;
KEY *new_key;
KEY *new_key_end = ha_alter_info->key_info_buffer + ha_alter_info->key_count;
DBUG_PRINT("info", ("index count old: %d new: %d", table->s->keys,
ha_alter_info->key_count));
/*
First, we need to handle keys being renamed, otherwise code handling
dropping/addition of keys might be confused in some situations.
*/
for (table_key = table->key_info; table_key < table_key_end; table_key++)
table_key->flags &= ~HA_KEY_RENAMED;
for (new_key = ha_alter_info->key_info_buffer; new_key < new_key_end;
new_key++)
new_key->flags &= ~HA_KEY_RENAMED;
for (const Alter_rename_key *rename_key : alter_info->alter_rename_key_list) {
table_key =
find_key_ci(rename_key->old_name, table->key_info, table_key_end);
new_key = find_key_ci(rename_key->new_name, ha_alter_info->key_info_buffer,
new_key_end);
table_key->flags |= HA_KEY_RENAMED;
new_key->flags |= HA_KEY_RENAMED;
if (!has_index_def_changed(ha_alter_info, table_key, new_key)) {
/* Key was not modified in any significant way but still was renamed. */
ha_alter_info->handler_flags |= Alter_inplace_info::RENAME_INDEX;
ha_alter_info->add_renamed_key(table_key, new_key);
/*
Check for insignificant changes which do not call for index
recreation, but still require update of .FRM.
*/
if (table_key->is_algorithm_explicit != new_key->is_algorithm_explicit)
ha_alter_info->handler_flags |= Alter_inplace_info::CHANGE_INDEX_OPTION;
} else {
/* Key was modified. */
ha_alter_info->add_modified_key(table_key, new_key);
}
}
for (const Alter_index_visibility *alter_index_visibility :
alter_info->alter_index_visibility_list) {
const char *name = alter_index_visibility->name();
table_key = find_key_ci(name, table->key_info, table_key_end);
new_key = find_key_ci(name, ha_alter_info->key_info_buffer, new_key_end);
if (new_key == nullptr) {
my_error(ER_KEY_DOES_NOT_EXITS, MYF(0), name, table->s->table_name.str);
return true;
}
new_key->is_visible = alter_index_visibility->is_visible();
ha_alter_info->handler_flags |= Alter_inplace_info::RENAME_INDEX;
ha_alter_info->add_altered_index_visibility(table_key, new_key);
}
/*
Step through all keys of the old table and search matching new keys.
*/
for (table_key = table->key_info; table_key < table_key_end; table_key++) {
/* Skip renamed keys. */
if (table_key->flags & HA_KEY_RENAMED) continue;
new_key = find_key_cs(table_key->name, ha_alter_info->key_info_buffer,
new_key_end);
if (new_key == nullptr) {
/* Matching new key not found. This means the key should be dropped. */
ha_alter_info->add_dropped_key(table_key);
} else if (has_index_def_changed(ha_alter_info, table_key, new_key)) {
/* Key was modified. */
ha_alter_info->add_modified_key(table_key, new_key);
} else {
/*
Key was not modified in significant way. Still we need to check
for insignificant changes which do not call for index recreation,
but still require update of .FRM.
*/
if (table_key->is_algorithm_explicit != new_key->is_algorithm_explicit)
ha_alter_info->handler_flags |= Alter_inplace_info::CHANGE_INDEX_OPTION;
}
}
/*
Step through all keys of the new table and find matching old keys.
*/
for (new_key = ha_alter_info->key_info_buffer; new_key < new_key_end;
new_key++) {
/* Skip renamed keys. */
if (new_key->flags & HA_KEY_RENAMED) continue;
if (!find_key_cs(new_key->name, table->key_info, table_key_end)) {
/* Matching old key not found. This means the key should be added. */
ha_alter_info->add_added_key(new_key);
}
}
/*
Sort index_add_buffer according to how key_info_buffer is sorted.
I.e. with primary keys first - see sort_keys().
*/
std::sort(ha_alter_info->index_add_buffer,
ha_alter_info->index_add_buffer + ha_alter_info->index_add_count);
/* Now let us calculate flags for storage engine API. */
/* Count all existing candidate keys. */
for (table_key = table->key_info; table_key < table_key_end; table_key++) {
/*
Check if key is a candidate key, This key is either already primary key
or could be promoted to primary key if the original primary key is
dropped.
In MySQL one is allowed to create primary key with partial fields (i.e.
primary key which is not considered candidate). For simplicity we count
such key as a candidate key here.
*/
if (((uint)(table_key - table->key_info) == table->s->primary_key) ||
is_candidate_key(table_key))
candidate_key_count++;
}
/* Figure out what kind of indexes we are dropping. */
KEY **dropped_key;
KEY **dropped_key_end =
ha_alter_info->index_drop_buffer + ha_alter_info->index_drop_count;
for (dropped_key = ha_alter_info->index_drop_buffer;
dropped_key < dropped_key_end; dropped_key++) {
table_key = *dropped_key;
if (table_key->flags & HA_NOSAME) {
/*
Unique key. Check for PRIMARY KEY. Also see comment about primary
and candidate keys above.
*/
if ((uint)(table_key - table->key_info) == table->s->primary_key) {
ha_alter_info->handler_flags |= Alter_inplace_info::DROP_PK_INDEX;
candidate_key_count--;
} else {
ha_alter_info->handler_flags |= Alter_inplace_info::DROP_UNIQUE_INDEX;
if (is_candidate_key(table_key)) candidate_key_count--;
}
} else
ha_alter_info->handler_flags |= Alter_inplace_info::DROP_INDEX;
}
/* Now figure out what kind of indexes we are adding. */
for (uint add_key_idx = 0; add_key_idx < ha_alter_info->index_add_count;
add_key_idx++) {
new_key = ha_alter_info->key_info_buffer +
ha_alter_info->index_add_buffer[add_key_idx];
if (new_key->flags & HA_NOSAME) {
bool is_pk =
!my_strcasecmp(system_charset_info, new_key->name, primary_key_name);
if ((!(new_key->flags & HA_KEY_HAS_PART_KEY_SEG) &&
!(new_key->flags & HA_NULL_PART_KEY)) ||
is_pk) {
/* Candidate key or primary key! */
if (candidate_key_count == 0 || is_pk)
ha_alter_info->handler_flags |= Alter_inplace_info::ADD_PK_INDEX;
else
ha_alter_info->handler_flags |= Alter_inplace_info::ADD_UNIQUE_INDEX;
candidate_key_count++;
} else {
ha_alter_info->handler_flags |= Alter_inplace_info::ADD_UNIQUE_INDEX;
}
} else {
if (new_key->flags & HA_SPATIAL) {
ha_alter_info->handler_flags |= Alter_inplace_info::ADD_SPATIAL_INDEX;
} else {
ha_alter_info->handler_flags |= Alter_inplace_info::ADD_INDEX;
}
}
}
return false;
}
/**
Mark fields participating in newly added indexes in TABLE object which
corresponds to new version of altered table.
@param ha_alter_info Alter_inplace_info describing in-place ALTER.
@param altered_table TABLE object for new version of TABLE in which
fields should be marked.
*/
static void update_altered_table(const Alter_inplace_info &ha_alter_info,
TABLE *altered_table) {
uint field_idx, add_key_idx;
KEY *key;
KEY_PART_INFO *end, *key_part;
/*
Clear marker for all fields, as we are going to set it only
for fields which participate in new indexes.
*/
for (field_idx = 0; field_idx < altered_table->s->fields; ++field_idx)
altered_table->field[field_idx]->clear_flag(FIELD_IN_ADD_INDEX);
/*
Go through array of newly added indexes and mark fields
participating in them.
*/
for (add_key_idx = 0; add_key_idx < ha_alter_info.index_add_count;
add_key_idx++) {
key = ha_alter_info.key_info_buffer +
ha_alter_info.index_add_buffer[add_key_idx];
end = key->key_part + key->user_defined_key_parts;
for (key_part = key->key_part; key_part < end; key_part++)
altered_table->field[key_part->fieldnr]->set_flag(FIELD_IN_ADD_INDEX);
}
}
/**
Initialize TABLE::field for the new table with appropriate
column static defaults.
@note Can be plain default values from TABLE_SHARE::default_values
or datetime function defaults. We don't handle general
expression defaults here as their values need to be evaluated
for each row and such evaluation might result in error.
@param altered_table TABLE object for the new version of the table.
@param create Create_field list for new version of the table,
which is used for identifying new columns.
*/
static void set_column_static_defaults(TABLE *altered_table,
List<Create_field> &create) {
// Initialize TABLE::field default values
restore_record(altered_table, s->default_values);
// Now set datetime expression defaults for new columns.
List_iterator<Create_field> iter(create);
for (uint i = 0; i < altered_table->s->fields; ++i) {
const Create_field *definition = iter++;
if (definition->field == nullptr &&
altered_table->field[i]->has_insert_default_datetime_value_expression())
altered_table->field[i]->evaluate_insert_default_function();
}
}
/**
Compare two tables to see if their metadata are compatible.
One table specified by a TABLE instance, the other using Alter_info
and HA_CREATE_INFO.
@param thd Thread handler
@param[in] table The first table.
@param[in] alter_info Alter options, fields and keys for the
second table.
@param[in] create_info Create options for the second table.
@param[out] metadata_equal Result of comparison.
@retval true error
@retval false success
*/
bool mysql_compare_tables(THD *thd, TABLE *table, Alter_info *alter_info,
HA_CREATE_INFO *create_info, bool *metadata_equal) {
DBUG_TRACE;
uint changes = IS_EQUAL_NO;
uint key_count;
uint fk_key_count = 0;
List_iterator_fast<Create_field> tmp_new_field_it;
*metadata_equal = false;
/*
Create a copy of alter_info.
To compare definitions, we need to "prepare" the definition - transform it
from parser output to a format that describes the table layout (all column
defaults are initialized, duplicate columns are removed). This is done by
mysql_prepare_create_table. Unfortunately, mysql_prepare_create_table
performs its transformations "in-place", that is, modifies the argument.
Since we would like to keep mysql_compare_tables() idempotent (not altering
any of the arguments) we create a copy of alter_info here and pass it to
mysql_prepare_create_table, then use the result to compare the tables, and
then destroy the copy.
*/
Alter_info tmp_alter_info(*alter_info, thd->mem_root);
KEY *key_info_buffer = nullptr;
FOREIGN_KEY *fk_key_info_buffer = nullptr;
/* Create the prepared information. */
if (mysql_prepare_create_table(thd,
"", // Not used
"", // Not used
create_info, &tmp_alter_info, table->file,
false, // Not used
&key_info_buffer, &key_count,
&fk_key_info_buffer, &fk_key_count, nullptr, 0,
nullptr, 0, 0, false))
return true;
/* Some very basic checks. */
if (table->s->fields != alter_info->create_list.elements ||
table->s->db_type() != create_info->db_type || table->s->tmp_table ||
(table->s->row_type != create_info->row_type))
return false;
/* Go through fields and check if they are compatible. */
tmp_new_field_it.init(tmp_alter_info.create_list);
for (Field **f_ptr = table->field; *f_ptr; f_ptr++) {
Field *field = *f_ptr;
const Create_field *tmp_new_field = tmp_new_field_it++;
/* Check to see if both fields are alike. */
if (tmp_new_field->is_virtual_gcol() != field->is_virtual_gcol()) {
my_error(ER_UNSUPPORTED_ACTION_ON_GENERATED_COLUMN, MYF(0),
"Exchanging partitions for non-generated columns");
return false;
}
/* Check that NULL behavior is the same. */
if ((tmp_new_field->flags & NOT_NULL_FLAG) !=
field->is_flag_set(NOT_NULL_FLAG))
return false;
/* Check if field was renamed */
if (my_strcasecmp(system_charset_info, field->field_name,
tmp_new_field->field_name))
return false;
/* Evaluate changes bitmap and send to check_if_incompatible_data() */
uint field_changes = field->is_equal(tmp_new_field);
if (field_changes != IS_EQUAL_YES) return false;
changes |= field_changes;
}
/* Check if changes are compatible with current handler. */
if (table->file->check_if_incompatible_data(create_info, changes))
return false;
/* Go through keys and check if they are compatible. */
KEY *table_key;
KEY *table_key_end = table->key_info + table->s->keys;
KEY *new_key;
KEY *new_key_end = key_info_buffer + key_count;
/* Step through all keys of the first table and search matching keys. */
for (table_key = table->key_info; table_key < table_key_end; table_key++) {
/* Search a key with the same name. */
for (new_key = key_info_buffer; new_key < new_key_end; new_key++) {
if (!strcmp(table_key->name, new_key->name)) break;
}
if (new_key >= new_key_end) return false;
/* Check that the key types are compatible. */
if ((table_key->algorithm != new_key->algorithm) ||
((table_key->flags & HA_KEYFLAG_MASK) !=
(new_key->flags & HA_KEYFLAG_MASK)) ||
(table_key->user_defined_key_parts != new_key->user_defined_key_parts))
return false;
/* Check that the key parts remain compatible. */
KEY_PART_INFO *table_part;
KEY_PART_INFO *table_part_end =
table_key->key_part + table_key->user_defined_key_parts;
KEY_PART_INFO *new_part;
for (table_part = table_key->key_part, new_part = new_key->key_part;
table_part < table_part_end; table_part++, new_part++) {
/*
Key definition is different if we are using a different field or
if the used key part length is different. We know that the fields
are equal. Comparing field numbers is sufficient.
*/
if ((table_part->length != new_part->length) ||
(table_part->fieldnr - 1 != new_part->fieldnr))
return false;
}
}
/* Step through all keys of the second table and find matching keys. */
for (new_key = key_info_buffer; new_key < new_key_end; new_key++) {
/* Search a key with the same name. */
for (table_key = table->key_info; table_key < table_key_end; table_key++) {
if (!strcmp(table_key->name, new_key->name)) break;
}
if (table_key >= table_key_end) return false;
}
*metadata_equal = true; // Tables are compatible
return false;
}
/**
Report a zero date warning if no default value is supplied
for the DATE/DATETIME 'NOT NULL' field and 'NO_ZERO_DATE'
sql_mode is enabled.
@param thd Thread handle.
@param datetime_field DATE/DATETIME column definition.
*/
static bool push_zero_date_warning(THD *thd, Create_field *datetime_field) {
uint f_length = 0;
enum enum_mysql_timestamp_type t_type = MYSQL_TIMESTAMP_DATE;
switch (datetime_field->sql_type) {
case MYSQL_TYPE_DATE:
case MYSQL_TYPE_NEWDATE:
f_length = MAX_DATE_WIDTH; // "0000-00-00";
t_type = MYSQL_TIMESTAMP_DATE;
break;
case MYSQL_TYPE_DATETIME:
case MYSQL_TYPE_DATETIME2:
f_length = MAX_DATETIME_WIDTH; // "0000-00-00 00:00:00";
t_type = MYSQL_TIMESTAMP_DATETIME;
break;
default:
assert(false); // Should not get here.
}
return make_truncated_value_warning(
thd, Sql_condition::SL_WARNING,
ErrConvString(my_zero_datetime6, f_length), t_type,
datetime_field->field_name);
}
/*
Manages enabling/disabling of indexes for ALTER TABLE
SYNOPSIS
alter_table_manage_keys()
table Target table
indexes_were_disabled Whether the indexes of the from table
were disabled
keys_onoff ENABLE | DISABLE | LEAVE_AS_IS
RETURN VALUES
false OK
true Error
*/
static bool alter_table_manage_keys(
THD *thd, TABLE *table, int indexes_were_disabled,
Alter_info::enum_enable_or_disable keys_onoff) {
int error = 0;
DBUG_TRACE;
DBUG_PRINT("enter", ("table=%p were_disabled=%d on_off=%d", table,
indexes_were_disabled, keys_onoff));
switch (keys_onoff) {
case Alter_info::ENABLE:
error = table->file->ha_enable_indexes(HA_KEY_SWITCH_NONUNIQ_SAVE);
break;
case Alter_info::LEAVE_AS_IS:
if (!indexes_were_disabled) break;
/* fall-through: disabled indexes */
[[fallthrough]];
case Alter_info::DISABLE:
error = table->file->ha_disable_indexes(HA_KEY_SWITCH_NONUNIQ_SAVE);
}
if (error == HA_ERR_WRONG_COMMAND) {
push_warning_printf(thd, Sql_condition::SL_NOTE, ER_ILLEGAL_HA,
ER_THD(thd, ER_ILLEGAL_HA), table->s->table_name.str);
error = 0;
} else if (error)
table->file->print_error(error, MYF(0));
return error;
}
/**
Check if the pending ALTER TABLE operations support the in-place
algorithm based on restrictions in the SQL layer or given the
nature of the operations themselves. If in-place isn't supported,
it won't be necessary to check with the storage engine.
@param table The original TABLE.
@param create_info Information from the parsing phase about new
table properties.
@param alter_info Data related to detected changes.
@return false In-place is possible, check with storage engine.
@return true Incompatible operations, must use table copy.
*/
static bool is_inplace_alter_impossible(TABLE *table,
HA_CREATE_INFO *create_info,
const Alter_info *alter_info) {
DBUG_TRACE;
/* At the moment we can't handle altering temporary tables without a copy. */
if (table->s->tmp_table) return true;
/*
For the ALTER TABLE tbl_name ORDER BY ... we always use copy
algorithm. In theory, this operation can be done in-place by some
engine, but since a) no current engine does this and b) our current
API lacks infrastructure for passing information about table ordering
to storage engine we simply always do copy now.
ENABLE/DISABLE KEYS is a MyISAM/Heap specific operation that is
not supported for in-place in combination with other operations.
Alone, it will be done by simple_rename_or_index_change().
Stored generated columns are evaluated in server, thus can't be
added/changed inplace.
*/
if (alter_info->flags &
(Alter_info::ALTER_ORDER | Alter_info::ALTER_KEYS_ONOFF))
return true;
/*
Check constraints are evaluated in the server, if any check constraint
(re-)evaluation is required then it can't be added/enforced inplace.
*/
if (is_any_check_constraints_evaluation_required(alter_info)) return true;
/*
If the table engine is changed explicitly (using ENGINE clause)
or implicitly (e.g. when non-partitioned table becomes
partitioned) a regular alter table (copy) needs to be
performed.
*/
if (create_info->db_type != table->s->db_type()) return true;
/*
There was a bug prior to mysql-4.0.25. Number of null fields was
calculated incorrectly. As a result frm and data files gets out of
sync after fast alter table. There is no way to determine by which
mysql version (in 4.0 and 4.1 branches) table was created, thus we
disable fast alter table for all tables created by mysql versions
prior to 5.0 branch.
See BUG#6236.
*/
if (!table->s->mysql_version) return true;
/*
If we are changing the SRID modifier of a column, we must do a COPY.
But not if we are changing to the NULL SRID. In that case, we can do it
inplace (only metadata change, and no verification needed).
*/
for (const Create_field &new_field_def : alter_info->create_list) {
if (new_field_def.field != nullptr &&
new_field_def.field->type() == MYSQL_TYPE_GEOMETRY) {
const Field_geom *field_geom =
down_cast<const Field_geom *>(new_field_def.field);
if (field_geom->get_srid() != new_field_def.m_srid &&
new_field_def.m_srid.has_value())
return true;
}
}
return false;
}
/**
Add MDL requests for exclusive lock on tables referenced by the
foreign keys to be dropped by ALTER TABLE operation. Also add
the referenced table names to the foreign key invalidator,
to be used at a later stage to invalidate the dd::Table objects.
@param thd Thread handle.
@param alter_info Alter_info object with the list of FKs
to be dropped.
@param table_def dd::Table describing the table before
ALTER operation.
@param hton Handlerton for table's storage engine.
@param[in,out] mdl_requests List to which MDL requests are to be added.
@param[in,out] fk_invalidator Object keeping track of which dd::Table
objects to invalidate.
@retval operation outcome, false if no error.
*/
static bool collect_fk_parents_for_dropped_fks(
THD *thd, const Alter_info *alter_info, const dd::Table *table_def,
handlerton *hton, MDL_request_list *mdl_requests,
Foreign_key_parents_invalidator *fk_invalidator) {
for (const Alter_drop *drop : alter_info->drop_list) {
if (drop->type == Alter_drop::FOREIGN_KEY) {
for (const dd::Foreign_key *fk : table_def->foreign_keys()) {
if (my_strcasecmp(system_charset_info, drop->name,
fk->name().c_str()) == 0) {
char buff_db[NAME_LEN + 1];
char buff_table[NAME_LEN + 1];
my_stpncpy(buff_db, fk->referenced_table_schema_name().c_str(),
NAME_LEN);
my_stpncpy(buff_table, fk->referenced_table_name().c_str(), NAME_LEN);
/*
In lower-case-table-names == 2 mode we store original versions
of table and db names in the data-dictionary. Hence they need
to be lowercased to produce correct MDL key for them and for
other uses.
*/
if (lower_case_table_names == 2) {
my_casedn_str(system_charset_info, buff_db);
my_casedn_str(system_charset_info, buff_table);
}
MDL_request *mdl_request = new (thd->mem_root) MDL_request;
if (mdl_request == nullptr) return true;
MDL_REQUEST_INIT(mdl_request, MDL_key::TABLE, buff_db, buff_table,
MDL_EXCLUSIVE, MDL_STATEMENT);
mdl_requests->push_front(mdl_request);
mdl_request = new (thd->mem_root) MDL_request;
if (mdl_request == nullptr) return true;
MDL_REQUEST_INIT(mdl_request, MDL_key::SCHEMA, buff_db, "",
MDL_INTENTION_EXCLUSIVE, MDL_STATEMENT);
mdl_requests->push_front(mdl_request);
fk_invalidator->add(buff_db, buff_table, hton);
break;
}
}
}
}
return false;
}
/**
Acquire exclusive metadata locks on tables which definitions need to
be updated or invalidated due to foreign keys created or dropped as
result of complex ALTER TABLE operation.
Also add the referenced table names for the FKs created/dropped to the
foreign key invalidator, to be used at a later stage to invalidate the
dd::Table objects.
@param thd Thread handle.
@param table_list Table list element for table being ALTERed.
@param old_table_def Old table definition of table being ALTERed.
@param alter_ctx ALTER TABLE operation context.
@param alter_info Alter_info object with the lists of FKs
to be added or dropped.
@param old_hton Table's old SE.
@param new_hton Table's new SE.
@param[in,out] fk_invalidator Object keeping track of which dd::Table
objects to invalidate.
@retval operation outcome, false if no error.
*/
static bool collect_and_lock_fk_tables_for_complex_alter_table(
THD *thd, Table_ref *table_list, const dd::Table *old_table_def,
const Alter_table_ctx *alter_ctx, const Alter_info *alter_info,
handlerton *old_hton, handlerton *new_hton,
Foreign_key_parents_invalidator *fk_invalidator) {
MDL_request_list mdl_requests;
if (collect_fk_parents_for_new_fks(
thd, table_list->db, table_list->table_name, alter_info,
MDL_EXCLUSIVE, new_hton, &mdl_requests, fk_invalidator))
return true;
if (alter_ctx->is_table_renamed()) {
if (collect_fk_parents_for_all_fks(thd, old_table_def, old_hton,
MDL_EXCLUSIVE, &mdl_requests,
fk_invalidator))
return true;
} else {
if (collect_fk_parents_for_dropped_fks(thd, alter_info, old_table_def,
old_hton, &mdl_requests,
fk_invalidator))
return true;
}
if (new_hton != old_hton) {
/*
By changing table's storage engine we might be introducing parent
table for previously orphan foreign keys in the new SE. We need
to lock child tables of such orphan foreign keys. OTOH it is safe
to assume that if SE is changed table can't be parent in any
foreign keys in old SE.
*/
assert(old_table_def->foreign_key_parents().size() == 0);
if (collect_fk_children(thd, table_list->db, table_list->table_name,
new_hton, MDL_EXCLUSIVE, &mdl_requests))
return true;
} else {
if (collect_fk_children(thd, old_table_def, MDL_EXCLUSIVE, &mdl_requests))
return true;
}
if (alter_ctx->is_table_renamed()) {
if (collect_fk_children(thd, alter_ctx->new_db, alter_ctx->new_alias,
new_hton, MDL_EXCLUSIVE, &mdl_requests))
return true;
}
if (!mdl_requests.is_empty() &&
thd->mdl_context.acquire_locks(&mdl_requests,
thd->variables.lock_wait_timeout))
return true;
return false;
}
/**
Update referenced table names and the unique constraint name for FKs
affected by complex ALTER TABLE operation.
@param thd Thread handle.
@param table_list Table list element for table being ALTERed.
@param alter_ctx ALTER TABLE operation context.
@param alter_info Alter_info describing ALTER TABLE, specifically
containing information about columns being renamed.
@param new_hton Table's new SE.
@param fk_invalidator Object keeping track of which dd::Table
objects to invalidate. Used to filter out
which FK parents should have their FK parent
information reloaded.
@retval operation outcome, false if no error.
*/
static bool adjust_fks_for_complex_alter_table(
THD *thd, Table_ref *table_list, Alter_table_ctx *alter_ctx,
Alter_info *alter_info, handlerton *new_hton,
const Foreign_key_parents_invalidator *fk_invalidator) {
if (!(new_hton->flags & HTON_SUPPORTS_FOREIGN_KEYS)) return false;
const dd::Table *new_table = nullptr;
if (thd->dd_client()->acquire(alter_ctx->new_db, alter_ctx->new_alias,
&new_table))
return true;
assert(new_table != nullptr);
if (adjust_fk_children_after_parent_def_change(
thd,
/*
For consistency with check_fk_children_after_parent_def_change(),
allow charset discrepancies between child and parent columns in
FOREIGN_KEY_CHECKS=0 mode.
*/
!(thd->variables.option_bits & OPTION_NO_FOREIGN_KEY_CHECKS),
table_list->db, table_list->table_name, new_hton, new_table,
alter_info, true))
return true;
if (alter_ctx->is_table_renamed()) {
if (adjust_fk_children_after_parent_rename(
thd, table_list->db, table_list->table_name, new_hton,
alter_ctx->new_db, alter_ctx->new_alias))
return true;
if (adjust_fk_children_after_parent_def_change(
thd, alter_ctx->new_db, alter_ctx->new_alias, new_hton, new_table,
nullptr))
return true;
}
return adjust_fk_parents(thd, alter_ctx->new_db, alter_ctx->new_alias, true,
fk_invalidator);
}
/**
Add appropriate MDL requests on names of foreign keys on the table
to be renamed to the requests list.
@param thd Thread handle.
@param db Table's old schema.
@param table_name Table's old name.
@param table_def Table definition of table being RENAMEd.
@param hton Table's storage engine.
@param new_db Table's new schema.
@param new_table_name Table's new name.
@param[in,out] mdl_requests List to which MDL requests need to be
added.
@retval operation outcome, false if no error.
*/
static bool collect_fk_names_for_rename_table(
THD *thd, const char *db, const char *table_name,
const dd::Table *table_def, handlerton *hton, const char *new_db,
const char *new_table_name, MDL_request_list *mdl_requests)
{
bool is_table_renamed =
(my_strcasecmp(table_alias_charset, table_name, new_table_name) != 0);
bool is_db_changed = (my_strcasecmp(table_alias_charset, db, new_db) != 0);
char old_table_name_norm[NAME_LEN + 1];
strmake(old_table_name_norm, table_name, NAME_LEN);
if (lower_case_table_names == 2)
my_casedn_str(system_charset_info, old_table_name_norm);
char new_table_name_lc[NAME_LEN + 1];
strmake(new_table_name_lc, new_table_name, NAME_LEN);
/*
Unless new table name in lower case already we need to lowercase
it, so it can be used to construct lowercased version of FK name
for acquiring metadata lock.
*/
if (lower_case_table_names != 1)
my_casedn_str(system_charset_info, new_table_name_lc);
size_t old_table_name_norm_len = strlen(old_table_name_norm);
for (const dd::Foreign_key *fk : table_def->foreign_keys()) {
/*
Since foreign key names are case-insensitive we need to lowercase
them before passing to MDL subsystem.
*/
char fk_name[NAME_LEN + 1];
strmake(fk_name, fk->name().c_str(), NAME_LEN);
my_casedn_str(system_charset_info, fk_name);
MDL_request *mdl_request = new (thd->mem_root) MDL_request;
if (mdl_request == nullptr) return true;
MDL_REQUEST_INIT(mdl_request, MDL_key::FOREIGN_KEY, db, fk_name,
MDL_EXCLUSIVE, MDL_STATEMENT);
mdl_requests->push_front(mdl_request);
if (is_table_renamed &&
dd::is_generated_foreign_key_name(old_table_name_norm,
old_table_name_norm_len, hton, *fk)) {
char new_fk_name[NAME_LEN + 1];
/*
Copy <SE-specific or default FK name suffix><number> part.
Here we truncate generated name if it is too long. This is sufficient
for MDL purposes. Error will be reported later in this case.
*/
strxnmov(new_fk_name, NAME_LEN, new_table_name_lc,
fk->name().c_str() + old_table_name_norm_len, NullS);
MDL_request *mdl_request2 = new (thd->mem_root) MDL_request;
if (mdl_request2 == nullptr) return true;
MDL_REQUEST_INIT(mdl_request2, MDL_key::FOREIGN_KEY, new_db, new_fk_name,
MDL_EXCLUSIVE, MDL_STATEMENT);
mdl_requests->push_front(mdl_request2);
} else if (is_db_changed) {
MDL_request *mdl_request2 = new (thd->mem_root) MDL_request;
if (mdl_request2 == nullptr) return true;
MDL_REQUEST_INIT(mdl_request2, MDL_key::FOREIGN_KEY, new_db, fk_name,
MDL_EXCLUSIVE, MDL_STATEMENT);
mdl_requests->push_front(mdl_request2);
}
}
return false;
}
/**
Check if complex ALTER TABLE with RENAME clause results in foreign key
names conflicts.
@param thd Thread handle.
@param table_list Table list element for table altered.
@param table_def dd::Table object describing new version of
table prior to rename operation.
@param hton Table's storage engine.
@param new_schema dd::Schema object for target schema.
@param alter_ctx ALTER TABLE operation context.
@retval True if error (e.g. due to foreign key name conflict),
false - otherwise.
*/
static bool check_fk_names_before_rename(THD *thd, Table_ref *table_list,
const dd::Table &table_def,
handlerton *hton,
const dd::Schema &new_schema,
const Alter_table_ctx &alter_ctx) {
for (const dd::Foreign_key *fk : table_def.foreign_keys()) {
if (alter_ctx.is_table_name_changed() &&
dd::is_generated_foreign_key_name(
table_list->table_name, table_list->table_name_length, hton, *fk)) {
// We reserve extra NAME_LEN to ensure that new name fits.
char new_fk_name[NAME_LEN + NAME_LEN + 1];
/*
Construct new name by copying <FK name suffix><number> suffix
from the old one.
*/
strxnmov(new_fk_name, sizeof(new_fk_name) - 1, alter_ctx.new_name,
fk->name().c_str() + table_list->table_name_length, NullS);
if (check_string_char_length(to_lex_cstring(new_fk_name), "",
NAME_CHAR_LEN, system_charset_info,
true /* no error */)) {
my_error(ER_TOO_LONG_IDENT, MYF(0), new_fk_name);
return true;
}
bool exists;
if (thd->dd_client()->check_foreign_key_exists(new_schema, new_fk_name,
&exists))
return true;
if (exists) {
my_error(ER_FK_DUP_NAME, MYF(0), new_fk_name);
return true;
}
} else if (alter_ctx.is_database_changed()) {
bool exists;
if (thd->dd_client()->check_foreign_key_exists(new_schema, fk->name(),
&exists))
return true;
if (exists) {
my_error(ER_FK_DUP_NAME, MYF(0), fk->name().c_str());
return true;
}
}
}
return false;
}
/**
Check if a table is empty, i.e., it has no rows.
@param[in] table The table.
@param[out] is_empty Set to true if the table is empty.
@retval false Success.
@retval true An error occurred (and has been reported with print_error).
*/
static bool table_is_empty(TABLE *table, bool *is_empty) {
*is_empty = false;
int error = 0;
if (!(error = table->file->ha_rnd_init(true))) {
do {
error = table->file->ha_rnd_next(table->record[0]);
} while (error == HA_ERR_RECORD_DELETED);
if (error == HA_ERR_END_OF_FILE) *is_empty = true;
}
if (error && error != HA_ERR_END_OF_FILE) {
table->file->print_error(error, MYF(0));
table->file->ha_rnd_end();
return true;
}
if ((error = table->file->ha_rnd_end())) {
table->file->print_error(error, MYF(0));
return true;
}
return false;
}
/**
* Unloads table from secondary engine if SECONDARY_ENGINE = NULL.
*
* @param thd Thread handler.
* @param table Table opened in primary storage engine.
* @param create_info Information from the parsing phase about new
* table properties.
* @param old_table_def Definition of table before the alter statement.
*
* @return True if error, false otherwise.
*/
static bool remove_secondary_engine(THD *thd, const Table_ref &table,
const HA_CREATE_INFO &create_info,
const dd::Table *old_table_def) {
// Nothing to do if no secondary engine defined for the table.
if (table.table->s->secondary_engine.str == nullptr) return false;
// Check if SECONDARY_ENGINE = NULL has been set in ALTER TABLE.
const bool is_null =
create_info.used_fields & HA_CREATE_USED_SECONDARY_ENGINE &&
create_info.secondary_engine.str == nullptr;
if (!is_null) return false;
if (thd->mdl_context.upgrade_shared_lock(table.table->mdl_ticket,
MDL_EXCLUSIVE,
thd->variables.lock_wait_timeout))
return true;
return secondary_engine_unload_table(thd, table.db, table.table_name,
*old_table_def, false);
}
/**
Perform in-place alter table.
@param thd Thread handle.
@param schema Source schema.
@param new_schema Target schema.
@param table_def Table object for the original table.
@param altered_table_def Table object for the new version of the table.
@param table_list Table_ref for the table to change.
@param table The original TABLE.
@param altered_table TABLE object for new version of the table.
@param ha_alter_info Structure describing ALTER TABLE to be carried
out and serving as a storage place for data
used during different phases.
@param inplace_supported Enum describing the locking requirements.
@param alter_ctx ALTER TABLE runtime context.
@param columns A list of columns to be modified. This is needed
for removal/renaming of histogram statistics.
@param fk_key_info Array of FOREIGN_KEY objects describing foreign
keys in new table version.
@param fk_key_count Number of foreign keys in new table version.
@param[out] fk_invalidator Set of parent tables which participate in FKs
together with table being altered and which
entries in DD cache need to be invalidated.
@retval true Error
@retval false Success
@note
If mysql_alter_table does not need to copy the table, it is
either an alter table where the storage engine does not
need to know about the change, only the frm will change,
or the storage engine supports performing the alter table
operation directly, in-place without mysql having to copy
the table.
@note This function frees the TABLE object associated with the new version of
the table and removes the .FRM file for it in case of both success and
failure.
*/
static bool mysql_inplace_alter_table(
THD *thd, const dd::Schema &schema, const dd::Schema &new_schema,
const dd::Table *table_def, dd::Table *altered_table_def,
Table_ref *table_list, TABLE *table, TABLE *altered_table,
Alter_inplace_info *ha_alter_info,
enum_alter_inplace_result inplace_supported, Alter_table_ctx *alter_ctx,
histograms::columns_set &columns, FOREIGN_KEY *fk_key_info,
uint fk_key_count, Foreign_key_parents_invalidator *fk_invalidator) {
handlerton *db_type = table->s->db_type();
MDL_ticket *mdl_ticket = table->mdl_ticket;
Alter_info *alter_info = ha_alter_info->alter_info;
bool reopen_tables = false;
bool rollback_needs_dict_cache_reset = false;
MDL_request_list mdl_requests;
DBUG_TRACE;
/*
Upgrade to EXCLUSIVE lock if:
- This is requested by the storage engine
- Or the storage engine needs exclusive lock for just the prepare
phase
- Or requested by the user
Note that we handle situation when storage engine needs exclusive
lock for prepare phase under LOCK TABLES in the same way as when
exclusive lock is required for duration of the whole statement.
*/
if (inplace_supported == HA_ALTER_INPLACE_EXCLUSIVE_LOCK ||
((inplace_supported == HA_ALTER_INPLACE_SHARED_LOCK_AFTER_PREPARE ||
inplace_supported == HA_ALTER_INPLACE_NO_LOCK_AFTER_PREPARE) &&
(thd->locked_tables_mode == LTM_LOCK_TABLES ||
thd->locked_tables_mode == LTM_PRELOCKED_UNDER_LOCK_TABLES)) ||
alter_info->requested_lock == Alter_info::ALTER_TABLE_LOCK_EXCLUSIVE) {
if (wait_while_table_is_used(thd, table, HA_EXTRA_FORCE_REOPEN))
goto cleanup;
/*
Get rid of all TABLE instances belonging to this thread
except one to be used for in-place ALTER TABLE.
This is mostly needed to satisfy InnoDB assumptions/asserts.
*/
close_all_tables_for_name(thd, table->s, false, table);
/*
If we are under LOCK TABLES we will need to reopen tables which we
just have closed in case of error.
*/
reopen_tables = true;
} else if (inplace_supported == HA_ALTER_INPLACE_SHARED_LOCK_AFTER_PREPARE ||
inplace_supported == HA_ALTER_INPLACE_NO_LOCK_AFTER_PREPARE) {
/*
Storage engine has requested exclusive lock only for prepare phase
and we are not under LOCK TABLES.
Don't mark TABLE_SHARE as old in this case, as this won't allow opening
of table by other threads during main phase of in-place ALTER TABLE.
*/
if (thd->mdl_context.upgrade_shared_lock(table->mdl_ticket, MDL_EXCLUSIVE,
thd->variables.lock_wait_timeout))
goto cleanup;
tdc_remove_table(thd, TDC_RT_REMOVE_NOT_OWN_KEEP_SHARE, table->s->db.str,
table->s->table_name.str, false);
}
/*
Upgrade to SHARED_NO_WRITE lock if:
- The storage engine needs writes blocked for the whole duration
- Or this is requested by the user
Note that under LOCK TABLES, we will already have SHARED_NO_READ_WRITE.
*/
if ((inplace_supported == HA_ALTER_INPLACE_SHARED_LOCK ||
alter_info->requested_lock == Alter_info::ALTER_TABLE_LOCK_SHARED) &&
thd->mdl_context.upgrade_shared_lock(table->mdl_ticket,
MDL_SHARED_NO_WRITE,
thd->variables.lock_wait_timeout)) {
goto cleanup;
}
/*
Acquire locks on names of new foreign keys. INPLACE algorithm creates
the new table definition in the original table's database.
*/
if (collect_fk_names_for_new_fks(
thd, table_list->db, table_list->table_name, alter_info, db_type,
get_fk_max_generated_name_number(table_list->table_name, table_def,
db_type),
&mdl_requests) ||
(alter_ctx->is_table_renamed() &&
collect_fk_names_for_rename_table(
thd, table_list->db, table_list->table_name, altered_table_def,
db_type, alter_ctx->new_db, alter_ctx->new_name, &mdl_requests)))
goto cleanup;
if (!mdl_requests.is_empty() &&
thd->mdl_context.acquire_locks(&mdl_requests,
thd->variables.lock_wait_timeout))
goto cleanup;
/*
Check if ALTER TABLE results in any foreign key name conflicts
before starting potentially expensive phases of INPLACE ALTER.
*/
if (!dd::get_dictionary()->is_dd_table_name(table_list->db,
table_list->table_name) &&
(db_type->flags & HTON_SUPPORTS_FOREIGN_KEYS)) {
for (FOREIGN_KEY *fk = fk_key_info + alter_ctx->fk_count;
fk < fk_key_info + fk_key_count; ++fk) {
bool exists;
if (thd->dd_client()->check_foreign_key_exists(schema, fk->name, &exists))
goto cleanup;
if (exists) {
my_error(ER_FK_DUP_NAME, MYF(0), fk->name);
goto cleanup;
}
}
if (alter_ctx->is_table_renamed() &&
check_fk_names_before_rename(thd, table_list, *altered_table_def,
db_type, new_schema, *alter_ctx))
goto cleanup;
}
// It's now safe to take the table level lock.
if (lock_tables(thd, table_list, alter_ctx->tables_opened, 0)) goto cleanup;
if (alter_ctx->error_if_not_empty) {
/*
Storage engines should not suggest/support INSTANT algorithm if
error_if_not_empty flag is set.
The problem is that the below check if table is empty is not "instant",
as it might have to traverse through deleted versions of rows on SQL-layer
(e.g. MyISAM) or in SE (e.g. InnoDB).
OTOH for cases when table is empty difference between INSTANT and INPLACE
or COPY algorithms should be negligible.
This limitation might be raised in the future if we will implement support
for quick (i.e. non-traversing) check for table emptiness.
*/
assert(inplace_supported != HA_ALTER_INPLACE_INSTANT);
/*
Operations which set error_if_not_empty flag typically request exclusive
lock during prepare phase, so we don't have to upgrade lock to prevent
concurrent table modifications here.
*/
assert(table->mdl_ticket->get_type() == MDL_EXCLUSIVE);
bool empty_table = false;
if (table_is_empty(table_list->table, &empty_table)) goto cleanup;
if (!empty_table) {
if (alter_ctx->error_if_not_empty &
Alter_table_ctx::GEOMETRY_WITHOUT_DEFAULT) {
my_error(ER_INVALID_USE_OF_NULL, MYF(0));
} else if ((alter_ctx->error_if_not_empty &
Alter_table_ctx::DATETIME_WITHOUT_DEFAULT) &&
(thd->variables.sql_mode & MODE_NO_ZERO_DATE)) {
/*
Report a warning if the NO ZERO DATE MODE is enabled. The
warning will be promoted to an error if strict mode is
also enabled. Do not check for errors here as we check
thd->is_error() just below.
*/
(void)push_zero_date_warning(thd, alter_ctx->datetime_field);
}
if (thd->is_error()) goto cleanup;
}
// Empty table, so don't allow inserts during inplace operation.
if (inplace_supported == HA_ALTER_INPLACE_NO_LOCK ||
inplace_supported == HA_ALTER_INPLACE_NO_LOCK_AFTER_PREPARE)
inplace_supported = HA_ALTER_INPLACE_SHARED_LOCK;
}
DEBUG_SYNC(thd, "alter_table_inplace_after_lock_upgrade");
THD_STAGE_INFO(thd, stage_alter_inplace_prepare);
switch (inplace_supported) {
case HA_ALTER_ERROR:
case HA_ALTER_INPLACE_NOT_SUPPORTED:
assert(0);
[[fallthrough]];
case HA_ALTER_INPLACE_NO_LOCK:
case HA_ALTER_INPLACE_NO_LOCK_AFTER_PREPARE:
switch (alter_info->requested_lock) {
case Alter_info::ALTER_TABLE_LOCK_DEFAULT:
case Alter_info::ALTER_TABLE_LOCK_NONE:
ha_alter_info->online = true;
break;
case Alter_info::ALTER_TABLE_LOCK_SHARED:
case Alter_info::ALTER_TABLE_LOCK_EXCLUSIVE:
break;
}
break;
case HA_ALTER_INPLACE_EXCLUSIVE_LOCK:
case HA_ALTER_INPLACE_SHARED_LOCK_AFTER_PREPARE:
case HA_ALTER_INPLACE_SHARED_LOCK:
case HA_ALTER_INPLACE_INSTANT:
break;
}
{
/*
We want warnings/errors about data truncation emitted when
values of virtual columns are evaluated in INPLACE algorithm.
*/
thd->check_for_truncated_fields = CHECK_FIELD_WARN;
thd->num_truncated_fields = 0L;
if (table->file->ha_prepare_inplace_alter_table(
altered_table, ha_alter_info, table_def, altered_table_def)) {
goto rollback;
}
/*
Downgrade the lock if storage engine has told us that exclusive lock was
necessary only for prepare phase (unless we are not under LOCK TABLES) and
user has not explicitly requested exclusive lock.
*/
if ((inplace_supported == HA_ALTER_INPLACE_SHARED_LOCK_AFTER_PREPARE ||
inplace_supported == HA_ALTER_INPLACE_NO_LOCK_AFTER_PREPARE) &&
!(thd->locked_tables_mode == LTM_LOCK_TABLES ||
thd->locked_tables_mode == LTM_PRELOCKED_UNDER_LOCK_TABLES) &&
(alter_info->requested_lock !=
Alter_info::ALTER_TABLE_LOCK_EXCLUSIVE)) {
/* If storage engine or user requested shared lock downgrade to SNW. */
if (inplace_supported == HA_ALTER_INPLACE_SHARED_LOCK_AFTER_PREPARE ||
alter_info->requested_lock == Alter_info::ALTER_TABLE_LOCK_SHARED)
table->mdl_ticket->downgrade_lock(MDL_SHARED_NO_WRITE);
else {
assert(inplace_supported == HA_ALTER_INPLACE_NO_LOCK_AFTER_PREPARE);
table->mdl_ticket->downgrade_lock(MDL_SHARED_UPGRADABLE);
}
}
DEBUG_SYNC(thd, "alter_table_inplace_after_lock_downgrade");
THD_STAGE_INFO(thd, stage_alter_inplace);
if (table->file->ha_inplace_alter_table(altered_table, ha_alter_info,
table_def, altered_table_def)) {
goto rollback;
}
// Upgrade to EXCLUSIVE before commit.
if (wait_while_table_is_used(thd, table, HA_EXTRA_PREPARE_FOR_RENAME))
goto rollback;
if (collect_and_lock_fk_tables_for_complex_alter_table(
thd, table_list, table_def, alter_ctx, alter_info, db_type, db_type,
fk_invalidator))
goto rollback;
/*
Check if this is an ALTER command that will cause histogram statistics to
become invalid. If that is the case; remove the histogram statistics.
This will take care of scenarios when INPLACE alter is used, but not COPY.
*/
if (alter_table_drop_histograms(thd, table_list, ha_alter_info->alter_info,
ha_alter_info->create_info, columns,
table_def, altered_table_def))
goto rollback;
/*
If we are killed after this point, we should ignore and continue.
We have mostly completed the operation at this point, there should
be no long waits left.
*/
DBUG_EXECUTE_IF("alter_table_rollback_new_index", {
table->file->ha_commit_inplace_alter_table(
altered_table, ha_alter_info, false, table_def, altered_table_def);
my_error(ER_UNKNOWN_ERROR, MYF(0));
thd->check_for_truncated_fields = CHECK_FIELD_IGNORE;
goto cleanup;
});
DEBUG_SYNC(thd, "alter_table_inplace_before_commit");
THD_STAGE_INFO(thd, stage_alter_inplace_commit);
if (table->file->ha_commit_inplace_alter_table(
altered_table, ha_alter_info, true, table_def, altered_table_def)) {
goto rollback;
}
thd->check_for_truncated_fields = CHECK_FIELD_IGNORE;
close_all_tables_for_name(thd, table->s, false, nullptr);
table_list->table = table = nullptr;
reopen_tables = true;
close_temporary_table(thd, altered_table, true, false);
rollback_needs_dict_cache_reset = true;
DEBUG_SYNC(thd, "alter_table_inplace_will_need_reset");
/*
Replace table definition in the data-dictionary.
Note that any error after this point is really awkward for storage engines
which don't support atomic DDL. Changes to table in SE are already
committed and can't be rolled back. Failure to update data-dictionary or
binary log will create inconsistency between them and SE. Since we can't
do much in this situation we simply return error and hope that old table
definition is compatible enough with a new one.
For engines supporting atomic DDL error is business-as-usual situation.
Rollback of statement which happens on error should revert changes to
table in SE as well.
*/
altered_table_def->set_schema_id(table_def->schema_id());
altered_table_def->set_name(alter_ctx->alias);
altered_table_def->set_hidden(dd::Abstract_table::HT_VISIBLE);
/*
Copy pre-existing triggers to the new table definition.
Since trigger names have to be unique per schema, we cannot
create them while both the old and the new version of the
table definition exist. Note that we drop the old table before
we call update on the new table definition.
*/
altered_table_def->copy_triggers(table_def);
if (thd->dd_client()->drop(table_def)) goto cleanup2;
table_def = nullptr;
DEBUG_SYNC_C("alter_table_after_dd_client_drop");
// Reset check constraint's mode.
reset_check_constraints_alter_mode(altered_table_def);
if ((db_type->flags & HTON_SUPPORTS_ATOMIC_DDL)) {
/*
For engines supporting atomic DDL we have delayed storing new
table definition in the data-dictionary so far in order to avoid
conflicts between old and new definitions on foreign key names.
Since the old table definition is gone we can safely store new
definition now.
*/
if (thd->dd_client()->store(altered_table_def)) goto cleanup2;
} else {
if (thd->dd_client()->update(altered_table_def)) goto cleanup2;
/*
Persist changes to data-dictionary for storage engines which don't
support atomic DDL. Such SEs can't rollback in-place changes if error
or crash happens after this point, so we are better to have
data-dictionary in sync with SE.
Prevent intermediate commits to invoke commit order
*/
Implicit_substatement_state_guard substatement_guard(thd);
if (trans_commit_stmt(thd) || trans_commit_implicit(thd)) goto cleanup2;
}
}
#ifdef HAVE_PSI_TABLE_INTERFACE
PSI_TABLE_CALL(drop_table_share)
(true, alter_ctx->new_db, static_cast<int>(strlen(alter_ctx->new_db)),
alter_ctx->tmp_name, static_cast<int>(strlen(alter_ctx->tmp_name)));
#endif
DBUG_EXECUTE_IF("crash_after_index_create",
DBUG_SET("-d,crash_after_index_create");
DBUG_SUICIDE(););
/*
Tell the SE that the changed table in the data-dictionary.
For engines which don't support atomic DDL this needs to be
done before trying to rename the table.
*/
if (!(db_type->flags & HTON_SUPPORTS_ATOMIC_DDL)) {
Open_table_context ot_ctx(thd, MYSQL_OPEN_REOPEN);
table_list->mdl_request.ticket = mdl_ticket;
if (open_table(thd, table_list, &ot_ctx)) goto cleanup2;
table_list->table->file->ha_notify_table_changed(ha_alter_info);
/*
We might be going to reopen table down on the road, so we have to
restore state of the TABLE object which we used for obtaining of
handler object to make it usable for later reopening.
*/
assert(table_list->table == thd->open_tables);
close_thread_table(thd, &thd->open_tables);
table_list->table = nullptr;
/*
Remove TABLE and TABLE_SHARE for from the TDC as we might have to
rename table later.
*/
tdc_remove_table(thd, TDC_RT_REMOVE_ALL, alter_ctx->db,
alter_ctx->table_name, false);
}
// Rename altered table if requested.
if (alter_ctx->is_table_renamed()) {
if (mysql_rename_table(
thd, db_type, alter_ctx->db, alter_ctx->table_name, alter_ctx->db,
alter_ctx->table_name, new_schema, alter_ctx->new_db,
alter_ctx->new_alias,
((db_type->flags & HTON_SUPPORTS_ATOMIC_DDL) ? NO_DD_COMMIT : 0))) {
/*
If the rename fails we will still have a working table
with the old name, but with other changes applied.
*/
goto cleanup2;
}
}
/*
We don't have SEs which support FKs and don't support atomic DDL.
If we ever to support such engines we need to decide how to handle
errors in the below code for them.
*/
assert(!(db_type->flags & HTON_SUPPORTS_FOREIGN_KEYS) ||
(db_type->flags & HTON_SUPPORTS_ATOMIC_DDL));
if (adjust_fks_for_complex_alter_table(thd, table_list, alter_ctx, alter_info,
db_type, fk_invalidator))
goto cleanup2;
THD_STAGE_INFO(thd, stage_end);
DBUG_EXECUTE_IF("sleep_alter_before_main_binlog", my_sleep(6000000););
DEBUG_SYNC(thd, "alter_table_before_main_binlog");
ha_binlog_log_query(thd, ha_alter_info->create_info->db_type,
LOGCOM_ALTER_TABLE, thd->query().str, thd->query().length,
alter_ctx->db, alter_ctx->table_name);
assert(!(mysql_bin_log.is_open() &&
thd->is_current_stmt_binlog_format_row() &&
(ha_alter_info->create_info->options & HA_LEX_CREATE_TMP_TABLE)));
if (write_bin_log(thd, true, thd->query().str, thd->query().length,
(db_type->flags & HTON_SUPPORTS_ATOMIC_DDL)))
goto cleanup2;
{
Uncommitted_tables_guard uncommitted_tables(thd);
uncommitted_tables.add_table(table_list);
bool views_err =
(alter_ctx->is_table_renamed()
? update_referencing_views_metadata(
thd, table_list, alter_ctx->new_db, alter_ctx->new_name,
!(db_type->flags & HTON_SUPPORTS_ATOMIC_DDL),
&uncommitted_tables)
: update_referencing_views_metadata(
thd, table_list,
!(db_type->flags & HTON_SUPPORTS_ATOMIC_DDL),
&uncommitted_tables));
if (alter_ctx->is_table_renamed())
tdc_remove_table(thd, TDC_RT_REMOVE_ALL, alter_ctx->new_db,
alter_ctx->new_name, false);
if (views_err) goto cleanup2;
}
DEBUG_SYNC(thd, "action_after_write_bin_log");
if (db_type->flags & HTON_SUPPORTS_ATOMIC_DDL) {
enum_implicit_substatement_guard_mode mode =
enum_implicit_substatement_guard_mode ::
ENABLE_GTID_AND_SPCO_IF_SPCO_ACTIVE;
/* Disable GTID and SPCO for OPTIMIZE TABLE to avoid deadlock. */
if (thd->lex->sql_command == SQLCOM_OPTIMIZE)
mode = enum_implicit_substatement_guard_mode ::
DISABLE_GTID_AND_SPCO_IF_SPCO_ACTIVE;
/*
It allows saving GTID and invoking commit order, except when
replica-preserve-commit-order is enabled and OPTIMIZE TABLE command
is getting executed. The exception for OPTIMIZE TABLE command is
because if it does enter commit order here and at the same time
any operation on the table which is getting optimized is done,
it results in deadlock.
*/
Implicit_substatement_state_guard guard(thd, mode);
/*
Commit ALTER TABLE. Needs to be done here and not in the callers
(which do it anyway) to be able notify SE about changed table.
*/
if (trans_commit_stmt(thd) || trans_commit_implicit(thd)) goto cleanup2;
/* Call SE DDL post-commit hook. */
if (db_type->post_ddl) db_type->post_ddl(thd);
/*
Finally we can tell SE supporting atomic DDL that the changed table
in the data-dictionary.
*/
Table_ref new_table_list(alter_ctx->new_db, alter_ctx->new_name,
alter_ctx->new_alias, TL_READ);
new_table_list.mdl_request.ticket =
alter_ctx->is_table_renamed() ? alter_ctx->target_mdl_request.ticket
: mdl_ticket;
Open_table_context ot_ctx(thd, MYSQL_OPEN_REOPEN);
if (open_table(thd, &new_table_list, &ot_ctx)) return true;
new_table_list.table->file->ha_notify_table_changed(ha_alter_info);
assert(new_table_list.table == thd->open_tables);
close_thread_table(thd, &thd->open_tables);
}
// TODO: May move the opening of the table and the call to
// ha_notify_table_changed() here to make sure we don't
// notify the handler until all meta data is complete.
return false;
rollback:
table->file->ha_commit_inplace_alter_table(
altered_table, ha_alter_info, false, table_def, altered_table_def);
thd->check_for_truncated_fields = CHECK_FIELD_IGNORE;
cleanup:
close_temporary_table(thd, altered_table, true, false);
cleanup2:
(void)trans_rollback_stmt(thd);
/*
Full rollback in case we have THD::transaction_rollback_request
and to synchronize DD state in cache and on disk (as statement
rollback doesn't clear DD cache of modified uncommitted objects).
*/
(void)trans_rollback(thd);
if ((db_type->flags & HTON_SUPPORTS_ATOMIC_DDL) && db_type->post_ddl)
db_type->post_ddl(thd);
/*
InnoDB requires additional SE dictionary cache invalidation if we roll back
after successful call to handler::ha_commit_inplace_alter_table().
*/
if (rollback_needs_dict_cache_reset) {
if (db_type->dict_cache_reset != nullptr)
db_type->dict_cache_reset(alter_ctx->db, alter_ctx->table_name);
}
/*
Re-opening of table needs to be done after rolling back the failed
statement/transaction and clearing THD::transaction_rollback_request
flag.
*/
if (reopen_tables) {
/* Close the only table instance which might be still around. */
if (table) close_all_tables_for_name(thd, table->s, false, nullptr);
/*
For engines which support atomic DDL all changes were reverted
by this point, so we can safely reopen them using old name.
For engines which do not support atomic DDL we can't be sure
that rename step was reverted, so we simply remove table from
the list of locked tables. We also downgrade/release metadata
locks later. This won't mess up FK-related invariants for LOCK
TABLES as such engines do not support FKs.
*/
if (!(db_type->flags & HTON_SUPPORTS_ATOMIC_DDL) &&
alter_ctx->is_table_renamed()) {
assert(!(db_type->flags & HTON_SUPPORTS_FOREIGN_KEYS));
thd->locked_tables_list.unlink_all_closed_tables(thd, nullptr, 0);
}
(void)thd->locked_tables_list.reopen_tables(thd);
}
if (!(db_type->flags & HTON_SUPPORTS_ATOMIC_DDL)) {
const dd::Table *drop_table_def = nullptr;
if (!thd->dd_client()->acquire(alter_ctx->new_db, alter_ctx->tmp_name,
&drop_table_def) &&
(drop_table_def != nullptr)) {
bool result = dd::drop_table(thd, alter_ctx->new_db, alter_ctx->tmp_name,
*drop_table_def);
(void)trans_intermediate_ddl_commit(thd, result);
}
}
if (thd->locked_tables_mode == LTM_LOCK_TABLES ||
thd->locked_tables_mode == LTM_PRELOCKED_UNDER_LOCK_TABLES)
mdl_ticket->downgrade_lock(MDL_SHARED_NO_READ_WRITE);
return true;
}
/**
maximum possible length for certain blob types.
@param[in] type Blob type (e.g. MYSQL_TYPE_TINY_BLOB)
@return
length
*/
static uint blob_length_by_type(enum_field_types type) {
switch (type) {
case MYSQL_TYPE_TINY_BLOB:
return 255;
case MYSQL_TYPE_BLOB:
return 65535;
case MYSQL_TYPE_MEDIUM_BLOB:
return 16777215;
case MYSQL_TYPE_LONG_BLOB:
return 4294967295U;
default:
assert(0); // we should never go here
return 0;
}
}
/**
Convert the old temporal data types to the new temporal
type format for ADD/CHANGE COLUMN, ADD INDEXES and ALTER
FORCE ALTER operation.
@param thd Thread context.
@param alter_info Alter info parameters.
@retval true Error.
@retval false Either the old temporal data types
are not present or they are present
and have been successfully upgraded.
*/
static bool upgrade_old_temporal_types(THD *thd, Alter_info *alter_info) {
bool old_temporal_type_present = false;
DBUG_TRACE;
if (!((alter_info->flags & Alter_info::ALTER_ADD_COLUMN) ||
(alter_info->flags & Alter_info::ALTER_ADD_INDEX) ||
(alter_info->flags & Alter_info::ALTER_CHANGE_COLUMN) ||
(alter_info->flags & Alter_info::ALTER_RECREATE)))
return false;
/*
Upgrade the old temporal types if any, for ADD/CHANGE COLUMN/
ADD INDEXES and FORCE ALTER operation.
*/
Create_field *def;
List_iterator<Create_field> create_it(alter_info->create_list);
while ((def = create_it++)) {
// Check if any old temporal type is present.
if ((def->sql_type == MYSQL_TYPE_TIME) ||
(def->sql_type == MYSQL_TYPE_DATETIME) ||
(def->sql_type == MYSQL_TYPE_TIMESTAMP)) {
old_temporal_type_present = true;
break;
}
}
// Upgrade is not required since there are no old temporal types.
if (!old_temporal_type_present) return false;
// Upgrade old temporal types to the new temporal types.
create_it.rewind();
while ((def = create_it++)) {
enum enum_field_types sql_type;
Item *default_value = def->constant_default;
Item *update_value = nullptr;
/*
Set CURRENT_TIMESTAMP as default/update value based on
the auto_flags value.
*/
if ((def->sql_type == MYSQL_TYPE_DATETIME ||
def->sql_type == MYSQL_TYPE_TIMESTAMP) &&
(def->auto_flags != Field::NONE)) {
Item_func_now_local *now = new (thd->mem_root) Item_func_now_local(0);
if (!now) return true;
if (def->auto_flags & Field::DEFAULT_NOW) default_value = now;
if (def->auto_flags & Field::ON_UPDATE_NOW) update_value = now;
}
switch (def->sql_type) {
case MYSQL_TYPE_TIME:
sql_type = MYSQL_TYPE_TIME2;
break;
case MYSQL_TYPE_DATETIME:
sql_type = MYSQL_TYPE_DATETIME2;
break;
case MYSQL_TYPE_TIMESTAMP:
sql_type = MYSQL_TYPE_TIMESTAMP2;
break;
default:
continue;
}
// Replace the old temporal field with the new temporal field.
Create_field *temporal_field = nullptr;
if (!(temporal_field = new (thd->mem_root) Create_field()) ||
temporal_field->init(thd, def->field_name, sql_type, nullptr, nullptr,
(def->flags & NOT_NULL_FLAG), default_value,
update_value, &def->comment, def->change, nullptr,
nullptr, false, 0, nullptr, nullptr, def->m_srid,
def->hidden, def->is_array))
return true;
temporal_field->field = def->field;
create_it.replace(temporal_field);
}
// Report a NOTE informing about the upgrade.
push_warning(thd, Sql_condition::SL_NOTE, ER_OLD_TEMPORALS_UPGRADED,
ER_THD(thd, ER_OLD_TEMPORALS_UPGRADED));
return false;
}
static fk_option to_fk_option(dd::Foreign_key::enum_rule rule) {
switch (rule) {
case dd::Foreign_key::enum_rule::RULE_NO_ACTION:
return FK_OPTION_NO_ACTION;
case dd::Foreign_key::enum_rule::RULE_RESTRICT:
return FK_OPTION_RESTRICT;
case dd::Foreign_key::enum_rule::RULE_CASCADE:
return FK_OPTION_CASCADE;
case dd::Foreign_key::enum_rule::RULE_SET_NULL:
return FK_OPTION_SET_NULL;
case dd::Foreign_key::enum_rule::RULE_SET_DEFAULT:
return FK_OPTION_DEFAULT;
}
assert(false);
return FK_OPTION_UNDEF;
}
static fk_match_opt to_fk_match_opt(dd::Foreign_key::enum_match_option match) {
switch (match) {
case dd::Foreign_key::enum_match_option::OPTION_NONE:
return FK_MATCH_SIMPLE;
case dd::Foreign_key::enum_match_option::OPTION_PARTIAL:
return FK_MATCH_PARTIAL;
case dd::Foreign_key::enum_match_option::OPTION_FULL:
return FK_MATCH_FULL;
}
assert(false);
return FK_MATCH_UNDEF;
}
static void to_lex_cstring(MEM_ROOT *mem_root, LEX_CSTRING *target,
const dd::String_type &source) {
target->str = strmake_root(mem_root, source.c_str(), source.length() + 1);
target->length = source.length();
}
/**
Remember information about pre-existing foreign keys so
that they can be added to the new version of the table later.
Omit foreign keys to be dropped. Also check that the foreign
keys to be kept are still valid.
@note This function removes pre-existing foreign keys from the
drop_list, while Alter_info::drop_list is kept intact.
A non-empty drop_list upon return of this function indicates
an error, and means that the statement tries to drop a
foreign key that did not exist in the first place.
@param[in] thd Thread handle.
@param[in] src_table The source table.
@param[in] src_db_name Original database name of table.
@param[in] src_table_name Original table name of table.
@param[in] hton Original storage engine.
@param[in] alter_info Info about ALTER TABLE statement.
@param[in] new_create_list List of new columns, used for rename check.
@param[in,out] drop_list Copy of list of foreign keys to be dropped.
@param[in,out] alter_ctx Runtime context for ALTER TABLE to which
information about pre-existing foreign
keys is added.
*/
static bool transfer_preexisting_foreign_keys(
THD *thd, const dd::Table *src_table, const char *src_db_name,
const char *src_table_name, handlerton *hton, const Alter_info *alter_info,
List<Create_field> *new_create_list, Alter_table_ctx *alter_ctx,
Prealloced_array<const Alter_drop *, 1> *drop_list) {
if (src_table == nullptr)
return false; // Could be temporary table or during upgrade.
List_iterator<Create_field> find_it(*new_create_list);
alter_ctx->fk_info = (FOREIGN_KEY *)sql_calloc(
sizeof(FOREIGN_KEY) * src_table->foreign_keys().size());
for (size_t i = 0; i < src_table->foreign_keys().size(); i++) {
const dd::Foreign_key *dd_fk = src_table->foreign_keys()[i];
// Skip foreign keys that are to be dropped
size_t k = 0;
while (k < drop_list->size()) {
const Alter_drop *drop = (*drop_list)[k];
// Index names are always case insensitive
if (drop->type == Alter_drop::FOREIGN_KEY &&
my_strcasecmp(system_charset_info, drop->name,
dd_fk->name().c_str()) == 0) {
break;
}
k++;
}
if (k < drop_list->size()) {
drop_list->erase(k);
continue;
}
// Self-referencing foreign keys will need additional handling later.
bool is_self_referencing =
my_strcasecmp(table_alias_charset,
dd_fk->referenced_table_schema_name().c_str(),
src_db_name) == 0 &&
my_strcasecmp(table_alias_charset,
dd_fk->referenced_table_name().c_str(),
src_table_name) == 0;
FOREIGN_KEY *sql_fk = &alter_ctx->fk_info[alter_ctx->fk_count++];
sql_fk->name = strmake_root(thd->mem_root, dd_fk->name().c_str(),
dd_fk->name().length() + 1);
sql_fk->unique_index_name =
strmake_root(thd->mem_root, dd_fk->unique_constraint_name().c_str(),
dd_fk->unique_constraint_name().length() + 1);
sql_fk->key_parts = dd_fk->elements().size();
to_lex_cstring(thd->mem_root, &sql_fk->ref_db,
dd_fk->referenced_table_schema_name());
to_lex_cstring(thd->mem_root, &sql_fk->ref_table,
dd_fk->referenced_table_name());
sql_fk->delete_opt = to_fk_option(dd_fk->delete_rule());
sql_fk->update_opt = to_fk_option(dd_fk->update_rule());
sql_fk->match_opt = to_fk_match_opt(dd_fk->match_option());
sql_fk->key_part =
(LEX_CSTRING *)sql_calloc(sizeof(LEX_CSTRING) * sql_fk->key_parts);
sql_fk->fk_key_part =
(LEX_CSTRING *)sql_calloc(sizeof(LEX_CSTRING) * sql_fk->key_parts);
for (size_t j = 0; j < sql_fk->key_parts; j++) {
const dd::Foreign_key_element *dd_fk_ele = dd_fk->elements()[j];
if (alter_info->flags & Alter_info::ALTER_DROP_COLUMN) {
/* Check if column used in the foreign key was dropped. */
if (std::any_of(
alter_info->drop_list.cbegin(), alter_info->drop_list.cend(),
[dd_fk_ele](const Alter_drop *drop) {
return drop->type == Alter_drop::COLUMN &&
!my_strcasecmp(system_charset_info,
dd_fk_ele->column().name().c_str(),
drop->name);
})) {
my_error(ER_FK_COLUMN_CANNOT_DROP, MYF(0),
dd_fk_ele->column().name().c_str(), dd_fk->name().c_str());
return true;
}
if (is_self_referencing) {
/*
Do the same check for referenced column if child and parent
table are the same.
*/
find_it.rewind();
const Create_field *find;
while ((find = find_it++)) {
if (find->field &&
my_strcasecmp(system_charset_info,
dd_fk_ele->referenced_column_name().c_str(),
find->field->field_name) == 0) {
break;
}
}
if (find == nullptr) {
my_error(ER_FK_COLUMN_CANNOT_DROP_CHILD, MYF(0),
dd_fk_ele->referenced_column_name().c_str(),
dd_fk->name().c_str(), dd_fk->table().name().c_str());
return true;
}
}
}
// Check if the column was renamed by the same statement.
bool col_renamed = false;
bool ref_col_renamed = false;
if (alter_info->flags & Alter_info::ALTER_CHANGE_COLUMN) {
find_it.rewind();
const Create_field *find;
while ((find = find_it++) && !col_renamed) {
if (find->change && my_strcasecmp(system_charset_info,
dd_fk_ele->column().name().c_str(),
find->change) == 0) {
// Use new name
sql_fk->key_part[j].str = find->field_name;
sql_fk->key_part[j].length = strlen(find->field_name);
col_renamed = true;
}
}
/*
If foreign key has the same table as child and parent we also
need to update names of referenced columns if they are renamed.
*/
if (is_self_referencing) {
find_it.rewind();
while ((find = find_it++) && !ref_col_renamed) {
if (find->change &&
my_strcasecmp(system_charset_info,
dd_fk_ele->referenced_column_name().c_str(),
find->change) == 0) {
// Use new name
sql_fk->fk_key_part[j].str = find->field_name;
sql_fk->fk_key_part[j].length = strlen(find->field_name);
ref_col_renamed = true;
}
}
}
}
if (!col_renamed) // Use old name
to_lex_cstring(thd->mem_root, &sql_fk->key_part[j],
dd_fk_ele->column().name());
if (!ref_col_renamed)
to_lex_cstring(thd->mem_root, &sql_fk->fk_key_part[j],
dd_fk_ele->referenced_column_name());
/*
Orphan non-self-referencing FK become non-orphan/adopted
self-referencing FK as a result of a table rename operation. Make sure
referenced column exists and it is not a virtual column. Such FK needs
additional handling later.
*/
if (!is_self_referencing && alter_ctx->is_table_renamed() &&
my_strcasecmp(table_alias_charset,
dd_fk->referenced_table_schema_name().c_str(),
alter_ctx->new_db) == 0 &&
my_strcasecmp(table_alias_charset,
dd_fk->referenced_table_name().c_str(),
alter_ctx->new_name) == 0) {
find_it.rewind();
const Create_field *find;
while ((find = find_it++)) {
if (find->field &&
my_strcasecmp(system_charset_info,
dd_fk_ele->referenced_column_name().c_str(),
find->field_name) == 0)
break;
}
if (find == nullptr) {
my_error(ER_FK_NO_COLUMN_PARENT, MYF(0), sql_fk->fk_key_part[j].str,
dd_fk->name().c_str(),
dd_fk->referenced_table_name().c_str());
return true;
}
if (find->is_virtual_gcol()) {
my_error(ER_FK_CANNOT_USE_VIRTUAL_COLUMN, MYF(0),
dd_fk->name().c_str(), sql_fk->fk_key_part[j].str);
return true;
}
}
#ifndef NDEBUG
{
find_it.rewind();
Create_field *find;
while ((find = find_it++)) {
if (my_strcasecmp(system_charset_info, sql_fk->key_part[j].str,
find->field_name) == 0 &&
find->field != nullptr) {
break;
}
}
/*
Thanks to the above code handling dropped columns referencing
column must exist.
*/
assert(find != nullptr);
/*
Also due to facts a) that we don't allow virtual columns in
foreign keys and b) that existing generated columns can't be
changed to virtual, referencing column must be non-virtual.
*/
assert(!find->is_virtual_gcol());
if (is_self_referencing) {
find_it.rewind();
while ((find = find_it++)) {
if (my_strcasecmp(system_charset_info, sql_fk->fk_key_part[j].str,
find->field_name) == 0 &&
find->field != nullptr) {
break;
}
}
/*
The same applies to referenced columns if foreign key has
same table as child and parent.
*/
assert(find != nullptr);
assert(!find->is_virtual_gcol());
}
}
#endif
}
}
alter_ctx->fk_max_generated_name_number =
get_fk_max_generated_name_number(src_table_name, src_table, hton);
return false;
}
/**
Check if the column being removed or renamed is in use by partitioning
function for the table and that the partitioning is kept/partitioning
function is unchanged by this ALTER TABLE, and report error if it is
the case.
@param table TABLE object describing old table version.
@param field Field object for column to be checked.
@param alter_info Alter_info describing the ALTER TABLE.
@return
true The field is used by partitioning function, error was reported.
false Otherwise.
*/
static bool check_if_field_used_by_partitioning_func(
TABLE *table, const Field *field, const Alter_info *alter_info) {
partition_info *part_info = table->part_info;
// There is no partitioning function if table is not partitioned.
if (!part_info) return false;
// Check if column is not used by (sub)partitioning function.
if (!bitmap_is_set(&part_info->full_part_field_set, field->field_index()))
return false;
/*
It is OK to rename/drop column that is used by old partitioning function
if partitioning is removed. It is also OK to do this if partitioning for
table is changed. The latter gives users a way to update partitioning
function after renaming/dropping columns. Data inconsistency doesn't
occur in this case as change of partitioning causes table rebuild.
*/
if (alter_info->flags &
(Alter_info::ALTER_REMOVE_PARTITIONING | Alter_info::ALTER_PARTITION))
return false;
/*
We also allow renaming and dropping of columns used by partitioning
function when it is defined using PARTITION BY KEY () clause (notice
empty column list). In this case partitioning function is defined by
the primary key.
So partitioning function stays valid when column in the primary key is
renamed since the primary key is automagically adjusted in this case.
Dropping column is also acceptable, as this is handled as a change of
primary key (deletion of old one and addition of a new one) and storage
engines are supposed to handle this correctly (at least InnoDB does
thanks to fix for bug#20190520).
Note that we avoid complex checks and simple disallow renaming/dropping
of columns if table with PARTITION BY KEY() clause is also subpartitioned.
Subpartitioning by KEY always uses explicit column list so it is not safe
for renaming/dropping columns.
*/
if (part_info->part_type == partition_type::HASH &&
part_info->list_of_part_fields && part_info->part_field_list.is_empty() &&
!part_info->is_sub_partitioned())
return false;
my_error(ER_DEPENDENT_BY_PARTITION_FUNC, MYF(0), field->field_name);
return true;
}
/**
Sets column default, drops default, renames or alters visibility.
*/
static bool alter_column_name_default_or_visibility(
const Alter_info *alter_info,
Prealloced_array<const Alter_column *, 1> *alter_list, Create_field *def) {
DBUG_TRACE;
// Check if ALTER TABLE has requested of such a change.
size_t i = 0;
const Alter_column *alter = nullptr;
while (i < alter_list->size()) {
alter = (*alter_list)[i];
if (!my_strcasecmp(system_charset_info, def->field_name, alter->name))
break;
i++;
}
// Nothing changed.
if (i == alter_list->size()) return false;
// Setup the field.
switch (alter->change_type()) {
case Alter_column::Type::SET_DEFAULT: {
assert(alter->def || alter->m_default_val_expr);
// Assign new default.
def->constant_default = alter->def;
def->m_default_val_expr = alter->m_default_val_expr;
if (alter->def && def->flags & BLOB_FLAG) {
my_error(ER_BLOB_CANT_HAVE_DEFAULT, MYF(0), def->field_name);
return true;
}
if (alter->m_default_val_expr != nullptr &&
pre_validate_value_generator_expr(
alter->m_default_val_expr->expr_item, alter->name,
VGS_DEFAULT_EXPRESSION))
return true;
// Default value is not permitted for generated columns
if (def->field->is_gcol()) {
my_error(ER_WRONG_USAGE, MYF(0), "DEFAULT", "generated column");
return true;
}
def->flags &= ~NO_DEFAULT_VALUE_FLAG;
/*
The defaults are explicitly altered for the TIMESTAMP/DATETIME
field, through SET DEFAULT. Hence, set the auto_flags member
appropriately.
*/
if (real_type_with_now_as_default(def->sql_type)) {
assert((def->auto_flags & ~(Field::DEFAULT_NOW | Field::ON_UPDATE_NOW |
Field::GENERATED_FROM_EXPRESSION)) == 0);
def->auto_flags &= ~Field::DEFAULT_NOW;
}
/*
Columns can't have AUTO_INCREMENT and DEFAULT/ON UPDATE
CURRENT_TIMESTAMP/ default from expression the same time.
*/
if ((def->auto_flags & Field::NEXT_NUMBER) != 0 &&
((def->auto_flags & (Field::DEFAULT_NOW | Field::ON_UPDATE_NOW)) !=
0 ||
def->m_default_val_expr != nullptr)) {
my_error(ER_INVALID_DEFAULT, MYF(0), def->field_name);
return true;
}
} break;
case Alter_column::Type::DROP_DEFAULT: {
assert(!alter->def);
// Mark field to have no default.
def->constant_default = nullptr;
def->m_default_val_expr = nullptr;
def->flags |= NO_DEFAULT_VALUE_FLAG;
} break;
case Alter_column::Type::RENAME_COLUMN: {
def->change = alter->name;
def->field_name = alter->m_new_name;
/*
If a generated column or a default expression is dependent
on this column, this column cannot be renamed.
The same applies to case when this table is partitioned and
partitioning function is dependent on column being renamed.
*/
if (check_if_field_used_by_generated_column_or_default(
def->field->table, def->field, alter_info) ||
check_if_field_used_by_partitioning_func(def->field->table,
def->field, alter_info))
return true;
} break;
case Alter_column::Type::SET_COLUMN_VISIBLE:
def->hidden = dd::Column::enum_hidden_type::HT_VISIBLE;
break;
case Alter_column::Type::SET_COLUMN_INVISIBLE:
def->hidden = dd::Column::enum_hidden_type::HT_HIDDEN_USER;
break;
default:
assert(0);
my_error(ER_UNKNOWN_ERROR, MYF(0));
return true;
}
// Remove the element from to be altered column list.
alter_list->erase(i);
return false;
}
/**
Check if the column being removed or renamed is in use by a generated
column, default or functional index, which will be kept around/unchanged
by this ALTER TABLE, and report error which is appropriate for the case.
@param table TABLE object describing old table version.
@param field Field object for column to be checked.
@param alter_info Alter_info describing which columns, defaults or
indexes are dropped or modified.
@return
true The field is used by generated column/default or functional
index, error was reported.
false Otherwise.
*/
static bool check_if_field_used_by_generated_column_or_default(
TABLE *table, const Field *field, const Alter_info *alter_info) {
MY_BITMAP dependent_fields;
my_bitmap_map bitbuf[bitmap_buffer_size(MAX_FIELDS) / sizeof(my_bitmap_map)];
bitmap_init(&dependent_fields, bitbuf, table->s->fields);
MY_BITMAP *save_old_read_set = table->read_set;
table->read_set = &dependent_fields;
for (Field **vfield_ptr = table->field; *vfield_ptr; vfield_ptr++) {
Field *vfield = *vfield_ptr;
if (vfield->is_gcol() ||
vfield->has_insert_default_general_value_expression()) {
/*
Ignore generated columns (including hidden columns for functional
indexes) and columns with generated defaults which are going to
be dropped.
*/
if (std::any_of(alter_info->drop_list.cbegin(),
alter_info->drop_list.cend(),
[vfield](const Alter_drop *drop) {
return drop->type == Alter_drop::COLUMN &&
!my_strcasecmp(system_charset_info,
vfield->field_name, drop->name);
}))
continue;
/*
Ignore generated default values which are removed or changed.
If new default value is dependent on removed/renamed column
the problem will be detected and reported as error later.
*/
if (vfield->has_insert_default_general_value_expression() &&
std::any_of(alter_info->alter_list.cbegin(),
alter_info->alter_list.cend(),
[vfield](const Alter_column *alter) {
return (alter->change_type() ==
Alter_column::Type::SET_DEFAULT ||
alter->change_type() ==
Alter_column::Type::DROP_DEFAULT) &&
!my_strcasecmp(system_charset_info,
vfield->field_name, alter->name);
}))
continue;
/*
Ignore columns which are explicitly mentioned in CHANGE/MODIFY
clauses in this ALTER TABLE and thus have new generation expression
or default.
Again if such new expression is dependent on removed/renamed column
the problem will be detected and reported as error later.
*/
if (std::any_of(alter_info->create_list.cbegin(),
alter_info->create_list.cend(),
[vfield](const Create_field &def) {
return (def.change &&
!my_strcasecmp(system_charset_info,
vfield->field_name, def.change));
}))
continue;
assert((vfield->gcol_info && vfield->gcol_info->expr_item) ||
(vfield->m_default_val_expr &&
vfield->m_default_val_expr->expr_item));
Mark_field mark_fld(MARK_COLUMNS_TEMP);
Item *expr = vfield->is_gcol() ? vfield->gcol_info->expr_item
: vfield->m_default_val_expr->expr_item;
expr->walk(&Item::mark_field_in_map, enum_walk::PREFIX,
reinterpret_cast<uchar *>(&mark_fld));
if (bitmap_is_set(table->read_set, field->field_index())) {
if (vfield->is_gcol()) {
if (vfield->is_field_for_functional_index())
my_error(ER_DEPENDENT_BY_FUNCTIONAL_INDEX, MYF(0),
field->field_name);
else
my_error(ER_DEPENDENT_BY_GENERATED_COLUMN, MYF(0),
field->field_name);
} else {
my_error(ER_DEPENDENT_BY_DEFAULT_GENERATED_VALUE, MYF(0),
field->field_name, table->alias);
}
table->read_set = save_old_read_set;
return true;
}
}
}
table->read_set = save_old_read_set;
return false;
}
// Prepare Create_field and Key_spec objects for ALTER and upgrade.
bool prepare_fields_and_keys(THD *thd, const dd::Table *src_table, TABLE *table,
HA_CREATE_INFO *create_info,
Alter_info *alter_info, Alter_table_ctx *alter_ctx,
const uint &used_fields) {
/* New column definitions are added here */
List<Create_field> new_create_list;
/* New key definitions are added here */
Mem_root_array<Key_spec *> new_key_list(thd->mem_root);
/*
Original Alter_info::drop_list is used by foreign key handling code and
storage engines. check_if_field_used_by_generated_column_or_default()
also needs original Alter_info::drop_list. So this function should not
modify original list but rather work with its copy.
*/
Prealloced_array<const Alter_drop *, 1> drop_list(
PSI_INSTRUMENT_ME, alter_info->drop_list.cbegin(),
alter_info->drop_list.cend());
/*
Alter_info::alter_rename_key_list is also used by fill_alter_inplace_info()
call. So this function should not modify original list but rather work with
its copy.
*/
Prealloced_array<const Alter_rename_key *, 1> rename_key_list(
PSI_INSTRUMENT_ME, alter_info->alter_rename_key_list.cbegin(),
alter_info->alter_rename_key_list.cend());
/*
This is how we check that all indexes to be altered are name-resolved: We
make a copy of the list from the alter_info, and remove all the indexes
that are found in the table. Later we check that there is nothing left in
the list. This is obviously just a copy-paste of what is done for renamed
indexes.
*/
Prealloced_array<const Alter_index_visibility *, 1> index_visibility_list(
PSI_INSTRUMENT_ME, alter_info->alter_index_visibility_list.cbegin(),
alter_info->alter_index_visibility_list.cend());
/*
Alter_info::alter_list is used by fill_alter_inplace_info() call as well.
So this function works on its copy rather than original list.
*/
Prealloced_array<const Alter_column *, 1> alter_list(
PSI_INSTRUMENT_ME, alter_info->alter_list.cbegin(),
alter_info->alter_list.cend());
List_iterator<Create_field> def_it(alter_info->create_list);
List_iterator<Create_field> find_it(new_create_list);
List_iterator<Create_field> field_it(new_create_list);
List<Key_part_spec> key_parts;
KEY *key_info = table->key_info;
DBUG_TRACE;
/*
During upgrade from 5.7, old tables are temporarily accessed to
get the keys and fields, and in this process, we assign
table->record[0] = table->s->default_values, hence, we make the
call to restore_record() below conditional to avoid valgrind errors
due to overlapping source and destination for memcpy.
*/
if (table->record[0] != table->s->default_values)
restore_record(table, s->default_values); // Empty record for DEFAULT
std::vector<Create_field *> functional_index_columns;
Create_field *def;
/*
First collect all fields from table which isn't in drop_list
*/
Field **f_ptr, *field;
for (f_ptr = table->field; (field = *f_ptr); f_ptr++) {
/* Check if field should be dropped */
size_t i = 0;
while (i < drop_list.size()) {
const Alter_drop *drop = drop_list[i];
if (drop->type == Alter_drop::COLUMN &&
!my_strcasecmp(system_charset_info, field->field_name, drop->name)) {
/* Reset auto_increment value if it was dropped */
if ((field->auto_flags & Field::NEXT_NUMBER) &&
!(used_fields & HA_CREATE_USED_AUTO)) {
create_info->auto_increment_value = 0;
create_info->used_fields |= HA_CREATE_USED_AUTO;
}
/*
If a generated column or a default expression is dependent
on this column, this column cannot be dropped.
The same applies to case when this table is partitioned and
we drop column used by partitioning function.
*/
if (check_if_field_used_by_generated_column_or_default(table, field,
alter_info) ||
check_if_field_used_by_partitioning_func(table, field, alter_info))
return true;
break; // Column was found.
}
i++;
}
if (i < drop_list.size()) {
drop_list.erase(i);
continue;
}
/* Check if field is changed */
def_it.rewind();
while ((def = def_it++)) {
if (def->change &&
!my_strcasecmp(system_charset_info, field->field_name, def->change))
break;
}
if (def) { // Field is changed
def->field = field;
def->charset = get_sql_field_charset(def, create_info);
if (field->stored_in_db != def->stored_in_db) {
my_error(ER_UNSUPPORTED_ACTION_ON_GENERATED_COLUMN, MYF(0),
"Changing the STORED status");
return true;
}
/*
If a generated column or a default expression is dependent
on this column, this column cannot be renamed.
The same applies to case when this table is partitioned and
we rename column used by partitioning function.
*/
if ((my_strcasecmp(system_charset_info, def->field_name, def->change) !=
0) &&
(check_if_field_used_by_generated_column_or_default(table, field,
alter_info) ||
check_if_field_used_by_partitioning_func(table, field, alter_info)))
return true;
/*
Add column being updated to the list of new columns.
Note that columns with AFTER clauses are added to the end
of the list for now. Their positions will be corrected later.
*/
new_create_list.push_back(def);
/*
If the new column type is GEOMETRY (or a subtype) NOT NULL,
and the old column type is nullable and not GEOMETRY (or a
subtype), existing NULL values will be converted into empty
strings in non-strict mode. Empty strings are illegal values
in GEOMETRY columns.
However, generated columns have implicit default values, so they can be
NOT NULL.
*/
if (def->sql_type == MYSQL_TYPE_GEOMETRY &&
(def->flags & (NO_DEFAULT_VALUE_FLAG | NOT_NULL_FLAG)) &&
field->type() != MYSQL_TYPE_GEOMETRY && field->is_nullable() &&
!thd->is_strict_mode() && !def->is_gcol()) {
alter_ctx->error_if_not_empty |=
Alter_table_ctx::GEOMETRY_WITHOUT_DEFAULT;
}
} else {
/*
This field was not dropped and the definition is not changed, add
it to the list for the new table.
*/
def = new (thd->mem_root) Create_field(field, field);
// Mark if collation was specified explicitly by user for the column.
const dd::Table *obj =
(table->s->tmp_table ? table->s->tmp_table_def : src_table);
// In case of upgrade, we do not have src_table.
if (!obj)
def->is_explicit_collation = false;
else
def->is_explicit_collation =
obj->get_column(field->field_name)->is_explicit_collation();
// If we have a replication setup _and_ the master doesn't sort
// functional index columns last in the table, we will not do it either.
// Otherwise, we will position the functional index columns last in the
// table, sorted on their name.
if (is_field_for_functional_index(def) &&
is_not_slave_or_master_sorts_functional_index_columns_last(
thd->variables.original_server_version)) {
functional_index_columns.push_back(def);
} else {
new_create_list.push_back(def);
}
if (alter_column_name_default_or_visibility(alter_info, &alter_list, def))
return true;
}
}
def_it.rewind();
while ((def = def_it++)) // Add new columns
{
if (def->change && !def->field) {
my_error(ER_BAD_FIELD_ERROR, MYF(0), def->change,
table->s->table_name.str);
return true;
}
warn_on_deprecated_float_auto_increment(thd, *def);
/*
If this ALTER TABLE doesn't have an AFTER clause for the modified
column then it doesn't need further processing.
*/
if (def->change && !def->after) continue;
/*
New columns of type DATE/DATETIME/GEOMETRIC with NOT NULL constraint
added as part of ALTER operation will generate zero date for DATE/
DATETIME types and empty string for GEOMETRIC types when the table
is not empty. Hence certain additional checks needs to be performed
as described below. This cannot be caught by SE(For INPLACE ALTER)
since it checks for only NULL value. Zero date and empty string
does not violate the NOT NULL value constraint.
*/
if (!def->change) {
/*
Check that the DATE/DATETIME NOT NULL field we are going to
add either has a default value, is a generated column, or the
date '0000-00-00' is allowed by the set sql mode.
If the '0000-00-00' value isn't allowed then raise the
error_if_not_empty flag to allow ALTER TABLE only if the table to be
altered is empty.
*/
if ((def->sql_type == MYSQL_TYPE_DATE ||
def->sql_type == MYSQL_TYPE_NEWDATE ||
def->sql_type == MYSQL_TYPE_DATETIME ||
def->sql_type == MYSQL_TYPE_DATETIME2) &&
!alter_ctx->datetime_field && !def->is_gcol() &&
!(~def->flags & (NO_DEFAULT_VALUE_FLAG | NOT_NULL_FLAG))) {
alter_ctx->datetime_field = def;
alter_ctx->error_if_not_empty |=
Alter_table_ctx::DATETIME_WITHOUT_DEFAULT;
}
/*
New GEOMETRY (and subtypes) columns can't be NOT NULL unless they have a
default value. Explicit default values are currently not supported for
geometry columns. To add a GEOMETRY NOT NULL column, first create a
GEOMETRY NULL column, UPDATE the table to set a different value than
NULL, and then do a ALTER TABLE MODIFY COLUMN to set NOT NULL.
This restriction can be lifted once MySQL supports explicit default
values (i.e., functions) for geometry columns. The new restriction would
then be for added GEOMETRY NOT NULL columns to always have a provided
default value.
Generated columns (including generated geometry columns) have implicit
default values, so they can be NOT NULL.
*/
if (def->sql_type == MYSQL_TYPE_GEOMETRY && !def->is_gcol() &&
(def->flags & (NO_DEFAULT_VALUE_FLAG | NOT_NULL_FLAG))) {
alter_ctx->error_if_not_empty |=
Alter_table_ctx::GEOMETRY_WITHOUT_DEFAULT;
}
}
if (!def->after)
new_create_list.push_back(def);
else {
const Create_field *find;
if (def->change) {
find_it.rewind();
/*
For columns being modified with AFTER clause we should first remove
these columns from the list and then add them back at their correct
positions.
*/
while ((find = find_it++)) {
/*
Create_fields representing changed columns are added directly
from Alter_info::create_list to new_create_list. We can therefore
safely use pointer equality rather than name matching here.
This prevents removing the wrong column in case of column rename.
*/
if (find == def) {
find_it.remove();
break;
}
}
}
if (def->after == first_keyword)
new_create_list.push_front(def);
else {
find_it.rewind();
while ((find = find_it++)) {
if (!my_strcasecmp(system_charset_info, def->after, find->field_name))
break;
}
if (!find) {
my_error(ER_BAD_FIELD_ERROR, MYF(0), def->after,
table->s->table_name.str);
return true;
}
find_it.after(def); // Put column after this
}
}
}
if (alter_list.size() > 0) {
my_error(ER_BAD_FIELD_ERROR, MYF(0), alter_list[0]->name,
table->s->table_name.str);
return true;
}
// Ensure that hidden generated column for functional indexes are inserted at
// the end, sorted by their column name.
std::sort(functional_index_columns.begin(), functional_index_columns.end(),
[](const Create_field *a, const Create_field *b) {
return my_strcasecmp(system_charset_info, a->field_name,
b->field_name) < 0;
});
for (Create_field *ic_field : functional_index_columns) {
new_create_list.push_back(ic_field);
}
if (!new_create_list.elements) {
my_error(ER_CANT_REMOVE_ALL_FIELDS, MYF(0));
return true;
}
// Make sure generated invisible primary key column is at the first position.
if (adjust_generated_invisible_primary_key_column_position(
thd, create_info->db_type, table, &new_create_list))
return true;
/*
Collect all keys which isn't in drop list. Add only those
for which some fields exists.
*/
for (uint i = 0; i < table->s->keys; i++, key_info++) {
const char *key_name = key_info->name;
bool index_column_dropped = false;
size_t drop_idx = 0;
while (drop_idx < drop_list.size()) {
const Alter_drop *drop = drop_list[drop_idx];
if (drop->type == Alter_drop::KEY &&
!my_strcasecmp(system_charset_info, key_name, drop->name))
break;
drop_idx++;
}
if (drop_idx < drop_list.size()) {
drop_list.erase(drop_idx);
continue;
}
KEY_PART_INFO *key_part = key_info->key_part;
key_parts.clear();
for (uint j = 0; j < key_info->user_defined_key_parts; j++, key_part++) {
if (!key_part->field) continue; // Wrong field (from UNIREG)
const char *key_part_name = key_part->field->field_name;
const Create_field *cfield;
field_it.rewind();
while ((cfield = field_it++)) {
if (cfield->change) {
if (!my_strcasecmp(system_charset_info, key_part_name,
cfield->change))
break;
} else if (!my_strcasecmp(system_charset_info, key_part_name,
cfield->field_name))
break;
}
if (!cfield) {
/*
We are dropping a column associated with an index.
*/
index_column_dropped = true;
continue; // Field is removed
}
uint key_part_length = key_part->length;
if (cfield->field) // Not new field
{
/*
If the field can't have only a part used in a key according to its
new type, or should not be used partially according to its
previous type, or the field length is less than the key part
length, unset the key part length.
We also unset the key part length if it is the same as the
old field's length, so the whole new field will be used.
BLOBs may have cfield->length == 0, which is why we test it before
checking whether cfield->length < key_part_length (in chars).
In case of TEXTs we check the data type maximum length *in bytes*
to key part length measured *in characters* (i.e. key_part_length
divided to mbmaxlen). This is because it's OK to have:
CREATE TABLE t1 (a tinytext, key(a(254)) character set utf8);
In case of this example:
- data type maximum length is 255.
- key_part_length is 1016 (=254*4, where 4 is mbmaxlen)
*/
if (!Field::type_can_have_key_part(cfield->field->type()) ||
!Field::type_can_have_key_part(cfield->sql_type) ||
/* spatial keys can't have sub-key length */
(key_info->flags & HA_SPATIAL) ||
(cfield->field->field_length == key_part_length &&
key_part->field->type() != MYSQL_TYPE_BLOB) ||
(cfield->max_display_width_in_codepoints() &&
(((cfield->sql_type >= MYSQL_TYPE_TINY_BLOB &&
cfield->sql_type <= MYSQL_TYPE_BLOB)
? blob_length_by_type(cfield->sql_type)
: cfield->max_display_width_in_codepoints()) <
key_part_length / key_part->field->charset()->mbmaxlen)))
key_part_length = 0; // Use whole field
}
key_part_length /= key_part->field->charset()->mbmaxlen;
// The Key_part_spec constructor differentiates between explicit ascending
// (ORDER_ASC) and implicit ascending order (ORDER_NOT_RELEVANT). However,
// here we only have HA_REVERSE_SORT to base our ordering decision on. The
// only known case where the difference matters is in case of indexes on
// geometry columns and typed arrays, which can't have explicit ordering.
// Therefore, in such cases we pass ORDER_NOT_RELEVANT.
enum_order order =
key_part->key_part_flag & HA_REVERSE_SORT
? ORDER_DESC
: ((key_part->field->type() == MYSQL_TYPE_GEOMETRY ||
key_part->field->is_array())
? ORDER_NOT_RELEVANT
: ORDER_ASC);
if (key_part->field->is_field_for_functional_index()) {
key_parts.push_back(new (thd->mem_root) Key_part_spec(
cfield->field_name, key_part->field->gcol_info->expr_item, order));
} else {
key_parts.push_back(new (thd->mem_root) Key_part_spec(
to_lex_cstring(cfield->field_name), key_part_length, order));
}
}
if (key_parts.elements) {
KEY_CREATE_INFO key_create_info(key_info->is_visible);
keytype key_type;
/* If this index is to stay in the table check if it has to be renamed. */
for (size_t rename_idx = 0; rename_idx < rename_key_list.size();
rename_idx++) {
const Alter_rename_key *rename_key = rename_key_list[rename_idx];
if (!my_strcasecmp(system_charset_info, key_name,
rename_key->old_name)) {
if (!my_strcasecmp(system_charset_info, key_name, primary_key_name)) {
my_error(ER_WRONG_NAME_FOR_INDEX, MYF(0), rename_key->old_name);
return true;
} else if (!my_strcasecmp(system_charset_info, rename_key->new_name,
primary_key_name)) {
my_error(ER_WRONG_NAME_FOR_INDEX, MYF(0), rename_key->new_name);
return true;
}
key_name = rename_key->new_name;
rename_key_list.erase(rename_idx);
/*
If the user has explicitly renamed the key, we should no longer
treat it as generated. Otherwise this key might be automatically
dropped by mysql_prepare_create_table() and this will confuse
code in fill_alter_inplace_info().
*/
key_info->flags &= ~HA_GENERATED_KEY;
break;
}
}
// Erase all alter operations that operate on this index.
for (auto it = index_visibility_list.begin();
it < index_visibility_list.end();)
if (my_strcasecmp(system_charset_info, key_name, (*it)->name()) == 0)
index_visibility_list.erase(it);
else
++it;
if (key_info->is_algorithm_explicit) {
key_create_info.algorithm = key_info->algorithm;
key_create_info.is_algorithm_explicit = true;
} else {
/*
If key algorithm was not specified explicitly for source table
don't specify one a new version as well, This allows to handle
ALTER TABLEs which change SE nicely.
OTOH this means that any ALTER TABLE will rebuild such keys when
SE changes default algorithm for key. Code will have to be adjusted
to handle such situation more gracefully.
*/
assert((key_create_info.is_algorithm_explicit == false) &&
(key_create_info.algorithm == HA_KEY_ALG_SE_SPECIFIC));
}
if (key_info->flags & HA_USES_BLOCK_SIZE)
key_create_info.block_size = key_info->block_size;
if (key_info->flags & HA_USES_PARSER)
key_create_info.parser_name = *plugin_name(key_info->parser);
if (key_info->flags & HA_USES_COMMENT)
key_create_info.comment = key_info->comment;
if (key_info->engine_attribute.str != nullptr)
key_create_info.m_engine_attribute = key_info->engine_attribute;
if (key_info->secondary_engine_attribute.str != nullptr)
key_create_info.m_secondary_engine_attribute =
key_info->secondary_engine_attribute;
for (const Alter_index_visibility *alter_index_visibility :
alter_info->alter_index_visibility_list) {
const char *name = alter_index_visibility->name();
if (my_strcasecmp(system_charset_info, key_name, name) == 0) {
if (table->s->primary_key <= MAX_KEY &&
table->key_info + table->s->primary_key == key_info) {
my_error(ER_PK_INDEX_CANT_BE_INVISIBLE, MYF(0));
return true;
}
key_create_info.is_visible = alter_index_visibility->is_visible();
}
}
if (key_info->flags & HA_SPATIAL)
key_type = KEYTYPE_SPATIAL;
else if (key_info->flags & HA_NOSAME) {
if (!my_strcasecmp(system_charset_info, key_name, primary_key_name))
key_type = KEYTYPE_PRIMARY;
else
key_type = KEYTYPE_UNIQUE;
} else if (key_info->flags & HA_FULLTEXT)
key_type = KEYTYPE_FULLTEXT;
else
key_type = KEYTYPE_MULTIPLE;
/*
If we have dropped a column associated with an index,
this warrants a check for duplicate indexes
*/
new_key_list.push_back(new (thd->mem_root) Key_spec(
thd->mem_root, key_type, to_lex_cstring(key_name), &key_create_info,
(key_info->flags & HA_GENERATED_KEY), index_column_dropped,
key_parts));
}
}
{
new_key_list.reserve(new_key_list.size() + alter_info->key_list.size());
for (size_t i = 0; i < alter_info->key_list.size(); i++)
new_key_list.push_back(alter_info->key_list[i]); // Add new keys
}
/*
Copy existing foreign keys from the source table into
Alter_table_ctx so that they can be added to the new table
later. Omits foreign keys to be dropped and removes them
from the drop_list. Checks that foreign keys to be kept
are still valid.
*/
if (create_info->db_type->flags & HTON_SUPPORTS_FOREIGN_KEYS) {
if (transfer_preexisting_foreign_keys(
thd, src_table, table->s->db.str, table->s->table_name.str,
table->s->db_type(), alter_info, &new_create_list, alter_ctx,
&drop_list))
return true;
}
if (drop_list.size() > 0) {
// Now this contains only DROP for not-found objects.
for (const Alter_drop *drop : drop_list) {
switch (drop->type) {
case Alter_drop::FOREIGN_KEY:
if (!(create_info->db_type->flags & HTON_SUPPORTS_FOREIGN_KEYS)) {
/*
For historical reasons we silently ignore attempts to drop
foreign keys from tables in storage engines which don't
support them. This is in sync with the fact that attempts
to add foreign keys to such tables are silently ignored
as well. Once the latter is changed the former hack can
be removed as well.
*/
break;
}
[[fallthrough]];
case Alter_drop::KEY:
case Alter_drop::COLUMN:
my_error(ER_CANT_DROP_FIELD_OR_KEY, MYF(0), drop->name);
return true;
case Alter_drop::CHECK_CONSTRAINT:
/*
Check constraints to be dropped are already handled by the
prepare_check_constraints_for_alter().
*/
break;
case Alter_drop::ANY_CONSTRAINT:
/*
Constraint type is resolved by name and a new Alter_drop element
with resolved type is added to the Alter_drop list.
Alter_drop::ANY_CONSTRAINT element is retained in the Alter_drop
list to support re-execution of stored routine or prepared
statement.
*/
break;
default:
assert(false);
break;
}
}
}
if (rename_key_list.size() > 0) {
my_error(ER_KEY_DOES_NOT_EXITS, MYF(0), rename_key_list[0]->old_name,
table->s->table_name.str);
return true;
}
if (index_visibility_list.size() > 0) {
my_error(ER_KEY_DOES_NOT_EXITS, MYF(0), index_visibility_list[0]->name(),
table->s->table_name.str);
return true;
}
alter_info->create_list.swap(new_create_list);
alter_info->key_list.clear();
alter_info->key_list.resize(new_key_list.size());
std::copy(new_key_list.begin(), new_key_list.end(),
alter_info->key_list.begin());
return false;
}
/**
Prepare column and key definitions for CREATE TABLE in ALTER TABLE.
This function transforms parse output of ALTER TABLE - lists of
columns and keys to add, drop or modify into, essentially,
CREATE TABLE definition - a list of columns and keys of the new
table. While doing so, it also performs some (bug not all)
semantic checks.
This function is invoked when we know that we're going to
perform ALTER TABLE via a temporary table -- i.e. in-place ALTER TABLE
is not possible, perhaps because the ALTER statement contains
instructions that require change in table data, not only in
table definition or indexes.
@param[in,out] thd thread handle. Used as a memory pool
and source of environment information.
@param[in] src_table DD table object for the table to be
created/altered. Will be nullptr for temporary tables.
@param[in] table the source table, open and locked
Used as an interface to the storage engine
to acquire additional information about
the original table.
@param[in,out] create_info A blob with CREATE/ALTER TABLE
parameters
@param[in,out] alter_info Another blob with ALTER/CREATE parameters.
Originally create_info was used only in
CREATE TABLE and alter_info only in ALTER TABLE.
But since ALTER might end-up doing CREATE,
this distinction is gone and we just carry
around two structures.
@param[in,out] alter_ctx Runtime context for ALTER TABLE.
@return
Fills various create_info members based on information retrieved
from the storage engine.
Sets create_info->varchar if the table has a VARCHAR column.
Prepares alter_info->create_list and alter_info->key_list with
columns and keys of the new table.
@retval true error, out of memory or a semantical error in ALTER
TABLE instructions
@retval false success
*/
bool mysql_prepare_alter_table(THD *thd, const dd::Table *src_table,
TABLE *table, HA_CREATE_INFO *create_info,
Alter_info *alter_info,
Alter_table_ctx *alter_ctx) {
uint db_create_options =
(table->s->db_create_options & ~(HA_OPTION_PACK_RECORD));
uint64_t used_fields = create_info->used_fields;
DBUG_TRACE;
// Prepare data in HA_CREATE_INFO shared by ALTER and upgrade code.
create_info->init_create_options_from_share(table->s, used_fields);
if (!(used_fields & HA_CREATE_USED_AUTO) && table->found_next_number_field) {
/* Table has an autoincrement, copy value to new table */
table->file->info(HA_STATUS_AUTO);
create_info->auto_increment_value = table->file->stats.auto_increment_value;
}
if (prepare_fields_and_keys(thd, src_table, table, create_info, alter_info,
alter_ctx, used_fields))
return true;
table->file->update_create_info(create_info);
/* Get the autoextend_size value for the old table if the user did not
specify it on the command line */
if (src_table && src_table->engine() == "InnoDB") {
ulonglong autoextend_size{};
dd::get_implicit_tablespace_options(thd, src_table, &autoextend_size);
if (!create_info->m_implicit_tablespace_autoextend_size_change) {
create_info->m_implicit_tablespace_autoextend_size = autoextend_size;
}
}
/*
NDB storage engine misuses handler::update_create_info() to implement
special handling of table comments which are used to specify and store
some NDB-specific table options. In the process it might report error.
In order to detect and correctly handle such situation we need to call
THD::is_error().
*/
if (thd->is_error()) return true;
if ((create_info->table_options &
(HA_OPTION_PACK_KEYS | HA_OPTION_NO_PACK_KEYS)) ||
(used_fields & HA_CREATE_USED_PACK_KEYS))
db_create_options &= ~(HA_OPTION_PACK_KEYS | HA_OPTION_NO_PACK_KEYS);
if ((create_info->table_options &
(HA_OPTION_STATS_PERSISTENT | HA_OPTION_NO_STATS_PERSISTENT)) ||
(used_fields & HA_CREATE_USED_STATS_PERSISTENT))
db_create_options &=
~(HA_OPTION_STATS_PERSISTENT | HA_OPTION_NO_STATS_PERSISTENT);
if (create_info->table_options & (HA_OPTION_CHECKSUM | HA_OPTION_NO_CHECKSUM))
db_create_options &= ~(HA_OPTION_CHECKSUM | HA_OPTION_NO_CHECKSUM);
if (create_info->table_options &
(HA_OPTION_DELAY_KEY_WRITE | HA_OPTION_NO_DELAY_KEY_WRITE))
db_create_options &=
~(HA_OPTION_DELAY_KEY_WRITE | HA_OPTION_NO_DELAY_KEY_WRITE);
create_info->table_options |= db_create_options;
if (table->s->tmp_table) create_info->options |= HA_LEX_CREATE_TMP_TABLE;
return false;
}
/**
Get Create_field object for newly created table by its name
in the old version of table.
@param alter_info Alter_info describing newly created table.
@param old_name Name of field in old table.
@returns Pointer to Create_field object, NULL - if field is
not present in new version of table.
*/
static const Create_field *get_field_by_old_name(Alter_info *alter_info,
const char *old_name) {
List_iterator_fast<Create_field> new_field_it(alter_info->create_list);
const Create_field *new_field;
while ((new_field = new_field_it++)) {
if (new_field->field &&
(my_strcasecmp(system_charset_info, new_field->field->field_name,
old_name) == 0))
break;
}
return new_field;
}
/** Type of change to foreign key column, */
enum fk_column_change_type {
FK_COLUMN_NO_CHANGE,
FK_COLUMN_DATA_CHANGE,
FK_COLUMN_RENAMED,
FK_COLUMN_DROPPED
};
/**
Check that ALTER TABLE's changes on columns of a foreign key are allowed.
@tparam F Function class which returns foreign key's
referenced or referencing (depending on
whether we check ALTER TABLE that changes
parent or child table) column name by its
index.
@param[in] thd Thread context.
@param[in] alter_info Alter_info describing changes to be done
by ALTER TABLE.
@param[in] fk_col_count Number of columns in the foreign key.
@param[in] fk_columns Object of F type bound to the specific foreign
key for which check is carried out.
@param[out] bad_column_name Name of field on which ALTER TABLE tries to
do prohibited operation.
@note This function takes into account value of @@foreign_key_checks
setting.
@retval FK_COLUMN_NO_CHANGE No significant changes are to be done on
foreign key columns.
@retval FK_COLUMN_DATA_CHANGE ALTER TABLE might result in value
change in foreign key column (and
foreign_key_checks is on).
@retval FK_COLUMN_RENAMED Foreign key column is renamed.
@retval FK_COLUMN_DROPPED Foreign key column is dropped.
*/
template <class F>
static fk_column_change_type fk_check_column_changes(
THD *thd, Alter_info *alter_info, uint fk_col_count, const F &fk_columns,
const char **bad_column_name) {
*bad_column_name = nullptr;
for (uint i = 0; i < fk_col_count; ++i) {
const char *column = fk_columns(i);
const Create_field *new_field = get_field_by_old_name(alter_info, column);
if (new_field) {
Field *old_field = new_field->field;
if (my_strcasecmp(system_charset_info, old_field->field_name,
new_field->field_name)) {
/*
Copy algorithm doesn't support proper renaming of columns in
the foreign key yet. At the moment we lack API which will tell
SE that foreign keys should be updated to use new name of column
like it happens in case of in-place algorithm.
*/
*bad_column_name = column;
return FK_COLUMN_RENAMED;
}
if ((old_field->is_equal(new_field) == IS_EQUAL_NO) ||
((new_field->flags & NOT_NULL_FLAG) &&
!old_field->is_flag_set(NOT_NULL_FLAG))) {
if (!(thd->variables.option_bits & OPTION_NO_FOREIGN_KEY_CHECKS)) {
/*
Column in a FK has changed significantly. Unless
foreign_key_checks are off we prohibit this since this
means values in this column might be changed by ALTER
and thus referential integrity might be broken,
*/
*bad_column_name = column;
return FK_COLUMN_DATA_CHANGE;
}
}
assert(old_field->is_gcol() == new_field->is_gcol() &&
old_field->is_virtual_gcol() == new_field->is_virtual_gcol());
assert(!old_field->is_gcol() || old_field->gcol_expr_is_equal(new_field));
} else {
/*
Column in FK was dropped. Most likely this will break
integrity constraints of InnoDB data-dictionary (and thus
InnoDB will emit an error), so we prohibit this right away
even if foreign_key_checks are off.
This also includes a rare case when another field replaces
field being dropped since it is easy to break referential
integrity in this case.
*/
*bad_column_name = column;
return FK_COLUMN_DROPPED;
}
}
return FK_COLUMN_NO_CHANGE;
}
/**
Check if ALTER TABLE we are about to execute using COPY algorithm
is not supported as it might break referential integrity.
@note If foreign_key_checks is disabled (=0), we allow to break
referential integrity. But we still disallow some operations
like dropping or renaming columns in foreign key since they
are likely to break consistency of InnoDB data-dictionary
and thus will end-up in error anyway.
@param[in] thd Thread context.
@param[in] table_list Table_ref element for the table to be altered.
@param[in] table_def dd::Table for old version of table to be altered.
@param[in] alter_info Lists of fields, keys to be changed, added
or dropped.
@retval false Success.
@retval true Error, ALTER - tries to do change which is not compatible
with foreign key definitions on the table.
*/
static bool fk_check_copy_alter_table(THD *thd, Table_ref *table_list,
const dd::Table *table_def,
Alter_info *alter_info) {
DBUG_TRACE;
if (!table_def) return false; // Must be a temporary table.
for (const dd::Foreign_key_parent *fk_p : table_def->foreign_key_parents()) {
/*
First, check foreign keys in which table participates as parent.
To get necessary information about such a foreign key we need to
acquire dd::Table object describing child table.
*/
dd::cache::Dictionary_client::Auto_releaser releaser(thd->dd_client());
const dd::Table *child_table_def;
bool self_ref_fk =
(my_strcasecmp(table_alias_charset, fk_p->child_schema_name().c_str(),
table_list->db) == 0 &&
my_strcasecmp(table_alias_charset, fk_p->child_table_name().c_str(),
table_list->table_name) == 0);
if (self_ref_fk)
child_table_def = table_def;
else {
if (thd->dd_client()->acquire(fk_p->child_schema_name(),
fk_p->child_table_name(), &child_table_def))
return true;
}
assert(child_table_def != nullptr);
for (const dd::Foreign_key *fk : child_table_def->foreign_keys()) {
/*
Skip all foreign keys except one which corresponds to the
dd::Foreign_key_parent object being processed.
*/
if (my_strcasecmp(system_charset_info, fk_p->fk_name().c_str(),
fk->name().c_str()) != 0)
continue;
if (self_ref_fk) {
/*
Also skip all foreign keys which are to be dropped by this
ALTER TABLE. This is possible when a foreign key has the
same table as child and parent.
*/
bool is_dropped = false;
for (const Alter_drop *drop : alter_info->drop_list) {
/* Names of foreign keys in InnoDB are case-insensitive. */
if ((drop->type == Alter_drop::FOREIGN_KEY) &&
(my_strcasecmp(system_charset_info, fk->name().c_str(),
drop->name) == 0)) {
is_dropped = true;
break;
}
}
if (is_dropped) continue;
}
enum fk_column_change_type changes;
const char *bad_column_name;
auto fk_columns_lambda = [fk](uint i) {
return fk->elements()[i]->referenced_column_name().c_str();
};
changes = fk_check_column_changes(thd, alter_info, fk->elements().size(),
fk_columns_lambda, &bad_column_name);
switch (changes) {
case FK_COLUMN_NO_CHANGE:
/* No significant changes. We can proceed with ALTER! */
break;
case FK_COLUMN_DATA_CHANGE: {
char buff[NAME_LEN * 2 + 2];
strxnmov(buff, sizeof(buff) - 1, fk_p->child_schema_name().c_str(),
".", fk_p->child_table_name().c_str(), NullS);
my_error(ER_FK_COLUMN_CANNOT_CHANGE_CHILD, MYF(0), bad_column_name,
fk->name().c_str(), buff);
return true;
}
case FK_COLUMN_RENAMED:
my_error(
ER_ALTER_OPERATION_NOT_SUPPORTED_REASON, MYF(0), "ALGORITHM=COPY",
ER_THD(thd, ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_FK_RENAME),
"ALGORITHM=INPLACE");
return true;
case FK_COLUMN_DROPPED:
/*
Should already have been checked in
transfer_preexisting_foreign_keys().
*/
assert(false);
default:
assert(0);
}
}
}
for (const dd::Foreign_key *fk : table_def->foreign_keys()) {
/*
Now, check foreign keys in which table participates as child.
Skip all foreign keys which are to be dropped by this ALTER TABLE.
*/
bool is_dropped = false;
for (const Alter_drop *drop : alter_info->drop_list) {
/* Names of foreign keys in InnoDB are case-insensitive. */
if ((drop->type == Alter_drop::FOREIGN_KEY) &&
(my_strcasecmp(system_charset_info, fk->name().c_str(), drop->name) ==
0)) {
is_dropped = true;
break;
}
}
if (is_dropped) continue;
enum fk_column_change_type changes;
const char *bad_column_name;
auto fk_columns_lambda = [fk](uint i) {
return fk->elements()[i]->column().name().c_str();
};
changes = fk_check_column_changes(thd, alter_info, fk->elements().size(),
fk_columns_lambda, &bad_column_name);
switch (changes) {
case FK_COLUMN_NO_CHANGE:
/* No significant changes. We can proceed with ALTER! */
break;
case FK_COLUMN_DATA_CHANGE:
my_error(ER_FK_COLUMN_CANNOT_CHANGE, MYF(0), bad_column_name,
fk->name().c_str());
return true;
case FK_COLUMN_RENAMED:
my_error(ER_ALTER_OPERATION_NOT_SUPPORTED_REASON, MYF(0),
"ALGORITHM=COPY",
ER_THD(thd, ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_FK_RENAME),
"ALGORITHM=INPLACE");
return true;
case FK_COLUMN_DROPPED:
/*
Should already have been checked in
transfer_preexisting_foreign_keys().
*/
assert(false);
default:
assert(0);
}
}
return false;
}
bool collect_and_lock_fk_tables_for_rename_table(
THD *thd, const char *db, const char *table_name,
const dd::Table *table_def, const char *new_db, const char *new_table_name,
handlerton *hton, Foreign_key_parents_invalidator *fk_invalidator) {
MDL_request_list mdl_requests;
if (collect_fk_children(thd, db, table_name, hton, MDL_EXCLUSIVE,
&mdl_requests) ||
collect_fk_children(thd, new_db, new_table_name, hton, MDL_EXCLUSIVE,
&mdl_requests) ||
collect_fk_parents_for_all_fks(thd, table_def, hton, MDL_EXCLUSIVE,
&mdl_requests, fk_invalidator) ||
collect_fk_names_for_rename_table(thd, db, table_name, table_def, hton,
new_db, new_table_name, &mdl_requests))
return true;
if (!mdl_requests.is_empty() &&
thd->mdl_context.acquire_locks(&mdl_requests,
thd->variables.lock_wait_timeout))
return true;
return false;
}
bool adjust_adopted_self_ref_fk_for_simple_rename_table(
THD *thd, const char *db, const char *table_name, const char *new_db,
const char *new_table_name, handlerton *hton) {
dd::cache::Dictionary_client::Auto_releaser releaser(thd->dd_client());
dd::Table *table_def = nullptr;
if (thd->dd_client()->acquire_for_modification(db, table_name, &table_def))
return true;
if (table_def->foreign_keys()->empty()) return false;
bool has_adopted_fk = false;
for (dd::Foreign_key *fk : *(table_def->foreign_keys())) {
if (my_strcasecmp(table_alias_charset,
fk->referenced_table_schema_name().c_str(),
new_db) == 0 &&
my_strcasecmp(table_alias_charset, fk->referenced_table_name().c_str(),
new_table_name) == 0) {
/*
Check that table has a column which is compatible with the foreign key's
referenced column.
*/
for (dd::Foreign_key_element *fk_el : *(fk->elements())) {
if (check_table_has_col_compatible_with_fk_ref_col(table_def, fk, fk_el,
hton))
return true;
}
if (prepare_fk_parent_key(hton, table_def, nullptr, nullptr, true, fk))
return true;
has_adopted_fk = true;
}
}
return (has_adopted_fk && thd->dd_client()->update(table_def));
}
bool adjust_fks_for_rename_table(THD *thd, const char *db,
const char *table_name, const char *new_db,
const char *new_table_name, handlerton *hton) {
const dd::Table *new_table = nullptr;
if (thd->dd_client()->acquire(new_db, new_table_name, &new_table))
return true;
assert(new_table != nullptr);
if (adjust_fk_children_after_parent_rename(thd, db, table_name, hton, new_db,
new_table_name))
return true;
if (adjust_fk_children_after_parent_def_change(thd, new_db, new_table_name,
hton, new_table, nullptr))
return true;
if (adjust_fk_parents(thd, new_db, new_table_name, true, nullptr))
return true;
return false;
}
/**
Check if ALTER TABLE in question is a simple ALTER TABLE RENAME or
ALTER TABLE ENABLE/DISABLE KEYS.
@param alter_info Alter_info describing ALTER.
*/
static bool is_simple_rename_or_index_change(const Alter_info *alter_info) {
return (!(alter_info->flags &
~(Alter_info::ALTER_RENAME | Alter_info::ALTER_KEYS_ONOFF)) &&
alter_info->requested_algorithm !=
Alter_info::ALTER_TABLE_ALGORITHM_COPY);
}
/**
Rename table and/or turn indexes on/off without touching .FRM
@param thd Thread handler
@param new_schema Target schema.
@param table_list Table_ref for the table to change
@param keys_onoff ENABLE or DISABLE KEYS?
@param alter_ctx ALTER TABLE runtime context.
@return Operation status
@retval false Success
@retval true Failure
*/
static bool simple_rename_or_index_change(
THD *thd, const dd::Schema &new_schema, Table_ref *table_list,
Alter_info::enum_enable_or_disable keys_onoff, Alter_table_ctx *alter_ctx) {
TABLE *table = table_list->table;
MDL_ticket *mdl_ticket = table->mdl_ticket;
int error = 0;
handlerton *old_db_type = table->s->db_type();
bool atomic_ddl = (old_db_type->flags & HTON_SUPPORTS_ATOMIC_DDL);
Foreign_key_parents_invalidator fk_invalidator;
DBUG_TRACE;
if (keys_onoff != Alter_info::LEAVE_AS_IS) {
if (wait_while_table_is_used(thd, table, HA_EXTRA_FORCE_REOPEN))
return true;
// It's now safe to take the table level lock.
if (lock_tables(thd, table_list, alter_ctx->tables_opened, 0)) return true;
if (keys_onoff == Alter_info::ENABLE) {
DEBUG_SYNC(thd, "alter_table_enable_indexes");
DBUG_EXECUTE_IF("sleep_alter_enable_indexes", my_sleep(6000000););
error = table->file->ha_enable_indexes(HA_KEY_SWITCH_NONUNIQ_SAVE);
} else if (keys_onoff == Alter_info::DISABLE)
error = table->file->ha_disable_indexes(HA_KEY_SWITCH_NONUNIQ_SAVE);
if (error == HA_ERR_WRONG_COMMAND) {
push_warning_printf(thd, Sql_condition::SL_NOTE, ER_ILLEGAL_HA,
ER_THD(thd, ER_ILLEGAL_HA), table->alias);
error = 0;
} else if (error > 0) {
table->file->print_error(error, MYF(0));
error = -1;
} else {
/**
Update mysql.tables.options with keys_disabled=1/0 based on keys_onoff.
This will used by INFORMATION_SCHEMA.STATISTICS system view to display
keys were disabled.
*/
dd::Table *tab_obj = nullptr;
if (thd->dd_client()->acquire_for_modification(
table_list->db, table_list->table_name, &tab_obj))
error = -1;
else {
assert(tab_obj != nullptr);
tab_obj->options().set("keys_disabled",
(keys_onoff == Alter_info::DISABLE ? 1 : 0));
// Update the changes
bool result = thd->dd_client()->update(tab_obj);
if (!atomic_ddl) result = trans_intermediate_ddl_commit(thd, result);
if (result) error = -1;
}
}
}
if (!error && alter_ctx->is_table_renamed()) {
THD_STAGE_INFO(thd, stage_rename);
/*
Then do a 'simple' rename of the table. First we need to close all
instances of 'source' table.
Note that if wait_while_table_is_used() returns error here (i.e. if
this thread was killed) then it must be that previous step of
simple rename did nothing and therefore we can safely return
without additional clean-up.
*/
if (wait_while_table_is_used(thd, table, HA_EXTRA_FORCE_REOPEN))
return true;
const dd::Table *table_def = nullptr;
if (thd->dd_client()->acquire(table_list->db, table_list->table_name,
&table_def))
return true;
assert(table_def != nullptr);
/*
Check table encryption privilege, if rename changes database.
*/
if (alter_ctx->is_database_changed()) {
bool is_general_tablespace{false};
bool is_table_encrypted{false};
dd::Encrypt_result result =
dd::is_tablespace_encrypted(thd, *table_def, &is_general_tablespace);
if (result.error) {
return true;
}
is_table_encrypted = result.value;
// If implicit tablespace, read the encryption clause value.
if (!is_general_tablespace &&
table_def->options().exists("encrypt_type")) {
dd::String_type et;
(void)table_def->options().get("encrypt_type", &et);
assert(et.empty() == false);
is_table_encrypted = is_encrypted(et);
}
// If table encryption differ from schema encryption, check privilege.
if (new_schema.default_encryption() != is_table_encrypted) {
if (opt_table_encryption_privilege_check) {
if (check_table_encryption_admin_access(thd)) {
my_error(ER_CANNOT_SET_TABLE_ENCRYPTION, MYF(0));
return true;
}
} else if (new_schema.default_encryption() && !is_table_encrypted) {
push_warning(thd, Sql_condition::SL_WARNING,
WARN_UNENCRYPTED_TABLE_IN_ENCRYPTED_DB,
ER_THD(thd, WARN_UNENCRYPTED_TABLE_IN_ENCRYPTED_DB));
}
}
}
if ((old_db_type->flags & HTON_SUPPORTS_FOREIGN_KEYS) &&
collect_and_lock_fk_tables_for_rename_table(
thd, table_list->db, table_list->table_name, table_def,
alter_ctx->new_db, alter_ctx->new_alias, old_db_type,
&fk_invalidator)) {
return true;
}
if (lock_check_constraint_names_for_rename(
thd, table_list->db, table_list->table_name, table_def,
alter_ctx->new_db, alter_ctx->new_alias))
return true;
close_all_tables_for_name(thd, table->s, false, nullptr);
/*
Orphan non-self-referencing foreign keys may become non-orphan/adopted
self-referencing foreign keys. Check that table has compatible referenced
column and parent key for such foreign key. Also, update
DD.UNIQUE_CONSTRAINT_NAME.
*/
if ((old_db_type->flags & HTON_SUPPORTS_FOREIGN_KEYS) &&
adjust_adopted_self_ref_fk_for_simple_rename_table(
thd, table_list->db, table_list->table_name, alter_ctx->new_db,
alter_ctx->new_alias, old_db_type))
error = -1;
if (!error) {
if (mysql_rename_table(thd, old_db_type, alter_ctx->db,
alter_ctx->table_name, alter_ctx->db,
alter_ctx->table_name, new_schema,
alter_ctx->new_db, alter_ctx->new_alias,
(atomic_ddl ? NO_DD_COMMIT : 0)))
error = -1;
else if (old_db_type->flags & HTON_SUPPORTS_FOREIGN_KEYS) {
/*
We don't have SEs which support FKs and don't support atomic DDL.
If we ever to support such engines we need to decide how to handle
errors in the below code for them.
*/
assert(atomic_ddl);
if (adjust_fks_for_rename_table(
thd, table_list->db, table_list->table_name, alter_ctx->new_db,
alter_ctx->new_alias, old_db_type))
error = -1;
}
}
}
if (!error) {
error =
write_bin_log(thd, true, thd->query().str, thd->query().length,
atomic_ddl && (keys_onoff != Alter_info::LEAVE_AS_IS ||
alter_ctx->is_table_renamed()));
// Update referencing views metadata.
if (!error) {
Uncommitted_tables_guard uncommitted_tables(thd);
error = update_referencing_views_metadata(
thd, table_list, alter_ctx->new_db, alter_ctx->new_alias, !atomic_ddl,
&uncommitted_tables);
if (alter_ctx->is_table_renamed()) {
uncommitted_tables.add_table(table_list);
tdc_remove_table(thd, TDC_RT_REMOVE_ALL, alter_ctx->new_db,
alter_ctx->new_name, false);
}
}
/*
Commit changes to data-dictionary, SE and binary log if it was not done
earlier. We need to do this before releasing/downgrading MDL.
*/
if (!error && atomic_ddl)
error = (trans_commit_stmt(thd) || trans_commit_implicit(thd));
if (!error) fk_invalidator.invalidate(thd);
}
if (error) {
/*
We need rollback possible changes to data-dictionary before releasing
or downgrading metadata lock.
Full rollback will synchronize state of data-dictionary in
cache and on disk. Also it is needed in case we have
THD::transaction_rollback_request.
*/
trans_rollback_stmt(thd);
trans_rollback(thd);
}
if (atomic_ddl && old_db_type->post_ddl) old_db_type->post_ddl(thd);
if (!error) {
if (alter_ctx->is_table_renamed())
thd->locked_tables_list.rename_locked_table(
table_list, alter_ctx->new_db, alter_ctx->new_name,
alter_ctx->target_mdl_request.ticket);
} else {
if (atomic_ddl) {
/*
Engines that support atomic DDL restore status-quo on error.
So we can safely try to reopen table under old name.
*/
} else {
/*
For engines which don't support atomic DDL we simply close
the table and later downgrade/release metadata lock, as we
don't track at which step error has occurred exactly.
Since such engines do not support FKs downgrading/releasing
the metadata locks should not cause problems with violating
FK invariants for LOCK TABLES. For the same reason, the below
call won't unlink any parent tables which might have been
closed by FK invalidator.
*/
assert(!(old_db_type->flags & HTON_SUPPORTS_FOREIGN_KEYS));
thd->locked_tables_list.unlink_all_closed_tables(thd, nullptr, 0);
}
}
bool reopen_error = thd->locked_tables_list.reopen_tables(thd);
if (!error && !reopen_error) my_ok(thd);
if ((thd->locked_tables_mode == LTM_LOCK_TABLES ||
thd->locked_tables_mode == LTM_PRELOCKED_UNDER_LOCK_TABLES)) {
/*
Under LOCK TABLES we should adjust meta-data locks before finishing
statement. Otherwise we can rely on them being released
along with the implicit commit.
*/
if (!error && alter_ctx->is_table_renamed()) {
/*
Note that we ignore reopen_error value here as not keeping target
metadata locks in this case can lead to breaking foreign key
invariants for LOCK TABLES.
*/
thd->mdl_context.release_all_locks_for_name(mdl_ticket);
thd->mdl_context.set_lock_duration(alter_ctx->target_mdl_request.ticket,
MDL_EXPLICIT);
alter_ctx->target_mdl_request.ticket->downgrade_lock(
MDL_SHARED_NO_READ_WRITE);
if (alter_ctx->is_database_changed())
thd->mdl_context.set_lock_duration(
alter_ctx->target_db_mdl_request.ticket, MDL_EXPLICIT);
} else
mdl_ticket->downgrade_lock(MDL_SHARED_NO_READ_WRITE);
}
return error != 0 || reopen_error;
}
/**
Check if we are changing the SRID specification on a geometry column that
has a spatial index. If that is the case, reject the change since allowing
geometries with different SRIDs in a spatial index will make the index
useless.
@param alter_info Structure describing the changes to be carried out.
@retval true if all of the geometry columns can be altered/changed as
requested
@retval false if the change is considered invalid
*/
static bool is_alter_geometry_column_valid(Alter_info *alter_info) {
Create_field *create_field;
List_iterator<Create_field> list_it(alter_info->create_list);
while ((create_field = list_it++)) {
if (create_field->change != nullptr &&
create_field->sql_type == MYSQL_TYPE_GEOMETRY &&
create_field->field->type() == MYSQL_TYPE_GEOMETRY) {
const Field_geom *geom_field =
down_cast<const Field_geom *>(create_field->field);
const TABLE_SHARE *share = geom_field->table->s;
if (geom_field->get_srid() != create_field->m_srid) {
/*
Check if there is a spatial index on this column. If that is the
case, reject the change.
*/
for (uint i = 0; i < share->keys; ++i) {
if (geom_field->key_start.is_set(i) &&
share->key_info[i].flags & HA_SPATIAL) {
my_error(ER_CANNOT_ALTER_SRID_DUE_TO_INDEX, MYF(0),
geom_field->field_name);
return false;
}
}
}
}
}
return true;
}
/**
Add MDL requests for exclusive lock on names of the foreign keys to
be dropped by ALTER TABLE operation to the lock requests list.
@param thd Thread context.
@param db Table's database before ALTER TABLE
operation.
@param alter_info Alter_info object with the list of FKs
to be dropped.
@param table_def dd::Table describing the table before
ALTER operation.
@param[in,out] mdl_requests List to which MDL requests are to be added.
@retval operation outcome, false if no error.
*/
static bool collect_fk_names_for_dropped_fks(THD *thd, const char *db,
const Alter_info *alter_info,
const dd::Table *table_def,
MDL_request_list *mdl_requests) {
for (const Alter_drop *drop : alter_info->drop_list) {
if (drop->type == Alter_drop::FOREIGN_KEY) {
for (const dd::Foreign_key *fk : table_def->foreign_keys()) {
if (my_strcasecmp(system_charset_info, drop->name,
fk->name().c_str()) == 0) {
/*
Since foreign key names are case-insensitive we need to lowercase
them before passing to MDL subsystem.
*/
char fk_name[NAME_LEN + 1];
strmake(fk_name, fk->name().c_str(), NAME_LEN);
my_casedn_str(system_charset_info, fk_name);
MDL_request *mdl_request = new (thd->mem_root) MDL_request;
if (mdl_request == nullptr) return true;
MDL_REQUEST_INIT(mdl_request, MDL_key::FOREIGN_KEY, db, fk_name,
MDL_EXCLUSIVE, MDL_STATEMENT);
mdl_requests->push_front(mdl_request);
break;
}
}
}
}
return false;
}
/**
This function will check if we are dropping a functional index. In that
case, the function will add any related hidden generated columns to the drop
list as well.
@param thd Thread handler
@param alter_info The changes to be carried out
@param table_list The current table reference
@retval true on error (my_error is already called)
@retval false on success
*/
static bool handle_drop_functional_index(THD *thd, Alter_info *alter_info,
Table_ref *table_list) {
// Check if we are dropping a functional index. In that case, we need to drop
// the source column as well.
for (const Alter_drop *drop : alter_info->drop_list) {
if (drop->type == Alter_drop::KEY) {
for (uint j = 0; j < table_list->table->s->keys; j++) {
const KEY &key_info = table_list->table->s->key_info[j];
if (my_strcasecmp(system_charset_info, key_info.name, drop->name) ==
0) {
for (uint k = 0; k < key_info.user_defined_key_parts; ++k) {
const KEY_PART_INFO &key_part = key_info.key_part[k];
if (key_part.field->is_field_for_functional_index()) {
// Add column to drop list
Alter_drop *column_drop = new (thd->mem_root)
Alter_drop(Alter_drop::COLUMN, key_part.field->field_name);
alter_info->drop_list.push_back(column_drop);
alter_info->flags |= Alter_info::ALTER_DROP_COLUMN;
}
}
}
}
} else if (drop->type == Alter_drop::COLUMN) {
for (uint j = 0; j < table_list->table->s->fields; j++) {
Field *field = table_list->table->s->field[j];
if (my_strcasecmp(system_charset_info, field->field_name, drop->name) ==
0 &&
field->is_field_for_functional_index()) {
my_error(ER_CANNOT_DROP_COLUMN_FUNCTIONAL_INDEX, MYF(0),
field->field_name);
return true;
}
}
}
}
return false;
}
/**
This function will check if we are renaming a functional index. In that case,
the function will add a "change column" operation to the create list that
renames any affected hidden generated column(s). The reason is that the hidden
generated column name is generated by MD5(key name + key part number), so a
change in the index name will change the name of the column.
@param thd thread handler
@param alter_info the changes to be carried out.
@param table_list a reference to the current table
@retval true OOM
@retval false success
*/
static bool handle_rename_functional_index(THD *thd, Alter_info *alter_info,
Table_ref *table_list) {
assert(alter_info->flags & Alter_info::ALTER_RENAME_INDEX);
for (const Alter_rename_key *alter_rename_key :
alter_info->alter_rename_key_list) {
// Find the matching existing index
for (uint j = 0; j < table_list->table->s->keys; ++j) {
const KEY &key = table_list->table->s->key_info[j];
if (my_strcasecmp(system_charset_info, key.name,
alter_rename_key->old_name) == 0) {
for (uint k = 0; k < key.actual_key_parts; ++k) {
const KEY_PART_INFO &key_part = key.key_part[k];
if (key_part.field->is_field_for_functional_index()) {
// Rename the field. But use the field that exists in the table
// object. In particular, the field object in KEY_PART_INFO does
// not have the generated column expression.
for (uint l = 0; l < table_list->table->s->fields; ++l) {
Field *field = table_list->table->field[l];
if (field->field_index() == key_part.field->field_index()) {
Create_field *new_create_field =
new (thd->mem_root) Create_field(field, nullptr);
if (new_create_field == nullptr) {
return true; /* purecov: deadcode */
}
new_create_field->change = field->field_name;
new_create_field->after = nullptr;
new_create_field->field_name =
make_functional_index_column_name(
alter_rename_key->new_name, k, alter_info->create_list,
thd->mem_root);
alter_info->create_list.push_back(new_create_field);
alter_info->flags |= Alter_info::ALTER_CHANGE_COLUMN;
}
}
}
}
break;
}
}
}
return false;
}
/**
Alter table
@param thd Thread handle
@param new_db If there is a RENAME clause
@param new_name If there is a RENAME clause
@param create_info Information from the parsing phase about new
table properties.
@param table_list The table to change.
@param alter_info Lists of fields, keys to be changed, added
or dropped.
@retval true Error
@retval false Success
This is a veery long function and is everything but the kitchen sink :)
It is used to alter a table and not only by ALTER TABLE but also
CREATE|DROP INDEX are mapped on this function.
When the ALTER TABLE statement just does a RENAME or ENABLE|DISABLE KEYS,
or both, then this function short cuts its operation by renaming
the table and/or enabling/disabling the keys. In this case, the FRM is
not changed, directly by mysql_alter_table. However, if there is a
RENAME + change of a field, or an index, the short cut is not used.
See how `create_list` is used to generate the new FRM regarding the
structure of the fields. The same is done for the indices of the table.
Altering a table can be done in two ways. The table can be modified
directly using an in-place algorithm, or the changes can be done using
an intermediate temporary table (copy). In-place is the preferred
algorithm as it avoids copying table data. The storage engine
selects which algorithm to use in check_if_supported_inplace_alter()
based on information about the table changes from fill_alter_inplace_info().
*/
bool mysql_alter_table(THD *thd, const char *new_db, const char *new_name,
HA_CREATE_INFO *create_info, Table_ref *table_list,
Alter_info *alter_info) {
DBUG_TRACE;
/*
Check if we attempt to alter mysql.slow_log or
mysql.general_log table and return an error if
it is the case.
TODO: this design is obsolete and will be removed.
*/
enum_log_table_type table_kind =
query_logger.check_if_log_table(table_list, false);
if (table_kind != QUERY_LOG_NONE) {
/* Disable alter of enabled query log tables */
if (query_logger.is_log_table_enabled(table_kind)) {
my_error(ER_BAD_LOG_STATEMENT, MYF(0), "ALTER");
return true;
}
/* Disable alter of log tables to unsupported engine */
if ((create_info->used_fields & HA_CREATE_USED_ENGINE) &&
(!create_info->db_type || /* unknown engine */
!(create_info->db_type->flags & HTON_SUPPORT_LOG_TABLES))) {
my_error(ER_UNSUPORTED_LOG_ENGINE, MYF(0));
return true;
}
if (alter_info->flags & Alter_info::ALTER_PARTITION) {
my_error(ER_WRONG_USAGE, MYF(0), "PARTITION", "log table");
return true;
}
}
// Reject request to ALTER TABLE with START TRANSACTION.
if (create_info->m_transactional_ddl) {
my_error(ER_NOT_ALLOWED_WITH_START_TRANSACTION, MYF(0),
"with ALTER TABLE command.");
return true;
}
if (alter_info->with_validation != Alter_info::ALTER_VALIDATION_DEFAULT &&
!(alter_info->flags &
(Alter_info::ALTER_ADD_COLUMN | Alter_info::ALTER_CHANGE_COLUMN))) {
my_error(ER_WRONG_USAGE, MYF(0), "ALTER", "WITH VALIDATION");
return true;
}
if ((alter_info->flags & Alter_info::ALTER_ADD_COLUMN) ==
Alter_info::ALTER_ADD_COLUMN) {
for (auto create_field : alter_info->create_list) {
if (create_field.m_default_val_expr) {
// ALTER TABLE .. DEFAULT (NDF function) should be rejected for mixed or
// row binlog_format. For statement binlog_format it should be allowed
// to continue and warning should be logged and/or pushed to the client
if ((thd->variables.option_bits & OPTION_BIN_LOG) &&
thd->lex->is_stmt_unsafe(
Query_tables_list::BINLOG_STMT_UNSAFE_SYSTEM_FUNCTION)) {
if (thd->variables.binlog_format == BINLOG_FORMAT_STMT) {
LogErr(WARNING_LEVEL, ER_SERVER_BINLOG_UNSAFE_SYSTEM_FUNCTION,
"ALTER TABLE .. DEFAULT (NDF function)");
push_warning(thd, Sql_condition::SL_WARNING,
ER_BINLOG_UNSAFE_SYSTEM_FUNCTION,
ER_THD(thd, ER_BINLOG_UNSAFE_SYSTEM_FUNCTION));
break;
} else {
my_error(ER_BINLOG_UNSAFE_SYSTEM_FUNCTION, MYF(0));
return true;
}
}
}
}
}
// LOCK clause doesn't make any sense for ALGORITHM=INSTANT.
if (alter_info->requested_algorithm ==
Alter_info::ALTER_TABLE_ALGORITHM_INSTANT &&
alter_info->requested_lock != Alter_info::ALTER_TABLE_LOCK_DEFAULT) {
my_error(ER_WRONG_USAGE, MYF(0), "ALGORITHM=INSTANT",
"LOCK=NONE/SHARED/EXCLUSIVE");
return true;
}
THD_STAGE_INFO(thd, stage_init);
// Reject invalid usage of the 'mysql' tablespace.
if (dd::invalid_tablespace_usage(thd, table_list->db, table_list->table_name,
create_info))
return true;
/*
Assign target tablespace name to enable locking in lock_table_names().
Reject invalid name lengths. Names will be validated after the table is
opened and the SE (needed for SE specific validation) is identified.
*/
if (create_info->tablespace) {
if (validate_tablespace_name_length(create_info->tablespace)) return true;
if (lex_string_strmake(thd->mem_root, &table_list->target_tablespace_name,
create_info->tablespace,
strlen(create_info->tablespace))) {
my_error(ER_OUT_OF_RESOURCES, MYF(ME_FATALERROR));
return true;
}
}
/* Validate that AUTOEXTEND_SIZE option is not specified for
temporary tables */
if (is_temporary_table(table_list)) {
if (create_info->m_implicit_tablespace_autoextend_size > 0) {
my_error(ER_CANNOT_USE_AUTOEXTEND_SIZE_CLAUSE, MYF(0), "temporary");
return true;
}
}
/*
Reject invalid tablespace name lengths specified for partitions.
Names will be validated after the table has been opened.
*/
if (validate_partition_tablespace_name_lengths(thd->lex->part_info))
return true;
/*
Assign the partition info, so that the locks on tablespaces
assigned for any new partitions added would be acquired during
open_table.
*/
thd->work_part_info = thd->lex->part_info;
/*
Code below can handle only base tables so ensure that we won't open a view.
Note that RENAME TABLE the only ALTER clause which is supported for views
has been already processed.
*/
table_list->required_type = dd::enum_table_type::BASE_TABLE;
/*
If we are about to ALTER non-temporary table we need to get permission
from/notify interested storage engines.
*/
Table_ddl_hton_notification_guard notification_guard{
thd, &table_list->mdl_request.key, HA_ALTER_DDL};
if (!is_temporary_table(table_list) && notification_guard.notify())
return true;
Alter_table_prelocking_strategy alter_prelocking_strategy;
DEBUG_SYNC(thd, "alter_table_before_open_tables");
uint tables_opened;
bool error = open_tables(thd, &table_list, &tables_opened, 0,
&alter_prelocking_strategy);
DEBUG_SYNC(thd, "alter_opened_table");
if (error) return true;
// If we are removing a functional index, add any related hidden generated
// columns to the drop list as well.
if (handle_drop_functional_index(thd, alter_info, table_list)) {
return true;
}
// If we are renaming a functional index, rename any related hidden generated
// columns as well.
if (alter_info->flags & Alter_info::ALTER_RENAME_INDEX) {
if (handle_rename_functional_index(thd, alter_info, table_list)) {
return true; /* purecov: deadcode */
}
}
// Check tablespace name validity for the relevant engine.
{
// If there is no target handlerton, use the current.
const handlerton *target_handlerton = create_info->db_type;
if (target_handlerton == nullptr)
target_handlerton = table_list->table->file->ht;
/*
Reject invalid tablespace names for the relevant engine, if the ALTER
statement changes either tablespace or engine. We do this after the table
has been opened because we need the handlerton and tablespace information.
No need to validate if neither engine nor tablespace is changed, then the
validation was done when the table was created.
*/
if (create_info->tablespace || create_info->db_type) {
// If there is no target table level tablespace, use the current.
const char *target_tablespace = create_info->tablespace;
if (target_tablespace == nullptr)
target_tablespace = table_list->table->s->tablespace;
// Check the tablespace/engine combination.
assert(target_handlerton);
if (target_tablespace != nullptr &&
validate_tablespace_name(TS_CMD_NOT_DEFINED, target_tablespace,
target_handlerton))
return true;
}
// Reject invalid tablespace names specified for partitions.
if (validate_partition_tablespace_names(thd->lex->part_info,
target_handlerton))
return true;
}
if (validate_secondary_engine_option(thd, *alter_info, *create_info,
*table_list->table))
return true;
if (lock_trigger_names(thd, table_list)) return true;
/*
If we're in LOCK TABLE mode, we must lock the target tablespace name
as well as the currently used tablesapces (since these may have been
introduced by a previous ALTER while already in LOCK TABLE mode).
*/
if (thd->locked_tables_mode &&
get_and_lock_tablespace_names(thd, table_list, nullptr,
thd->variables.lock_wait_timeout, MYF(0))) {
return true;
}
if (table_list->table->s->db_type() != create_info->db_type &&
(alter_info->flags & Alter_info::ALTER_OPTIONS) &&
(create_info->used_fields & HA_CREATE_USED_ENGINE)) {
handlerton *actual_hton = get_viable_handlerton_for_alter(
thd, *create_info, table_list->table->s->db_type());
if (actual_hton == nullptr) return true;
create_info->db_type = actual_hton;
}
const handlerton *hton = create_info->db_type;
if (hton == nullptr) {
hton = table_list->table->s->db_type();
}
assert(hton != nullptr);
if ((alter_info->flags & Alter_info::ANY_ENGINE_ATTRIBUTE) != 0 &&
((hton->flags & HTON_SUPPORTS_ENGINE_ATTRIBUTE) == 0 &&
DBUG_EVALUATE_IF("simulate_engine_attribute_support", false, true))) {
my_error(ER_ENGINE_ATTRIBUTE_NOT_SUPPORTED, MYF(0),
ha_resolve_storage_engine_name(hton));
return true;
}
TABLE *table = table_list->table;
table->use_all_columns();
MDL_ticket *mdl_ticket = table->mdl_ticket;
/*
Prohibit changing of the UNION list of a non-temporary MERGE table
under LOCK tables. It would be quite difficult to reuse a shrunk
set of tables from the old table or to open a new TABLE object for
an extended list and verify that they belong to locked tables.
*/
if ((thd->locked_tables_mode == LTM_LOCK_TABLES ||
thd->locked_tables_mode == LTM_PRELOCKED_UNDER_LOCK_TABLES) &&
(create_info->used_fields & HA_CREATE_USED_UNION) &&
(table->s->tmp_table == NO_TMP_TABLE)) {
my_error(ER_LOCK_OR_ACTIVE_TRANSACTION, MYF(0));
return true;
}
Alter_table_ctx alter_ctx(thd, table_list, tables_opened, new_db, new_name);
/*
Acquire and keep schema locks until commit time, so the DD layer can
safely assert that we have proper MDL on objects stored in the DD.
*/
dd::Schema_MDL_locker mdl_locker_1(thd), mdl_locker_2(thd);
const dd::Schema *schema = nullptr;
const dd::Schema *new_schema = nullptr;
const dd::Table *old_table_def = nullptr;
/*
This releaser allows us to keep uncommitted DD objects cached
in the Dictionary_client until commit time.
*/
dd::cache::Dictionary_client::Auto_releaser releaser(thd->dd_client());
if (mdl_locker_1.ensure_locked(alter_ctx.db) ||
mdl_locker_2.ensure_locked(alter_ctx.new_db) ||
thd->dd_client()->acquire(alter_ctx.db, &schema) ||
thd->dd_client()->acquire(alter_ctx.new_db, &new_schema))
return true;
if ((table->s->tmp_table == NO_TMP_TABLE) &&
thd->dd_client()->acquire(alter_ctx.db, alter_ctx.table_name,
&old_table_def))
return true;
// If this is a temporary table, the schema might not exist even
// if we have successfully opened the table
if (schema == nullptr) {
assert(table->s->tmp_table);
my_error(ER_BAD_DB_ERROR, MYF(0), alter_ctx.db);
return true;
}
assert((table->s->tmp_table != NO_TMP_TABLE) || old_table_def != nullptr);
if (new_schema == nullptr) {
my_error(ER_BAD_DB_ERROR, MYF(0), alter_ctx.new_db);
return true;
}
/*
Add old and new (if any) databases to the list of accessed databases
for this statement. Needed for MTS.
*/
thd->add_to_binlog_accessed_dbs(alter_ctx.db);
if (alter_ctx.is_database_changed())
thd->add_to_binlog_accessed_dbs(alter_ctx.new_db);
// Ensure that triggers are in the same schema as their subject table.
if (alter_ctx.is_database_changed() && old_table_def != nullptr &&
old_table_def->has_trigger()) {
my_error(ER_TRG_IN_WRONG_SCHEMA, MYF(0));
return true;
}
/* Check that we are not trying to rename to an existing table */
if (alter_ctx.is_table_renamed()) {
if (table->s->tmp_table != NO_TMP_TABLE) {
if (find_temporary_table(thd, alter_ctx.new_db, alter_ctx.new_name)) {
my_error(ER_TABLE_EXISTS_ERROR, MYF(0), alter_ctx.new_alias);
return true;
}
} else {
MDL_request_list mdl_requests;
mdl_requests.push_front(&alter_ctx.target_mdl_request);
/*
If we are moving the table to a different database, we also
need IX lock on the database name so that the target database
is protected by MDL while the table is moved.
*/
if (alter_ctx.is_database_changed())
mdl_requests.push_front(&alter_ctx.target_db_mdl_request);
/*
Global intention exclusive lock must have been already acquired when
table to be altered was open, so there is no need to do it here.
*/
assert(thd->mdl_context.owns_equal_or_stronger_lock(
MDL_key::GLOBAL, "", "", MDL_INTENTION_EXCLUSIVE));
if (thd->mdl_context.acquire_locks(&mdl_requests,
thd->variables.lock_wait_timeout))
return true;
DEBUG_SYNC(thd, "locked_table_name");
/*
Table maybe does not exist, but we got an exclusive lock
on the name, now we can safely try to find out for sure.
*/
const dd::Abstract_table *at = nullptr;
if (thd->dd_client()->acquire(alter_ctx.new_db, alter_ctx.new_name, &at))
return true;
if (at != nullptr) {
/* Table will be closed in do_command() */
my_error(ER_TABLE_EXISTS_ERROR, MYF(0), alter_ctx.new_alias);
return true;
}
}
}
if (!create_info->db_type) {
if (table->part_info && create_info->used_fields & HA_CREATE_USED_ENGINE) {
/*
This case happens when the user specified
ENGINE = x where x is a non-existing storage engine
We set create_info->db_type to default_engine_type
to ensure we don't change underlying engine type
due to a erroneously given engine name.
*/
create_info->db_type = table->part_info->default_engine_type;
} else
create_info->db_type = table->s->db_type();
}
if (check_engine(alter_ctx.new_db, alter_ctx.new_name, create_info))
return true;
/*
Do not allow change of storage engine if table participates in a foreign
key. Even in cases when both source and target storage engines support
foreign keys the fine details of what is supported might differ.
*/
if (create_info->db_type != table->s->db_type() && old_table_def != nullptr &&
(old_table_def->foreign_keys().size() ||
old_table_def->foreign_key_parents().size())) {
my_error(ER_FK_CANNOT_CHANGE_ENGINE, MYF(0));
return true;
}
/*
If foreign key is added then check permission to access parent table.
In function "check_fk_parent_table_access", create_info->db_type is used
to identify whether engine supports FK constraint or not. Since
create_info->db_type is set here, check to parent table access is delayed
till this point for the alter operation.
*/
if ((alter_info->flags & Alter_info::ADD_FOREIGN_KEY) &&
check_fk_parent_table_access(thd, create_info, alter_info))
return true;
Foreign_key_parents_invalidator fk_invalidator;
if (table->s->tmp_table == NO_TMP_TABLE) {
MDL_request_list mdl_requests;
if (collect_fk_parents_for_new_fks(
thd, table_list->db, table_list->table_name, alter_info,
MDL_SHARED_UPGRADABLE, nullptr, &mdl_requests, nullptr))
return true;
/*
Acquire SU locks on parent and child tables so we can access
their definition while checking if this ALTER TABLE will break
any FKs involving them.
TODO: Refine set of ALTER TABLE commands for which we do this.
This is obviously necessary for ADD/DROP KEY and COLUMN
modifications. But are there any other operations which
might affect indexes somehow?
*/
if (!is_simple_rename_or_index_change(alter_info)) {
if (collect_fk_parents_for_all_fks(thd, old_table_def, nullptr,
MDL_SHARED_UPGRADABLE, &mdl_requests,
nullptr))
return true;
if (create_info->db_type != table->s->db_type()) {
/*
By changing table's storage engine we might be introducing parent
table for previously orphan foreign keys in the new SE. We need
to lock child tables of such orphan foreign keys. OTOH it is safe
to assume that if SE is changed table can't be parent in any
foreign keys in old SE.
Note that here and in other similar places we assume that ALTER
TABLE which combines change of SE and renaming of table is executed
by changing SE first and then performing rename (this is closer to
ALTER TABLE real implementation). Because of this such ALTER TABLEs
need to pick up orphan foreign keys associated with old table names
as well. Thus we use old table name to get list of orphans.
*/
assert(old_table_def->foreign_key_parents().size() == 0);
if (collect_fk_children(thd, table_list->db, table_list->table_name,
create_info->db_type, MDL_SHARED_UPGRADABLE,
&mdl_requests))
return true;
} else {
if (collect_fk_children(thd, old_table_def, MDL_SHARED_UPGRADABLE,
&mdl_requests))
return true;
}
if (alter_ctx.is_table_renamed() &&
collect_fk_children(thd, alter_ctx.new_db, alter_ctx.new_alias,
create_info->db_type, MDL_SHARED_UPGRADABLE,
&mdl_requests))
return true;
}
/*
Lock names of foreign keys to be dropped.
Note that we can't lock names of foreign keys to be added yet
because database in which they will be created depends on ALTER
TABLE algorithm we are going to choose later.
*/
if (collect_fk_names_for_dropped_fks(thd, table_list->db, alter_info,
old_table_def, &mdl_requests))
return true;
/*
Under LOCK TABLES all parent tables must be locked at least in READ
mode. Otherwise, our ALTER TABLE will leave after itself child table
locked for WRITE, without corresponding parent tables locked and thus
without ability to perform FK checks when child table is modified.
*/
if (thd->locked_tables_mode == LTM_LOCK_TABLES ||
thd->locked_tables_mode == LTM_PRELOCKED_UNDER_LOCK_TABLES) {
MDL_request_list::Iterator it(mdl_requests);
MDL_request *mdl_request;
while ((mdl_request = it++) != nullptr) {
if (mdl_request->key.mdl_namespace() != MDL_key::TABLE) continue;
if (!thd->mdl_context.owns_equal_or_stronger_lock(
MDL_key::TABLE, mdl_request->key.db_name(),
mdl_request->key.name(), MDL_SHARED_READ_ONLY)) {
my_error(ER_TABLE_NOT_LOCKED, MYF(0), mdl_request->key.name());
return true;
}
}
}
if (!mdl_requests.is_empty() &&
thd->mdl_context.acquire_locks(&mdl_requests,
thd->variables.lock_wait_timeout))
return true;
DEBUG_SYNC(thd, "alter_table_after_mdl_lock_fk");
/*
If we are executing ALTER TABLE RENAME under LOCK TABLES we also need
to check that all previously orphan tables which reference new table
name through foreign keys are locked for write. Otherwise this ALTER
will leave after itself parent table locked for WRITE without child
tables locked for WRITE. This will break FK LOCK TABLES invariants if
some of previously orphan FKs have referential actions which update
child table.
The same should be done when we are going to add parent table to
previously orphan foreign keys by changing table storage engine.
In theory, we can reduce chance of MDL deadlocks by also checking at
this stage that all child and parent tables for FKs in which this
table participates are locked for WRITE (as we will have to acquire
to exclusive MDLs on these tables later). But this is, probably, too
severe restriction since many 3rd-party online ALTER tools use ALTER
TABLE RENAME under LOCK TABLES and are unaware of it.
*/
if (thd->locked_tables_mode == LTM_LOCK_TABLES ||
thd->locked_tables_mode == LTM_PRELOCKED_UNDER_LOCK_TABLES) {
MDL_request_list orphans_mdl_requests;
if (create_info->db_type != table->s->db_type()) {
assert(old_table_def->foreign_key_parents().size() == 0);
if (collect_fk_children(thd, table_list->db, table_list->table_name,
create_info->db_type, MDL_EXCLUSIVE,
&orphans_mdl_requests))
return true;
}
if (alter_ctx.is_table_renamed() &&
collect_fk_children(thd, alter_ctx.new_db, alter_ctx.new_alias,
create_info->db_type, MDL_EXCLUSIVE,
&orphans_mdl_requests))
return true;
if (!orphans_mdl_requests.is_empty()) {
MDL_request_list::Iterator it(orphans_mdl_requests);
MDL_request *mdl_request;
while ((mdl_request = it++) != nullptr) {
if (mdl_request->key.mdl_namespace() != MDL_key::TABLE) continue;
if (!thd->mdl_context.owns_equal_or_stronger_lock(
MDL_key::TABLE, mdl_request->key.db_name(),
mdl_request->key.name(), MDL_SHARED_NO_READ_WRITE)) {
my_error(ER_TABLE_NOT_LOCKED_FOR_WRITE, MYF(0),
mdl_request->key.name());
return true;
}
}
}
}
}
/*
If this is an ALTER TABLE and no explicit row type specified reuse
the table's row type.
Note : this is the same as if the row type was specified explicitly.
*/
if (create_info->row_type == ROW_TYPE_NOT_USED) {
/* ALTER TABLE without explicit row type */
create_info->row_type = table->s->row_type;
} else {
/* ALTER TABLE with specific row type */
create_info->used_fields |= HA_CREATE_USED_ROW_FORMAT;
}
DBUG_PRINT("info", ("old type: %s new type: %s",
ha_resolve_storage_engine_name(table->s->db_type()),
ha_resolve_storage_engine_name(create_info->db_type)));
if (ha_check_storage_engine_flag(table->s->db_type(),
HTON_ALTER_NOT_SUPPORTED) ||
ha_check_storage_engine_flag(create_info->db_type,
HTON_ALTER_NOT_SUPPORTED)) {
DBUG_PRINT("info", ("doesn't support alter"));
my_error(ER_ILLEGAL_HA, MYF(0), table_list->table_name);
return true;
}
THD_STAGE_INFO(thd, stage_setup);
if (is_simple_rename_or_index_change(alter_info) && !table->s->tmp_table) {
// This requires X-lock, no other lock levels supported.
if (alter_info->requested_lock != Alter_info::ALTER_TABLE_LOCK_DEFAULT &&
alter_info->requested_lock != Alter_info::ALTER_TABLE_LOCK_EXCLUSIVE) {
my_error(ER_ALTER_OPERATION_NOT_SUPPORTED, MYF(0), "LOCK=NONE/SHARED",
"LOCK=EXCLUSIVE");
return true;
}
return simple_rename_or_index_change(thd, *new_schema, table_list,
alter_info->keys_onoff, &alter_ctx);
}
/* We have to do full alter table. */
bool partition_changed = false;
partition_info *new_part_info = nullptr;
{
if (prep_alter_part_table(thd, table, alter_info, create_info, &alter_ctx,
&partition_changed, &new_part_info)) {
return true;
}
}
/*
Store all columns that are going to be dropped, since we need this list
when removing column statistics later. The reason we need to store it here,
is that 'mysql_prepare_alter_table' may remove some of the columns from
the drop_list.
*/
histograms::columns_set columns;
for (const auto column : alter_info->drop_list) {
if (column->type == Alter_drop::COLUMN) columns.emplace(column->name);
}
const Alter_column *alter = nullptr;
uint i = 0;
while (i < alter_info->alter_list.size()) {
alter = alter_info->alter_list[i];
if (alter->change_type() == Alter_column::Type::RENAME_COLUMN)
columns.emplace(alter->name);
i++;
}
Create_field *create_field;
List_iterator<Create_field> list_it(alter_info->create_list);
while ((create_field = list_it++)) {
if (create_field->change != nullptr) columns.emplace(create_field->change);
}
/*
Type of a constraint marked for DROP with DROP CONSTRAINT clause is unknown.
Resolve type of a constraint by name.
*/
Drop_constraint_type_resolver drop_constraint_type_resolver(alter_info);
if (drop_constraint_type_resolver.is_type_resolution_needed() &&
(drop_constraint_type_resolver.resolve_constraints_type(thd, table,
old_table_def)))
return true;
/*
Type of a constraint marked for ALTER with ALTER CONSTRAINT clause is
unknown. Resolve type of a constraint by name.
*/
Enforce_constraint_type_resolver enforce_constraint_type_resolver(alter_info);
if (enforce_constraint_type_resolver.is_type_resolution_needed() &&
(enforce_constraint_type_resolver.resolve_constraints_type(
thd, table, old_table_def)))
return true;
// Prepare check constraints for alter table operation.
if (prepare_check_constraints_for_alter(thd, table, alter_info, &alter_ctx))
return true;
if (mysql_prepare_alter_table(thd, old_table_def, table, create_info,
alter_info, &alter_ctx)) {
return true;
}
// Check restrictions on ALTER TABLE operations that affects GIPK and PK.
if (check_primary_key_alter_restrictions(thd, create_info->db_type,
alter_info, table))
return true;
/*
Check if we are changing the SRID specification on a geometry column that
has a spatial index. If that is the case, reject the change since allowing
geometries with different SRIDs in a spatial index will make the index
useless.
*/
if (!is_alter_geometry_column_valid(alter_info)) return true;
if (set_table_default_charset(thd, create_info, *schema)) return true;
/*
Use copy algorithm if:
- old_alter_table system variable is set without in-place requested using
the ALGORITHM clause.
- Or if in-place is impossible for given operation.
- Changes to partitioning needs to be handled using table copying
algorithm unless the engine supports partitioning changes using
in-place API (because it supports auto-partitioning or simply
can do partitioning changes using in-place using mark-up in
partition_info object).
*/
if ((thd->variables.old_alter_table &&
alter_info->requested_algorithm !=
Alter_info::ALTER_TABLE_ALGORITHM_INPLACE &&
alter_info->requested_algorithm !=
Alter_info::ALTER_TABLE_ALGORITHM_INSTANT) ||
is_inplace_alter_impossible(table, create_info, alter_info) ||
(partition_changed &&
!(table->s->db_type()->partition_flags() & HA_USE_AUTO_PARTITION) &&
!new_part_info)) {
if (alter_info->requested_algorithm ==
Alter_info::ALTER_TABLE_ALGORITHM_INPLACE) {
my_error(ER_ALTER_OPERATION_NOT_SUPPORTED, MYF(0), "ALGORITHM=INPLACE",
"ALGORITHM=COPY");
return true;
}
if (alter_info->requested_algorithm ==
Alter_info::ALTER_TABLE_ALGORITHM_INSTANT) {
my_error(ER_ALTER_OPERATION_NOT_SUPPORTED, MYF(0), "ALGORITHM=INSTANT",
"ALGORITHM=COPY");
return true;
}
alter_info->requested_algorithm = Alter_info::ALTER_TABLE_ALGORITHM_COPY;
}
/*
If 'avoid_temporal_upgrade' mode is not enabled, then the
pre MySQL 5.6.4 old temporal types if present is upgraded to the
current format.
*/
mysql_mutex_lock(&LOCK_global_system_variables);
bool check_temporal_upgrade = !avoid_temporal_upgrade;
mysql_mutex_unlock(&LOCK_global_system_variables);
if (check_temporal_upgrade) {
if (upgrade_old_temporal_types(thd, alter_info)) return true;
}
/*
ALTER TABLE ... ENGINE to the same engine is a common way to
request table rebuild. Set ALTER_RECREATE flag to force table
rebuild.
*/
if (create_info->db_type == table->s->db_type() &&
create_info->used_fields & HA_CREATE_USED_ENGINE)
alter_info->flags |= Alter_info::ALTER_RECREATE;
/*
If the old table had partitions and we are doing ALTER TABLE ...
engine= <new_engine>, the new table must preserve the original
partitioning. This means that the new engine is still the
partitioning engine, not the engine specified in the parser.
This is discovered in prep_alter_part_table, which in such case
updates create_info->db_type.
It's therefore important that the assignment below is done
after prep_alter_part_table.
*/
handlerton *new_db_type = create_info->db_type;
handlerton *old_db_type = table->s->db_type();
TABLE *new_table = nullptr;
ha_rows copied = 0, deleted = 0;
/*
Handling of symlinked tables:
If no rename:
Create new data file and index file on the same disk as the
old data and index files.
Copy data.
Rename new data file over old data file and new index file over
old index file.
Symlinks are not changed.
If rename:
Create new data file and index file on the same disk as the
old data and index files. Create also symlinks to point at
the new tables.
Copy data.
At end, rename intermediate tables, and symlinks to intermediate
table, to final table name.
Remove old table and old symlinks
If rename is made to another database:
Create new tables in new database.
Copy data.
Remove old table and symlinks.
*/
char index_file[FN_REFLEN], data_file[FN_REFLEN];
if (!alter_ctx.is_database_changed()) {
if (create_info->index_file_name) {
/* Fix index_file_name to have 'tmp_name' as basename */
my_stpcpy(index_file, alter_ctx.tmp_name);
create_info->index_file_name =
fn_same(index_file, create_info->index_file_name, 1);
}
if (create_info->data_file_name) {
/* Fix data_file_name to have 'tmp_name' as basename */
my_stpcpy(data_file, alter_ctx.tmp_name);
create_info->data_file_name =
fn_same(data_file, create_info->data_file_name, 1);
}
} else {
/* Ignore symlink if db is changed. */
create_info->data_file_name = create_info->index_file_name = nullptr;
}
DEBUG_SYNC(thd, "alter_table_before_create_table_no_lock");
DBUG_EXECUTE_IF("sleep_before_create_table_no_lock", my_sleep(100000););
/*
Promote first timestamp column, when explicit_defaults_for_timestamp
is not set
*/
if (!thd->variables.explicit_defaults_for_timestamp)
promote_first_timestamp_column(&alter_info->create_list);
/*
Create .FRM for new version of table with a temporary name.
We don't log the statement, it will be logged later.
Keep information about keys in newly created table as it
will be used later to construct Alter_inplace_info object
and by fill_alter_inplace_info() call.
*/
KEY *key_info;
uint key_count;
FOREIGN_KEY *fk_key_info = nullptr;
uint fk_key_count = 0;
Alter_info::enum_enable_or_disable keys_onoff =
((alter_info->keys_onoff == Alter_info::LEAVE_AS_IS &&
table->file->indexes_are_disabled())
? Alter_info::DISABLE
: alter_info->keys_onoff);
/*
Take the X metadata lock on temporary name used for new version of
the table. This ensures that concurrent I_S queries won't try to open it.
*/
MDL_request tmp_name_mdl_request;
bool is_tmp_table = (table->s->tmp_table != NO_TMP_TABLE);
// Avoid these tables to be visible by I_S/SHOW queries.
create_info->m_hidden = !is_tmp_table;
if (!is_tmp_table) {
MDL_REQUEST_INIT(&tmp_name_mdl_request, MDL_key::TABLE, alter_ctx.new_db,
alter_ctx.tmp_name, MDL_EXCLUSIVE, MDL_STATEMENT);
if (thd->mdl_context.acquire_lock(&tmp_name_mdl_request,
thd->variables.lock_wait_timeout))
return true;
}
// Stop if we have invalid encryption clause.
if (!is_tmp_table && validate_table_encryption(thd, create_info)) return true;
/*
For temporary tables or tables in SEs supporting atomic DDL dd::Table
object describing new version of table. This object will be created in
memory in create_table_impl() and will not be put into the on-disk DD
and DD Object Cache.
We become responsible for destroying this dd::Table object (for
temporary tables until we pass its ownership to the TABLE_SHARE).
*/
std::unique_ptr<dd::Table> non_dd_table_def;
{
Disable_binlog_guard binlog_guard(thd);
/* Prevent intermediate commits to invoke commit order */
Implicit_substatement_state_guard substatement_guard(
thd, enum_implicit_substatement_guard_mode ::
DISABLE_GTID_AND_SPCO_IF_SPCO_ACTIVE);
error = create_table_impl(
thd, *new_schema, alter_ctx.new_db, alter_ctx.tmp_name,
alter_ctx.table_name, alter_ctx.get_tmp_path(), create_info, alter_info,
true, 0, true, true,
/*
If target SE supports atomic DDL do not store
new table version in on-disk DD.
It is not required to rollback statement in
case of error and allows to keep correct names
for pre-existing foreign keys in the dd::Table
object for new table version.
*/
(new_db_type->flags & HTON_SUPPORTS_ATOMIC_DDL), nullptr, &key_info,
&key_count, keys_onoff, &fk_key_info, &fk_key_count, alter_ctx.fk_info,
alter_ctx.fk_count, old_table_def,
alter_ctx.fk_max_generated_name_number, &non_dd_table_def, nullptr);
}
if (error) {
/*
Play it safe, rollback possible changes to the data-dictionary,
so failed mysql_alter_table()/mysql_recreate_table() do not
require rollback in the caller. Also do full rollback in unlikely
case we have THD::transaction_rollback_request.
*/
trans_rollback_stmt(thd);
trans_rollback(thd);
return true;
}
/*
Atomic replacement of the table is possible only if both old and new
storage engines support DDL atomicity.
*/
bool atomic_replace = (new_db_type->flags & HTON_SUPPORTS_ATOMIC_DDL) &&
(old_db_type->flags & HTON_SUPPORTS_ATOMIC_DDL);
/* Remember that we have not created table in storage engine yet. */
bool no_ha_table = true;
/* Indicates special case when we do ALTER TABLE which is really no-op. */
bool is_noop = false;
/*
Indicates special case involving non-atomic ALTER TABLE which adds
foreign keys and then fails at the late stage. Such ALTER TABLE still
requires FK parent invalidation even despite of error.
*/
bool invalidate_fk_parents_on_error = false;
dd::Encrypt_result old_er{false, false};
dd::Encrypt_result new_er{false, false};
/*
If we are ALTERing non-temporary table in SE not supporting atomic DDL
we don't have dd::Table object describing new version of table yet.
Retrieve it now.
*/
dd::Table *table_def = non_dd_table_def.get();
if (!table_def) {
if (thd->dd_client()->acquire_for_modification(
alter_ctx.new_db, alter_ctx.tmp_name, &table_def))
goto err_new_table_cleanup;
set_check_constraints_alter_mode(table_def, alter_info);
assert(table_def);
}
if (!is_tmp_table) {
// Check for usage of prefix key index in PARTITION BY KEY() function.
dd::warn_on_deprecated_prefix_key_partition(
thd, alter_ctx.db, alter_ctx.table_name, table_def, false);
}
if (remove_secondary_engine(thd, *table_list, *create_info, old_table_def))
goto err_new_table_cleanup;
// If we are changing the tablespace or the table encryption type.
if (old_table_def &&
(create_info->used_fields & HA_CREATE_USED_TABLESPACE ||
create_info->used_fields & HA_CREATE_USED_ENCRYPT ||
create_info->used_fields & HA_CREATE_USED_AUTOEXTEND_SIZE ||
alter_ctx.is_database_changed())) {
bool source_is_general_tablespace{false};
bool source_encrytion_type{false};
bool destination_is_general_tablespace{false};
bool destination_encrytion_type{false};
// Determine source tablespace type and encryption type.
old_er = dd::is_tablespace_encrypted(thd, *old_table_def,
&source_is_general_tablespace);
if (old_er.error) {
goto err_new_table_cleanup;
}
source_encrytion_type = old_er.value;
if (!source_is_general_tablespace &&
old_table_def->options().exists("encrypt_type")) {
dd::String_type et;
(void)old_table_def->options().get("encrypt_type", &et);
assert(et.empty() == false);
source_encrytion_type = is_encrypted(et);
}
// Determine destination tablespace type and encryption type.
new_er = dd::is_tablespace_encrypted(thd, *table_def,
&destination_is_general_tablespace);
if (new_er.error) {
goto err_new_table_cleanup;
}
destination_encrytion_type = new_er.value;
if (!destination_is_general_tablespace &&
table_def->options().exists("encrypt_type")) {
dd::String_type et;
(void)table_def->options().get("encrypt_type", &et);
assert(et.empty() == false);
destination_encrytion_type = is_encrypted(et);
}
/*
Disallow converting a general tablespace to a file-per-table
tablespace without a explicit ENCRYPTION clause.
*/
if (source_is_general_tablespace && source_encrytion_type == true &&
!destination_is_general_tablespace &&
!(create_info->used_fields & HA_CREATE_USED_ENCRYPT)) {
my_error(ER_TARGET_TABLESPACE_UNENCRYPTED, MYF(0));
goto err_new_table_cleanup;
}
/*
Disallow moving encrypted table (using general or file-per-table
tablespace) to a unencrypted general tablespace.
*/
if (source_encrytion_type && destination_is_general_tablespace &&
!destination_encrytion_type) {
my_error(ER_TARGET_TABLESPACE_UNENCRYPTED, MYF(0));
goto err_new_table_cleanup;
}
/*
Check table encryption privilege, if table encryption type differ
from schema encryption type.
*/
if (new_schema->default_encryption() != destination_encrytion_type) {
// Ignore privilege check and show warning if database is same and
// table encryption type is not changed.
bool show_warning = !alter_ctx.is_database_changed() &&
source_encrytion_type == destination_encrytion_type;
if (!show_warning && opt_table_encryption_privilege_check) {
if (check_table_encryption_admin_access(thd)) {
my_error(ER_CANNOT_SET_TABLE_ENCRYPTION, MYF(0));
return true;
}
} else if (new_schema->default_encryption() &&
!destination_encrytion_type) {
push_warning(thd, Sql_condition::SL_WARNING,
WARN_UNENCRYPTED_TABLE_IN_ENCRYPTED_DB,
ER_THD(thd, WARN_UNENCRYPTED_TABLE_IN_ENCRYPTED_DB));
}
}
}
if (old_table_def) {
if (is_checked_for_upgrade(*old_table_def)) {
DBUG_PRINT("admin", ("Transfering upgrade mark "
"from Table %s (%llu) to Table %s (%llu)",
old_table_def->name().c_str(), old_table_def->id(),
table_def->name().c_str(), table_def->id()));
table_def->mark_as_checked_for_upgrade();
}
}
/*
Check if new table definition is compatible with foreign keys
on other tales which reference this one. We want to do this
before starting potentially expensive main phases of COPYing
or INPLACE ALTER TABLE.
*/
if (!is_tmp_table) {
if (new_db_type != old_db_type) {
/*
By changing table's storage engine we might be introducing parent
table for previously orphan foreign keys in the new SE. We need
to lock child tables of such orphan foreign keys. OTOH it is safe
to assume that if SE is changed table can't be parent in any
foreign keys in old SE.
We assume that ALTER TABLE which combines change of SE and renaming
of table is executed by changing SE first and then performing rename
(this is closer to ALTER TABLE real implementation). So such ALTER
TABLEs need to pick up orphan foreign keys associated with old table
names as well. Thus we use old table name in the below check.
*/
assert(old_table_def->foreign_key_parents().size() == 0);
if (check_fk_children_after_parent_def_change(
thd, table_list->db, table_list->table_name, nullptr, nullptr,
new_db_type, table_def))
goto err_new_table_cleanup;
} else {
if (check_fk_children_after_parent_def_change(
thd, table_list->db, table_list->table_name, new_db_type,
old_table_def, table_def, alter_info))
goto err_new_table_cleanup;
}
if (alter_ctx.is_table_renamed() &&
check_fk_children_after_parent_def_change(
thd, alter_ctx.new_db, alter_ctx.new_alias, table_list->db,
table_list->table_name, new_db_type, table_def))
goto err_new_table_cleanup;
}
if (alter_info->requested_algorithm !=
Alter_info::ALTER_TABLE_ALGORITHM_COPY) {
Alter_inplace_info ha_alter_info(create_info, alter_info,
alter_ctx.error_if_not_empty, key_info,
key_count, thd->work_part_info);
TABLE *altered_table = nullptr;
bool use_inplace = true;
/* Fill the Alter_inplace_info structure. */
if (fill_alter_inplace_info(thd, table, &ha_alter_info))
goto err_new_table_cleanup;
DBUG_EXECUTE_IF("innodb_index_drop_count_zero", {
if (ha_alter_info.index_drop_count) {
my_error(ER_ALTER_OPERATION_NOT_SUPPORTED, MYF(0), "Index rebuild",
"Without rebuild");
return true;
}
};);
DBUG_EXECUTE_IF("innodb_index_drop_count_one", {
if (ha_alter_info.index_drop_count != 1) {
my_error(ER_ALTER_OPERATION_NOT_SUPPORTED, MYF(0), "Index change",
"Index rebuild");
return true;
}
};);
// We assume that the table is non-temporary.
assert(!table->s->tmp_table);
if (!(altered_table = open_table_uncached(
thd, alter_ctx.get_tmp_path(), alter_ctx.new_db,
alter_ctx.tmp_name, true, false, *table_def)))
goto err_new_table_cleanup;
/* Set markers for fields in TABLE object for altered table. */
update_altered_table(ha_alter_info, altered_table);
/*
Mark all columns in 'altered_table' as used to allow usage
of its record[0] buffer and Field objects during in-place
ALTER TABLE.
*/
altered_table->column_bitmaps_set_no_signal(&altered_table->s->all_set,
&altered_table->s->all_set);
set_column_static_defaults(altered_table, alter_info->create_list);
if (ha_alter_info.handler_flags == 0) {
/*
No-op ALTER, no need to call handler API functions.
If this code path is entered for an ALTER statement that
should not be a real no-op, new handler flags should be added
and fill_alter_inplace_info() adjusted.
Note that we can end up here if an ALTER statement has clauses
that cancel each other out (e.g. ADD/DROP identically index).
Also note that we ignore the LOCK clause here.
*/
close_temporary_table(thd, altered_table, true, false);
if (!(create_info->db_type->flags & HTON_SUPPORTS_ATOMIC_DDL)) {
// Delete temporary table object from data dictionary.
bool result = dd::drop_table(thd, alter_ctx.new_db, alter_ctx.tmp_name,
*table_def);
(void)trans_intermediate_ddl_commit(thd, result);
}
is_noop = true;
goto end_inplace_noop;
}
// Ask storage engine whether to use copy or in-place
enum_alter_inplace_result inplace_supported =
table->file->check_if_supported_inplace_alter(altered_table,
&ha_alter_info);
// If INSTANT was requested but it is not supported, report error.
if (alter_info->requested_algorithm ==
Alter_info::ALTER_TABLE_ALGORITHM_INSTANT &&
inplace_supported != HA_ALTER_INPLACE_INSTANT &&
inplace_supported != HA_ALTER_ERROR) {
ha_alter_info.report_unsupported_error("ALGORITHM=INSTANT",
"ALGORITHM=COPY/INPLACE");
close_temporary_table(thd, altered_table, true, false);
goto err_new_table_cleanup;
}
switch (inplace_supported) {
case HA_ALTER_INPLACE_EXCLUSIVE_LOCK:
// If SHARED lock and no particular algorithm was requested, use COPY.
if (alter_info->requested_lock == Alter_info::ALTER_TABLE_LOCK_SHARED &&
alter_info->requested_algorithm ==
Alter_info::ALTER_TABLE_ALGORITHM_DEFAULT) {
use_inplace = false;
}
// Otherwise, if weaker lock was requested, report error.
else if (alter_info->requested_lock ==
Alter_info::ALTER_TABLE_LOCK_NONE ||
alter_info->requested_lock ==
Alter_info::ALTER_TABLE_LOCK_SHARED) {
ha_alter_info.report_unsupported_error("LOCK=NONE/SHARED",
"LOCK=EXCLUSIVE");
close_temporary_table(thd, altered_table, true, false);
goto err_new_table_cleanup;
}
break;
case HA_ALTER_INPLACE_SHARED_LOCK_AFTER_PREPARE:
case HA_ALTER_INPLACE_SHARED_LOCK:
// If weaker lock was requested, report error.
if (alter_info->requested_lock == Alter_info::ALTER_TABLE_LOCK_NONE) {
ha_alter_info.report_unsupported_error("LOCK=NONE", "LOCK=SHARED");
close_temporary_table(thd, altered_table, true, false);
goto err_new_table_cleanup;
}
break;
case HA_ALTER_INPLACE_NO_LOCK_AFTER_PREPARE:
case HA_ALTER_INPLACE_NO_LOCK:
case HA_ALTER_INPLACE_INSTANT:
/*
Note that any instant operation is also in fact in-place operation.
It is totally safe to execute operation using instant algorithm if it
has no drawbacks as compared to in-place algorithm even if user
explicitly asked for ALGORITHM=INPLACE. Doing so, also allows to
keep code in engines which support only limited subset of in-place
ALTER TABLE operations as instant metadata only changes simple.
If instant algorithm has some downsides to in-place algorithm and user
explicitly asks for ALGORITHM=INPLACE it is responsibility of storage
engine to fallback to in-place algorithm execution by returning
HA_ALTER_INPLACE_NO_LOCK or HA_ALTER_INPLACE_NO_LOCK_AFTER_PREPARE.
*/
break;
case HA_ALTER_INPLACE_NOT_SUPPORTED:
// If INPLACE was requested, report error.
if (alter_info->requested_algorithm ==
Alter_info::ALTER_TABLE_ALGORITHM_INPLACE) {
ha_alter_info.report_unsupported_error("ALGORITHM=INPLACE",
"ALGORITHM=COPY");
close_temporary_table(thd, altered_table, true, false);
goto err_new_table_cleanup;
}
// COPY with LOCK=NONE is not supported, no point in trying.
if (alter_info->requested_lock == Alter_info::ALTER_TABLE_LOCK_NONE) {
ha_alter_info.report_unsupported_error("LOCK=NONE", "LOCK=SHARED");
close_temporary_table(thd, altered_table, true, false);
goto err_new_table_cleanup;
}
// Otherwise use COPY
use_inplace = false;
break;
case HA_ALTER_ERROR:
default:
close_temporary_table(thd, altered_table, true, false);
goto err_new_table_cleanup;
}
if (use_inplace) {
if (mysql_inplace_alter_table(thd, *schema, *new_schema, old_table_def,
table_def, table_list, table, altered_table,
&ha_alter_info, inplace_supported,
&alter_ctx, columns, fk_key_info,
fk_key_count, &fk_invalidator)) {
return true;
}
goto end_inplace;
} else {
close_temporary_table(thd, altered_table, true, false);
}
}
/* ALTER TABLE using copy algorithm. */
/* Check if ALTER TABLE is compatible with foreign key definitions. */
if (fk_check_copy_alter_table(thd, table_list, old_table_def, alter_info))
goto err_new_table_cleanup;
if (!table->s->tmp_table) {
MDL_request_list mdl_requests;
// COPY algorithm doesn't work with concurrent writes.
if (alter_info->requested_lock == Alter_info::ALTER_TABLE_LOCK_NONE) {
my_error(ER_ALTER_OPERATION_NOT_SUPPORTED_REASON, MYF(0), "LOCK=NONE",
ER_THD(thd, ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_COPY),
"LOCK=SHARED");
goto err_new_table_cleanup;
}
// If EXCLUSIVE lock is requested, upgrade already.
if (alter_info->requested_lock == Alter_info::ALTER_TABLE_LOCK_EXCLUSIVE &&
wait_while_table_is_used(thd, table, HA_EXTRA_FORCE_REOPEN))
goto err_new_table_cleanup;
/*
Otherwise upgrade to SHARED_NO_WRITE.
Note that under LOCK TABLES, we will already have SHARED_NO_READ_WRITE.
*/
if (alter_info->requested_lock != Alter_info::ALTER_TABLE_LOCK_EXCLUSIVE &&
thd->mdl_context.upgrade_shared_lock(mdl_ticket, MDL_SHARED_NO_WRITE,
thd->variables.lock_wait_timeout))
goto err_new_table_cleanup;
DEBUG_SYNC(thd, "alter_table_copy_after_lock_upgrade");
/*
COPY algorithm creates new table version in the new database.
So if new database differs from old one we need to lock all
foreign key names in new table version. If it is the same as
the old one we need to lock only names of foreign keys added.
Also if table is renamed we need to acquire locks on all foreign
key names involved (taking into account adjustment of auto-generated
names).
*/
if (alter_ctx.is_database_changed()) {
if (collect_fk_names(thd, alter_ctx.new_db, table_def, &mdl_requests))
goto err_new_table_cleanup;
} else {
if (collect_fk_names_for_new_fks(
thd, alter_ctx.new_db, table_list->table_name, alter_info,
new_db_type,
get_fk_max_generated_name_number(table_list->table_name,
old_table_def, new_db_type),
&mdl_requests))
goto err_new_table_cleanup;
}
if (alter_ctx.is_table_renamed() &&
collect_fk_names_for_rename_table(
thd, table_list->db, table_list->table_name, table_def, new_db_type,
alter_ctx.new_db, alter_ctx.new_name, &mdl_requests))
goto err_new_table_cleanup;
/*
Acquire SRO locks on parent tables for newly added foreign keys
in order to prevent concurrent DML on them.
This is temporary workaround to the problem caused by the fact that
InnoDB makes such foreign keys visible in its internal dictionary
cache before ALTER TABLE commit. So such DML can result in access
to our temporary table without prior acquisition of metadata lock
on it (which would have blocked such access normally). As result
our ALTER TABLE can fail due to locks acquired by these accesses.
Long-term the problem should be solved by adjusting InnoDB code
to avoid making such uncommitted changes visible to other
connections.
*/
if (collect_fk_parents_for_new_fks(
thd, table_list->db, table_list->table_name, alter_info,
MDL_SHARED_READ_ONLY, nullptr, &mdl_requests, nullptr))
goto err_new_table_cleanup;
if (!mdl_requests.is_empty() &&
thd->mdl_context.acquire_locks(&mdl_requests,
thd->variables.lock_wait_timeout))
goto err_new_table_cleanup;
/*
Check if ALTER TABLE results in any foreign key name conflicts
before starting potentially expensive copying operation.
*/
if (!dd::get_dictionary()->is_dd_table_name(table_list->db,
table_list->table_name) &&
(new_db_type->flags & HTON_SUPPORTS_FOREIGN_KEYS)) {
if (alter_ctx.is_database_changed()) {
/*
If new table version was created schema different from the old one
we need to check names for both pre-existing and newly added foreign
keys.
*/
for (FOREIGN_KEY *fk = fk_key_info; fk < fk_key_info + fk_key_count;
++fk) {
bool exists;
if (thd->dd_client()->check_foreign_key_exists(*new_schema, fk->name,
&exists))
goto err_new_table_cleanup;
if (exists) {
my_error(ER_FK_DUP_NAME, MYF(0), fk->name);
goto err_new_table_cleanup;
}
}
} else {
/* Otherwise we can limit our check to newly added foreign keys only. */
for (FOREIGN_KEY *fk = fk_key_info + alter_ctx.fk_count;
fk < fk_key_info + fk_key_count; ++fk) {
bool exists;
if (thd->dd_client()->check_foreign_key_exists(*new_schema, fk->name,
&exists))
goto err_new_table_cleanup;
if (exists) {
my_error(ER_FK_DUP_NAME, MYF(0), fk->name);
goto err_new_table_cleanup;
}
}
}
if (alter_ctx.is_table_renamed() &&
check_fk_names_before_rename(thd, table_list, *table_def, new_db_type,
*new_schema, alter_ctx))
goto err_new_table_cleanup;
}
}
{
if (ha_create_table(thd, alter_ctx.get_tmp_path(), alter_ctx.new_db,
alter_ctx.tmp_name, create_info, false, true,
table_def))
goto err_new_table_cleanup;
/* Mark that we have created table in storage engine. */
no_ha_table = false;
if (create_info->options & HA_LEX_CREATE_TMP_TABLE) {
if (thd->decide_logging_format(table_list) ||
!open_table_uncached(thd, alter_ctx.get_tmp_path(), alter_ctx.new_db,
alter_ctx.tmp_name, true, true, *table_def))
goto err_new_table_cleanup;
/* in case of alter temp table send the tracker in OK packet */
if (thd->session_tracker.get_tracker(SESSION_STATE_CHANGE_TRACKER)
->is_enabled())
thd->session_tracker.get_tracker(SESSION_STATE_CHANGE_TRACKER)
->mark_as_changed(thd, {});
}
/* Open the table since we need to copy the data. */
if (table->s->tmp_table != NO_TMP_TABLE) {
Table_ref tbl(alter_ctx.new_db, alter_ctx.tmp_name, TL_READ_NO_INSERT);
/* Table is in thd->temporary_tables */
(void)open_temporary_table(thd, &tbl);
new_table = tbl.table;
/* Transfer dd::Table ownership to temporary table's share. */
new_table->s->tmp_table_def = non_dd_table_def.release();
} else {
/* table is a normal table: Create temporary table in same directory */
/* Open our intermediate table. */
new_table =
open_table_uncached(thd, alter_ctx.get_tmp_path(), alter_ctx.new_db,
alter_ctx.tmp_name, true, true, *table_def);
}
if (!new_table) goto err_new_table_cleanup;
/*
Note: In case of MERGE table, we do not attach children. We do not
copy data for MERGE tables. Only the children have data.
*/
// It's now safe to take the table level lock.
if (lock_tables(thd, table_list, alter_ctx.tables_opened, 0))
goto err_new_table_cleanup;
}
/*
We do not copy data for MERGE tables. Only the children have data.
MERGE tables have HA_NO_COPY_ON_ALTER set.
*/
if (!(new_table->file->ha_table_flags() & HA_NO_COPY_ON_ALTER)) {
new_table->next_number_field = new_table->found_next_number_field;
THD_STAGE_INFO(thd, stage_copy_to_tmp_table);
DBUG_EXECUTE_IF("abort_copy_table", {
my_error(ER_LOCK_WAIT_TIMEOUT, MYF(0));
goto err_new_table_cleanup;
});
if (copy_data_between_tables(thd, thd->m_stage_progress_psi, table,
new_table, alter_info->create_list, &copied,
&deleted, alter_info->keys_onoff, &alter_ctx))
goto err_new_table_cleanup;
DEBUG_SYNC(thd, "alter_after_copy_table");
} else {
/* Should be MERGE only */
assert(new_table->file->ht->db_type == DB_TYPE_MRG_MYISAM);
if (!table->s->tmp_table &&
wait_while_table_is_used(thd, table, HA_EXTRA_FORCE_REOPEN))
goto err_new_table_cleanup;
THD_STAGE_INFO(thd, stage_manage_keys);
DEBUG_SYNC(thd, "alter_table_manage_keys");
alter_table_manage_keys(thd, table, table->file->indexes_are_disabled(),
alter_info->keys_onoff);
assert(!(new_db_type->flags & HTON_SUPPORTS_ATOMIC_DDL));
/* Prevent intermediate commits to invoke commit order */
Implicit_substatement_state_guard substatement_guard(
thd, enum_implicit_substatement_guard_mode ::
DISABLE_GTID_AND_SPCO_IF_SPCO_ACTIVE);
if (trans_commit_stmt(thd) || trans_commit_implicit(thd))
goto err_new_table_cleanup;
}
if (table->s->tmp_table != NO_TMP_TABLE) {
/* Close lock if this is a transactional table */
if (thd->lock) {
if (thd->locked_tables_mode != LTM_LOCK_TABLES &&
thd->locked_tables_mode != LTM_PRELOCKED_UNDER_LOCK_TABLES) {
mysql_unlock_tables(thd, thd->lock);
thd->lock = nullptr;
} else {
/*
If LOCK TABLES list is not empty and contains this table,
unlock the table and remove the table from this list.
*/
mysql_lock_remove(thd, thd->lock, table);
}
}
/* Remove link to old table and rename the new one */
close_temporary_table(thd, table, true, true);
/* Should pass the 'new_name' as we store table name in the cache */
if (rename_temporary_table(thd, new_table, alter_ctx.new_db,
alter_ctx.new_name))
goto err_new_table_cleanup;
/*
We don't replicate alter table statement on temporary tables
in RBR mode.
*/
if (!thd->is_current_stmt_binlog_format_row() &&
write_bin_log(thd, true, thd->query().str, thd->query().length)) {
/*
We can't revert replacement of old table version with a new one
at this point. So, if possible, commit the statement to avoid
new table version being emptied by statement rollback.
*/
if (!thd->transaction_rollback_request) {
(void)trans_commit_stmt(thd);
(void)trans_commit_implicit(thd);
}
return true;
}
// Do implicit commit for consistency with non-temporary table case/
if (trans_commit_stmt(thd) || trans_commit_implicit(thd)) return true;
goto end_temporary;
}
/*
Close the intermediate table that will be the new table, but do
not delete it! Even though MERGE tables do not have their children
attached here it is safe to call close_temporary_table().
*/
close_temporary_table(thd, new_table, true, false);
new_table = nullptr;
DEBUG_SYNC(thd, "alter_table_before_rename_result_table");
DBUG_EXECUTE_IF("exit_after_alter_table_before_rename", {
my_error(ER_UNKNOWN_ERROR, MYF(0));
return true;
});
/*
Data is copied. Now we:
1) Wait until all other threads will stop using old version of table
by upgrading shared metadata lock to exclusive one.
2) Close instances of table open by this thread and replace them
with placeholders to simplify reopen process.
3) Rename the old table to a temp name, rename the new one to the
old name.
4) If we are under LOCK TABLES and don't do ALTER TABLE ... RENAME
we reopen new version of table.
5) Write statement to the binary log.
6) If we are under LOCK TABLES and do ALTER TABLE ... RENAME we
remove placeholders and release metadata locks.
7) If we are not not under LOCK TABLES we rely on the caller
(mysql_execute_command()) to release metadata locks.
*/
THD_STAGE_INFO(thd, stage_rename_result_table);
if (wait_while_table_is_used(thd, table, HA_EXTRA_PREPARE_FOR_RENAME))
goto err_new_table_cleanup;
if (collect_and_lock_fk_tables_for_complex_alter_table(
thd, table_list, old_table_def, &alter_ctx, alter_info, old_db_type,
new_db_type, &fk_invalidator))
goto err_new_table_cleanup;
/*
To ensure DDL atomicity after this point support from both old and
new engines is necessary. If either of them lacks such support let
us commit transaction so changes to data-dictionary are more closely
reflect situations in SEs.
Also if new SE supports atomic DDL then we have not stored new table
definition in on-disk data-dictionary so far. It is time to do this
now if ALTER TABLE as a whole won't be atomic.
*/
if (!atomic_replace) {
if ((new_db_type->flags & HTON_SUPPORTS_ATOMIC_DDL) &&
thd->dd_client()->store(non_dd_table_def.get()))
goto err_new_table_cleanup;
/* Prevent intermediate commits to invoke commit order */
Implicit_substatement_state_guard substatement_guard(thd);
if (trans_commit_stmt(thd) || trans_commit_implicit(thd))
goto err_new_table_cleanup;
// Safety, in-memory dd::Table is no longer totally correct.
non_dd_table_def.reset();
}
char backup_name[32];
assert(sizeof(my_thread_id) == 4);
snprintf(backup_name, sizeof(backup_name), "%s2-%lx-%x", tmp_file_prefix,
current_pid, thd->thread_id());
if (lower_case_table_names) my_casedn_str(files_charset_info, backup_name);
close_all_tables_for_name(thd, table->s, false, nullptr);
table_list->table = table = nullptr; /* Safety */
/*
Rename the old version to temporary name to have a backup in case
anything goes wrong while renaming the new table.
Take the X metadata lock on this temporary name too. This ensures that
concurrent I_S queries won't try to open it. Assert to ensure we do not
come here when ALTERing temporary table.
*/
{
assert(!is_tmp_table);
MDL_request backup_name_mdl_request;
MDL_REQUEST_INIT(&backup_name_mdl_request, MDL_key::TABLE, alter_ctx.db,
backup_name, MDL_EXCLUSIVE, MDL_STATEMENT);
dd::cache::Dictionary_client::Auto_releaser releaser_2(thd->dd_client());
const dd::Table *backup_table = nullptr;
if (thd->mdl_context.acquire_lock(&backup_name_mdl_request,
thd->variables.lock_wait_timeout) ||
thd->dd_client()->acquire(alter_ctx.db, backup_name, &backup_table)) {
/* purecov: begin tested */
/*
We need to clear THD::transaction_rollback_request (which might
be set due to MDL deadlock) before attempting to remove new version
of table.
*/
if (thd->transaction_rollback_request) {
trans_rollback_stmt(thd);
trans_rollback(thd);
}
if (!atomic_replace) {
(void)quick_rm_table(thd, new_db_type, alter_ctx.new_db,
alter_ctx.tmp_name, FN_IS_TMP);
}
goto err_with_mdl;
/* purecov: end */
}
if (backup_table != nullptr) {
/* purecov: begin tested */
my_error(ER_TABLE_EXISTS_ERROR, MYF(0), backup_name);
if (!atomic_replace) {
(void)quick_rm_table(thd, new_db_type, alter_ctx.new_db,
alter_ctx.tmp_name, FN_IS_TMP);
}
goto err_with_mdl;
/* purecov: end */
}
}
if (mysql_rename_table(thd, old_db_type, alter_ctx.db, alter_ctx.table_name,
alter_ctx.db, alter_ctx.table_name, *schema,
alter_ctx.db, backup_name,
FN_TO_IS_TMP | (atomic_replace ? NO_DD_COMMIT : 0) |
NO_FK_RENAME | NO_CC_RENAME)) {
// Rename to temporary name failed, delete the new table, abort ALTER.
if (!atomic_replace) {
/*
In non-atomic mode situations when the SE has requested rollback
should be handled already, by executing rollback right inside
mysql_rename_table() call.
*/
assert(!thd->transaction_rollback_request);
(void)quick_rm_table(thd, new_db_type, alter_ctx.new_db,
alter_ctx.tmp_name, FN_IS_TMP);
}
goto err_with_mdl;
}
/*
The below code assumes that only SE capable of atomic DDL support FK.
This is somewhat simplifies error handling below.
Note that we need to handle FKs atomically with this rename in order
to handle scenario when, for example, MyISAM table is altered to InnoDB
SE and some FKs are added at the same time.
*/
assert(!(new_db_type->flags & HTON_SUPPORTS_FOREIGN_KEYS) ||
(new_db_type->flags & HTON_SUPPORTS_ATOMIC_DDL));
/*
We also assume that we can't have non-atomic ALTER TABLE which
will preserve any foreign keys (i.e. such ALTER TABLE can only
drop all foreign keys on the table, or add new foreign keys to
table which previously didn't have any).
*/
assert(atomic_replace || alter_ctx.fk_count == 0);
/*
If both old and new SEs support atomic DDL then we have not stored
new table definition in on-disk data-dictionary so far. It is time
to do this now. However, before doing this we need to rename foreign
keys in old table definition to temporary names to avoid conflicts
with duplicate names.
*/
if (atomic_replace) {
if (alter_ctx.fk_count > 0 &&
adjust_foreign_key_names_for_old_table_version(thd, alter_ctx.db,
backup_name))
goto err_with_mdl;
if (thd->dd_client()->store(non_dd_table_def.get())) goto err_with_mdl;
// Safety, in-memory dd::Table is no longer totally correct.
non_dd_table_def.reset();
}
// Rename the new table to the correct name.
if (mysql_rename_table(
thd, new_db_type, alter_ctx.new_db, alter_ctx.tmp_name, alter_ctx.db,
alter_ctx.table_name, *new_schema, alter_ctx.new_db,
alter_ctx.new_alias,
(FN_FROM_IS_TMP |
((new_db_type->flags & HTON_SUPPORTS_ATOMIC_DDL) ? NO_DD_COMMIT
: 0) |
(alter_ctx.is_table_renamed() ? 0 : NO_FK_RENAME | NO_CC_RENAME))) ||
((new_db_type->flags & HTON_SUPPORTS_FOREIGN_KEYS) &&
adjust_fks_for_complex_alter_table(thd, table_list, &alter_ctx,
alter_info, new_db_type,
&fk_invalidator)) ||
/*
Try commit changes if ALTER TABLE as whole is not atomic and we have
not done this in the above mysql_rename_table() call.
*/
(!atomic_replace && (new_db_type->flags & HTON_SUPPORTS_ATOMIC_DDL) &&
trans_intermediate_ddl_commit(thd, false))) {
// Rename failed, delete the temporary table.
if (!atomic_replace) {
if (new_db_type->flags & HTON_SUPPORTS_ATOMIC_DDL) {
/*
If ALTER TABLE as whole is not atomic and the above rename or
FK changes have failed without cleaning up after themselves,
we need to do this now.
*/
(void)trans_intermediate_ddl_commit(thd, true);
}
/*
In non-atomic mode situations when the SE has requested rollback
should be handled already.
*/
assert(!thd->transaction_rollback_request);
(void)quick_rm_table(thd, new_db_type, alter_ctx.new_db,
alter_ctx.tmp_name, FN_IS_TMP);
// Restore the backup of the original table to its original name.
// If the operation fails, we need to retry it to avoid leaving
// the dictionary inconsistent.
//
// This hack might become unnecessary once InnoDB stops acquiring
// gap locks on DD tables (which might cause deadlocks).
uint retries = 20;
while (retries-- &&
mysql_rename_table(
thd, old_db_type, alter_ctx.db, backup_name, alter_ctx.db,
backup_name, *schema, alter_ctx.db, alter_ctx.alias,
FN_FROM_IS_TMP | NO_FK_CHECKS | NO_FK_RENAME | NO_CC_RENAME))
;
}
goto err_with_mdl;
}
/*
If ALTER TABLE is non-atomic and fails after this point it can add
foreign keys and such addition won't be reverted. So we need to
invalidate table objects for foreign key parents even on error.
*/
if (!atomic_replace) invalidate_fk_parents_on_error = true;
// Handle trigger name, check constraint names and histograms statistics.
{
dd::Table *backup_table = nullptr;
dd::Table *new_dd_table = nullptr;
if (thd->dd_client()->acquire_for_modification(alter_ctx.db, backup_name,
&backup_table) ||
thd->dd_client()->acquire_for_modification(
alter_ctx.new_db, alter_ctx.new_alias, &new_dd_table))
goto err_with_mdl;
assert(backup_table != nullptr && new_dd_table != nullptr);
/*
Check if this is an ALTER command that will cause histogram statistics to
become invalid. If that is the case; remove the histogram statistics.
This will take care of scenarios when COPY alter is used, but not INPLACE.
Do this before the commit for non-transactional tables, because the
new_dd_table is invalidated on commit.
*/
if (alter_table_drop_histograms(thd, table_list, alter_info, create_info,
columns, backup_table, new_dd_table))
goto err_with_mdl; /* purecov: deadcode */
bool update = (new_dd_table->check_constraints()->size() > 0);
// Set mode for new_dd_table's check constraints.
set_check_constraints_alter_mode(new_dd_table, alter_info);
/*
Check constraint names are unique per schema, we cannot create them while
both table version exists. Adjust check constraint names in old table
version.
*/
if (adjust_check_constraint_names_for_old_table_version(thd, alter_ctx.db,
backup_table))
goto err_with_mdl;
// Reset check constraint's mode.
reset_check_constraints_alter_mode(new_dd_table);
/*
Since trigger names have to be unique per schema, we cannot
create them while both the old and the tmp version of the
table exist.
*/
if (backup_table->has_trigger()) {
new_dd_table->copy_triggers(backup_table);
backup_table->drop_all_triggers();
update = true;
}
if (!is_checked_for_upgrade(*new_dd_table) &&
is_checked_for_upgrade(*backup_table)) {
new_dd_table->mark_as_checked_for_upgrade();
update = true;
}
if (update) {
if (thd->dd_client()->update(backup_table) ||
thd->dd_client()->update(new_dd_table))
goto err_with_mdl;
/* Prevent intermediate commits to invoke commit order */
Implicit_substatement_state_guard substatement_guard(thd);
if (!atomic_replace && (trans_commit_stmt(thd) || trans_commit(thd)))
goto err_with_mdl;
}
}
// If the ALTER command was a rename, rename any existing histograms.
if (alter_ctx.is_table_renamed() &&
rename_histograms(thd, table_list->db, table_list->table_name, new_db,
new_name)) {
goto err_with_mdl; /* purecov: deadcode */
}
// ALTER TABLE succeeded, delete the backup of the old table.
if (quick_rm_table(thd, old_db_type, alter_ctx.db, backup_name,
FN_IS_TMP | (atomic_replace ? NO_DD_COMMIT : 0))) {
/*
The fact that deletion of the backup failed is not critical
error, but still worth reporting as it might indicate serious
problem with server.
TODO: In !atomic_replace case we might need to do FK parents
invalidation here. However currently our FKs are not
even named correctly at this point, so we postpone
fixing this issue until we solve FK naming problem.
*/
goto err_with_mdl;
}
end_inplace_noop:
THD_STAGE_INFO(thd, stage_end);
DBUG_EXECUTE_IF("sleep_alter_before_main_binlog", my_sleep(6000000););
DEBUG_SYNC(thd, "alter_table_before_main_binlog");
ha_binlog_log_query(thd, create_info->db_type, LOGCOM_ALTER_TABLE,
thd->query().str, thd->query().length, alter_ctx.db,
alter_ctx.table_name);
assert(!(mysql_bin_log.is_open() &&
thd->is_current_stmt_binlog_format_row() &&
(create_info->options & HA_LEX_CREATE_TMP_TABLE)));
/*
If this is no-op ALTER TABLE we don't have transaction started.
We can't use binlog's trx cache in this case as it requires active
transaction with valid XID.
*/
if (write_bin_log(thd, true, thd->query().str, thd->query().length,
atomic_replace && !is_noop))
goto err_with_mdl;
if (!is_noop) {
Uncommitted_tables_guard uncommitted_tables(thd);
uncommitted_tables.add_table(table_list);
if (update_referencing_views_metadata(thd, table_list, new_db, new_name,
!atomic_replace, &uncommitted_tables))
goto err_with_mdl;
if (alter_ctx.is_table_renamed())
tdc_remove_table(thd, TDC_RT_REMOVE_ALL, alter_ctx.new_db,
alter_ctx.new_name, false);
}
// Commit if it was not done before in order to be able to reopen tables.
if (atomic_replace && (trans_commit_stmt(thd) || trans_commit_implicit(thd)))
goto err_with_mdl;
if ((new_db_type->flags & HTON_SUPPORTS_ATOMIC_DDL) && new_db_type->post_ddl)
new_db_type->post_ddl(thd);
if ((old_db_type->flags & HTON_SUPPORTS_ATOMIC_DDL) && old_db_type->post_ddl)
old_db_type->post_ddl(thd);
#ifndef WORKAROUND_TO_BE_REMOVED_BY_WL6049
{
Table_ref table_list_reopen(alter_ctx.new_db, alter_ctx.new_name,
alter_ctx.new_alias, TL_READ);
table_list_reopen.mdl_request.ticket =
alter_ctx.is_table_renamed() ? alter_ctx.target_mdl_request.ticket
: mdl_ticket;
Open_table_context ot_ctx(thd, MYSQL_OPEN_REOPEN);
if (open_table(thd, &table_list_reopen, &ot_ctx)) return true;
assert(table_list_reopen.table == thd->open_tables);
close_thread_table(thd, &thd->open_tables);
}
#endif
end_inplace:
fk_invalidator.invalidate(thd);
if (alter_ctx.is_table_renamed())
thd->locked_tables_list.rename_locked_table(
table_list, alter_ctx.new_db, alter_ctx.new_name,
alter_ctx.target_mdl_request.ticket);
{
bool reopen_error = thd->locked_tables_list.reopen_tables(thd);
if (thd->locked_tables_mode == LTM_LOCK_TABLES ||
thd->locked_tables_mode == LTM_PRELOCKED_UNDER_LOCK_TABLES) {
if (alter_ctx.is_table_renamed()) {
/*
Release metadata lock on old table name and keep the lock
on the new one. We have to ignore reopen_error in this case
as we will mess up FK invariants for LOCK TABLES otherwise.
*/
thd->mdl_context.release_all_locks_for_name(mdl_ticket);
thd->mdl_context.set_lock_duration(alter_ctx.target_mdl_request.ticket,
MDL_EXPLICIT);
alter_ctx.target_mdl_request.ticket->downgrade_lock(
MDL_SHARED_NO_READ_WRITE);
if (alter_ctx.is_database_changed())
thd->mdl_context.set_lock_duration(
alter_ctx.target_db_mdl_request.ticket, MDL_EXPLICIT);
} else
mdl_ticket->downgrade_lock(MDL_SHARED_NO_READ_WRITE);
}
if (reopen_error) return true;
}
end_temporary:
snprintf(alter_ctx.tmp_name, sizeof(alter_ctx.tmp_name),
ER_THD(thd, ER_INSERT_INFO), (long)(copied + deleted), (long)deleted,
(long)thd->get_stmt_da()->current_statement_cond_count());
my_ok(thd, copied + deleted, 0L, alter_ctx.tmp_name);
return false;
err_new_table_cleanup:
if (create_info->options & HA_LEX_CREATE_TMP_TABLE) {
if (new_table)
close_temporary_table(thd, new_table, true, true);
else if (!no_ha_table)
rm_temporary_table(thd, new_db_type, alter_ctx.get_tmp_path(),
non_dd_table_def.get());
} else {
/* close_temporary_table() frees the new_table pointer. */
if (new_table) close_temporary_table(thd, new_table, true, false);
if (!(new_db_type->flags & HTON_SUPPORTS_ATOMIC_DDL)) {
if (no_ha_table) // Only remove from DD.
{
dd::cache::Dictionary_client::Auto_releaser releaser_3(
thd->dd_client());
const dd::Table *drop_table_def = nullptr;
if (!thd->dd_client()->acquire(alter_ctx.new_db, alter_ctx.tmp_name,
&drop_table_def)) {
assert(drop_table_def != nullptr);
bool result = dd::drop_table(thd, alter_ctx.new_db,
alter_ctx.tmp_name, *drop_table_def);
(void)trans_intermediate_ddl_commit(thd, result);
}
} else // Remove from both DD and SE.
(void)quick_rm_table(thd, new_db_type, alter_ctx.new_db,
alter_ctx.tmp_name, FN_IS_TMP);
} else {
trans_rollback_stmt(thd);
/*
Full rollback in case we have THD::transaction_rollback_request
and to synchronize DD state in cache and on disk (as statement
rollback doesn't clear DD cache of modified uncommitted objects).
*/
trans_rollback(thd);
}
if ((new_db_type->flags & HTON_SUPPORTS_ATOMIC_DDL) &&
new_db_type->post_ddl)
new_db_type->post_ddl(thd);
}
if (alter_ctx.error_if_not_empty &
Alter_table_ctx::GEOMETRY_WITHOUT_DEFAULT) {
my_error(ER_INVALID_USE_OF_NULL, MYF(0));
}
/*
No default value was provided for a DATE/DATETIME field, the
current sql_mode doesn't allow the '0000-00-00' value and
the table to be altered isn't empty.
Report error here. Ignore error checkin for push_zero_date_warning()
as we return true right below.
*/
if ((alter_ctx.error_if_not_empty &
Alter_table_ctx::DATETIME_WITHOUT_DEFAULT) &&
(thd->variables.sql_mode & MODE_NO_ZERO_DATE) &&
thd->get_stmt_da()->current_row_for_condition()) {
(void)push_zero_date_warning(thd, alter_ctx.datetime_field);
}
return true;
err_with_mdl:
/*
An error happened while we were holding exclusive name metadata lock
on table being altered. Before releasing locks we need to rollback
changes to the data-dictionary, storage angine and binary log (if
they were not committed earlier) and execute post DDL hooks.
We also try to reopen old version of the table under LOCK TABLES
if possible.
*/
trans_rollback_stmt(thd);
/*
Full rollback in case we have THD::transaction_rollback_request
and to synchronize DD state in cache and on disk (as statement
rollback doesn't clear DD cache of modified uncommitted objects).
*/
trans_rollback(thd);
if ((new_db_type->flags & HTON_SUPPORTS_ATOMIC_DDL) && new_db_type->post_ddl)
new_db_type->post_ddl(thd);
if ((old_db_type->flags & HTON_SUPPORTS_ATOMIC_DDL) && old_db_type->post_ddl)
old_db_type->post_ddl(thd);
if (atomic_replace) {
/*
If both old and new storage engines support atomic DDL all changes
were reverted at this point. So we can safely try to reopen table
under old name.
*/
} else {
/*
If ALTER TABLE ... RENAME ... ALGORITHM=COPY is non-atomic we can't
be sure that rename step was reverted, so we simply remove table
from the list of locked tables.
*/
if (alter_ctx.is_table_renamed())
thd->locked_tables_list.unlink_all_closed_tables(thd, nullptr, 0);
}
/*
ALTER TABLE which changes table storage engine from MyISAM to InnoDB
and adds foreign keys at the same time can fail after installing
new table version. In this case we still need to invalidate table
objects for parent tables to avoid creating discrepancy between
data-dictionary and cache contents.
*/
if (invalidate_fk_parents_on_error) fk_invalidator.invalidate(thd);
(void)thd->locked_tables_list.reopen_tables(thd);
if ((thd->locked_tables_mode == LTM_LOCK_TABLES ||
thd->locked_tables_mode == LTM_PRELOCKED_UNDER_LOCK_TABLES)) {
/*
Non-atomic ALTER TABLE ... RENAME ... ALGORITHM=COPY can add
foreign keys if at the same time SE is changed from, e.g.,
MyISAM to InnoDB. Since releasing metadata locks on old or new
table name can break FK invariants for LOCK TABLES in various
scenarios we keep both of them.
*/
if (!atomic_replace && alter_ctx.is_table_renamed()) {
thd->mdl_context.set_lock_duration(alter_ctx.target_mdl_request.ticket,
MDL_EXPLICIT);
alter_ctx.target_mdl_request.ticket->downgrade_lock(
MDL_SHARED_NO_READ_WRITE);
if (alter_ctx.is_database_changed())
thd->mdl_context.set_lock_duration(
alter_ctx.target_db_mdl_request.ticket, MDL_EXPLICIT);
}
mdl_ticket->downgrade_lock(MDL_SHARED_NO_READ_WRITE);
}
return true;
}
/* mysql_alter_table */
/**
Prepare the transaction for the alter table's copy phase.
*/
bool mysql_trans_prepare_alter_copy_data(THD *thd) {
DBUG_TRACE;
/*
Turn off recovery logging since rollback of an alter table is to
delete the new table so there is no need to log the changes to it.
This needs to be done before external_lock.
Also this prevent intermediate commits to invoke commit order.
*/
Implicit_substatement_state_guard substatement_guard(thd);
if (ha_enable_transaction(thd, false)) return true;
return false;
}
/**
Commit the copy phase of the alter table.
*/
bool mysql_trans_commit_alter_copy_data(THD *thd) {
bool error = false;
DBUG_TRACE;
/*
Ensure that ha_commit_trans() which is implicitly called by
ha_enable_transaction() doesn't update GTID and slave info states.
Also this prevent intermediate commits to invoke commit order.
*/
Implicit_substatement_state_guard substatement_guard(thd);
if (ha_enable_transaction(thd, true)) return true;
/*
Ensure that the new table is saved properly to disk before installing
the new .frm.
And that InnoDB's internal latches are released, to avoid deadlock
when waiting on other instances of the table before rename (Bug#54747).
*/
if (trans_commit_stmt(thd)) error = true;
if (trans_commit_implicit(thd)) error = true;
return error;
}
static int copy_data_between_tables(
THD *thd, PSI_stage_progress *psi [[maybe_unused]], TABLE *from, TABLE *to,
List<Create_field> &create, ha_rows *copied, ha_rows *deleted,
Alter_info::enum_enable_or_disable keys_onoff, Alter_table_ctx *alter_ctx) {
DBUG_TRACE;
int error;
Copy_field *copy, *copy_end;
Field **ptr;
/*
Fields which values need to be generated for each row, i.e. either
generated fields or newly added fields with generated default values.
*/
Field **gen_fields, **gen_fields_end;
bool auto_increment_field_copied = false;
sql_mode_t save_sql_mode;
Query_expression *const unit = thd->lex->unit;
Query_block *const select = unit->first_query_block();
/*
If target storage engine supports atomic DDL we should not commit
and disable transaction to let SE do proper cleanup on error/crash.
Such engines should be smart enough to disable undo/redo logging
for target table automatically.
Temporary tables path doesn't employ atomic DDL support so disabling
transaction is OK. Moreover doing so allows to not interfere with
concurrent FLUSH TABLES WITH READ LOCK.
*/
if ((!(to->file->ht->flags & HTON_SUPPORTS_ATOMIC_DDL) ||
from->s->tmp_table) &&
mysql_trans_prepare_alter_copy_data(thd))
return -1;
if (!(copy = new (thd->mem_root) Copy_field[to->s->fields]))
return -1; /* purecov: inspected */
if (!(gen_fields = thd->mem_root->ArrayAlloc<Field *>(
to->s->gen_def_field_count + to->s->vfields))) {
destroy_array(copy, to->s->fields);
return -1;
}
if (to->file->ha_external_lock(thd, F_WRLCK)) {
destroy_array(copy, to->s->fields);
return -1;
}
/* We need external lock before we can disable/enable keys */
alter_table_manage_keys(thd, to, from->file->indexes_are_disabled(),
keys_onoff);
if (unit->is_prepared()) {
bind_fields(thd->stmt_arena->item_list());
}
/*
We want warnings/errors about data truncation emitted when we
copy data to new version of table.
*/
thd->check_for_truncated_fields = CHECK_FIELD_WARN;
thd->num_truncated_fields = 0L;
from->file->info(HA_STATUS_VARIABLE);
to->file->ha_start_bulk_insert(from->file->stats.records);
mysql_stage_set_work_estimated(psi, from->file->stats.records);
save_sql_mode = thd->variables.sql_mode;
List_iterator<Create_field> it(create);
const Create_field *def;
copy_end = copy;
gen_fields_end = gen_fields;
for (ptr = to->field; *ptr; ptr++) {
def = it++;
if ((*ptr)->is_gcol()) {
/*
Values in generated columns need to be (re)generated even for
pre-existing columns, as they might depend on other columns,
values in which might have changed as result of this ALTER.
Because of this there is no sense in copying old values for
these columns.
TODO: Figure out if we can avoid even reading these old values
from SE.
*/
*(gen_fields_end++) = *ptr;
continue;
}
// Array fields will be properly generated during GC update loop below
assert(!def->is_array);
if (def->field) {
if (*ptr == to->next_number_field) {
auto_increment_field_copied = true;
/*
If we are going to copy contents of one auto_increment column to
another auto_increment column it is sensible to preserve zeroes.
This condition also covers case when we are don't actually alter
auto_increment column.
*/
if (def->field == from->found_next_number_field)
thd->variables.sql_mode |= MODE_NO_AUTO_VALUE_ON_ZERO;
}
(copy_end++)->set(*ptr, def->field);
} else {
/*
New column. Add it to the array of columns requiring value
generation if it has generated default.
*/
if ((*ptr)->has_insert_default_general_value_expression()) {
assert(!((*ptr)->is_gcol()));
*(gen_fields_end++) = *ptr;
}
}
}
ulong found_count = 0;
ulong delete_count = 0;
ORDER *order = select->order_list.first;
unique_ptr_destroy_only<Filesort> fsort;
unique_ptr_destroy_only<RowIterator> iterator;
AccessPath *path =
create_table_access_path(thd, from, nullptr, nullptr, nullptr,
/*count_examined_rows=*/false);
if (order != nullptr && to->s->primary_key != MAX_KEY &&
to->file->primary_key_is_clustered()) {
char warn_buff[MYSQL_ERRMSG_SIZE];
snprintf(warn_buff, sizeof(warn_buff),
"ORDER BY ignored as there is a user-defined clustered index"
" in the table '%-.192s'",
from->s->table_name.str);
push_warning(thd, Sql_condition::SL_WARNING, ER_UNKNOWN_ERROR, warn_buff);
order = nullptr;
}
/* Tell handler that we have values for all columns in the to table */
to->use_all_columns();
if (order != nullptr) {
Table_ref tables;
tables.table = from;
tables.alias = tables.table_name = from->s->table_name.str;
tables.db = from->s->db.str;
error = 1;
if (!unit->is_prepared()) {
Column_privilege_tracker column_privilege(thd, SELECT_ACL);
if (select->setup_base_ref_items(thd)) {
goto err; /* purecov: inspected */
}
mem_root_deque<Item *> fields(thd->mem_root);
if (setup_order(thd, select->base_ref_items, &tables, &fields, order))
goto err;
}
fsort.reset(new (thd->mem_root) Filesort(
thd, {from}, /*keep_buffers=*/false, order, HA_POS_ERROR,
/*remove_duplicates=*/false, /*force_sort_rowids=*/true,
/*unwrap_rollup=*/false));
path = NewSortAccessPath(thd, path, fsort.get(), order,
/*count_examined_rows=*/false);
}
if (!unit->is_prepared()) unit->set_prepared();
iterator = CreateIteratorFromAccessPath(thd, path, /*join=*/nullptr,
/*eligible_for_batch_mode=*/true);
// Prevent cleanup in QEP_shared_owner::qs_cleanup(),
// to avoid double-destroy of the SortingIterator.
from->sorting_iterator = nullptr;
if (iterator == nullptr || iterator->Init()) {
error = 1;
goto err;
}
thd->get_stmt_da()->reset_current_row_for_condition();
set_column_static_defaults(to, create);
to->file->ha_extra(HA_EXTRA_BEGIN_ALTER_COPY);
while (!(error = iterator->Read())) {
if (thd->killed) {
thd->send_kill_message();
error = 1;
break;
}
/*
Return error if source table isn't empty.
For a DATE/DATETIME field, return error only if strict mode
and No ZERO DATE mode is enabled.
*/
if ((alter_ctx->error_if_not_empty &
Alter_table_ctx::GEOMETRY_WITHOUT_DEFAULT) ||
((alter_ctx->error_if_not_empty &
Alter_table_ctx::DATETIME_WITHOUT_DEFAULT) &&
(thd->variables.sql_mode & MODE_NO_ZERO_DATE) &&
thd->is_strict_mode())) {
error = 1;
break;
}
if (to->next_number_field) {
if (auto_increment_field_copied)
to->autoinc_field_has_explicit_non_null_value = true;
else
to->next_number_field->reset();
}
for (Copy_field *copy_ptr = copy; copy_ptr != copy_end; copy_ptr++) {
copy_ptr->invoke_do_copy();
}
if (thd->is_error()) {
error = 1;
break;
}
/*
Iterate through all generated columns and all new columns which have
generated defaults and evaluate their values. This needs to happen
after copying values for old columns and storing default values for
new columns without generated defaults, as generated values might
depend on these values.
OTOH generated columns/generated defaults need to be processed in
the order in which their columns are present in table as generated
values are allowed to depend on each other as long as there are no
forward references (i.e. references to other columns with generated
values which come later in the table).
*/
for (ptr = gen_fields; ptr != gen_fields_end; ptr++) {
Item *expr_item;
if ((*ptr)->is_gcol()) {
expr_item = (*ptr)->gcol_info->expr_item;
} else {
assert((*ptr)->has_insert_default_general_value_expression());
expr_item = (*ptr)->m_default_val_expr->expr_item;
}
expr_item->save_in_field(*ptr, false);
if (thd->is_error()) {
error = 1;
break;
}
}
if (error) break;
error = invoke_table_check_constraints(thd, to);
if (error) break;
error = to->file->ha_write_row(to->record[0]);
to->autoinc_field_has_explicit_non_null_value = false;
if (error) {
if (!to->file->is_ignorable_error(error)) {
/* Not a duplicate key error. */
to->file->print_error(error, MYF(0));
break;
} else {
/* Report duplicate key error. */
uint key_nr = to->file->get_dup_key(error);
if ((int)key_nr >= 0) {
const char *err_msg = ER_THD(thd, ER_DUP_ENTRY_WITH_KEY_NAME);
if (key_nr == 0 && (to->key_info[0].key_part[0].field->is_flag_set(
AUTO_INCREMENT_FLAG)))
err_msg = ER_THD(thd, ER_DUP_ENTRY_AUTOINCREMENT_CASE);
print_keydup_error(
to, key_nr == MAX_KEY ? nullptr : &to->key_info[key_nr], err_msg,
MYF(0), from->s->table_name.str);
} else
to->file->print_error(error, MYF(0));
break;
}
} else {
DEBUG_SYNC(thd, "copy_data_between_tables_before");
found_count++;
mysql_stage_set_work_completed(psi, found_count);
}
thd->get_stmt_da()->inc_current_row_for_condition();
}
iterator.reset();
free_io_cache(from);
if (to->file->ha_end_bulk_insert() && error <= 0) {
to->file->print_error(my_errno(), MYF(0));
error = 1;
}
to->file->ha_extra(HA_EXTRA_END_ALTER_COPY);
DBUG_EXECUTE_IF("crash_copy_before_commit", DBUG_SUICIDE(););
if ((!(to->file->ht->flags & HTON_SUPPORTS_ATOMIC_DDL) ||
from->s->tmp_table) &&
mysql_trans_commit_alter_copy_data(thd))
error = 1;
err:
destroy_array(copy, to->s->fields);
thd->variables.sql_mode = save_sql_mode;
free_io_cache(from);
*copied = found_count;
*deleted = delete_count;
to->file->ha_release_auto_increment();
if (to->file->ha_external_lock(thd, F_UNLCK)) error = 1;
if (error < 0 && to->file->ha_extra(HA_EXTRA_PREPARE_FOR_RENAME)) error = 1;
thd->check_for_truncated_fields = CHECK_FIELD_IGNORE;
return error > 0 ? -1 : 0;
}
/*
Recreates tables by calling mysql_alter_table().
SYNOPSIS
mysql_recreate_table()
thd Thread handler
tables Tables to recreate
table_copy Recreate the table by using ALTER TABLE COPY algorithm
RETURN
Like mysql_alter_table().
*/
bool mysql_recreate_table(THD *thd, Table_ref *table_list, bool table_copy) {
HA_CREATE_INFO create_info;
Alter_info alter_info(thd->mem_root);
DBUG_TRACE;
assert(!table_list->next_global);
/* Set lock type which is appropriate for ALTER TABLE. */
table_list->set_lock({TL_READ_NO_INSERT, THR_DEFAULT});
/* Same applies to MDL request. */
table_list->mdl_request.set_type(MDL_SHARED_NO_WRITE);
create_info.row_type = ROW_TYPE_NOT_USED;
create_info.default_table_charset = default_charset_info;
/* Force alter table to recreate table */
alter_info.flags =
(Alter_info::ALTER_CHANGE_COLUMN | Alter_info::ALTER_RECREATE);
if (table_copy)
alter_info.requested_algorithm = Alter_info::ALTER_TABLE_ALGORITHM_COPY;
const bool ret = mysql_alter_table(thd, NullS, NullS, &create_info,
table_list, &alter_info);
return ret;
}
bool mysql_checksum_table(THD *thd, Table_ref *tables,
HA_CHECK_OPT *check_opt) {
Table_ref *table;
Item *item;
Protocol *protocol = thd->get_protocol();
DBUG_TRACE;
/*
CHECKSUM TABLE returns results and rollbacks statement transaction,
so it should not be used in stored function or trigger.
*/
assert(!thd->in_sub_stmt);
mem_root_deque<Item *> field_list(thd->mem_root);
field_list.push_back(item = new Item_empty_string("Table", NAME_LEN * 2));
item->set_nullable(true);
field_list.push_back(item = new Item_int(NAME_STRING("Checksum"), (longlong)1,
MY_INT64_NUM_DECIMAL_DIGITS));
item->set_nullable(true);
if (thd->send_result_metadata(field_list,
Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF))
return true;
/*
Close all temporary tables which were pre-open to simplify
privilege checking. Clear all references to closed tables.
*/
close_thread_tables(thd);
for (table = tables; table; table = table->next_local) table->table = nullptr;
/* Open one table after the other to keep lock time as short as possible. */
for (table = tables; table; table = table->next_local) {
char table_name[NAME_LEN * 2 + 2];
TABLE *t;
Table_ref *save_next_global;
strxmov(table_name, table->db, ".", table->table_name, NullS);
/* Remember old 'next' pointer and break the list. */
save_next_global = table->next_global;
table->next_global = nullptr;
table->set_lock({TL_READ, THR_DEFAULT});
/* Allow to open real tables only. */
table->required_type = dd::enum_table_type::BASE_TABLE;
if (open_temporary_tables(thd, table) ||
open_and_lock_tables(thd, table, 0)) {
t = nullptr;
} else
t = table->table;
table->next_global = save_next_global;
protocol->start_row();
protocol->store(table_name, system_charset_info);
if (!t) {
/* Table didn't exist */
protocol->store_null();
} else {
if (t->file->ha_table_flags() & HA_HAS_CHECKSUM &&
!(check_opt->flags & T_EXTEND))
protocol->store((ulonglong)t->file->checksum());
else if (!(t->file->ha_table_flags() & HA_HAS_CHECKSUM) &&
(check_opt->flags & T_QUICK))
protocol->store_null();
else {
/* calculating table's checksum */
ha_checksum crc = 0;
uchar null_mask = 256 - (1 << t->s->last_null_bit_pos);
t->use_all_columns();
if (t->file->ha_rnd_init(true))
protocol->store_null();
else {
for (;;) {
if (thd->killed) {
/*
we've been killed; let handler clean up, and remove the
partial current row from the recordset (embedded lib)
*/
t->file->ha_rnd_end();
protocol->abort_row();
goto err;
}
ha_checksum row_crc = 0;
int error = t->file->ha_rnd_next(t->record[0]);
if (unlikely(error)) {
if (error == HA_ERR_RECORD_DELETED) continue;
break;
}
if (t->s->null_bytes) {
/* fix undefined null bits */
t->record[0][t->s->null_bytes - 1] |= null_mask;
if (!(t->s->db_create_options & HA_OPTION_PACK_RECORD))
t->record[0][0] |= 1;
row_crc = checksum_crc32(row_crc, t->record[0], t->s->null_bytes);
}
for (uint i = 0; i < t->s->fields; i++) {
Field *f = t->field[i];
/*
BLOB and VARCHAR have pointers in their field, we must convert
to string; GEOMETRY and JSON are implemented on top of BLOB.
BIT may store its data among NULL bits, convert as well.
*/
switch (f->type()) {
case MYSQL_TYPE_BLOB:
case MYSQL_TYPE_VARCHAR:
case MYSQL_TYPE_GEOMETRY:
case MYSQL_TYPE_JSON:
case MYSQL_TYPE_BIT: {
String tmp;
f->val_str(&tmp);
row_crc =
checksum_crc32(row_crc, (uchar *)tmp.ptr(), tmp.length());
break;
}
default:
row_crc =
checksum_crc32(row_crc, f->field_ptr(), f->pack_length());
break;
}
}
crc += row_crc;
}
protocol->store((ulonglong)crc);
t->file->ha_rnd_end();
}
}
trans_rollback_stmt(thd);
close_thread_tables(thd);
}
if (thd->transaction_rollback_request) {
/*
If transaction rollback was requested we honor it. To do this we
abort statement and return error as not only CHECKSUM TABLE is
rolled back but the whole transaction in which it was used.
*/
protocol->abort_row();
goto err;
}
/* Hide errors from client. Return NULL for problematic tables instead. */
thd->clear_error();
if (protocol->end_row()) goto err;
}
my_eof(thd);
return false;
err:
return true;
}
/**
@brief Check if the table can be created in the specified storage engine.
Checks if the storage engine is enabled and supports the given table
type (e.g. normal, temporary, system). May do engine substitution
if the requested engine does not support temporary tables.
@param db_name Database name.
@param table_name Name of table to be created.
@param create_info Create info from parser, including engine.
@retval true Engine not available/supported, error has been reported.
@retval false Engine available/supported.
*/
static bool check_engine(const char *db_name, const char *table_name,
HA_CREATE_INFO *create_info) {
DBUG_TRACE;
handlerton **new_engine = &create_info->db_type;
/*
Check, if the given table name is system table, and if the storage engine
does supports it.
*/
if ((create_info->used_fields & HA_CREATE_USED_ENGINE) &&
!ha_check_if_supported_system_table(*new_engine, db_name, table_name)) {
my_error(ER_UNSUPPORTED_ENGINE, MYF(0),
ha_resolve_storage_engine_name(*new_engine), db_name, table_name);
*new_engine = nullptr;
return true;
}
// The storage engine must support secondary engines.
if (create_info->used_fields & HA_CREATE_USED_SECONDARY_ENGINE &&
!((*new_engine)->flags & HTON_SUPPORTS_SECONDARY_ENGINE)) {
my_error(ER_CHECK_NOT_IMPLEMENTED, MYF(0), "SECONDARY_ENGINE");
return true;
}
// The storage engine must support encryption.
if (create_info->encrypt_type.str) {
bool encryption_request_type = false;
dd::String_type encrypt_type;
encrypt_type.assign(create_info->encrypt_type.str,
create_info->encrypt_type.length);
encryption_request_type = is_encrypted(encrypt_type);
if (encryption_request_type &&
!((*new_engine)->flags & HTON_SUPPORTS_TABLE_ENCRYPTION)) {
my_error(ER_CHECK_NOT_IMPLEMENTED, MYF(0), "ENCRYPTION");
return true;
}
}
return false;
}
/**
Helper method to generate check constraint name.
@param thd Thread handle.
@param table_name Table name.
@param ordinal_number Ordinal number of the generated name.
@param[out] name LEX_STRING instance to hold the
generated check constraint name.
@param skip_validation Skip generated name validation.
*/
static bool generate_check_constraint_name(THD *thd, const char *table_name,
uint ordinal_number,
LEX_STRING &name,
bool skip_validation) {
// Allocate memory for name.
size_t generated_name_len =
strlen(table_name) + sizeof(dd::CHECK_CONSTRAINT_NAME_SUBSTR) + 11 + 1;
name.str = (char *)thd->mem_root->Alloc(generated_name_len);
if (name.str == nullptr) return true; // OOM
// Prepare name for check constraint.
sprintf(name.str, "%s%s%u", table_name, dd::CHECK_CONSTRAINT_NAME_SUBSTR,
ordinal_number);
name.length = strlen(name.str);
// Validate check constraint name.
if (!skip_validation &&
check_string_char_length(to_lex_cstring(name), "", NAME_CHAR_LEN,
system_charset_info, true)) {
my_error(ER_TOO_LONG_IDENT, MYF(0), name.str);
return true;
}
return false;
}
/**
Helper method to create MDL_request for check constraint names. Check
constraint names are case insensitive. Hence names are lowercased
in MDL_request and pushed to MDL_request_list.
@param thd Thread handle.
@param db Database name.
@param cc_name Check constraint name.
@param[out] cc_mdl_request_list MDL request list.
@retval false Success.
@retval true Failure.
*/
static bool push_check_constraint_mdl_request_to_list(
THD *thd, const char *db, const char *cc_name,
MDL_request_list &cc_mdl_request_list) {
assert(thd != nullptr && db != nullptr && cc_name != nullptr);
/*
Check constraint names are case insensitive. Hence lowercasing names for
MDL locking.
*/
char lc_cc_name[NAME_LEN + 1];
strmake(lc_cc_name, cc_name, NAME_LEN);
my_casedn_str(system_charset_info, lc_cc_name);
MDL_request *mdl_request = new (thd->mem_root) MDL_request;
if (mdl_request == nullptr) return true; // OOM
MDL_REQUEST_INIT(mdl_request, MDL_key::CHECK_CONSTRAINT, db, lc_cc_name,
MDL_EXCLUSIVE, MDL_STATEMENT);
cc_mdl_request_list.push_front(mdl_request);
return false;
}
bool prepare_check_constraints_for_create(THD *thd, const char *db_name,
const char *table_name,
Alter_info *alter_info) {
DBUG_TRACE;
MDL_request_list cc_mdl_request_list;
uint cc_max_generated_number = 0;
/*
Do not process check constraint specification list if master is on version
not supporting check constraints feature.
*/
if (is_slave_with_master_without_check_constraints_support(thd)) {
alter_info->check_constraint_spec_list.clear();
return false;
}
for (auto &cc_spec : alter_info->check_constraint_spec_list) {
// If check constraint name is omitted then generate name.
if (cc_spec->name.length == 0) {
if (generate_check_constraint_name(
thd, table_name, ++cc_max_generated_number, cc_spec->name, false))
return true;
}
// Pre-validate check constraint.
if (cc_spec->pre_validate()) return true;
// Create MDL request for the check constraint.
if (push_check_constraint_mdl_request_to_list(
thd, db_name, cc_spec->name.str, cc_mdl_request_list))
return true;
}
// Make sure fields used by the check constraint exists in the create list.
mem_root_deque<Item_field *> fields(thd->mem_root);
for (auto &cc_spec : alter_info->check_constraint_spec_list) {
cc_spec->check_expr->walk(&Item::collect_item_field_processor,
enum_walk::POSTFIX, (uchar *)&fields);
Create_field *cur_fld;
List_iterator<Create_field> create_fields_it(alter_info->create_list);
for (Item_field *cur_item_fld : fields) {
if (cur_item_fld->type() != Item::FIELD_ITEM) continue;
while ((cur_fld = create_fields_it++)) {
if (!my_strcasecmp(system_charset_info, cur_item_fld->field_name,
cur_fld->field_name))
break;
}
create_fields_it.rewind();
if (cur_fld == nullptr) {
my_error(ER_CHECK_CONSTRAINT_REFERS_UNKNOWN_COLUMN, MYF(0),
cc_spec->name.str, cur_item_fld->field_name);
return true;
}
}
fields.clear();
}
DEBUG_SYNC(thd, "before_acquiring_lock_on_check_constraints");
if (thd->mdl_context.acquire_locks(&cc_mdl_request_list,
thd->variables.lock_wait_timeout))
return true;
DEBUG_SYNC(thd, "after_acquiring_lock_on_check_constraints");
return false;
}
/**
Method to prepare check constraints for the CREATE TABLE LIKE operation.
If check constraints are defined on the source table then check constraints
specifications are prepared for the table being created from it. To
avoid name conflicts, names are generated for all the check constraints
prepared for the table being created.
@param thd Thread handle.
@param src_table Table_ref instance for source
table.
@param target_table Table_ref instance for target
table.
@param alter_info Alter_info instance to prepare
list of check constraint spec
for table being created.
@retval false Success.
@retval true Failure.
*/
static bool prepare_check_constraints_for_create_like_table(
THD *thd, Table_ref *src_table, Table_ref *target_table,
Alter_info *alter_info) {
DBUG_TRACE;
MDL_request_list cc_mdl_request_list;
uint number = 0;
if (src_table->table->table_check_constraint_list != nullptr) {
for (auto &table_cc : *src_table->table->table_check_constraint_list) {
Sql_check_constraint_spec *cc_spec =
new (thd->mem_root) Sql_check_constraint_spec;
if (cc_spec == nullptr) return true; // OOM
// For create like table, all the check constraint names are generated to
// avoid name conflicts.
if (generate_check_constraint_name(thd, target_table->table_name,
++number, cc_spec->name, true))
return true;
// check constraint expression.
cc_spec->check_expr = table_cc.value_generator()->expr_item;
// Copy check constraint status.
cc_spec->is_enforced = table_cc.is_enforced();
alter_info->check_constraint_spec_list.push_back(cc_spec);
/*
Create MDL request for check constraint in source table and the
generated check constraint name for target table.
*/
if (push_check_constraint_mdl_request_to_list(
thd, src_table->db, table_cc.name().str, cc_mdl_request_list) ||
push_check_constraint_mdl_request_to_list(
thd, target_table->db, cc_spec->name.str, cc_mdl_request_list))
return true;
}
}
DEBUG_SYNC(thd, "before_acquiring_lock_on_check_constraints");
if (thd->mdl_context.acquire_locks(&cc_mdl_request_list,
thd->variables.lock_wait_timeout))
return true;
DEBUG_SYNC(thd, "after_acquiring_lock_on_check_constraints");
return false;
}
/**
Method to prepare check constraints for the ALTER TABLE operation.
Method prepares check constraints specifications from the existing
list of check constraints on the table, appends new check constraints
to list, updates state (enforced/not enforced) and drop any existing
check constraint from the list.
@param thd Thread handle.
@param table TABLE instance of source table.
@param alter_info Alter_info object to prepare
list of check constraint spec
for table being altered.
@param alter_tbl_ctx Runtime context for
ALTER TABLE.
@retval false Success.
@retval true Failure.
*/
static bool prepare_check_constraints_for_alter(
THD *thd, const TABLE *table, Alter_info *alter_info,
Alter_table_ctx *alter_tbl_ctx) {
DBUG_TRACE;
MDL_request_list cc_mdl_request_list;
Sql_check_constraint_spec_list new_check_cons_list(thd->mem_root);
uint cc_max_generated_number = 0;
uint table_name_len = strlen(alter_tbl_ctx->table_name);
/*
Do not process check constraint specification list if master is on version
not supporting check constraints feature.
*/
if (is_slave_with_master_without_check_constraints_support(thd)) {
alter_info->check_constraint_spec_list.clear();
return false;
}
auto find_cc_name = [](std::vector<const char *> &names, const char *s) {
auto name = find_if(names.begin(), names.end(), [s](const char *cc_name) {
return !my_strcasecmp(system_charset_info, s, cc_name);
});
return (name != names.end()) ? *name : nullptr;
};
/*
List of check constraint names. Used after acquiring MDL locks on final list
of check constraints to verify if check constraint names conflict with
existing check constraint names.
*/
std::vector<const char *> new_cc_names;
/*
Handle check constraint specifications marked for drop.
Prepare list of check constraint names (Pointer to the constraint name in
Alter_drop instances) marked for drop. List is used to skip constraints
while preparing specification list from existing check constraints and
while adding new check constraints with the same name.
*/
std::vector<const char *> dropped_cc_names;
for (const Alter_drop *drop : alter_info->drop_list) {
if (drop->type != Alter_drop::CHECK_CONSTRAINT) continue;
bool cc_found = false;
if (table->table_check_constraint_list != nullptr) {
for (Sql_table_check_constraint &table_cc :
*table->table_check_constraint_list) {
if (!my_strcasecmp(system_charset_info, table_cc.name().str,
drop->name)) {
dropped_cc_names.push_back(drop->name);
cc_found = true;
break;
}
}
}
if (!cc_found) {
my_error(ER_CHECK_CONSTRAINT_NOT_FOUND, MYF(0), drop->name);
return true;
}
}
/*
Auto-drop check constraint: If check constraint refers to only one column
and that column is marked for drop then drop
check constraint too.
Check constraints marked for auto-drop are added to list of check constraint
(dropped_cc_names) to be dropped.
*/
if (table->table_check_constraint_list != nullptr) {
for (const Alter_drop *drop : alter_info->drop_list) {
if (drop->type == Alter_drop::COLUMN) {
for (Sql_table_check_constraint &table_cc :
*table->table_check_constraint_list) {
if (check_constraint_expr_refers_to_only_column(
table_cc.value_generator()->expr_item, drop->name))
dropped_cc_names.push_back(table_cc.name().str);
}
}
}
}
/*
Prepare check constraint specification for the existing check constraints on
the table.
* Skip check constraint specification marked for drop.
* Get max sequence number for generated names. This is required when
handling new check constraints added to the table.
* If table is renamed, adjust generated check constraint names to use new
table name.
* Create MDL request on all check constraints.
- Also on adjusted check constraint names if table is renamed.
- If database changed then on all check constraints with the new database.
*/
if (table->table_check_constraint_list != nullptr) {
for (auto &table_cc : *table->table_check_constraint_list) {
/*
Push MDL_request for the existing check constraint name.
Note: Notice that this also handles case of dropped constraints.
*/
if (push_check_constraint_mdl_request_to_list(
thd, alter_tbl_ctx->db, table_cc.name().str, cc_mdl_request_list))
return true;
// Skip if constraint is marked for drop.
if (find_cc_name(dropped_cc_names, table_cc.name().str) != nullptr)
continue;
Sql_check_constraint_spec *cc_spec =
new (thd->mem_root) Sql_check_constraint_spec;
if (cc_spec == nullptr) return true; // OOM
bool is_generated_name = dd::is_generated_check_constraint_name(
alter_tbl_ctx->table_name, table_name_len, table_cc.name().str,
table_cc.name().length);
/*
Get number from generated name and update max generated number if
needed.
*/
if (is_generated_name) {
char *end;
uint number =
my_strtoull(table_cc.name().str + table_name_len +
sizeof(dd::CHECK_CONSTRAINT_NAME_SUBSTR) - 1,
&end, 10);
if (number > cc_max_generated_number) cc_max_generated_number = number;
}
// If generated name and table is renamed then update generated name.
if (is_generated_name && alter_tbl_ctx->is_table_name_changed()) {
char *end;
uint number =
my_strtoull(table_cc.name().str + table_name_len +
sizeof(dd::CHECK_CONSTRAINT_NAME_SUBSTR) - 1,
&end, 10);
if (number > cc_max_generated_number) cc_max_generated_number = number;
// Generate new check constraint name.
if (generate_check_constraint_name(thd, alter_tbl_ctx->new_name, number,
cc_spec->name, true))
return true;
} else {
lex_string_strmake(thd->mem_root, &cc_spec->name, table_cc.name().str,
table_cc.name().length);
if (cc_spec->name.str == nullptr) return true; // OOM
}
// check constraint expression.
cc_spec->check_expr = table_cc.value_generator()->expr_item;
// Copy check constraint status.
cc_spec->is_enforced = table_cc.is_enforced();
// Push check constraint to new list.
new_check_cons_list.push_back(cc_spec);
/*
If db is changed then push MDL_request on check constraint with new db
name or if table name is changed then push MDL_request on generated
check constraint name.
*/
if ((alter_tbl_ctx->is_database_changed() ||
(alter_tbl_ctx->is_table_name_changed() && is_generated_name))) {
if (push_check_constraint_mdl_request_to_list(
thd, alter_tbl_ctx->new_db, cc_spec->name.str,
cc_mdl_request_list))
return true;
new_cc_names.push_back(cc_spec->name.str);
}
}
/*
Check if any check constraint refers to column(s) being dropped or
renamed.
*/
if (!new_check_cons_list.empty()) {
// Check if any check constraint refers column(s) being dropped.
if (std::any_of(
alter_info->drop_list.begin(), alter_info->drop_list.end(),
Check_constraint_column_dependency_checker(new_check_cons_list)))
return true;
/*
Check if any check constraint refers column(s) being renamed using
RENAME COLUMN clause.
*/
if (std::any_of(
alter_info->alter_list.begin(), alter_info->alter_list.end(),
Check_constraint_column_dependency_checker(new_check_cons_list)))
return true;
/*
Check if any check constraint refers column(s) being renamed using
CHANGE [COLUMN] clause.
*/
if (std::any_of(
alter_info->create_list.begin(), alter_info->create_list.end(),
Check_constraint_column_dependency_checker(new_check_cons_list)))
return true;
}
}
// Update check constraint enforcement state (i.e. enforced or not enforced).
for (auto *alter_constraint : alter_info->alter_constraint_enforcement_list) {
if (alter_constraint->type !=
Alter_constraint_enforcement::Type::CHECK_CONSTRAINT)
continue;
bool cc_found = false;
for (auto &cc_spec : new_check_cons_list) {
if (!my_strcasecmp(system_charset_info, cc_spec->name.str,
alter_constraint->name)) {
cc_found = true;
// Update status.
cc_spec->is_enforced = alter_constraint->is_enforced;
break;
}
}
if (!cc_found) {
my_error(ER_CHECK_CONSTRAINT_NOT_FOUND, MYF(0), alter_constraint->name);
return true;
}
}
/*
Handle new check constraints added to the table.
* Generate name if name is not specified.
If table already has check constraints with generated name then use
sequence number generated when handling existing check constraint names.
* pre-validate check constraint.
* Prepare MDL request for new check constraints.
*/
for (auto &cc_spec : alter_info->check_constraint_spec_list) {
// If check constraint name is omitted then generate name.
if (cc_spec->name.length == 0) {
if (generate_check_constraint_name(thd, alter_tbl_ctx->new_name,
++cc_max_generated_number,
cc_spec->name, false))
return true;
}
if (cc_spec->pre_validate()) return true;
// Push check constraint to new list.
new_check_cons_list.push_back(cc_spec);
// Create MDL request for the check constraint.
if (push_check_constraint_mdl_request_to_list(
thd, alter_tbl_ctx->new_db, cc_spec->name.str, cc_mdl_request_list))
return true;
/*
We need to check if conflicting constraint name exists for all newly added
constraints. However, we don't need (and it is inconvenient) to do this
if constraint with the same name was dropped by the same ALTER TABLE,
unless old and new constraints belong to different databases (i.e. this
ALTER TABLE also moves table between databases).
*/
if (alter_tbl_ctx->is_database_changed() ||
find_cc_name(dropped_cc_names, cc_spec->name.str) == nullptr)
new_cc_names.push_back(cc_spec->name.str);
}
/*
Adjust Alter_info::flags.
* Check if final list has any check constraint whose state is changed from
NOT ENFORCED to ENFORCED.
* Check if list has any new check constraints added with ENFORCED state.
* Update Alter_info::flags accordingly.
*/
bool final_enforced_state = false;
for (auto &cc : new_check_cons_list) {
// Check if any of existing constraint is enforced.
if (table->table_check_constraint_list != nullptr) {
for (auto &table_cc : *table->table_check_constraint_list) {
if (!my_strcasecmp(system_charset_info, cc->name.str,
table_cc.name().str) &&
!table_cc.is_enforced() && cc->is_enforced) {
final_enforced_state = true;
break;
}
}
}
if (final_enforced_state) break;
// Check if new constraint is added in enforced state.
for (auto &new_cc : alter_info->check_constraint_spec_list) {
if (!my_strcasecmp(system_charset_info, cc->name.str, new_cc->name.str) &&
cc->is_enforced) {
final_enforced_state = true;
break;
}
}
if (final_enforced_state) break;
}
if (final_enforced_state)
alter_info->flags |= Alter_info::ENFORCE_CHECK_CONSTRAINT;
else
alter_info->flags &= ~Alter_info::ENFORCE_CHECK_CONSTRAINT;
/*
Set alter mode for each check constraint specification instance.
For non-temporary table prepare temporary check constraint names. During
ALTER TABLE operation, two versions of table exists and to avoid check
constraint name conflicts temporary(adjusted) names stored for newer
version and alter mode is set. Check constraint names are restored
later in ALTER TABLE operation. MDL request to temporary name is also
created to avoid creation of table with same name by concurrent operation.
* Prepare temporary(adjusted) name for each check constraint specification.
* Set alter mode for each check constraint specification.
* Prepare MDL request for each temporary name.
*/
if (table->s->tmp_table == NO_TMP_TABLE) {
ulong id = 1;
for (Sql_check_constraint_spec *cc : new_check_cons_list) {
const int prefix_len = 3; // #cc
const int process_id_len = 20;
const int thread_id_len = 10;
const int id_len = 20;
const int separator_len = 1;
char temp_name_buf[prefix_len + process_id_len + thread_id_len + id_len +
(separator_len * 3) + 1];
snprintf(temp_name_buf, sizeof(temp_name_buf), "#cc_%lu_%u_%lu",
current_pid, thd->thread_id(), id++);
// Create MDL request for the temp check constraint name.
if (push_check_constraint_mdl_request_to_list(
thd, alter_tbl_ctx->new_db, temp_name_buf, cc_mdl_request_list))
return true;
cc->is_alter_mode = true;
cc->alias_name.length = strlen(temp_name_buf);
cc->alias_name.str =
strmake_root(thd->mem_root, temp_name_buf, cc->alias_name.length);
}
}
// Acquire MDL lock on all the MDL_request prepared in this method.
DEBUG_SYNC(thd, "before_acquiring_lock_on_check_constraints");
if (thd->mdl_context.acquire_locks(&cc_mdl_request_list,
thd->variables.lock_wait_timeout))
return true;
DEBUG_SYNC(thd, "after_acquiring_lock_on_check_constraints");
/*
Make sure new check constraint names do not conflict with any existing check
constraint names before starting expensive ALTER operation.
*/
dd::Schema_MDL_locker mdl_locker(thd);
const dd::Schema *new_schema = nullptr;
dd::cache::Dictionary_client::Auto_releaser releaser(thd->dd_client());
if (mdl_locker.ensure_locked(alter_tbl_ctx->new_db) ||
thd->dd_client()->acquire(alter_tbl_ctx->new_db, &new_schema))
return true;
bool exists = false;
for (auto cc_name : new_cc_names) {
if (thd->dd_client()->check_constraint_exists(*new_schema, cc_name,
&exists))
return true;
if (exists) {
my_error(ER_CHECK_CONSTRAINT_DUP_NAME, MYF(0), cc_name);
return true;
}
}
alter_info->check_constraint_spec_list.clear();
alter_info->check_constraint_spec_list.resize(new_check_cons_list.size());
std::move(new_check_cons_list.begin(), new_check_cons_list.end(),
alter_info->check_constraint_spec_list.begin());
return false;
}
/**
During alter table operation, check constraints of a new table are marked as
in alter mode. If a table object is stored to the data-dictionary in this
mode then alias name is stored to avoid name conflicts due to two versions
of table objects. dd::Table object of a new table read from the
data-dictionary contains only alias name. So dd::Table object of a new table
is patched up here with the real name and alter mode to reflect the fact the
check constraint is in alter_mode as this information is not stored
parsistently.
@param new_table New table definition.
@param alter_info Alter_info object containing list of list of
check constraint spec for table being
altered.
*/
static void set_check_constraints_alter_mode(dd::Table *new_table,
Alter_info *alter_info) {
for (dd::Check_constraint *cc : *new_table->check_constraints()) {
if (cc->is_alter_mode()) continue;
for (Sql_check_constraint_spec *cc_spec :
alter_info->check_constraint_spec_list) {
if (!my_strcasecmp(system_charset_info, cc->name().c_str(),
cc_spec->alias_name.str)) {
cc->set_name(cc_spec->name.str);
cc->set_alias_name(cc_spec->alias_name.str);
cc->set_alter_mode(true);
}
}
}
}
/**
Reset alter mode of check constraints.
Method updates only dd::Table object. It is not stored or updated to
data-dictionary in this method.
@param new_table New table definition.
*/
static void reset_check_constraints_alter_mode(dd::Table *new_table) {
for (dd::Check_constraint *cc : *new_table->check_constraints()) {
assert(cc->is_alter_mode());
cc->set_alter_mode(false);
}
}
/**
Make old table definition's check constraint use temporary names. This is
needed to avoid problems with duplicate check constraint names while we
have two definitions of the same table.
Method updates only dd::Table object. It is not stored or updated to
data-dictionary in this method.
@param thd Thread context.
@param old_table_db Database of old table.
@param old_table Old table definition.
@returns false - Success, true - Failure.
*/
static bool adjust_check_constraint_names_for_old_table_version(
THD *thd, const char *old_table_db, dd::Table *old_table) {
MDL_request_list mdl_requests;
for (dd::Check_constraint *cc : *old_table->check_constraints()) {
const int prefix_len = 4; // #cc_
const int id_len = 20;
char temp_cc_name[prefix_len + id_len + 1];
snprintf(temp_cc_name, sizeof(temp_cc_name), "#cc_%llu",
(ulonglong)cc->id());
/*
Acquire lock on temporary names before updating data-dictionary just in
case somebody tries to create check constraints with same name.
*/
if (push_check_constraint_mdl_request_to_list(thd, old_table_db,
temp_cc_name, mdl_requests))
return true;
// Set adjusted name.
cc->set_name(temp_cc_name);
}
if (thd->mdl_context.acquire_locks(&mdl_requests,
thd->variables.lock_wait_timeout))
return true;
return false;
}
/**
Helper method to check if any check constraints (re-)evaluation is required.
If any check constraint re-evaluation is required then in-place alter is not
possible as it is done in the SQL-layer. This method is called by
is_inplace_alter_impossible() to check inplace alter is possible.
Check constraint (re-)evaluation is required when
1) New check constraint is added in ENFORCED state.
2) Any existing check constraint is ENFORCED.
3) Type of column used by any enforced check constraint is changed.
4) check constraints expression depends on DEFAULT function on a column and
default is changed as part of alter operation.
@param alter_info Data related to detected changes.
@retval true Check constraint (re-)evaluation required.
@retval false Otherwise.
*/
static bool is_any_check_constraints_evaluation_required(
const Alter_info *alter_info) {
/*
Check if any check constraint is added in enforced state or state of any
check is is changed to ENFORCED.
*/
if (alter_info->flags & Alter_info::ENFORCE_CHECK_CONSTRAINT) return true;
for (auto &cc_spec : alter_info->check_constraint_spec_list) {
if (!cc_spec->is_enforced) continue;
/*
if column is modified then check if type is changed or if default value is
changed. Check constraint re-evaluation is required in this case.
*/
if (alter_info->flags & Alter_info::ALTER_CHANGE_COLUMN) {
for (const Create_field &fld : alter_info->create_list) {
// Get fields used by check constraint.
mem_root_deque<Item_field *> fields(current_thd->mem_root);
cc_spec->check_expr->walk(&Item::collect_item_field_processor,
enum_walk::POSTFIX, (uchar *)&fields);
for (Item_field *itm_fld : fields) {
if (itm_fld->type() != Item::FIELD_ITEM || itm_fld->field == nullptr)
continue;
// Check if data type is changed.
if (!my_strcasecmp(system_charset_info, itm_fld->field_name,
fld.field_name) &&
(itm_fld->data_type() != fld.sql_type))
return true;
}
/*
If column is modified then default might have changed. Check if
check constraint uses default function.
*/
if (fld.change &&
cc_spec->check_expr->walk(
&Item::check_gcol_depend_default_processor, enum_walk::POSTFIX,
reinterpret_cast<uchar *>(const_cast<char *>(fld.change))))
return true;
}
}
/*
If column is altered to drop or set default then check any check
constraint using the default function. Re-evaluation of check constraint
is required in this case.
*/
if (alter_info->flags & Alter_info::ALTER_CHANGE_COLUMN_DEFAULT) {
for (auto *alter : alter_info->alter_list) {
if (alter->change_type() == Alter_column::Type::SET_DEFAULT ||
alter->change_type() == Alter_column::Type::DROP_DEFAULT) {
if (cc_spec->check_expr->walk(
&Item::check_gcol_depend_default_processor,
enum_walk::POSTFIX,
reinterpret_cast<uchar *>(const_cast<char *>(alter->name))))
return true;
}
}
}
}
return false;
}
bool lock_check_constraint_names_for_rename(THD *thd, const char *db,
const char *table_name,
const dd::Table *table_def,
const char *target_db,
const char *target_table_name) {
DBUG_TRACE;
MDL_request_list mdl_requests;
size_t table_name_len = strlen(table_name);
// Push lock requests for the check constraints defined on db.table_name.
for (auto &cc : table_def->check_constraints()) {
if (push_check_constraint_mdl_request_to_list(thd, db, cc->name().c_str(),
mdl_requests))
return true;
}
// Push lock request for the check constraints in target table.
for (auto &cc : table_def->check_constraints()) {
const char *cc_name = cc->name().c_str();
/*
If check constraint name is a generated name in the source table then
generate name with the target table to create mdl_request with it.
*/
bool is_generated_name = dd::is_generated_check_constraint_name(
table_name, table_name_len, cc->name().c_str(), cc->name().length());
if (is_generated_name) {
char *end;
uint number =
my_strtoull(cc->name().c_str() + table_name_len +
sizeof(dd::CHECK_CONSTRAINT_NAME_SUBSTR) - 1,
&end, 10);
LEX_STRING name;
if (generate_check_constraint_name(thd, target_table_name, number, name,
true))
return true;
cc_name = name.str;
}
/*
If check constraint name is generated or table moved different database
then create mdl_request with target_db.cc_name.
*/
if ((is_generated_name ||
my_strcasecmp(table_alias_charset, db, target_db)) &&
push_check_constraint_mdl_request_to_list(thd, target_db, cc_name,
mdl_requests))
return true;
}
// Acquire locks on all the collected check constraint names.
if (!mdl_requests.is_empty() &&
thd->mdl_context.acquire_locks(&mdl_requests,
thd->variables.lock_wait_timeout))
return true;
DEBUG_SYNC(thd, "after_acquiring_lock_on_check_constraints_for_rename");
return false;
}
bool lock_check_constraint_names(THD *thd, Table_ref *tables) {
DBUG_TRACE;
MEM_ROOT mdl_reqs_root(key_memory_rm_db_mdl_reqs_root, MEM_ROOT_BLOCK_SIZE);
MDL_request_list mdl_requests;
for (Table_ref *table = tables; table != nullptr; table = table->next_local) {
if (table->open_type != OT_BASE_ONLY && is_temporary_table(table)) continue;
dd::cache::Dictionary_client::Auto_releaser releaser(thd->dd_client());
const dd::Abstract_table *abstract_table_def = nullptr;
if (thd->dd_client()->acquire(table->db, table->table_name,
&abstract_table_def))
return true;
if (abstract_table_def == nullptr ||
abstract_table_def->type() != dd::enum_table_type::BASE_TABLE)
continue;
const dd::Table *table_def =
dynamic_cast<const dd::Table *>(abstract_table_def);
assert(table_def != nullptr);
/*
Ensure that we don't hold memory used by MDL_requests after locks
have been acquired. This reduces memory usage in cases when we have
DROP DATABASE that needs to drop lots of different objects.
*/
MEM_ROOT *save_thd_mem_root = thd->mem_root;
auto restore_thd_mem_root =
create_scope_guard([&]() { thd->mem_root = save_thd_mem_root; });
thd->mem_root = &mdl_reqs_root;
for (auto &cc : table_def->check_constraints()) {
if (push_check_constraint_mdl_request_to_list(
thd, table->db, cc->name().c_str(), mdl_requests))
return false;
}
}
// Acquire MDL lock on all the check constraint names.
if (!mdl_requests.is_empty() &&
thd->mdl_context.acquire_locks(&mdl_requests,
thd->variables.lock_wait_timeout))
return true;
return false;
}
|