1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524
|
/*
*-----------------------------------------------------------------------------
*
* tdbcpostgres.c --
*
* C code for the driver to interface TDBC and Postgres
*
* Copyright (c) 2009 by Slawomir Cygan.
* Copyright (c) 2010 by Kevin B. Kenny.
*
* Please refer to the file, 'license.terms' for the conditions on
* redistribution of this file and for a DISCLAIMER OF ALL WARRANTIES.
*
*-----------------------------------------------------------------------------
*/
#ifdef _MSC_VER
# define _CRT_SECURE_NO_DEPRECATE
# pragma warning(disable:4244)
#endif
#include <tcl.h>
#include <tclOO.h>
#include <tdbc.h>
#include "tdbcPostgresUuid.h"
#include <stdio.h>
#include <string.h>
#ifdef HAVE_STDINT_H
# include <stdint.h>
#endif
#ifdef HAVE_SYS_TYPES_H
# include <sys/types.h>
#endif
#include "int2ptr_ptr2int.h"
#ifdef USE_NATIVE_POSTGRES
# include <libpq-fe.h>
#else
# include "fakepq.h"
#endif
/* Include the files needed to locate htons() and htonl() */
#ifdef _WIN32
typedef int int32_t;
typedef short int16_t;
# define WIN32_LEAN_AND_MEAN
# include <windows.h>
# include <winsock2.h>
# ifdef _MSC_VER
# pragma comment (lib, "ws2_32")
# endif
#else
# include <netinet/in.h>
#endif
#if defined(_WIN32) && defined(_MSC_VER) && _MSC_VER < 1900
# define snprintf _snprintf
#endif
#ifndef JOIN
# define JOIN(a,b) JOIN1(a,b)
# define JOIN1(a,b) a##b
#endif
#ifndef TCL_UNUSED
# if defined(__cplusplus)
# define TCL_UNUSED(T) T
# elif defined(__GNUC__) && (__GNUC__ > 2)
# define TCL_UNUSED(T) T JOIN(dummy, __LINE__) __attribute__((unused))
# else
# define TCL_UNUSED(T) T JOIN(dummy, __LINE__)
# endif
#endif
#if (TCL_MAJOR_VERSION == 8) && (TCL_MINOR_VERSION < 7)
# define TCL_SIZE_MODIFIER ""
# define Tcl_Size int
#endif
/* Static data contained within this file */
static Tcl_Mutex pgMutex; /* Mutex protecting per-process structures */
static int pgRefCount = 0; /* Reference count for the PG load handle */
static Tcl_LoadHandle pgLoadHandle = NULL;
/* Load handle of the PG library */
/* Pool of literal values used to avoid excess Tcl_NewStringObj calls */
static const char *const LiteralValues[] = {
"",
"0",
"1",
"direction",
"in",
"inout",
"name",
"nullable",
"out",
"precision",
"scale",
"type",
NULL
};
enum LiteralIndex {
LIT_EMPTY,
LIT_0,
LIT_1,
LIT_DIRECTION,
LIT_IN,
LIT_INOUT,
LIT_NAME,
LIT_NULLABLE,
LIT_OUT,
LIT_PRECISION,
LIT_SCALE,
LIT_TYPE,
LIT__END
};
/* Object IDs for the Postgres data types */
#define UNTYPEDOID 0
#define BYTEAOID 17
#define INT8OID 20
#define INT2OID 21
#define INT4OID 23
#define TEXTOID 25
#define FLOAT4OID 700
#define FLOAT8OID 701
#define BPCHAROID 1042
#define VARCHAROID 1043
#define DATEOID 1082
#define TIMEOID 1083
#define TIMESTAMPOID 1114
#define BITOID 1560
#define NUMERICOID 1700
typedef struct PostgresDataType {
const char* name; /* Type name */
Oid oid; /* Type number */
} PostgresDataType;
static const PostgresDataType dataTypes[] = {
{ "NULL", UNTYPEDOID},
{ "smallint", INT2OID },
{ "integer", INT4OID },
{ "tinyint", INT2OID },
{ "float", FLOAT8OID },
{ "real", FLOAT4OID },
{ "double", FLOAT8OID },
{ "timestamp", TIMESTAMPOID },
{ "bigint", INT8OID },
{ "date", DATEOID },
{ "time", TIMEOID },
{ "bit", BITOID },
{ "numeric", NUMERICOID },
{ "decimal", NUMERICOID },
{ "text", TEXTOID },
{ "varbinary", BYTEAOID },
{ "varchar", VARCHAROID } ,
{ "char", BPCHAROID },
{ NULL, 0 }
};
/* Configuration options for Postgres connections */
/* Data types of configuration options */
enum OptType {
TYPE_STRING, /* Arbitrary character string */
TYPE_PORT, /* Port number */
TYPE_ENCODING, /* Encoding name */
TYPE_ISOLATION, /* Transaction isolation level */
TYPE_READONLY, /* Read-only indicator */
};
/* Locations of the string options in the string array */
enum OptStringIndex {
INDX_HOST, INDX_HOSTA, INDX_PORT, INDX_DB, INDX_USER,
INDX_PASS, INDX_OPT, INDX_TTY, INDX_SERV, INDX_TOUT,
INDX_SSLM, INDX_RSSL, INDX_KERB,
INDX_MAX
};
/* Names of string options for Postgres PGconnectdb() */
static const char *const optStringNames[] = {
"host", "hostaddr", "port", "dbname", "user",
"password", "options", "tty", "service", "connect_timeout",
"sslmode", "requiressl", "krbsrvname"
};
/* Flags in the configuration table */
#define CONN_OPT_FLAG_MOD 0x1 /* Configuration value changable at runtime */
#define CONN_OPT_FLAG_ALIAS 0x2 /* Configuration option is an alias */
/*
* Relay functions to allow Stubbed functions in the configuration options
* table.
*/
static char* _PQdb(const PGconn* conn) { return PQdb(conn); }
static char* _PQhost(const PGconn* conn) { return PQhost(conn); }
static char* _PQoptions(const PGconn* conn) { return PQoptions(conn); }
static char* _PQpass(const PGconn* conn) { return PQpass(conn); }
static char* _PQport(const PGconn* conn) { return PQport(conn); }
static char* _PQuser(const PGconn* conn) { return PQuser(conn); }
static char* _PQtty(const PGconn* conn) { return PQtty(conn); }
/* Table of configuration options */
static const struct {
const char * name; /* Option name */
enum OptType type; /* Option data type */
int info; /* Option index or flag value */
int flags; /* Flags - modifiable; SSL related;
* is an alias */
char *(*queryF)(const PGconn*); /* Function used to determine the
* option value */
} ConnOptions [] = {
{ "-host", TYPE_STRING, INDX_HOST, 0, _PQhost},
{ "-hostaddr", TYPE_STRING, INDX_HOSTA, 0, _PQhost},
{ "-port", TYPE_PORT, INDX_PORT, 0, _PQport},
{ "-database", TYPE_STRING, INDX_DB, 0, _PQdb},
{ "-db", TYPE_STRING, INDX_DB, CONN_OPT_FLAG_ALIAS, _PQdb},
{ "-user", TYPE_STRING, INDX_USER, 0, _PQuser},
{ "-password", TYPE_STRING, INDX_PASS, 0, _PQpass},
{ "-options", TYPE_STRING, INDX_OPT, 0, _PQoptions},
{ "-tty", TYPE_STRING, INDX_TTY, 0, _PQtty},
{ "-service", TYPE_STRING, INDX_SERV, 0, NULL},
{ "-timeout", TYPE_STRING, INDX_TOUT, 0, NULL},
{ "-sslmode", TYPE_STRING, INDX_SSLM, 0, NULL},
{ "-requiressl", TYPE_STRING, INDX_RSSL, 0, NULL},
{ "-krbsrvname", TYPE_STRING, INDX_KERB, 0, NULL},
{ "-encoding", TYPE_ENCODING, 0, CONN_OPT_FLAG_MOD, NULL},
{ "-isolation", TYPE_ISOLATION, 0, CONN_OPT_FLAG_MOD, NULL},
{ "-readonly", TYPE_READONLY, 0, CONN_OPT_FLAG_MOD, NULL},
{ NULL, TYPE_STRING, 0, 0, NULL}
};
/*
* Structure that holds per-interpreter data for the Postgres package.
*
* This structure is reference counted, because it cannot be destroyed
* until all connections, statements and result sets that refer to
* it are destroyed.
*/
typedef struct PerInterpData {
size_t refCount; /* Reference count */
Tcl_Obj* literals[LIT__END]; /* Literal pool */
Tcl_HashTable typeNumHash; /* Lookup table for type numbers */
} PerInterpData;
#define IncrPerInterpRefCount(x) \
do { \
++((x)->refCount); \
} while(0)
#define DecrPerInterpRefCount(x) \
do { \
PerInterpData* _pidata = x; \
if (_pidata->refCount-- <= 1) { \
DeletePerInterpData(_pidata); \
} \
} while(0)
/*
* Structure that carries the data for a Postgres connection
*
* This structure is reference counted, to enable deferring its
* destruction until the last statement or result set that refers
* to it is destroyed.
*/
typedef struct ConnectionData {
size_t refCount; /* Reference count. */
PerInterpData* pidata; /* Per-interpreter data */
PGconn* pgPtr; /* Postgres connection handle */
int stmtCounter; /* Counter for naming statements */
int flags;
int isolation; /* Current isolation level */
int readOnly; /* Read only connection indicator */
char * savedOpts[INDX_MAX]; /* Saved configuration options */
} ConnectionData;
/*
* Flags for the state of an POSTGRES connection
*/
#define CONN_FLAG_IN_XCN 0x1 /* Transaction is in progress */
#define IncrConnectionRefCount(x) \
do { \
++((x)->refCount); \
} while(0)
#define DecrConnectionRefCount(x) \
do { \
ConnectionData* conn = x; \
if (conn->refCount-- <= 1) { \
DeleteConnection(conn); \
} \
} while(0)
/*
* Structure that carries the data for a Postgres prepared statement.
*
* Just as with connections, statements need to defer taking down
* their client data until other objects (i.e., result sets) that
* refer to them have had a chance to clean up. Hence, this
* structure is reference counted as well.
*/
typedef struct StatementData {
size_t refCount; /* Reference count */
ConnectionData* cdata; /* Data for the connection to which this
* statement pertains. */
Tcl_Obj* subVars; /* List of variables to be substituted, in the
* order in which they appear in the
* statement */
Tcl_Obj* nativeSql; /* Native SQL statement to pass into
* Postgres */
char* stmtName; /* Name identyfing the statement */
Tcl_Obj* columnNames; /* Column names in the result set */
struct ParamData *params; /* Attributes of parameters */
Tcl_Size nParams; /* Number of parameters */
Oid* paramDataTypes; /* Param data types list */
int paramTypesChanged; /* Indicator of changed param types */
int flags;
} StatementData;
#define IncrStatementRefCount(x) \
do { \
++((x)->refCount); \
} while (0)
#define DecrStatementRefCount(x) \
do { \
StatementData* stmt = (x); \
if (stmt->refCount-- <= 1) { \
DeleteStatement(stmt); \
} \
} while(0)
/* Flags in the 'StatementData->flags' word */
#define STMT_FLAG_BUSY 0x1 /* Statement handle is in use */
/*
* Structure describing the data types of substituted parameters in
* a SQL statement.
*/
typedef struct ParamData {
int flags; /* Flags regarding the parameters - see below */
int precision; /* Size of the expected data */
int scale; /* Digits after decimal point of the
* expected data */
} ParamData;
#define PARAM_KNOWN 1<<0 /* Something is known about the parameter */
#define PARAM_IN 1<<1 /* Parameter is an input parameter */
#define PARAM_OUT 1<<2 /* Parameter is an output parameter */
/* (Both bits are set if parameter is
* an INOUT parameter) */
/*
* Structure describing a Postgres result set. The object that the Tcl
* API terms a "result set" actually has to be represented by a Postgres
* "statement", since a Postgres statement can have only one set of results
* at any given time.
*/
typedef struct ResultSetData {
size_t refCount; /* Reference count */
StatementData* sdata; /* Statement that generated this result set */
PGresult* execResult; /* Structure containing result of prepared statement execution */
char* stmtName; /* Name identyfing the statement */
int rowCount; /* Number of already retreived rows */
} ResultSetData;
#define IncrResultSetRefCount(x) \
do { \
++((x)->refCount); \
} while (0)
#define DecrResultSetRefCount(x) \
do { \
ResultSetData* rs = (x); \
if (rs->refCount-- <= 1) { \
DeleteResultSet(rs); \
} \
} while(0)
/* Tables of isolation levels: Tcl, SQL and Postgres C API */
static const char *const TclIsolationLevels[] = {
"readuncommitted",
"readcommitted",
"repeatableread",
"serializable",
NULL
};
static const char *const SqlIsolationLevels[] = {
"SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED",
"SET TRANSACTION ISOLATION LEVEL READ COMMITTED",
"SET TRANSACTION ISOLATION LEVEL REPEATABLE READ",
"SET TRANSACTION ISOLATION LEVEL SERIALIZABLE",
NULL
};
enum IsolationLevel {
ISOL_READ_UNCOMMITTED,
ISOL_READ_COMMITTED,
ISOL_REPEATABLE_READ,
ISOL_SERIALIZABLE,
ISOL_NONE = -1
};
/* Static functions defined within this file */
static int DeterminePostgresMajorVersion(Tcl_Interp* interp,
ConnectionData* cdata,
int* versionPtr);
static void DummyNoticeProcessor(void*, const PGresult*);
static int ExecSimpleQuery(Tcl_Interp* interp, PGconn * pgPtr,
const char * query, PGresult** resOut);
static void TransferPostgresError(Tcl_Interp* interp, PGconn * pgPtr);
static int TransferResultError(Tcl_Interp* interp, PGresult * res);
static Tcl_Obj* QueryConnectionOption(ConnectionData* cdata,
Tcl_Interp* interp,
int optionNum);
static int ConfigureConnection(ConnectionData* cdata, Tcl_Interp* interp,
Tcl_Size objc, Tcl_Obj *const objv[], Tcl_Size skip);
static int ConnectionConstructor(void *clientData, Tcl_Interp* interp,
Tcl_ObjectContext context,
int objc, Tcl_Obj *const objv[]);
static int ConnectionBegintransactionMethod(void *clientData,
Tcl_Interp* interp,
Tcl_ObjectContext context,
int objc, Tcl_Obj *const objv[]);
static int ConnectionColumnsMethod(void *clientData, Tcl_Interp* interp,
Tcl_ObjectContext context,
int objc, Tcl_Obj *const objv[]);
static int ConnectionCommitMethod(void *clientData, Tcl_Interp* interp,
Tcl_ObjectContext context,
int objc, Tcl_Obj *const objv[]);
static int ConnectionConfigureMethod(void *clientData, Tcl_Interp* interp,
Tcl_ObjectContext context,
int objc, Tcl_Obj *const objv[]);
static int ConnectionRollbackMethod(void *clientData, Tcl_Interp* interp,
Tcl_ObjectContext context,
int objc, Tcl_Obj *const objv[]);
static int ConnectionTablesMethod(void *clientData, Tcl_Interp* interp,
Tcl_ObjectContext context,
int objc, Tcl_Obj *const objv[]);
static void DeleteConnectionMetadata(void *clientData);
static void DeleteConnection(ConnectionData* cdata);
static int CloneConnection(Tcl_Interp* interp, void *oldClientData,
void **newClientData);
static char* GenStatementName(ConnectionData* cdata);
static void UnallocateStatement(PGconn* pgPtr, char* stmtName);
static StatementData* NewStatement(ConnectionData* cdata);
static PGresult* PrepareStatement(Tcl_Interp* interp,
StatementData* sdata, char* stmtName);
static Tcl_Obj* ResultDescToTcl(PGresult* resultDesc);
static int StatementConstructor(void *clientData, Tcl_Interp* interp,
Tcl_ObjectContext context,
int objc, Tcl_Obj *const objv[]);
static int StatementParamtypeMethod(void *clientData, Tcl_Interp* interp,
Tcl_ObjectContext context,
int objc, Tcl_Obj *const objv[]);
static int StatementParamsMethod(void *clientData, Tcl_Interp* interp,
Tcl_ObjectContext context,
int objc, Tcl_Obj *const objv[]);
static void DeleteStatementMetadata(void *clientData);
static void DeleteStatement(StatementData* sdata);
static int CloneStatement(Tcl_Interp* interp, void *oldClientData,
void **newClientData);
static int ResultSetConstructor(void *clientData, Tcl_Interp* interp,
Tcl_ObjectContext context,
int objc, Tcl_Obj *const objv[]);
static int ResultSetColumnsMethod(void *clientData, Tcl_Interp* interp,
Tcl_ObjectContext context,
int objc, Tcl_Obj *const objv[]);
static int ResultSetNextrowMethod(void *clientData, Tcl_Interp* interp,
Tcl_ObjectContext context,
int objc, Tcl_Obj *const objv[]);
static int ResultSetRowcountMethod(void *clientData, Tcl_Interp* interp,
Tcl_ObjectContext context,
int objc, Tcl_Obj *const objv[]);
static void DeleteResultSetMetadata(void *clientData);
static void DeleteResultSet(ResultSetData* rdata);
static int CloneResultSet(Tcl_Interp* interp, void *oldClientData,
void **newClientData);
static void DeleteCmd(void *clientData);
static int CloneCmd(Tcl_Interp* interp,
void *oldMetadata, void **newMetadata);
static void DeletePerInterpData(PerInterpData* pidata);
/* Metadata type that holds connection data */
const static Tcl_ObjectMetadataType connectionDataType = {
TCL_OO_METADATA_VERSION_CURRENT,
/* version */
"ConnectionData", /* name */
DeleteConnectionMetadata, /* deleteProc */
CloneConnection /* cloneProc - should cause an error
* 'cuz connections aren't clonable */
};
/* Metadata type that holds statement data */
const static Tcl_ObjectMetadataType statementDataType = {
TCL_OO_METADATA_VERSION_CURRENT,
/* version */
"StatementData", /* name */
DeleteStatementMetadata, /* deleteProc */
CloneStatement /* cloneProc - should cause an error
* 'cuz statements aren't clonable */
};
/* Metadata type for result set data */
const static Tcl_ObjectMetadataType resultSetDataType = {
TCL_OO_METADATA_VERSION_CURRENT,
/* version */
"ResultSetData", /* name */
DeleteResultSetMetadata, /* deleteProc */
CloneResultSet /* cloneProc - should cause an error
* 'cuz result sets aren't clonable */
};
/* Method types of the result set methods that are implemented in C */
const static Tcl_MethodType ResultSetConstructorType = {
TCL_OO_METHOD_VERSION_CURRENT,
/* version */
"CONSTRUCTOR", /* name */
ResultSetConstructor, /* callProc */
NULL, /* deleteProc */
NULL /* cloneProc */
};
const static Tcl_MethodType ResultSetColumnsMethodType = {
TCL_OO_METHOD_VERSION_CURRENT,
/* version */ "columns", /* name */
ResultSetColumnsMethod, /* callProc */
NULL, /* deleteProc */
NULL /* cloneProc */
};
const static Tcl_MethodType ResultSetNextrowMethodType = {
TCL_OO_METHOD_VERSION_CURRENT,
/* version */
"nextrow", /* name */
ResultSetNextrowMethod, /* callProc */
NULL, /* deleteProc */
NULL /* cloneProc */
};
const static Tcl_MethodType ResultSetRowcountMethodType = {
TCL_OO_METHOD_VERSION_CURRENT,
/* version */
"rowcount", /* name */
ResultSetRowcountMethod, /* callProc */
NULL, /* deleteProc */
NULL /* cloneProc */
};
/* Methods to create on the result set class */
const static Tcl_MethodType* ResultSetMethods[] = {
&ResultSetColumnsMethodType,
&ResultSetRowcountMethodType,
NULL
};
/* Method types of the connection methods that are implemented in C */
const static Tcl_MethodType ConnectionConstructorType = {
TCL_OO_METHOD_VERSION_CURRENT,
/* version */
"CONSTRUCTOR", /* name */
ConnectionConstructor, /* callProc */
DeleteCmd, /* deleteProc */
CloneCmd /* cloneProc */
};
const static Tcl_MethodType ConnectionBegintransactionMethodType = {
TCL_OO_METHOD_VERSION_CURRENT,
/* version */
"begintransaction", /* name */
ConnectionBegintransactionMethod, /* callProc */
NULL, /* deleteProc */
NULL /* cloneProc */
};
const static Tcl_MethodType ConnectionColumnsMethodType = {
TCL_OO_METHOD_VERSION_CURRENT,
/* version */
"columns", /* name */
ConnectionColumnsMethod, /* callProc */
NULL, /* deleteProc */
NULL /* cloneProc */
};
const static Tcl_MethodType ConnectionCommitMethodType = {
TCL_OO_METHOD_VERSION_CURRENT,
/* version */
"commit", /* name */
ConnectionCommitMethod, /* callProc */
NULL, /* deleteProc */
NULL /* cloneProc */
};
const static Tcl_MethodType ConnectionConfigureMethodType = {
TCL_OO_METHOD_VERSION_CURRENT,
/* version */
"configure", /* name */
ConnectionConfigureMethod, /* callProc */
NULL, /* deleteProc */
NULL /* cloneProc */
};
const static Tcl_MethodType ConnectionRollbackMethodType = {
TCL_OO_METHOD_VERSION_CURRENT,
/* version */
"rollback", /* name */
ConnectionRollbackMethod, /* callProc */
NULL, /* deleteProc */
NULL /* cloneProc */
};
const static Tcl_MethodType ConnectionTablesMethodType = {
TCL_OO_METHOD_VERSION_CURRENT,
/* version */
"tables", /* name */
ConnectionTablesMethod, /* callProc */
NULL, /* deleteProc */
NULL /* cloneProc */
};
const static Tcl_MethodType* ConnectionMethods[] = {
&ConnectionBegintransactionMethodType,
&ConnectionColumnsMethodType,
&ConnectionCommitMethodType,
&ConnectionConfigureMethodType,
&ConnectionRollbackMethodType,
&ConnectionTablesMethodType,
NULL
};
/* Method types of the statement methods that are implemented in C */
const static Tcl_MethodType StatementConstructorType = {
TCL_OO_METHOD_VERSION_CURRENT,
/* version */
"CONSTRUCTOR", /* name */
StatementConstructor, /* callProc */
NULL, /* deleteProc */
NULL /* cloneProc */
};
const static Tcl_MethodType StatementParamsMethodType = {
TCL_OO_METHOD_VERSION_CURRENT,
/* version */
"params", /* name */
StatementParamsMethod, /* callProc */
NULL, /* deleteProc */
NULL /* cloneProc */
};
const static Tcl_MethodType StatementParamtypeMethodType = {
TCL_OO_METHOD_VERSION_CURRENT,
/* version */
"paramtype", /* name */
StatementParamtypeMethod, /* callProc */
NULL, /* deleteProc */
NULL /* cloneProc */
};
/*
* Methods to create on the statement class.
*/
const static Tcl_MethodType* StatementMethods[] = {
&StatementParamsMethodType,
&StatementParamtypeMethodType,
NULL
};
/*
*-----------------------------------------------------------------------------
*
* DummyNoticeReceiver --
*
* Ignores warnings and notices from the PostgreSQL client library
*
* Results:
* None.
*
* Side effects:
* None.
*
* This procedure does precisely nothing.
*
*-----------------------------------------------------------------------------
*/
static void
DummyNoticeProcessor(
TCL_UNUSED(void *),
TCL_UNUSED(const PGresult *))
{
}
/*
*-----------------------------------------------------------------------------
*
* ExecSimpleQuery --
*
* Executes given query.
*
* Results:
* TCL_OK on success or the error was non fatal otherwise TCL_ERROR .
*
* Side effects:
* Sets the interpreter result and error code appropiately to
* query execution process. Optionally, when res parameter is
* not NULL and the execution is successful, it returns the
* PGResult * struct by this parameter. This struct should be
* freed with PQclear() when no longer needed.
*
*-----------------------------------------------------------------------------
*/
static int ExecSimpleQuery(
Tcl_Interp* interp, /* Tcl interpreter */
PGconn * pgPtr, /* Connection handle */
const char * query, /* Query to execute */
PGresult** resOut /* Optional handle to result struct */
) {
PGresult * res; /* Query result */
/* Execute the query */
res = PQexec(pgPtr, query);
/* Return error if the query was unsuccessful */
if (res == NULL) {
TransferPostgresError(interp, pgPtr);
return TCL_ERROR;
}
if (TransferResultError(interp, res) != TCL_OK) {
PQclear(res);
return TCL_ERROR;
}
/* Transfer query result to the caller */
if (resOut != NULL) {
*resOut = res;
} else {
PQclear(res);
}
return TCL_OK;
}
/*
*-----------------------------------------------------------------------------
*
* TransferPostgresError --
*
* Obtains the connection related error message from the Postgres
* client library and transfers them into the Tcl interpreter.
* Unfortunately we cannot get error number or SQL state in
* connection context.
*
* Results:
* None.
*
* Side effects:
*
* Sets the interpreter result and error code to describe the SQL
* connection error.
*
*-----------------------------------------------------------------------------
*/
static void
TransferPostgresError(
Tcl_Interp* interp, /* Tcl interpreter */
PGconn* pgPtr /* Postgres connection handle */
) {
Tcl_Obj* errorCode = Tcl_NewObj();
Tcl_ListObjAppendElement(NULL, errorCode, Tcl_NewStringObj("TDBC", -1));
Tcl_ListObjAppendElement(NULL, errorCode,
Tcl_NewStringObj("GENERAL_ERROR", -1));
Tcl_ListObjAppendElement(NULL, errorCode,
Tcl_NewStringObj("HY000", -1));
Tcl_ListObjAppendElement(NULL, errorCode, Tcl_NewStringObj("POSTGRES", -1));
Tcl_ListObjAppendElement(NULL, errorCode,
Tcl_NewWideIntObj(-1));
Tcl_SetObjErrorCode(interp, errorCode);
Tcl_SetObjResult(interp, Tcl_NewStringObj(PQerrorMessage(pgPtr), -1));
}
/*
*-----------------------------------------------------------------------------
*
* TransferPostgresError --
*
* Check if there is any error related to given PGresult object.
* If there was an error, it obtains error message, SQL state
* and error number from the Postgres client library and transfers
* thenm into the Tcl interpreter.
*
* Results:
* TCL_OK if no error exists or the error was non fatal,
* otherwise TCL_ERROR is returned
*
* Side effects:
*
* Sets the interpreter result and error code to describe the SQL
* connection error.
*
*-----------------------------------------------------------------------------
*/
static int TransferResultError(
Tcl_Interp* interp,
PGresult * res
) {
ExecStatusType error = PQresultStatus(res);
const char* sqlstate;
if (error == PGRES_BAD_RESPONSE
|| error == PGRES_EMPTY_QUERY
|| error == PGRES_NONFATAL_ERROR
|| error == PGRES_FATAL_ERROR) {
Tcl_Obj* errorCode = Tcl_NewObj();
Tcl_ListObjAppendElement(NULL, errorCode, Tcl_NewStringObj("TDBC", -1));
sqlstate = PQresultErrorField(res, PG_DIAG_SQLSTATE);
if (sqlstate == NULL) {
sqlstate = "HY000";
}
Tcl_ListObjAppendElement(NULL, errorCode,
Tcl_NewStringObj(Tdbc_MapSqlState(sqlstate), -1));
Tcl_ListObjAppendElement(NULL, errorCode,
Tcl_NewStringObj(sqlstate, -1));
Tcl_ListObjAppendElement(NULL, errorCode,
Tcl_NewStringObj("POSTGRES", -1));
Tcl_ListObjAppendElement(NULL, errorCode,
Tcl_NewWideIntObj(error));
Tcl_SetObjErrorCode(interp, errorCode);
if (error == PGRES_EMPTY_QUERY) {
Tcl_SetObjResult(interp, Tcl_NewStringObj("empty query", -1));
} else {
Tcl_SetObjResult(interp, Tcl_NewStringObj(
PQresultErrorField(res, PG_DIAG_MESSAGE_PRIMARY), -1));
}
}
if (error == PGRES_BAD_RESPONSE
|| error == PGRES_EMPTY_QUERY
|| error == PGRES_FATAL_ERROR) {
return TCL_ERROR;
} else {
return TCL_OK;
}
}
/*
*-----------------------------------------------------------------------------
*
* DeterminePostgresMajorVersion --
*
* Determine the major version of the PostgreSQL server at the
* other end of a connection.
*
* Results:
* Returns a standard Tcl error code.
*
* Side effects:
* Stores the version number in '*versionPtr' if successful.
*
*-----------------------------------------------------------------------------
*/
static int
DeterminePostgresMajorVersion(Tcl_Interp* interp,
/* Tcl interpreter */
ConnectionData* cdata,
/* Connection data */
int* versionPtr)
/* OUTPUT: PostgreSQL server version */
{
PGresult* res; /* Result of a Postgres query */
int status = TCL_ERROR; /* Status return */
char* versionStr; /* Version information from server */
if (ExecSimpleQuery(interp, cdata->pgPtr,
"SELECT version()", &res) == TCL_OK) {
versionStr = PQgetvalue(res, 0, 0);
if (sscanf(versionStr, " PostgreSQL %d", versionPtr) == 1) {
status = TCL_OK;
} else {
Tcl_Obj* result = Tcl_NewStringObj("unable to parse PostgreSQL "
"version: \"", -1);
Tcl_AppendToObj(result, versionStr, -1);
Tcl_AppendToObj(result, "\"", -1);
Tcl_SetErrorCode(interp, "TDBC", "GENERAL_ERROR", "HY000",
"POSTGRES", "-1", NULL);
}
PQclear(res);
}
return status;
}
/*
*-----------------------------------------------------------------------------
*
* QueryConnectionOption --
*
* Determine the current value of a connection option.
*
* Results:
* Returns a Tcl object containing the value if successful, or NULL
* if unsuccessful. If unsuccessful, stores error information in the
* Tcl interpreter.
*
*-----------------------------------------------------------------------------
*/
static Tcl_Obj*
QueryConnectionOption (
ConnectionData* cdata, /* Connection data */
Tcl_Interp* interp, /* Tcl interpreter */
int optionNum /* Position of the option in the table */
) {
PerInterpData* pidata = cdata->pidata; /* Per-interpreter data */
Tcl_Obj** literals = pidata->literals;
char * value; /* Return value as C string */
/* Suppress attempts to query the password */
if (ConnOptions[optionNum].info == INDX_PASS) {
return Tcl_NewObj();
}
if (ConnOptions[optionNum].type == TYPE_ENCODING) {
value = (char* )pg_encoding_to_char(PQclientEncoding(cdata->pgPtr));
return Tcl_NewStringObj(value, -1);
}
if (ConnOptions[optionNum].type == TYPE_ISOLATION) {
if (cdata->isolation == ISOL_NONE) {
PGresult * res;
char * isoName;
int i = 0;
/* The isolation level wasn't set - get default value */
if (ExecSimpleQuery(interp, cdata->pgPtr,
"SHOW default_transaction_isolation", &res) != TCL_OK) {
return NULL;
}
value = PQgetvalue(res, 0, 0);
isoName = (char*) ckalloc(strlen(value) + 1);
strcpy(isoName, value);
PQclear(res);
/* get rid of space */
while (isoName[i] != ' ' && isoName[i] != '\0') {
i+=1;
}
if (isoName[i] == ' ') {
while (isoName[i] != '\0') {
isoName[i] = isoName[i+1];
i+=1;
}
}
/* Search for isolation level name in predefined table */
i=0;
while (TclIsolationLevels[i] != NULL
&& strcmp(isoName, TclIsolationLevels[i])) {
i += 1;
}
ckfree(isoName);
if (TclIsolationLevels[i] != NULL) {
cdata->isolation = i;
} else {
return NULL;
}
}
return Tcl_NewStringObj(
TclIsolationLevels[cdata->isolation], -1);
}
if (ConnOptions[optionNum].type == TYPE_READONLY) {
if (cdata->readOnly == 0) {
return literals[LIT_0];
} else {
return literals[LIT_1];
}
}
if (ConnOptions[optionNum].queryF != NULL) {
value = ConnOptions[optionNum].queryF(cdata->pgPtr);
if (value != NULL) {
return Tcl_NewStringObj(value, -1);
}
}
if (ConnOptions[optionNum].type == TYPE_STRING &&
ConnOptions[optionNum].info != -1) {
/* Fallback: get value saved ealier */
value = cdata->savedOpts[ConnOptions[optionNum].info];
if (value != NULL) {
return Tcl_NewStringObj(value, -1);
}
}
return literals[LIT_EMPTY];
}
/*
*-----------------------------------------------------------------------------
*
* ConfigureConnection --
*
* Applies configuration settings to a Postrgre connection.
*
* Results:
* Returns a Tcl result. If the result is TCL_ERROR, error information
* is stored in the interpreter.
*
* Side effects:
* Updates configuration in the connection data. Opens a connection
* if none is yet open.
*
*-----------------------------------------------------------------------------
*/
static int
ConfigureConnection(
ConnectionData* cdata, /* Connection data */
Tcl_Interp* interp, /* Tcl interpreter */
Tcl_Size objc, /* Parameter count */
Tcl_Obj* const objv[], /* Parameter data */
Tcl_Size skip /* Number of parameters to skip */
) {
int optionIndex; /* Index of the current option in
* ConnOptions */
int optionValue; /* Integer value of the current option */
int i;
size_t j;
char portval[10]; /* String representation of port number */
char * encoding = NULL; /* Selected encoding name */
int isolation = ISOL_NONE; /* Isolation level */
int readOnly = -1; /* Read only indicator */
#define CONNINFO_LEN 1000
char connInfo[CONNINFO_LEN]; /* Configuration string for PQconnectdb() */
Tcl_Obj* retval;
Tcl_Obj* optval;
int vers; /* PostgreSQL major version */
if (cdata->pgPtr != NULL) {
/* Query configuration options on an existing connection */
if (objc == skip) {
/* Return all options as a dict */
retval = Tcl_NewObj();
for (i = 0; ConnOptions[i].name != NULL; ++i) {
if (ConnOptions[i].flags & CONN_OPT_FLAG_ALIAS) continue;
optval = QueryConnectionOption(cdata, interp, i);
if (optval == NULL) {
return TCL_ERROR;
}
Tcl_DictObjPut(NULL, retval,
Tcl_NewStringObj(ConnOptions[i].name, -1),
optval);
}
Tcl_SetObjResult(interp, retval);
return TCL_OK;
} else if (objc == skip+1) {
/* Return one option value */
if (Tcl_GetIndexFromObjStruct(interp, objv[skip],
(void*) ConnOptions,
sizeof(ConnOptions[0]), "option",
0, &optionIndex) != TCL_OK) {
return TCL_ERROR;
}
retval = QueryConnectionOption(cdata, interp, optionIndex);
if (retval == NULL) {
return TCL_ERROR;
} else {
Tcl_SetObjResult(interp, retval);
return TCL_OK;
}
}
}
/* In all cases number of parameters must be even */
if ((objc-skip) % 2 != 0) {
Tcl_WrongNumArgs(interp, skip, objv, "?-option value?...");
return TCL_ERROR;
}
/* Extract options from the command line */
for (i = 0; i < INDX_MAX; ++i) {
cdata->savedOpts[i] = NULL;
}
for (i = skip; i < objc; i += 2) {
/* Unknown option */
if (Tcl_GetIndexFromObjStruct(interp, objv[i], (void*) ConnOptions,
sizeof(ConnOptions[0]), "option",
0, &optionIndex) != TCL_OK) {
return TCL_ERROR;
}
/* Unmodifiable option */
if (cdata->pgPtr != NULL && !(ConnOptions[optionIndex].flags
& CONN_OPT_FLAG_MOD)) {
Tcl_Obj* msg = Tcl_NewStringObj("\"", -1);
Tcl_AppendObjToObj(msg, objv[i]);
Tcl_AppendToObj(msg, "\" option cannot be changed dynamically",
-1);
Tcl_SetObjResult(interp, msg);
Tcl_SetErrorCode(interp, "TDBC", "GENERAL_ERROR", "HY000",
"POSTGRES", "-1", NULL);
return TCL_ERROR;
}
/* Record option value */
switch (ConnOptions[optionIndex].type) {
case TYPE_STRING:
cdata->savedOpts[ConnOptions[optionIndex].info] =
Tcl_GetString(objv[i+1]);
break;
case TYPE_ENCODING:
encoding = Tcl_GetString(objv[i+1]);
break;
case TYPE_ISOLATION:
if (Tcl_GetIndexFromObjStruct(interp, objv[i+1], TclIsolationLevels,
sizeof(char *), "isolation level", TCL_EXACT, &isolation)
!= TCL_OK) {
return TCL_ERROR;
}
break;
case TYPE_PORT:
if (Tcl_GetIntFromObj(interp, objv[i+1], &optionValue) != TCL_OK) {
return TCL_ERROR;
}
if (optionValue < 0 || optionValue > 0xffff) {
Tcl_SetObjResult(interp, Tcl_NewStringObj("port number must "
"be in range "
"[0..65535]", -1));
Tcl_SetErrorCode(interp, "TDBC", "GENERAL_ERROR", "HY000",
"POSTGRES", "-1", NULL);
return TCL_ERROR;
}
snprintf(portval, sizeof(portval), "%d", optionValue);
cdata->savedOpts[INDX_PORT] = portval;
break;
case TYPE_READONLY:
if (Tcl_GetBooleanFromObj(interp, objv[i+1], &readOnly)
!= TCL_OK) {
return TCL_ERROR;
}
break;
}
}
if (cdata->pgPtr == NULL) {
j=0;
connInfo[0] = '\0';
for (i=0; i<INDX_MAX; i+=1) {
if (cdata->savedOpts[i] != NULL ) {
/* TODO escape values */
strncpy(&connInfo[j], optStringNames[i], CONNINFO_LEN - j);
j+=strlen(optStringNames[i]);
strncpy(&connInfo[j], " = '", CONNINFO_LEN - j);
j+=strlen(" = '");
strncpy(&connInfo[j], cdata->savedOpts[i], CONNINFO_LEN - j);
j+=strlen(cdata->savedOpts[i]);
strncpy(&connInfo[j], "' ", CONNINFO_LEN - j);
j+=strlen("' ");
}
}
cdata->pgPtr = PQconnectdb(connInfo);
if (cdata->pgPtr == NULL) {
Tcl_SetObjResult(interp,
Tcl_NewStringObj("PQconnectdb() failed, "
"propably out of memory.", -1));
Tcl_SetErrorCode(interp, "TDBC", "GENERAL_ERROR", "HY001",
"POSTGRES", "NULL", NULL);
return TCL_ERROR;
}
if (PQstatus(cdata->pgPtr) != CONNECTION_OK) {
TransferPostgresError(interp, cdata->pgPtr);
return TCL_ERROR;
}
PQsetNoticeProcessor(cdata->pgPtr, DummyNoticeProcessor, NULL);
}
/* Character encoding */
if (encoding != NULL ) {
if (PQsetClientEncoding(cdata->pgPtr, encoding) != 0) {
TransferPostgresError(interp, cdata->pgPtr);
return TCL_ERROR;
}
}
/* Transaction isolation level */
if (isolation != ISOL_NONE) {
if (ExecSimpleQuery(interp, cdata->pgPtr,
SqlIsolationLevels[isolation], NULL) != TCL_OK) {
return TCL_ERROR;
}
cdata->isolation = isolation;
}
/* Readonly indicator */
if (readOnly != -1) {
if (readOnly == 0) {
if (ExecSimpleQuery(interp, cdata->pgPtr,
"SET TRANSACTION READ WRITE", NULL) != TCL_OK) {
return TCL_ERROR;
}
} else {
if (ExecSimpleQuery(interp, cdata->pgPtr,
"SET TRANSACTION READ ONLY", NULL) != TCL_OK) {
return TCL_ERROR;
}
}
cdata->readOnly = readOnly;
}
/* Determine the PostgreSQL version in use */
if (DeterminePostgresMajorVersion(interp, cdata, &vers) != TCL_OK) {
return TCL_ERROR;
}
/*
* On PostgreSQL 9.0 and later, change 'bytea_output' to the
* backward-compatible 'escape' setting, so that the code in
* ResultSetNextrowMethod will retrieve byte array values correctly
* on either 8.x or 9.x servers.
*/
if (vers >= 9) {
if (ExecSimpleQuery(interp, cdata->pgPtr,
"SET bytea_output = 'escape'", NULL) != TCL_OK) {
return TCL_ERROR;
}
}
return TCL_OK;
}
/*
*-----------------------------------------------------------------------------
*
* ConnectionConstructor --
*
* Constructor for ::tdbc::postgres::connection, which represents a
* database connection.
*
* Results:
* Returns a standard Tcl result.
*
* The ConnectionInitMethod takes alternating keywords and values giving
* the configuration parameters of the connection, and attempts to connect
* to the database.
*
*-----------------------------------------------------------------------------
*/
static int
ConnectionConstructor(
void *clientData, /* Environment handle */
Tcl_Interp* interp, /* Tcl interpreter */
Tcl_ObjectContext context, /* Object context */
int objc, /* Parameter count */
Tcl_Obj *const objv[] /* Parameter vector */
) {
PerInterpData* pidata = (PerInterpData*) clientData;
/* Per-interp data for the POSTGRES package */
Tcl_Object thisObject = Tcl_ObjectContextObject(context);
/* The current object */
Tcl_Size skip = Tcl_ObjectContextSkippedArgs(context);
/* The number of leading arguments to skip */
ConnectionData* cdata; /* Per-connection data */
/* Hang client data on this connection */
cdata = (ConnectionData*) ckalloc(sizeof(ConnectionData));
memset(cdata, 0, sizeof(ConnectionData));
cdata->refCount = 1;
cdata->pidata = pidata;
cdata->pgPtr = NULL;
cdata->stmtCounter = 0;
cdata->flags = 0;
cdata->isolation = ISOL_NONE;
cdata->readOnly = 0;
IncrPerInterpRefCount(pidata);
Tcl_ObjectSetMetadata(thisObject, &connectionDataType, cdata);
/* Configure the connection */
if (ConfigureConnection(cdata, interp, objc, objv, skip) != TCL_OK) {
return TCL_ERROR;
}
return TCL_OK;
}
/*
*-----------------------------------------------------------------------------
*
* ConnectionBegintransactionMethod --
*
* Method that requests that following operations on an POSTGRES
* connection be executed as an atomic transaction.
*
* Usage:
* $connection begintransaction
*
* Parameters:
* None.
*
* Results:
* Returns an empty result if successful, and throws an error otherwise.
*
*-----------------------------------------------------------------------------
*/
static int
ConnectionBegintransactionMethod(
TCL_UNUSED(void *),
Tcl_Interp* interp, /* Tcl interpreter */
Tcl_ObjectContext objectContext, /* Object context */
int objc, /* Parameter count */
Tcl_Obj *const objv[] /* Parameter vector */
) {
Tcl_Object thisObject = Tcl_ObjectContextObject(objectContext);
/* The current connection object */
ConnectionData* cdata = (ConnectionData*)
Tcl_ObjectGetMetadata(thisObject, &connectionDataType);
/* Check parameters */
if (objc != 2) {
Tcl_WrongNumArgs(interp, 2, objv, "");
return TCL_ERROR;
}
/* Reject attempts at nested transactions */
if (cdata->flags & CONN_FLAG_IN_XCN) {
Tcl_SetObjResult(interp, Tcl_NewStringObj("Postgres does not support "
"nested transactions", -1));
Tcl_SetErrorCode(interp, "TDBC", "GENERAL_ERROR", "HYC00",
"POSTGRES", "-1", NULL);
return TCL_ERROR;
}
cdata->flags |= CONN_FLAG_IN_XCN;
/* Execute begin trasnaction block command */
return ExecSimpleQuery(interp, cdata->pgPtr, "BEGIN", NULL);
}
/*
*-----------------------------------------------------------------------------
*
* ConnectionCommitMethod --
*
* Method that requests that a pending transaction against a database
* be committed.
*
* Usage:
* $connection commit
*
* Parameters:
* None.
*
* Results:
* Returns an empty Tcl result if successful, and throws an error
* otherwise.
*
*-----------------------------------------------------------------------------
*/
static int
ConnectionCommitMethod(
TCL_UNUSED(void *),
Tcl_Interp* interp, /* Tcl interpreter */
Tcl_ObjectContext objectContext, /* Object context */
int objc, /* Parameter count */
Tcl_Obj *const objv[] /* Parameter vector */
) {
Tcl_Object thisObject = Tcl_ObjectContextObject(objectContext);
/* The current connection object */
ConnectionData* cdata = (ConnectionData*)
Tcl_ObjectGetMetadata(thisObject, &connectionDataType);
/* Instance data */
/* Check parameters */
if (objc != 2) {
Tcl_WrongNumArgs(interp, 2, objv, "");
return TCL_ERROR;
}
/* Reject the request if no transaction is in progress */
if (!(cdata->flags & CONN_FLAG_IN_XCN)) {
Tcl_SetObjResult(interp, Tcl_NewStringObj("no transaction is in "
"progress", -1));
Tcl_SetErrorCode(interp, "TDBC", "GENERAL_ERROR", "HY010",
"POSTGRES", "-1", NULL);
return TCL_ERROR;
}
cdata->flags &= ~ CONN_FLAG_IN_XCN;
/* Execute commit SQL command */
return ExecSimpleQuery(interp, cdata->pgPtr, "COMMIT", NULL);
}
/*
*-----------------------------------------------------------------------------
*
* ConnectionColumnsMethod --
*
* Method that asks for the names of columns in a table
* in the database (optionally matching a given pattern)
*
* Usage:
* $connection columns table ?pattern?
*
* Parameters:
* None.
*
* Results:
* Returns the list of tables
*
*-----------------------------------------------------------------------------
*/
static int
ConnectionColumnsMethod(
TCL_UNUSED(void *),
Tcl_Interp* interp, /* Tcl interpreter */
Tcl_ObjectContext objectContext, /* Object context */
int objc, /* Parameter count */
Tcl_Obj *const objv[] /* Parameter vector */
) {
Tcl_Object thisObject = Tcl_ObjectContextObject(objectContext);
/* The current connection object */
ConnectionData* cdata = (ConnectionData*)
Tcl_ObjectGetMetadata(thisObject, &connectionDataType);
/* Instance data */
PerInterpData* pidata = cdata->pidata;
/* Per-interpreter data */
Tcl_Obj** literals = pidata->literals;
/* Literal pool */
PGresult* res,* resType; /* Results of libpq call */
char* columnName; /* Name of the column */
Oid typeOid; /* Oid of column type */
Tcl_Obj* retval; /* List of table names */
Tcl_Obj* attrs; /* Attributes of the column */
Tcl_Obj* name; /* Name of a column */
Tcl_Obj* sqlQuery = Tcl_NewStringObj("SELECT * FROM \"", -1);
/* Query used */
Tcl_IncrRefCount(sqlQuery);
/* Check parameters */
if (objc < 3 || objc > 4) {
Tcl_WrongNumArgs(interp, 2, objv, "table ?pattern?");
return TCL_ERROR;
}
/* Check if table exists by retreiving one row.
* The result wille be later used to determine column types (oids) */
Tcl_AppendObjToObj(sqlQuery, objv[2]);
Tcl_AppendToObj(sqlQuery, "\" LIMIT 1", -1);
if (ExecSimpleQuery(interp, cdata->pgPtr, Tcl_GetString(sqlQuery),
&resType) != TCL_OK) {
Tcl_DecrRefCount(sqlQuery);
return TCL_ERROR;
}
Tcl_DecrRefCount(sqlQuery);
/* Retreive column attributes */
sqlQuery = Tcl_NewStringObj("SELECT "
" column_name,"
" numeric_precision,"
" character_maximum_length,"
" numeric_scale,"
" is_nullable"
" FROM information_schema.columns"
" WHERE table_name='", -1);
Tcl_IncrRefCount(sqlQuery);
Tcl_AppendObjToObj(sqlQuery, objv[2]);
if (objc == 4) {
Tcl_AppendToObj(sqlQuery,"' AND column_name LIKE '", -1);
Tcl_AppendObjToObj(sqlQuery, objv[3]);
}
Tcl_AppendToObj(sqlQuery,"'", -1);
if (ExecSimpleQuery(interp, cdata->pgPtr,
Tcl_GetString(sqlQuery), &res) != TCL_OK) {
Tcl_DecrRefCount(sqlQuery);
PQclear(resType);
return TCL_ERROR;
} else {
int i, j;
retval = Tcl_NewObj();
Tcl_IncrRefCount(retval);
for (i = 0; i < PQntuples(res); i += 1) {
attrs = Tcl_NewObj();
/* 0 is column_name column number */
columnName = PQgetvalue(res, i, 0);
name = Tcl_NewStringObj(columnName, -1);
Tcl_DictObjPut(NULL, attrs, literals[LIT_NAME], name);
/* Get the type name, by retrieving type oid */
j = PQfnumber(resType, columnName);
if (j >= 0) {
typeOid = PQftype(resType, j);
/* TODO: bsearch or sthing */
j = 0 ;
while (dataTypes[j].name != NULL
&& dataTypes[j].oid != typeOid) {
j+=1;
}
if ( dataTypes[j].name != NULL) {
Tcl_DictObjPut(NULL, attrs, literals[LIT_TYPE],
Tcl_NewStringObj(dataTypes[j].name, -1));
}
}
/* 1 is numeric_precision column number */
if (!PQgetisnull(res, i, 1)) {
Tcl_DictObjPut(NULL, attrs, literals[LIT_PRECISION],
Tcl_NewStringObj(PQgetvalue(res, i, 1), -1));
} else {
/* 2 is character_maximum_length column number */
if (!PQgetisnull(res, i, 2)) {
Tcl_DictObjPut(NULL, attrs, literals[LIT_PRECISION],
Tcl_NewStringObj(PQgetvalue(res, i, 2), -1));
}
}
/* 3 is character_maximum_length column number */
if (!PQgetisnull(res, i, 3)) {
/* This is for numbers */
Tcl_DictObjPut(NULL, attrs, literals[LIT_SCALE],
Tcl_NewStringObj(PQgetvalue(res, i, 3), -1));
}
/* 4 is is_nullable column number */
Tcl_DictObjPut(NULL, attrs, literals[LIT_NULLABLE],
Tcl_NewWideIntObj(strcmp("YES",
PQgetvalue(res, i, 4)) == 0));
Tcl_DictObjPut(NULL, retval, name, attrs);
}
Tcl_DecrRefCount(sqlQuery);
Tcl_SetObjResult(interp, retval);
Tcl_DecrRefCount(retval);
PQclear(resType);
PQclear(res);
return TCL_OK;
}
}
/*
*-----------------------------------------------------------------------------
*
* ConnectionConfigureMethod --
*
* Change configuration parameters on an open connection.
*
* Usage:
* $connection configure ?-keyword? ?value? ?-keyword value ...?
*
* Parameters:
* Keyword-value pairs (or a single keyword, or an empty set)
* of configuration options.
*
* Options:
* The following options are supported;
* -database
* Name of the database to use by default in queries
* -encoding
* Character encoding to use with the server. (Must be utf-8)
* -isolation
* Transaction isolation level.
* -readonly
* Read-only flag (must be a false Boolean value)
* -timeout
* Timeout value (both wait_timeout and interactive_timeout)
*
* Other options supported by the constructor are here in read-only
* mode; any attempt to change them will result in an error.
*
*-----------------------------------------------------------------------------
*/
static int ConnectionConfigureMethod(
TCL_UNUSED(void *),
Tcl_Interp* interp,
Tcl_ObjectContext objectContext,
int objc,
Tcl_Obj *const objv[]
) {
Tcl_Object thisObject = Tcl_ObjectContextObject(objectContext);
/* The current connection object */
Tcl_Size skip = Tcl_ObjectContextSkippedArgs(objectContext);
/* Number of arguments to skip */
ConnectionData* cdata = (ConnectionData*)
Tcl_ObjectGetMetadata(thisObject, &connectionDataType);
/* Instance data */
return ConfigureConnection(cdata, interp, objc, objv, skip);
}
/*
*-----------------------------------------------------------------------------
*
* ConnectionRollbackMethod --
*
* Method that requests that a pending transaction against a database
* be rolled back.
*
* Usage:
* $connection rollback
*
* Parameters:
* None.
*
* Results:
* Returns an empty Tcl result if successful, and throws an error
* otherwise.
*
*-----------------------------------------------------------------------------
*/
static int
ConnectionRollbackMethod(
TCL_UNUSED(void *),
Tcl_Interp* interp, /* Tcl interpreter */
Tcl_ObjectContext objectContext, /* Object context */
int objc, /* Parameter count */
Tcl_Obj *const objv[] /* Parameter vector */
) {
Tcl_Object thisObject = Tcl_ObjectContextObject(objectContext);
/* The current connection object */
ConnectionData* cdata = (ConnectionData*)
Tcl_ObjectGetMetadata(thisObject, &connectionDataType);
/* Instance data */
/* Check parameters */
if (objc != 2) {
Tcl_WrongNumArgs(interp, 2, objv, "");
return TCL_ERROR;
}
/* Reject the request if no transaction is in progress */
if (!(cdata->flags & CONN_FLAG_IN_XCN)) {
Tcl_SetObjResult(interp, Tcl_NewStringObj("no transaction is in "
"progress", -1));
Tcl_SetErrorCode(interp, "TDBC", "GENERAL_ERROR", "HY010",
"POSTGRES", "-1", NULL);
return TCL_ERROR;
}
cdata->flags &= ~CONN_FLAG_IN_XCN;
/* Send end transaction SQL command */
return ExecSimpleQuery(interp, cdata->pgPtr, "ROLLBACK", NULL);
}
/*
*-----------------------------------------------------------------------------
*
* ConnectionTablesMethod --
*
* Method that asks for the names of tables in the database (optionally
* matching a given pattern
*
* Usage:
* $connection tables ?pattern?
*
* Parameters:
* None.
*
* Results:
* Returns the list of tables
*
*-----------------------------------------------------------------------------
*/
static int
ConnectionTablesMethod(
TCL_UNUSED(void *),
Tcl_Interp* interp, /* Tcl interpreter */
Tcl_ObjectContext objectContext, /* Object context */
int objc, /* Parameter count */
Tcl_Obj *const objv[] /* Parameter vector */
) {
Tcl_Object thisObject = Tcl_ObjectContextObject(objectContext);
/* The current connection object */
ConnectionData* cdata = (ConnectionData*)
Tcl_ObjectGetMetadata(thisObject, &connectionDataType);
/* Instance data */
Tcl_Obj** literals = cdata->pidata->literals;
/* Literal pool */
PGresult* res; /* Result of libpq call */
char * field; /* Field value from SQL result */
Tcl_Obj* retval; /* List of table names */
Tcl_Obj* sqlQuery = Tcl_NewStringObj("SELECT tablename"
" FROM pg_tables"
" WHERE schemaname = 'public'",
-1);
/* SQL query for table list */
int i;
Tcl_IncrRefCount(sqlQuery);
/* Check parameters */
if (objc < 2 || objc > 3) {
Tcl_WrongNumArgs(interp, 2, objv, "");
return TCL_ERROR;
}
if (objc == 3) {
/* Pattern string is given */
Tcl_AppendToObj(sqlQuery, " AND tablename LIKE '", -1);
Tcl_AppendObjToObj(sqlQuery, objv[2]);
Tcl_AppendToObj(sqlQuery, "'", -1);
}
/* Retrieve the table list */
if (ExecSimpleQuery(interp, cdata ->pgPtr, Tcl_GetString(sqlQuery),
&res) != TCL_OK) {
Tcl_DecrRefCount(sqlQuery);
return TCL_ERROR;
}
Tcl_DecrRefCount(sqlQuery);
/* Iterate through the tuples and make the Tcl result */
retval = Tcl_NewObj();
for (i = 0; i < PQntuples(res); i+=1) {
if (!PQgetisnull(res, i, 0)) {
field = PQgetvalue(res, i, 0);
if (field) {
Tcl_ListObjAppendElement(NULL, retval,
Tcl_NewStringObj(field, -1));
Tcl_ListObjAppendElement(NULL, retval, literals[LIT_EMPTY]);
}
}
}
PQclear(res);
Tcl_SetObjResult(interp, retval);
return TCL_OK;
}
/*
*-----------------------------------------------------------------------------
*
* DeleteConnectionMetadata, DeleteConnection --
*
* Cleans up when a database connection is deleted.
*
* Results:
* None.
*
* Side effects:
* Terminates the connection and frees all system resources associated
* with it.
*
*-----------------------------------------------------------------------------
*/
static void
DeleteConnectionMetadata(
void *clientData /* Instance data for the connection */
) {
DecrConnectionRefCount((ConnectionData*)clientData);
}
static void
DeleteConnection(
ConnectionData* cdata /* Instance data for the connection */
) {
if (cdata->pgPtr != NULL) {
PQfinish(cdata->pgPtr);
}
DecrPerInterpRefCount(cdata->pidata);
ckfree(cdata);
}
/*
*-----------------------------------------------------------------------------
*
* CloneConnection --
*
* Attempts to clone an Postgres connection's metadata.
*
* Results:
* Returns the new metadata
*
* At present, we don't attempt to clone connections - it's not obvious
* that such an action would ever even make sense. Instead, we return NULL
* to indicate that the metadata should not be cloned. (Note that this
* action isn't right, either. What *is* right is to indicate that the object
* is not clonable, but the API gives us no way to do that.
*
*-----------------------------------------------------------------------------
*/
static int
CloneConnection(
Tcl_Interp* interp, /* Tcl interpreter for error reporting */
TCL_UNUSED(void *),
TCL_UNUSED(void **)
) {
Tcl_SetObjResult(interp,
Tcl_NewStringObj("Postgres connections are not clonable",
-1));
return TCL_ERROR;
}
/*
*-----------------------------------------------------------------------------
*
* DeleteCmd --
*
* Callback executed when the initialization method of the connection
* class is deleted.
*
* Side effects:
* Dismisses the environment, which has the effect of shutting
* down POSTGRES when it is no longer required.
*
*-----------------------------------------------------------------------------
*/
static void
DeleteCmd (
void *clientData /* Environment handle */
) {
PerInterpData* pidata = (PerInterpData*) clientData;
DecrPerInterpRefCount(pidata);
}
/*
*-----------------------------------------------------------------------------
*
* CloneCmd --
*
* Callback executed when any of the POSTGRES client methods is cloned.
*
* Results:
* Returns TCL_OK to allow the method to be copied.
*
* Side effects:
* Obtains a fresh copy of the environment handle, to keep the
* refcounts accurate
*
*-----------------------------------------------------------------------------
*/
static int
CloneCmd(
TCL_UNUSED(Tcl_Interp*),
void *oldClientData, /* Environment handle to be discarded */
void **newClientData /* New environment handle to be used */
) {
*newClientData = oldClientData;
return TCL_OK;
}
/*
*-----------------------------------------------------------------------------
*
* GenStatementName --
*
* Generates a unique name for a Postgre statement
*
* Results:
* Null terminated, free-able, string containg the name.
*
*-----------------------------------------------------------------------------
*/
static char*
GenStatementName(
ConnectionData* cdata /* Instance data for the connection */
) {
char stmtName[30];
char* retval;
cdata->stmtCounter += 1;
snprintf(stmtName, 30, "statement%d", cdata->stmtCounter);
retval = (char *)ckalloc(strlen(stmtName) + 1);
strcpy(retval, stmtName);
return retval;
}
/*
*-----------------------------------------------------------------------------
*
* UnallocateStatement --
*
* Tries tu unallocate prepared statement using SQL query. No
* errors are reported on failure.
*
* Results:
* Nothing.
*
*-----------------------------------------------------------------------------
*/
static void
UnallocateStatement(
PGconn * pgPtr, /* Connection handle */
char* stmtName /* Statement name */
) {
Tcl_Obj * sqlQuery = Tcl_NewStringObj("DEALLOCATE ", -1);
Tcl_IncrRefCount(sqlQuery);
Tcl_AppendToObj(sqlQuery, stmtName, -1);
PQclear(PQexec(pgPtr, Tcl_GetString(sqlQuery)));
Tcl_DecrRefCount(sqlQuery);
}
/*
*-----------------------------------------------------------------------------
*
* NewStatement --
*
* Creates an empty object to hold statement data.
*
* Results:
* Returns a pointer to the newly-created object.
*
*-----------------------------------------------------------------------------
*/
static StatementData*
NewStatement(
ConnectionData* cdata /* Instance data for the connection */
) {
StatementData* sdata = (StatementData*) ckalloc(sizeof(StatementData));
memset(sdata, 0, sizeof(StatementData));
sdata->refCount = 1;
sdata->cdata = cdata;
IncrConnectionRefCount(cdata);
sdata->subVars = Tcl_NewObj();
Tcl_IncrRefCount(sdata->subVars);
sdata->params = NULL;
sdata->paramDataTypes = NULL;
sdata->nativeSql = NULL;
sdata->columnNames = NULL;
sdata->flags = 0;
sdata->stmtName = GenStatementName(cdata);
sdata->paramTypesChanged = 0;
return sdata;
}
/*
*-----------------------------------------------------------------------------
*
* PrepareStatement --
*
* Prepare a PostgreSQL statement. When stmtName equals to
* NULL, statement name is taken from sdata strucure.
*
* Results:
* Returns the Posgres result object if successful, and NULL on failure.
*
* Side effects:
* Prepares the statement.
* Stores error message and error code in the interpreter on failure.
*
*-----------------------------------------------------------------------------
*/
static PGresult*
PrepareStatement(
Tcl_Interp* interp, /* Tcl interpreter for error reporting */
StatementData* sdata, /* Statement data */
char * stmtName /* Overriding name of the statement */
) {
ConnectionData* cdata = sdata->cdata;
/* Connection data */
const char* nativeSqlStr; /* Native SQL statement to prepare */
PGresult* res; /* result of statement preparing*/
PGresult* res2;
int i;
if (stmtName == NULL) {
stmtName = sdata->stmtName;
}
/*
* Prepare the statement. Rather than giving parameter types, try
* to let PostgreSQL infer all of them.
*/
nativeSqlStr = Tcl_GetString(sdata->nativeSql);
res = PQprepare(cdata->pgPtr, stmtName, nativeSqlStr, 0, NULL);
if (res == NULL) {
TransferPostgresError(interp, cdata->pgPtr);
return NULL;
}
/*
* Report on what parameter types were inferred.
*/
res2 = PQdescribePrepared(cdata->pgPtr, stmtName);
if (res2 == NULL) {
TransferPostgresError(interp, cdata->pgPtr);
PQclear(res);
return NULL;
}
for (i = 0; i < PQnparams(res2); ++i) {
sdata->paramDataTypes[i] = PQparamtype(res2, i);
sdata->params[i].precision = 0;
sdata->params[i].scale = 0;
}
PQclear(res2);
return res;
}
/*
*-----------------------------------------------------------------------------
*
* ResultDescToTcl --
*
* Converts a Postgres result description for return as a Tcl list.
*
* Results:
* Returns a Tcl object holding the result description
*
* If any column names are duplicated, they are disambiguated by
* appending '#n' where n increments once for each occurrence of the
* column name.
*
*-----------------------------------------------------------------------------
*/
static Tcl_Obj*
ResultDescToTcl(
PGresult* result /* Result set description */
) {
Tcl_Obj* retval = Tcl_NewObj();
Tcl_HashTable names; /* Hash table to resolve name collisions */
char * fieldName;
Tcl_InitHashTable(&names, TCL_STRING_KEYS);
if (result != NULL) {
unsigned int fieldCount = PQnfields(result);
unsigned int i;
char numbuf[16];
for (i = 0; i < fieldCount; ++i) {
int isNew;
int count = 1;
Tcl_Obj* nameObj;
Tcl_HashEntry* entry;
fieldName = PQfname(result, i);
nameObj = Tcl_NewStringObj(fieldName, -1);
Tcl_IncrRefCount(nameObj);
entry =
Tcl_CreateHashEntry(&names, fieldName, &isNew);
while (!isNew) {
count = PTR2INT(Tcl_GetHashValue(entry));
++count;
Tcl_SetHashValue(entry, INT2PTR(count));
snprintf(numbuf, sizeof(numbuf), "#%d", count);
Tcl_AppendToObj(nameObj, numbuf, -1);
entry = Tcl_CreateHashEntry(&names, Tcl_GetString(nameObj),
&isNew);
}
Tcl_SetHashValue(entry, INT2PTR(count));
Tcl_ListObjAppendElement(NULL, retval, nameObj);
Tcl_DecrRefCount(nameObj);
}
}
Tcl_DeleteHashTable(&names);
return retval;
}
/*
*-----------------------------------------------------------------------------
*
* StatementConstructor --
*
* C-level initialization for the object representing an Postgres prepared
* statement.
*
* Usage:
* statement new connection statementText
* statement create name connection statementText
*
* Parameters:
* connection -- the Postgres connection object
* statementText -- text of the statement to prepare.
*
* Results:
* Returns a standard Tcl result
*
* Side effects:
* Prepares the statement, and stores it (plus a reference to the
* connection) in instance metadata.
*
*-----------------------------------------------------------------------------
*/
static int
StatementConstructor(
TCL_UNUSED(void *),
Tcl_Interp* interp, /* Tcl interpreter */
Tcl_ObjectContext context, /* Object context */
int objc, /* Parameter count */
Tcl_Obj *const objv[] /* Parameter vector */
) {
Tcl_Object thisObject = Tcl_ObjectContextObject(context);
/* The current statement object */
Tcl_Size skip = Tcl_ObjectContextSkippedArgs(context);
/* Number of args to skip before the
* payload arguments */
Tcl_Object connectionObject;
/* The database connection as a Tcl_Object */
ConnectionData* cdata; /* The connection object's data */
StatementData* sdata; /* The statement's object data */
Tcl_Obj* tokens; /* The tokens of the statement to be prepared */
Tcl_Size tokenc; /* Length of the 'tokens' list */
Tcl_Obj** tokenv; /* Exploded tokens from the list */
Tcl_Obj* nativeSql; /* SQL statement mapped to native form */
char* tokenStr; /* Token string */
Tcl_Size tokenLen; /* Length of a token */
PGresult* res; /* Temporary result of libpq calls */
char tmpstr[30]; /* Temporary array for strings */
Tcl_Size i, j;
/* Find the connection object, and get its data. */
thisObject = Tcl_ObjectContextObject(context);
if (objc != skip+2) {
Tcl_WrongNumArgs(interp, skip, objv, "connection statementText");
return TCL_ERROR;
}
connectionObject = Tcl_GetObjectFromObj(interp, objv[skip]);
if (connectionObject == NULL) {
return TCL_ERROR;
}
cdata = (ConnectionData*) Tcl_ObjectGetMetadata(connectionObject,
&connectionDataType);
if (cdata == NULL) {
Tcl_AppendResult(interp, Tcl_GetString(objv[skip]),
" does not refer to a Postgres connection", NULL);
return TCL_ERROR;
}
/*
* Allocate an object to hold data about this statement
*/
sdata = NewStatement(cdata);
/* Tokenize the statement */
tokens = Tdbc_TokenizeSql(interp, Tcl_GetString(objv[skip+1]));
if (tokens == NULL) {
goto freeSData;
}
Tcl_IncrRefCount(tokens);
/*
* Rewrite the tokenized statement to Postgres syntax. Reject the
* statement if it is actually multiple statements.
*/
if (Tcl_ListObjGetElements(interp, tokens, &tokenc, &tokenv) != TCL_OK) {
goto freeTokens;
}
nativeSql = Tcl_NewObj();
Tcl_IncrRefCount(nativeSql);
j=0;
for (i = 0; i < tokenc; ++i) {
tokenStr = Tcl_GetStringFromObj(tokenv[i], &tokenLen);
switch (tokenStr[0]) {
case '$':
case ':':
/*
* A PostgreSQL cast is not a parameter!
*/
if (tokenStr[0] == ':' && tokenStr[1] == tokenStr[0]) {
Tcl_AppendToObj(nativeSql, tokenStr, tokenLen);
break;
}
j+=1;
snprintf(tmpstr, 30, "$%" TCL_SIZE_MODIFIER "d", j);
Tcl_AppendToObj(nativeSql, tmpstr, -1);
Tcl_ListObjAppendElement(NULL, sdata->subVars,
Tcl_NewStringObj(tokenStr+1, tokenLen-1));
break;
case ';':
Tcl_SetObjResult(interp,
Tcl_NewStringObj("tdbc::postgres"
" does not support semicolons "
"in statements", -1));
goto freeNativeSql;
break;
default:
Tcl_AppendToObj(nativeSql, tokenStr, tokenLen);
break;
}
}
sdata->nativeSql = nativeSql;
Tcl_DecrRefCount(tokens);
Tcl_ListObjLength(NULL, sdata->subVars, &sdata->nParams);
sdata->params = (ParamData*) ckalloc(sdata->nParams * sizeof(ParamData));
memset(sdata->params, 0, sdata->nParams * sizeof(ParamData));
sdata->paramDataTypes = (Oid*) ckalloc(sdata->nParams * sizeof(Oid));
memset(sdata->paramDataTypes, 0, sdata->nParams * sizeof(Oid));
for (i = 0; i < sdata->nParams; ++i) {
sdata->params[i].flags = PARAM_IN;
sdata->paramDataTypes[i] = UNTYPEDOID ;
sdata->params[i].precision = 0;
sdata->params[i].scale = 0;
}
/* Prepare the statement */
res = PrepareStatement(interp, sdata, NULL);
if (res == NULL) {
goto freeSData;
}
if (TransferResultError(interp, res) != TCL_OK) {
PQclear(res);
goto freeSData;
}
PQclear(res);
/* Attach the current statement data as metadata to the current object */
Tcl_ObjectSetMetadata(thisObject, &statementDataType, sdata);
return TCL_OK;
/* On error, unwind all the resource allocations */
freeNativeSql:
Tcl_DecrRefCount(nativeSql);
freeTokens:
Tcl_DecrRefCount(tokens);
freeSData:
DecrStatementRefCount(sdata);
return TCL_ERROR;
}
/*
*-----------------------------------------------------------------------------
*
* StatementParamsMethod --
*
* Lists the parameters in a Postgres statement.
*
* Usage:
* $statement params
*
* Results:
* Returns a standard Tcl result containing a dictionary. The keys
* of the dictionary are parameter names, and the values are parameter
* types, themselves expressed as dictionaries containing the keys,
* 'name', 'direction', 'type', 'precision', 'scale' and 'nullable'.
*
*
*-----------------------------------------------------------------------------
*/
static int
StatementParamsMethod(
TCL_UNUSED(void *),
Tcl_Interp* interp, /* Tcl interpreter */
Tcl_ObjectContext context, /* Object context */
int objc, /* Parameter count */
Tcl_Obj *const objv[] /* Parameter vector */
) {
Tcl_Object thisObject = Tcl_ObjectContextObject(context);
/* The current statement object */
StatementData* sdata /* The current statement */
= (StatementData*) Tcl_ObjectGetMetadata(thisObject,
&statementDataType);
ConnectionData* cdata = sdata->cdata;
PerInterpData* pidata = cdata->pidata; /* Per-interp data */
Tcl_Obj** literals = pidata->literals; /* Literal pool */
Tcl_Obj* paramName; /* Name of a parameter */
Tcl_Obj* paramDesc; /* Description of one parameter */
Tcl_Obj* dataTypeName; /* Name of a parameter's data type */
Tcl_Obj* retVal; /* Return value from this command */
Tcl_HashEntry* typeHashEntry;
Tcl_Size i;
if (objc != 2) {
Tcl_WrongNumArgs(interp, 2, objv, "");
return TCL_ERROR;
}
retVal = Tcl_NewObj();
for (i = 0; i < sdata->nParams; ++i) {
paramDesc = Tcl_NewObj();
Tcl_ListObjIndex(NULL, sdata->subVars, i, ¶mName);
Tcl_DictObjPut(NULL, paramDesc, literals[LIT_NAME], paramName);
switch (sdata->params[i].flags & (PARAM_IN | PARAM_OUT)) {
case PARAM_IN:
Tcl_DictObjPut(NULL, paramDesc, literals[LIT_DIRECTION],
literals[LIT_IN]);
break;
case PARAM_OUT:
Tcl_DictObjPut(NULL, paramDesc, literals[LIT_DIRECTION],
literals[LIT_OUT]);
break;
case PARAM_IN | PARAM_OUT:
Tcl_DictObjPut(NULL, paramDesc, literals[LIT_DIRECTION],
literals[LIT_INOUT]);
break;
default:
break;
}
typeHashEntry =
Tcl_FindHashEntry(&(pidata->typeNumHash),
INT2PTR(sdata->paramDataTypes[i]));
if (typeHashEntry != NULL) {
dataTypeName = (Tcl_Obj*) Tcl_GetHashValue(typeHashEntry);
Tcl_DictObjPut(NULL, paramDesc, literals[LIT_TYPE], dataTypeName);
}
Tcl_DictObjPut(NULL, paramDesc, literals[LIT_PRECISION],
Tcl_NewWideIntObj(sdata->params[i].precision));
Tcl_DictObjPut(NULL, paramDesc, literals[LIT_SCALE],
Tcl_NewWideIntObj(sdata->params[i].scale));
Tcl_DictObjPut(NULL, retVal, paramName, paramDesc);
}
Tcl_SetObjResult(interp, retVal);
return TCL_OK;
}
/*
*-----------------------------------------------------------------------------
*
* StatementParamtypeMethod --
*
* Defines a parameter type in a Postgres statement.
*
* Usage:
* $statement paramtype paramName ?direction? type ?precision ?scale??
*
* Results:
* Returns a standard Tcl result.
*
* Side effects:
* Updates the description of the given parameter.
*
*-----------------------------------------------------------------------------
*/
static int
StatementParamtypeMethod(
TCL_UNUSED(void *),
Tcl_Interp* interp, /* Tcl interpreter */
Tcl_ObjectContext context, /* Object context */
int objc, /* Parameter count */
Tcl_Obj *const objv[] /* Parameter vector */
) {
Tcl_Object thisObject = Tcl_ObjectContextObject(context);
/* The current statement object */
StatementData* sdata /* The current statement */
= (StatementData*) Tcl_ObjectGetMetadata(thisObject,
&statementDataType);
static const struct {
const char* name;
int flags;
} directions[] = {
{ "in", PARAM_IN },
{ "out", PARAM_OUT },
{ "inout", PARAM_IN | PARAM_OUT },
{ NULL, 0 }
};
int direction;
int typeNum; /* Data type number of a parameter */
int precision; /* Data precision */
int scale; /* Data scale */
const char* paramName; /* Name of the parameter being set */
Tcl_Obj* targetNameObj; /* Name of the ith parameter in the statement */
const char* targetName; /* Name of a candidate parameter in the
* statement */
int matchFound = 0; /* Number of parameters matching the name */
Tcl_Obj* errorObj; /* Error message */
int i;
/* Check parameters */
if (objc < 4) {
goto wrongNumArgs;
}
i = 3;
if (Tcl_GetIndexFromObjStruct(interp, objv[i], directions,
sizeof(directions[0]), "direction",
TCL_EXACT, &direction) != TCL_OK) {
direction = PARAM_IN;
Tcl_ResetResult(interp);
} else {
++i;
}
if (i >= objc) goto wrongNumArgs;
if (Tcl_GetIndexFromObjStruct(interp, objv[i], dataTypes,
sizeof(dataTypes[0]), "SQL data type",
TCL_EXACT, &typeNum) == TCL_OK) {
++i;
} else {
return TCL_ERROR;
}
if (i < objc) {
if (Tcl_GetIntFromObj(interp, objv[i], &precision) == TCL_OK) {
++i;
} else {
return TCL_ERROR;
}
}
if (i < objc) {
if (Tcl_GetIntFromObj(interp, objv[i], &scale) == TCL_OK) {
++i;
} else {
return TCL_ERROR;
}
}
if (i != objc) {
goto wrongNumArgs;
}
/* Look up parameters by name. */
paramName = Tcl_GetString(objv[2]);
for (i = 0; i < sdata->nParams; ++i) {
Tcl_ListObjIndex(NULL, sdata->subVars, i, &targetNameObj);
targetName = Tcl_GetString(targetNameObj);
if (!strcmp(paramName, targetName)) {
matchFound = 1;
sdata->params[i].flags = direction;
if (sdata->paramDataTypes[i] != dataTypes[typeNum].oid) {
sdata->paramTypesChanged = 1;
}
sdata->paramDataTypes[i] = dataTypes[typeNum].oid;
sdata->params[i].precision = precision;
sdata->params[i].scale = scale;
}
}
if (!matchFound) {
errorObj = Tcl_NewStringObj("unknown parameter \"", -1);
Tcl_AppendToObj(errorObj, paramName, -1);
Tcl_AppendToObj(errorObj, "\": must be ", -1);
for (i = 0; i < sdata->nParams; ++i) {
Tcl_ListObjIndex(NULL, sdata->subVars, i, &targetNameObj);
Tcl_AppendObjToObj(errorObj, targetNameObj);
if (i < sdata->nParams-2) {
Tcl_AppendToObj(errorObj, ", ", -1);
} else if (i == sdata->nParams-2) {
Tcl_AppendToObj(errorObj, " or ", -1);
}
}
Tcl_SetObjResult(interp, errorObj);
return TCL_ERROR;
}
return TCL_OK;
wrongNumArgs:
Tcl_WrongNumArgs(interp, 2, objv,
"name ?direction? type ?precision ?scale??");
return TCL_ERROR;
}
/*
*-----------------------------------------------------------------------------
*
* DeleteStatementMetadata, DeleteStatement --
*
* Cleans up when a Postgres statement is no longer required.
*
* Side effects:
* Frees all resources associated with the statement.
*
*-----------------------------------------------------------------------------
*/
static void
DeleteStatementMetadata(
void *clientData /* Instance data for the connection */
) {
DecrStatementRefCount((StatementData*)clientData);
}
static void
DeleteStatement(
StatementData* sdata /* Metadata for the statement */
) {
if (sdata->columnNames != NULL) {
Tcl_DecrRefCount(sdata->columnNames);
}
if (sdata->stmtName != NULL) {
UnallocateStatement(sdata->cdata->pgPtr, sdata->stmtName);
ckfree(sdata->stmtName);
}
if (sdata->nativeSql != NULL) {
Tcl_DecrRefCount(sdata->nativeSql);
}
if (sdata->params != NULL) {
ckfree(sdata->params);
}
if (sdata->paramDataTypes != NULL) {
ckfree(sdata->paramDataTypes);
}
Tcl_DecrRefCount(sdata->subVars);
DecrConnectionRefCount(sdata->cdata);
ckfree(sdata);
}
/*
*-----------------------------------------------------------------------------
*
* CloneStatement --
*
* Attempts to clone a Postgres statement's metadata.
*
* Results:
* Returns the new metadata
*
* At present, we don't attempt to clone statements - it's not obvious
* that such an action would ever even make sense. Instead, we return NULL
* to indicate that the metadata should not be cloned. (Note that this
* action isn't right, either. What *is* right is to indicate that the object
* is not clonable, but the API gives us no way to do that.
*
*-----------------------------------------------------------------------------
*/
static int
CloneStatement(
Tcl_Interp* interp, /* Tcl interpreter for error reporting */
TCL_UNUSED(void *),
TCL_UNUSED(void **)
) {
Tcl_SetObjResult(interp,
Tcl_NewStringObj("Postgres statements are not clonable",
-1));
return TCL_ERROR;
}
/*
*-----------------------------------------------------------------------------
*
* ResultSetConstructor --
*
* Constructs a new result set.
*
* Usage:
* $resultSet new statement ?dictionary?
* $resultSet create name statement ?dictionary?
*
* Parameters:
* statement -- Statement handle to which this resultset belongs
* dictionary -- Dictionary containing the substitutions for named
* parameters in the given statement.
*
* Results:
* Returns a standard Tcl result. On error, the interpreter result
* contains an appropriate message.
*
*-----------------------------------------------------------------------------
*/
static int
ResultSetConstructor(
TCL_UNUSED(void *),
Tcl_Interp* interp, /* Tcl interpreter */
Tcl_ObjectContext context, /* Object context */
int objc, /* Parameter count */
Tcl_Obj *const objv[] /* Parameter vector */
) {
Tcl_Object thisObject = Tcl_ObjectContextObject(context);
/* The current result set object */
Tcl_Size skip = Tcl_ObjectContextSkippedArgs(context);
/* Number of args to skip */
Tcl_Object statementObject; /* The current statement object */
ConnectionData* cdata; /* The Postgres connection object's data */
StatementData* sdata; /* The statement object's data */
ResultSetData* rdata; /* THe result set object's data */
Tcl_Obj* paramNameObj; /* Name of the current parameter */
const char* paramName; /* Name of the current parameter */
Tcl_Obj* paramValObj; /* Value of the current parameter */
const char** paramValues; /* Table of values */
int* paramLengths; /* Table of parameter lengths */
int* paramFormats; /* Table of parameter formats
* (binary or string) */
char* paramNeedsFreeing; /* Flags for whether a parameter needs
* its memory released */
Tcl_Obj** paramTempObjs; /* Temporary parameter objects allocated
* to canonicalize numeric parameter values */
PGresult* res; /* Temporary result */
int i;
int status = TCL_ERROR; /* Return status */
Tcl_Size len;
/* Check parameter count */
if (objc != skip+1 && objc != skip+2) {
Tcl_WrongNumArgs(interp, skip, objv, "statement ?dictionary?");
return TCL_ERROR;
}
/* Initialize the base classes */
Tcl_ObjectContextInvokeNext(interp, context, skip, objv, skip);
/* Find the statement object, and get the statement data */
statementObject = Tcl_GetObjectFromObj(interp, objv[skip]);
if (statementObject == NULL) {
return TCL_ERROR;
}
sdata = (StatementData*) Tcl_ObjectGetMetadata(statementObject,
&statementDataType);
if (sdata == NULL) {
Tcl_AppendResult(interp, Tcl_GetString(objv[skip]),
" does not refer to a Postgres statement", NULL);
return TCL_ERROR;
}
cdata = sdata->cdata;
rdata = (ResultSetData*) ckalloc(sizeof(ResultSetData));
memset(rdata, 0, sizeof(ResultSetData));
rdata->refCount = 1;
rdata->sdata = sdata;
rdata->stmtName = NULL;
rdata->execResult = NULL;
rdata->rowCount = 0;
IncrStatementRefCount(sdata);
Tcl_ObjectSetMetadata(thisObject, &resultSetDataType, rdata);
/*
* Find a statement handle that we can use to execute the SQL code.
* If the main statement handle associated with the statement
* is idle, we can use it. Otherwise, we have to allocate and
* prepare a fresh one.
*/
if (sdata->flags & STMT_FLAG_BUSY) {
rdata->stmtName = GenStatementName(cdata);
res = PrepareStatement(interp, sdata, rdata->stmtName);
if (res == NULL) {
return TCL_ERROR;
}
if (TransferResultError(interp, res) != TCL_OK) {
PQclear(res);
return TCL_ERROR;
}
PQclear(res);
} else {
rdata->stmtName = sdata->stmtName;
sdata->flags |= STMT_FLAG_BUSY;
/* We need to check if parameter types changed since the
* statement was prepared. If so, the statement is no longer
* usable, so we prepare it once again */
if (sdata->paramTypesChanged) {
UnallocateStatement(cdata->pgPtr, sdata->stmtName);
ckfree(sdata->stmtName);
sdata->stmtName = GenStatementName(cdata);
rdata->stmtName = sdata->stmtName;
res = PrepareStatement(interp, sdata, NULL);
if (res == NULL) {
return TCL_ERROR;
}
if (TransferResultError(interp, res) != TCL_OK) {
PQclear(res);
return TCL_ERROR;
}
PQclear(res);
sdata->paramTypesChanged = 0;
}
}
paramValues = (const char**) ckalloc(sdata->nParams * sizeof(char* ));
paramLengths = (int *) ckalloc(sdata->nParams * sizeof(int *));
paramFormats = (int*) ckalloc(sdata->nParams * sizeof(int*));
paramNeedsFreeing = (char *)ckalloc(sdata->nParams);
paramTempObjs = (Tcl_Obj**) ckalloc(sdata->nParams * sizeof(Tcl_Obj*));
memset(paramNeedsFreeing, 0, sdata->nParams);
for (i = 0; i < sdata->nParams; i++) {
paramTempObjs[i] = NULL;
}
for (i=0; i<sdata->nParams; i++) {
Tcl_ListObjIndex(NULL, sdata->subVars, i, ¶mNameObj);
paramName = Tcl_GetString(paramNameObj);
if (objc == skip+2) {
/* Param from a dictionary */
if (Tcl_DictObjGet(interp, objv[skip+1],
paramNameObj, ¶mValObj) != TCL_OK) {
goto freeParamTables;
}
} else {
/* Param from a variable */
paramValObj = Tcl_GetVar2Ex(interp, paramName, NULL,
TCL_LEAVE_ERR_MSG);
}
/* At this point, paramValObj contains the parameter value */
if (paramValObj != NULL) {
char * bufPtr;
int32_t tmp32;
int16_t tmp16;
switch (sdata->paramDataTypes[i]) {
case INT2OID:
bufPtr = (char *)ckalloc(sizeof(int));
if (Tcl_GetIntFromObj(interp, paramValObj,
(int*) bufPtr) != TCL_OK) {
goto freeParamTables;
}
paramValues[i] = (char *)ckalloc(sizeof(int16_t));
paramNeedsFreeing[i] = 1;
tmp16 = *(int*) bufPtr;
ckfree(bufPtr);
*(int16_t*)(paramValues[i])=htons(tmp16);
paramFormats[i] = 1;
paramLengths[i] = sizeof(int16_t);
break;
case INT4OID:
bufPtr = (char *)ckalloc(sizeof(long));
if (Tcl_GetLongFromObj(interp, paramValObj,
(long*) bufPtr) != TCL_OK) {
goto freeParamTables;
}
paramValues[i] = (char *)ckalloc(sizeof(int32_t));
paramNeedsFreeing[i] = 1;
tmp32 = *(long*) bufPtr;
ckfree(bufPtr);
*((int32_t*)(paramValues[i]))=htonl(tmp32);
paramFormats[i] = 1;
paramLengths[i] = sizeof(int32_t);
break;
/*
* With INT8, FLOAT4, FLOAT8, and NUMERIC, we will be passing
* the parameter as text, but it may not be in a canonical
* format, because Tcl will recognize binary, octal, and hex
* constants where Postgres will not. Begin by extracting
* wide int, float, or bignum from the parameter. If that
* succeeds, reconvert the result to text to canonicalize
* it, and send that text over.
*/
case INT8OID:
case NUMERICOID:
{
Tcl_WideInt val;
if (Tcl_GetWideIntFromObj(NULL, paramValObj, &val)
== TCL_OK) {
paramTempObjs[i] = Tcl_NewWideIntObj(val);
Tcl_IncrRefCount(paramTempObjs[i]);
paramFormats[i] = 0;
paramValues[i] =
Tcl_GetStringFromObj(paramTempObjs[i],
&len);
paramLengths[i] = len;
} else {
goto convertString;
/* If Tcl can't parse it, let SQL try */
}
}
break;
case FLOAT4OID:
case FLOAT8OID:
{
double val;
if (Tcl_GetDoubleFromObj(NULL, paramValObj, &val)
== TCL_OK) {
paramTempObjs[i] = Tcl_NewDoubleObj(val);
Tcl_IncrRefCount(paramTempObjs[i]);
paramFormats[i] = 0;
paramValues[i] =
Tcl_GetStringFromObj(paramTempObjs[i],
&len);
paramLengths[i] = len;
} else {
goto convertString;
/* If Tcl can't parse it, let SQL try */
}
}
break;
case BYTEAOID:
paramFormats[i] = 1;
paramValues[i] =
(char*)Tcl_GetByteArrayFromObj(paramValObj,
&len);
paramLengths[i] = len;
break;
default:
convertString:
paramFormats[i] = 0;
paramValues[i] = Tcl_GetStringFromObj(paramValObj,
&len);
paramLengths[i] = len;
break;
}
} else {
paramValues[i] = NULL;
paramFormats[i] = 0;
}
}
/* Execute the statement */
rdata->execResult = PQexecPrepared(cdata->pgPtr, rdata->stmtName,
sdata->nParams, paramValues,
paramLengths, paramFormats, 0);
if (TransferResultError(interp, rdata->execResult) != TCL_OK) {
goto freeParamTables;
}
sdata->columnNames = ResultDescToTcl(rdata->execResult);
Tcl_IncrRefCount(sdata->columnNames);
status = TCL_OK;
/* Clean up allocated memory */
freeParamTables:
for (i = 0; i < sdata->nParams; ++i) {
if (paramNeedsFreeing[i]) {
ckfree((void *)paramValues[i]);
}
if (paramTempObjs[i] != NULL) {
Tcl_DecrRefCount(paramTempObjs[i]);
}
}
ckfree(paramValues);
ckfree(paramLengths);
ckfree(paramFormats);
ckfree(paramNeedsFreeing);
ckfree(paramTempObjs);
return status;
}
/*
*-----------------------------------------------------------------------------
*
* ResultSetColumnsMethod --
*
* Retrieves the list of columns from a result set.
*
* Usage:
* $resultSet columns
*
* Results:
* Returns the count of columns
*
*-----------------------------------------------------------------------------
*/
static int
ResultSetColumnsMethod(
TCL_UNUSED(void *),
Tcl_Interp* interp, /* Tcl interpreter */
Tcl_ObjectContext context, /* Object context */
int objc, /* Parameter count */
Tcl_Obj *const objv[] /* Parameter vector */
) {
Tcl_Object thisObject = Tcl_ObjectContextObject(context);
/* The current result set object */
ResultSetData* rdata = (ResultSetData*)
Tcl_ObjectGetMetadata(thisObject, &resultSetDataType);
StatementData* sdata = (StatementData*) rdata->sdata;
if (objc != 2) {
Tcl_WrongNumArgs(interp, 2, objv, "?pattern?");
return TCL_ERROR;
}
Tcl_SetObjResult(interp, (sdata->columnNames));
return TCL_OK;
}
/*
*-----------------------------------------------------------------------------
*
* ResultSetNextrowMethod --
*
* Retrieves the next row from a result set.
*
* Usage:
* $resultSet nextrow ?-as lists|dicts? ?--? variableName
*
* Options:
* -as Selects the desired form for returning the results.
*
* Parameters:
* variableName -- Variable in which the results are to be returned
*
* Results:
* Returns a standard Tcl result. The interpreter result is 1 if there
* are more rows remaining, and 0 if no more rows remain.
*
* Side effects:
* Stores in the given variable either a list or a dictionary
* containing one row of the result set.
*
*-----------------------------------------------------------------------------
*/
static int
ResultSetNextrowMethod(
void *clientData, /* Not used */
Tcl_Interp* interp, /* Tcl interpreter */
Tcl_ObjectContext context, /* Object context */
int objc, /* Parameter count */
Tcl_Obj *const objv[] /* Parameter vector */
) {
int lists = PTR2INT(clientData);
Tcl_Object thisObject = Tcl_ObjectContextObject(context);
/* The current result set object */
ResultSetData* rdata = (ResultSetData*)
Tcl_ObjectGetMetadata(thisObject, &resultSetDataType);
/* Data pertaining to the current result set */
StatementData* sdata = (StatementData*) rdata->sdata;
/* Statement that yielded the result set */
ConnectionData* cdata = (ConnectionData*) sdata->cdata;
/* Connection that opened the statement */
PerInterpData* pidata = (PerInterpData*) cdata->pidata;
/* Per interpreter data */
Tcl_Obj** literals = pidata->literals;
Tcl_Size nColumns = 0; /* Number of columns in the result set */
Tcl_Obj* colObj; /* Column obtained from the row */
Tcl_Obj* colName; /* Name of the current column */
Tcl_Obj* resultRow; /* Row of the result set under construction */
int status = TCL_ERROR; /* Status return from this command */
char * buffer; /* buffer containing field value */
int buffSize; /* size of buffer containing field value */
Tcl_Size i;
if (objc != 3) {
Tcl_WrongNumArgs(interp, 2, objv, "varName");
return TCL_ERROR;
}
/* Check if row counter haven't already rech the last row */
if (rdata->rowCount >= PQntuples(rdata->execResult)) {
Tcl_SetObjResult(interp, literals[LIT_0]);
return TCL_OK;
}
/* Get the column names in the result set. */
Tcl_ListObjLength(NULL, sdata->columnNames, &nColumns);
if (nColumns == 0) {
Tcl_SetObjResult(interp, literals[LIT_0]);
return TCL_OK;
}
resultRow = Tcl_NewObj();
Tcl_IncrRefCount(resultRow);
/* Retrieve one column at a time. */
for (i = 0; i < nColumns; ++i) {
colObj = NULL;
if (PQgetisnull(rdata->execResult, rdata->rowCount, i) == 0) {
buffSize = PQgetlength(rdata->execResult, rdata->rowCount, i);
buffer = PQgetvalue(rdata->execResult, rdata->rowCount, i);
if (PQftype(rdata->execResult, i) == BYTEAOID) {
/*
* Postgres returns backslash-escape sequences for
* binary data. Substitute them away.
*/
Tcl_Obj* toSubst;
toSubst = Tcl_NewStringObj(buffer, buffSize);
Tcl_IncrRefCount(toSubst);
colObj = Tcl_SubstObj(interp, toSubst, TCL_SUBST_BACKSLASHES);
Tcl_DecrRefCount(toSubst);
} else {
colObj = Tcl_NewStringObj((char*)buffer, buffSize);
}
}
if (lists) {
if (colObj == NULL) {
colObj = Tcl_NewObj();
}
Tcl_ListObjAppendElement(NULL, resultRow, colObj);
} else {
if (colObj != NULL) {
Tcl_ListObjIndex(NULL, sdata->columnNames, i, &colName);
Tcl_DictObjPut(NULL, resultRow, colName, colObj);
}
}
}
/* Advance to the next row */
rdata->rowCount += 1;
/* Save the row in the given variable */
if (Tcl_SetVar2Ex(interp, Tcl_GetString(objv[2]), NULL,
resultRow, TCL_LEAVE_ERR_MSG) == NULL) {
goto cleanup;
}
Tcl_SetObjResult(interp, literals[LIT_1]);
status = TCL_OK;
cleanup:
Tcl_DecrRefCount(resultRow);
return status;
}
/*
*-----------------------------------------------------------------------------
*
* DeleteResultSetMetadata, DeleteResultSet --
*
* Cleans up when a Postgres result set is no longer required.
*
* Side effects:
* Frees all resources associated with the result set.
*
*-----------------------------------------------------------------------------
*/
static void
DeleteResultSetMetadata(
void *clientData /* Instance data for the connection */
) {
DecrResultSetRefCount((ResultSetData*)clientData);
}
static void
DeleteResultSet(
ResultSetData* rdata /* Metadata for the result set */
) {
StatementData* sdata = rdata->sdata;
if (rdata->stmtName != NULL) {
if (rdata->stmtName != sdata->stmtName) {
UnallocateStatement(sdata->cdata->pgPtr, rdata->stmtName);
ckfree(rdata->stmtName);
} else {
sdata->flags &= ~ STMT_FLAG_BUSY;
}
}
if (rdata->execResult != NULL) {
PQclear(rdata->execResult);
}
DecrStatementRefCount(rdata->sdata);
ckfree(rdata);
}
/*
*-----------------------------------------------------------------------------
*
* CloneResultSet --
*
* Attempts to clone a PostreSQL result set's metadata.
*
* Results:
* Returns the new metadata
*
* At present, we don't attempt to clone result sets - it's not obvious
* that such an action would ever even make sense. Instead, we throw an
* error.
*
*-----------------------------------------------------------------------------
*/
static int
CloneResultSet(
Tcl_Interp* interp, /* Tcl interpreter for error reporting */
TCL_UNUSED(void *),
TCL_UNUSED(void **)
) {
Tcl_SetObjResult(interp,
Tcl_NewStringObj("Postgres result sets are not clonable",
-1));
return TCL_ERROR;
}
/*
*-----------------------------------------------------------------------------
*
* ResultSetRowcountMethod --
*
* Returns (if known) the number of rows affected by a Postgres statement.
*
* Usage:
* $resultSet rowcount
*
* Results:
* Returns a standard Tcl result giving the number of affected rows.
*
*-----------------------------------------------------------------------------
*/
static int
ResultSetRowcountMethod(
TCL_UNUSED(void *),
Tcl_Interp* interp, /* Tcl interpreter */
Tcl_ObjectContext context, /* Object context */
int objc, /* Parameter count */
Tcl_Obj *const objv[] /* Parameter vector */
) {
char * nTuples;
Tcl_Object thisObject = Tcl_ObjectContextObject(context);
/* The current result set object */
ResultSetData* rdata = (ResultSetData*)
Tcl_ObjectGetMetadata(thisObject, &resultSetDataType);
/* Data pertaining to the current result set */
StatementData* sdata = rdata->sdata;
/* The current statement */
ConnectionData* cdata = sdata->cdata;
PerInterpData* pidata = cdata->pidata; /* Per-interp data */
Tcl_Obj** literals = pidata->literals; /* Literal pool */
if (objc != 2) {
Tcl_WrongNumArgs(interp, 2, objv, "");
return TCL_ERROR;
}
nTuples = PQcmdTuples(rdata->execResult);
if (strlen(nTuples) == 0) {
Tcl_SetObjResult(interp, literals[LIT_0]);
} else {
Tcl_SetObjResult(interp,
Tcl_NewStringObj(nTuples, -1));
}
return TCL_OK;
}
/*
*-----------------------------------------------------------------------------
*
* Tdbcpostgres_Init --
*
* Initializes the TDBC-POSTGRES bridge when this library is loaded.
*
* Side effects:
* Creates the ::tdbc::postgres namespace and the commands that reside in it.
* Initializes the POSTGRES environment.
*
*-----------------------------------------------------------------------------
*/
#ifndef STRINGIFY
# define STRINGIFY(x) STRINGIFY1(x)
# define STRINGIFY1(x) #x
#endif
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
DLLEXPORT int
Tdbcpostgres_Init(
Tcl_Interp* interp /* Tcl interpreter */
) {
PerInterpData* pidata; /* Per-interpreter data for this package */
Tcl_Obj* nameObj; /* Name of a class or method being looked up */
Tcl_Object curClassObject; /* Tcl_Object representing the current class */
Tcl_Class curClass; /* Tcl_Class representing the current class */
int i;
Tcl_CmdInfo info;
if (Tcl_InitStubs(interp, "8.5-", 0) == NULL) {
return TCL_ERROR;
}
if (TclOOInitializeStubs(interp, "1.0") == NULL) {
return TCL_ERROR;
}
if (Tdbc_InitStubs(interp) == NULL) {
return TCL_ERROR;
}
if (Tcl_GetCommandInfo(interp, "::tcl::build-info", &info)) {
Tcl_CreateObjCommand(interp, "::tdbc::postgres::build-info",
info.objProc, (void *)(
PACKAGE_VERSION "+" STRINGIFY(TDBC_POSTGRES_VERSION_UUID)
#if defined(__clang__) && defined(__clang_major__)
".clang-" STRINGIFY(__clang_major__)
#if __clang_minor__ < 10
"0"
#endif
STRINGIFY(__clang_minor__)
#endif
#if defined(__cplusplus) && !defined(__OBJC__)
".cplusplus"
#endif
#ifndef NDEBUG
".debug"
#endif
#if !defined(__clang__) && !defined(__INTEL_COMPILER) && defined(__GNUC__)
".gcc-" STRINGIFY(__GNUC__)
#if __GNUC_MINOR__ < 10
"0"
#endif
STRINGIFY(__GNUC_MINOR__)
#endif
#ifdef __INTEL_COMPILER
".icc-" STRINGIFY(__INTEL_COMPILER)
#endif
#ifdef TCL_MEM_DEBUG
".memdebug"
#endif
#if defined(_MSC_VER)
".msvc-" STRINGIFY(_MSC_VER)
#endif
#ifdef USE_NMAKE
".nmake"
#endif
#ifndef TCL_CFG_OPTIMIZED
".no-optimize"
#endif
#ifdef __OBJC__
".objective-c"
#if defined(__cplusplus)
"plusplus"
#endif
#endif
#ifdef TCL_CFG_PROFILED
".profile"
#endif
#ifdef PURIFY
".purify"
#endif
#ifdef STATIC_BUILD
".static"
#endif
), NULL);
}
/* Provide the current package */
if (Tcl_PkgProvideEx(interp, "tdbc::postgres", PACKAGE_VERSION, NULL) != TCL_OK) {
return TCL_ERROR;
}
/*
* Create per-interpreter data for the package
*/
pidata = (PerInterpData*) ckalloc(sizeof(PerInterpData));
pidata->refCount = 1;
for (i = 0; i < LIT__END; ++i) {
pidata->literals[i] = Tcl_NewStringObj(LiteralValues[i], -1);
Tcl_IncrRefCount(pidata->literals[i]);
}
Tcl_InitHashTable(&(pidata->typeNumHash), TCL_ONE_WORD_KEYS);
for (i = 0; dataTypes[i].name != NULL; ++i) {
int isNew;
Tcl_HashEntry* entry =
Tcl_CreateHashEntry(&(pidata->typeNumHash),
INT2PTR(dataTypes[i].oid),
&isNew);
Tcl_Obj* nameObj = Tcl_NewStringObj(dataTypes[i].name, -1);
Tcl_IncrRefCount(nameObj);
Tcl_SetHashValue(entry, (void *) nameObj);
}
/*
* Find the connection class, and attach an 'init' method to it.
*/
nameObj = Tcl_NewStringObj("::tdbc::postgres::connection", -1);
Tcl_IncrRefCount(nameObj);
if ((curClassObject = Tcl_GetObjectFromObj(interp, nameObj)) == NULL) {
Tcl_DecrRefCount(nameObj);
return TCL_ERROR;
}
Tcl_DecrRefCount(nameObj);
curClass = Tcl_GetObjectAsClass(curClassObject);
Tcl_ClassSetConstructor(interp, curClass,
Tcl_NewMethod(interp, curClass, NULL, 1,
&ConnectionConstructorType,
(void *) pidata));
/* Attach the methods to the 'connection' class */
for (i = 0; ConnectionMethods[i] != NULL; ++i) {
nameObj = Tcl_NewStringObj(ConnectionMethods[i]->name, -1);
Tcl_IncrRefCount(nameObj);
Tcl_NewMethod(interp, curClass, nameObj, 1, ConnectionMethods[i],
NULL);
Tcl_DecrRefCount(nameObj);
}
/* Look up the 'statement' class */
nameObj = Tcl_NewStringObj("::tdbc::postgres::statement", -1);
Tcl_IncrRefCount(nameObj);
if ((curClassObject = Tcl_GetObjectFromObj(interp, nameObj)) == NULL) {
Tcl_DecrRefCount(nameObj);
return TCL_ERROR;
}
Tcl_DecrRefCount(nameObj);
curClass = Tcl_GetObjectAsClass(curClassObject);
/* Attach the constructor to the 'statement' class */
Tcl_ClassSetConstructor(interp, curClass,
Tcl_NewMethod(interp, curClass, NULL, 1,
&StatementConstructorType,
NULL));
/* Attach the methods to the 'statement' class */
for (i = 0; StatementMethods[i] != NULL; ++i) {
nameObj = Tcl_NewStringObj(StatementMethods[i]->name, -1);
Tcl_IncrRefCount(nameObj);
Tcl_NewMethod(interp, curClass, nameObj, 1, StatementMethods[i],
NULL);
Tcl_DecrRefCount(nameObj);
}
/* Look up the 'resultSet' class */
nameObj = Tcl_NewStringObj("::tdbc::postgres::resultset", -1);
Tcl_IncrRefCount(nameObj);
if ((curClassObject = Tcl_GetObjectFromObj(interp, nameObj)) == NULL) {
Tcl_DecrRefCount(nameObj);
return TCL_ERROR;
}
Tcl_DecrRefCount(nameObj);
curClass = Tcl_GetObjectAsClass(curClassObject);
/* Attach the constructor to the 'resultSet' class */
Tcl_ClassSetConstructor(interp, curClass,
Tcl_NewMethod(interp, curClass, NULL, 1,
&ResultSetConstructorType,
NULL));
/* Attach the methods to the 'resultSet' class */
for (i = 0; ResultSetMethods[i] != NULL; ++i) {
nameObj = Tcl_NewStringObj(ResultSetMethods[i]->name, -1);
Tcl_IncrRefCount(nameObj);
Tcl_NewMethod(interp, curClass, nameObj, 1, ResultSetMethods[i],
NULL);
Tcl_DecrRefCount(nameObj);
}
nameObj = Tcl_NewStringObj("nextlist", -1);
Tcl_IncrRefCount(nameObj);
Tcl_NewMethod(interp, curClass, nameObj, 1, &ResultSetNextrowMethodType,
INT2PTR(1));
Tcl_DecrRefCount(nameObj);
nameObj = Tcl_NewStringObj("nextdict", -1);
Tcl_IncrRefCount(nameObj);
Tcl_NewMethod(interp, curClass, nameObj, 1, &ResultSetNextrowMethodType,
INT2PTR(0));
Tcl_DecrRefCount(nameObj);
/*
* Initialize the PostgreSQL library if this is the first interp using it.
*/
Tcl_MutexLock(&pgMutex);
if (pgRefCount == 0) {
if ((pgLoadHandle = PostgresqlInitStubs(interp)) == NULL) {
Tcl_MutexUnlock(&pgMutex);
return TCL_ERROR;
}
}
++pgRefCount;
Tcl_MutexUnlock(&pgMutex);
return TCL_OK;
}
#ifdef __cplusplus
}
#endif /* __cplusplus */
/*
*-----------------------------------------------------------------------------
*
* DeletePerInterpData --
*
* Delete per-interpreter data when the POSTGRES package is finalized
*
* Side effects:
*
* Releases the (presumably last) reference on the environment handle,
* cleans up the literal pool, and deletes the per-interp data structure.
*
*-----------------------------------------------------------------------------
*/
static void
DeletePerInterpData(
PerInterpData* pidata /* Data structure to clean up */
) {
int i;
Tcl_HashSearch search;
Tcl_HashEntry *entry;
for (entry = Tcl_FirstHashEntry(&(pidata->typeNumHash), &search);
entry != NULL;
entry = Tcl_NextHashEntry(&search)) {
Tcl_Obj* nameObj = (Tcl_Obj*) Tcl_GetHashValue(entry);
Tcl_DecrRefCount(nameObj);
}
Tcl_DeleteHashTable(&(pidata->typeNumHash));
for (i = 0; i < LIT__END; ++i) {
Tcl_DecrRefCount(pidata->literals[i]);
}
ckfree(pidata);
Tcl_MutexLock(&pgMutex);
if (--pgRefCount == 0) {
Tcl_FSUnloadFile(NULL, pgLoadHandle);
pgLoadHandle = NULL;
}
Tcl_MutexUnlock(&pgMutex);
}
/*
* Local Variables:
* mode: c
* c-basic-offset: 4
* End:
*/
|