1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207
|
/*-------------------------------------------------------------------------
*
* Copyright (c) 2004-2008, PostgreSQL Global Development Group
*
* IDENTIFICATION
* $PostgreSQL: pgjdbc/org/postgresql/jdbc2/AbstractJdbc2Statement.java,v 1.114 2009/05/27 23:55:19 jurka Exp $
*
*-------------------------------------------------------------------------
*/
package org.postgresql.jdbc2;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.*;
import java.sql.*;
import java.util.ArrayList;
import java.util.Vector;
import java.util.Calendar;
import org.postgresql.Driver;
import org.postgresql.largeobject.*;
import org.postgresql.core.*;
import org.postgresql.core.types.*;
import org.postgresql.util.PSQLException;
import org.postgresql.util.PSQLState;
import org.postgresql.util.PGobject;
import org.postgresql.util.GT;
/**
* This class defines methods of the jdbc2 specification.
* The real Statement class (for jdbc2) is org.postgresql.jdbc2.Jdbc2Statement
*/
public abstract class AbstractJdbc2Statement implements BaseStatement
{
protected ArrayList batchStatements = null;
protected ArrayList batchParameters = null;
protected final int resultsettype; // the resultset type to return (ResultSet.TYPE_xxx)
protected final int concurrency; // is it updateable or not? (ResultSet.CONCUR_xxx)
protected int fetchdirection = ResultSet.FETCH_FORWARD; // fetch direction hint (currently ignored)
/**
* Does the caller of execute/executeUpdate want generated keys for this
* execution? This is set by Statement methods that have generated keys
* arguments and cleared after execution is complete.
*/
protected boolean wantsGeneratedKeysOnce = false;
/**
* Was this PreparedStatement created to return generated keys for every
* execution? This is set at creation time and never cleared by
* execution.
*/
public boolean wantsGeneratedKeysAlways = false;
// The connection who created us
protected BaseConnection connection;
/** The warnings chain. */
protected SQLWarning warnings = null;
/** Maximum number of rows to return, 0 = unlimited */
protected int maxrows = 0;
/** Number of rows to get in a batch. */
protected int fetchSize = 0;
/** Timeout (in seconds) for a query (not used) */
protected int timeout = 0;
protected boolean replaceProcessingEnabled = true;
/** The current results. */
protected ResultWrapper result = null;
/** The first unclosed result. */
protected ResultWrapper firstUnclosedResult = null;
/** Results returned by a statement that wants generated keys. */
protected ResultWrapper generatedKeys = null;
/** used to differentiate between new function call
* logic and old function call logic
* will be set to true if the server is < 8.1 or
* if we are using v2 protocol
* There is an exception to this where we are using v3, and the
* call does not have an out parameter before the call
*/
protected boolean adjustIndex = false;
/*
* Used to set adjustIndex above
*/
protected boolean outParmBeforeFunc=false;
// Static variables for parsing SQL when replaceProcessing is true.
private static final short IN_SQLCODE = 0;
private static final short IN_STRING = 1;
private static final short IN_IDENTIFIER = 6;
private static final short BACKSLASH = 2;
private static final short ESC_TIMEDATE = 3;
private static final short ESC_FUNCTION = 4;
private static final short ESC_OUTERJOIN = 5;
private static final short ESC_ESCAPECHAR = 7;
protected final Query preparedQuery; // Query fragments for prepared statement.
protected final ParameterList preparedParameters; // Parameter values for prepared statement.
protected Query lastSimpleQuery;
protected int m_prepareThreshold; // Reuse threshold to enable use of PREPARE
protected int m_useCount = 0; // Number of times this statement has been used
//Used by the callablestatement style methods
private boolean isFunction;
// functionReturnType contains the user supplied value to check
// testReturn contains a modified version to make it easier to
// check the getXXX methods..
private int []functionReturnType;
private int []testReturn;
// returnTypeSet is true when a proper call to registerOutParameter has been made
private boolean returnTypeSet;
protected Object []callResult;
protected int maxfieldSize = 0;
public ResultSet createDriverResultSet(Field[] fields, Vector tuples)
throws SQLException
{
return createResultSet(null, fields, tuples, null);
}
public AbstractJdbc2Statement (AbstractJdbc2Connection c, int rsType, int rsConcurrency) throws SQLException
{
this.connection = c;
this.preparedQuery = null;
this.preparedParameters = null;
this.lastSimpleQuery = null;
resultsettype = rsType;
concurrency = rsConcurrency;
}
public AbstractJdbc2Statement(AbstractJdbc2Connection connection, String sql, boolean isCallable, int rsType, int rsConcurrency) throws SQLException
{
this.connection = connection;
this.lastSimpleQuery = null;
String parsed_sql = replaceProcessing(sql);
if (isCallable)
parsed_sql = modifyJdbcCall(parsed_sql);
this.preparedQuery = connection.getQueryExecutor().createParameterizedQuery(parsed_sql);
this.preparedParameters = preparedQuery.createParameterList();
int inParamCount = preparedParameters.getInParameterCount() + 1;
this.testReturn = new int[inParamCount];
this.functionReturnType = new int[inParamCount];
resultsettype = rsType;
concurrency = rsConcurrency;
}
public abstract ResultSet createResultSet(Query originalQuery, Field[] fields, Vector tuples, ResultCursor cursor)
throws SQLException;
public BaseConnection getPGConnection() {
return connection;
}
public String getFetchingCursorName() {
return null;
}
public int getFetchSize() {
return fetchSize;
}
protected boolean wantsScrollableResultSet() {
return resultsettype != ResultSet.TYPE_FORWARD_ONLY;
}
protected boolean wantsHoldableResultSet() {
return false;
}
//
// ResultHandler implementations for updates, queries, and either-or.
//
public class StatementResultHandler implements ResultHandler {
private SQLException error;
private ResultWrapper results;
ResultWrapper getResults() {
return results;
}
private void append(ResultWrapper newResult) {
if (results == null)
results = newResult;
else
results.append(newResult);
}
public void handleResultRows(Query fromQuery, Field[] fields, Vector tuples, ResultCursor cursor) {
try
{
ResultSet rs = AbstractJdbc2Statement.this.createResultSet(fromQuery, fields, tuples, cursor);
append(new ResultWrapper(rs));
}
catch (SQLException e)
{
handleError(e);
}
}
public void handleCommandStatus(String status, int updateCount, long insertOID) {
append(new ResultWrapper(updateCount, insertOID));
}
public void handleWarning(SQLWarning warning) {
AbstractJdbc2Statement.this.addWarning(warning);
}
public void handleError(SQLException newError) {
if (error == null)
error = newError;
else
error.setNextException(newError);
}
public void handleCompletion() throws SQLException {
if (error != null)
throw error;
}
}
/*
* Execute a SQL statement that retruns a single ResultSet
*
* @param sql typically a static SQL SELECT statement
* @return a ResulSet that contains the data produced by the query
* @exception SQLException if a database access error occurs
*/
public java.sql.ResultSet executeQuery(String p_sql) throws SQLException
{
if (preparedQuery != null)
throw new PSQLException(GT.tr("Can''t use query methods that take a query string on a PreparedStatement."),
PSQLState.WRONG_OBJECT_TYPE);
if (!executeWithFlags(p_sql, 0))
throw new PSQLException(GT.tr("No results were returned by the query."), PSQLState.NO_DATA);
if (result.getNext() != null)
throw new PSQLException(GT.tr("Multiple ResultSets were returned by the query."),
PSQLState.TOO_MANY_RESULTS);
return (ResultSet)result.getResultSet();
}
/*
* A Prepared SQL query is executed and its ResultSet is returned
*
* @return a ResultSet that contains the data produced by the
* * query - never null
* @exception SQLException if a database access error occurs
*/
public java.sql.ResultSet executeQuery() throws SQLException
{
if (!executeWithFlags(0))
throw new PSQLException(GT.tr("No results were returned by the query."), PSQLState.NO_DATA);
if (result.getNext() != null)
throw new PSQLException(GT.tr("Multiple ResultSets were returned by the query."), PSQLState.TOO_MANY_RESULTS);
return (ResultSet) result.getResultSet();
}
/*
* Execute a SQL INSERT, UPDATE or DELETE statement. In addition
* SQL statements that return nothing such as SQL DDL statements
* can be executed
*
* @param sql a SQL statement
* @return either a row count, or 0 for SQL commands
* @exception SQLException if a database access error occurs
*/
public int executeUpdate(String p_sql) throws SQLException
{
if (preparedQuery != null)
throw new PSQLException(GT.tr("Can''t use query methods that take a query string on a PreparedStatement."),
PSQLState.WRONG_OBJECT_TYPE);
if( isFunction )
{
executeWithFlags(p_sql, 0);
return 0;
}
if (executeWithFlags(p_sql, QueryExecutor.QUERY_NO_RESULTS))
throw new PSQLException(GT.tr("A result was returned when none was expected."),
PSQLState.TOO_MANY_RESULTS);
return getUpdateCount();
}
/*
* Execute a SQL INSERT, UPDATE or DELETE statement. In addition,
* SQL statements that return nothing such as SQL DDL statements can
* be executed.
*
* @return either the row count for INSERT, UPDATE or DELETE; or
* * 0 for SQL statements that return nothing.
* @exception SQLException if a database access error occurs
*/
public int executeUpdate() throws SQLException
{
if( isFunction )
{
executeWithFlags(0);
return 0;
}
if (executeWithFlags(QueryExecutor.QUERY_NO_RESULTS))
throw new PSQLException(GT.tr("A result was returned when none was expected."),
PSQLState.TOO_MANY_RESULTS);
return getUpdateCount();
}
/*
* Execute a SQL statement that may return multiple results. We
* don't have to worry about this since we do not support multiple
* ResultSets. You can use getResultSet or getUpdateCount to
* retrieve the result.
*
* @param sql any SQL statement
* @return true if the next result is a ResulSet, false if it is
* an update count or there are no more results
* @exception SQLException if a database access error occurs
*/
public boolean execute(String p_sql) throws SQLException
{
if (preparedQuery != null)
throw new PSQLException(GT.tr("Can''t use query methods that take a query string on a PreparedStatement."),
PSQLState.WRONG_OBJECT_TYPE);
return executeWithFlags(p_sql, 0);
}
public boolean executeWithFlags(String p_sql, int flags) throws SQLException
{
checkClosed();
p_sql = replaceProcessing(p_sql);
Query simpleQuery = connection.getQueryExecutor().createSimpleQuery(p_sql);
execute(simpleQuery, null, QueryExecutor.QUERY_ONESHOT | flags);
this.lastSimpleQuery = simpleQuery;
return (result != null && result.getResultSet() != null);
}
public boolean execute() throws SQLException
{
return executeWithFlags(0);
}
public boolean executeWithFlags(int flags) throws SQLException
{
checkClosed();
execute(preparedQuery, preparedParameters, flags);
// If we are executing and there are out parameters
// callable statement function set the return data
if (isFunction && returnTypeSet )
{
if (result == null || result.getResultSet() == null)
throw new PSQLException(GT.tr("A CallableStatement was executed with nothing returned."), PSQLState.NO_DATA);
ResultSet rs = result.getResultSet();
if (!rs.next())
throw new PSQLException(GT.tr("A CallableStatement was executed with nothing returned."), PSQLState.NO_DATA);
// figure out how many columns
int cols = rs.getMetaData().getColumnCount();
int outParameterCount = preparedParameters.getOutParameterCount() ;
if ( cols != outParameterCount )
throw new PSQLException(GT.tr("A CallableStatement was executed with an invalid number of parameters"),PSQLState.SYNTAX_ERROR);
// reset last result fetched (for wasNull)
lastIndex = 0;
// allocate enough space for all possible parameters without regard to in/out
callResult = new Object[preparedParameters.getParameterCount()+1];
// move them into the result set
for ( int i=0,j=0; i < cols; i++,j++)
{
// find the next out parameter, the assumption is that the functionReturnType
// array will be initialized with 0 and only out parameters will have values
// other than 0. 0 is the value for java.sql.Types.NULL, which should not
// conflict
while( j< functionReturnType.length && functionReturnType[j]==0) j++;
callResult[j] = rs.getObject(i+1);
int columnType = rs.getMetaData().getColumnType(i+1);
if (columnType != functionReturnType[j])
{
// this is here for the sole purpose of passing the cts
if ( columnType == Types.DOUBLE && functionReturnType[j] == Types.REAL )
{
// return it as a float
if ( callResult[j] != null)
callResult[j] = new Float(((Double)callResult[j]).floatValue());
}
else
{
throw new PSQLException (GT.tr("A CallableStatement function was executed and the out parameter {0} was of type {1} however type {2} was registered.",
new Object[]{new Integer(i+1),
"java.sql.Types=" + columnType, "java.sql.Types=" + functionReturnType[j] }),
PSQLState.DATA_TYPE_MISMATCH);
}
}
}
rs.close();
result = null;
return false;
}
return (result != null && result.getResultSet() != null);
}
protected void execute(Query queryToExecute, ParameterList queryParameters, int flags) throws SQLException {
// Every statement execution clears any previous warnings.
clearWarnings();
// Close any existing resultsets associated with this statement.
while (firstUnclosedResult != null)
{
if (firstUnclosedResult.getResultSet() != null)
firstUnclosedResult.getResultSet().close();
firstUnclosedResult = firstUnclosedResult.getNext();
}
if (lastSimpleQuery != null) {
lastSimpleQuery.close();
lastSimpleQuery = null;
}
// Enable cursor-based resultset if possible.
if (fetchSize > 0 && !wantsScrollableResultSet() && !connection.getAutoCommit() && !wantsHoldableResultSet())
flags |= QueryExecutor.QUERY_FORWARD_CURSOR;
if (wantsGeneratedKeysOnce || wantsGeneratedKeysAlways)
{
flags |= QueryExecutor.QUERY_BOTH_ROWS_AND_STATUS;
// If the no results flag is set (from executeUpdate)
// clear it so we get the generated keys results.
//
if ((flags & QueryExecutor.QUERY_NO_RESULTS) != 0)
flags &= ~(QueryExecutor.QUERY_NO_RESULTS);
}
// Only use named statements after we hit the threshold
if (preparedQuery != null)
{
++m_useCount; // We used this statement once more.
if (m_prepareThreshold == 0 || m_useCount < m_prepareThreshold)
flags |= QueryExecutor.QUERY_ONESHOT;
}
if (connection.getAutoCommit())
flags |= QueryExecutor.QUERY_SUPPRESS_BEGIN;
StatementResultHandler handler = new StatementResultHandler();
result = null;
connection.getQueryExecutor().execute(queryToExecute,
queryParameters,
handler,
maxrows,
fetchSize,
flags);
result = firstUnclosedResult = handler.getResults();
if (wantsGeneratedKeysOnce || wantsGeneratedKeysAlways)
{
generatedKeys = result;
result = result.getNext();
if (wantsGeneratedKeysOnce)
wantsGeneratedKeysOnce = false;
}
}
/*
* setCursorName defines the SQL cursor name that will be used by
* subsequent execute methods. This name can then be used in SQL
* positioned update/delete statements to identify the current row
* in the ResultSet generated by this statement. If a database
* doesn't support positioned update/delete, this method is a
* no-op.
*
* <p><B>Note:</B> By definition, positioned update/delete execution
* must be done by a different Statement than the one which
* generated the ResultSet being used for positioning. Also, cursor
* names must be unique within a Connection.
*
* @param name the new cursor name
* @exception SQLException if a database access error occurs
*/
public void setCursorName(String name) throws SQLException
{
checkClosed();
// No-op.
}
protected boolean isClosed = false;
private int lastIndex = 0;
/*
* getUpdateCount returns the current result as an update count,
* if the result is a ResultSet or there are no more results, -1
* is returned. It should only be called once per result.
*
* @return the current result as an update count.
* @exception SQLException if a database access error occurs
*/
public int getUpdateCount() throws SQLException
{
checkClosed();
if (result == null || result.getResultSet() != null)
return -1;
return result.getUpdateCount();
}
/*
* getMoreResults moves to a Statement's next result. If it returns
* true, this result is a ResulSet.
*
* @return true if the next ResultSet is valid
* @exception SQLException if a database access error occurs
*/
public boolean getMoreResults() throws SQLException
{
if (result == null)
return false;
result = result.getNext();
// Close preceding resultsets.
while (firstUnclosedResult != result)
{
if (firstUnclosedResult.getResultSet() != null)
firstUnclosedResult.getResultSet().close();
firstUnclosedResult = firstUnclosedResult.getNext();
}
return (result != null && result.getResultSet() != null);
}
/*
* The maxRows limit is set to limit the number of rows that
* any ResultSet can contain. If the limit is exceeded, the
* excess rows are silently dropped.
*
* @return the current maximum row limit; zero means unlimited
* @exception SQLException if a database access error occurs
*/
public int getMaxRows() throws SQLException
{
checkClosed();
return maxrows;
}
/*
* Set the maximum number of rows
*
* @param max the new max rows limit; zero means unlimited
* @exception SQLException if a database access error occurs
* @see getMaxRows
*/
public void setMaxRows(int max) throws SQLException
{
checkClosed();
if (max < 0)
throw new PSQLException(GT.tr("Maximum number of rows must be a value grater than or equal to 0."),
PSQLState.INVALID_PARAMETER_VALUE);
maxrows = max;
}
/*
* If escape scanning is on (the default), the driver will do escape
* substitution before sending the SQL to the database.
*
* @param enable true to enable; false to disable
* @exception SQLException if a database access error occurs
*/
public void setEscapeProcessing(boolean enable) throws SQLException
{
checkClosed();
replaceProcessingEnabled = enable;
}
/*
* The queryTimeout limit is the number of seconds the driver
* will wait for a Statement to execute. If the limit is
* exceeded, a SQLException is thrown.
*
* @return the current query timeout limit in seconds; 0 = unlimited
* @exception SQLException if a database access error occurs
*/
public int getQueryTimeout() throws SQLException
{
checkClosed();
return timeout;
}
/*
* Sets the queryTimeout limit
*
* @param seconds - the new query timeout limit in seconds
* @exception SQLException if a database access error occurs
*/
public void setQueryTimeout(int seconds) throws SQLException
{
checkClosed();
if (seconds < 0)
throw new PSQLException(GT.tr("Query timeout must be a value greater than or equals to 0."),
PSQLState.INVALID_PARAMETER_VALUE);
if (seconds > 0)
throw Driver.notImplemented(this.getClass(), "setQueryTimeout(int)");
timeout = seconds;
}
/**
* This adds a warning to the warning chain.
* @param warn warning to add
*/
public void addWarning(SQLWarning warn)
{
if (warnings != null)
warnings.setNextWarning(warn);
else
warnings = warn;
}
/*
* The first warning reported by calls on this Statement is
* returned. A Statement's execute methods clear its SQLWarning
* chain. Subsequent Statement warnings will be chained to this
* SQLWarning.
*
* <p>The Warning chain is automatically cleared each time a statement
* is (re)executed.
*
* <p><B>Note:</B> If you are processing a ResultSet then any warnings
* associated with ResultSet reads will be chained on the ResultSet
* object.
*
* @return the first SQLWarning on null
* @exception SQLException if a database access error occurs
*/
public SQLWarning getWarnings() throws SQLException
{
checkClosed();
return warnings;
}
/*
* The maxFieldSize limit (in bytes) is the maximum amount of
* data returned for any column value; it only applies to
* BINARY, VARBINARY, LONGVARBINARY, CHAR, VARCHAR and LONGVARCHAR
* columns. If the limit is exceeded, the excess data is silently
* discarded.
*
* @return the current max column size limit; zero means unlimited
* @exception SQLException if a database access error occurs
*/
public int getMaxFieldSize() throws SQLException
{
return maxfieldSize;
}
/*
* Sets the maxFieldSize
*
* @param max the new max column size limit; zero means unlimited
* @exception SQLException if a database access error occurs
*/
public void setMaxFieldSize(int max) throws SQLException
{
checkClosed();
if (max < 0)
throw new PSQLException(GT.tr("The maximum field size must be a value greater than or equal to 0."),
PSQLState.INVALID_PARAMETER_VALUE);
maxfieldSize = max;
}
/*
* After this call, getWarnings returns null until a new warning
* is reported for this Statement.
*
* @exception SQLException if a database access error occurs
*/
public void clearWarnings() throws SQLException
{
warnings = null;
}
/*
* getResultSet returns the current result as a ResultSet. It
* should only be called once per result.
*
* @return the current result set; null if there are no more
* @exception SQLException if a database access error occurs (why?)
*/
public java.sql.ResultSet getResultSet() throws SQLException
{
checkClosed();
if (result == null)
return null;
return (ResultSet) result.getResultSet();
}
/*
* In many cases, it is desirable to immediately release a
* Statement's database and JDBC resources instead of waiting
* for this to happen when it is automatically closed. The
* close method provides this immediate release.
*
* <p><B>Note:</B> A Statement is automatically closed when it is
* garbage collected. When a Statement is closed, its current
* ResultSet, if one exists, is also closed.
*
* @exception SQLException if a database access error occurs (why?)
*/
public void close() throws SQLException
{
// closing an already closed Statement is a no-op.
if (isClosed)
return ;
// Force the ResultSet(s) to close
while (firstUnclosedResult != null)
{
if (firstUnclosedResult.getResultSet() != null)
firstUnclosedResult.getResultSet().close();
firstUnclosedResult = firstUnclosedResult.getNext();
}
if (lastSimpleQuery != null)
lastSimpleQuery.close();
if (preparedQuery != null)
preparedQuery.close();
// Disasociate it from us
result = firstUnclosedResult = null;
isClosed = true;
}
/**
* This finalizer ensures that statements that have allocated server-side
* resources free them when they become unreferenced.
*/
protected void finalize() {
try
{
close();
}
catch (SQLException e)
{
}
}
/*
* Filter the SQL string of Java SQL Escape clauses.
*
* Currently implemented Escape clauses are those mentioned in 11.3
* in the specification. Basically we look through the sql string for
* {d xxx}, {t xxx}, {ts xxx}, {oj xxx} or {fn xxx} in non-string sql
* code. When we find them, we just strip the escape part leaving only
* the xxx part.
* So, something like "select * from x where d={d '2001-10-09'}" would
* return "select * from x where d= '2001-10-09'".
*/
protected String replaceProcessing(String p_sql) throws SQLException
{
if (replaceProcessingEnabled)
{
// Since escape codes can only appear in SQL CODE, we keep track
// of if we enter a string or not.
int len = p_sql.length();
StringBuffer newsql = new StringBuffer(len);
int i=0;
while (i<len){
i=parseSql(p_sql,i,newsql,false,connection.getStandardConformingStrings());
// We need to loop here in case we encounter invalid
// SQL, consider: SELECT a FROM t WHERE (1 > 0)) ORDER BY a
// We can't ending replacing after the extra closing paren
// because that changes a syntax error to a valid query
// that isn't what the user specified.
if (i < len) {
newsql.append(p_sql.charAt(i));
i++;
}
}
return newsql.toString();
}
else
{
return p_sql;
}
}
/**
* parse the given sql from index i, appending it to the gven buffer
* until we hit an unmatched right parentheses or end of string. When
* the stopOnComma flag is set we also stop processing when a comma is
* found in sql text that isn't inside nested parenthesis.
*
* @param p_sql the original query text
* @param i starting position for replacing
* @param newsql where to write the replaced output
* @param stopOnComma should we stop after hitting the first comma in sql text?
* @param stdStrings whether standard_conforming_strings is on
* @return the position we stopped processing at
*/
protected static int parseSql(String p_sql,int i,StringBuffer newsql, boolean stopOnComma,
boolean stdStrings)throws SQLException{
short state = IN_SQLCODE;
int len = p_sql.length();
int nestedParenthesis=0;
boolean endOfNested=false;
// because of the ++i loop
i--;
while (!endOfNested && ++i < len)
{
char c = p_sql.charAt(i);
switch (state)
{
case IN_SQLCODE:
if (c == '\'') // start of a string?
state = IN_STRING;
else if (c == '"') // start of a identifer?
state = IN_IDENTIFIER;
else if (c=='(') { // begin nested sql
nestedParenthesis++;
} else if (c==')') { // end of nested sql
nestedParenthesis--;
if (nestedParenthesis<0){
endOfNested=true;
break;
}
} else if (stopOnComma && c==',' && nestedParenthesis==0) {
endOfNested=true;
break;
} else if (c == '{') { // start of an escape code?
if (i + 1 < len)
{
char next = p_sql.charAt(i + 1);
char nextnext = (i + 2 < len) ? p_sql.charAt(i + 2) : '\0';
if (next == 'd' || next == 'D')
{
state = ESC_TIMEDATE;
i++;
newsql.append("DATE ");
break;
}
else if (next == 't' || next == 'T')
{
state = ESC_TIMEDATE;
if (nextnext == 's' || nextnext == 'S'){
// timestamp constant
i+=2;
newsql.append("TIMESTAMP ");
}else{
// time constant
i++;
newsql.append("TIME ");
}
break;
}
else if ( next == 'f' || next == 'F' )
{
state = ESC_FUNCTION;
i += (nextnext == 'n' || nextnext == 'N') ? 2 : 1;
break;
}
else if ( next == 'o' || next == 'O' )
{
state = ESC_OUTERJOIN;
i += (nextnext == 'j' || nextnext == 'J') ? 2 : 1;
break;
}
else if ( next == 'e' || next == 'E' )
{ // we assume that escape is the only escape sequence beginning with e
state = ESC_ESCAPECHAR;
break;
}
}
}
newsql.append(c);
break;
case IN_STRING:
if (c == '\'') // end of string?
state = IN_SQLCODE;
else if (c == '\\' && !stdStrings) // a backslash?
state = BACKSLASH;
newsql.append(c);
break;
case IN_IDENTIFIER:
if (c == '"') // end of identifier
state = IN_SQLCODE;
newsql.append(c);
break;
case BACKSLASH:
state = IN_STRING;
newsql.append(c);
break;
case ESC_FUNCTION:
// extract function name
String functionName;
int posArgs = p_sql.indexOf('(',i);
if (posArgs!=-1){
functionName=p_sql.substring(i,posArgs).trim();
// extract arguments
i= posArgs+1;// we start the scan after the first (
StringBuffer args=new StringBuffer();
i = parseSql(p_sql,i,args,false,stdStrings);
// translate the function and parse arguments
newsql.append(escapeFunction(functionName,args.toString(),stdStrings));
}
// go to the end of the function copying anything found
i++;
while (i<len && p_sql.charAt(i)!='}')
newsql.append(p_sql.charAt(i++));
state = IN_SQLCODE; // end of escaped function (or query)
break;
case ESC_TIMEDATE:
case ESC_OUTERJOIN:
case ESC_ESCAPECHAR:
if (c == '}')
state = IN_SQLCODE; // end of escape code.
else
newsql.append(c);
break;
} // end switch
}
return i;
}
/**
* generate sql for escaped functions
* @param functionName the escaped function name
* @param args the arguments for this functin
* @param stdStrings whether standard_conforming_strings is on
* @return the right postgreSql sql
*/
protected static String escapeFunction(String functionName, String args, boolean stdStrings) throws SQLException{
// parse function arguments
int len = args.length();
int i=0;
ArrayList parsedArgs = new ArrayList();
while (i<len){
StringBuffer arg = new StringBuffer();
int lastPos=i;
i=parseSql(args,i,arg,true,stdStrings);
if (lastPos!=i){
parsedArgs.add(arg);
}
i++;
}
// we can now tranlate escape functions
try{
Method escapeMethod = EscapedFunctions.getFunction(functionName);
return (String) escapeMethod.invoke(null,new Object[] {parsedArgs});
}catch(InvocationTargetException e){
if (e.getTargetException() instanceof SQLException)
throw (SQLException) e.getTargetException();
else
throw new PSQLException(e.getTargetException().getMessage(),
PSQLState.SYSTEM_ERROR);
}catch (Exception e){
// by default the function name is kept unchanged
StringBuffer buf = new StringBuffer();
buf.append(functionName).append('(');
for (int iArg = 0;iArg<parsedArgs.size();iArg++){
buf.append(parsedArgs.get(iArg));
if (iArg!=(parsedArgs.size()-1))
buf.append(',');
}
buf.append(')');
return buf.toString();
}
}
/*
*
* The following methods are postgres extensions and are defined
* in the interface BaseStatement
*
*/
/*
* Returns the Last inserted/updated oid. Deprecated in 7.2 because
* range of OID values is greater than a java signed int.
* @deprecated Replaced by getLastOID in 7.2
*/
public int getInsertedOID() throws SQLException
{
checkClosed();
if (result == null)
return 0;
return (int) result.getInsertOID();
}
/*
* Returns the Last inserted/updated oid.
* @return OID of last insert
* @since 7.2
*/
public long getLastOID() throws SQLException
{
checkClosed();
if (result == null)
return 0;
return result.getInsertOID();
}
/*
* Set a parameter to SQL NULL
*
* <p><B>Note:</B> You must specify the parameter's SQL type.
*
* @param parameterIndex the first parameter is 1, etc...
* @param sqlType the SQL type code defined in java.sql.Types
* @exception SQLException if a database access error occurs
*/
public void setNull(int parameterIndex, int sqlType) throws SQLException
{
checkClosed();
int oid;
switch (sqlType)
{
case Types.INTEGER:
oid = Oid.INT4;
break;
case Types.TINYINT:
case Types.SMALLINT:
oid = Oid.INT2;
break;
case Types.BIGINT:
oid = Oid.INT8;
break;
case Types.REAL:
oid = Oid.FLOAT4;
break;
case Types.DOUBLE:
case Types.FLOAT:
oid = Oid.FLOAT8;
break;
case Types.DECIMAL:
case Types.NUMERIC:
oid = Oid.NUMERIC;
break;
case Types.CHAR:
oid = Oid.BPCHAR;
break;
case Types.VARCHAR:
case Types.LONGVARCHAR:
oid = Oid.VARCHAR;
break;
case Types.DATE:
oid = Oid.DATE;
break;
case Types.TIME:
oid = Oid.TIME;
break;
case Types.TIMESTAMP:
oid = Oid.TIMESTAMPTZ;
break;
case Types.BIT:
oid = Oid.BOOL;
break;
case Types.BINARY:
case Types.VARBINARY:
case Types.LONGVARBINARY:
if (connection.haveMinimumCompatibleVersion("7.2"))
{
oid = Oid.BYTEA;
}
else
{
oid = Oid.OID;
}
break;
case Types.BLOB:
case Types.CLOB:
oid = Oid.OID;
break;
case Types.ARRAY:
case Types.DISTINCT:
case Types.STRUCT:
case Types.NULL:
case Types.OTHER:
oid = Oid.UNSPECIFIED;
break;
default:
// Bad Types value.
throw new PSQLException(GT.tr("Unknown Types value."), PSQLState.INVALID_PARAMETER_TYPE);
}
if ( adjustIndex )
parameterIndex--;
preparedParameters.setNull( parameterIndex, oid);
}
/*
* Set a parameter to a Java boolean value. The driver converts this
* to a SQL BIT value when it sends it to the database.
*
* @param parameterIndex the first parameter is 1...
* @param x the parameter value
* @exception SQLException if a database access error occurs
*/
public void setBoolean(int parameterIndex, boolean x) throws SQLException
{
checkClosed();
bindString(parameterIndex, x ? "1" : "0", Oid.BOOL);
}
/*
* Set a parameter to a Java byte value. The driver converts this to
* a SQL TINYINT value when it sends it to the database.
*
* @param parameterIndex the first parameter is 1...
* @param x the parameter value
* @exception SQLException if a database access error occurs
*/
public void setByte(int parameterIndex, byte x) throws SQLException
{
checkClosed();
bindLiteral(parameterIndex, Integer.toString(x), Oid.INT2);
}
/*
* Set a parameter to a Java short value. The driver converts this
* to a SQL SMALLINT value when it sends it to the database.
*
* @param parameterIndex the first parameter is 1...
* @param x the parameter value
* @exception SQLException if a database access error occurs
*/
public void setShort(int parameterIndex, short x) throws SQLException
{
checkClosed();
bindLiteral(parameterIndex, Integer.toString(x), Oid.INT2);
}
/*
* Set a parameter to a Java int value. The driver converts this to
* a SQL INTEGER value when it sends it to the database.
*
* @param parameterIndex the first parameter is 1...
* @param x the parameter value
* @exception SQLException if a database access error occurs
*/
public void setInt(int parameterIndex, int x) throws SQLException
{
checkClosed();
bindLiteral(parameterIndex, Integer.toString(x), Oid.INT4);
}
/*
* Set a parameter to a Java long value. The driver converts this to
* a SQL BIGINT value when it sends it to the database.
*
* @param parameterIndex the first parameter is 1...
* @param x the parameter value
* @exception SQLException if a database access error occurs
*/
public void setLong(int parameterIndex, long x) throws SQLException
{
checkClosed();
bindLiteral(parameterIndex, Long.toString(x), Oid.INT8);
}
/*
* Set a parameter to a Java float value. The driver converts this
* to a SQL FLOAT value when it sends it to the database.
*
* @param parameterIndex the first parameter is 1...
* @param x the parameter value
* @exception SQLException if a database access error occurs
*/
public void setFloat(int parameterIndex, float x) throws SQLException
{
checkClosed();
bindLiteral(parameterIndex, Float.toString(x), Oid.FLOAT8);
}
/*
* Set a parameter to a Java double value. The driver converts this
* to a SQL DOUBLE value when it sends it to the database
*
* @param parameterIndex the first parameter is 1...
* @param x the parameter value
* @exception SQLException if a database access error occurs
*/
public void setDouble(int parameterIndex, double x) throws SQLException
{
checkClosed();
bindLiteral(parameterIndex, Double.toString(x), Oid.FLOAT8);
}
/*
* Set a parameter to a java.lang.BigDecimal value. The driver
* converts this to a SQL NUMERIC value when it sends it to the
* database.
*
* @param parameterIndex the first parameter is 1...
* @param x the parameter value
* @exception SQLException if a database access error occurs
*/
public void setBigDecimal(int parameterIndex, BigDecimal x) throws SQLException
{
checkClosed();
if (x == null)
setNull(parameterIndex, Types.DECIMAL);
else
bindLiteral(parameterIndex, x.toString(), Oid.NUMERIC);
}
/*
* Set a parameter to a Java String value. The driver converts this
* to a SQL VARCHAR or LONGVARCHAR value (depending on the arguments
* size relative to the driver's limits on VARCHARs) when it sends it
* to the database.
*
* @param parameterIndex the first parameter is 1...
* @param x the parameter value
* @exception SQLException if a database access error occurs
*/
public void setString(int parameterIndex, String x) throws SQLException
{
checkClosed();
setString(parameterIndex, x, (connection.getStringVarcharFlag() ? Oid.VARCHAR : Oid.UNSPECIFIED));
}
protected void setString(int parameterIndex, String x, int oid) throws SQLException
{
// if the passed string is null, then set this column to null
checkClosed();
if (x == null)
{
if ( adjustIndex )
parameterIndex--;
preparedParameters.setNull( parameterIndex, oid);
}
else
bindString(parameterIndex, x, oid);
}
/*
* Set a parameter to a Java array of bytes. The driver converts this
* to a SQL VARBINARY or LONGVARBINARY (depending on the argument's
* size relative to the driver's limits on VARBINARYs) when it sends
* it to the database.
*
* <p>Implementation note:
* <br>With org.postgresql, this creates a large object, and stores the
* objects oid in this column.
*
* @param parameterIndex the first parameter is 1...
* @param x the parameter value
* @exception SQLException if a database access error occurs
*/
public void setBytes(int parameterIndex, byte[] x) throws SQLException
{
checkClosed();
if (null == x)
{
setNull(parameterIndex, Types.VARBINARY);
return ;
}
if (connection.haveMinimumCompatibleVersion("7.2"))
{
//Version 7.2 supports the bytea datatype for byte arrays
byte[] copy = new byte[x.length];
System.arraycopy(x, 0, copy, 0, x.length);
preparedParameters.setBytea( parameterIndex, copy, 0, x.length);
}
else
{
//Version 7.1 and earlier support done as LargeObjects
LargeObjectManager lom = connection.getLargeObjectAPI();
long oid = lom.createLO();
LargeObject lob = lom.open(oid);
lob.write(x);
lob.close();
setLong(parameterIndex, oid);
}
}
/*
* Set a parameter to a java.sql.Date value. The driver converts this
* to a SQL DATE value when it sends it to the database.
*
* @param parameterIndex the first parameter is 1...
* @param x the parameter value
* @exception SQLException if a database access error occurs
*/
public void setDate(int parameterIndex, java.sql.Date x) throws SQLException
{
setDate(parameterIndex, x, null);
}
/*
* Set a parameter to a java.sql.Time value. The driver converts
* this to a SQL TIME value when it sends it to the database.
*
* @param parameterIndex the first parameter is 1...));
* @param x the parameter value
* @exception SQLException if a database access error occurs
*/
public void setTime(int parameterIndex, Time x) throws SQLException
{
setTime(parameterIndex, x, null);
}
/*
* Set a parameter to a java.sql.Timestamp value. The driver converts
* this to a SQL TIMESTAMP value when it sends it to the database.
*
* @param parameterIndex the first parameter is 1...
* @param x the parameter value
* @exception SQLException if a database access error occurs
*/
public void setTimestamp(int parameterIndex, Timestamp x) throws SQLException
{
setTimestamp(parameterIndex, x, null);
}
private void setCharacterStreamPost71(int parameterIndex, InputStream x, int length, String encoding) throws SQLException
{
if (x == null)
{
setNull(parameterIndex, Types.VARCHAR);
return ;
}
if (length < 0)
throw new PSQLException(GT.tr("Invalid stream length {0}.", new Integer(length)),
PSQLState.INVALID_PARAMETER_VALUE);
//Version 7.2 supports AsciiStream for all PG text types (char, varchar, text)
//As the spec/javadoc for this method indicate this is to be used for
//large String values (i.e. LONGVARCHAR) PG doesn't have a separate
//long varchar datatype, but with toast all text datatypes are capable of
//handling very large values. Thus the implementation ends up calling
//setString() since there is no current way to stream the value to the server
try
{
InputStreamReader l_inStream = new InputStreamReader(x, encoding);
char[] l_chars = new char[length];
int l_charsRead = 0;
while (true)
{
int n = l_inStream.read(l_chars, l_charsRead, length - l_charsRead);
if (n == -1)
break;
l_charsRead += n;
if (l_charsRead == length)
break;
}
setString(parameterIndex, new String(l_chars, 0, l_charsRead), Oid.VARCHAR);
}
catch (UnsupportedEncodingException l_uee)
{
throw new PSQLException(GT.tr("The JVM claims not to support the {0} encoding.", encoding), PSQLState.UNEXPECTED_ERROR, l_uee);
}
catch (IOException l_ioe)
{
throw new PSQLException(GT.tr("Provided InputStream failed."), PSQLState.UNEXPECTED_ERROR, l_ioe);
}
}
/*
* When a very large ASCII value is input to a LONGVARCHAR parameter,
* it may be more practical to send it via a java.io.InputStream.
* JDBC will read the data from the stream as needed, until it reaches
* end-of-file. The JDBC driver will do any necessary conversion from
* ASCII to the database char format.
*
* <P><B>Note:</B> This stream object can either be a standard Java
* stream object or your own subclass that implements the standard
* interface.
*
* @param parameterIndex the first parameter is 1...
* @param x the parameter value
* @param length the number of bytes in the stream
* @exception SQLException if a database access error occurs
*/
public void setAsciiStream(int parameterIndex, InputStream x, int length) throws SQLException
{
checkClosed();
if (connection.haveMinimumCompatibleVersion("7.2"))
{
setCharacterStreamPost71(parameterIndex, x, length, "ASCII");
}
else
{
//Version 7.1 supported only LargeObjects by treating everything
//as binary data
setBinaryStream(parameterIndex, x, length);
}
}
/*
* When a very large Unicode value is input to a LONGVARCHAR parameter,
* it may be more practical to send it via a java.io.InputStream.
* JDBC will read the data from the stream as needed, until it reaches
* end-of-file. The JDBC driver will do any necessary conversion from
* UNICODE to the database char format.
*
* <P><B>Note:</B> This stream object can either be a standard Java
* stream object or your own subclass that implements the standard
* interface.
*
* @param parameterIndex the first parameter is 1...
* @param x the parameter value
* @exception SQLException if a database access error occurs
*/
public void setUnicodeStream(int parameterIndex, InputStream x, int length) throws SQLException
{
checkClosed();
if (connection.haveMinimumCompatibleVersion("7.2"))
{
setCharacterStreamPost71(parameterIndex, x, length, "UTF-8");
}
else
{
//Version 7.1 supported only LargeObjects by treating everything
//as binary data
setBinaryStream(parameterIndex, x, length);
}
}
/*
* When a very large binary value is input to a LONGVARBINARY parameter,
* it may be more practical to send it via a java.io.InputStream.
* JDBC will read the data from the stream as needed, until it reaches
* end-of-file.
*
* <P><B>Note:</B> This stream object can either be a standard Java
* stream object or your own subclass that implements the standard
* interface.
*
* @param parameterIndex the first parameter is 1...
* @param x the parameter value
* @exception SQLException if a database access error occurs
*/
public void setBinaryStream(int parameterIndex, InputStream x, int length) throws SQLException
{
checkClosed();
if (x == null)
{
setNull(parameterIndex, Types.VARBINARY);
return ;
}
if (length < 0)
throw new PSQLException(GT.tr("Invalid stream length {0}.", new Integer(length)),
PSQLState.INVALID_PARAMETER_VALUE);
if (connection.haveMinimumCompatibleVersion("7.2"))
{
//Version 7.2 supports BinaryStream for for the PG bytea type
//As the spec/javadoc for this method indicate this is to be used for
//large binary values (i.e. LONGVARBINARY) PG doesn't have a separate
//long binary datatype, but with toast the bytea datatype is capable of
//handling very large values.
preparedParameters.setBytea(parameterIndex, x, length);
}
else
{
//Version 7.1 only supported streams for LargeObjects
//but the jdbc spec indicates that streams should be
//available for LONGVARBINARY instead
LargeObjectManager lom = connection.getLargeObjectAPI();
long oid = lom.createLO();
LargeObject lob = lom.open(oid);
OutputStream los = lob.getOutputStream();
try
{
// could be buffered, but then the OutputStream returned by LargeObject
// is buffered internally anyhow, so there would be no performance
// boost gained, if anything it would be worse!
int c = x.read();
int p = 0;
while (c > -1 && p < length)
{
los.write(c);
c = x.read();
p++;
}
los.close();
}
catch (IOException se)
{
throw new PSQLException(GT.tr("Provided InputStream failed."), PSQLState.UNEXPECTED_ERROR, se);
}
// lob is closed by the stream so don't call lob.close()
setLong(parameterIndex, oid);
}
}
/*
* In general, parameter values remain in force for repeated used of a
* Statement. Setting a parameter value automatically clears its
* previous value. However, in coms cases, it is useful to immediately
* release the resources used by the current parameter values; this
* can be done by calling clearParameters
*
* @exception SQLException if a database access error occurs
*/
public void clearParameters() throws SQLException
{
preparedParameters.clear();
}
private PGType createInternalType( Object x, int targetType ) throws PSQLException
{
if ( x instanceof Byte ) return PGByte.castToServerType((Byte)x, targetType );
if ( x instanceof Short ) return PGShort.castToServerType((Short)x, targetType );
if ( x instanceof Integer ) return PGInteger.castToServerType((Integer)x, targetType );
if ( x instanceof Long ) return PGLong.castToServerType((Long)x, targetType );
if ( x instanceof Double ) return PGDouble.castToServerType((Double)x, targetType );
if ( x instanceof Float ) return PGFloat.castToServerType((Float)x, targetType );
if ( x instanceof BigDecimal) return PGBigDecimal.castToServerType((BigDecimal)x, targetType );
// since all of the above are instances of Number make sure this is after them
if ( x instanceof Number ) return PGNumber.castToServerType((Number)x, targetType );
if ( x instanceof Boolean) return PGBoolean.castToServerType((Boolean)x, targetType );
return new PGUnknown(x);
}
// Helper method for setting parameters to PGobject subclasses.
private void setPGobject(int parameterIndex, PGobject x) throws SQLException {
String typename = x.getType();
int oid = connection.getTypeInfo().getPGType(typename);
if (oid == Oid.UNSPECIFIED)
throw new PSQLException(GT.tr("Unknown type {0}.", typename), PSQLState.INVALID_PARAMETER_TYPE);
setString(parameterIndex, x.getValue(), oid);
}
/*
* Set the value of a parameter using an object; use the java.lang
* equivalent objects for integral values.
*
* <P>The given Java object will be converted to the targetSqlType before
* being sent to the database.
*
* <P>note that this method may be used to pass database-specific
* abstract data types. This is done by using a Driver-specific
* Java type and using a targetSqlType of java.sql.Types.OTHER
*
* @param parameterIndex the first parameter is 1...
* @param x the object containing the input parameter value
* @param targetSqlType The SQL type to be send to the database
* @param scale For java.sql.Types.DECIMAL or java.sql.Types.NUMERIC
* * types this is the number of digits after the decimal. For
* * all other types this value will be ignored.
* @exception SQLException if a database access error occurs
*/
public void setObject(int parameterIndex, Object in, int targetSqlType, int scale) throws SQLException
{
checkClosed();
if (in == null)
{
setNull(parameterIndex, targetSqlType);
return ;
}
Object pgType = createInternalType( in, targetSqlType );
switch (targetSqlType)
{
case Types.INTEGER:
bindLiteral(parameterIndex, pgType.toString(), Oid.INT4);
break;
case Types.TINYINT:
case Types.SMALLINT:
bindLiteral(parameterIndex, pgType.toString(), Oid.INT2);
break;
case Types.BIGINT:
bindLiteral(parameterIndex, pgType.toString(), Oid.INT8);
break;
case Types.REAL:
//TODO: is this really necessary ?
//bindLiteral(parameterIndex, new Float(pgType.toString()).toString(), Oid.FLOAT4);
bindLiteral(parameterIndex, pgType.toString(), Oid.FLOAT4);
break;
case Types.DOUBLE:
case Types.FLOAT:
bindLiteral(parameterIndex, pgType.toString(), Oid.FLOAT8);
break;
case Types.DECIMAL:
case Types.NUMERIC:
bindLiteral(parameterIndex, pgType.toString(), Oid.NUMERIC);
break;
case Types.CHAR:
setString(parameterIndex, pgType.toString(), Oid.BPCHAR);
break;
case Types.VARCHAR:
case Types.LONGVARCHAR:
setString(parameterIndex, pgType.toString(), Oid.VARCHAR);
break;
case Types.DATE:
if (in instanceof java.sql.Date)
setDate(parameterIndex, (java.sql.Date)in);
else
{
java.sql.Date tmpd;
if (in instanceof java.util.Date) {
tmpd = new java.sql.Date(((java.util.Date)in).getTime());
} else {
tmpd = connection.getTimestampUtils().toDate(null, in.toString());
}
setDate(parameterIndex, tmpd);
}
break;
case Types.TIME:
if (in instanceof java.sql.Time)
setTime(parameterIndex, (java.sql.Time)in);
else
{
java.sql.Time tmpt;
if (in instanceof java.util.Date) {
tmpt = new java.sql.Time(((java.util.Date)in).getTime());
} else {
tmpt = connection.getTimestampUtils().toTime(null, in.toString());
}
setTime(parameterIndex, tmpt);
}
break;
case Types.TIMESTAMP:
if (in instanceof java.sql.Timestamp)
setTimestamp(parameterIndex , (java.sql.Timestamp)in);
else
{
java.sql.Timestamp tmpts;
if (in instanceof java.util.Date) {
tmpts = new java.sql.Timestamp(((java.util.Date)in).getTime());
} else {
tmpts = connection.getTimestampUtils().toTimestamp(null, in.toString());
}
setTimestamp(parameterIndex, tmpts);
}
break;
case Types.BIT:
bindLiteral(parameterIndex, pgType.toString(), Oid.BOOL);
break;
case Types.BINARY:
case Types.VARBINARY:
case Types.LONGVARBINARY:
setObject(parameterIndex, in);
break;
case Types.BLOB:
if (in instanceof Blob)
setBlob(parameterIndex, (Blob)in);
else
throw new PSQLException(GT.tr("Cannot cast an instance of {0} to type {1}", new Object[]{in.getClass().getName(),"Types.BLOB"}), PSQLState.INVALID_PARAMETER_TYPE);
break;
case Types.CLOB:
if (in instanceof Clob)
setClob(parameterIndex, (Clob)in);
else
throw new PSQLException(GT.tr("Cannot cast an instance of {0} to type {1}", new Object[]{in.getClass().getName(),"Types.CLOB"}), PSQLState.INVALID_PARAMETER_TYPE);
break;
case Types.ARRAY:
if (in instanceof Array)
setArray(parameterIndex, (Array)in);
else
throw new PSQLException(GT.tr("Cannot cast an instance of {0} to type {1}", new Object[]{in.getClass().getName(),"Types.ARRAY"}), PSQLState.INVALID_PARAMETER_TYPE);
break;
case Types.OTHER:
if (in instanceof PGobject)
setPGobject(parameterIndex, (PGobject)in);
else
bindString(parameterIndex, in.toString(), Oid.UNSPECIFIED);
break;
default:
throw new PSQLException(GT.tr("Unsupported Types value: {0}", new Integer(targetSqlType)), PSQLState.INVALID_PARAMETER_TYPE);
}
}
public void setObject(int parameterIndex, Object x, int targetSqlType) throws SQLException
{
setObject(parameterIndex, x, targetSqlType, 0);
}
/*
* This stores an Object into a parameter.
*/
public void setObject(int parameterIndex, Object x) throws SQLException
{
checkClosed();
if (x == null)
setNull(parameterIndex, Types.OTHER);
else if (x instanceof String)
setString(parameterIndex, (String)x);
else if (x instanceof BigDecimal)
setBigDecimal(parameterIndex, (BigDecimal)x);
else if (x instanceof Short)
setShort(parameterIndex, ((Short)x).shortValue());
else if (x instanceof Integer)
setInt(parameterIndex, ((Integer)x).intValue());
else if (x instanceof Long)
setLong(parameterIndex, ((Long)x).longValue());
else if (x instanceof Float)
setFloat(parameterIndex, ((Float)x).floatValue());
else if (x instanceof Double)
setDouble(parameterIndex, ((Double)x).doubleValue());
else if (x instanceof byte[])
setBytes(parameterIndex, (byte[])x);
else if (x instanceof java.sql.Date)
setDate(parameterIndex, (java.sql.Date)x);
else if (x instanceof Time)
setTime(parameterIndex, (Time)x);
else if (x instanceof Timestamp)
setTimestamp(parameterIndex, (Timestamp)x);
else if (x instanceof Boolean)
setBoolean(parameterIndex, ((Boolean)x).booleanValue());
else if (x instanceof Byte)
setByte(parameterIndex, ((Byte)x).byteValue());
else if (x instanceof Blob)
setBlob(parameterIndex, (Blob)x);
else if (x instanceof Clob)
setClob(parameterIndex, (Clob)x);
else if (x instanceof Array)
setArray(parameterIndex, (Array)x);
else if (x instanceof PGobject)
setPGobject(parameterIndex, (PGobject)x);
else
{
// Can't infer a type.
throw new PSQLException(GT.tr("Can''t infer the SQL type to use for an instance of {0}. Use setObject() with an explicit Types value to specify the type to use.", x.getClass().getName()), PSQLState.INVALID_PARAMETER_TYPE);
}
}
/*
* Before executing a stored procedure call you must explicitly
* call registerOutParameter to register the java.sql.Type of each
* out parameter.
*
* <p>Note: When reading the value of an out parameter, you must use
* the getXXX method whose Java type XXX corresponds to the
* parameter's registered SQL type.
*
* ONLY 1 RETURN PARAMETER if {?= call ..} syntax is used
*
* @param parameterIndex the first parameter is 1, the second is 2,...
* @param sqlType SQL type code defined by java.sql.Types; for
* parameters of type Numeric or Decimal use the version of
* registerOutParameter that accepts a scale value
* @exception SQLException if a database-access error occurs.
*/
public void registerOutParameter(int parameterIndex, int sqlType, boolean setPreparedParameters) throws SQLException
{
checkClosed();
switch( sqlType )
{
case Types.TINYINT:
// we don't have a TINYINT type use SMALLINT
sqlType = Types.SMALLINT;
break;
case Types.LONGVARCHAR:
sqlType = Types.VARCHAR;
break;
case Types.DECIMAL:
sqlType = Types.NUMERIC;
break;
case Types.FLOAT:
// float is the same as double
sqlType = Types.DOUBLE;
break;
case Types.VARBINARY:
case Types.LONGVARBINARY:
sqlType = Types.BINARY;
break;
default:
break;
}
if (!isFunction)
throw new PSQLException (GT.tr("This statement does not declare an OUT parameter. Use '{' ?= call ... '}' to declare one."), PSQLState.STATEMENT_NOT_ALLOWED_IN_FUNCTION_CALL);
checkIndex(parameterIndex, false);
if( setPreparedParameters )
preparedParameters.registerOutParameter( parameterIndex, sqlType );
// functionReturnType contains the user supplied value to check
// testReturn contains a modified version to make it easier to
// check the getXXX methods..
functionReturnType[parameterIndex-1] = sqlType;
testReturn[parameterIndex-1] = sqlType;
if (functionReturnType[parameterIndex-1] == Types.CHAR ||
functionReturnType[parameterIndex-1] == Types.LONGVARCHAR)
testReturn[parameterIndex-1] = Types.VARCHAR;
else if (functionReturnType[parameterIndex-1] == Types.FLOAT)
testReturn[parameterIndex-1] = Types.REAL; // changes to streamline later error checking
returnTypeSet = true;
}
/*
* You must also specify the scale for numeric/decimal types:
*
* <p>Note: When reading the value of an out parameter, you must use
* the getXXX method whose Java type XXX corresponds to the
* parameter's registered SQL type.
*
* @param parameterIndex the first parameter is 1, the second is 2,...
* @param sqlType use either java.sql.Type.NUMERIC or java.sql.Type.DECIMAL
* @param scale a value greater than or equal to zero representing the
* desired number of digits to the right of the decimal point
* @exception SQLException if a database-access error occurs.
*/
public void registerOutParameter(int parameterIndex, int sqlType,
int scale, boolean setPreparedParameters) throws SQLException
{
registerOutParameter (parameterIndex, sqlType, setPreparedParameters); // ignore for now..
}
/*
* An OUT parameter may have the value of SQL NULL; wasNull
* reports whether the last value read has this special value.
*
* <p>Note: You must first call getXXX on a parameter to read its
* value and then call wasNull() to see if the value was SQL NULL.
* @return true if the last parameter read was SQL NULL
* @exception SQLException if a database-access error occurs.
*/
public boolean wasNull() throws SQLException
{
if (lastIndex == 0)
throw new PSQLException(GT.tr("wasNull cannot be call before fetching a result."), PSQLState.OBJECT_NOT_IN_STATE);
// check to see if the last access threw an exception
return (callResult[lastIndex-1] == null);
}
/*
* Get the value of a CHAR, VARCHAR, or LONGVARCHAR parameter as a
* Java String.
*
* @param parameterIndex the first parameter is 1, the second is 2,...
* @return the parameter value; if the value is SQL NULL, the result is null
* @exception SQLException if a database-access error occurs.
*/
public String getString(int parameterIndex) throws SQLException
{
checkClosed();
checkIndex (parameterIndex, Types.VARCHAR, "String");
return (String)callResult[parameterIndex-1];
}
/*
* Get the value of a BIT parameter as a Java boolean.
*
* @param parameterIndex the first parameter is 1, the second is 2,...
* @return the parameter value; if the value is SQL NULL, the result is false
* @exception SQLException if a database-access error occurs.
*/
public boolean getBoolean(int parameterIndex) throws SQLException
{
checkClosed();
checkIndex (parameterIndex, Types.BIT, "Boolean");
if (callResult[parameterIndex-1] == null)
return false;
return ((Boolean)callResult[parameterIndex-1]).booleanValue ();
}
/*
* Get the value of a TINYINT parameter as a Java byte.
*
* @param parameterIndex the first parameter is 1, the second is 2,...
* @return the parameter value; if the value is SQL NULL, the result is 0
* @exception SQLException if a database-access error occurs.
*/
public byte getByte(int parameterIndex) throws SQLException
{
checkClosed();
// fake tiny int with smallint
checkIndex (parameterIndex, Types.SMALLINT, "Byte");
if (callResult[parameterIndex-1] == null)
return 0;
return ((Integer)callResult[parameterIndex-1]).byteValue();
}
/*
* Get the value of a SMALLINT parameter as a Java short.
*
* @param parameterIndex the first parameter is 1, the second is 2,...
* @return the parameter value; if the value is SQL NULL, the result is 0
* @exception SQLException if a database-access error occurs.
*/
public short getShort(int parameterIndex) throws SQLException
{
checkClosed();
checkIndex (parameterIndex, Types.SMALLINT, "Short");
if (callResult[parameterIndex-1] == null)
return 0;
return ((Integer)callResult[parameterIndex-1]).shortValue ();
}
/*
* Get the value of an INTEGER parameter as a Java int.
*
* @param parameterIndex the first parameter is 1, the second is 2,...
* @return the parameter value; if the value is SQL NULL, the result is 0
* @exception SQLException if a database-access error occurs.
*/
public int getInt(int parameterIndex) throws SQLException
{
checkClosed();
checkIndex (parameterIndex, Types.INTEGER, "Int");
if (callResult[parameterIndex-1] == null)
return 0;
return ((Integer)callResult[parameterIndex-1]).intValue ();
}
/*
* Get the value of a BIGINT parameter as a Java long.
*
* @param parameterIndex the first parameter is 1, the second is 2,...
* @return the parameter value; if the value is SQL NULL, the result is 0
* @exception SQLException if a database-access error occurs.
*/
public long getLong(int parameterIndex) throws SQLException
{
checkClosed();
checkIndex (parameterIndex, Types.BIGINT, "Long");
if (callResult[parameterIndex-1] == null)
return 0;
return ((Long)callResult[parameterIndex-1]).longValue ();
}
/*
* Get the value of a FLOAT parameter as a Java float.
*
* @param parameterIndex the first parameter is 1, the second is 2,...
* @return the parameter value; if the value is SQL NULL, the result is 0
* @exception SQLException if a database-access error occurs.
*/
public float getFloat(int parameterIndex) throws SQLException
{
checkClosed();
checkIndex (parameterIndex, Types.REAL, "Float");
if (callResult[parameterIndex-1] == null)
return 0;
return ((Float)callResult[parameterIndex-1]).floatValue ();
}
/*
* Get the value of a DOUBLE parameter as a Java double.
*
* @param parameterIndex the first parameter is 1, the second is 2,...
* @return the parameter value; if the value is SQL NULL, the result is 0
* @exception SQLException if a database-access error occurs.
*/
public double getDouble(int parameterIndex) throws SQLException
{
checkClosed();
checkIndex (parameterIndex, Types.DOUBLE, "Double");
if (callResult[parameterIndex-1] == null)
return 0;
return ((Double)callResult[parameterIndex-1]).doubleValue ();
}
/*
* Get the value of a NUMERIC parameter as a java.math.BigDecimal
* object.
*
* @param parameterIndex the first parameter is 1, the second is 2,...
* @param scale a value greater than or equal to zero representing the
* desired number of digits to the right of the decimal point
* @return the parameter value; if the value is SQL NULL, the result is null
* @exception SQLException if a database-access error occurs.
* @deprecated in Java2.0
*/
public BigDecimal getBigDecimal(int parameterIndex, int scale)
throws SQLException
{
checkClosed();
checkIndex (parameterIndex, Types.NUMERIC, "BigDecimal");
return ((BigDecimal)callResult[parameterIndex-1]);
}
/*
* Get the value of a SQL BINARY or VARBINARY parameter as a Java
* byte[]
*
* @param parameterIndex the first parameter is 1, the second is 2,...
* @return the parameter value; if the value is SQL NULL, the result is null
* @exception SQLException if a database-access error occurs.
*/
public byte[] getBytes(int parameterIndex) throws SQLException
{
checkClosed();
checkIndex (parameterIndex, Types.VARBINARY, Types.BINARY, "Bytes");
return ((byte [])callResult[parameterIndex-1]);
}
/*
* Get the value of a SQL DATE parameter as a java.sql.Date object
*
* @param parameterIndex the first parameter is 1, the second is 2,...
* @return the parameter value; if the value is SQL NULL, the result is null
* @exception SQLException if a database-access error occurs.
*/
public java.sql.Date getDate(int parameterIndex) throws SQLException
{
checkClosed();
checkIndex (parameterIndex, Types.DATE, "Date");
return (java.sql.Date)callResult[parameterIndex-1];
}
/*
* Get the value of a SQL TIME parameter as a java.sql.Time object.
*
* @param parameterIndex the first parameter is 1, the second is 2,...
* @return the parameter value; if the value is SQL NULL, the result is null
* @exception SQLException if a database-access error occurs.
*/
public java.sql.Time getTime(int parameterIndex) throws SQLException
{
checkClosed();
checkIndex (parameterIndex, Types.TIME, "Time");
return (java.sql.Time)callResult[parameterIndex-1];
}
/*
* Get the value of a SQL TIMESTAMP parameter as a java.sql.Timestamp object.
*
* @param parameterIndex the first parameter is 1, the second is 2,...
* @return the parameter value; if the value is SQL NULL, the result is null
* @exception SQLException if a database-access error occurs.
*/
public java.sql.Timestamp getTimestamp(int parameterIndex)
throws SQLException
{
checkClosed();
checkIndex (parameterIndex, Types.TIMESTAMP, "Timestamp");
return (java.sql.Timestamp)callResult[parameterIndex-1];
}
// getObject returns a Java object for the parameter.
// See the JDBC spec's "Dynamic Programming" chapter for details.
/*
* Get the value of a parameter as a Java object.
*
* <p>This method returns a Java object whose type coresponds to the
* SQL type that was registered for this parameter using
* registerOutParameter.
*
* <P>Note that this method may be used to read datatabase-specific,
* abstract data types. This is done by specifying a targetSqlType
* of java.sql.types.OTHER, which allows the driver to return a
* database-specific Java type.
*
* <p>See the JDBC spec's "Dynamic Programming" chapter for details.
*
* @param parameterIndex the first parameter is 1, the second is 2,...
* @return A java.lang.Object holding the OUT parameter value.
* @exception SQLException if a database-access error occurs.
*/
public Object getObject(int parameterIndex)
throws SQLException
{
checkClosed();
checkIndex (parameterIndex);
return callResult[parameterIndex-1];
}
/*
* Returns the SQL statement with the current template values
* substituted.
*/
public String toString()
{
if (preparedQuery == null)
return super.toString();
return preparedQuery.toString(preparedParameters);
}
/*
* Note if s is a String it should be escaped by the caller to avoid SQL
* injection attacks. It is not done here for efficency reasons as
* most calls to this method do not require escaping as the source
* of the string is known safe (i.e. Integer.toString())
*/
protected void bindLiteral(int paramIndex, String s, int oid) throws SQLException
{
if(adjustIndex)
paramIndex--;
preparedParameters.setLiteralParameter(paramIndex, s, oid);
}
/*
* This version is for values that should turn into strings
* e.g. setString directly calls bindString with no escaping;
* the per-protocol ParameterList does escaping as needed.
*/
private void bindString(int paramIndex, String s, int oid) throws SQLException
{
if (adjustIndex)
paramIndex--;
preparedParameters.setStringParameter( paramIndex, s, oid);
}
/**
* this method will turn a string of the form
* { [? =] call <some_function> [(?, [?,..])] }
* into the PostgreSQL format which is
* select <some_function> (?, [?, ...]) as result
* or select * from <some_function> (?, [?, ...]) as result (7.3)
*/
private String modifyJdbcCall(String p_sql) throws SQLException
{
checkClosed();
// Mini-parser for JDBC function-call syntax (only)
// TODO: Merge with escape processing (and parameter parsing?)
// so we only parse each query once.
isFunction = false;
boolean stdStrings = connection.getStandardConformingStrings();
int len = p_sql.length();
int state = 1;
boolean inQuotes = false, inEscape = false;
outParmBeforeFunc = false;
int startIndex = -1, endIndex = -1;
boolean syntaxError = false;
int i = 0;
while (i < len && !syntaxError)
{
char ch = p_sql.charAt(i);
switch (state)
{
case 1: // Looking for { at start of query
if (ch == '{')
{
++i;
++state;
}
else if (Character.isWhitespace(ch))
{
++i;
}
else
{
// Not function-call syntax. Skip the rest of the string.
i = len;
}
break;
case 2: // After {, looking for ? or =, skipping whitespace
if (ch == '?')
{
outParmBeforeFunc = isFunction = true; // { ? = call ... } -- function with one out parameter
++i;
++state;
}
else if (ch == 'c')
{ // { call ... } -- proc with no out parameters
state += 3; // Don't increase 'i'
}
else if (Character.isWhitespace(ch))
{
++i;
}
else
{
// "{ foo ...", doesn't make sense, complain.
syntaxError = true;
}
break;
case 3: // Looking for = after ?, skipping whitespace
if (ch == '=')
{
++i;
++state;
}
else if (Character.isWhitespace(ch))
{
++i;
}
else
{
syntaxError = true;
}
break;
case 4: // Looking for 'call' after '? =' skipping whitespace
if (ch == 'c' || ch == 'C')
{
++state; // Don't increase 'i'.
}
else if (Character.isWhitespace(ch))
{
++i;
}
else
{
syntaxError = true;
}
break;
case 5: // Should be at 'call ' either at start of string or after ?=
if ((ch == 'c' || ch == 'C') && i + 4 <= len && p_sql.substring(i, i + 4).equalsIgnoreCase("call"))
{
isFunction=true;
i += 4;
++state;
}
else if (Character.isWhitespace(ch))
{
++i;
}
else
{
syntaxError = true;
}
break;
case 6: // Looking for whitespace char after 'call'
if (Character.isWhitespace(ch))
{
// Ok, we found the start of the real call.
++i;
++state;
startIndex = i;
}
else
{
syntaxError = true;
}
break;
case 7: // In "body" of the query (after "{ [? =] call ")
if (ch == '\'')
{
inQuotes = !inQuotes;
++i;
}
else if (inQuotes && ch == '\\' && !stdStrings)
{
// Backslash in string constant, skip next character.
i += 2;
}
else if (!inQuotes && ch == '{')
{
inEscape = !inEscape;
++i;
}
else if (!inQuotes && ch == '}')
{
if (!inEscape)
{
// Should be end of string.
endIndex = i;
++i;
++state;
}
else
{
inEscape = false;
}
}
else if (!inQuotes && ch == ';')
{
syntaxError = true;
}
else
{
// Everything else is ok.
++i;
}
break;
case 8: // At trailing end of query, eating whitespace
if (Character.isWhitespace(ch))
{
++i;
}
else
{
syntaxError = true;
}
break;
default:
throw new IllegalStateException("somehow got into bad state " + state);
}
}
// We can only legally end in a couple of states here.
if (i == len && !syntaxError)
{
if (state == 1)
return p_sql; // Not an escaped syntax.
if (state != 8)
syntaxError = true; // Ran out of query while still parsing
}
if (syntaxError)
throw new PSQLException (GT.tr("Malformed function or procedure escape syntax at offset {0}.", new Integer(i)),
PSQLState.STATEMENT_NOT_ALLOWED_IN_FUNCTION_CALL);
if (connection.haveMinimumServerVersion("8.1") && ((AbstractJdbc2Connection)connection).getProtocolVersion() == 3)
{
String s = p_sql.substring(startIndex, endIndex );
StringBuffer sb = new StringBuffer(s);
if ( outParmBeforeFunc )
{
// move the single out parameter into the function call
// so that it can be treated like all other parameters
boolean needComma=false;
// have to use String.indexOf for java 2
int opening = s.indexOf('(')+1;
int closing = s.indexOf(')');
for ( int j=opening; j< closing;j++ )
{
if ( !Character.isWhitespace(sb.charAt(j)) )
{
needComma = true;
break;
}
}
if ( needComma )
{
sb.insert(opening, "?,");
}
else
{
sb.insert(opening, "?");
}
}
return "select * from " + sb.toString() + " as result";
}
else
{
return "select " + p_sql.substring(startIndex, endIndex) + " as result";
}
}
/** helperfunction for the getXXX calls to check isFunction and index == 1
* Compare BOTH type fields against the return type.
*/
protected void checkIndex (int parameterIndex, int type1, int type2, String getName)
throws SQLException
{
checkIndex (parameterIndex);
if (type1 != this.testReturn[parameterIndex-1] && type2 != this.testReturn[parameterIndex-1])
throw new PSQLException(GT.tr("Parameter of type {0} was registered, but call to get{1} (sqltype={2}) was made.",
new Object[]{"java.sql.Types=" + testReturn[parameterIndex-1],
getName,
"java.sql.Types=" + type1}),
PSQLState.MOST_SPECIFIC_TYPE_DOES_NOT_MATCH);
}
/** helperfunction for the getXXX calls to check isFunction and index == 1
*/
protected void checkIndex (int parameterIndex, int type, String getName)
throws SQLException
{
checkIndex (parameterIndex);
if (type != this.testReturn[parameterIndex-1])
throw new PSQLException(GT.tr("Parameter of type {0} was registered, but call to get{1} (sqltype={2}) was made.",
new Object[]{"java.sql.Types=" + testReturn[parameterIndex-1],
getName,
"java.sql.Types=" + type}),
PSQLState.MOST_SPECIFIC_TYPE_DOES_NOT_MATCH);
}
private void checkIndex (int parameterIndex) throws SQLException
{
checkIndex(parameterIndex, true);
}
/** helperfunction for the getXXX calls to check isFunction and index == 1
* @param parameterIndex index of getXXX (index)
* check to make sure is a function and index == 1
*/
private void checkIndex (int parameterIndex, boolean fetchingData) throws SQLException
{
if (!isFunction)
throw new PSQLException(GT.tr("A CallableStatement was declared, but no call to registerOutParameter(1, <some type>) was made."), PSQLState.STATEMENT_NOT_ALLOWED_IN_FUNCTION_CALL);
if (fetchingData) {
if (!returnTypeSet)
throw new PSQLException(GT.tr("No function outputs were registered."), PSQLState.OBJECT_NOT_IN_STATE);
if (callResult == null)
throw new PSQLException(GT.tr("Results cannot be retrieved from a CallableStatement before it is executed."), PSQLState.NO_DATA);
lastIndex = parameterIndex;
}
}
public void setPrepareThreshold(int newThreshold) throws SQLException {
checkClosed();
if (newThreshold < 0)
newThreshold = 0;
this.m_prepareThreshold = newThreshold;
}
public int getPrepareThreshold() {
return m_prepareThreshold;
}
public void setUseServerPrepare(boolean flag) throws SQLException {
setPrepareThreshold(flag ? 1 : 0);
}
public boolean isUseServerPrepare() {
return (preparedQuery != null && m_prepareThreshold != 0 && m_useCount + 1 >= m_prepareThreshold);
}
protected void checkClosed() throws SQLException
{
if (isClosed)
throw new PSQLException(GT.tr("This statement has been closed."),
PSQLState.OBJECT_NOT_IN_STATE);
}
// ** JDBC 2 Extensions **
public void addBatch(String p_sql) throws SQLException
{
checkClosed();
if (preparedQuery != null)
throw new PSQLException(GT.tr("Can''t use query methods that take a query string on a PreparedStatement."),
PSQLState.WRONG_OBJECT_TYPE);
if (batchStatements == null)
{
batchStatements = new ArrayList();
batchParameters = new ArrayList();
}
p_sql = replaceProcessing(p_sql);
batchStatements.add(connection.getQueryExecutor().createSimpleQuery(p_sql));
batchParameters.add(null);
}
public void clearBatch() throws SQLException
{
if (batchStatements != null)
{
batchStatements.clear();
batchParameters.clear();
}
}
//
// ResultHandler for batch queries.
//
private class BatchResultHandler implements ResultHandler {
private BatchUpdateException batchException = null;
private int resultIndex = 0;
private final Query[] queries;
private final ParameterList[] parameterLists;
private final int[] updateCounts;
BatchResultHandler(Query[] queries, ParameterList[] parameterLists, int[] updateCounts) {
this.queries = queries;
this.parameterLists = parameterLists;
this.updateCounts = updateCounts;
}
public void handleResultRows(Query fromQuery, Field[] fields, Vector tuples, ResultCursor cursor) {
handleError(new PSQLException(GT.tr("A result was returned when none was expected."),
PSQLState.TOO_MANY_RESULTS));
}
public void handleCommandStatus(String status, int updateCount, long insertOID) {
if (resultIndex >= updateCounts.length)
{
handleError(new PSQLException(GT.tr("Too many update results were returned."),
PSQLState.TOO_MANY_RESULTS));
return ;
}
updateCounts[resultIndex++] = updateCount;
}
public void handleWarning(SQLWarning warning) {
AbstractJdbc2Statement.this.addWarning(warning);
}
public void handleError(SQLException newError) {
if (batchException == null)
{
int[] successCounts;
if (resultIndex >= updateCounts.length)
successCounts = updateCounts;
else
{
successCounts = new int[resultIndex];
System.arraycopy(updateCounts, 0, successCounts, 0, resultIndex);
}
String queryString = "<unknown>";
if (resultIndex < queries.length)
queryString = queries[resultIndex].toString(parameterLists[resultIndex]);
batchException = new BatchUpdateException(GT.tr("Batch entry {0} {1} was aborted. Call getNextException to see the cause.",
new Object[]{ new Integer(resultIndex),
queryString}),
newError.getSQLState(),
successCounts);
}
batchException.setNextException(newError);
}
public void handleCompletion() throws SQLException {
if (batchException != null)
throw batchException;
}
}
private class CallableBatchResultHandler implements ResultHandler {
private BatchUpdateException batchException = null;
private int resultIndex = 0;
private final Query[] queries;
private final ParameterList[] parameterLists;
private final int[] updateCounts;
CallableBatchResultHandler(Query[] queries, ParameterList[] parameterLists, int[] updateCounts) {
this.queries = queries;
this.parameterLists = parameterLists;
this.updateCounts = updateCounts;
}
public void handleResultRows(Query fromQuery, Field[] fields, Vector tuples, ResultCursor cursor)
{
}
public void handleCommandStatus(String status, int updateCount, long insertOID) {
if (resultIndex >= updateCounts.length)
{
handleError(new PSQLException(GT.tr("Too many update results were returned."),
PSQLState.TOO_MANY_RESULTS));
return ;
}
updateCounts[resultIndex++] = updateCount;
}
public void handleWarning(SQLWarning warning) {
AbstractJdbc2Statement.this.addWarning(warning);
}
public void handleError(SQLException newError) {
if (batchException == null)
{
int[] successCounts;
if (resultIndex >= updateCounts.length)
successCounts = updateCounts;
else
{
successCounts = new int[resultIndex];
System.arraycopy(updateCounts, 0, successCounts, 0, resultIndex);
}
String queryString = "<unknown>";
if (resultIndex < queries.length)
queryString = queries[resultIndex].toString(parameterLists[resultIndex]);
batchException = new BatchUpdateException(GT.tr("Batch entry {0} {1} was aborted. Call getNextException to see the cause.",
new Object[]{ new Integer(resultIndex),
queryString}),
newError.getSQLState(),
successCounts);
}
batchException.setNextException(newError);
}
public void handleCompletion() throws SQLException {
if (batchException != null)
throw batchException;
}
}
public int[] executeBatch() throws SQLException
{
checkClosed();
// Every statement execution clears any previous warnings.
clearWarnings();
if (batchStatements == null || batchStatements.isEmpty())
return new int[0];
int size = batchStatements.size();
int[] updateCounts = new int[size];
// Construct query/parameter arrays.
Query[] queries = (Query[])batchStatements.toArray(new Query[batchStatements.size()]);
ParameterList[] parameterLists = (ParameterList[])batchParameters.toArray(new ParameterList[batchParameters.size()]);
batchStatements.clear();
batchParameters.clear();
// Close any existing resultsets associated with this statement.
while (firstUnclosedResult != null)
{
if (firstUnclosedResult.getResultSet() != null)
{
firstUnclosedResult.getResultSet().close();
}
firstUnclosedResult = firstUnclosedResult.getNext();
}
if (lastSimpleQuery != null) {
lastSimpleQuery.close();
lastSimpleQuery = null;
}
int flags = QueryExecutor.QUERY_NO_RESULTS;
// Only use named statements after we hit the threshold
if (preparedQuery != null)
{
m_useCount += queries.length;
}
if (m_prepareThreshold == 0 || m_useCount < m_prepareThreshold)
flags |= QueryExecutor.QUERY_ONESHOT;
if (connection.getAutoCommit())
flags |= QueryExecutor.QUERY_SUPPRESS_BEGIN;
result = null;
ResultHandler handler;
if (isFunction) {
handler = new CallableBatchResultHandler(queries, parameterLists, updateCounts );
} else {
handler = new BatchResultHandler(queries, parameterLists, updateCounts);
}
connection.getQueryExecutor().execute(queries,
parameterLists,
handler,
maxrows,
fetchSize,
flags);
return updateCounts;
}
/*
* Cancel can be used by one thread to cancel a statement that
* is being executed by another thread.
* <p>
*
* @exception SQLException only because thats the spec.
*/
public void cancel() throws SQLException
{
connection.cancelQuery();
}
public Connection getConnection() throws SQLException
{
return (Connection) connection;
}
public int getFetchDirection()
{
return fetchdirection;
}
public int getResultSetConcurrency()
{
return concurrency;
}
public int getResultSetType()
{
return resultsettype;
}
public void setFetchDirection(int direction) throws SQLException
{
switch (direction)
{
case ResultSet.FETCH_FORWARD:
case ResultSet.FETCH_REVERSE:
case ResultSet.FETCH_UNKNOWN:
fetchdirection = direction;
break;
default:
throw new PSQLException(GT.tr("Invalid fetch direction constant: {0}.", new Integer(direction)),
PSQLState.INVALID_PARAMETER_VALUE);
}
}
public void setFetchSize(int rows) throws SQLException
{
checkClosed();
if (rows < 0)
throw new PSQLException(GT.tr("Fetch size must be a value greater to or equal to 0."),
PSQLState.INVALID_PARAMETER_VALUE);
fetchSize = rows;
}
public void addBatch() throws SQLException
{
checkClosed();
if (batchStatements == null)
{
batchStatements = new ArrayList();
batchParameters = new ArrayList();
}
// we need to create copies of our parameters, otherwise the values can be changed
batchStatements.add(preparedQuery);
batchParameters.add(preparedParameters.copy());
}
public ResultSetMetaData getMetaData() throws SQLException
{
checkClosed();
ResultSet rs = getResultSet();
if (rs == null) {
// OK, we haven't executed it yet, we've got to go to the backend
// for more info. We send the full query, but just don't
// execute it.
int flags = QueryExecutor.QUERY_ONESHOT | QueryExecutor.QUERY_DESCRIBE_ONLY | QueryExecutor.QUERY_SUPPRESS_BEGIN;
StatementResultHandler handler = new StatementResultHandler();
connection.getQueryExecutor().execute(preparedQuery, preparedParameters, handler, 0, 0, flags);
ResultWrapper wrapper = handler.getResults();
if (wrapper != null) {
rs = wrapper.getResultSet();
}
}
if (rs != null)
return rs.getMetaData();
return null;
}
public void setArray(int i, java.sql.Array x) throws SQLException
{
checkClosed();
if (null == x)
{
setNull(i, Types.ARRAY);
return;
}
// This only works for Array implementations that return a valid array
// literal from Array.toString(), such as the implementation we return
// from ResultSet.getArray(). Eventually we need a proper implementation
// here that works for any Array implementation.
// Use a typename that is "_" plus the base type; this matches how the
// backend looks for array types.
String typename = "_" + x.getBaseTypeName();
int oid = connection.getTypeInfo().getPGType(typename);
if (oid == Oid.UNSPECIFIED)
throw new PSQLException(GT.tr("Unknown type {0}.", typename), PSQLState.INVALID_PARAMETER_TYPE);
setString(i, x.toString(), oid);
}
public void setBlob(int i, Blob x) throws SQLException
{
checkClosed();
if (x == null)
{
setNull(i, Types.BLOB);
return;
}
InputStream l_inStream = x.getBinaryStream();
LargeObjectManager lom = connection.getLargeObjectAPI();
long oid = lom.createLO();
LargeObject lob = lom.open(oid);
OutputStream los = lob.getOutputStream();
byte[] buf = new byte[4096];
try
{
// could be buffered, but then the OutputStream returned by LargeObject
// is buffered internally anyhow, so there would be no performance
// boost gained, if anything it would be worse!
int bytesRemaining = (int)x.length();
int numRead = l_inStream.read(buf, 0, Math.min(buf.length, bytesRemaining));
while (numRead != -1 && bytesRemaining > 0)
{
bytesRemaining -= numRead;
if ( numRead == buf.length )
los.write(buf); // saves a buffer creation and copy in LargeObject since it's full
else
los.write(buf, 0, numRead);
numRead = l_inStream.read(buf, 0, Math.min(buf.length, bytesRemaining));
}
}
catch (IOException se)
{
throw new PSQLException(GT.tr("Unexpected error writing large object to database."), PSQLState.UNEXPECTED_ERROR, se);
}
finally
{
try
{
los.close();
l_inStream.close();
}
catch ( Exception e )
{
}
}
setLong(i, oid);
}
public void setCharacterStream(int i, java.io.Reader x, int length) throws SQLException
{
checkClosed();
if (x == null) {
if (connection.haveMinimumServerVersion("7.2")) {
setNull(i, Types.VARCHAR);
} else {
setNull(i, Types.CLOB);
}
return;
}
if (length < 0)
throw new PSQLException(GT.tr("Invalid stream length {0}.", new Integer(length)),
PSQLState.INVALID_PARAMETER_VALUE);
if (connection.haveMinimumCompatibleVersion("7.2"))
{
//Version 7.2 supports CharacterStream for for the PG text types
//As the spec/javadoc for this method indicate this is to be used for
//large text values (i.e. LONGVARCHAR) PG doesn't have a separate
//long varchar datatype, but with toast all the text datatypes are capable of
//handling very large values. Thus the implementation ends up calling
//setString() since there is no current way to stream the value to the server
char[] l_chars = new char[length];
int l_charsRead = 0;
try
{
while (true)
{
int n = x.read(l_chars, l_charsRead, length - l_charsRead);
if (n == -1)
break;
l_charsRead += n;
if (l_charsRead == length)
break;
}
}
catch (IOException l_ioe)
{
throw new PSQLException(GT.tr("Provided Reader failed."), PSQLState.UNEXPECTED_ERROR, l_ioe);
}
setString(i, new String(l_chars, 0, l_charsRead));
}
else
{
//Version 7.1 only supported streams for LargeObjects
//but the jdbc spec indicates that streams should be
//available for LONGVARCHAR instead
LargeObjectManager lom = connection.getLargeObjectAPI();
long oid = lom.createLO();
LargeObject lob = lom.open(oid);
OutputStream los = lob.getOutputStream();
try
{
// could be buffered, but then the OutputStream returned by LargeObject
// is buffered internally anyhow, so there would be no performance
// boost gained, if anything it would be worse!
int c = x.read();
int p = 0;
while (c > -1 && p < length)
{
los.write(c);
c = x.read();
p++;
}
los.close();
}
catch (IOException se)
{
throw new PSQLException(GT.tr("Unexpected error writing large object to database."), PSQLState.UNEXPECTED_ERROR, se);
}
// lob is closed by the stream so don't call lob.close()
setLong(i, oid);
}
}
public void setClob(int i, Clob x) throws SQLException
{
checkClosed();
if (x == null)
{
setNull(i, Types.CLOB);
return;
}
InputStream l_inStream = x.getAsciiStream();
int l_length = (int) x.length();
LargeObjectManager lom = connection.getLargeObjectAPI();
long oid = lom.createLO();
LargeObject lob = lom.open(oid);
OutputStream los = lob.getOutputStream();
try
{
// could be buffered, but then the OutputStream returned by LargeObject
// is buffered internally anyhow, so there would be no performance
// boost gained, if anything it would be worse!
int c = l_inStream.read();
int p = 0;
while (c > -1 && p < l_length)
{
los.write(c);
c = l_inStream.read();
p++;
}
los.close();
}
catch (IOException se)
{
throw new PSQLException(GT.tr("Unexpected error writing large object to database."), PSQLState.UNEXPECTED_ERROR, se);
}
// lob is closed by the stream so don't call lob.close()
setLong(i, oid);
}
public void setNull(int i, int t, String s) throws SQLException
{
checkClosed();
setNull(i, t);
}
public void setRef(int i, Ref x) throws SQLException
{
throw Driver.notImplemented(this.getClass(), "setRef(int,Ref)");
}
public void setDate(int i, java.sql.Date d, java.util.Calendar cal) throws SQLException
{
checkClosed();
if (d == null)
{
setNull(i, Types.DATE);
return;
}
if (cal != null)
cal = (Calendar)cal.clone();
// We must use UNSPECIFIED here, or inserting a Date-with-timezone into a
// timestamptz field does an unexpected rotation by the server's TimeZone:
//
// We want to interpret 2005/01/01 with calendar +0100 as
// "local midnight in +0100", but if we go via date it interprets it
// as local midnight in the server's timezone:
// template1=# select '2005-01-01+0100'::timestamptz;
// timestamptz
// ------------------------
// 2005-01-01 02:00:00+03
// (1 row)
// template1=# select '2005-01-01+0100'::date::timestamptz;
// timestamptz
// ------------------------
// 2005-01-01 00:00:00+03
// (1 row)
bindString(i, connection.getTimestampUtils().toString(cal, d), Oid.UNSPECIFIED);
}
public void setTime(int i, Time t, java.util.Calendar cal) throws SQLException
{
checkClosed();
if (t == null)
{
setNull(i, Types.TIME);
return;
}
if (cal != null)
cal = (Calendar)cal.clone();
bindString(i, connection.getTimestampUtils().toString(cal, t), Oid.UNSPECIFIED);
}
public void setTimestamp(int i, Timestamp t, java.util.Calendar cal) throws SQLException
{
checkClosed();
if (t == null) {
setNull(i, Types.TIMESTAMP);
return;
}
if (cal != null)
cal = (Calendar)cal.clone();
// Use UNSPECIFIED as a compromise to get both TIMESTAMP and TIMESTAMPTZ working.
// This is because you get this in a +1300 timezone:
//
// template1=# select '2005-01-01 15:00:00 +1000'::timestamptz;
// timestamptz
// ------------------------
// 2005-01-01 18:00:00+13
// (1 row)
// template1=# select '2005-01-01 15:00:00 +1000'::timestamp;
// timestamp
// ---------------------
// 2005-01-01 15:00:00
// (1 row)
// template1=# select '2005-01-01 15:00:00 +1000'::timestamptz::timestamp;
// timestamp
// ---------------------
// 2005-01-01 18:00:00
// (1 row)
// So we want to avoid doing a timestamptz -> timestamp conversion, as that
// will first convert the timestamptz to an equivalent time in the server's
// timezone (+1300, above), then turn it into a timestamp with the "wrong"
// time compared to the string we originally provided. But going straight
// to timestamp is OK as the input parser for timestamp just throws away
// the timezone part entirely. Since we don't know ahead of time what type
// we're actually dealing with, UNSPECIFIED seems the lesser evil, even if it
// does give more scope for type-mismatch errors being silently hidden.
bindString(i, connection.getTimestampUtils().toString(cal, t), Oid.UNSPECIFIED); // Let the server infer the right type.
}
// ** JDBC 2 Extensions for CallableStatement**
public java.sql.Array getArray(int i) throws SQLException
{
checkClosed();
checkIndex(i, Types.ARRAY, "Array");
return (Array)callResult[i-1];
}
public java.math.BigDecimal getBigDecimal(int parameterIndex) throws SQLException
{
checkClosed();
checkIndex (parameterIndex, Types.NUMERIC, "BigDecimal");
return ((BigDecimal)callResult[parameterIndex-1]);
}
public Blob getBlob(int i) throws SQLException
{
throw Driver.notImplemented(this.getClass(), "getBlob(int)");
}
public Clob getClob(int i) throws SQLException
{
throw Driver.notImplemented(this.getClass(), "getClob(int)");
}
public Object getObjectImpl(int i, java.util.Map map) throws SQLException
{
if (map == null || map.isEmpty()) {
return getObject(i);
}
throw Driver.notImplemented(this.getClass(), "getObjectImpl(int,Map)");
}
public Ref getRef(int i) throws SQLException
{
throw Driver.notImplemented(this.getClass(), "getRef(int)");
}
public java.sql.Date getDate(int i, java.util.Calendar cal) throws SQLException
{
checkClosed();
checkIndex(i, Types.DATE, "Date");
if (callResult[i-1] == null)
return null;
if (cal != null)
cal = (Calendar)cal.clone();
String value = callResult[i-1].toString();
return connection.getTimestampUtils().toDate(cal, value);
}
public Time getTime(int i, java.util.Calendar cal) throws SQLException
{
checkClosed();
checkIndex(i, Types.TIME, "Time");
if (callResult[i-1] == null)
return null;
if (cal != null)
cal = (Calendar)cal.clone();
String value = callResult[i-1].toString();
return connection.getTimestampUtils().toTime(cal, value);
}
public Timestamp getTimestamp(int i, java.util.Calendar cal) throws SQLException
{
checkClosed();
checkIndex(i, Types.TIMESTAMP, "Timestamp");
if (callResult[i-1] == null)
return null;
if (cal != null)
cal = (Calendar)cal.clone();
String value = callResult[i-1].toString();
return connection.getTimestampUtils().toTimestamp(cal, value);
}
// no custom types allowed yet..
public void registerOutParameter(int parameterIndex, int sqlType, String typeName) throws SQLException
{
throw Driver.notImplemented(this.getClass(), "registerOutParameter(int,int,String)");
}
}
|