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
|
/*-------------------------------------------------------------------------
*
* Copyright (c) 2003-2008, PostgreSQL Global Development Group
*
* IDENTIFICATION
* $PostgreSQL: pgjdbc/org/postgresql/jdbc2/AbstractJdbc2ResultSet.java,v 1.107 2009/04/19 16:11:48 jurka Exp $
*
*-------------------------------------------------------------------------
*/
package org.postgresql.jdbc2;
import java.io.CharArrayReader;
import java.io.InputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.io.ByteArrayInputStream;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.*;
import java.util.HashMap;
import java.util.Iterator;
import java.util.StringTokenizer;
import java.util.Vector;
import java.util.Calendar;
import java.util.Locale;
import org.postgresql.core.*;
import org.postgresql.largeobject.*;
import org.postgresql.util.PGobject;
import org.postgresql.util.PGbytea;
import org.postgresql.util.PGtokenizer;
import org.postgresql.util.PSQLException;
import org.postgresql.util.PSQLState;
import org.postgresql.util.GT;
public abstract class AbstractJdbc2ResultSet implements BaseResultSet, org.postgresql.PGRefCursorResultSet
{
//needed for updateable result set support
private boolean updateable = false;
private boolean doingUpdates = false;
private HashMap updateValues = null;
private boolean usingOID = false; // are we using the OID for the primary key?
private Vector primaryKeys; // list of primary keys
private boolean singleTable = false;
private String onlyTable = "";
private String tableName = null;
private PreparedStatement updateStatement = null;
private PreparedStatement insertStatement = null;
private PreparedStatement deleteStatement = null;
private PreparedStatement selectStatement = null;
private final int resultsettype;
private final int resultsetconcurrency;
private int fetchdirection = ResultSet.FETCH_UNKNOWN;
protected final BaseConnection connection; // the connection we belong to
protected final BaseStatement statement; // the statement we belong to
protected final Field fields[]; // Field metadata for this resultset.
protected final Query originalQuery; // Query we originated from
protected final int maxRows; // Maximum rows in this resultset (might be 0).
protected final int maxFieldSize; // Maximum field size in this resultset (might be 0).
protected Vector rows; // Current page of results.
protected int current_row = -1; // Index into 'rows' of our currrent row (0-based)
protected int row_offset; // Offset of row 0 in the actual resultset
protected byte[][] this_row; // copy of the current result row
protected SQLWarning warnings = null; // The warning chain
/**
* True if the last obtained column value was SQL NULL as specified by
* {@link #wasNull}. The value is always updated by the
* {@link #checkResultSet} method.
*/
protected boolean wasNullFlag = false;
protected boolean onInsertRow = false; // are we on the insert row (for JDBC2 updatable resultsets)?
private byte[][] rowBuffer = null; // updateable rowbuffer
protected int fetchSize; // Current fetch size (might be 0).
protected ResultCursor cursor; // Cursor for fetching additional data.
private HashMap columnNameIndexMap; // Speed up findColumn by caching lookups
public abstract ResultSetMetaData getMetaData() throws SQLException;
public AbstractJdbc2ResultSet(Query originalQuery, BaseStatement statement, Field[] fields, Vector tuples,
ResultCursor cursor, int maxRows, int maxFieldSize,
int rsType, int rsConcurrency) throws SQLException
{
this.originalQuery = originalQuery;
this.connection = (BaseConnection) statement.getConnection();
this.statement = statement;
this.fields = fields;
this.rows = tuples;
this.cursor = cursor;
this.maxRows = maxRows;
this.maxFieldSize = maxFieldSize;
this.resultsettype = rsType;
this.resultsetconcurrency = rsConcurrency;
}
public java.net.URL getURL(int columnIndex) throws SQLException
{
checkClosed();
throw org.postgresql.Driver.notImplemented(this.getClass(), "getURL(int)");
}
public java.net.URL getURL(String columnName) throws SQLException
{
return getURL(findColumn(columnName));
}
protected Object internalGetObject(int columnIndex, Field field) throws SQLException
{
switch (getSQLType(columnIndex))
{
case Types.BIT:
// Also Types.BOOLEAN in JDBC3
return getBoolean(columnIndex) ? Boolean.TRUE : Boolean.FALSE;
case Types.TINYINT:
case Types.SMALLINT:
case Types.INTEGER:
return new Integer(getInt(columnIndex));
case Types.BIGINT:
return new Long(getLong(columnIndex));
case Types.NUMERIC:
case Types.DECIMAL:
return getBigDecimal
(columnIndex, (field.getMod() == -1) ? -1 : ((field.getMod() - 4) & 0xffff));
case Types.REAL:
return new Float(getFloat(columnIndex));
case Types.FLOAT:
case Types.DOUBLE:
return new Double(getDouble(columnIndex));
case Types.CHAR:
case Types.VARCHAR:
case Types.LONGVARCHAR:
return getString(columnIndex);
case Types.DATE:
return getDate(columnIndex);
case Types.TIME:
return getTime(columnIndex);
case Types.TIMESTAMP:
return getTimestamp(columnIndex, null);
case Types.BINARY:
case Types.VARBINARY:
case Types.LONGVARBINARY:
return getBytes(columnIndex);
case Types.ARRAY:
return getArray(columnIndex);
case Types.CLOB:
return getClob(columnIndex);
case Types.BLOB:
return getBlob(columnIndex);
default:
String type = getPGType(columnIndex);
// if the backend doesn't know the type then coerce to String
if (type.equals("unknown"))
return getString(columnIndex);
if (type.equals("uuid"))
return getUUID(getString(columnIndex));
// Specialized support for ref cursors is neater.
if (type.equals("refcursor"))
{
// Fetch all results.
String cursorName = getString(columnIndex);
StringBuffer sb = new StringBuffer("FETCH ALL IN ");
Utils.appendEscapedIdentifier(sb, cursorName);
// nb: no BEGIN triggered here. This is fine. If someone
// committed, and the cursor was not holdable (closing the
// cursor), we avoid starting a new xact and promptly causing
// it to fail. If the cursor *was* holdable, we don't want a
// new xact anyway since holdable cursor state isn't affected
// by xact boundaries. If our caller didn't commit at all, or
// autocommit was on, then we wouldn't issue a BEGIN anyway.
//
// We take the scrollability from the statement, but until
// we have updatable cursors it must be readonly.
ResultSet rs = connection.execSQLQuery(sb.toString(), resultsettype, ResultSet.CONCUR_READ_ONLY);
//
// In long running transactions these backend cursors take up memory space
// we could close in rs.close(), but if the transaction is closed before the result set, then
// the cursor no longer exists
sb.setLength(0);
sb.append("CLOSE ");
Utils.appendEscapedIdentifier(sb, cursorName);
connection.execSQLUpdate(sb.toString());
((AbstractJdbc2ResultSet)rs).setRefCursor(cursorName);
return rs;
}
// Caller determines what to do (JDBC3 overrides in this case)
return null;
}
}
private void checkScrollable() throws SQLException
{
checkClosed();
if (resultsettype == ResultSet.TYPE_FORWARD_ONLY)
throw new PSQLException(GT.tr("Operation requires a scrollable ResultSet, but this ResultSet is FORWARD_ONLY."),
PSQLState.INVALID_CURSOR_STATE);
}
public boolean absolute(int index) throws SQLException
{
checkScrollable();
// index is 1-based, but internally we use 0-based indices
int internalIndex;
if (index == 0)
{
beforeFirst();
return false;
}
final int rows_size = rows.size();
//if index<0, count from the end of the result set, but check
//to be sure that it is not beyond the first index
if (index < 0)
{
if (index >= -rows_size)
internalIndex = rows_size + index;
else
{
beforeFirst();
return false;
}
}
else
{
//must be the case that index>0,
//find the correct place, assuming that
//the index is not too large
if (index <= rows_size)
internalIndex = index - 1;
else
{
afterLast();
return false;
}
}
current_row = internalIndex;
initRowBuffer();
onInsertRow = false;
return true;
}
public void afterLast() throws SQLException
{
checkScrollable();
final int rows_size = rows.size();
if (rows_size > 0)
current_row = rows_size;
onInsertRow = false;
this_row = null;
rowBuffer = null;
}
public void beforeFirst() throws SQLException
{
checkScrollable();
if (rows.size() > 0)
current_row = -1;
onInsertRow = false;
this_row = null;
rowBuffer = null;
}
public boolean first() throws SQLException
{
checkScrollable();
if (rows.size() <= 0)
return false;
current_row = 0;
initRowBuffer();
onInsertRow = false;
return true;
}
public java.sql.Array getArray(String colName) throws SQLException
{
return getArray(findColumn(colName));
}
public java.sql.Array getArray(int i) throws SQLException
{
checkResultSet( i );
if (wasNullFlag)
return null;
return createArray(i);
}
public java.math.BigDecimal getBigDecimal(int columnIndex) throws SQLException
{
return getBigDecimal(columnIndex, -1);
}
public java.math.BigDecimal getBigDecimal(String columnName) throws SQLException
{
return getBigDecimal(findColumn(columnName));
}
public Blob getBlob(String columnName) throws SQLException
{
return getBlob(findColumn(columnName));
}
public abstract Blob getBlob(int i) throws SQLException;
public java.io.Reader getCharacterStream(String columnName) throws SQLException
{
return getCharacterStream(findColumn(columnName));
}
public java.io.Reader getCharacterStream(int i) throws SQLException
{
checkResultSet( i );
if (wasNullFlag)
return null;
if (((AbstractJdbc2Connection) connection).haveMinimumCompatibleVersion("7.2"))
{
//Version 7.2 supports AsciiStream for all 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 string datatype, but with toast the text datatype is capable of
//handling very large values. Thus the implementation ends up calling
//getString() since there is no current way to stream the value from the server
return new CharArrayReader(getString(i).toCharArray());
}
else
{
// In 7.1 Handle as BLOBS so return the LargeObject input stream
Encoding encoding = connection.getEncoding();
InputStream input = getBinaryStream(i);
try
{
return encoding.getDecodingReader(input);
}
catch (IOException ioe)
{
throw new PSQLException(GT.tr("Unexpected error while decoding character data from a large object."), PSQLState.UNEXPECTED_ERROR, ioe);
}
}
}
public Clob getClob(String columnName) throws SQLException
{
return getClob(findColumn(columnName));
}
public abstract Clob getClob(int i) throws SQLException;
public int getConcurrency() throws SQLException
{
checkClosed();
return resultsetconcurrency;
}
public java.sql.Date getDate(int i, java.util.Calendar cal) throws SQLException
{
checkResultSet(i);
if (wasNullFlag)
return null;
if (cal != null)
cal = (Calendar)cal.clone();
return connection.getTimestampUtils().toDate(cal, getString(i));
}
public Time getTime(int i, java.util.Calendar cal) throws SQLException
{
checkResultSet(i);
if (wasNullFlag)
return null;
if (cal != null)
cal = (Calendar)cal.clone();
return connection.getTimestampUtils().toTime(cal, getString(i));
}
public Timestamp getTimestamp(int i, java.util.Calendar cal) throws SQLException
{
checkResultSet(i);
if (wasNullFlag)
return null;
if (cal != null)
cal = (Calendar)cal.clone();
// If this is actually a timestamptz, the server-provided timezone will override
// the one we pass in, which is the desired behaviour. Otherwise, we'll
// interpret the timezone-less value in the provided timezone.
return connection.getTimestampUtils().toTimestamp(cal, getString(i));
}
public java.sql.Date getDate(String c, java.util.Calendar cal) throws SQLException
{
return getDate(findColumn(c), cal);
}
public Time getTime(String c, java.util.Calendar cal) throws SQLException
{
return getTime(findColumn(c), cal);
}
public Timestamp getTimestamp(String c, java.util.Calendar cal) throws SQLException
{
return getTimestamp(findColumn(c), cal);
}
public int getFetchDirection() throws SQLException
{
checkClosed();
return fetchdirection;
}
public Object getObjectImpl(String columnName, java.util.Map map) throws SQLException
{
return getObjectImpl(findColumn(columnName), map);
}
/*
* This checks against map for the type of column i, and if found returns
* an object based on that mapping. The class must implement the SQLData
* interface.
*/
public Object getObjectImpl(int i, java.util.Map map) throws SQLException
{
checkClosed();
if (map == null || map.isEmpty()) {
return getObject(i);
}
throw org.postgresql.Driver.notImplemented(this.getClass(), "getObjectImpl(int,Map)");
}
public Ref getRef(String columnName) throws SQLException
{
return getRef(findColumn(columnName));
}
public Ref getRef(int i) throws SQLException
{
checkClosed();
//The backend doesn't yet have SQL3 REF types
throw org.postgresql.Driver.notImplemented(this.getClass(), "getRef(int)");
}
public int getRow() throws SQLException
{
checkClosed();
if (onInsertRow)
return 0;
final int rows_size = rows.size();
if (current_row < 0 || current_row >= rows_size)
return 0;
return row_offset + current_row + 1;
}
// This one needs some thought, as not all ResultSets come from a statement
public Statement getStatement() throws SQLException
{
checkClosed();
return (Statement) statement;
}
public int getType() throws SQLException
{
checkClosed();
return resultsettype;
}
public boolean isAfterLast() throws SQLException
{
checkClosed();
if (onInsertRow)
return false;
final int rows_size = rows.size();
return (current_row >= rows_size && rows_size > 0);
}
public boolean isBeforeFirst() throws SQLException
{
checkClosed();
if (onInsertRow)
return false;
return ((row_offset + current_row) < 0 && rows.size() > 0);
}
public boolean isFirst() throws SQLException
{
checkClosed();
if (onInsertRow)
return false;
return ((row_offset + current_row) == 0);
}
public boolean isLast() throws SQLException
{
checkClosed();
if (onInsertRow)
return false;
final int rows_size = rows.size();
if (rows_size == 0)
return false; // No rows.
if (current_row != (rows_size - 1))
return false; // Not on the last row of this block.
// We are on the last row of the current block.
if (cursor == null)
{
// This is the last block and therefore the last row.
return true;
}
if (maxRows > 0 && row_offset + current_row == maxRows)
{
// We are implicitly limited by maxRows.
return true;
}
// Now the more painful case begins.
// We are on the last row of the current block, but we don't know if the
// current block is the last block; we must try to fetch some more data to
// find out.
// We do a fetch of the next block, then prepend the current row to that
// block (so current_row == 0). This works as the current row
// must be the last row of the current block if we got this far.
row_offset += rows_size - 1; // Discarding all but one row.
// Work out how many rows maxRows will let us fetch.
int fetchRows = fetchSize;
if (maxRows != 0)
{
if (fetchRows == 0 || row_offset + fetchRows > maxRows) // Fetch would exceed maxRows, limit it.
fetchRows = maxRows - row_offset;
}
// Do the actual fetch.
connection.getQueryExecutor().fetch(cursor, new CursorResultHandler(), fetchRows);
// Now prepend our one saved row and move to it.
rows.insertElementAt(this_row, 0);
current_row = 0;
// Finally, now we can tell if we're the last row or not.
return (rows.size() == 1);
}
public boolean last() throws SQLException
{
checkScrollable();
final int rows_size = rows.size();
if (rows_size <= 0)
return false;
current_row = rows_size - 1;
initRowBuffer();
onInsertRow = false;
return true;
}
public boolean previous() throws SQLException
{
checkScrollable();
if (onInsertRow)
throw new PSQLException(GT.tr("Can''t use relative move methods while on the insert row."),
PSQLState.INVALID_CURSOR_STATE);
if (current_row -1 < 0)
{
current_row = -1;
this_row = null;
rowBuffer = null;
return false;
}
else
{
current_row--;
}
initRowBuffer();
return true;
}
public boolean relative(int rows) throws SQLException
{
checkScrollable();
if (onInsertRow)
throw new PSQLException(GT.tr("Can''t use relative move methods while on the insert row."),
PSQLState.INVALID_CURSOR_STATE);
//have to add 1 since absolute expects a 1-based index
return absolute(current_row + 1 + rows);
}
public void setFetchDirection(int direction) throws SQLException
{
checkClosed();
switch (direction)
{
case ResultSet.FETCH_FORWARD:
break;
case ResultSet.FETCH_REVERSE:
case ResultSet.FETCH_UNKNOWN:
checkScrollable();
break;
default:
throw new PSQLException(GT.tr("Invalid fetch direction constant: {0}.", new Integer(direction)),
PSQLState.INVALID_PARAMETER_VALUE);
}
this.fetchdirection = direction;
}
public synchronized void cancelRowUpdates()
throws SQLException
{
checkClosed();
if (onInsertRow)
{
throw new PSQLException(GT.tr("Cannot call cancelRowUpdates() when on the insert row."),
PSQLState.INVALID_CURSOR_STATE);
}
if (doingUpdates)
{
doingUpdates = false;
clearRowBuffer(true);
}
}
public synchronized void deleteRow()
throws SQLException
{
checkUpdateable();
if (onInsertRow)
{
throw new PSQLException(GT.tr("Cannot call deleteRow() when on the insert row."),
PSQLState.INVALID_CURSOR_STATE);
}
if (isBeforeFirst())
{
throw new PSQLException(GT.tr("Currently positioned before the start of the ResultSet. You cannot call deleteRow() here."),
PSQLState.INVALID_CURSOR_STATE);
}
if (isAfterLast())
{
throw new PSQLException(GT.tr("Currently positioned after the end of the ResultSet. You cannot call deleteRow() here."),
PSQLState.INVALID_CURSOR_STATE);
}
if (rows.size() == 0)
{
throw new PSQLException(GT.tr("There are no rows in this ResultSet."),
PSQLState.INVALID_CURSOR_STATE);
}
int numKeys = primaryKeys.size();
if ( deleteStatement == null )
{
StringBuffer deleteSQL = new StringBuffer("DELETE FROM " ).append(onlyTable).append(tableName).append(" where " );
for ( int i = 0; i < numKeys; i++ )
{
Utils.appendEscapedIdentifier(deleteSQL, ((PrimaryKey)primaryKeys.get(i)).name);
deleteSQL.append(" = ?");
if ( i < numKeys - 1 )
{
deleteSQL.append( " and " );
}
}
deleteStatement = ((java.sql.Connection) connection).prepareStatement(deleteSQL.toString());
}
deleteStatement.clearParameters();
for ( int i = 0; i < numKeys; i++ )
{
deleteStatement.setObject(i + 1, ((PrimaryKey) primaryKeys.get(i)).getValue());
}
deleteStatement.executeUpdate();
rows.removeElementAt(current_row);
current_row--;
moveToCurrentRow();
}
public synchronized void insertRow()
throws SQLException
{
checkUpdateable();
if (!onInsertRow)
{
throw new PSQLException(GT.tr("Not on the insert row."), PSQLState.INVALID_CURSOR_STATE);
}
else if (updateValues.size() == 0)
{
throw new PSQLException(GT.tr("You must specify at least one column value to insert a row."),
PSQLState.INVALID_PARAMETER_VALUE);
}
else
{
// loop through the keys in the insertTable and create the sql statement
// we have to create the sql every time since the user could insert different
// columns each time
StringBuffer insertSQL = new StringBuffer("INSERT INTO ").append(tableName).append(" (");
StringBuffer paramSQL = new StringBuffer(") values (" );
Iterator columnNames = updateValues.keySet().iterator();
int numColumns = updateValues.size();
for ( int i = 0; columnNames.hasNext(); i++ )
{
String columnName = (String) columnNames.next();
Utils.appendEscapedIdentifier(insertSQL, columnName);
if ( i < numColumns - 1 )
{
insertSQL.append(", ");
paramSQL.append("?,");
}
else
{
paramSQL.append("?)");
}
}
insertSQL.append(paramSQL.toString());
insertStatement = ((java.sql.Connection) connection).prepareStatement(insertSQL.toString());
Iterator keys = updateValues.keySet().iterator();
for ( int i = 1; keys.hasNext(); i++)
{
String key = (String) keys.next();
Object o = updateValues.get(key);
insertStatement.setObject(i, o);
}
insertStatement.executeUpdate();
if ( usingOID )
{
// we have to get the last inserted OID and put it in the resultset
long insertedOID = ((AbstractJdbc2Statement) insertStatement).getLastOID();
updateValues.put("oid", new Long(insertedOID) );
}
// update the underlying row to the new inserted data
updateRowBuffer();
rows.addElement(rowBuffer);
// we should now reflect the current data in this_row
// that way getXXX will get the newly inserted data
this_row = rowBuffer;
// need to clear this in case of another insert
clearRowBuffer(false);
}
}
public synchronized void moveToCurrentRow()
throws SQLException
{
checkUpdateable();
if (current_row < 0 || current_row >= rows.size())
{
this_row = null;
rowBuffer = null;
}
else
{
initRowBuffer();
}
onInsertRow = false;
doingUpdates = false;
}
public synchronized void moveToInsertRow()
throws SQLException
{
checkUpdateable();
if (insertStatement != null)
{
insertStatement = null;
}
// make sure the underlying data is null
clearRowBuffer(false);
onInsertRow = true;
doingUpdates = false;
}
private synchronized void clearRowBuffer(boolean copyCurrentRow)
throws SQLException
{
// rowBuffer is the temporary storage for the row
rowBuffer = new byte[fields.length][];
// inserts want an empty array while updates want a copy of the current row
if (copyCurrentRow)
{
System.arraycopy(this_row, 0, rowBuffer, 0, this_row.length);
}
// clear the updateValues hashTable for the next set of updates
updateValues.clear();
}
public boolean rowDeleted() throws SQLException
{
checkClosed();
return false;
}
public boolean rowInserted() throws SQLException
{
checkClosed();
return false;
}
public boolean rowUpdated() throws SQLException
{
checkClosed();
return false;
}
public synchronized void updateAsciiStream(int columnIndex,
java.io.InputStream x,
int length
)
throws SQLException
{
if (x == null)
{
updateNull(columnIndex);
return ;
}
try
{
InputStreamReader reader = new InputStreamReader(x, "ASCII");
char data[] = new char[length];
int numRead = 0;
while (true)
{
int n = reader.read(data, numRead, length - numRead);
if (n == -1)
break;
numRead += n;
if (numRead == length)
break;
}
updateString(columnIndex, new String(data, 0, numRead));
}
catch (UnsupportedEncodingException uee)
{
throw new PSQLException(GT.tr("The JVM claims not to support the encoding: {0}","ASCII"), PSQLState.UNEXPECTED_ERROR, uee);
}
catch (IOException ie)
{
throw new PSQLException(GT.tr("Provided InputStream failed."), null, ie);
}
}
public synchronized void updateBigDecimal(int columnIndex,
java.math.BigDecimal x )
throws SQLException
{
updateValue(columnIndex, x);
}
public synchronized void updateBinaryStream(int columnIndex,
java.io.InputStream x,
int length
)
throws SQLException
{
if (x == null)
{
updateNull(columnIndex);
return ;
}
byte data[] = new byte[length];
int numRead = 0;
try
{
while (true)
{
int n = x.read(data, numRead, length - numRead);
if (n == -1)
break;
numRead += n;
if (numRead == length)
break;
}
}
catch (IOException ie)
{
throw new PSQLException(GT.tr("Provided InputStream failed."), null, ie);
}
if (numRead == length)
{
updateBytes(columnIndex, data);
}
else
{
// the stream contained less data than they said
// perhaps this is an error?
byte data2[] = new byte[numRead];
System.arraycopy(data, 0, data2, 0, numRead);
updateBytes(columnIndex, data2);
}
}
public synchronized void updateBoolean(int columnIndex, boolean x)
throws SQLException
{
updateValue(columnIndex, new Boolean(x));
}
public synchronized void updateByte(int columnIndex, byte x)
throws SQLException
{
updateValue(columnIndex, String.valueOf(x));
}
public synchronized void updateBytes(int columnIndex, byte[] x)
throws SQLException
{
updateValue(columnIndex, x);
}
public synchronized void updateCharacterStream(int columnIndex,
java.io.Reader x,
int length
)
throws SQLException
{
if (x == null)
{
updateNull(columnIndex);
return ;
}
try
{
char data[] = new char[length];
int numRead = 0;
while (true)
{
int n = x.read(data, numRead, length - numRead);
if (n == -1)
break;
numRead += n;
if (numRead == length)
break;
}
updateString(columnIndex, new String(data, 0, numRead));
}
catch (IOException ie)
{
throw new PSQLException(GT.tr("Provided Reader failed."), null, ie);
}
}
public synchronized void updateDate(int columnIndex, java.sql.Date x)
throws SQLException
{
updateValue(columnIndex, x);
}
public synchronized void updateDouble(int columnIndex, double x)
throws SQLException
{
updateValue(columnIndex, new Double(x));
}
public synchronized void updateFloat(int columnIndex, float x)
throws SQLException
{
updateValue(columnIndex, new Float(x));
}
public synchronized void updateInt(int columnIndex, int x)
throws SQLException
{
updateValue(columnIndex, new Integer(x));
}
public synchronized void updateLong(int columnIndex, long x)
throws SQLException
{
updateValue(columnIndex, new Long(x));
}
public synchronized void updateNull(int columnIndex)
throws SQLException
{
checkColumnIndex(columnIndex);
String columnTypeName = connection.getTypeInfo().getPGType(fields[columnIndex - 1].getOID());
updateValue(columnIndex, new NullObject(columnTypeName));
}
public synchronized void updateObject(int columnIndex, Object x)
throws SQLException
{
updateValue(columnIndex, x);
}
public synchronized void updateObject(int columnIndex, Object x, int scale)
throws SQLException
{
this.updateObject(columnIndex, x);
}
public void refreshRow() throws SQLException
{
checkUpdateable();
if (onInsertRow)
throw new PSQLException(GT.tr("Can''t refresh the insert row."),
PSQLState.INVALID_CURSOR_STATE);
if (isBeforeFirst() || isAfterLast() || rows.size() == 0)
return ;
StringBuffer selectSQL = new StringBuffer( "select ");
final int numColumns = java.lang.reflect.Array.getLength(fields);
for (int i = 0; i < numColumns; i++ )
{
selectSQL.append( fields[i].getColumnName(connection) );
if ( i < numColumns - 1 )
{
selectSQL.append(", ");
}
}
selectSQL.append(" from " ).append(onlyTable).append(tableName).append(" where ");
int numKeys = primaryKeys.size();
for ( int i = 0; i < numKeys; i++ )
{
PrimaryKey primaryKey = ((PrimaryKey) primaryKeys.get(i));
selectSQL.append(primaryKey.name).append("= ?");
if ( i < numKeys - 1 )
{
selectSQL.append(" and ");
}
}
if ( connection.getLogger().logDebug() )
connection.getLogger().debug("selecting " + selectSQL.toString());
selectStatement = ((java.sql.Connection) connection).prepareStatement(selectSQL.toString());
for ( int j = 0, i = 1; j < numKeys; j++, i++)
{
selectStatement.setObject( i, ((PrimaryKey) primaryKeys.get(j)).getValue() );
}
AbstractJdbc2ResultSet rs = (AbstractJdbc2ResultSet) selectStatement.executeQuery();
if ( rs.next() )
{
rowBuffer = rs.this_row;
}
rows.setElementAt( rowBuffer, current_row );
this_row = rowBuffer;
connection.getLogger().debug("done updates");
rs.close();
selectStatement.close();
selectStatement = null;
}
public synchronized void updateRow()
throws SQLException
{
checkUpdateable();
if (onInsertRow)
{
throw new PSQLException(GT.tr("Cannot call updateRow() when on the insert row."),
PSQLState.INVALID_CURSOR_STATE);
}
if (isBeforeFirst() || isAfterLast() || rows.size() == 0)
{
throw new PSQLException(GT.tr("Cannot update the ResultSet because it is either before the start or after the end of the results."),
PSQLState.INVALID_CURSOR_STATE);
}
if (!doingUpdates)
return; // No work pending.
StringBuffer updateSQL = new StringBuffer("UPDATE " + onlyTable + tableName + " SET ");
int numColumns = updateValues.size();
Iterator columns = updateValues.keySet().iterator();
for (int i = 0; columns.hasNext(); i++ )
{
String column = (String) columns.next();
Utils.appendEscapedIdentifier(updateSQL, column);
updateSQL.append(" = ?");
if ( i < numColumns - 1 )
updateSQL.append(", ");
}
updateSQL.append( " WHERE " );
int numKeys = primaryKeys.size();
for ( int i = 0; i < numKeys; i++ )
{
PrimaryKey primaryKey = ((PrimaryKey) primaryKeys.get(i));
Utils.appendEscapedIdentifier(updateSQL, primaryKey.name);
updateSQL.append(" = ?");
if ( i < numKeys - 1 )
updateSQL.append(" and ");
}
if ( connection.getLogger().logDebug() )
connection.getLogger().debug("updating " + updateSQL.toString());
updateStatement = ((java.sql.Connection) connection).prepareStatement(updateSQL.toString());
int i = 0;
Iterator iterator = updateValues.values().iterator();
for (; iterator.hasNext(); i++)
{
Object o = iterator.next();
updateStatement.setObject( i + 1, o );
}
for ( int j = 0; j < numKeys; j++, i++)
{
updateStatement.setObject( i + 1, ((PrimaryKey) primaryKeys.get(j)).getValue() );
}
updateStatement.executeUpdate();
updateStatement.close();
updateStatement = null;
updateRowBuffer();
connection.getLogger().debug("copying data");
System.arraycopy(rowBuffer, 0, this_row, 0, rowBuffer.length);
rows.setElementAt( rowBuffer, current_row );
connection.getLogger().debug("done updates");
updateValues.clear();
doingUpdates = false;
}
public synchronized void updateShort(int columnIndex, short x)
throws SQLException
{
updateValue(columnIndex, new Short(x));
}
public synchronized void updateString(int columnIndex, String x)
throws SQLException
{
updateValue(columnIndex, x);
}
public synchronized void updateTime(int columnIndex, Time x)
throws SQLException
{
updateValue(columnIndex, x);
}
public synchronized void updateTimestamp(int columnIndex, Timestamp x)
throws SQLException
{
updateValue(columnIndex, x);
}
public synchronized void updateNull(String columnName)
throws SQLException
{
updateNull(findColumn(columnName));
}
public synchronized void updateBoolean(String columnName, boolean x)
throws SQLException
{
updateBoolean(findColumn(columnName), x);
}
public synchronized void updateByte(String columnName, byte x)
throws SQLException
{
updateByte(findColumn(columnName), x);
}
public synchronized void updateShort(String columnName, short x)
throws SQLException
{
updateShort(findColumn(columnName), x);
}
public synchronized void updateInt(String columnName, int x)
throws SQLException
{
updateInt(findColumn(columnName), x);
}
public synchronized void updateLong(String columnName, long x)
throws SQLException
{
updateLong(findColumn(columnName), x);
}
public synchronized void updateFloat(String columnName, float x)
throws SQLException
{
updateFloat(findColumn(columnName), x);
}
public synchronized void updateDouble(String columnName, double x)
throws SQLException
{
updateDouble(findColumn(columnName), x);
}
public synchronized void updateBigDecimal(String columnName, BigDecimal x)
throws SQLException
{
updateBigDecimal(findColumn(columnName), x);
}
public synchronized void updateString(String columnName, String x)
throws SQLException
{
updateString(findColumn(columnName), x);
}
public synchronized void updateBytes(String columnName, byte x[])
throws SQLException
{
updateBytes(findColumn(columnName), x);
}
public synchronized void updateDate(String columnName, java.sql.Date x)
throws SQLException
{
updateDate(findColumn(columnName), x);
}
public synchronized void updateTime(String columnName, java.sql.Time x)
throws SQLException
{
updateTime(findColumn(columnName), x);
}
public synchronized void updateTimestamp(String columnName, java.sql.Timestamp x)
throws SQLException
{
updateTimestamp(findColumn(columnName), x);
}
public synchronized void updateAsciiStream(
String columnName,
java.io.InputStream x,
int length)
throws SQLException
{
updateAsciiStream(findColumn(columnName), x, length);
}
public synchronized void updateBinaryStream(
String columnName,
java.io.InputStream x,
int length)
throws SQLException
{
updateBinaryStream(findColumn(columnName), x, length);
}
public synchronized void updateCharacterStream(
String columnName,
java.io.Reader reader,
int length)
throws SQLException
{
updateCharacterStream(findColumn(columnName), reader, length);
}
public synchronized void updateObject(String columnName, Object x, int scale)
throws SQLException
{
updateObject(findColumn(columnName), x);
}
public synchronized void updateObject(String columnName, Object x)
throws SQLException
{
updateObject(findColumn(columnName), x);
}
/**
* Is this ResultSet updateable?
*/
boolean isUpdateable() throws SQLException
{
checkClosed();
if (resultsetconcurrency == ResultSet.CONCUR_READ_ONLY)
throw new PSQLException(GT.tr("ResultSets with concurrency CONCUR_READ_ONLY cannot be updated."),
PSQLState.INVALID_CURSOR_STATE);
if (updateable)
return true;
connection.getLogger().debug("checking if rs is updateable");
parseQuery();
if ( singleTable == false )
{
connection.getLogger().debug("not a single table");
return false;
}
connection.getLogger().debug("getting primary keys");
//
// Contains the primary key?
//
primaryKeys = new Vector();
// this is not stricty jdbc spec, but it will make things much faster if used
// the user has to select oid, * from table and then we will just use oid
usingOID = false;
int oidIndex = findColumnIndex( "oid" ); // 0 if not present
int i = 0;
// if we find the oid then just use it
//oidIndex will be >0 if the oid was in the select list
if ( oidIndex > 0 )
{
i++;
primaryKeys.add( new PrimaryKey( oidIndex, "oid" ) );
usingOID = true;
}
else
{
// otherwise go and get the primary keys and create a hashtable of keys
String[] s = quotelessTableName(tableName);
String quotelessTableName = s[0];
String quotelessSchemaName = s[1];
java.sql.ResultSet rs = ((java.sql.Connection) connection).getMetaData().getPrimaryKeys("", quotelessSchemaName, quotelessTableName);
for (; rs.next(); i++ )
{
String columnName = rs.getString(4); // get the columnName
int index = findColumn( columnName );
if ( index > 0 )
{
primaryKeys.add( new PrimaryKey(index, columnName ) ); // get the primary key information
}
}
rs.close();
}
if ( connection.getLogger().logDebug() )
connection.getLogger().debug( "no of keys=" + i );
if ( i < 1 )
{
throw new PSQLException(GT.tr("No primary key found for table {0}.", tableName),
PSQLState.DATA_ERROR);
}
updateable = primaryKeys.size() > 0;
if ( connection.getLogger().logDebug() )
connection.getLogger().debug( "checking primary key " + updateable );
return updateable;
}
/** Cracks out the table name and schema (if it exists) from a fully
* qualified table name.
* @param fullname string that we are trying to crack. Test cases:<pre>
* Table: table ()
* "Table": Table ()
* Schema.Table: table (schema)
* "Schema"."Table": Table (Schema)
* "Schema"."Dot.Table": Dot.Table (Schema)
* Schema."Dot.Table": Dot.Table (schema)
* </pre>
* @return String array with element zero always being the tablename and
* element 1 the schema name which may be a zero length string.
*/
public static String[] quotelessTableName(String fullname) {
StringBuffer buf = new StringBuffer(fullname);
String[] parts = new String[] {null, ""};
StringBuffer acc = new StringBuffer();
boolean betweenQuotes = false;
for (int i = 0; i < buf.length(); i++)
{
char c = buf.charAt(i);
switch (c)
{
case '"':
if ((i < buf.length() - 1) && (buf.charAt(i + 1) == '"'))
{
// two consecutive quotes - keep one
i++;
acc.append(c); // keep the quote
}
else
{ // Discard it
betweenQuotes = !betweenQuotes;
}
break;
case '.':
if (betweenQuotes)
{ // Keep it
acc.append(c);
}
else
{ // Have schema name
parts[1] = acc.toString();
acc = new StringBuffer();
}
break;
default:
acc.append((betweenQuotes) ? c : Character.toLowerCase(c));
break;
}
}
// Always put table in slot 0
parts[0] = acc.toString();
return parts;
}
private void parseQuery()
{
String l_sql = originalQuery.toString(null);
StringTokenizer st = new StringTokenizer(l_sql, " \r\t\n");
boolean tableFound = false, tablesChecked = false;
String name = "";
singleTable = true;
while ( !tableFound && !tablesChecked && st.hasMoreTokens() )
{
name = st.nextToken();
if ( !tableFound )
{
if ("from".equalsIgnoreCase(name))
{
tableName = st.nextToken();
if ("only".equalsIgnoreCase(tableName)) {
tableName = st.nextToken();
onlyTable = "ONLY ";
}
tableFound = true;
}
}
else
{
tablesChecked = true;
// if the very next token is , then there are multiple tables
singleTable = !name.equalsIgnoreCase(",");
}
}
}
private void updateRowBuffer() throws SQLException
{
Iterator columns = updateValues.keySet().iterator();
while ( columns.hasNext() )
{
String columnName = (String) columns.next();
int columnIndex = findColumn( columnName ) - 1;
Object valueObject = updateValues.get(columnName);
if (valueObject instanceof NullObject)
{
rowBuffer[columnIndex] = null;
}
else
{
switch ( getSQLType(columnIndex + 1) )
{
case Types.DECIMAL:
case Types.BIGINT:
case Types.DOUBLE:
case Types.BIT:
case Types.VARCHAR:
case Types.SMALLINT:
case Types.FLOAT:
case Types.INTEGER:
case Types.CHAR:
case Types.NUMERIC:
case Types.REAL:
case Types.TINYINT:
case Types.ARRAY:
case Types.OTHER:
rowBuffer[columnIndex] = connection.encodeString(String.valueOf( valueObject));
break;
//
// toString() isn't enough for date and time types; we must format it correctly
// or we won't be able to re-parse it.
//
case Types.DATE:
rowBuffer[columnIndex] =
connection.encodeString(connection.getTimestampUtils().toString(null, (Date)valueObject));
break;
case Types.TIME:
rowBuffer[columnIndex] =
connection.encodeString(connection.getTimestampUtils().toString(null, (Time)valueObject));
break;
case Types.TIMESTAMP:
rowBuffer[columnIndex] =
connection.encodeString(connection.getTimestampUtils().toString(null, (Timestamp)valueObject));
break;
case Types.NULL:
// Should never happen?
break;
case Types.BINARY:
case Types.LONGVARBINARY:
case Types.VARBINARY:
if (fields[columnIndex].getFormat() == Field.BINARY_FORMAT) {
rowBuffer[columnIndex] = (byte[]) valueObject;
} else {
try {
rowBuffer[columnIndex] = PGbytea.toPGString((byte[]) valueObject).getBytes("ISO-8859-1");
} catch (UnsupportedEncodingException e) {
throw new PSQLException(GT.tr("The JVM claims not to support the encoding: {0}", "ISO-8859-1"), PSQLState.UNEXPECTED_ERROR, e);
}
}
break;
default:
rowBuffer[columnIndex] = (byte[]) valueObject;
}
}
}
}
public class CursorResultHandler implements ResultHandler {
private SQLException error;
public void handleResultRows(Query fromQuery, Field[] fields, Vector tuples, ResultCursor cursor) {
AbstractJdbc2ResultSet.this.rows = tuples;
AbstractJdbc2ResultSet.this.cursor = cursor;
}
public void handleCommandStatus(String status, int updateCount, long insertOID) {
handleError(new PSQLException(GT.tr("Unexpected command status: {0}.", status),
PSQLState.PROTOCOL_VIOLATION));
}
public void handleWarning(SQLWarning warning) {
AbstractJdbc2ResultSet.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;
}
};
public BaseStatement getPGStatement() {
return statement;
}
//
// Backwards compatibility with PGRefCursorResultSet
//
private String refCursorName;
public String getRefCursor() {
// Can't check this because the PGRefCursorResultSet
// interface doesn't allow throwing a SQLException
//
// checkClosed();
return refCursorName;
}
private void setRefCursor(String refCursorName) {
this.refCursorName = refCursorName;
}
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 int getFetchSize() throws SQLException
{
checkClosed();
return fetchSize;
}
public boolean next() throws SQLException
{
checkClosed();
if (onInsertRow)
throw new PSQLException(GT.tr("Can''t use relative move methods while on the insert row."),
PSQLState.INVALID_CURSOR_STATE);
if (current_row + 1 >= rows.size())
{
if (cursor == null || (maxRows > 0 && row_offset + rows.size() >= maxRows))
{
current_row = rows.size();
this_row = null;
rowBuffer = null;
return false; // End of the resultset.
}
// Ask for some more data.
row_offset += rows.size(); // We are discarding some data.
int fetchRows = fetchSize;
if (maxRows != 0)
{
if (fetchRows == 0 || row_offset + fetchRows > maxRows) // Fetch would exceed maxRows, limit it.
fetchRows = maxRows - row_offset;
}
// Execute the fetch and update this resultset.
connection.getQueryExecutor().fetch(cursor, new CursorResultHandler(), fetchRows);
current_row = 0;
// Test the new rows array.
if (rows.size() == 0)
{
this_row = null;
rowBuffer = null;
return false;
}
}
else
{
current_row++;
}
initRowBuffer();
return true;
}
public void close() throws SQLException
{
//release resources held (memory for tuples)
rows = null;
if (cursor != null) {
cursor.close();
cursor = null;
}
}
public boolean wasNull() throws SQLException
{
checkClosed();
return wasNullFlag;
}
public String getString(int columnIndex) throws SQLException
{
checkResultSet( columnIndex );
if (wasNullFlag)
return null;
Encoding encoding = connection.getEncoding();
try
{
return trimString(columnIndex, encoding.decode(this_row[columnIndex - 1]));
}
catch (IOException ioe)
{
throw new PSQLException(GT.tr("Invalid character data was found. This is most likely caused by stored data containing characters that are invalid for the character set the database was created in. The most common example of this is storing 8bit data in a SQL_ASCII database."), PSQLState.DATA_ERROR, ioe);
}
}
public boolean getBoolean(int columnIndex) throws SQLException
{
checkResultSet(columnIndex);
if (wasNullFlag)
return false; // SQL NULL
return toBoolean( getString(columnIndex) );
}
private static final BigInteger BYTEMAX = new BigInteger(Byte.toString(Byte.MAX_VALUE));
private static final BigInteger BYTEMIN = new BigInteger(Byte.toString(Byte.MIN_VALUE));
public byte getByte(int columnIndex) throws SQLException
{
checkResultSet(columnIndex);
if (wasNullFlag)
return 0; // SQL NULL
String s = getString(columnIndex);
if (s != null )
{
s = s.trim();
if ( s.length() == 0 )
return 0;
try
{
// try the optimal parse
return Byte.parseByte(s);
}
catch (NumberFormatException e)
{
// didn't work, assume the column is not a byte
try
{
BigDecimal n = new BigDecimal(s);
BigInteger i = n.toBigInteger();
int gt = i.compareTo(BYTEMAX);
int lt = i.compareTo(BYTEMIN);
if ( gt > 0 || lt < 0 )
{
throw new PSQLException(GT.tr("Bad value for type {0} : {1}", new Object[]{"byte",s}),
PSQLState.NUMERIC_VALUE_OUT_OF_RANGE);
}
return i.byteValue();
}
catch ( NumberFormatException ex )
{
throw new PSQLException(GT.tr("Bad value for type {0} : {1}", new Object[]{"byte",s}),
PSQLState.NUMERIC_VALUE_OUT_OF_RANGE);
}
}
}
return 0; // SQL NULL
}
private static final BigInteger SHORTMAX = new BigInteger(Short.toString(Short.MAX_VALUE));
private static final BigInteger SHORTMIN = new BigInteger(Short.toString(Short.MIN_VALUE));
public short getShort(int columnIndex) throws SQLException
{
checkResultSet(columnIndex);
if (wasNullFlag)
return 0; // SQL NULL
String s = getFixedString(columnIndex);
if (s != null)
{
s = s.trim();
try
{
return Short.parseShort(s);
}
catch (NumberFormatException e)
{
try
{
BigDecimal n = new BigDecimal(s);
BigInteger i = n.toBigInteger();
int gt = i.compareTo(SHORTMAX);
int lt = i.compareTo(SHORTMIN);
if ( gt > 0 || lt < 0 )
{
throw new PSQLException(GT.tr("Bad value for type {0} : {1}", new Object[]{"short",s}),
PSQLState.NUMERIC_VALUE_OUT_OF_RANGE);
}
return i.shortValue();
}
catch ( NumberFormatException ne )
{
throw new PSQLException(GT.tr("Bad value for type {0} : {1}", new Object[]{"short",s}),
PSQLState.NUMERIC_VALUE_OUT_OF_RANGE);
}
}
}
return 0; // SQL NULL
}
public int getInt(int columnIndex) throws SQLException
{
checkResultSet(columnIndex);
if (wasNullFlag)
return 0; // SQL NULL
Encoding encoding = connection.getEncoding();
if (encoding.hasAsciiNumbers()) {
try {
return getFastInt(columnIndex);
} catch (NumberFormatException ex) {
}
}
return toInt( getFixedString(columnIndex) );
}
public long getLong(int columnIndex) throws SQLException
{
checkResultSet(columnIndex);
if (wasNullFlag)
return 0; // SQL NULL
Encoding encoding = connection.getEncoding();
if (encoding.hasAsciiNumbers()) {
try {
return getFastLong(columnIndex);
} catch (NumberFormatException ex) {
}
}
return toLong( getFixedString(columnIndex) );
}
/**
* A dummy exception thrown when fast byte[] to number parsing fails and
* no value can be returned. The exact stack trace does not matter because
* the exception is always caught and is not visible to users.
*/
private static final NumberFormatException FAST_NUMBER_FAILED =
new NumberFormatException();
/**
* Optimised byte[] to number parser. This code does not
* handle null values, so the caller must do checkResultSet
* and handle null values prior to calling this function.
*
* @param columnIndex The column to parse.
* @return The parsed number.
* @throws SQLException If an error occurs while fetching column.
* @throws NumberFormatException If the number is invalid or the
* out of range for fast parsing. The value must then be parsed by
* {@link #toLong(String)}.
*/
private long getFastLong(int columnIndex) throws SQLException,
NumberFormatException {
byte[] bytes = this_row[columnIndex - 1];
if (bytes.length == 0) {
throw FAST_NUMBER_FAILED;
}
long val = 0;
int start;
boolean neg;
if (bytes[0] == '-') {
neg = true;
start = 1;
if (bytes.length == 1 || bytes.length > 19) {
throw FAST_NUMBER_FAILED;
}
} else {
start = 0;
neg = false;
if (bytes.length > 18) {
throw FAST_NUMBER_FAILED;
}
}
while (start < bytes.length) {
byte b = bytes[start++];
if (b < '0' || b > '9') {
throw FAST_NUMBER_FAILED;
}
val *= 10;
val += b - '0';
}
if (neg) {
val = -val;
}
return val;
}
/**
* Optimised byte[] to number parser. This code does not
* handle null values, so the caller must do checkResultSet
* and handle null values prior to calling this function.
*
* @param columnIndex The column to parse.
* @return The parsed number.
* @throws SQLException If an error occurs while fetching column.
* @throws NumberFormatException If the number is invalid or the
* out of range for fast parsing. The value must then be parsed by
* {@link #toInt(String)}.
*/
private int getFastInt(int columnIndex) throws SQLException,
NumberFormatException {
byte[] bytes = this_row[columnIndex - 1];
if (bytes.length == 0) {
throw FAST_NUMBER_FAILED;
}
int val = 0;
int start;
boolean neg;
if (bytes[0] == '-') {
neg = true;
start = 1;
if (bytes.length == 1 || bytes.length > 10) {
throw FAST_NUMBER_FAILED;
}
} else {
start = 0;
neg = false;
if (bytes.length > 9) {
throw FAST_NUMBER_FAILED;
}
}
while (start < bytes.length) {
byte b = bytes[start++];
if (b < '0' || b > '9') {
throw FAST_NUMBER_FAILED;
}
val *= 10;
val += b - '0';
}
if (neg) {
val = -val;
}
return val;
}
/**
* Optimised byte[] to number parser. This code does not
* handle null values, so the caller must do checkResultSet
* and handle null values prior to calling this function.
*
* @param columnIndex The column to parse.
* @return The parsed number.
* @throws SQLException If an error occurs while fetching column.
* @throws NumberFormatException If the number is invalid or the
* out of range for fast parsing. The value must then be parsed by
* {@link #toBigDecimal(String)}.
*/
private BigDecimal getFastBigDecimal(int columnIndex) throws SQLException,
NumberFormatException {
byte[] bytes = this_row[columnIndex - 1];
if (bytes.length == 0) {
throw FAST_NUMBER_FAILED;
}
int scale = 0;
long val = 0;
int start;
boolean neg;
if (bytes[0] == '-') {
neg = true;
start = 1;
if (bytes.length == 1 || bytes.length > 19) {
throw FAST_NUMBER_FAILED;
}
} else {
start = 0;
neg = false;
if (bytes.length > 18) {
throw FAST_NUMBER_FAILED;
}
}
int periodsSeen = 0;
while (start < bytes.length) {
byte b = bytes[start++];
if (b < '0' || b > '9') {
if (b == '.') {
scale = bytes.length - start;
periodsSeen++;
continue;
} else
throw FAST_NUMBER_FAILED;
}
val *= 10;
val += b - '0';
}
int numNonSignChars = neg ? bytes.length - 1 : bytes.length;
if (periodsSeen > 1 || periodsSeen == numNonSignChars)
throw FAST_NUMBER_FAILED;
if (neg) {
val = -val;
}
return BigDecimal.valueOf(val, scale);
}
public float getFloat(int columnIndex) throws SQLException
{
checkResultSet(columnIndex);
if (wasNullFlag)
return 0; // SQL NULL
return toFloat( getFixedString(columnIndex) );
}
public double getDouble(int columnIndex) throws SQLException
{
checkResultSet(columnIndex);
if (wasNullFlag)
return 0; // SQL NULL
return toDouble( getFixedString(columnIndex) );
}
public BigDecimal getBigDecimal(int columnIndex, int scale) throws SQLException
{
checkResultSet(columnIndex);
if (wasNullFlag)
return null;
Encoding encoding = connection.getEncoding();
if (encoding.hasAsciiNumbers()) {
try {
return getFastBigDecimal(columnIndex);
} catch (NumberFormatException ex) {
}
}
return toBigDecimal( getFixedString(columnIndex), scale );
}
/*
* Get the value of a column in the current row as a Java byte array.
*
* <p>In normal use, the bytes represent the raw values returned by the
* backend. However, if the column is an OID, then it is assumed to
* refer to a Large Object, and that object is returned as a byte array.
*
* <p><b>Be warned</b> If the large object is huge, then you may run out
* of memory.
*
* @param columnIndex the first column is 1, the second is 2, ...
* @return the column value; if the value is SQL NULL, the result
* is null
* @exception SQLException if a database access error occurs
*/
public byte[] getBytes(int columnIndex) throws SQLException
{
checkResultSet( columnIndex );
if (wasNullFlag)
return null;
if (fields[columnIndex - 1].getFormat() == Field.BINARY_FORMAT)
{
//If the data is already binary then just return it
return this_row[columnIndex - 1];
}
else if (connection.haveMinimumCompatibleVersion("7.2"))
{
//Version 7.2 supports the bytea datatype for byte arrays
if (fields[columnIndex - 1].getOID() == Oid.BYTEA)
{
return trimBytes(columnIndex, PGbytea.toBytes(this_row[columnIndex - 1]));
}
else
{
return trimBytes(columnIndex, this_row[columnIndex - 1]);
}
}
else
{
//Version 7.1 and earlier supports LargeObjects for byte arrays
// Handle OID's as BLOBS
if ( fields[columnIndex - 1].getOID() == Oid.OID)
{
LargeObjectManager lom = connection.getLargeObjectAPI();
LargeObject lob = lom.open(getLong(columnIndex));
byte buf[] = lob.read(lob.size());
lob.close();
return trimBytes(columnIndex, buf);
}
else
{
return trimBytes(columnIndex, this_row[columnIndex - 1]);
}
}
}
public java.sql.Date getDate(int columnIndex) throws SQLException
{
return getDate(columnIndex, null);
}
public Time getTime(int columnIndex) throws SQLException
{
return getTime(columnIndex, null);
}
public Timestamp getTimestamp(int columnIndex) throws SQLException
{
return getTimestamp(columnIndex, null);
}
public InputStream getAsciiStream(int columnIndex) throws SQLException
{
checkResultSet( columnIndex );
if (wasNullFlag)
return null;
if (connection.haveMinimumCompatibleVersion("7.2"))
{
//Version 7.2 supports AsciiStream for all 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 string datatype, but with toast the text datatype is capable of
//handling very large values. Thus the implementation ends up calling
//getString() since there is no current way to stream the value from the server
try
{
return new ByteArrayInputStream(getString(columnIndex).getBytes("ASCII"));
}
catch (UnsupportedEncodingException l_uee)
{
throw new PSQLException(GT.tr("The JVM claims not to support the encoding: {0}","ASCII"), PSQLState.UNEXPECTED_ERROR, l_uee);
}
}
else
{
// In 7.1 Handle as BLOBS so return the LargeObject input stream
return getBinaryStream(columnIndex);
}
}
public InputStream getUnicodeStream(int columnIndex) throws SQLException
{
checkResultSet( columnIndex );
if (wasNullFlag)
return null;
if (connection.haveMinimumCompatibleVersion("7.2"))
{
//Version 7.2 supports AsciiStream for all 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 string datatype, but with toast the text datatype is capable of
//handling very large values. Thus the implementation ends up calling
//getString() since there is no current way to stream the value from the server
try
{
return new ByteArrayInputStream(getString(columnIndex).getBytes("UTF-8"));
}
catch (UnsupportedEncodingException l_uee)
{
throw new PSQLException(GT.tr("The JVM claims not to support the encoding: {0}","UTF-8"), PSQLState.UNEXPECTED_ERROR, l_uee);
}
}
else
{
// In 7.1 Handle as BLOBS so return the LargeObject input stream
return getBinaryStream(columnIndex);
}
}
public InputStream getBinaryStream(int columnIndex) throws SQLException
{
checkResultSet( columnIndex );
if (wasNullFlag)
return null;
if (connection.haveMinimumCompatibleVersion("7.2"))
{
//Version 7.2 supports BinaryStream for all 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. Thus the implementation ends up calling
//getBytes() since there is no current way to stream the value from the server
byte b[] = getBytes(columnIndex);
if (b != null)
return new ByteArrayInputStream(b);
}
else
{
// In 7.1 Handle as BLOBS so return the LargeObject input stream
if ( fields[columnIndex - 1].getOID() == Oid.OID)
{
LargeObjectManager lom = connection.getLargeObjectAPI();
LargeObject lob = lom.open(getLong(columnIndex));
return lob.getInputStream();
}
}
return null;
}
public String getString(String columnName) throws SQLException
{
return getString(findColumn(columnName));
}
public boolean getBoolean(String columnName) throws SQLException
{
return getBoolean(findColumn(columnName));
}
public byte getByte(String columnName) throws SQLException
{
return getByte(findColumn(columnName));
}
public short getShort(String columnName) throws SQLException
{
return getShort(findColumn(columnName));
}
public int getInt(String columnName) throws SQLException
{
return getInt(findColumn(columnName));
}
public long getLong(String columnName) throws SQLException
{
return getLong(findColumn(columnName));
}
public float getFloat(String columnName) throws SQLException
{
return getFloat(findColumn(columnName));
}
public double getDouble(String columnName) throws SQLException
{
return getDouble(findColumn(columnName));
}
public BigDecimal getBigDecimal(String columnName, int scale) throws SQLException
{
return getBigDecimal(findColumn(columnName), scale);
}
public byte[] getBytes(String columnName) throws SQLException
{
return getBytes(findColumn(columnName));
}
public java.sql.Date getDate(String columnName) throws SQLException
{
return getDate(findColumn(columnName), null);
}
public Time getTime(String columnName) throws SQLException
{
return getTime(findColumn(columnName), null);
}
public Timestamp getTimestamp(String columnName) throws SQLException
{
return getTimestamp(findColumn(columnName), null);
}
public InputStream getAsciiStream(String columnName) throws SQLException
{
return getAsciiStream(findColumn(columnName));
}
public InputStream getUnicodeStream(String columnName) throws SQLException
{
return getUnicodeStream(findColumn(columnName));
}
public InputStream getBinaryStream(String columnName) throws SQLException
{
return getBinaryStream(findColumn(columnName));
}
public SQLWarning getWarnings() throws SQLException
{
checkClosed();
return warnings;
}
public void clearWarnings() throws SQLException
{
checkClosed();
warnings = null;
}
protected void addWarning(SQLWarning warnings)
{
if (this.warnings != null)
this.warnings.setNextWarning(warnings);
else
this.warnings = warnings;
}
public String getCursorName() throws SQLException
{
checkClosed();
return null;
}
/*
* Get the value of a column in the current row as a Java object
*
* <p>This method will return the value of the given column as a
* Java object. The type of the Java object will be the default
* Java Object type corresponding to the column's SQL type, following
* the mapping specified in the JDBC specification.
*
* <p>This method may also be used to read database specific abstract
* data types.
*
* @param columnIndex the first column is 1, the second is 2...
* @return a Object holding the column value
* @exception SQLException if a database access error occurs
*/
public Object getObject(int columnIndex) throws SQLException {
Field field;
checkResultSet(columnIndex);
if (wasNullFlag)
return null;
field = fields[columnIndex - 1];
// some fields can be null, mainly from those returned by MetaData methods
if (field == null)
{
wasNullFlag = true;
return null;
}
Object result = internalGetObject(columnIndex, field);
if (result != null)
return result;
return connection.getObject(getPGType(columnIndex), getString(columnIndex));
}
public Object getObject(String columnName) throws SQLException
{
return getObject(findColumn(columnName));
}
/*
* Map a ResultSet column name to a ResultSet column index
*/
public int findColumn(String columnName) throws SQLException
{
checkClosed();
int col = findColumnIndex(columnName);
if (col == 0)
throw new PSQLException (GT.tr("The column name {0} was not found in this ResultSet.", columnName),
PSQLState.UNDEFINED_COLUMN);
return col;
}
private int findColumnIndex(String columnName)
{
if (columnNameIndexMap == null)
{
columnNameIndexMap = new HashMap(fields.length * 2);
// The JDBC spec says when you have duplicate columns names,
// the first one should be returned. So load the map in
// reverse order so the first ones will overwrite later ones.
for (int i = fields.length - 1; i >= 0; i--)
{
columnNameIndexMap.put(fields[i].getColumnLabel().toLowerCase(Locale.US), new Integer(i + 1));
}
}
Integer index = (Integer)columnNameIndexMap.get(columnName);
if (index != null)
{
return index.intValue();
}
index = (Integer)columnNameIndexMap.get(columnName.toLowerCase(Locale.US));
if (index != null)
{
columnNameIndexMap.put(columnName, index);
return index.intValue();
}
return 0;
}
/*
* returns the OID of a field.<p>
* It is used internally by the driver.
*/
public int getColumnOID(int field)
{
return fields[field -1].getOID();
}
/*
* This is used to fix get*() methods on Money fields. It should only be
* used by those methods!
*
* It converts ($##.##) to -##.## and $##.## to ##.##
*/
public String getFixedString(int col) throws SQLException
{
String s = getString(col);
if (s == null)
return null;
// if we don't have at least 2 characters it can't be money.
if (s.length() < 2)
return s;
// Handle Money
char ch = s.charAt(0);
// optimise for non-money type: return immediately with one check
// if the first char cannot be '(', '$' or '-'
if (ch > '-') {
return s;
}
if (ch == '(')
{
s = "-" + PGtokenizer.removePara(s).substring(1);
}
else if (ch == '$')
{
s = s.substring(1);
}
else if (ch == '-' && s.charAt(1) == '$')
{
s = "-" + s.substring(2);
}
return s;
}
protected String getPGType( int column ) throws SQLException
{
return connection.getTypeInfo().getPGType(fields[column - 1].getOID());
}
protected int getSQLType( int column ) throws SQLException
{
return connection.getTypeInfo().getSQLType(fields[column - 1].getOID());
}
private void checkUpdateable() throws SQLException
{
checkClosed();
if (!isUpdateable())
throw new PSQLException(GT.tr("ResultSet is not updateable. The query that generated this result set must select only one table, and must select all primary keys from that table. See the JDBC 2.1 API Specification, section 5.6 for more details."),
PSQLState.INVALID_CURSOR_STATE);
if (updateValues == null)
{
// allow every column to be updated without a rehash.
updateValues = new HashMap((int)(fields.length / 0.75), 0.75f);
}
}
protected void checkClosed() throws SQLException {
if (rows == null)
throw new PSQLException(GT.tr("This ResultSet is closed."), PSQLState.CONNECTION_DOES_NOT_EXIST);
}
protected void checkColumnIndex(int column) throws SQLException
{
if ( column < 1 || column > fields.length )
throw new PSQLException(GT.tr("The column index is out of range: {0}, number of columns: {1}.", new Object[]{new Integer(column), new Integer(fields.length)}), PSQLState.INVALID_PARAMETER_VALUE );
}
/**
* Checks that the result set is not closed, it's positioned on a
* valid row and that the given column number is valid. Also
* updates the {@link #wasNullFlag} to correct value.
*
* @param column The column number to check. Range starts from 1.
* @throws SQLException If state or column is invalid.
*/
protected void checkResultSet( int column ) throws SQLException
{
checkClosed();
if ( this_row == null )
throw new PSQLException(GT.tr("ResultSet not positioned properly, perhaps you need to call next."),
PSQLState.INVALID_CURSOR_STATE);
checkColumnIndex(column);
wasNullFlag = (this_row[column - 1] == null);
}
//----------------- Formatting Methods -------------------
public static boolean toBoolean(String s)
{
if (s != null)
{
s = s.trim();
if (s.equalsIgnoreCase("t") || s.equalsIgnoreCase("true") || s.equals("1"))
return true;
if (s.equalsIgnoreCase("f") || s.equalsIgnoreCase("false") || s.equals("0"))
return false;
try
{
if (Double.valueOf(s).doubleValue() == 1)
return true;
}
catch (NumberFormatException e)
{
}
}
return false; // SQL NULL
}
private static final BigInteger INTMAX = new BigInteger(Integer.toString(Integer.MAX_VALUE));
private static final BigInteger INTMIN = new BigInteger(Integer.toString(Integer.MIN_VALUE));
public static int toInt(String s) throws SQLException
{
if (s != null)
{
try
{
s = s.trim();
return Integer.parseInt(s);
}
catch (NumberFormatException e)
{
try
{
BigDecimal n = new BigDecimal(s);
BigInteger i = n.toBigInteger();
int gt = i.compareTo(INTMAX);
int lt = i.compareTo(INTMIN);
if (gt > 0 || lt < 0)
{
throw new PSQLException(GT.tr("Bad value for type {0} : {1}", new Object[]{"int",s}),
PSQLState.NUMERIC_VALUE_OUT_OF_RANGE);
}
return i.intValue();
}
catch ( NumberFormatException ne )
{
throw new PSQLException(GT.tr("Bad value for type {0} : {1}", new Object[]{"int",s}),
PSQLState.NUMERIC_VALUE_OUT_OF_RANGE);
}
}
}
return 0; // SQL NULL
}
private final static BigInteger LONGMAX = new BigInteger(Long.toString(Long.MAX_VALUE));
private final static BigInteger LONGMIN = new BigInteger(Long.toString(Long.MIN_VALUE));
public static long toLong(String s) throws SQLException
{
if (s != null)
{
try
{
s = s.trim();
return Long.parseLong(s);
}
catch (NumberFormatException e)
{
try
{
BigDecimal n = new BigDecimal(s);
BigInteger i = n.toBigInteger();
int gt = i.compareTo(LONGMAX);
int lt = i.compareTo(LONGMIN);
if ( gt > 0 || lt < 0 )
{
throw new PSQLException(GT.tr("Bad value for type {0} : {1}", new Object[]{"long",s}),
PSQLState.NUMERIC_VALUE_OUT_OF_RANGE);
}
return i.longValue();
}
catch ( NumberFormatException ne )
{
throw new PSQLException(GT.tr("Bad value for type {0} : {1}", new Object[]{"long",s}),
PSQLState.NUMERIC_VALUE_OUT_OF_RANGE);
}
}
}
return 0; // SQL NULL
}
public static BigDecimal toBigDecimal(String s, int scale) throws SQLException
{
BigDecimal val;
if (s != null)
{
try
{
s = s.trim();
val = new BigDecimal(s);
}
catch (NumberFormatException e)
{
throw new PSQLException(GT.tr("Bad value for type {0} : {1}", new Object[]{"BigDecimal",s}),
PSQLState.NUMERIC_VALUE_OUT_OF_RANGE);
}
if (scale == -1)
return val;
try
{
return val.setScale(scale);
}
catch (ArithmeticException e)
{
throw new PSQLException(GT.tr("Bad value for type {0} : {1}", new Object[]{"BigDecimal",s}),
PSQLState.NUMERIC_VALUE_OUT_OF_RANGE);
}
}
return null; // SQL NULL
}
public static float toFloat(String s) throws SQLException
{
if (s != null)
{
try
{
s = s.trim();
return Float.parseFloat(s);
}
catch (NumberFormatException e)
{
throw new PSQLException(GT.tr("Bad value for type {0} : {1}", new Object[]{"float",s}),
PSQLState.NUMERIC_VALUE_OUT_OF_RANGE);
}
}
return 0; // SQL NULL
}
public static double toDouble(String s) throws SQLException
{
if (s != null)
{
try
{
s = s.trim();
return Double.parseDouble(s);
}
catch (NumberFormatException e)
{
throw new PSQLException(GT.tr("Bad value for type {0} : {1}", new Object[]{"double",s}),
PSQLState.NUMERIC_VALUE_OUT_OF_RANGE);
}
}
return 0; // SQL NULL
}
private void initRowBuffer()
{
this_row = (byte[][]) rows.elementAt(current_row);
// We only need a copy of the current row if we're going to
// modify it via an updatable resultset.
if (resultsetconcurrency == ResultSet.CONCUR_UPDATABLE) {
rowBuffer = new byte[this_row.length][];
System.arraycopy(this_row, 0, rowBuffer, 0, this_row.length);
} else {
rowBuffer = null;
}
}
private boolean isColumnTrimmable(int columnIndex) throws SQLException
{
switch (getSQLType(columnIndex))
{
case Types.CHAR:
case Types.VARCHAR:
case Types.LONGVARCHAR:
case Types.BINARY:
case Types.VARBINARY:
case Types.LONGVARBINARY:
return true;
}
return false;
}
private byte[] trimBytes(int p_columnIndex, byte[] p_bytes) throws SQLException
{
//we need to trim if maxsize is set and the length is greater than maxsize and the
//type of this column is a candidate for trimming
if (maxFieldSize > 0 && p_bytes.length > maxFieldSize && isColumnTrimmable(p_columnIndex))
{
byte[] l_bytes = new byte[maxFieldSize];
System.arraycopy (p_bytes, 0, l_bytes, 0, maxFieldSize);
return l_bytes;
}
else
{
return p_bytes;
}
}
private String trimString(int p_columnIndex, String p_string) throws SQLException
{
//we need to trim if maxsize is set and the length is greater than maxsize and the
//type of this column is a candidate for trimming
if (maxFieldSize > 0 && p_string.length() > maxFieldSize && isColumnTrimmable(p_columnIndex))
{
return p_string.substring(0, maxFieldSize);
}
else
{
return p_string;
}
}
protected void updateValue(int columnIndex, Object value) throws SQLException {
checkUpdateable();
if (!onInsertRow && (isBeforeFirst() || isAfterLast() || rows.size() == 0))
{
throw new PSQLException(GT.tr("Cannot update the ResultSet because it is either before the start or after the end of the results."),
PSQLState.INVALID_CURSOR_STATE);
}
checkColumnIndex(columnIndex);
doingUpdates = !onInsertRow;
if (value == null)
updateNull(columnIndex);
else
updateValues.put(fields[columnIndex - 1].getColumnName(connection), value);
}
/**
* Newer JVMs will return a java.util.UUID object, but it isn't
* available in older versions.
*/
protected Object getUUID(String data) throws SQLException
{
return data;
}
private class PrimaryKey
{
int index; // where in the result set is this primaryKey
String name; // what is the columnName of this primary Key
PrimaryKey( int index, String name)
{
this.index = index;
this.name = name;
}
Object getValue() throws SQLException
{
return getObject(index);
}
};
//
// We need to specify the type of NULL when updating a column to NULL, so
// NullObject is a simple extension of PGobject that always returns null
// values but retains column type info.
//
static class NullObject extends PGobject {
NullObject(String type) {
setType(type);
}
public String getValue() {
return null;
}
};
}
|