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
|
/*
Derby - Class org.apache.derbyTesting.functionTests.tests.lang.ConstraintCharacteristicsTest
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.apache.derbyTesting.functionTests.tests.lang;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Savepoint;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.sql.XAConnection;
import javax.sql.XADataSource;
import javax.transaction.xa.XAException;
import javax.transaction.xa.XAResource;
import javax.transaction.xa.Xid;
import junit.framework.Test;
import org.apache.derby.iapi.services.context.ContextManager;
import org.apache.derby.iapi.sql.conn.LanguageConnectionContext;
import org.apache.derby.impl.jdbc.EmbedConnection;
import org.apache.derby.impl.sql.GenericPreparedStatement;
import org.apache.derbyTesting.junit.BaseJDBCTestCase;
import org.apache.derbyTesting.junit.BaseTestSuite;
import org.apache.derbyTesting.junit.J2EEDataSource;
import org.apache.derbyTesting.junit.JDBC;
import org.apache.derbyTesting.junit.SupportFilesSetup;
import org.apache.derbyTesting.junit.SystemPropertyTestSetup;
import org.apache.derbyTesting.junit.TestConfiguration;
import org.apache.derbyTesting.junit.XATestUtil;
import org.apache.derby.shared.common.error.DerbySQLIntegrityConstraintViolationException;
public class ConstraintCharacteristicsTest extends BaseJDBCTestCase
{
private static final String LANG_DUPLICATE_KEY_CONSTRAINT = "23505";
private static final String LANG_DEFERRED_DUP_VIOLATION_T = "23506";
private static final String LANG_DEFERRED_DUP_VIOLATION_S = "23507";
private static final String LANG_CHECK_CONSTRAINT_VIOLATED = "23513";
private static final String LANG_DEFERRED_CHECK_VIOLATION_T = "23514";
private static final String LANG_DEFERRED_CHECK_VIOLATION_S = "23515";
private static final String LANG_DEFERRED_FK_VIOLATION_T = "23516";
private static final String LANG_DEFERRED_FK_VIOLATION_S = "23517";
private static final String LOCK_TIMEOUT = "40XL1";
private static final String LANG_INCONSISTENT_C_CHARACTERISTICS = "42X97";
private static final String LANG_DROP_OR_ALTER_NON_EXISTING_C = "42X86";
private static final String LANG_SYNTAX_ERROR = "42X01";
private static final String NOT_IMPLEMENTED = "0A000";
private static final String LANG_NOT_NULL_CHARACTERISTICS = "42XAN";
private static final String LANG_OBJECT_NOT_FOUND = "42X94";
private static final String LANG_DB2_DUPLICATE_NAMES = "42734";
private static final String LANG_ADD_CHECK_CONSTRAINT_FAILED = "X0Y59";
private static String expImpDataFile; // file used to perform
// import/export
private static String expImpDataWithNullsFile; // file used to perform
// import/export
private static boolean exportFilesCreatedEmbedded = false;
private static boolean exportFilesCreatedClient = false;
private static final int WAIT_TIMEOUT_DURATION = 1;
public ConstraintCharacteristicsTest(String name) {
super(name);
}
public static Test suite() {
final String nameRoot = ConstraintCharacteristicsTest.class.getName();
final BaseTestSuite suite = new BaseTestSuite(nameRoot);
suite.addTest(baseSuite1(nameRoot + ":embedded 1"));
suite.addTest(TestConfiguration.clientServerDecorator(
baseSuite1(nameRoot + ":client 1")));
suite.addTest(baseSuite2(nameRoot + ":embedded 2"));
suite.addTest(TestConfiguration.clientServerDecorator(
baseSuite2(nameRoot + ":client 2")));
suite.addTest(baseSuite3(nameRoot + ":embedded 3"));
suite.addTest(TestConfiguration.clientServerDecorator(
baseSuite3(nameRoot + ":client 3")));
return suite;
}
// this suite holds tests that require a more optimal
// locks.waitTimeout setting.
private static Test baseSuite3(final String name) {
final BaseTestSuite suite = new BaseTestSuite(name);
suite.addTest(new ConstraintCharacteristicsTest(
"testDeferredRowsInvalidation"));
suite.addTest(new ConstraintCharacteristicsTest(
"testLockingForUniquePK"));
final Properties systemProperties = new Properties();
systemProperties.setProperty(
"derby.locks.waitTimeout", Integer.toString(WAIT_TIMEOUT_DURATION));
return new SupportFilesSetup(
new SystemPropertyTestSetup(suite, systemProperties, true));
}
private static Test baseSuite2(final String name) {
final BaseTestSuite suite = new BaseTestSuite(name);
final Properties systemProperties = new Properties();
systemProperties.setProperty("derby.language.logQueryPlan", "true");
suite.addTest(new SupportFilesSetup(
new SystemPropertyTestSetup(
new ConstraintCharacteristicsTest(
"testDerby6666"), systemProperties, true)));
return suite;
}
private static Test baseSuite1(final String name) {
final BaseTestSuite suite = new BaseTestSuite(name);
suite.addTest(new ConstraintCharacteristicsTest(
"testSyntaxAndBinding"));
suite.addTest(new ConstraintCharacteristicsTest(
"testDropNotNullOnUniqueColumn"));
suite.addTest(new ConstraintCharacteristicsTest(
"testCompressTableOKUnique"));
suite.addTest(new ConstraintCharacteristicsTest(
"testLockingForUniquePKWithCommit"));
suite.addTest(new ConstraintCharacteristicsTest(
"testLockingForUniquePKWithRollback"));
suite.addTest(new ConstraintCharacteristicsTest(
"testDatabaseMetaData"));
suite.addTest(new ConstraintCharacteristicsTest(
"testCreateConstraintDictionaryEncodings"));
suite.addTest(new ConstraintCharacteristicsTest(
"testAlterConstraintDictionaryEncodings"));
suite.addTest(new ConstraintCharacteristicsTest(
"testAlterConstraintInvalidation"));
suite.addTest(new ConstraintCharacteristicsTest(
"testBasicDeferral"));
suite.addTest(new ConstraintCharacteristicsTest(
"testRoutines"));
suite.addTest(new ConstraintCharacteristicsTest(
"testImport"));
suite.addTest(new ConstraintCharacteristicsTest(
"testDerby6374"));
suite.addTest(new ConstraintCharacteristicsTest(
"testXA"));
suite.addTest(new ConstraintCharacteristicsTest(
"testAlmostRemovedAllDups"));
suite.addTest(new ConstraintCharacteristicsTest(
"testCheckConstraintsWithDeferredRows"));
suite.addTest(new ConstraintCharacteristicsTest(
"testSeveralCheckConstraints"));
suite.addTest(new ConstraintCharacteristicsTest(
"testDerby6670_a"));
suite.addTest(new ConstraintCharacteristicsTest(
"testDerby6670_b"));
suite.addTest(new ConstraintCharacteristicsTest(
"testManySimilarDuplicates"));
suite.addTest(new ConstraintCharacteristicsTest(
"testDerby6773"));
final Properties systemProperties = new Properties();
systemProperties.setProperty(
"derby.locks.waitTimeout", Integer.toString(500));
return new SupportFilesSetup(
new SystemPropertyTestSetup(suite, systemProperties, true));
}
@Override
protected void setUp() throws Exception {
super.setUp();
final Statement s = createStatement();
s.executeUpdate("create table referenced(" +
" i int primary key, j int default 0)");
if ((usingEmbedded() && !exportFilesCreatedEmbedded) ||
(usingDerbyNetClient() && !exportFilesCreatedClient)) {
// We have to do this once for embedded and once for client/server
if (usingEmbedded()) {
exportFilesCreatedEmbedded = true;
} else {
exportFilesCreatedClient = true;
}
// Create a file for import that contains duplicate rows,
// see testImport and testDerby6374.
//
expImpDataFile =
SupportFilesSetup.getReadWrite("t.data").getPath();
expImpDataWithNullsFile =
SupportFilesSetup.getReadWrite("t_with_nulls.data").getPath();
s.executeUpdate("create table t(i int)");
s.executeUpdate("insert into t values 1,-2,-2, 3");
s.executeUpdate("create table t_with_nulls(i int)");
s.executeUpdate("insert into t_with_nulls values 1,null, null, 3");
s.executeUpdate(
"call SYSCS_UTIL.SYSCS_EXPORT_TABLE (" +
" 'APP' , 'T' , '" + expImpDataFile + "'," +
" null, null , null)");
s.executeUpdate(
"call SYSCS_UTIL.SYSCS_EXPORT_TABLE (" +
" 'APP' , 'T_WITH_NULLS' , '" + expImpDataWithNullsFile +
"', null, null , null)");
s.executeUpdate("drop table t");
s.executeUpdate("drop table t_with_nulls");
}
s.close();
setAutoCommit(false);
}
@Override
protected void tearDown() throws Exception {
rollback();
setAutoCommit(true);
getConnection().createStatement().
executeUpdate("drop table referenced");
super.tearDown();
}
public void testSyntaxAndBinding() throws SQLException {
final Connection c = getConnection();
final Statement s = c.createStatement();
//
// T A B L E L E V E L C O N S T R A I N T S
//
assertTableLevelDefaultBehaviorAccepted(c, s);
assertTableLevelNonDefaultAccepted(s);
//
// A L T E R C O N S T R A I N T C H A R A C T E R I S T I C S
//
s.executeUpdate(
"create table t(i int, constraint app.c primary key(i))");
// default, so allow
s.executeUpdate("alter table t alter constraint c enforced");
// not default behavior, expect error until feature implemented
assertStatementError(
NOT_IMPLEMENTED, s,
"alter table t alter constraint c not enforced");
for (String ch : illegalAlterCharacteristics) {
// Anything beyond enforcement is illegal in ALTER context
assertStatementError(
LANG_SYNTAX_ERROR, s, "alter table t alter constraint c " + ch);
}
// Unknown constraint name
assertStatementError(
LANG_DROP_OR_ALTER_NON_EXISTING_C, s,
"alter table t alter constraint cuckoo not enforced");
//
// S E T C O N S T R A I N T
//
s.executeUpdate("alter table t drop constraint c");
s.executeUpdate("alter table t add constraint c " +
" primary key(i) deferrable");
s.executeUpdate("set constraints c deferred");
s.executeUpdate("set constraints all deferred");
// Unknown constraint name
assertStatementError(LANG_OBJECT_NOT_FOUND, s,
"set constraints cuckoo deferred");
assertStatementError(LANG_DB2_DUPLICATE_NAMES , s,
"set constraints c,c deferred");
c.rollback();
//
// C O L U M N L E V E L C O N S T R A I N T S
//
assertColumnLevelDefaultBehaviorAccepted(c, s);
assertColumnLevelNonDefaultAccepted(s);
// Characteristics are not currently allowed for NOT NULL,
// since Derby does not represent NOT NULL as a constraint,
// but rather as an aspect of the column's data type. It is
// possible to alter the column nullable and vice versa,
// though.
assertStatementError(LANG_NOT_NULL_CHARACTERISTICS, s,
"create table t(i int " +
"not null deferrable initially immediate)");
}
/**
* Check that constraint characteristics are correctly encoded
* into the STATE column in SYS.SYSCONSTRAINTS.
* Cf. specification attached to DERBY-532.
*
* FIXME: Note that this test runs with property derby.constraintsTesting
* to bypass NOT IMPLEMENTED checks. Remove this property usage when
* DERBY-532 is done.
* @throws SQLException
*/
public void testCreateConstraintDictionaryEncodings() throws SQLException {
final Statement s = getConnection().createStatement();
for (String[] ch : defaultCharacteristics) {
assertDictState(s, ch[0], ch[1]);
}
for (String[] ch : nonDefaultCharacteristics) {
assertDictState(s, ch[0], ch[1]);
}
for (String ch : illegalCharacteristics) {
assertCreateInconsistentCharacteristics(s, ch);
}
rollback();
}
/**
* Check that constraint characteristics are correctly encoded
* into the STATE column in SYS.SYSCONSTRAINTS.
* Cf. specification attached to DERBY-532.
*
* FIXME: Note that this test runs with property derby.constraintsTesting
* to bypass NOT IMPLEMENTED checks. Remove this property usage when
* DERBY-532 is done.
* @throws SQLException
*/
public void testAlterConstraintDictionaryEncodings() throws SQLException {
final Statement s = getConnection().createStatement();
for (String[] ch : defaultCharacteristics) {
s.executeUpdate(
"create table t(i int, constraint c primary key(i) " +
ch[0] + ")");
assertAlterDictState(s, "enforced");
assertAlterDictState(s, "not enforced");
rollback();
}
for (String[] ch : nonDefaultCharacteristics) {
if (ch[0].contains("not enforced")) {
assertStatementError(NOT_IMPLEMENTED,
s,
"create table t(i int, constraint c primary key(i) " +
ch[0] + ")");
} else {
s.executeUpdate(
"create table t(i int, constraint c primary key(i) " +
ch[0] + ")");
assertAlterDictState(s, "enforced");
assertAlterDictState(s, "not enforced");
rollback();
}
}
for (String ch : illegalAlterCharacteristics) {
assertAlterInconsistentCharacteristics(s, ch);
}
}
/**
* Check that altering constraint characteristics invalidates prepared
* statements.
* @throws SQLException
*/
public void testAlterConstraintInvalidation() throws SQLException {
if (usingDerbyNetClient()) {
// Skip, since we need to see inside an embedded connection here
return;
}
final Connection c = getConnection();
final Statement s = createStatement();
s.executeUpdate("create table t(i int, constraint c primary key(i))");
final PreparedStatement ps =
c.prepareStatement("insert into t values 3");
ps.execute();
s.executeUpdate("alter table t alter constraint c enforced ");
final LanguageConnectionContext lcc = getLCC( c );
final GenericPreparedStatement derbyPs =
(GenericPreparedStatement)lcc.getLastActivation().
getPreparedStatement();
assertFalse(derbyPs.isValid());
rollback();
}
static final String[] uniqueForms = {
"create table t(i int, j int, constraint c primary key(i)",
"create table t(i int, j int, constraint c unique(i)",
"create table t(i int not null, j int, constraint c unique(i)"};
static final String[] uniqueSpec = { // corresponding to above forms
"primary key(i)",
"unique(i)",
"unique(i)"};
static final String[] checkForms = {
"create table t(i int, j int, constraint c check (i > 0)"};
static final String[] fkForms = {
"create table t(i int, j int, " +
" constraint c foreign key(i) references referenced(i)"};
static final String[] checkSpec = { // corresponding to above forms
"check (i > 0)"};
static final String[][] initialContents = new String[][] {
{"1", "10"},
{"2", "20"},
{"3", "30"}};
static final String[][] negatedInitialContents = new String[][] {
{"-1", "10"},
{"-2", "20"},
{"-3", "30"}};
static final String[] setConstraintsForms = {
"set constraints all",
"set constraints c"};
public void testDatabaseMetaData() throws SQLException {
// Test that our constraint backing index is still reported as unique
// even if we implement it as physically non-unique when deferrable:
// logically it is still a unique index.
final Statement s = createStatement();
s.executeUpdate(
"create table t(i int not null " +
" constraint c primary key deferrable initially immediate)");
final DatabaseMetaData dbmd = s.getConnection().getMetaData();
ResultSet rs = dbmd.getIndexInfo(null, null, "T", false, false);
rs.next();
assertEquals("false", rs.getString("NON_UNIQUE"));
// Test that we get the right values for DEFERRABILITY in
// getImportedKeys, getExportedKeys and getCrossReference
String[] cchars = new String[]{
"deferrable initially immediate",
"deferrable initially deferred",
"not deferrable"
};
int[] dbmdState = new int[]{
DatabaseMetaData.importedKeyInitiallyImmediate,
DatabaseMetaData.importedKeyInitiallyDeferred,
DatabaseMetaData.importedKeyNotDeferrable,
};
for (int i = 0; i < cchars.length; i++) {
s.executeUpdate(
"create table child(i int, constraint c2 foreign key(i) " +
" references t(i) " + cchars[i] + ")");
rs = dbmd.getImportedKeys(null, null, "CHILD");
rs.next();
assertEquals(
Integer.toString(dbmdState[i]),
rs.getString("DEFERRABILITY"));
rs.close();
rs = dbmd.getExportedKeys(null, null, "T");
rs.next();
assertEquals(
Integer.toString(dbmdState[i]),
rs.getString("DEFERRABILITY"));
rs.close();
rs = dbmd.getCrossReference(null, null, "T", null, null, "CHILD");
rs.next();
assertEquals(
Integer.toString(dbmdState[i]),
rs.getString("DEFERRABILITY"));
rs.close();
s.executeUpdate("drop table child");
}
}
public void testLockingForUniquePK() throws SQLException {
final Statement s = createStatement();
s.executeUpdate(
"create table t1(i int, " +
"constraint c1 primary key(i) not deferrable)");
s.executeUpdate(
"create table t2(i int, " +
"constraint c2 primary key(i) deferrable initially deferred)");
s.executeUpdate("insert into t1 values 1,2,3");
s.executeUpdate("insert into t2 values 1,2,3");
commit();
//
// Locks for PK insert, not deferrable
//
// There is an X row lock on the inserted row.
//
s.executeUpdate("insert into t1 values 4");
ResultSet rs = s.executeQuery(
LockTableTest.getSelectLocksString());
JDBC.assertFullResultSet(rs, new String[][]{
{"APP", "UserTransaction", "TABLE", "2",
"IX", "T1", "Tablelock", "GRANT", "ACTIVE"},
{"APP", "UserTransaction", "ROW", "1",
"X", "T1", "(1,10)", "GRANT", "ACTIVE"}
});
Connection c2 = null;
try {
// Verify that another transaction has to wait
c2 = openDefaultConnection();
c2.setAutoCommit(false);
final Statement s2 = c2.createStatement();
assertStatementError(LOCK_TIMEOUT, s2, "insert into t1 values 4");
} finally {
if (c2 != null) {
c2.rollback();
c2.close();
}
}
commit();
//
// Locks for PK insert, deferrable, not a duplicate.
//
s.executeUpdate("insert into t2 values 4");
rs = s.executeQuery(
LockTableTest.getSelectLocksString());
JDBC.assertFullResultSet(rs, new String[][]{
{"APP", "UserTransaction", "TABLE", "1",
"IS", "T2", "Tablelock", "GRANT", "ACTIVE"},
{"APP", "UserTransaction", "TABLE", "2",
"IX", "T2", "Tablelock", "GRANT", "ACTIVE"},
{"APP", "UserTransaction", "ROW", "1",
"X", "T2", "(1,10)", "GRANT", "ACTIVE"}});
commit();
//
// Locks for PK insert, deferrable and a duplicate
//
s.executeUpdate("insert into t2 values 4");
rs = s.executeQuery(
LockTableTest.getSelectLocksString());
JDBC.assertFullResultSet(rs, new String[][]{
{"APP", "UserTransaction", "TABLE", "1",
"IS", "T2", "Tablelock", "GRANT", "ACTIVE"},
{"APP", "UserTransaction", "TABLE", "2",
"IX", "T2", "Tablelock", "GRANT", "ACTIVE"},
{"APP", "UserTransaction", "ROW", "1",
"X", "T2", "(1,11)", "GRANT", "ACTIVE"}});
try {
// Verify that another transaction doesn't have to wait on insert
// It will see a timeout and assume a duplicate for checking on
// commit, which in this case will see the timeout instead.
c2 = openDefaultConnection();
c2.setAutoCommit(false);
final Statement s2 = c2.createStatement();
s2.executeUpdate("insert into t2 values 4");
assertCommitError(LOCK_TIMEOUT, c2);
} finally {
try {
if (c2 != null) {
c2.rollback();
c2.close();
}
} catch (SQLException e) {
}
}
rollback();
// Thread 1: insert a row (not a duplicate)
s.executeUpdate("insert into t2 values 5");
// Thread 2: insert same row (duplicate)
c2 = openDefaultConnection();
c2.setAutoCommit(false);
final Statement s2 = c2.createStatement();
s2.executeUpdate("insert into t2 values 5");
// Thread 1: try to commit: should not time out we are not doing
// a checking scan here
commit();
c2.rollback();
//
// Let a thread 2 insert a key before and after a key inserted by t1.
// t1 should be able to commit without waiting because the checking
// scan should not see the rows locked before and after t1's key
// (read committed mode).
//
s2.executeUpdate("insert into t2 values 10,12");
// Insert a duplicate,
s.executeUpdate("insert into t2 values 11,11");
// next delete one of the duplicates,
final Statement us = createStatement(
ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_UPDATABLE);
rs = us.executeQuery("select * from t2 where i=11");
rs.next();
rs.deleteRow();
rs.close();
// then try to commit.
commit();
// clean up
c2.rollback();
c2.close();
s.executeUpdate("drop table t1");
s.executeUpdate("drop table t2");
commit();
}
public void testBasicDeferral() throws SQLException {
final Statement s = createStatement();
for (String sCF : setConstraintsForms) {
int idx = 0;
//
// P R I M A R Y K E Y, U N I Q U E C O N S T R A I N T S
//
for (String ct : uniqueForms) {
try {
s.executeUpdate(
ct + " deferrable initially immediate)");
s.executeUpdate(
"insert into t values " + rs2Values(initialContents));
commit();
//
// I N S E R T O F D U P L I C A T E S
//
// Normal duplicate insert should fail, still
// immediate mode
assertStatementError(LANG_DUPLICATE_KEY_CONSTRAINT,
s,
"insert into t values (2,30)");
// Now set deferred mode in one of two ways: by specifying
// ALL or by naming our index explicitly.
s.executeUpdate(sCF + " deferred");
// Duplicate insert should now work
s.executeUpdate(
"insert into t values (2,19),(2,21),(3,31)");
// Check contents
JDBC.assertFullResultSet(
s.executeQuery("select * from t"),
new String[][] {
{"1", "10"},
{"2", "20"},
{"3", "30"},
{"2", "19"},
{"2", "21"},
{"3", "31"}});
// Check contents: specify ORDER BY and force use of index
// use the index.
JDBC.assertFullResultSet(
s.executeQuery(
"select * from t --DERBY-PROPERTIES constraint=c\n" +
" order by i"),
new String[][] {
{"1", "10"},
{"2", "20"},
{"2", "19"},
{"2", "21"},
{"3", "30"},
{"3", "31"}});
// Try to set immediate mode, and detect violation
assertStatementError(LANG_DEFERRED_DUP_VIOLATION_S,
s,
sCF + " immediate");
// Once more, error above should not roll back
assertStatementError(LANG_DEFERRED_DUP_VIOLATION_S,
s,
sCF + " immediate");
// Now try to commit, which should lead to rollback
assertCommitError(LANG_DEFERRED_DUP_VIOLATION_T,
getConnection());
// Verify that contents are the same as before we did the
// duplicate inserts
JDBC.assertFullResultSet(
s.executeQuery("select * from t"), initialContents);
// Setting immediate now should work again:
s.executeUpdate(sCF + " immediate");
assertStatementError(LANG_DUPLICATE_KEY_CONSTRAINT,
s,
"insert into t values (2,30)");
// setting deferred again:
s.executeUpdate(sCF + " deferred");
// Duplicate insert should now work
s.executeUpdate(
"insert into t values (2,19),(2,21),(3,31)");
assertStatementError(LANG_DEFERRED_DUP_VIOLATION_S,
s,
sCF + " immediate");
rollback();
//
// U P D A T E G I V I N G D U P L I C A T E S
//
// Now set deferred mode in one of two ways: by specifying
// ALL or by naming our constraint explicitly.
s.executeUpdate(sCF + " deferred");
// Now test the same, but using UPDATE instead of INSERT
s.executeUpdate(
"insert into t values (20,19),(200,21),(30,31)");
s.executeUpdate("update t set i=2 where i=20");
s.executeUpdate("update t set i=2 where i=200");
s.executeUpdate("update t set i=3 where i=30");
// Check result: specify ORDER BY and force use of index
// use the index
JDBC.assertFullResultSet(
s.executeQuery(
"select * from t --DERBY-PROPERTIES constraint=c\n" +
" order by i"),
new String[][] {
{"1", "10"},
{"2", "20"},
{"2", "19"},
{"2", "21"},
{"3", "30"},
{"3", "31"}});
// Now try to commit, which should lead to rollback
assertCommitError(LANG_DEFERRED_DUP_VIOLATION_T,
getConnection());
// Verify that contents are the same as before we did the
// duplicate updates
JDBC.assertFullResultSet(
s.executeQuery("select * from t"), initialContents);
// Specify ORDER BY and force use of index use the index
JDBC.assertFullResultSet(s.executeQuery(
"select * from t --DERBY-PROPERTIES constraint=c\n" +
" order by i"),
initialContents);
checkConsistencyOfBaseTableAndIndex(s);
// Test add of a deferred constraint to an existing table
s.execute("alter table t drop constraint c");
// Insert duplicates: no constraint now
s.executeUpdate(
"insert into t values (2,19),(2,21),(3,31)");
commit();
// We can't add a constraint with immediate checking
// because of the existing duplicates.
assertStatementError(
LANG_DUPLICATE_KEY_CONSTRAINT,
s,
"alter table t add constraint c " + uniqueSpec[idx]);
// But we can add a deferred constraint:
s.executeUpdate(
"alter table t add constraint c " +
uniqueSpec[idx] + " deferrable initially deferred");
// Specify ORDER BY and force use of index use the index
JDBC.assertFullResultSet(
s.executeQuery(
"select * from t --DERBY-PROPERTIES constraint=c\n" +
" order by i"),
new String[][] {
{"1", "10"},
{"2", "20"},
{"2", "19"},
{"2", "21"},
{"3", "30"},
{"3", "31"}});
// But since we still have duplicates, the commit will fail
assertCommitError(LANG_DEFERRED_DUP_VIOLATION_T,
getConnection());
checkConsistencyOfBaseTableAndIndex(s);
} finally {
idx++;
dropTable("t");
commit();
}
}
//
// C H E C K C O N S T R A I N T S
//
idx = 0;
for (String ct : checkForms) {
try {
s.executeUpdate(
ct + " deferrable initially immediate)");
s.executeUpdate(
"insert into t values " + rs2Values(initialContents));
commit();
//
// I N S E R T O F V I O L A T I N G R O W S
//
// Normal duplicate insert should fail, still
// immediate mode
assertStatementError(LANG_CHECK_CONSTRAINT_VIOLATED,
s,
"insert into t values (-2,30)");
// Test the DERBY-6773 support:
try {
s.execute( "insert into t values (-2,30)" );
fail();
}
catch ( DerbySQLIntegrityConstraintViolationException dsicve ) {
assertSQLState(LANG_CHECK_CONSTRAINT_VIOLATED, dsicve);
assertEquals( "\"APP\".\"T\"", dsicve.getTableName() );
assertEquals( "C", dsicve.getConstraintName() );
}
// Now set deferred mode in one of two ways: by specifying
// ALL or by naming our index explicitly.
s.executeUpdate(sCF + " deferred");
// Rows violating CHECK constraint should now work
s.executeUpdate(
"insert into t values (-2,30),(1,31),(-3,32)");
// Check contents
JDBC.assertFullResultSet(
s.executeQuery("select * from t"),
new String[][] {
{"1", "10"},
{"2", "20"},
{"3", "30"},
{"-2", "30"},
{"1", "31"},
{"-3", "32"}});
// Try to set immediate mode, and detect violation
assertStatementError(LANG_DEFERRED_CHECK_VIOLATION_S,
s,
sCF + " immediate");
// Once more, error above should not roll back
assertStatementError(LANG_DEFERRED_CHECK_VIOLATION_S,
s,
sCF + " immediate");
// Test the DERBY-6773 support:
try {
s.execute( sCF + " immediate" );
fail();
}
catch ( DerbySQLIntegrityConstraintViolationException dsicve ) {
assertSQLState(LANG_DEFERRED_CHECK_VIOLATION_S, dsicve);
assertEquals( "\"APP\".\"T\"", dsicve.getTableName() );
assertEquals( "C", dsicve.getConstraintName() );
}
// Now try to commit, which should lead to rollback
//assertCommitError(LANG_DEFERRED_CHECK_VIOLATION_T,
// getConnection());
// Test the DERBY-6773 support:
try {
getConnection().commit();
fail();
}
catch ( DerbySQLIntegrityConstraintViolationException dsicve ) {
assertSQLState(LANG_DEFERRED_CHECK_VIOLATION_T, dsicve);
assertEquals( "\"APP\".\"T\"", dsicve.getTableName() );
assertEquals( "C", dsicve.getConstraintName() );
}
// Verify that contents are the same as before we did the
// duplicate inserts
JDBC.assertFullResultSet(
s.executeQuery("select * from t"), initialContents);
// Setting immediate now should work again:
s.executeUpdate(sCF + " immediate");
assertStatementError(LANG_CHECK_CONSTRAINT_VIOLATED,
s,
"insert into t values (-2,30)");
// setting deferred again:
s.executeUpdate(sCF + " deferred");
// Insert with check violations should now work
s.executeUpdate(
"insert into t values (-2,19),(2,21),(-3,31)");
assertStatementError(LANG_DEFERRED_CHECK_VIOLATION_S,
s,
sCF + " immediate");
rollback();
//
// U P D A T E G I V I N G V I O L A T I N G R O W S
//
// Now set deferred mode in one of two ways: by specifying
// ALL or by naming our constraint explicitly.
s.executeUpdate(sCF + " deferred");
// Now test the same, but using UPDATE instead of INSERT
s.executeUpdate(
"insert into t values (20,19),(200,21),(30,31)");
s.executeUpdate("update t set i=-2 where i=20");
s.executeUpdate("update t set i=-3 where i=200");
s.executeUpdate("update t set i=-4 where i=30");
// Check result
JDBC.assertFullResultSet(
s.executeQuery(
"select * from t order by j"),
new String[][] {
{"1", "10"},
{"-2", "19"},
{"2", "20"},
{"-3", "21"},
{"3", "30"},
{"-4", "31"}});
// Now try to commit, which should lead to rollback
assertCommitError(LANG_DEFERRED_CHECK_VIOLATION_T,
getConnection());
// Verify that contents are the same as before we did the
// duplicate inserts
JDBC.assertFullResultSet(
s.executeQuery("select * from t"), initialContents);
JDBC.assertFullResultSet(s.executeQuery(
"select * from t order by i"),
initialContents);
checkConsistencyOfBaseTableAndIndex(s);
// Test add of a deferred constraint to an existing table
s.execute("alter table t drop constraint c");
// Insert "violating" rows: no constraint now
s.executeUpdate(
"insert into t values (-2,19),(2,21),(-3,31)");
commit();
// We can't add a constraint with immediate checking
// because of the existing violations..
assertStatementError(
LANG_ADD_CHECK_CONSTRAINT_FAILED,
s,
"alter table t add constraint c " + checkSpec[idx]);
// But we can add a deferred constraint:
s.executeUpdate(
"alter table t add constraint c " +
checkSpec[idx] + " deferrable initially deferred");
JDBC.assertFullResultSet(
s.executeQuery(
"select * from t order by i,j"),
new String[][] {
{"-3", "31"},
{"-2", "19"},
{"1", "10"},
{"2", "20"},
{"2", "21"},
{"3", "30"}});
// But since we still have violations, the commit will fail
assertCommitError(LANG_DEFERRED_CHECK_VIOLATION_T,
getConnection());
checkConsistencyOfBaseTableAndIndex(s);
} finally {
idx++;
dropTable("t");
commit();
}
}
}
}
/**
* Test that if the constraint mode is immediate and a routine has changed
* this to introduce duplicates, we raise an error and roll back on exit
* from the routine.
* @throws SQLException
*/
public void testRoutines() throws SQLException {
final Statement s = createStatement();
//
// P R I M A R Y K E Y, U N I Q U E C O N S T R A I N T S
//
// Caller has not explicitly done any "SET CONSTRAINTS", but
// constraint is initially immediate
for (String ct : uniqueForms) {
try {
s.executeUpdate(
ct + " deferrable initially immediate)");
s.executeUpdate(
"insert into t values " + rs2Values(initialContents));
commit();
declareCalledNested(s);
assertStatementError(
LANG_DEFERRED_DUP_VIOLATION_T,
s,
"call calledNested(false)");
} finally {
dropTable("t");
}
}
// Constraint is initially deferred, but mode then set to immediate
// before the call
for (String setConstraintForm : setConstraintsForms) {
for (String ct : uniqueForms) {
try {
s.executeUpdate(
ct + " deferrable initially deferred)");
s.executeUpdate(
"insert into t values " + rs2Values(initialContents));
commit();
s.executeUpdate(setConstraintForm + " immediate");
declareCalledNested(s);
assertStatementError(LANG_DEFERRED_DUP_VIOLATION_T,
s,
"call calledNested(false)");
} finally {
dropTable("t");
commit();
}
}
}
// Check that we don't bark if we actually introduced the duplicates
// in the caller session context
for (String ct : uniqueForms) {
try {
s.executeUpdate(
ct + " deferrable initially deferred)");
s.executeUpdate(
"insert into t values " + rs2Values(initialContents));
s.executeUpdate(
"insert into t values " + rs2Values(initialContents));
declareCalledNested(s);
s.executeUpdate("call calledNested(false)");
} finally {
rollback();
}
}
//
// C H E C K C O N S T R A I N T S
//
for (String ct : checkForms) {
try {
s.executeUpdate(
ct + " deferrable initially immediate)");
s.executeUpdate(
"insert into t values " + rs2Values(initialContents));
commit();
declareCalledNested(s);
assertStatementError(
LANG_DEFERRED_CHECK_VIOLATION_T,
s,
"call calledNested(true)");
} finally {
dropTable("t");
commit();
}
}
// Constraint is initially deferred, but mode then set to immediate
// before the call
for (String setConstraintForm : setConstraintsForms) {
for (String ct : checkForms) {
try {
s.executeUpdate(
ct + " deferrable initially deferred)");
s.executeUpdate(
"insert into t values " + rs2Values(initialContents));
commit();
s.executeUpdate(setConstraintForm + " immediate");
declareCalledNested(s);
assertStatementError(LANG_DEFERRED_CHECK_VIOLATION_T,
s,
"call calledNested(true)");
} finally {
dropTable("t");
commit();
}
}
}
// Check that we don't bark if we actually introduced the violations
// in the caller session context
for (String ct : checkForms) {
try {
s.executeUpdate(ct + " deferrable initially deferred)");
s.executeUpdate("insert into t values " +
rs2Values(negatedInitialContents));
declareCalledNested(s);
s.executeUpdate("call calledNested(true)");
} finally {
rollback();
}
}
// Check what happens if routine set mode to immediate with
// deferred rows inserted by caller
for (String ct : checkForms) {
try {
s.executeUpdate(
ct + " deferrable initially deferred)");
s.executeUpdate(
"insert into t values " + rs2Values(negatedInitialContents));
declareCalledNestedSetImmediate(s);
assertStatementError(LANG_DEFERRED_CHECK_VIOLATION_S,
s, "call calledNestedSetImmediate()");
} finally {
rollback();
}
}
//
// F O R E I G N K E Y C O N S T R A I N T S
//
for (String ct : fkForms) {
try {
s.executeUpdate(
ct + " deferrable initially immediate)");
s.executeUpdate("insert into referenced values " +
rs2Values(initialContents));
s.executeUpdate(
"insert into t values " + rs2Values(initialContents));
commit();
declareCalledNestedFk(s);
assertStatementError(
LANG_DEFERRED_FK_VIOLATION_T,
s,
"call calledNestedFk()");
} finally {
dropTable("t");
dontThrow(s, "delete from referenced");
commit();
}
}
// Constraint is initially deferred, but mode then set to immediate
// before the call
for (String setConstraintForm : setConstraintsForms) {
for (String ct : fkForms) {
try {
s.executeUpdate(
ct + " deferrable initially deferred)");
s.executeUpdate(
"insert into t values " + rs2Values(initialContents));
s.executeUpdate(
"insert into referenced(i) select i from t");
commit();
s.executeUpdate(setConstraintForm + " immediate");
declareCalledNestedFk(s);
assertStatementError(LANG_DEFERRED_FK_VIOLATION_T,
s,
"call calledNestedFk()");
} finally {
dropTable("t");
dontThrow(s, "delete from referenced");
commit();
}
}
}
// Check that we don't bark if we actually introduced the violations
// in the caller session context
for (String ct : fkForms) {
try {
s.executeUpdate(
ct + " deferrable initially deferred)");
s.executeUpdate(
"insert into t values " + rs2Values(initialContents));
declareCalledNestedFk(s);
s.executeUpdate("call calledNestedFk()");
assertCommitError(LANG_DEFERRED_FK_VIOLATION_T,
getConnection());
} finally {
rollback();
}
}
// Check what happens if routine set mode to immediate with
// deferred rows inserted by caller
for (String ct : fkForms) {
try {
s.executeUpdate(
ct + " deferrable initially deferred)");
s.executeUpdate(
"insert into t values " + rs2Values(initialContents));
declareCalledNestedSetImmediate(s);
assertStatementError(LANG_DEFERRED_FK_VIOLATION_S, s,
"call calledNestedSetImmediate()");
} finally {
rollback();
}
}
}
public void testDeferredRowsInvalidation() throws SQLException {
final Statement s = createStatement();
//
// U N I Q U E, P R I M A R Y K E Y C O N S T R A I N T
//
// D r o p t h e c o n s t r a i n t
s.executeUpdate("create table t(i int, " +
" constraint c primary key (i) initially deferred)");
s.executeUpdate("insert into t values 1,2,2,3");
s.executeUpdate("alter table t drop constraint c");
// Commit (below) normally forces checking of the deferred constraint
// "c". The dropping of the constraint should make sure we don't see
// any issue with the recorded information lcc#deferredHashTables
// i.e. {index conglomerate -> duplicate rows} .
//
// See LanguageConnectionContext#forgetDeferredConstraintsData.
commit();
s.executeUpdate("drop table t");
commit();
// D r o p t h e t a b l e
s.executeUpdate("create table t(i int, " +
" constraint c primary key (i) initially deferred)");
s.executeUpdate("insert into t values 1,2,2,3");
assertStatementError(LANG_DEFERRED_DUP_VIOLATION_S, s,
"set constraints c immediate");
s.executeUpdate("drop table t");
commit();
// T r u n c a t e t h e t a b l e
s.executeUpdate("create table t(i int, " +
" constraint c primary key (i) initially deferred)");
s.executeUpdate("insert into t values 1,2,2,3");
assertStatementError(LANG_DEFERRED_DUP_VIOLATION_S, s,
"set constraints c immediate");
s.executeUpdate("truncate table t");
s.executeUpdate("set constraints c immediate");
s.executeUpdate("set constraints c deferred");
s.executeUpdate("insert into t values 1,2,2,3");
assertStatementError(LANG_DEFERRED_DUP_VIOLATION_S, s,
"set constraints c immediate");
s.executeUpdate("drop table t");
commit();
// C o m p r e s s t h e t a b l e
s.executeUpdate("create table t(i int, " +
" constraint c primary key (i) initially deferred)");
s.executeUpdate("insert into t values 1,2,2,3");
assertStatementError(LANG_DEFERRED_DUP_VIOLATION_S, s,
"set constraints c immediate");
s.executeUpdate("delete from t where i=1");
s.executeUpdate("call syscs_util.syscs_compress_table('APP', 'T', 0)");
assertStatementError(LANG_DEFERRED_DUP_VIOLATION_S, s,
"set constraints c immediate");
assertCommitError(LANG_DEFERRED_DUP_VIOLATION_T, getConnection());
s.executeUpdate("create table t(i int, " +
" constraint c primary key (i) initially deferred)");
commit();
s.executeUpdate("insert into t values 1,2,3");
s.executeUpdate("delete from t where i=1");
// Inline compress times out if we add a PK (even without deferred
// constraints)
assertStatementError(LOCK_TIMEOUT, s,
"call syscs_util.syscs_inplace_compress_table(" +
"'APP', 'T', 1, 1, 1)");
// assertStatementError(LANG_DEFERRED_DUP_VIOLATION_S, s,
// "set constraints c immediate");
// assertCommitError(LANG_DEFERRED_DUP_VIOLATION_T, getConnection());
s.executeUpdate("drop table t");
commit();
//
// C H E C K C O N S T R A I N T
//
// D r o p t h e c o n s t r a i n t
s.executeUpdate("create table t(i int, " +
" constraint c check (i > 0) initially deferred)");
s.executeUpdate("insert into t values -1,-2, -2, -3");
assertStatementError(LANG_DEFERRED_CHECK_VIOLATION_S, s,
"set constraints c immediate");
s.executeUpdate("alter table t drop constraint c");
commit();
s.executeUpdate("drop table t");
commit();
// D r o p t h e t a b l e
s.executeUpdate("create table t(i int, " +
" constraint c check (i > 0) initially deferred)");
s.executeUpdate("insert into t values -1, -2, -2, -3");
assertStatementError(LANG_DEFERRED_CHECK_VIOLATION_S, s,
"set constraints c immediate");
s.executeUpdate("drop table t");
commit();
// T r u n c a t e t h e t a b l e
s.executeUpdate("create table t(i int, " +
" constraint c check (i > 0) initially deferred)");
s.executeUpdate("insert into t values -1, -2, -2, -3");
assertStatementError(LANG_DEFERRED_CHECK_VIOLATION_S, s,
"set constraints c immediate");
s.executeUpdate("truncate table t");
commit();
s.executeUpdate("drop table t");
commit();
// C o m p r e s s t h e t a b l e
//
// We can no longer rely on row locations, so we do a full table scan
// instead to detect any violations.
s.executeUpdate("create table t(i int, " +
" constraint c check (i > 0) initially deferred)");
s.executeUpdate("insert into t values -1, -2, -2, -3");
s.executeUpdate("delete from t where i=-2");
s.executeUpdate("call syscs_util.syscs_compress_table('APP', 'T', 0)");
assertCommitError(LANG_DEFERRED_CHECK_VIOLATION_T, getConnection());
s.executeUpdate("create table t(i int, " +
" constraint c check (i > 0) initially deferred)");
commit();
s.executeUpdate("insert into t values -1, -2, -2, -3");
s.executeUpdate("delete from t where i=-2");
s.executeUpdate("call syscs_util.syscs_inplace_compress_table(" +
"'APP', 'T', 1, 1, 1)");
assertCommitError(LANG_DEFERRED_CHECK_VIOLATION_T, getConnection());
s.executeUpdate("drop table t");
commit();
//
// F O R E I G N K E Y C O N S T R A I N T
//
// D r o p t h e c o n s t r a i n t
s.executeUpdate("create table t(i int, constraint c foreign key(i) " +
"references referenced(i) initially deferred)");
s.executeUpdate("insert into t values 1,2,3");
assertStatementError(LANG_DEFERRED_FK_VIOLATION_S, s,
"set constraints c immediate");
s.executeUpdate("alter table t drop constraint c");
commit();
s.executeUpdate("drop table t");
commit();
// T r u n c a t e t h e r e f e r e n c i n g t a b l e
s.executeUpdate("create table t(i int, constraint c foreign key(i) " +
"references referenced(i) initially deferred)");
s.executeUpdate("insert into t values 1,2,3");
assertStatementError(LANG_DEFERRED_FK_VIOLATION_S, s,
"set constraints c immediate");
s.executeUpdate("truncate table t");
commit();
s.executeUpdate("insert into t values 1,2,3");
assertStatementError(LANG_DEFERRED_FK_VIOLATION_S, s,
"set constraints c immediate");
s.executeUpdate("drop table t");
commit();
// C o m p r e s s t h e r e f e r e n c i n g t a b l e
// Compress by recreating the conglomerate
s.executeUpdate("create table t(i int, constraint c foreign key(i) " +
"references referenced(i) initially deferred)");
s.executeUpdate("insert into referenced(i) values 4,5,6");
s.executeUpdate("insert into t values 4,5,6,7");
s.executeUpdate("delete from t where i=5");
s.executeUpdate("call syscs_util.syscs_compress_table('APP', 'T', 0)");
assertCommitError(LANG_DEFERRED_FK_VIOLATION_T, getConnection());
// In-place compress
s.executeUpdate("create table t(i int, constraint c foreign key(i) " +
"references referenced(i) initially deferred)");
s.executeUpdate("insert into referenced(i) values 4,5,6");
s.executeUpdate("insert into t values 4,5,6,7");
s.executeUpdate("delete from t where i=5");
// s.executeUpdate("call syscs_util.syscs_inplace_compress_table(" +
// " 'APP', 'T', 1,1,1)");
assertStatementError(
LOCK_TIMEOUT, s,
"call syscs_util.syscs_inplace_compress_table('APP', 'T', 1,1,1)");
// assertCommitError(LANG_DEFERRED_FK_VIOLATION_T, getConnection());
// C o m p r e s s t h e r e f e r e n c e d t a b l e
//
// Compress by recreating the conglomerate
s.executeUpdate(
"create table t(i int, constraint c foreign key(i) " +
"references referenced(i) ON DELETE NO ACTION initially deferred)");
s.executeUpdate("insert into referenced(i) values 4,5,6");
s.executeUpdate("insert into t values 4,5,6");
s.executeUpdate("delete from referenced where i=5");
assertStatementError(LANG_DEFERRED_FK_VIOLATION_S, s,
"set constraints c immediate");
s.executeUpdate("call syscs_util.syscs_compress_table('APP', 'T', 0)");
assertCommitError(LANG_DEFERRED_FK_VIOLATION_T, getConnection());
// In-place compress
s.executeUpdate(
"create table t(i int, constraint c foreign key(i) " +
"references referenced(i) ON DELETE NO ACTION initially deferred)");
s.executeUpdate("insert into referenced(i) values 4,5,6");
s.executeUpdate("insert into t values 4,5,6");
s.executeUpdate("delete from referenced where i=5");
assertStatementError(LANG_DEFERRED_FK_VIOLATION_S, s,
"set constraints c immediate");
// s.executeUpdate("call syscs_util.syscs_inplace_compress_table(" +
// " 'APP', 'T', 1,1,1)");
assertStatementError(
LOCK_TIMEOUT, s,
"call syscs_util.syscs_inplace_compress_table('APP', 'T', 1, 1, 1)");
// assertCommitError(LANG_DEFERRED_FK_VIOLATION_T, getConnection());
}
/**
* Import uses other code paths than normal insert, so test it. Not very
* useful with deferred constraints, however, since the IMPORT performs an
* implicit commit at the end. However, the implementation goes through the
* motions of deferring the checking, and the actual checking happens at
* commit time. So, if the implicit commit is lifted in the future, the
* deferred constraints should work. For now, the only net effect is to
* delay the violation detection, so we should recommend immediate checking
* in conjunction with import.
*
* @throws SQLException
*/
public void testImport() throws SQLException {
final Statement s = createStatement();
s.executeUpdate("create table t(i int)");
try {
// Try the test cases below with both "replace" and "append"
// semantics
for (int addOrReplace = 0; addOrReplace < 2; addOrReplace++) {
//
// P R I M A R Y C O N S T R A I N T
//
s.executeUpdate("alter table t alter column i not null");
s.executeUpdate(
"alter table t " +
"add constraint c primary key(i) " +
" deferrable initially immediate");
commit();
s.executeUpdate("set constraints c deferred");
// import and implicit commit leads to checking
assertStatementError(
LANG_DEFERRED_DUP_VIOLATION_T, s,
"call SYSCS_UTIL.SYSCS_IMPORT_TABLE (" +
" 'APP' , 'T' , '" + expImpDataFile + "'," +
" null, null , null, " + addOrReplace + ")");
//
// U N I Q U E N O T N U L L C O N S T R A I N T
//
s.executeUpdate("alter table t alter column i not null");
s.executeUpdate("alter table t drop constraint c");
s.executeUpdate
("alter table t " +
"add constraint c unique(i) " +
" deferrable initially immediate");
commit();
s.executeUpdate("set constraints c deferred");
// import and implicit commit leads to checking
assertStatementError(
LANG_DEFERRED_DUP_VIOLATION_T, s,
"call SYSCS_UTIL.SYSCS_IMPORT_TABLE (" +
" 'APP' , 'T' , '" + expImpDataFile + "'," +
" null, null , null, " + addOrReplace + ")");
//
// n u l l a b l e U N I Q U E C O N S T R A I N T
//
s.executeUpdate("alter table t alter column i null");
s.executeUpdate("alter table t drop constraint c");
s.executeUpdate(
"alter table t " +
"add constraint c unique(i) initially deferred");
commit();
// import and implicit commit leads to checking
assertStatementError(
LANG_DEFERRED_DUP_VIOLATION_T, s,
"call SYSCS_UTIL.SYSCS_IMPORT_TABLE (" +
" 'APP' , 'T' , '" + expImpDataFile + "'," +
" null, null , null, " + addOrReplace + ")");
// Import OK data with multiple NULLs should still work with
// nullable UNIQUE deferred constraint
s.executeUpdate(
"call SYSCS_UTIL.SYSCS_IMPORT_TABLE (" +
" 'APP' , 'T' , '" +
expImpDataWithNullsFile + "'," +
" null, null , null, " + addOrReplace + ")");
s.executeUpdate("alter table t drop constraint c");
s.executeUpdate("truncate table t");
commit();
//
// C H E C K C O N S T R A I N T
//
s.executeUpdate(
"alter table t " +
"add constraint c check (i > 0) initially deferred");
// import and implicit commit leads to checking
assertStatementError(
LANG_DEFERRED_CHECK_VIOLATION_T, s,
"call SYSCS_UTIL.SYSCS_IMPORT_TABLE (" +
" 'APP' , 'T' , '" + expImpDataFile + "'," +
" null, null , null, " + addOrReplace + ")");
s.executeUpdate("truncate table t");
commit();
}
} finally {
dropTable("t");
commit();
}
}
// Adapted from UniqueConstraintSetNullTest which exposed an error
// when we ran all regressions with default deferrable: when a NOT NULL
// clause was dropped, the test used to drop and recreate the index to
// be non-unique was incomplete in the deferrable case.
public void testDropNotNullOnUniqueColumn() throws SQLException {
final Statement s = createStatement();
s.executeUpdate("create table constraintest (" +
"val1 varchar (20) not null, " +
"val2 varchar (20))");
s.executeUpdate("alter table constraintest add constraint " +
"u_con unique (val1) deferrable initially immediate");
s.executeUpdate("alter table constraintest alter column val1 null");
s.executeUpdate("insert into constraintest(val1) values 'name1'");
assertStatementError(
LANG_DUPLICATE_KEY_CONSTRAINT, s,
"insert into constraintest(val1) values 'name1'");
final PreparedStatement ps = prepareStatement(
"insert into constraintest(val1) values (?)");
ps.setString(1, null);
ps.executeUpdate();
ps.setString(1, null);
ps.executeUpdate();
}
public void testDerby6374() throws SQLException {
final Statement s = createStatement();
s.executeUpdate("create table t(i int)");
try {
// Try the test cases below with both "replace" and not with
// the import statement:
for (int addOrReplace = 0; addOrReplace < 2; addOrReplace++) {
// Import duplicate data into a table a nullable
// UNIQUE constraint
s.executeUpdate("alter table t add constraint c unique(i)");
commit();
assertStatementError(
LANG_DUPLICATE_KEY_CONSTRAINT, s,
"call SYSCS_UTIL.SYSCS_IMPORT_TABLE (" +
" 'APP' , 'T' , '" + expImpDataFile + "'," +
" null, null , null, " + addOrReplace + ")");
s.executeUpdate("alter table t drop constraint c");
}
} finally {
dropTable("t");
commit();
}
}
public void testXA() throws SQLException, XAException {
final XADataSource xads = J2EEDataSource.getXADataSource();
J2EEDataSource.setBeanProperty(xads, "databaseName", "wombat");
final int UNIQUE_PK = 0; // loop iteration 0
final int CHECK = 1; // loop iteration 1
final String[] expectedError = {
LANG_DEFERRED_DUP_VIOLATION_T,
LANG_DEFERRED_CHECK_VIOLATION_T};
for (int i = UNIQUE_PK; i <= CHECK; i++) {
final XAConnection xaconn = xads.getXAConnection();
try {
final XAResource xar = xaconn.getXAResource();
final Connection conn = xaconn.getConnection();
conn.setAutoCommit(false);
final Statement s = conn.createStatement();
//
// Do XA rollback when we have a violation; expect normal
// operation.
//
Xid xid = (i == UNIQUE_PK) ?
doXAWorkUniquePK(s, xar) :
doXAWorkCheck(s, xar);
xar.rollback(xid);
assertXidRolledBack(xar, xid);
//
// Do an XA prepare when we have a violation; expect exception
// and rollback.
//
xid = (i == UNIQUE_PK) ?
doXAWorkUniquePK(s, xar) :
doXAWorkCheck(s, xar);
try {
xar.prepare(xid);
fail("Expected XA prepare to fail due to " +
"constraint violation");
} catch (XAException xe) {
assertEquals(XAException.XA_RBINTEGRITY, xe.errorCode);
if (!usingDerbyNetClient()) {
Throwable t = xe.getCause();
assertTrue(t != null && t instanceof SQLException);
assertSQLState(expectedError[i], (SQLException)t);
}
assertXidRolledBack(xar, xid);
}
//
// Do XA commit (1PC, no prepare) when we have a violation;
// expect exception and rollback.
//
xid = (i == UNIQUE_PK) ?
doXAWorkUniquePK(s, xar) :
doXAWorkCheck(s, xar);
try {
xar.commit(xid, true);
fail("Expected XA commit to fail due to " +
"constraint violation");
} catch (XAException xe) {
if (xe.errorCode == -3) {
System.err.println("huff");
} else {
assertEquals(XAException.XA_RBINTEGRITY, xe.errorCode);
if (!usingDerbyNetClient()) {
Throwable t = xe.getCause();
assertTrue(t != null && t instanceof SQLException);
assertSQLState(expectedError[i], (SQLException)t);
}
}
assertXidRolledBack(xar, xid);
}
} finally {
if (usingDerbyNetClient()) {
xaconn.getConnection().rollback();
}
xaconn.close();
}
}
}
// Exposed a bug when running regression suites with default
// deferrable: compress recreates the index.
public void testCompressTableOKUnique() throws SQLException {
final Statement stmt = createStatement();
stmt.executeUpdate(
"create table table1(" +
"name1 int unique deferrable initially immediate, " +
"name2 int unique not null, " +
"name3 int primary key)");
try {
stmt.execute(
"call syscs_util.syscs_compress_table('APP','TABLE1',1)");
stmt.executeUpdate(
"insert into table1 values(1,11,111)");
// The following should run into problem because of constraint
// on name1
assertStatementError(
LANG_DUPLICATE_KEY_CONSTRAINT, stmt,
"insert into table1 values(1,22,222)");
// The following should run into problem because of constraint
// on name2
assertStatementError(
LANG_DUPLICATE_KEY_CONSTRAINT, stmt,
"insert into table1 values(3,11,333)");
// The following should run into problem because of constraint
// on name3
assertStatementError(
LANG_DUPLICATE_KEY_CONSTRAINT, stmt,
"insert into table1 values(4,44,111)");
// Test the DERBY-6773 support:
try {
stmt.execute( "insert into table1 values(1,22,222)");
fail();
}
catch ( DerbySQLIntegrityConstraintViolationException dsicve ) {
assertSQLState(LANG_DUPLICATE_KEY_CONSTRAINT, dsicve);
assertEquals( "TABLE1", dsicve.getTableName() );
assertTrue( dsicve.getConstraintName().startsWith( "SQL" ) );
}
} finally {
stmt.executeUpdate("drop table table1");
}
}
final static long NO_OF_INSERTED_ROWS = (1024L * 4);
public void testManySimilarDuplicates() throws SQLException {
if (usingDerbyNetClient()) {
// skip, too heavy fixture to do twice...
return;
}
final Connection c = getConnection();
c.setAutoCommit(false);
final Statement s = c.createStatement();
try {
s.executeUpdate(
"create table t (i varchar(256), " +
" constraint c primary key(i) initially deferred)");
final PreparedStatement ps =
c.prepareStatement("insert into t values ?");
char[] value = new char[256];
Arrays.fill(value, 'a');
ps.setString(1, String.valueOf(value));
for (long l=0; l < NO_OF_INSERTED_ROWS; l++) {
ps.executeUpdate();
}
c.commit();
fail();
} catch (SQLException e) {
assertSQLState(LANG_DEFERRED_DUP_VIOLATION_T, e);
s.executeUpdate("call syscs_util.syscs_checkpoint_database()");
}
}
/**
* Remove all duplicates except the last
* @throws java.sql.SQLException
*/
public void testAlmostRemovedAllDups() throws SQLException {
final Statement s = createStatement();
s.executeUpdate(
"create table t(i int, j int, " +
" constraint c primary key (i) initially deferred)");
try {
final PreparedStatement ps = prepareStatement(
"insert into t values (?,?)");
for (int i=0; i < 10; i++) {
ps.setInt(1, 1);
ps.setInt(2, i);
ps.executeUpdate();
}
// leave one row
s.executeUpdate("delete from t where j > 0");
commit(); // should work
s.executeUpdate("truncate table t");
// make many different duplicates and delete all except the last
// two rows, i.e. one duplicate left.
for (int i=0; i < 10; i++) {
ps.setInt(1, i);
ps.setInt(2, i);
ps.executeUpdate();
ps.setInt(1, i);
ps.setInt(2, i);
ps.executeUpdate();
}
s.execute("delete from t where i < 9");
JDBC.assertFullResultSet(s.executeQuery("select * from t"),
new String[][]{
{"9","9"},
{"9","9"}});
commit();
} catch (SQLException e) {
assertSQLState(LANG_DEFERRED_DUP_VIOLATION_T, e);
} finally {
dropTable("t");
commit();
}
}
private static void setupTab1(final Connection c) throws SQLException {
final Statement stmt = c.createStatement();
stmt.execute(
"create table tab1 (i integer)");
stmt.executeUpdate(
"alter table tab1 add constraint con1 unique (i) deferrable");
final PreparedStatement ps = c.prepareStatement("insert into tab1 " +
"values (?)");
for (int i = 0; i < 10; i++) {
ps.setInt(1, i);
ps.executeUpdate();
}
ps.close();
stmt.close();
c.commit();
}
private static void dropTab1(final Connection c) throws SQLException {
final Statement stmt = c.createStatement();
try {
stmt.execute("drop table tab1");
c.commit();
} catch (SQLException e) {
// ignore so we get to see original exception if there is one
}
}
/**
* Test inserting a duplicate record while original is deleted in a
* transaction and later committed.
* <p/>
* This test was lifted from UniqueConstraintMultiThrededTest
* except that here we run it with a deferrable constraint. We
* include it her e since it exposed a bug during implementation
* of deferrable constraints: we check a deferrable constraint
* <em>after</em> the insert (cf. {@code IndexChanger}) by using a
* BTree scan. Iff the constraint mode is deferred, we treat any
* lock or deadlock timeout as if it were a duplicate, allowing us
* to defer the check till commit time, as so possibly gain more
* concurrency. To get speed in this case, the scan returns
* immediately if it can't get a lock. The error was that, if the
* constraint mode is <em>not</em> deferred (i.e. immediate), we
* should wait for the lock, and we didn't. This was exposed by
* this test since the 2 seconds wait makes it work in the normal
* case (the lock would be released), but in the no-wait scan, we
* saw a the lock time-out error.
* @throws java.lang.Exception
*/
public void testLockingForUniquePKWithCommit () throws Exception {
setupTab1(getConnection());
try {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
executeThreads(
this,
(int)Math.pow(2,i),
(int)Math.pow(2,j), true);
}
}
} finally {
dropTab1(getConnection());
}
}
/**
* Test inserting a duplicate record while original is deleted in
* a transaction and later rolled back.
* <p/>
* See also comment for {@link #testLockingForUniquePKWithCommit() }.
*
* @throws java.lang.Exception
*/
public void testLockingForUniquePKWithRollback () throws Exception {
setupTab1(getConnection());
try {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
executeThreads(
this,
(int)Math.pow(2,i),
(int)Math.pow(2,j), false);
}
}
} finally {
dropTab1(getConnection());
}
}
/**
* A bit of white box testing to cover different code paths. SOmetimes, on
* INSERT and UPDATE, the actual writing of the rows is deferred, e.g.
* due to a "self" select, or due to the presence of triggers.
*
* @throws SQLException
*/
public void testCheckConstraintsWithDeferredRows () throws
SQLException {
final Statement s = createStatement();
try {
s.executeUpdate(
"create table tab1 (c1 int, " +
"constraint c check (c1 > 0) deferrable initially deferred)");
commit();
//
// I N S E R T, D E F E R R E D P R O C E S S I N G
//
// INSERT from self causes the violation
s.executeUpdate("insert into tab1 values (4)");
s.executeUpdate("insert into tab1 values (3)");
s.executeUpdate("insert into tab1 select c1-3 from tab1");
assertCommitError(LANG_DEFERRED_CHECK_VIOLATION_T,
getConnection());
//
// U P D A T E, D E F E R R E D P R O C E S S I N G
//
// correlated query to force deferred update processing:
s.executeUpdate("insert into tab1 values (2)");
s.executeUpdate("update tab1 as grr set c1=-1 where c1 = 2 and " +
"((select max(c1) from tab1 where grr.c1 > 0) > 0)");
assertCommitError(LANG_DEFERRED_CHECK_VIOLATION_T,
getConnection());
// Correlated query to force deferred update processing but with
// trigger which causes another code path.
s.executeUpdate("insert into tab1 values (2)");
s.executeUpdate("create table trigtab(i int)");
s.executeUpdate("create trigger mytrigger " +
"after update on tab1 insert into trigtab values 1");
s.executeUpdate("update tab1 as grr set c1=-1 where c1 = 2 and " +
"((select max(c1) from tab1 where grr.c1 > 0) > 0)");
assertCommitError(LANG_DEFERRED_CHECK_VIOLATION_T,
getConnection());
} finally {
// clean up
dropTable("tab1");
dropTable("trigtab");
commit();
}
}
final static String DID = "deferrable initially deferred";
/**
* We can have several constraints broken on one row write,
* test is we register all correctly
*
* @throws SQLException
*/
public void testSeveralCheckConstraints () throws SQLException {
final Statement s = createStatement();
try {
s.executeUpdate(
"create table t(" +
"i int, constraint ci check (i > 0) " + DID + ", " +
"j int, constraint cj check (j > 0) " + DID + ", " +
"k int, constraint ck check (k > 0) " + DID + ")");
commit();
final String[] setStrings = {
"j = -j, k = -k",
"i = -i, k = -k",
"i = -i, j = -j"};
final String[] makeImmediate = {"ci", "cj", "ck"};
// All constraints are broken, make all except one good and
// check that the one still barfs when made immediate.
for (int i = 0; i < 3; i++) {
s.executeUpdate("insert into t values (-1, -2, -3)");
s.executeUpdate("update t set " + setStrings[i]);
try {
// We force checking of only the column which is still
// broken
s.executeUpdate("set constraints " + makeImmediate[i] +
" immediate");
fail("expected violation: " + i);
} catch (SQLException e) {
assertSQLState(LANG_DEFERRED_CHECK_VIOLATION_S, e);
assertTrue(e.getMessage().contains(
makeImmediate[i].toUpperCase()));
}
rollback();
}
// Check that we accumulate the set of broken constraints
// when many are violated on separate occasions
s.executeUpdate("insert into t values (-1, 2, 3)");
s.executeUpdate("insert into t values ( 1, -2, 3)");
s.executeUpdate("insert into t values ( 1, 2, -3)");
for (int i = 0; i < 3; i++) {
try {
s.executeUpdate("set constraints " + makeImmediate[i] +
" immediate");
fail("expected violation: " + i);
} catch (SQLException e) {
assertSQLState(LANG_DEFERRED_CHECK_VIOLATION_S, e);
assertTrue(e.getMessage().contains(
makeImmediate[i].toUpperCase()));
}
}
rollback();
// Violations on the same the same row many times
s.executeUpdate("insert into t values (-1, 2, 3)");
s.executeUpdate("update t set i=-1");
s.executeUpdate("update t set i=-1");
assertCommitError(LANG_DEFERRED_CHECK_VIOLATION_T,
getConnection());
} finally {
dropTable("t");
commit();
}
}
/**
* Deletes a record in a transaction and tries to insert the same
* from a different transaction. Once second transaction goes on wait
* first transaction is committed or rolled back based on third
* parameter (boolean commit).
*
* @param thisTest the test object to operate on
* @param isolation1 isolation level for 1st thread
* @param isolation2 isolation level for 2nd thread
* @param commit whether or not to commit
*
* (Lifted from UniqueConstraintMultiThrededTest to test with deferrable
* constraint.)
*
* @throws java.lang.Exception
*/
private static void executeThreads (
final ConstraintCharacteristicsTest thisTest,
final int isolation1,
final int isolation2,
final boolean commit) throws Exception {
final Connection con1 = thisTest.openDefaultConnection();
con1.setTransactionIsolation(isolation1);
final Connection con2 = thisTest.openDefaultConnection();
try {
con2.setTransactionIsolation(isolation2);
final DBOperations dbo1 = new DBOperations (con1, 5);
final DBOperations dbo2 = new DBOperations (con2, 5);
dbo1.delete();
final Thread t = new Thread (dbo2);
t.start();
Thread.sleep((WAIT_TIMEOUT_DURATION * 1000) / 2 );
if (commit) {
dbo1.rollback();
t.join();
assertSQLState(
"isolation levels: " + isolation1 + " " + isolation2,
LANG_DUPLICATE_KEY_CONSTRAINT,
dbo2.getException());
} else {
dbo1.commit();
t.join();
assertNull("isolation levels: " + isolation1
+ " " + isolation2 + ": exception " +
dbo2.getException(), dbo2.getException());
}
assertNull("unexpected failure: " + isolation1
+ " " + isolation2 + ": exception " +
dbo2.getUnexpectedException(),
dbo2.getUnexpectedException());
}
finally {
con1.commit();
con2.commit();
con1.close();
con2.close();
}
}
private Xid doXAWorkUniquePK(final Statement s, final XAResource xar)
throws SQLException, XAException {
final Xid xid = XATestUtil.getXid(1,05,32);
// Start work on a transaction branch
xar.start(xid, XAResource.TMNOFLAGS);
// Create the table and insert some records which violate a deferred
// constraint into it.
s.executeUpdate(
"create table derby532xa(i int, " +
" constraint derby532xa_c primary key(i) initially deferred)");
s.executeUpdate("insert into derby532xa values 1,1,2");
// End work on a transaction branch
xar.end(xid, XAResource.TMSUCCESS);
return xid;
}
private Xid doXAWorkCheck(final Statement s, final XAResource xar)
throws SQLException, XAException {
final Xid xid = XATestUtil.getXid(1,05,32);
// Start work on a transaction branch
xar.start(xid, XAResource.TMNOFLAGS);
// Create the table and insert some records which violate a deferred
// constraint into it.
s.executeUpdate(
"create table derby532xa(i int, " +
" constraint derby532xa_c check(i > 0) initially deferred)");
s.executeUpdate("insert into derby532xa values -1, 1,-2");
// End work on a transaction branch
xar.end(xid, XAResource.TMSUCCESS);
return xid;
}
private void assertXidRolledBack(final XAResource xar, final Xid xid) {
try {
xar.rollback(xid);
fail("expected the transaction to be unknown");
} catch (XAException xe) {
assertEquals(xe.errorCode, XAException.XAER_NOTA);
}
}
/**
* Format rows to single string in syntax suitable for VALUES statement:
* "{@code (v1,v2,..,vn), (v1,v2,..,vn),....}"
*
* @param rs result set strings
* @return the formatted string
*/
private static String rs2Values(final String[][] rs) {
final StringBuilder sb = new StringBuilder();
for (String[] row : rs) {
sb.append('(');
for (String v : row) {
sb.append(v);
sb.append(',');
}
sb.deleteCharAt(sb.length() - 1); // trailing comma
sb.append("),");
}
sb.deleteCharAt(sb.length() - 1); // trailing comma
return sb.toString();
}
private static void checkConsistencyOfBaseTableAndIndex(Statement s)
throws SQLException {
JDBC.assertFullResultSet(
s.executeQuery("values SYSCS_UTIL.SYSCS_CHECK_TABLE('APP', 'T')"),
new String[][] {{"1"}});
}
private final static String[] tableConstraintTypes = {
" foreign key (i) references referenced(i)",
" primary key(i)",
" unique(i)",
" check(i<3)"
};
private final static String[] columnConstraintTypes = {
" references referenced(i)",
" primary key",
" unique",
" check(i<3)"
};
// Each of the three characteristics can have 3 values
// corresponding to {default, on, off}. This translates into 3 x 3
// x 3 = 27 syntax permutations, classified below with their
// corresponding dictionary state.
//
private final static String[][] defaultCharacteristics = {
{" not deferrable initially immediate enforced", "E"},
{" not deferrable initially immediate", "E"},
{" not deferrable enforced", "E"},
{" not deferrable", "E"},
{" initially immediate enforced", "E"},
{" initially immediate", "E"},
{" enforced", "E"},
{"", "E"}};
private final static String[][] nonDefaultCharacteristics = {
{" deferrable", "i"},
{" deferrable initially immediate", "i"},
{" deferrable enforced", "i"},
{" deferrable initially immediate enforced", "i"},
{" deferrable initially deferred", "e"},
{" deferrable initially deferred enforced", "e"},
{" initially deferred enforced", "e"},
{" initially deferred", "e"},
{" deferrable not enforced", "j"},
{" deferrable initially immediate not enforced", "j"},
{" deferrable initially deferred not enforced", "d"},
{" initially deferred not enforced", "d"},
{" not enforced", "D"},
{" initially immediate not enforced", "D"},
{" not deferrable not enforced", "D"},
{" not deferrable initially immediate not enforced", "D"}
};
private final static String[] illegalCharacteristics = {
" not deferrable initially deferred",
" not deferrable initially deferred enforced",
" not deferrable initially deferred not enforced"
};
private final static String[] illegalAlterCharacteristics;
static {
final List<String> characteristics = new ArrayList<String>();
characteristics.addAll(Arrays.asList(defaultCharacteristics[0]));
characteristics.addAll(Arrays.asList(nonDefaultCharacteristics[0]));
characteristics.addAll(Arrays.asList(illegalCharacteristics));
characteristics.remove(" not enforced");
characteristics.remove(" enforced");
characteristics.remove("");
illegalAlterCharacteristics = characteristics.toArray(new String[0]);
}
private final static Map<String, String[]> inverseState =
new HashMap<String, String[]>();
static {
inverseState.put("E", new String[]{"E", "D"});
inverseState.put("D", new String[]{"E", "D"});
inverseState.put("i", new String[]{"i", "j"});
inverseState.put("j", new String[]{"i", "j"});
inverseState.put("i", new String[]{"i", "j"});
inverseState.put("e", new String[]{"e", "d"});
inverseState.put("d", new String[]{"e", "d"});
}
/**
* Assert that we fail with feature not implemented
* until feature is implemented (for characteristics that are not Derby
* default).
*
* @param s statement
* @throws SQLException
*/
private static void assertTableLevelNonDefaultAccepted(
final Statement s) throws SQLException {
for (String ct : tableConstraintTypes) {
for (String[] ch : nonDefaultCharacteristics) {
// Only primary key and unique implemented
if (ch[0].contains("not enforced")) {
assertStatementError(NOT_IMPLEMENTED,
s,
"create table t(i int, constraint c " +
ct + ch[0] + ")");
} else {
s.executeUpdate("create table t(i int, constraint c " +
ct + ch[0] + ")");
s.executeUpdate("drop table t");
}
}
}
}
/**
* Assert that we allow non defaults
*
* @param s statement
* @throws SQLException
*/
private static void assertColumnLevelNonDefaultAccepted(
final Statement s) throws SQLException {
for (String ct : columnConstraintTypes) {
for (String[] ch : nonDefaultCharacteristics) {
// Only primary key and unique implemented
if (ch[0].contains("not enforced")) {
assertStatementError(NOT_IMPLEMENTED,
s,
"create table t(i int " +
ct + ch[0] + ")");
} else {
s.executeUpdate("create table t(i int " +
ct + ch[0] + ")");
s.executeUpdate("drop table t");
}
}
}
}
/**
* Assert that we accept characteristics that merely specify the default
* behavior anyway.
*
* @param c connection
* @param s statement
*
* @throws SQLException
*/
private static void assertTableLevelDefaultBehaviorAccepted (
final Connection c,
final Statement s) throws SQLException {
for (String ct : tableConstraintTypes) {
for (String[] ch : defaultCharacteristics) {
assertUpdateCount(s, 0,
"create table t(i int, constraint c " + ct + ch[0] + ")");
c.rollback();
}
}
}
/**
* Assert that we accept characteristics that merely specify the default
* behavior anyway.
*
* @param c connection
* @param s statement
*
* @throws SQLException
*/
private static void assertColumnLevelDefaultBehaviorAccepted (
final Connection c,
final Statement s) throws SQLException {
for (String ct : columnConstraintTypes) {
for (String ch[] : defaultCharacteristics) {
assertUpdateCount(s, 0,
"create table t(i int " + ct + ch[0] + ")");
c.rollback();
}
}
}
/**
* Check that the dictionary state resulting from {@code characteristics}
* equals {@code}.
*
* @param s Statement to use
* @param characteristics A table level constraint characteristics string
* @param code Character encoding for characteristics
*
* @throws SQLException
*/
private void assertDictState(
final Statement s,
final String characteristics,
final String code) throws SQLException {
for (String ct: tableConstraintTypes) {
try {
s.executeUpdate(
"create table t(i int, constraint c " + ct + " " +
characteristics + ")");
if (characteristics.contains("not enforced")) {
fail();
} else {
JDBC.assertFullResultSet(
s.executeQuery(
"select state from sys.sysconstraints " +
" where constraintname = 'C'"),
new String[][]{{code}});
rollback();
}
} catch (SQLException e) {
if (characteristics.contains("not enforced")) {
assertSQLState(NOT_IMPLEMENTED, e);
} else {
throw e;
}
}
}
}
/**
* Check that the altered dictionary state resulting from new
* {@code characteristics} equals {@code}.
*
* @param s The statement object to use
* @param enforcement String containing ENFORCED or NOT ENFORCED
*
* @throws SQLException
*/
private void assertAlterDictState(
final Statement s,
final String enforcement) throws SQLException {
final String oldState = getOldState(s);
final String newState = computeNewState(oldState, enforcement);
if (!enforcement.contains("not enforced")) {
s.executeUpdate("alter table t alter constraint c " +
enforcement);
JDBC.assertFullResultSet(
s.executeQuery("select state from sys.sysconstraints " +
" where constraintname = 'C'"),
new String[][]{{newState}});
} else {
assertStatementError(NOT_IMPLEMENTED, s,
"alter table t alter constraint c " + enforcement);
}
}
private String getOldState(final Statement s) throws SQLException {
final ResultSet rs = s.executeQuery(
"select state from sys.sysconstraints " +
" where constraintname = 'C'");
try {
rs.next();
return rs.getString(1);
} finally {
rs.close();
}
}
private String computeNewState(String oldState, String enforcement) {
return inverseState.get(oldState)[
enforcement.equals("enforced") ? 0 : 1];
}
private void assertCreateInconsistentCharacteristics(
final Statement s,
final String characteristics) throws SQLException {
for (String ct: tableConstraintTypes) {
try {
s.executeUpdate(
"create table t(i int, constraint c " + ct + " " +
characteristics + ")");
fail("wrong characteristics unexpectedly passed muster");
rollback();
} catch (SQLException e) {
assertSQLState(LANG_INCONSISTENT_C_CHARACTERISTICS, e);
}
}
}
private void assertAlterInconsistentCharacteristics(
final Statement s,
final String characteristics) throws SQLException {
try {
s.executeUpdate("alter table t alter constraint c " +
characteristics);
fail("wrong characteristics unexpectedly passed muster");
rollback();
} catch (SQLException e) {
assertSQLState(LANG_SYNTAX_ERROR, e);
}
}
private void declareCalledNested(final Statement s) throws SQLException {
s.executeUpdate(
"create procedure calledNested(isCheckConstraint boolean)" +
" language java parameter style java" +
" external name '" +
this.getClass().getName() +
".calledNested' modifies sql data");
}
private void declareCalledNestedFk(final Statement s) throws SQLException {
s.executeUpdate(
"create procedure calledNestedFk()" +
" language java parameter style java" +
" external name '" +
this.getClass().getName() +
".calledNestedFk' modifies sql data");
}
private void declareCalledNestedSetImmediate(final Statement s)
throws SQLException {
s.executeUpdate(
"create procedure calledNestedSetImmediate()" +
" language java parameter style java" +
" external name '" +
this.getClass().getName() +
".calledNestedSetImmediate' modifies sql data");
}
public static void calledNested(final boolean isCheckConstraint)
throws SQLException
{
final Connection c =
DriverManager.getConnection("jdbc:default:connection");
final Statement cStmt = c.createStatement();
cStmt.executeUpdate("set constraints c deferred");
cStmt.executeUpdate("insert into t values " +
rs2Values(isCheckConstraint ?
negatedInitialContents :
initialContents));
c.close();
}
public static void calledNestedFk() throws SQLException
{
final Connection c =
DriverManager.getConnection("jdbc:default:connection");
final Statement cStmt = c.createStatement();
cStmt.executeUpdate("set constraints c deferred");
cStmt.executeUpdate("insert into t select i*2, j*2 from t");
c.close();
}
public static void calledNestedSetImmediate() throws SQLException
{
final Connection c =
DriverManager.getConnection("jdbc:default:connection");
final Statement cStmt = c.createStatement();
try {
cStmt.executeUpdate("set constraints c immediate");
} finally {
c.close();
}
}
private void dontThrow(Statement st, String stm) {
try {
st.executeUpdate(stm);
} catch (SQLException e) {
// ignore, best effort here
println("\"" + stm+ "\"failed: " + e);
}
}
/**
* DERBY-6670 test cases. The violation information would be released when
* we dropped a constraint. Unfortunately, an undo in the form of a
* rollback to save point would not redo the row operations (so as to
* regenerate the violation information), but just undo the conglomerate
* delete (which still isn't physically deleted. So, we'd need the
* violation information back too. After this fix, we do not release the
* violation information until commit/rollback, just make it robust to
* disappearance of constraints and their associated tables/schemas.
*
* @throws SQLException
*/
public void testDerby6670_a() throws SQLException {
final Connection c = getConnection();
Statement s = createStatement();
String[] types = new String[]{"pk", "fk", "check"};
for (String type : types) {
String expectedErr = null;
try {
if (type.equals("pk")) {
s.execute("create table derby6670_1(x int primary key " +
" initially deferred)");
s.execute("insert into derby6670_1 values 1,1,1,1");
expectedErr = LANG_DEFERRED_DUP_VIOLATION_T;
} else if (type.equals("fk")) {
s.execute("create table derby6670_11(x int primary key)");
s.execute("create table derby6670_1(x int " +
" references derby6670_11 initially deferred)");
s.execute("insert into derby6670_1 values 1");
expectedErr = LANG_DEFERRED_FK_VIOLATION_T;
} else if (type.equals("check")) {
s.execute("create table derby6670_1(x int check (x < 0) " +
" initially deferred)");
s.execute("insert into derby6670_1 values 1");
expectedErr = LANG_DEFERRED_CHECK_VIOLATION_T;
}
Savepoint sp = c.setSavepoint();
s.execute("drop table derby6670_1");
c.rollback(sp);
// Since there are four identical rows in DERBY6670_1, this
// call should fail because the primary key was violated. It
// did not prior to DERBY-6670.
try {
commit();
fail();
} catch (SQLException e) {
assertSQLState(expectedErr, e);
}
// In savepoint, create table and make a violation, then roll
// back. Commit should work since no violation exists.
sp = c.setSavepoint();
if (type.equals("pk")) {
s.execute("create table derby6670_2(x int primary key " +
" initially deferred)");
s.execute("insert into derby6670_2 values 1,1,1,1");
} else if (type.equals("fk")) {
s.execute("create table derby6670_22(x int primary key)");
s.execute("create table derby6670_2(x int " +
" references derby6670_22 initially deferred)");
s.execute("insert into derby6670_2 values 1");
} else if (type.equals("check")) {
s.execute("create table derby6670_2(x int)");
s.execute("alter table derby6670_2 add constraint c " +
" check(x > 0) deferrable initially deferred");
s.execute("insert into derby6670_2 values -1");
}
c.rollback(sp);
commit();
// In a savepoint, add constraint with offending rows. After
// rollback, the commit should work since no violations exist.
s.execute("create table derby6670_3(x int not null)");
commit();
sp = c.setSavepoint();
if (type.equals("pk")) {
s.execute("alter table derby6670_3 add constraint c " +
" primary key(x) deferrable " +
" initially deferred");
s.execute("insert into derby6670_3 values 1,1");
} else if (type.equals("fk")) {
s.execute("create table derby6670_33(x int primary key)");
s.execute("alter table derby6670_3 add constraint c " +
" foreign key(x) references derby6670_33 " +
" deferrable initially deferred");
s.execute("insert into derby6670_3 values -1");
} else if (type.equals("check")) {
s.execute("alter table derby6670_3 add constraint c " +
" check(x > 0) deferrable initially deferred");
s.execute("insert into derby6670_3 values -1");
}
c.rollback(sp);
commit();
// In a savepoint, drop a constraint, then rollback. We should
// still see violation at commit.
s.execute("create table derby6670_4(x int not null)");
c.commit();
if (type.equals("pk")) {
s.execute("alter table derby6670_4 add constraint c " +
" primary key(x) deferrable " +
" initially deferred");
s.execute("insert into derby6670_4 values 1,1");
} else if (type.equals("fk")) {
s.execute("create table derby6670_44(x int primary key)");
s.execute("alter table derby6670_4 add constraint c " +
" foreign key(x) references derby6670_44 " +
" deferrable initially deferred");
s.execute("insert into derby6670_4 values -1");
} else if (type.equals("check")) {
s.execute("alter table derby6670_4 add constraint c " +
" check(x > 0) deferrable initially deferred");
s.execute("insert into derby6670_4 values -1");
}
sp = c.setSavepoint();
s.execute("alter table derby6670_4 drop constraint c");
c.rollback(sp);
try {
c.commit();
fail();
} catch (SQLException e) {
assertSQLState(expectedErr, e);
}
} finally {
for (int i = 1; i <= 4; i++) {
dropTable("derby6670_" + i);
}
c.commit();
}
}
}
/**
* Similarly to what happened for dropping of constraints, when we revert
* from deferred constraint mode to immediate, and no violations are seen,
* we used to drop the violation information, if any. Again, this is not
* safe iff a rollback to a savepoint re-introduces the violations. This
* test would fail prior to DERBY-6670.
* @throws SQLException test error
*/
public void testDerby6670_b() throws SQLException {
final Connection c = getConnection();
final Statement s = createStatement();
String[] forms = new String[]{"c", "all"};
for (String form : forms) {
s.execute("create table t1(x int primary key, " +
" constraint c check(x > 0) initially deferred)");
s.execute("insert into t1 values -1");
Savepoint sp = c.setSavepoint();
s.execute("delete from t1");
s.execute("set constraints " + form + " immediate");
c.rollback(sp);
try {
// Used to succeed because we released violation information of
// the successful constraint when moving to immediate mode
c.commit();
fail();
} catch (SQLException e) {
assertSQLState(LANG_DEFERRED_CHECK_VIOLATION_T, e);
}
}
}
/**
* DERBY-6666. Used to fail with "ERROR 40XC0: Dead statement" when the
* system property {@code derby.language.logQueryPlan} is set to {@code
* true}, which it is is here.
*
* @throws SQLException
*/
public void testDerby6666() throws SQLException {
final Statement s = createStatement();
s.executeUpdate("create table t1(x int primary key)");
s.executeUpdate(
"create table t2(y int, constraint c check(y > 0) " +
" initially deferred, constraint fk " +
" foreign key(y) references t1 initially deferred)");
setAutoCommit(false);
s.executeUpdate("insert into t1 values -1, 1");
s.executeUpdate("insert into t2 values 1");
s.executeUpdate("update t2 set y = -1");
try {
commit();
fail();
} catch (SQLException e) {
assertSQLState(LANG_DEFERRED_CHECK_VIOLATION_T, e);
}
}
/**
* DERBY-6773: check the Derby-specific subclass of the standard
* SQLIntegrityConstraintViolationException.
*/
public void testDerby6773() throws Exception
{
final Statement s = createStatement();
s.executeUpdate( "create table Application " +
" (id bigint generated by default as identity," +
" name varchar(255)," +
" shortName varchar(32)," +
" userId varchar(32)," +
" primary key (id))" );
s.executeUpdate( "create unique index UK_APPLICATION_SHORTNAME " +
" on Application (shortName)" );
s.executeUpdate( "create unique index UK_APPLICATION_NAME " +
" on Application (name)" );
s.executeUpdate( "insert into Application (name, shortName, userId) " +
" VALUES ('fooApp', 'Foo Application 0', 'me')" );
try
{
s.executeUpdate(
"insert into Application (name, shortName, userId) " +
" VALUES ('fooApp', 'Foo Application 1', 'me')" );
fail();
}
catch ( DerbySQLIntegrityConstraintViolationException dsicve )
{
assertEquals( "APPLICATION", dsicve.getTableName() );
assertEquals( "UK_APPLICATION_NAME", dsicve.getConstraintName() );
}
try
{
s.executeUpdate(
"insert into Application (name, shortName, userId) " +
" VALUES ('BarApp', 'Foo Application 0', 'me')" );
fail();
}
catch ( DerbySQLIntegrityConstraintViolationException dsicve )
{
assertEquals( "APPLICATION", dsicve.getTableName() );
assertEquals( "UK_APPLICATION_SHORTNAME",
dsicve.getConstraintName() );
}
}
/**
* Privileged lookup of the LCC from a Connection.
*/
public static LanguageConnectionContext getLCC( final Connection conn )
{
return AccessController.doPrivileged
(
new PrivilegedAction<LanguageConnectionContext>()
{
public LanguageConnectionContext run()
{
final ContextManager contextManager =
((EmbedConnection)conn).getContextManager();
return (LanguageConnectionContext)
contextManager.getContext( "LanguageConnectionContext" );
}
}
);
}
}
|