1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064
|
/*
* $Id: pgmodule.c 877 2016-07-16 09:36:09Z cito $
* PyGres, version 2.2 A Python interface for PostgreSQL database. Written by
* D'Arcy J.M. Cain, (darcy@druid.net). Based heavily on code written by
* Pascal Andre, andre@chimay.via.ecp.fr. Copyright (c) 1995, Pascal Andre
* (andre@via.ecp.fr).
*
* Permission to use, copy, modify, and distribute this software and its
* documentation for any purpose, without fee, and without a written
* agreement is hereby granted, provided that the above copyright notice and
* this paragraph and the following two paragraphs appear in all copies or in
* any new file that contains a substantial portion of this file.
*
* IN NO EVENT SHALL THE AUTHOR BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
* SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,
* ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE
* AUTHOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* THE AUTHOR SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE
* AUTHOR HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT, UPDATES,
* ENHANCEMENTS, OR MODIFICATIONS.
*
* Further modifications copyright 1997 to 2016 by D'Arcy J.M. Cain
* (darcy@PyGreSQL.org) subject to the same terms and conditions as above.
*
*/
/* Note: This should be linked against the same C runtime lib as Python */
#include <Python.h>
#include <libpq-fe.h>
#include <libpq/libpq-fs.h>
/* the type definitions from <server/catalog/pg_type.h> */
#include "pgtypes.h"
/* macros for single-source Python 2/3 compatibility */
#include "py3c.h"
static PyObject *Error, *Warning, *InterfaceError,
*DatabaseError, *InternalError, *OperationalError, *ProgrammingError,
*IntegrityError, *DataError, *NotSupportedError;
#define _TOSTRING(x) #x
#define TOSTRING(x) _TOSTRING(x)
static const char *PyPgVersion = TOSTRING(PYGRESQL_VERSION);
#if SIZEOF_SIZE_T != SIZEOF_INT
#define Py_InitModule4 Py_InitModule4_64
#endif
/* default values */
#define PG_ARRAYSIZE 1
/* flags for object validity checks */
#define CHECK_OPEN 1
#define CHECK_CLOSE 2
#define CHECK_CNX 4
#define CHECK_RESULT 8
#define CHECK_DQL 16
/* query result types */
#define RESULT_EMPTY 1
#define RESULT_DML 2
#define RESULT_DDL 3
#define RESULT_DQL 4
/* flags for move methods */
#define QUERY_MOVEFIRST 1
#define QUERY_MOVELAST 2
#define QUERY_MOVENEXT 3
#define QUERY_MOVEPREV 4
#define MAX_BUFFER_SIZE 8192 /* maximum transaction size */
#define MAX_ARRAY_DEPTH 16 /* maximum allowed depth of an array */
/* MODULE GLOBAL VARIABLES */
#ifdef DEFAULT_VARS
static PyObject *pg_default_host; /* default database host */
static PyObject *pg_default_base; /* default database name */
static PyObject *pg_default_opt; /* default connection options */
static PyObject *pg_default_port; /* default connection port */
static PyObject *pg_default_user; /* default username */
static PyObject *pg_default_passwd; /* default password */
#endif /* DEFAULT_VARS */
static PyObject *decimal = NULL, /* decimal type */
*namedresult = NULL, /* function for getting named results */
*jsondecode = NULL; /* function for decoding json strings */
static const char *date_format = NULL; /* date format that is always assumed */
static char decimal_point = '.'; /* decimal point used in money values */
static int bool_as_text = 0; /* whether bool shall be returned as text */
static int array_as_text = 0; /* whether arrays shall be returned as text */
static int bytea_escaped = 0; /* whether bytea shall be returned escaped */
static int pg_encoding_utf8 = 0;
static int pg_encoding_latin1 = 0;
static int pg_encoding_ascii = 0;
/*
OBJECTS
=======
Each object has a number of elements. The naming scheme will be based on
the object type. Here are the elements using example object type "foo".
- fooObject: A structure to hold local object information.
- fooXxx: Object methods such as Delete and Getattr.
- fooMethods: Methods declaration.
- fooType: Type definition for object.
This is followed by the object methods.
The objects that we need to create:
- pg: The module itself.
- conn: Connection object returned from pg.connect().
- notice: Notice object returned from pg.notice().
- large: Large object returned by pg.conn.locreate() and Pg.Conn.loimport().
- query: Query object returned by pg.conn.Conn.query().
- source: Source object returned by pg.conn.source().
*/
/* forward declarations for types */
static PyTypeObject noticeType;
static PyTypeObject queryType;
static PyTypeObject sourceType;
static PyTypeObject largeType;
static PyTypeObject connType;
/* forward static declarations */
static void notice_receiver(void *, const PGresult *);
/* --------------------------------------------------------------------- */
/* Object declarations */
/* --------------------------------------------------------------------- */
typedef struct
{
PyObject_HEAD
int valid; /* validity flag */
PGconn *cnx; /* Postgres connection handle */
const char *date_format; /* date format derived from datestyle */
PyObject *cast_hook; /* external typecast method */
PyObject *notice_receiver; /* current notice receiver */
} connObject;
#define is_connObject(v) (PyType(v) == &connType)
typedef struct
{
PyObject_HEAD
int valid; /* validity flag */
connObject *pgcnx; /* parent connection object */
PGresult *result; /* result content */
int encoding; /* client encoding */
int result_type; /* result type (DDL/DML/DQL) */
long arraysize; /* array size for fetch method */
int current_row; /* current selected row */
int max_row; /* number of rows in the result */
int num_fields; /* number of fields in each row */
} sourceObject;
#define is_sourceObject(v) (PyType(v) == &sourceType)
typedef struct
{
PyObject_HEAD
connObject *pgcnx; /* parent connection object */
PGresult const *res; /* an error or warning */
} noticeObject;
#define is_noticeObject(v) (PyType(v) == ¬iceType)
typedef struct
{
PyObject_HEAD
connObject *pgcnx; /* parent connection object */
PGresult *result; /* result content */
int encoding; /* client encoding */
} queryObject;
#define is_queryObject(v) (PyType(v) == &queryType)
#ifdef LARGE_OBJECTS
typedef struct
{
PyObject_HEAD
connObject *pgcnx; /* parent connection object */
Oid lo_oid; /* large object oid */
int lo_fd; /* large object fd */
} largeObject;
#define is_largeObject(v) (PyType(v) == &largeType)
#endif /* LARGE_OBJECTS */
/* PyGreSQL internal types */
/* simple types */
#define PYGRES_INT 1
#define PYGRES_LONG 2
#define PYGRES_FLOAT 3
#define PYGRES_DECIMAL 4
#define PYGRES_MONEY 5
#define PYGRES_BOOL 6
/* text based types */
#define PYGRES_TEXT 8
#define PYGRES_BYTEA 9
#define PYGRES_JSON 10
#define PYGRES_OTHER 11
/* array types */
#define PYGRES_ARRAY 16
/* --------------------------------------------------------------------- */
/* Internal Functions */
/* --------------------------------------------------------------------- */
/* shared function for encoding and decoding strings */
static PyObject *
get_decoded_string(const char *str, Py_ssize_t size, int encoding)
{
if (encoding == pg_encoding_utf8)
return PyUnicode_DecodeUTF8(str, size, "strict");
if (encoding == pg_encoding_latin1)
return PyUnicode_DecodeLatin1(str, size, "strict");
if (encoding == pg_encoding_ascii)
return PyUnicode_DecodeASCII(str, size, "strict");
/* encoding name should be properly translated to Python here */
return PyUnicode_Decode(str, size,
pg_encoding_to_char(encoding), "strict");
}
static PyObject *
get_encoded_string(PyObject *unicode_obj, int encoding)
{
if (encoding == pg_encoding_utf8)
return PyUnicode_AsUTF8String(unicode_obj);
if (encoding == pg_encoding_latin1)
return PyUnicode_AsLatin1String(unicode_obj);
if (encoding == pg_encoding_ascii)
return PyUnicode_AsASCIIString(unicode_obj);
/* encoding name should be properly translated to Python here */
return PyUnicode_AsEncodedString(unicode_obj,
pg_encoding_to_char(encoding), "strict");
}
/* helper functions */
/* get PyGreSQL internal types for a PostgreSQL type */
static int
get_type(Oid pgtype)
{
int t;
switch (pgtype)
{
/* simple types */
case INT2OID:
case INT4OID:
case CIDOID:
case OIDOID:
case XIDOID:
t = PYGRES_INT;
break;
case INT8OID:
t = PYGRES_LONG;
break;
case FLOAT4OID:
case FLOAT8OID:
t = PYGRES_FLOAT;
break;
case NUMERICOID:
t = PYGRES_DECIMAL;
break;
case CASHOID:
t = decimal_point ? PYGRES_MONEY : PYGRES_TEXT;
break;
case BOOLOID:
t = PYGRES_BOOL;
break;
case BYTEAOID:
t = bytea_escaped ? PYGRES_TEXT : PYGRES_BYTEA;
break;
case JSONOID:
case JSONBOID:
t = jsondecode ? PYGRES_JSON : PYGRES_TEXT;
break;
case BPCHAROID:
case CHAROID:
case TEXTOID:
case VARCHAROID:
case NAMEOID:
case REGTYPEOID:
t = PYGRES_TEXT;
break;
/* array types */
case INT2ARRAYOID:
case INT4ARRAYOID:
case CIDARRAYOID:
case OIDARRAYOID:
case XIDARRAYOID:
t = array_as_text ? PYGRES_TEXT : (PYGRES_INT | PYGRES_ARRAY);
break;
case INT8ARRAYOID:
t = array_as_text ? PYGRES_TEXT : (PYGRES_LONG | PYGRES_ARRAY);
break;
case FLOAT4ARRAYOID:
case FLOAT8ARRAYOID:
t = array_as_text ? PYGRES_TEXT : (PYGRES_FLOAT | PYGRES_ARRAY);
break;
case NUMERICARRAYOID:
t = array_as_text ? PYGRES_TEXT : (PYGRES_DECIMAL | PYGRES_ARRAY);
break;
case CASHARRAYOID:
t = array_as_text ? PYGRES_TEXT : ((decimal_point ?
PYGRES_MONEY : PYGRES_TEXT) | PYGRES_ARRAY);
break;
case BOOLARRAYOID:
t = array_as_text ? PYGRES_TEXT : (PYGRES_BOOL | PYGRES_ARRAY);
break;
case BYTEAARRAYOID:
t = array_as_text ? PYGRES_TEXT : ((bytea_escaped ?
PYGRES_TEXT : PYGRES_BYTEA) | PYGRES_ARRAY);
break;
case JSONARRAYOID:
case JSONBARRAYOID:
t = array_as_text ? PYGRES_TEXT : ((jsondecode ?
PYGRES_JSON : PYGRES_TEXT) | PYGRES_ARRAY);
break;
case BPCHARARRAYOID:
case CHARARRAYOID:
case TEXTARRAYOID:
case VARCHARARRAYOID:
case NAMEARRAYOID:
case REGTYPEARRAYOID:
t = array_as_text ? PYGRES_TEXT : (PYGRES_TEXT | PYGRES_ARRAY);
break;
default:
t = PYGRES_OTHER;
}
return t;
}
/* get PyGreSQL column types for all result columns */
static int *
get_col_types(PGresult *result, int nfields)
{
int *types, *t, j;
if (!(types = PyMem_Malloc(sizeof(int) * nfields)))
return (int *)PyErr_NoMemory();
for (j = 0, t=types; j < nfields; ++j)
*t++ = get_type(PQftype(result, j));
return types;
}
/* Cast a bytea encoded text based type to a Python object.
This assumes the text is null-terminated character string. */
static PyObject *
cast_bytea_text(char *s)
{
PyObject *obj;
char *tmp_str;
size_t str_len;
/* this function should not be called when bytea_escaped is set */
tmp_str = (char *)PQunescapeBytea((unsigned char*)s, &str_len);
obj = PyBytes_FromStringAndSize(tmp_str, str_len);
if (tmp_str)
PQfreemem(tmp_str);
return obj;
}
/* Cast a text based type to a Python object.
This needs the character string, size and encoding. */
static PyObject *
cast_sized_text(char *s, Py_ssize_t size, int encoding, int type)
{
PyObject *obj, *tmp_obj;
char *tmp_str;
size_t str_len;
switch (type) /* this must be the PyGreSQL internal type */
{
case PYGRES_BYTEA:
/* this type should not be passed when bytea_escaped is set */
/* we need to add a null byte */
tmp_str = (char *) PyMem_Malloc(size + 1);
if (!tmp_str) return PyErr_NoMemory();
memcpy(tmp_str, s, size);
s = tmp_str; *(s + size) = '\0';
tmp_str = (char *)PQunescapeBytea((unsigned char*)s, &str_len);
PyMem_Free(s);
if (!tmp_str) return PyErr_NoMemory();
obj = PyBytes_FromStringAndSize(tmp_str, str_len);
if (tmp_str)
PQfreemem(tmp_str);
break;
case PYGRES_JSON:
/* this type should only be passed when jsondecode is set */
obj = get_decoded_string(s, size, encoding);
if (obj && jsondecode) /* was able to decode */
{
tmp_obj = Py_BuildValue("(O)", obj);
obj = PyObject_CallObject(jsondecode, tmp_obj);
Py_DECREF(tmp_obj);
}
break;
default: /* PYGRES_TEXT */
#if IS_PY3
obj = get_decoded_string(s, size, encoding);
if (!obj) /* cannot decode */
#endif
obj = PyBytes_FromStringAndSize(s, size);
}
return obj;
}
/* Cast an arbitrary type to a Python object using a callback function.
This needs the character string, size, encoding, the Postgres type
and the external typecast function to be called. */
static PyObject *
cast_other(char *s, Py_ssize_t size, int encoding, Oid pgtype,
PyObject *cast_hook)
{
PyObject *obj;
obj = cast_sized_text(s, size, encoding, PYGRES_TEXT);
if (cast_hook)
{
PyObject *tmp_obj = obj;
obj = PyObject_CallFunction(cast_hook, "(OI)", obj, pgtype);
Py_DECREF(tmp_obj);
}
return obj;
}
/* Cast a simple type to a Python object.
This needs a character string representation with a given size. */
static PyObject *
cast_sized_simple(char *s, Py_ssize_t size, int type)
{
PyObject *obj, *tmp_obj;
char buf[64], *t;
int i, j, n;
switch (type) /* this must be the PyGreSQL internal type */
{
case PYGRES_INT:
n = sizeof(buf)/sizeof(buf[0]) - 1;
if ((int)size < n) n = (int)size;
for (i = 0, t = buf; i < n; ++i) *t++ = *s++;
*t = '\0';
obj = PyInt_FromString(buf, NULL, 10);
break;
case PYGRES_LONG:
n = sizeof(buf)/sizeof(buf[0]) - 1;
if ((int)size < n) n = (int)size;
for (i = 0, t = buf; i < n; ++i) *t++ = *s++;
*t = '\0';
obj = PyLong_FromString(buf, NULL, 10);
break;
case PYGRES_FLOAT:
tmp_obj = PyStr_FromStringAndSize(s, size);
obj = PyFloat_FromString(tmp_obj);
Py_DECREF(tmp_obj);
break;
case PYGRES_MONEY:
/* this type should only be passed when decimal_point is set */
n = sizeof(buf)/sizeof(buf[0]) - 1;
for (i = 0, j = 0; i < size && j < n; ++i, ++s)
{
if (*s >= '0' && *s <= '9')
buf[j++] = *s;
else if (*s == decimal_point)
buf[j++] = '.';
else if (*s == '(' || *s == '-')
buf[j++] = '-';
}
if (decimal)
{
buf[j] = '\0';
obj = PyObject_CallFunction(decimal, "(s)", buf);
}
else
{
tmp_obj = PyStr_FromString(buf);
obj = PyFloat_FromString(tmp_obj);
Py_DECREF(tmp_obj);
}
break;
case PYGRES_DECIMAL:
tmp_obj = PyStr_FromStringAndSize(s, size);
obj = decimal ? PyObject_CallFunctionObjArgs(
decimal, tmp_obj, NULL) : PyFloat_FromString(tmp_obj);
Py_DECREF(tmp_obj);
break;
case PYGRES_BOOL:
/* convert to bool only if bool_as_text is not set */
if (bool_as_text)
{
obj = PyStr_FromString(*s == 't' ? "t" : "f");
}
else
{
obj = *s == 't' ? Py_True : Py_False;
Py_INCREF(obj);
}
break;
default:
/* other types should never be passed, use cast_sized_text */
obj = PyStr_FromStringAndSize(s, size);
}
return obj;
}
/* Cast a simple type to a Python object.
This needs a null-terminated character string representation. */
static PyObject *
cast_unsized_simple(char *s, int type)
{
PyObject *obj, *tmp_obj;
char buf[64];
int j, n;
switch (type) /* this must be the PyGreSQL internal type */
{
case PYGRES_INT:
obj = PyInt_FromString(s, NULL, 10);
break;
case PYGRES_LONG:
obj = PyLong_FromString(s, NULL, 10);
break;
case PYGRES_FLOAT:
tmp_obj = PyStr_FromString(s);
obj = PyFloat_FromString(tmp_obj);
Py_DECREF(tmp_obj);
break;
case PYGRES_MONEY:
/* this type should only be passed when decimal_point is set */
n = sizeof(buf)/sizeof(buf[0]) - 1;
for (j = 0; *s && j < n; ++s)
{
if (*s >= '0' && *s <= '9')
buf[j++] = *s;
else if (*s == decimal_point)
buf[j++] = '.';
else if (*s == '(' || *s == '-')
buf[j++] = '-';
}
buf[j] = '\0'; s = buf;
/* FALLTHROUGH */ /* no break here */
case PYGRES_DECIMAL:
if (decimal)
{
obj = PyObject_CallFunction(decimal, "(s)", s);
}
else
{
tmp_obj = PyStr_FromString(s);
obj = PyFloat_FromString(tmp_obj);
Py_DECREF(tmp_obj);
}
break;
case PYGRES_BOOL:
/* convert to bool only if bool_as_text is not set */
if (bool_as_text)
{
obj = PyStr_FromString(*s == 't' ? "t" : "f");
}
else
{
obj = *s == 't' ? Py_True : Py_False;
Py_INCREF(obj);
}
break;
default:
/* other types should never be passed, use cast_sized_text */
obj = PyStr_FromString(s);
}
return obj;
}
/* quick case insensitive check if given sized string is null */
#define STR_IS_NULL(s, n) (n == 4 \
&& (s[0] == 'n' || s[0] == 'N') \
&& (s[1] == 'u' || s[1] == 'U') \
&& (s[2] == 'l' || s[2] == 'L') \
&& (s[3] == 'l' || s[3] == 'L'))
/* Cast string s with size and encoding to a Python list,
using the input and output syntax for arrays.
Use internal type or cast function to cast elements.
The parameter delim specifies the delimiter for the elements,
since some types do not use the default delimiter of a comma. */
static PyObject *
cast_array(char *s, Py_ssize_t size, int encoding,
int type, PyObject *cast, char delim)
{
PyObject *result, *stack[MAX_ARRAY_DEPTH];
char *end = s + size, *t;
int depth, ranges = 0, level = 0;
if (type)
{
type &= ~PYGRES_ARRAY; /* get the base type */
if (!type) type = PYGRES_TEXT;
}
if (!delim)
delim = ',';
else if (delim == '{' || delim =='}' || delim=='\\')
{
PyErr_SetString(PyExc_ValueError, "Invalid array delimiter");
return NULL;
}
/* strip blanks at the beginning */
while (s != end && *s == ' ') ++s;
if (*s == '[') /* dimension ranges */
{
int valid;
for (valid = 0; !valid;)
{
if (s == end || *s++ != '[') break;
while (s != end && *s == ' ') ++s;
if (s != end && (*s == '+' || *s == '-')) ++s;
if (s == end || *s <= '0' || *s >= '9') break;
while (s != end && *s >= '0' && *s <= '9') ++s;
if (s == end || *s++ != ':') break;
if (s != end && (*s == '+' || *s == '-')) ++s;
if (s == end || *s <= '0' || *s >= '9') break;
while (s != end && *s >= '0' && *s <= '9') ++s;
if (s == end || *s++ != ']') break;
while (s != end && *s == ' ') ++s;
++ranges;
if (s != end && *s == '=')
{
do ++s; while (s != end && *s == ' ');
valid = 1;
}
}
if (!valid)
{
PyErr_SetString(PyExc_ValueError, "Invalid array dimensions");
return NULL;
}
}
for (t = s, depth = 0; t != end && (*t == '{' || *t == ' '); ++t)
if (*t == '{') ++depth;
if (!depth)
{
PyErr_SetString(PyExc_ValueError,
"Array must start with a left brace");
return NULL;
}
if (ranges && depth != ranges)
{
PyErr_SetString(PyExc_ValueError,
"Array dimensions do not match content");
return NULL;
}
if (depth > MAX_ARRAY_DEPTH)
{
PyErr_SetString(PyExc_ValueError, "Array is too deeply nested");
return NULL;
}
depth--; /* next level of parsing */
result = PyList_New(0);
if (!result) return NULL;
do ++s; while (s != end && *s == ' ');
/* everything is set up, start parsing the array */
while (s != end)
{
if (*s == '}')
{
PyObject *subresult;
if (!level) break; /* top level array ended */
do ++s; while (s != end && *s == ' ');
if (s == end) break; /* error */
if (*s == delim)
{
do ++s; while (s != end && *s == ' ');
if (s == end) break; /* error */
if (*s != '{')
{
PyErr_SetString(PyExc_ValueError,
"Subarray expected but not found");
Py_DECREF(result); return NULL;
}
}
else if (*s != '}') break; /* error */
subresult = result;
result = stack[--level];
if (PyList_Append(result, subresult))
{
Py_DECREF(result); return NULL;
}
}
else if (level == depth) /* we expect elements at this level */
{
PyObject *element;
char *estr;
Py_ssize_t esize;
int escaped = 0;
if (*s == '{')
{
PyErr_SetString(PyExc_ValueError,
"Subarray found where not expected");
Py_DECREF(result); return NULL;
}
if (*s == '"') /* quoted element */
{
estr = ++s;
while (s != end && *s != '"')
{
if (*s == '\\')
{
++s; if (s == end) break;
escaped = 1;
}
++s;
}
esize = s - estr;
do ++s; while (s != end && *s == ' ');
}
else /* unquoted element */
{
estr = s;
/* can contain blanks inside */
while (s != end && *s != '"' &&
*s != '{' && *s != '}' && *s != delim)
{
if (*s == '\\')
{
++s; if (s == end) break;
escaped = 1;
}
++s;
}
t = s; while (t > estr && *(t - 1) == ' ') --t;
if (!(esize = t - estr))
{
s = end; break; /* error */
}
if (STR_IS_NULL(estr, esize)) /* NULL gives None */
estr = NULL;
}
if (s == end) break; /* error */
if (estr)
{
if (escaped)
{
char *r;
Py_ssize_t i;
/* create unescaped string */
t = estr;
estr = (char *) PyMem_Malloc(esize);
if (!estr)
{
Py_DECREF(result); return PyErr_NoMemory();
}
for (i = 0, r = estr; i < esize; ++i)
{
if (*t == '\\') ++t, ++i;
*r++ = *t++;
}
esize = r - estr;
}
if (type) /* internal casting of base type */
{
if (type & PYGRES_TEXT)
element = cast_sized_text(estr, esize, encoding, type);
else
element = cast_sized_simple(estr, esize, type);
}
else /* external casting of base type */
{
#if IS_PY3
element = encoding == pg_encoding_ascii ? NULL :
get_decoded_string(estr, esize, encoding);
if (!element) /* no decoding necessary or possible */
#endif
element = PyBytes_FromStringAndSize(estr, esize);
if (element && cast)
{
PyObject *tmp = element;
element = PyObject_CallFunctionObjArgs(
cast, element, NULL);
Py_DECREF(tmp);
}
}
if (escaped) PyMem_Free(estr);
if (!element)
{
Py_DECREF(result); return NULL;
}
}
else
{
Py_INCREF(Py_None); element = Py_None;
}
if (PyList_Append(result, element))
{
Py_DECREF(element); Py_DECREF(result); return NULL;
}
Py_DECREF(element);
if (*s == delim)
{
do ++s; while (s != end && *s == ' ');
if (s == end) break; /* error */
}
else if (*s != '}') break; /* error */
}
else /* we expect arrays at this level */
{
if (*s != '{')
{
PyErr_SetString(PyExc_ValueError,
"Subarray must start with a left brace");
Py_DECREF(result); return NULL;
}
do ++s; while (s != end && *s == ' ');
if (s == end) break; /* error */
stack[level++] = result;
if (!(result = PyList_New(0))) return NULL;
}
}
if (s == end || *s != '}')
{
PyErr_SetString(PyExc_ValueError,
"Unexpected end of array");
Py_DECREF(result); return NULL;
}
do ++s; while (s != end && *s == ' ');
if (s != end)
{
PyErr_SetString(PyExc_ValueError,
"Unexpected characters after end of array");
Py_DECREF(result); return NULL;
}
return result;
}
/* Cast string s with size and encoding to a Python tuple.
using the input and output syntax for composite types.
Use array of internal types or cast function or sequence of cast
functions to cast elements. The parameter len is the record size.
The parameter delim can specify a delimiter for the elements,
although composite types always use a comma as delimiter. */
static PyObject *
cast_record(char *s, Py_ssize_t size, int encoding,
int *type, PyObject *cast, Py_ssize_t len, char delim)
{
PyObject *result, *ret;
char *end = s + size, *t;
Py_ssize_t i;
if (!delim)
delim = ',';
else if (delim == '(' || delim ==')' || delim=='\\')
{
PyErr_SetString(PyExc_ValueError, "Invalid record delimiter");
return NULL;
}
/* strip blanks at the beginning */
while (s != end && *s == ' ') ++s;
if (s == end || *s != '(')
{
PyErr_SetString(PyExc_ValueError,
"Record must start with a left parenthesis");
return NULL;
}
result = PyList_New(0);
if (!result) return NULL;
i = 0;
/* everything is set up, start parsing the record */
while (++s != end)
{
PyObject *element;
if (*s == ')' || *s == delim)
{
Py_INCREF(Py_None); element = Py_None;
}
else
{
char *estr;
Py_ssize_t esize;
int quoted = 0, escaped =0;
estr = s;
quoted = *s == '"';
if (quoted) ++s;
esize = 0;
while (s != end)
{
if (!quoted && (*s == ')' || *s == delim))
break;
if (*s == '"')
{
++s; if (s == end) break;
if (!(quoted && *s == '"'))
{
quoted = !quoted; continue;
}
}
if (*s == '\\')
{
++s; if (s == end) break;
}
++s, ++esize;
}
if (s == end) break; /* error */
if (estr + esize != s)
{
char *r;
escaped = 1;
/* create unescaped string */
t = estr;
estr = (char *) PyMem_Malloc(esize);
if (!estr)
{
Py_DECREF(result); return PyErr_NoMemory();
}
quoted = 0;
r = estr;
while (t != s)
{
if (*t == '"')
{
++t;
if (!(quoted && *t == '"'))
{
quoted = !quoted; continue;
}
}
if (*t == '\\') ++t;
*r++ = *t++;
}
}
if (type) /* internal casting of element type */
{
int etype = type[i];
if (etype & PYGRES_ARRAY)
element = cast_array(
estr, esize, encoding, etype, NULL, 0);
else if (etype & PYGRES_TEXT)
element = cast_sized_text(estr, esize, encoding, etype);
else
element = cast_sized_simple(estr, esize, etype);
}
else /* external casting of base type */
{
#if IS_PY3
element = encoding == pg_encoding_ascii ? NULL :
get_decoded_string(estr, esize, encoding);
if (!element) /* no decoding necessary or possible */
#endif
element = PyBytes_FromStringAndSize(estr, esize);
if (element && cast)
{
if (len)
{
PyObject *ecast = PySequence_GetItem(cast, i);
if (ecast)
{
if (ecast != Py_None)
{
PyObject *tmp = element;
element = PyObject_CallFunctionObjArgs(
ecast, element, NULL);
Py_DECREF(tmp);
}
}
else
{
Py_DECREF(element); element = NULL;
}
}
else
{
PyObject *tmp = element;
element = PyObject_CallFunctionObjArgs(
cast, element, NULL);
Py_DECREF(tmp);
}
}
}
if (escaped) PyMem_Free(estr);
if (!element)
{
Py_DECREF(result); return NULL;
}
}
if (PyList_Append(result, element))
{
Py_DECREF(element); Py_DECREF(result); return NULL;
}
Py_DECREF(element);
if (len) ++i;
if (*s != delim) break; /* no next record */
if (len && i >= len)
{
PyErr_SetString(PyExc_ValueError, "Too many columns");
Py_DECREF(result); return NULL;
}
}
if (s == end || *s != ')')
{
PyErr_SetString(PyExc_ValueError, "Unexpected end of record");
Py_DECREF(result); return NULL;
}
do ++s; while (s != end && *s == ' ');
if (s != end)
{
PyErr_SetString(PyExc_ValueError,
"Unexpected characters after end of record");
Py_DECREF(result); return NULL;
}
if (len && i < len)
{
PyErr_SetString(PyExc_ValueError, "Too few columns");
Py_DECREF(result); return NULL;
}
ret = PyList_AsTuple(result);
Py_DECREF(result);
return ret;
}
/* Cast string s with size and encoding to a Python dictionary.
using the input and output syntax for hstore values. */
static PyObject *
cast_hstore(char *s, Py_ssize_t size, int encoding)
{
PyObject *result;
char *end = s + size;
result = PyDict_New();
/* everything is set up, start parsing the record */
while (s != end)
{
char *key, *val;
PyObject *key_obj, *val_obj;
Py_ssize_t key_esc = 0, val_esc = 0, size;
int quoted;
while (s != end && *s == ' ') ++s;
if (s == end) break;
quoted = *s == '"';
if (quoted)
{
key = ++s;
while (s != end)
{
if (*s == '"') break;
if (*s == '\\')
{
if (++s == end) break;
++key_esc;
}
++s;
}
if (s == end)
{
PyErr_SetString(PyExc_ValueError, "Unterminated quote");
Py_DECREF(result); return NULL;
}
}
else
{
key = s;
while (s != end)
{
if (*s == '=' || *s == ' ') break;
if (*s == '\\')
{
if (++s == end) break;
++key_esc;
}
++s;
}
if (s == key)
{
PyErr_SetString(PyExc_ValueError, "Missing key");
Py_DECREF(result); return NULL;
}
}
size = s - key - key_esc;
if (key_esc)
{
char *r = key, *t;
key = (char *) PyMem_Malloc(size);
if (!key)
{
Py_DECREF(result); return PyErr_NoMemory();
}
t = key;
while (r != s)
{
if (*r == '\\')
{
++r; if (r == s) break;
}
*t++ = *r++;
}
}
key_obj = cast_sized_text(key, size, encoding, PYGRES_TEXT);
if (key_esc) PyMem_Free(key);
if (!key_obj)
{
Py_DECREF(result); return NULL;
}
if (quoted) ++s;
while (s != end && *s == ' ') ++s;
if (s == end || *s++ != '=' || s == end || *s++ != '>')
{
PyErr_SetString(PyExc_ValueError, "Invalid characters after key");
Py_DECREF(key_obj); Py_DECREF(result); return NULL;
}
while (s != end && *s == ' ') ++s;
quoted = *s == '"';
if (quoted)
{
val = ++s;
while (s != end)
{
if (*s == '"') break;
if (*s == '\\')
{
if (++s == end) break;
++val_esc;
}
++s;
}
if (s == end)
{
PyErr_SetString(PyExc_ValueError, "Unterminated quote");
Py_DECREF(result); return NULL;
}
}
else
{
val = s;
while (s != end)
{
if (*s == ',' || *s == ' ') break;
if (*s == '\\')
{
if (++s == end) break;
++val_esc;
}
++s;
}
if (s == val)
{
PyErr_SetString(PyExc_ValueError, "Missing value");
Py_DECREF(key_obj); Py_DECREF(result); return NULL;
}
if (STR_IS_NULL(val, s - val))
val = NULL;
}
if (val)
{
size = s - val - val_esc;
if (val_esc)
{
char *r = val, *t;
val = (char *) PyMem_Malloc(size);
if (!val)
{
Py_DECREF(key_obj); Py_DECREF(result);
return PyErr_NoMemory();
}
t = val;
while (r != s)
{
if (*r == '\\')
{
++r; if (r == s) break;
}
*t++ = *r++;
}
}
val_obj = cast_sized_text(val, size, encoding, PYGRES_TEXT);
if (val_esc) PyMem_Free(val);
if (!val_obj)
{
Py_DECREF(key_obj); Py_DECREF(result); return NULL;
}
}
else
{
Py_INCREF(Py_None); val_obj = Py_None;
}
if (quoted) ++s;
while (s != end && *s == ' ') ++s;
if (s != end)
{
if (*s++ != ',')
{
PyErr_SetString(PyExc_ValueError,
"Invalid characters after val");
Py_DECREF(key_obj); Py_DECREF(val_obj);
Py_DECREF(result); return NULL;
}
while (s != end && *s == ' ') ++s;
if (s == end)
{
PyErr_SetString(PyExc_ValueError, "Missing entry");
Py_DECREF(key_obj); Py_DECREF(val_obj);
Py_DECREF(result); return NULL;
}
}
PyDict_SetItem(result, key_obj, val_obj);
Py_DECREF(key_obj); Py_DECREF(val_obj);
}
return result;
}
/* internal wrapper for the notice receiver callback */
static void
notice_receiver(void *arg, const PGresult *res)
{
PyGILState_STATE gstate = PyGILState_Ensure();
connObject *self = (connObject*) arg;
PyObject *func = self->notice_receiver;
if (func)
{
noticeObject *notice = PyObject_NEW(noticeObject, ¬iceType);
PyObject *ret;
if (notice)
{
notice->pgcnx = arg;
notice->res = res;
}
else
{
Py_INCREF(Py_None);
notice = (noticeObject *)(void *)Py_None;
}
ret = PyObject_CallFunction(func, "(O)", notice);
Py_XDECREF(ret);
}
PyGILState_Release(gstate);
}
/* gets appropriate error type from sqlstate */
static PyObject *
get_error_type(const char *sqlstate)
{
switch (sqlstate[0]) {
case '0':
switch (sqlstate[1])
{
case 'A':
return NotSupportedError;
}
break;
case '2':
switch (sqlstate[1])
{
case '0':
case '1':
return ProgrammingError;
case '2':
return DataError;
case '3':
return IntegrityError;
case '4':
case '5':
return InternalError;
case '6':
case '7':
case '8':
return OperationalError;
case 'B':
case 'D':
case 'F':
return InternalError;
}
break;
case '3':
switch (sqlstate[1])
{
case '4':
return OperationalError;
case '8':
case '9':
case 'B':
return InternalError;
case 'D':
case 'F':
return ProgrammingError;
}
break;
case '4':
switch (sqlstate[1])
{
case '0':
return OperationalError;
case '2':
case '4':
return ProgrammingError;
}
break;
case '5':
case 'H':
return OperationalError;
case 'F':
case 'P':
case 'X':
return InternalError;
}
return DatabaseError;
}
/* sets database error message and sqlstate attribute */
static void
set_error_msg_and_state(PyObject *type,
const char *msg, int encoding, const char *sqlstate)
{
PyObject *err_obj, *msg_obj, *sql_obj = NULL;
#if IS_PY3
if (encoding == -1) /* unknown */
{
msg_obj = PyUnicode_DecodeLocale(msg, NULL);
}
else
msg_obj = get_decoded_string(msg, strlen(msg), encoding);
if (!msg_obj) /* cannot decode */
#endif
msg_obj = PyBytes_FromString(msg);
if (sqlstate)
sql_obj = PyStr_FromStringAndSize(sqlstate, 5);
else
{
Py_INCREF(Py_None); sql_obj = Py_None;
}
err_obj = PyObject_CallFunctionObjArgs(type, msg_obj, NULL);
if (err_obj)
{
Py_DECREF(msg_obj);
PyObject_SetAttrString(err_obj, "sqlstate", sql_obj);
Py_DECREF(sql_obj);
PyErr_SetObject(type, err_obj);
Py_DECREF(err_obj);
}
else
{
PyErr_SetString(type, msg);
}
}
/* sets given database error message */
static void
set_error_msg(PyObject *type, const char *msg)
{
set_error_msg_and_state(type, msg, pg_encoding_ascii, NULL);
}
/* sets database error from connection and/or result */
static void
set_error(PyObject *type, const char * msg, PGconn *cnx, PGresult *result)
{
char *sqlstate = NULL; int encoding = pg_encoding_ascii;
if (cnx)
{
char *err_msg = PQerrorMessage(cnx);
if (err_msg)
{
msg = err_msg;
encoding = PQclientEncoding(cnx);
}
}
if (result)
{
sqlstate = PQresultErrorField(result, PG_DIAG_SQLSTATE);
if (sqlstate) type = get_error_type(sqlstate);
}
set_error_msg_and_state(type, msg, encoding, sqlstate);
}
/* checks connection validity */
static int
check_cnx_obj(connObject *self)
{
if (!self || !self->valid || !self->cnx)
{
set_error_msg(OperationalError, "Connection has been closed");
return 0;
}
return 1;
}
/* format result (mostly useful for debugging) */
/* Note: This is similar to the Postgres function PQprint().
* PQprint() is not used because handing over a stream from Python to
* Postgres can be problematic if they use different libs for streams
* and because using PQprint() and tp_print is not recommended any more.
*/
static PyObject *
format_result(const PGresult *res)
{
const int n = PQnfields(res);
if (n > 0)
{
char * const aligns = (char *) PyMem_Malloc(n * sizeof(char));
int * const sizes = (int *) PyMem_Malloc(n * sizeof(int));
if (aligns && sizes)
{
const int m = PQntuples(res);
int i, j;
size_t size;
char *buffer;
/* calculate sizes and alignments */
for (j = 0; j < n; ++j)
{
const char * const s = PQfname(res, j);
const int format = PQfformat(res, j);
sizes[j] = s ? (int)strlen(s) : 0;
if (format)
{
aligns[j] = '\0';
if (m && sizes[j] < 8)
/* "<binary>" must fit */
sizes[j] = 8;
}
else
{
const Oid ftype = PQftype(res, j);
switch (ftype)
{
case INT2OID:
case INT4OID:
case INT8OID:
case FLOAT4OID:
case FLOAT8OID:
case NUMERICOID:
case OIDOID:
case XIDOID:
case CIDOID:
case CASHOID:
aligns[j] = 'r';
break;
default:
aligns[j] = 'l';
}
}
}
for (i = 0; i < m; ++i)
{
for (j = 0; j < n; ++j)
{
if (aligns[j])
{
const int k = PQgetlength(res, i, j);
if (sizes[j] < k)
/* value must fit */
sizes[j] = k;
}
}
}
size = 0;
/* size of one row */
for (j = 0; j < n; ++j) size += sizes[j] + 1;
/* times number of rows incl. heading */
size *= (m + 2);
/* plus size of footer */
size += 40;
/* is the buffer size that needs to be allocated */
buffer = (char *) PyMem_Malloc(size);
if (buffer)
{
char *p = buffer;
PyObject *result;
/* create the header */
for (j = 0; j < n; ++j)
{
const char * const s = PQfname(res, j);
const int k = sizes[j];
const int h = (k - (int)strlen(s)) / 2;
sprintf(p, "%*s", h, "");
sprintf(p + h, "%-*s", k - h, s);
p += k;
if (j + 1 < n)
*p++ = '|';
}
*p++ = '\n';
for (j = 0; j < n; ++j)
{
int k = sizes[j];
while (k--)
*p++ = '-';
if (j + 1 < n)
*p++ = '+';
}
*p++ = '\n';
/* create the body */
for (i = 0; i < m; ++i)
{
for (j = 0; j < n; ++j)
{
const char align = aligns[j];
const int k = sizes[j];
if (align)
{
sprintf(p, align == 'r' ?
"%*s" : "%-*s", k,
PQgetvalue(res, i, j));
}
else
{
sprintf(p, "%-*s", k,
PQgetisnull(res, i, j) ?
"" : "<binary>");
}
p += k;
if (j + 1 < n)
*p++ = '|';
}
*p++ = '\n';
}
/* free memory */
PyMem_Free(aligns); PyMem_Free(sizes);
/* create the footer */
sprintf(p, "(%d row%s)", m, m == 1 ? "" : "s");
/* return the result */
result = PyStr_FromString(buffer);
PyMem_Free(buffer);
return result;
}
else
{
PyMem_Free(aligns); PyMem_Free(sizes); return PyErr_NoMemory();
}
}
else
{
PyMem_Free(aligns); PyMem_Free(sizes); return PyErr_NoMemory();
}
}
else
return PyStr_FromString("(nothing selected)");
}
/* --------------------------------------------------------------------- */
/* large objects */
/* --------------------------------------------------------------------- */
#ifdef LARGE_OBJECTS
/* checks large object validity */
static int
check_lo_obj(largeObject *self, int level)
{
if (!check_cnx_obj(self->pgcnx))
return 0;
if (!self->lo_oid)
{
set_error_msg(IntegrityError, "Object is not valid (null oid)");
return 0;
}
if (level & CHECK_OPEN)
{
if (self->lo_fd < 0)
{
PyErr_SetString(PyExc_IOError, "Object is not opened");
return 0;
}
}
if (level & CHECK_CLOSE)
{
if (self->lo_fd >= 0)
{
PyErr_SetString(PyExc_IOError, "Object is already opened");
return 0;
}
}
return 1;
}
/* constructor (internal use only) */
static largeObject *
largeNew(connObject *pgcnx, Oid oid)
{
largeObject *npglo;
if (!(npglo = PyObject_NEW(largeObject, &largeType)))
return NULL;
Py_XINCREF(pgcnx);
npglo->pgcnx = pgcnx;
npglo->lo_fd = -1;
npglo->lo_oid = oid;
return npglo;
}
/* destructor */
static void
largeDealloc(largeObject *self)
{
if (self->lo_fd >= 0 && self->pgcnx->valid)
lo_close(self->pgcnx->cnx, self->lo_fd);
Py_XDECREF(self->pgcnx);
PyObject_Del(self);
}
/* opens large object */
static char largeOpen__doc__[] =
"open(mode) -- open access to large object with specified mode\n\n"
"The mode must be one of INV_READ, INV_WRITE (module level constants).\n";
static PyObject *
largeOpen(largeObject *self, PyObject *args)
{
int mode,
fd;
/* gets arguments */
if (!PyArg_ParseTuple(args, "i", &mode))
{
PyErr_SetString(PyExc_TypeError,
"The open() method takes an integer argument");
return NULL;
}
/* check validity */
if (!check_lo_obj(self, CHECK_CLOSE))
return NULL;
/* opens large object */
if ((fd = lo_open(self->pgcnx->cnx, self->lo_oid, mode)) < 0)
{
PyErr_SetString(PyExc_IOError, "Can't open large object");
return NULL;
}
self->lo_fd = fd;
/* no error : returns Py_None */
Py_INCREF(Py_None);
return Py_None;
}
/* close large object */
static char largeClose__doc__[] =
"close() -- close access to large object data";
static PyObject *
largeClose(largeObject *self, PyObject *noargs)
{
/* checks validity */
if (!check_lo_obj(self, CHECK_OPEN))
return NULL;
/* closes large object */
if (lo_close(self->pgcnx->cnx, self->lo_fd))
{
PyErr_SetString(PyExc_IOError, "Error while closing large object fd");
return NULL;
}
self->lo_fd = -1;
/* no error : returns Py_None */
Py_INCREF(Py_None);
return Py_None;
}
/* reads from large object */
static char largeRead__doc__[] =
"read(size) -- read from large object to sized string\n\n"
"Object must be opened in read mode before calling this method.\n";
static PyObject *
largeRead(largeObject *self, PyObject *args)
{
int size;
PyObject *buffer;
/* gets arguments */
if (!PyArg_ParseTuple(args, "i", &size))
{
PyErr_SetString(PyExc_TypeError,
"Method read() takes an integer argument");
return NULL;
}
if (size <= 0)
{
PyErr_SetString(PyExc_ValueError,
"Method read() takes a positive integer as argument");
return NULL;
}
/* checks validity */
if (!check_lo_obj(self, CHECK_OPEN))
return NULL;
/* allocate buffer and runs read */
buffer = PyBytes_FromStringAndSize((char *) NULL, size);
if ((size = lo_read(self->pgcnx->cnx, self->lo_fd,
PyBytes_AS_STRING((PyBytesObject *)(buffer)), size)) < 0)
{
PyErr_SetString(PyExc_IOError, "Error while reading");
Py_XDECREF(buffer);
return NULL;
}
/* resize buffer and returns it */
_PyBytes_Resize(&buffer, size);
return buffer;
}
/* write to large object */
static char largeWrite__doc__[] =
"write(string) -- write sized string to large object\n\n"
"Object must be opened in read mode before calling this method.\n";
static PyObject *
largeWrite(largeObject *self, PyObject *args)
{
char *buffer;
int size,
bufsize;
/* gets arguments */
if (!PyArg_ParseTuple(args, "s#", &buffer, &bufsize))
{
PyErr_SetString(PyExc_TypeError,
"Method write() expects a sized string as argument");
return NULL;
}
/* checks validity */
if (!check_lo_obj(self, CHECK_OPEN))
return NULL;
/* sends query */
if ((size = lo_write(self->pgcnx->cnx, self->lo_fd, buffer,
bufsize)) < bufsize)
{
PyErr_SetString(PyExc_IOError, "Buffer truncated during write");
return NULL;
}
/* no error : returns Py_None */
Py_INCREF(Py_None);
return Py_None;
}
/* go to position in large object */
static char largeSeek__doc__[] =
"seek(offset, whence) -- move to specified position\n\n"
"Object must be opened before calling this method. The whence option\n"
"can be SEEK_SET, SEEK_CUR or SEEK_END (module level constants).\n";
static PyObject *
largeSeek(largeObject *self, PyObject *args)
{
/* offset and whence are initialized to keep compiler happy */
int ret,
offset = 0,
whence = 0;
/* gets arguments */
if (!PyArg_ParseTuple(args, "ii", &offset, &whence))
{
PyErr_SetString(PyExc_TypeError,
"Method lseek() expects two integer arguments");
return NULL;
}
/* checks validity */
if (!check_lo_obj(self, CHECK_OPEN))
return NULL;
/* sends query */
if ((ret = lo_lseek(self->pgcnx->cnx, self->lo_fd, offset, whence)) == -1)
{
PyErr_SetString(PyExc_IOError, "Error while moving cursor");
return NULL;
}
/* returns position */
return PyInt_FromLong(ret);
}
/* gets large object size */
static char largeSize__doc__[] =
"size() -- return large object size\n\n"
"The object must be opened before calling this method.\n";
static PyObject *
largeSize(largeObject *self, PyObject *noargs)
{
int start,
end;
/* checks validity */
if (!check_lo_obj(self, CHECK_OPEN))
return NULL;
/* gets current position */
if ((start = lo_tell(self->pgcnx->cnx, self->lo_fd)) == -1)
{
PyErr_SetString(PyExc_IOError, "Error while getting current position");
return NULL;
}
/* gets end position */
if ((end = lo_lseek(self->pgcnx->cnx, self->lo_fd, 0, SEEK_END)) == -1)
{
PyErr_SetString(PyExc_IOError, "Error while getting end position");
return NULL;
}
/* move back to start position */
if ((start = lo_lseek(
self->pgcnx->cnx, self->lo_fd, start, SEEK_SET)) == -1)
{
PyErr_SetString(PyExc_IOError,
"Error while moving back to first position");
return NULL;
}
/* returns size */
return PyInt_FromLong(end);
}
/* gets large object cursor position */
static char largeTell__doc__[] =
"tell() -- give current position in large object\n\n"
"The object must be opened before calling this method.\n";
static PyObject *
largeTell(largeObject *self, PyObject *noargs)
{
int start;
/* checks validity */
if (!check_lo_obj(self, CHECK_OPEN))
return NULL;
/* gets current position */
if ((start = lo_tell(self->pgcnx->cnx, self->lo_fd)) == -1)
{
PyErr_SetString(PyExc_IOError, "Error while getting position");
return NULL;
}
/* returns size */
return PyInt_FromLong(start);
}
/* exports large object as unix file */
static char largeExport__doc__[] =
"export(filename) -- export large object data to specified file\n\n"
"The object must be closed when calling this method.\n";
static PyObject *
largeExport(largeObject *self, PyObject *args)
{
char *name;
/* checks validity */
if (!check_lo_obj(self, CHECK_CLOSE))
return NULL;
/* gets arguments */
if (!PyArg_ParseTuple(args, "s", &name))
{
PyErr_SetString(PyExc_TypeError,
"The method export() takes a filename as argument");
return NULL;
}
/* runs command */
if (!lo_export(self->pgcnx->cnx, self->lo_oid, name))
{
PyErr_SetString(PyExc_IOError, "Error while exporting large object");
return NULL;
}
Py_INCREF(Py_None);
return Py_None;
}
/* deletes a large object */
static char largeUnlink__doc__[] =
"unlink() -- destroy large object\n\n"
"The object must be closed when calling this method.\n";
static PyObject *
largeUnlink(largeObject *self, PyObject *noargs)
{
/* checks validity */
if (!check_lo_obj(self, CHECK_CLOSE))
return NULL;
/* deletes the object, invalidate it on success */
if (!lo_unlink(self->pgcnx->cnx, self->lo_oid))
{
PyErr_SetString(PyExc_IOError, "Error while unlinking large object");
return NULL;
}
self->lo_oid = 0;
Py_INCREF(Py_None);
return Py_None;
}
/* get the list of large object attributes */
static PyObject *
largeDir(largeObject *self, PyObject *noargs)
{
PyObject *attrs;
attrs = PyObject_Dir(PyObject_Type((PyObject *)self));
PyObject_CallMethod(attrs, "extend", "[sss]",
"oid", "pgcnx", "error");
return attrs;
}
/* large object methods */
static struct PyMethodDef largeMethods[] = {
{"__dir__", (PyCFunction) largeDir, METH_NOARGS, NULL},
{"open", (PyCFunction) largeOpen, METH_VARARGS, largeOpen__doc__},
{"close", (PyCFunction) largeClose, METH_NOARGS, largeClose__doc__},
{"read", (PyCFunction) largeRead, METH_VARARGS, largeRead__doc__},
{"write", (PyCFunction) largeWrite, METH_VARARGS, largeWrite__doc__},
{"seek", (PyCFunction) largeSeek, METH_VARARGS, largeSeek__doc__},
{"size", (PyCFunction) largeSize, METH_NOARGS, largeSize__doc__},
{"tell", (PyCFunction) largeTell, METH_NOARGS, largeTell__doc__},
{"export",(PyCFunction) largeExport, METH_VARARGS, largeExport__doc__},
{"unlink",(PyCFunction) largeUnlink, METH_NOARGS, largeUnlink__doc__},
{NULL, NULL}
};
/* gets large object attributes */
static PyObject *
largeGetAttr(largeObject *self, PyObject *nameobj)
{
const char *name = PyStr_AsString(nameobj);
/* list postgreSQL large object fields */
/* associated pg connection object */
if (!strcmp(name, "pgcnx"))
{
if (check_lo_obj(self, 0))
{
Py_INCREF(self->pgcnx);
return (PyObject *) (self->pgcnx);
}
PyErr_Clear();
Py_INCREF(Py_None);
return Py_None;
}
/* large object oid */
if (!strcmp(name, "oid"))
{
if (check_lo_obj(self, 0))
return PyInt_FromLong(self->lo_oid);
PyErr_Clear();
Py_INCREF(Py_None);
return Py_None;
}
/* error (status) message */
if (!strcmp(name, "error"))
return PyStr_FromString(PQerrorMessage(self->pgcnx->cnx));
/* seeks name in methods (fallback) */
return PyObject_GenericGetAttr((PyObject *) self, nameobj);
}
/* return large object as string in human readable form */
static PyObject *
largeStr(largeObject *self)
{
char str[80];
sprintf(str, self->lo_fd >= 0 ?
"Opened large object, oid %ld" :
"Closed large object, oid %ld", (long) self->lo_oid);
return PyStr_FromString(str);
}
static char large__doc__[] = "PostgreSQL large object";
/* large object type definition */
static PyTypeObject largeType = {
PyVarObject_HEAD_INIT(NULL, 0)
"pg.LargeObject", /* tp_name */
sizeof(largeObject), /* tp_basicsize */
0, /* tp_itemsize */
/* methods */
(destructor) largeDealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_compare */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
(reprfunc) largeStr, /* tp_str */
(getattrofunc) largeGetAttr, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT, /* tp_flags */
large__doc__, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
largeMethods, /* tp_methods */
};
#endif /* LARGE_OBJECTS */
/* --------------------------------------------------------------------- */
/* connection object */
/* --------------------------------------------------------------------- */
static void
connDelete(connObject *self)
{
if (self->cnx)
{
Py_BEGIN_ALLOW_THREADS
PQfinish(self->cnx);
Py_END_ALLOW_THREADS
}
Py_XDECREF(self->cast_hook);
Py_XDECREF(self->notice_receiver);
PyObject_Del(self);
}
/* source creation */
static char connSource__doc__[] =
"source() -- create a new source object for this connection";
static PyObject *
connSource(connObject *self, PyObject *noargs)
{
sourceObject *npgobj;
/* checks validity */
if (!check_cnx_obj(self))
return NULL;
/* allocates new query object */
if (!(npgobj = PyObject_NEW(sourceObject, &sourceType)))
return NULL;
/* initializes internal parameters */
Py_XINCREF(self);
npgobj->pgcnx = self;
npgobj->result = NULL;
npgobj->valid = 1;
npgobj->arraysize = PG_ARRAYSIZE;
return (PyObject *) npgobj;
}
/* database query */
static char connQuery__doc__[] =
"query(sql, [arg]) -- create a new query object for this connection\n\n"
"You must pass the SQL (string) request and you can optionally pass\n"
"a tuple with positional parameters.\n";
static PyObject *
connQuery(connObject *self, PyObject *args)
{
PyObject *query_obj;
PyObject *param_obj = NULL;
char *query;
PGresult *result;
queryObject *npgobj;
int encoding,
status,
nparms = 0;
if (!self->cnx)
{
PyErr_SetString(PyExc_TypeError, "Connection is not valid");
return NULL;
}
/* get query args */
if (!PyArg_ParseTuple(args, "O|O", &query_obj, ¶m_obj))
{
return NULL;
}
encoding = PQclientEncoding(self->cnx);
if (PyBytes_Check(query_obj))
{
query = PyBytes_AsString(query_obj);
query_obj = NULL;
}
else if (PyUnicode_Check(query_obj))
{
query_obj = get_encoded_string(query_obj, encoding);
if (!query_obj) return NULL; /* pass the UnicodeEncodeError */
query = PyBytes_AsString(query_obj);
}
else
{
PyErr_SetString(PyExc_TypeError,
"Method query() expects a string as first argument");
return NULL;
}
/* If param_obj is passed, ensure it's a non-empty tuple. We want to treat
* an empty tuple the same as no argument since we'll get that when the
* caller passes no arguments to db.query(), and historic behaviour was
* to call PQexec() in that case, which can execute multiple commands. */
if (param_obj)
{
param_obj = PySequence_Fast(param_obj,
"Method query() expects a sequence as second argument");
if (!param_obj)
{
Py_XDECREF(query_obj);
return NULL;
}
nparms = (int)PySequence_Fast_GET_SIZE(param_obj);
/* if there's a single argument and it's a list or tuple, it
* contains the positional arguments. */
if (nparms == 1)
{
PyObject *first_obj = PySequence_Fast_GET_ITEM(param_obj, 0);
if (PyList_Check(first_obj) || PyTuple_Check(first_obj))
{
Py_DECREF(param_obj);
param_obj = PySequence_Fast(first_obj, NULL);
nparms = (int)PySequence_Fast_GET_SIZE(param_obj);
}
}
}
/* gets result */
if (nparms)
{
/* prepare arguments */
PyObject **str, **s;
char **parms, **p;
register int i;
str = (PyObject **)PyMem_Malloc(nparms * sizeof(*str));
parms = (char **)PyMem_Malloc(nparms * sizeof(*parms));
if (!str || !parms)
{
PyMem_Free(parms); PyMem_Free(str);
Py_XDECREF(query_obj); Py_XDECREF(param_obj);
return PyErr_NoMemory();
}
/* convert optional args to a list of strings -- this allows
* the caller to pass whatever they like, and prevents us
* from having to map types to OIDs */
for (i = 0, s=str, p=parms; i < nparms; ++i, ++p)
{
PyObject *obj = PySequence_Fast_GET_ITEM(param_obj, i);
if (obj == Py_None)
{
*p = NULL;
}
else if (PyBytes_Check(obj))
{
*p = PyBytes_AsString(obj);
}
else if (PyUnicode_Check(obj))
{
PyObject *str_obj = get_encoded_string(obj, encoding);
if (!str_obj)
{
PyMem_Free(parms);
while (s != str) { s--; Py_DECREF(*s); }
PyMem_Free(str);
Py_XDECREF(query_obj);
Py_XDECREF(param_obj);
/* pass the UnicodeEncodeError */
return NULL;
}
*s++ = str_obj;
*p = PyBytes_AsString(str_obj);
}
else
{
PyObject *str_obj = PyObject_Str(obj);
if (!str_obj)
{
PyMem_Free(parms);
while (s != str) { s--; Py_DECREF(*s); }
PyMem_Free(str);
Py_XDECREF(query_obj);
Py_XDECREF(param_obj);
PyErr_SetString(PyExc_TypeError,
"Query parameter has no string representation");
return NULL;
}
*s++ = str_obj;
*p = PyStr_AsString(str_obj);
}
}
Py_BEGIN_ALLOW_THREADS
result = PQexecParams(self->cnx, query, nparms,
NULL, (const char * const *)parms, NULL, NULL, 0);
Py_END_ALLOW_THREADS
PyMem_Free(parms);
while (s != str) { s--; Py_DECREF(*s); }
PyMem_Free(str);
}
else
{
Py_BEGIN_ALLOW_THREADS
result = PQexec(self->cnx, query);
Py_END_ALLOW_THREADS
}
/* we don't need the query and its params any more */
Py_XDECREF(query_obj);
Py_XDECREF(param_obj);
/* checks result validity */
if (!result)
{
PyErr_SetString(PyExc_ValueError, PQerrorMessage(self->cnx));
return NULL;
}
/* this may have changed the datestyle, so we reset the date format
in order to force fetching it newly when next time requested */
self->date_format = date_format; /* this is normally NULL */
/* checks result status */
if ((status = PQresultStatus(result)) != PGRES_TUPLES_OK)
{
switch (status)
{
case PGRES_EMPTY_QUERY:
PyErr_SetString(PyExc_ValueError, "Empty query");
break;
case PGRES_BAD_RESPONSE:
case PGRES_FATAL_ERROR:
case PGRES_NONFATAL_ERROR:
set_error(ProgrammingError, "Cannot execute query",
self->cnx, result);
break;
case PGRES_COMMAND_OK:
{ /* INSERT, UPDATE, DELETE */
Oid oid = PQoidValue(result);
if (oid == InvalidOid) /* not a single insert */
{
char *ret = PQcmdTuples(result);
PQclear(result);
if (ret[0]) /* return number of rows affected */
{
return PyStr_FromString(ret);
}
Py_INCREF(Py_None);
return Py_None;
}
/* for a single insert, return the oid */
PQclear(result);
return PyInt_FromLong(oid);
}
case PGRES_COPY_OUT: /* no data will be received */
case PGRES_COPY_IN:
PQclear(result);
Py_INCREF(Py_None);
return Py_None;
default:
set_error_msg(InternalError, "Unknown result status");
}
PQclear(result);
return NULL; /* error detected on query */
}
if (!(npgobj = PyObject_NEW(queryObject, &queryType)))
return PyErr_NoMemory();
/* stores result and returns object */
Py_XINCREF(self);
npgobj->pgcnx = self;
npgobj->result = result;
npgobj->encoding = encoding;
return (PyObject *) npgobj;
}
#ifdef DIRECT_ACCESS
static char connPutLine__doc__[] =
"putline(line) -- send a line directly to the backend";
/* direct access function: putline */
static PyObject *
connPutLine(connObject *self, PyObject *args)
{
char *line;
int line_length;
if (!self->cnx)
{
PyErr_SetString(PyExc_TypeError, "Connection is not valid");
return NULL;
}
/* reads args */
if (!PyArg_ParseTuple(args, "s#", &line, &line_length))
{
PyErr_SetString(PyExc_TypeError,
"Method putline() takes a string argument");
return NULL;
}
/* sends line to backend */
if (PQputline(self->cnx, line))
{
PyErr_SetString(PyExc_IOError, PQerrorMessage(self->cnx));
return NULL;
}
Py_INCREF(Py_None);
return Py_None;
}
/* direct access function: getline */
static char connGetLine__doc__[] =
"getline() -- get a line directly from the backend";
static PyObject *
connGetLine(connObject *self, PyObject *noargs)
{
char line[MAX_BUFFER_SIZE];
PyObject *str = NULL; /* GCC */
if (!self->cnx)
{
PyErr_SetString(PyExc_TypeError, "Connection is not valid");
return NULL;
}
/* gets line */
switch (PQgetline(self->cnx, line, MAX_BUFFER_SIZE))
{
case 0:
str = PyStr_FromString(line);
break;
case 1:
PyErr_SetString(PyExc_MemoryError, "Buffer overflow");
str = NULL;
break;
case EOF:
Py_INCREF(Py_None);
str = Py_None;
break;
}
return str;
}
/* direct access function: end copy */
static char connEndCopy__doc__[] =
"endcopy() -- synchronize client and server";
static PyObject *
connEndCopy(connObject *self, PyObject *noargs)
{
if (!self->cnx)
{
PyErr_SetString(PyExc_TypeError, "Connection is not valid");
return NULL;
}
/* ends direct copy */
if (PQendcopy(self->cnx))
{
PyErr_SetString(PyExc_IOError, PQerrorMessage(self->cnx));
return NULL;
}
Py_INCREF(Py_None);
return Py_None;
}
#endif /* DIRECT_ACCESS */
/* return query as string in human readable form */
static PyObject *
queryStr(queryObject *self)
{
return format_result(self->result);
}
/* insert table */
static char connInsertTable__doc__[] =
"inserttable(table, data) -- insert list into table\n\n"
"The fields in the list must be in the same order as in the table.\n";
static PyObject *
connInsertTable(connObject *self, PyObject *args)
{
PGresult *result;
char *table,
*buffer,
*bufpt;
int encoding;
size_t bufsiz;
PyObject *list,
*sublist,
*item;
PyObject *(*getitem) (PyObject *, Py_ssize_t);
PyObject *(*getsubitem) (PyObject *, Py_ssize_t);
Py_ssize_t i,
j,
m,
n;
if (!self->cnx)
{
PyErr_SetString(PyExc_TypeError, "Connection is not valid");
return NULL;
}
/* gets arguments */
if (!PyArg_ParseTuple(args, "sO:filter", &table, &list))
{
PyErr_SetString(PyExc_TypeError,
"Method inserttable() expects a string and a list as arguments");
return NULL;
}
/* checks list type */
if (PyTuple_Check(list))
{
m = PyTuple_Size(list);
getitem = PyTuple_GetItem;
}
else if (PyList_Check(list))
{
m = PyList_Size(list);
getitem = PyList_GetItem;
}
else
{
PyErr_SetString(PyExc_TypeError,
"Method inserttable() expects some kind of array"
" as second argument");
return NULL;
}
/* allocate buffer */
if (!(buffer = PyMem_Malloc(MAX_BUFFER_SIZE)))
return PyErr_NoMemory();
/* starts query */
sprintf(buffer, "copy %s from stdin", table);
Py_BEGIN_ALLOW_THREADS
result = PQexec(self->cnx, buffer);
Py_END_ALLOW_THREADS
if (!result)
{
PyMem_Free(buffer);
PyErr_SetString(PyExc_ValueError, PQerrorMessage(self->cnx));
return NULL;
}
encoding = PQclientEncoding(self->cnx);
PQclear(result);
n = 0; /* not strictly necessary but avoids warning */
/* feed table */
for (i = 0; i < m; ++i)
{
sublist = getitem(list, i);
if (PyTuple_Check(sublist))
{
j = PyTuple_Size(sublist);
getsubitem = PyTuple_GetItem;
}
else if (PyList_Check(sublist))
{
j = PyList_Size(sublist);
getsubitem = PyList_GetItem;
}
else
{
PyErr_SetString(PyExc_TypeError,
"Second arg must contain some kind of arrays");
return NULL;
}
if (i)
{
if (j != n)
{
PyMem_Free(buffer);
PyErr_SetString(PyExc_TypeError,
"Arrays contained in second arg must have same size");
return NULL;
}
}
else
{
n = j; /* never used before this assignment */
}
/* builds insert line */
bufpt = buffer;
bufsiz = MAX_BUFFER_SIZE - 1;
for (j = 0; j < n; ++j)
{
if (j)
{
*bufpt++ = '\t'; --bufsiz;
}
item = getsubitem(sublist, j);
/* convert item to string and append to buffer */
if (item == Py_None)
{
if (bufsiz > 2)
{
*bufpt++ = '\\'; *bufpt++ = 'N';
bufsiz -= 2;
}
else
bufsiz = 0;
}
else if (PyBytes_Check(item))
{
const char* t = PyBytes_AsString(item);
while (*t && bufsiz)
{
if (*t == '\\' || *t == '\t' || *t == '\n')
{
*bufpt++ = '\\'; --bufsiz;
if (!bufsiz) break;
}
*bufpt++ = *t++; --bufsiz;
}
}
else if (PyUnicode_Check(item))
{
PyObject *s = get_encoded_string(item, encoding);
if (!s)
{
PyMem_Free(buffer);
return NULL; /* pass the UnicodeEncodeError */
}
else
{
const char* t = PyBytes_AsString(s);
while (*t && bufsiz)
{
if (*t == '\\' || *t == '\t' || *t == '\n')
{
*bufpt++ = '\\'; --bufsiz;
if (!bufsiz) break;
}
*bufpt++ = *t++; --bufsiz;
}
Py_DECREF(s);
}
}
else if (PyInt_Check(item) || PyLong_Check(item))
{
PyObject* s = PyObject_Str(item);
const char* t = PyStr_AsString(s);
while (*t && bufsiz)
{
*bufpt++ = *t++; --bufsiz;
}
Py_DECREF(s);
}
else
{
PyObject* s = PyObject_Repr(item);
const char* t = PyStr_AsString(s);
while (*t && bufsiz)
{
if (*t == '\\' || *t == '\t' || *t == '\n')
{
*bufpt++ = '\\'; --bufsiz;
if (!bufsiz) break;
}
*bufpt++ = *t++; --bufsiz;
}
Py_DECREF(s);
}
if (bufsiz <= 0)
{
PyMem_Free(buffer); return PyErr_NoMemory();
}
}
*bufpt++ = '\n'; *bufpt = '\0';
/* sends data */
if (PQputline(self->cnx, buffer))
{
PyErr_SetString(PyExc_IOError, PQerrorMessage(self->cnx));
PQendcopy(self->cnx);
PyMem_Free(buffer);
return NULL;
}
}
/* ends query */
if (PQputline(self->cnx, "\\.\n"))
{
PyErr_SetString(PyExc_IOError, PQerrorMessage(self->cnx));
PQendcopy(self->cnx);
PyMem_Free(buffer);
return NULL;
}
if (PQendcopy(self->cnx))
{
PyErr_SetString(PyExc_IOError, PQerrorMessage(self->cnx));
PyMem_Free(buffer);
return NULL;
}
PyMem_Free(buffer);
/* no error : returns nothing */
Py_INCREF(Py_None);
return Py_None;
}
/* get transaction state */
static char connTransaction__doc__[] =
"transaction() -- return the current transaction status";
static PyObject *
connTransaction(connObject *self, PyObject *noargs)
{
if (!self->cnx)
{
PyErr_SetString(PyExc_TypeError, "Connection is not valid");
return NULL;
}
return PyInt_FromLong(PQtransactionStatus(self->cnx));
}
/* get parameter setting */
static char connParameter__doc__[] =
"parameter(name) -- look up a current parameter setting";
static PyObject *
connParameter(connObject *self, PyObject *args)
{
const char *name;
if (!self->cnx)
{
PyErr_SetString(PyExc_TypeError, "Connection is not valid");
return NULL;
}
/* get query args */
if (!PyArg_ParseTuple(args, "s", &name))
{
PyErr_SetString(PyExc_TypeError,
"Method parameter() takes a string as argument");
return NULL;
}
name = PQparameterStatus(self->cnx, name);
if (name)
return PyStr_FromString(name);
/* unknown parameter, return None */
Py_INCREF(Py_None);
return Py_None;
}
/* internal function converting a Postgres datestyles to date formats */
static const char *
date_style_to_format(const char *s)
{
static const char *formats[] = {
"%Y-%m-%d", /* 0 = ISO */
"%m-%d-%Y", /* 1 = Postgres, MDY */
"%d-%m-%Y", /* 2 = Postgres, DMY */
"%m/%d/%Y", /* 3 = SQL, MDY */
"%d/%m/%Y", /* 4 = SQL, DMY */
"%d.%m.%Y"}; /* 5 = German */
switch (s ? *s : 'I')
{
case 'P': /* Postgres */
s = strchr(s + 1, ',');
if (s) do ++s; while (*s && *s == ' ');
return formats[s && *s == 'D' ? 2 : 1];
case 'S': /* SQL */
s = strchr(s + 1, ',');
if (s) do ++s; while (*s && *s == ' ');
return formats[s && *s == 'D' ? 4 : 3];
case 'G': /* German */
return formats[5];
default: /* ISO */
return formats[0]; /* ISO is the default */
}
}
/* internal function converting a date format to a Postgres datestyle */
static const char *
date_format_to_style(const char *s)
{
static const char *datestyle[] = {
"ISO, YMD", /* 0 = %Y-%m-%d */
"Postgres, MDY", /* 1 = %m-%d-%Y */
"Postgres, DMY", /* 2 = %d-%m-%Y */
"SQL, MDY", /* 3 = %m/%d/%Y */
"SQL, DMY", /* 4 = %d/%m/%Y */
"German, DMY"}; /* 5 = %d.%m.%Y */
switch (s ? s[1] : 'Y')
{
case 'm':
switch (s[2])
{
case '/':
return datestyle[3]; /* SQL, MDY */
default:
return datestyle[1]; /* Postgres, MDY */
}
case 'd':
switch (s[2])
{
case '/':
return datestyle[4]; /* SQL, DMY */
case '.':
return datestyle[5]; /* German */
default:
return datestyle[2]; /* Postgres, DMY */
}
default:
return datestyle[0]; /* ISO */
}
}
/* get current date format */
static char connDateFormat__doc__[] =
"date_format() -- return the current date format";
static PyObject *
connDateFormat(connObject *self, PyObject *noargs)
{
const char *fmt;
if (!self->cnx)
{
PyErr_SetString(PyExc_TypeError, "Connection is not valid");
return NULL;
}
/* check if the date format is cached in the connection */
fmt = self->date_format;
if (!fmt)
{
fmt = date_style_to_format(PQparameterStatus(self->cnx, "DateStyle"));
self->date_format = fmt; /* cache the result */
}
return PyStr_FromString(fmt);
}
#ifdef ESCAPING_FUNCS
/* escape literal */
static char connEscapeLiteral__doc__[] =
"escape_literal(str) -- escape a literal constant for use within SQL";
static PyObject *
connEscapeLiteral(connObject *self, PyObject *string)
{
PyObject *tmp_obj = NULL, /* auxiliary string object */
*to_obj; /* string object to return */
char *from, /* our string argument as encoded string */
*to; /* the result as encoded string */
Py_ssize_t from_length; /* length of string */
size_t to_length; /* length of result */
int encoding = -1; /* client encoding */
if (PyBytes_Check(string))
{
PyBytes_AsStringAndSize(string, &from, &from_length);
}
else if (PyUnicode_Check(string))
{
encoding = PQclientEncoding(self->cnx);
tmp_obj = get_encoded_string(string, encoding);
if (!tmp_obj) return NULL; /* pass the UnicodeEncodeError */
PyBytes_AsStringAndSize(tmp_obj, &from, &from_length);
}
else
{
PyErr_SetString(PyExc_TypeError,
"Method escape_literal() expects a string as argument");
return NULL;
}
to = PQescapeLiteral(self->cnx, from, (size_t)from_length);
to_length = strlen(to);
Py_XDECREF(tmp_obj);
if (encoding == -1)
to_obj = PyBytes_FromStringAndSize(to, to_length);
else
to_obj = get_decoded_string(to, to_length, encoding);
if (to)
PQfreemem(to);
return to_obj;
}
/* escape identifier */
static char connEscapeIdentifier__doc__[] =
"escape_identifier(str) -- escape an identifier for use within SQL";
static PyObject *
connEscapeIdentifier(connObject *self, PyObject *string)
{
PyObject *tmp_obj = NULL, /* auxiliary string object */
*to_obj; /* string object to return */
char *from, /* our string argument as encoded string */
*to; /* the result as encoded string */
Py_ssize_t from_length; /* length of string */
size_t to_length; /* length of result */
int encoding = -1; /* client encoding */
if (PyBytes_Check(string))
{
PyBytes_AsStringAndSize(string, &from, &from_length);
}
else if (PyUnicode_Check(string))
{
encoding = PQclientEncoding(self->cnx);
tmp_obj = get_encoded_string(string, encoding);
if (!tmp_obj) return NULL; /* pass the UnicodeEncodeError */
PyBytes_AsStringAndSize(tmp_obj, &from, &from_length);
}
else
{
PyErr_SetString(PyExc_TypeError,
"Method escape_identifier() expects a string as argument");
return NULL;
}
to = PQescapeIdentifier(self->cnx, from, (size_t)from_length);
to_length = strlen(to);
Py_XDECREF(tmp_obj);
if (encoding == -1)
to_obj = PyBytes_FromStringAndSize(to, to_length);
else
to_obj = get_decoded_string(to, to_length, encoding);
if (to)
PQfreemem(to);
return to_obj;
}
#endif /* ESCAPING_FUNCS */
/* escape string */
static char connEscapeString__doc__[] =
"escape_string(str) -- escape a string for use within SQL";
static PyObject *
connEscapeString(connObject *self, PyObject *string)
{
PyObject *tmp_obj = NULL, /* auxiliary string object */
*to_obj; /* string object to return */
char *from, /* our string argument as encoded string */
*to; /* the result as encoded string */
Py_ssize_t from_length; /* length of string */
size_t to_length; /* length of result */
int encoding = -1; /* client encoding */
if (PyBytes_Check(string))
{
PyBytes_AsStringAndSize(string, &from, &from_length);
}
else if (PyUnicode_Check(string))
{
encoding = PQclientEncoding(self->cnx);
tmp_obj = get_encoded_string(string, encoding);
if (!tmp_obj) return NULL; /* pass the UnicodeEncodeError */
PyBytes_AsStringAndSize(tmp_obj, &from, &from_length);
}
else
{
PyErr_SetString(PyExc_TypeError,
"Method escape_string() expects a string as argument");
return NULL;
}
to_length = 2*from_length + 1;
if ((Py_ssize_t)to_length < from_length) /* overflow */
{
to_length = from_length;
from_length = (from_length - 1)/2;
}
to = (char *)PyMem_Malloc(to_length);
to_length = PQescapeStringConn(self->cnx,
to, from, (size_t)from_length, NULL);
Py_XDECREF(tmp_obj);
if (encoding == -1)
to_obj = PyBytes_FromStringAndSize(to, to_length);
else
to_obj = get_decoded_string(to, to_length, encoding);
PyMem_Free(to);
return to_obj;
}
/* escape bytea */
static char connEscapeBytea__doc__[] =
"escape_bytea(data) -- escape binary data for use within SQL as type bytea";
static PyObject *
connEscapeBytea(connObject *self, PyObject *data)
{
PyObject *tmp_obj = NULL, /* auxiliary string object */
*to_obj; /* string object to return */
char *from, /* our string argument as encoded string */
*to; /* the result as encoded string */
Py_ssize_t from_length; /* length of string */
size_t to_length; /* length of result */
int encoding = -1; /* client encoding */
if (PyBytes_Check(data))
{
PyBytes_AsStringAndSize(data, &from, &from_length);
}
else if (PyUnicode_Check(data))
{
encoding = PQclientEncoding(self->cnx);
tmp_obj = get_encoded_string(data, encoding);
if (!tmp_obj) return NULL; /* pass the UnicodeEncodeError */
PyBytes_AsStringAndSize(tmp_obj, &from, &from_length);
}
else
{
PyErr_SetString(PyExc_TypeError,
"Method escape_bytea() expects a string as argument");
return NULL;
}
to = (char *)PQescapeByteaConn(self->cnx,
(unsigned char *)from, (size_t)from_length, &to_length);
Py_XDECREF(tmp_obj);
if (encoding == -1)
to_obj = PyBytes_FromStringAndSize(to, to_length - 1);
else
to_obj = get_decoded_string(to, to_length - 1, encoding);
if (to)
PQfreemem(to);
return to_obj;
}
#ifdef LARGE_OBJECTS
/* creates large object */
static char connCreateLO__doc__[] =
"locreate(mode) -- create a new large object in the database";
static PyObject *
connCreateLO(connObject *self, PyObject *args)
{
int mode;
Oid lo_oid;
/* checks validity */
if (!check_cnx_obj(self))
return NULL;
/* gets arguments */
if (!PyArg_ParseTuple(args, "i", &mode))
{
PyErr_SetString(PyExc_TypeError,
"Method locreate() takes an integer argument");
return NULL;
}
/* creates large object */
lo_oid = lo_creat(self->cnx, mode);
if (lo_oid == 0)
{
set_error_msg(OperationalError, "Can't create large object");
return NULL;
}
return (PyObject *) largeNew(self, lo_oid);
}
/* init from already known oid */
static char connGetLO__doc__[] =
"getlo(oid) -- create a large object instance for the specified oid";
static PyObject *
connGetLO(connObject *self, PyObject *args)
{
int lo_oid;
/* checks validity */
if (!check_cnx_obj(self))
return NULL;
/* gets arguments */
if (!PyArg_ParseTuple(args, "i", &lo_oid))
{
PyErr_SetString(PyExc_TypeError,
"Method getlo() takes an integer argument");
return NULL;
}
if (!lo_oid)
{
PyErr_SetString(PyExc_ValueError, "The object oid can't be null");
return NULL;
}
/* creates object */
return (PyObject *) largeNew(self, lo_oid);
}
/* import unix file */
static char connImportLO__doc__[] =
"loimport(name) -- create a new large object from specified file";
static PyObject *
connImportLO(connObject *self, PyObject *args)
{
char *name;
Oid lo_oid;
/* checks validity */
if (!check_cnx_obj(self))
return NULL;
/* gets arguments */
if (!PyArg_ParseTuple(args, "s", &name))
{
PyErr_SetString(PyExc_TypeError,
"Method loimport() takes a string argument");
return NULL;
}
/* imports file and checks result */
lo_oid = lo_import(self->cnx, name);
if (lo_oid == 0)
{
set_error_msg(OperationalError, "Can't create large object");
return NULL;
}
return (PyObject *) largeNew(self, lo_oid);
}
#endif /* LARGE_OBJECTS */
/* resets connection */
static char connReset__doc__[] =
"reset() -- reset connection with current parameters\n\n"
"All derived queries and large objects derived from this connection\n"
"will not be usable after this call.\n";
static PyObject *
connReset(connObject *self, PyObject *noargs)
{
if (!self->cnx)
{
PyErr_SetString(PyExc_TypeError, "Connection is not valid");
return NULL;
}
/* resets the connection */
PQreset(self->cnx);
Py_INCREF(Py_None);
return Py_None;
}
/* cancels current command */
static char connCancel__doc__[] =
"cancel() -- abandon processing of the current command";
static PyObject *
connCancel(connObject *self, PyObject *noargs)
{
if (!self->cnx)
{
PyErr_SetString(PyExc_TypeError, "Connection is not valid");
return NULL;
}
/* request that the server abandon processing of the current command */
return PyInt_FromLong((long) PQrequestCancel(self->cnx));
}
/* get connection socket */
static char connFileno__doc__[] =
"fileno() -- return database connection socket file handle";
static PyObject *
connFileno(connObject *self, PyObject *noargs)
{
if (!self->cnx)
{
PyErr_SetString(PyExc_TypeError, "Connection is not valid");
return NULL;
}
#ifdef NO_PQSOCKET
return PyInt_FromLong((long) self->cnx->sock);
#else
return PyInt_FromLong((long) PQsocket(self->cnx));
#endif
}
/* set external typecast callback function */
static char connSetCastHook__doc__[] =
"set_cast_hook(func) -- set a fallback typecast function";
static PyObject *
connSetCastHook(connObject *self, PyObject *func)
{
PyObject *ret = NULL;
if (func == Py_None)
{
Py_XDECREF(self->cast_hook);
self->cast_hook = NULL;
Py_INCREF(Py_None); ret = Py_None;
}
else if (PyCallable_Check(func))
{
Py_XINCREF(func); Py_XDECREF(self->cast_hook);
self->cast_hook = func;
Py_INCREF(Py_None); ret = Py_None;
}
else
PyErr_SetString(PyExc_TypeError,
"Method set_cast_hook() expects"
" a callable or None as argument");
return ret;
}
/* get notice receiver callback function */
static char connGetCastHook__doc__[] =
"get_cast_hook() -- get the fallback typecast function";
static PyObject *
connGetCastHook(connObject *self, PyObject *noargs)
{
PyObject *ret = self->cast_hook;;
if (!ret)
ret = Py_None;
Py_INCREF(ret);
return ret;
}
/* set notice receiver callback function */
static char connSetNoticeReceiver__doc__[] =
"set_notice_receiver(func) -- set the current notice receiver";
static PyObject *
connSetNoticeReceiver(connObject *self, PyObject *func)
{
PyObject *ret = NULL;
if (func == Py_None)
{
Py_XDECREF(self->notice_receiver);
self->notice_receiver = NULL;
Py_INCREF(Py_None); ret = Py_None;
}
else if (PyCallable_Check(func))
{
Py_XINCREF(func); Py_XDECREF(self->notice_receiver);
self->notice_receiver = func;
PQsetNoticeReceiver(self->cnx, notice_receiver, self);
Py_INCREF(Py_None); ret = Py_None;
}
else
PyErr_SetString(PyExc_TypeError,
"Method set_notice_receiver() expects"
" a callable or None as argument");
return ret;
}
/* get notice receiver callback function */
static char connGetNoticeReceiver__doc__[] =
"get_notice_receiver() -- get the current notice receiver";
static PyObject *
connGetNoticeReceiver(connObject *self, PyObject *noargs)
{
PyObject *ret = self->notice_receiver;
if (!ret)
ret = Py_None;
Py_INCREF(ret);
return ret;
}
/* close without deleting */
static char connClose__doc__[] =
"close() -- close connection\n\n"
"All instances of the connection object and derived objects\n"
"(queries and large objects) can no longer be used after this call.\n";
static PyObject *
connClose(connObject *self, PyObject *noargs)
{
/* connection object cannot already be closed */
if (!self->cnx)
{
set_error_msg(InternalError, "Connection already closed");
return NULL;
}
Py_BEGIN_ALLOW_THREADS
PQfinish(self->cnx);
Py_END_ALLOW_THREADS
self->cnx = NULL;
Py_INCREF(Py_None);
return Py_None;
}
/* gets asynchronous notify */
static char connGetNotify__doc__[] =
"getnotify() -- get database notify for this connection";
static PyObject *
connGetNotify(connObject *self, PyObject *noargs)
{
PGnotify *notify;
if (!self->cnx)
{
PyErr_SetString(PyExc_TypeError, "Connection is not valid");
return NULL;
}
/* checks for NOTIFY messages */
PQconsumeInput(self->cnx);
if (!(notify = PQnotifies(self->cnx)))
{
Py_INCREF(Py_None);
return Py_None;
}
else
{
PyObject *notify_result,
*temp;
if (!(temp = PyStr_FromString(notify->relname)))
return NULL;
if (!(notify_result = PyTuple_New(3)))
return NULL;
PyTuple_SET_ITEM(notify_result, 0, temp);
if (!(temp = PyInt_FromLong(notify->be_pid)))
{
Py_DECREF(notify_result);
return NULL;
}
PyTuple_SET_ITEM(notify_result, 1, temp);
/* extra exists even in old versions that did not support it */
if (!(temp = PyStr_FromString(notify->extra)))
{
Py_DECREF(notify_result);
return NULL;
}
PyTuple_SET_ITEM(notify_result, 2, temp);
PQfreemem(notify);
return notify_result;
}
}
/* get the list of connection attributes */
static PyObject *
connDir(connObject *self, PyObject *noargs)
{
PyObject *attrs;
attrs = PyObject_Dir(PyObject_Type((PyObject *)self));
PyObject_CallMethod(attrs, "extend", "[sssssssss]",
"host", "port", "db", "options", "error", "status", "user",
"protocol_version", "server_version");
return attrs;
}
/* connection object methods */
static struct PyMethodDef connMethods[] = {
{"__dir__", (PyCFunction) connDir, METH_NOARGS, NULL},
{"source", (PyCFunction) connSource, METH_NOARGS, connSource__doc__},
{"query", (PyCFunction) connQuery, METH_VARARGS, connQuery__doc__},
{"reset", (PyCFunction) connReset, METH_NOARGS, connReset__doc__},
{"cancel", (PyCFunction) connCancel, METH_NOARGS, connCancel__doc__},
{"close", (PyCFunction) connClose, METH_NOARGS, connClose__doc__},
{"fileno", (PyCFunction) connFileno, METH_NOARGS, connFileno__doc__},
{"get_cast_hook", (PyCFunction) connGetCastHook, METH_NOARGS,
connGetCastHook__doc__},
{"set_cast_hook", (PyCFunction) connSetCastHook, METH_O,
connSetCastHook__doc__},
{"get_notice_receiver", (PyCFunction) connGetNoticeReceiver, METH_NOARGS,
connGetNoticeReceiver__doc__},
{"set_notice_receiver", (PyCFunction) connSetNoticeReceiver, METH_O,
connSetNoticeReceiver__doc__},
{"getnotify", (PyCFunction) connGetNotify, METH_NOARGS,
connGetNotify__doc__},
{"inserttable", (PyCFunction) connInsertTable, METH_VARARGS,
connInsertTable__doc__},
{"transaction", (PyCFunction) connTransaction, METH_NOARGS,
connTransaction__doc__},
{"parameter", (PyCFunction) connParameter, METH_VARARGS,
connParameter__doc__},
{"date_format", (PyCFunction) connDateFormat, METH_NOARGS,
connDateFormat__doc__},
#ifdef ESCAPING_FUNCS
{"escape_literal", (PyCFunction) connEscapeLiteral, METH_O,
connEscapeLiteral__doc__},
{"escape_identifier", (PyCFunction) connEscapeIdentifier, METH_O,
connEscapeIdentifier__doc__},
#endif /* ESCAPING_FUNCS */
{"escape_string", (PyCFunction) connEscapeString, METH_O,
connEscapeString__doc__},
{"escape_bytea", (PyCFunction) connEscapeBytea, METH_O,
connEscapeBytea__doc__},
#ifdef DIRECT_ACCESS
{"putline", (PyCFunction) connPutLine, METH_VARARGS, connPutLine__doc__},
{"getline", (PyCFunction) connGetLine, METH_NOARGS, connGetLine__doc__},
{"endcopy", (PyCFunction) connEndCopy, METH_NOARGS, connEndCopy__doc__},
#endif /* DIRECT_ACCESS */
#ifdef LARGE_OBJECTS
{"locreate", (PyCFunction) connCreateLO, METH_VARARGS, connCreateLO__doc__},
{"getlo", (PyCFunction) connGetLO, METH_VARARGS, connGetLO__doc__},
{"loimport", (PyCFunction) connImportLO, METH_VARARGS, connImportLO__doc__},
#endif /* LARGE_OBJECTS */
{NULL, NULL} /* sentinel */
};
/* gets connection attributes */
static PyObject *
connGetAttr(connObject *self, PyObject *nameobj)
{
const char *name = PyStr_AsString(nameobj);
/*
* Although we could check individually, there are only a few
* attributes that don't require a live connection and unless someone
* has an urgent need, this will have to do
*/
/* first exception - close which returns a different error */
if (strcmp(name, "close") && !self->cnx)
{
PyErr_SetString(PyExc_TypeError, "Connection is not valid");
return NULL;
}
/* list PostgreSQL connection fields */
/* postmaster host */
if (!strcmp(name, "host"))
{
char *r = PQhost(self->cnx);
if (!r)
r = "localhost";
return PyStr_FromString(r);
}
/* postmaster port */
if (!strcmp(name, "port"))
return PyInt_FromLong(atol(PQport(self->cnx)));
/* selected database */
if (!strcmp(name, "db"))
return PyStr_FromString(PQdb(self->cnx));
/* selected options */
if (!strcmp(name, "options"))
return PyStr_FromString(PQoptions(self->cnx));
/* error (status) message */
if (!strcmp(name, "error"))
return PyStr_FromString(PQerrorMessage(self->cnx));
/* connection status : 1 - OK, 0 - BAD */
if (!strcmp(name, "status"))
return PyInt_FromLong(PQstatus(self->cnx) == CONNECTION_OK ? 1 : 0);
/* provided user name */
if (!strcmp(name, "user"))
return PyStr_FromString(PQuser(self->cnx));
/* protocol version */
if (!strcmp(name, "protocol_version"))
return PyInt_FromLong(PQprotocolVersion(self->cnx));
/* backend version */
if (!strcmp(name, "server_version"))
return PyInt_FromLong(PQserverVersion(self->cnx));
return PyObject_GenericGetAttr((PyObject *) self, nameobj);
}
/* connection type definition */
static PyTypeObject connType = {
PyVarObject_HEAD_INIT(NULL, 0)
"pg.Connection", /* tp_name */
sizeof(connObject), /* tp_basicsize */
0, /* tp_itemsize */
(destructor) connDelete, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_reserved */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
(getattrofunc) connGetAttr, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT, /* tp_flags */
0, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
connMethods, /* tp_methods */
};
/* --------------------------------------------------------------------- */
/* source object */
/* --------------------------------------------------------------------- */
/* checks source object validity */
static int
check_source_obj(sourceObject *self, int level)
{
if (!self->valid)
{
set_error_msg(OperationalError, "Object has been closed");
return 0;
}
if ((level & CHECK_RESULT) && !self->result)
{
set_error_msg(DatabaseError, "No result");
return 0;
}
if ((level & CHECK_DQL) && self->result_type != RESULT_DQL)
{
set_error_msg(DatabaseError, "Last query did not return tuples");
return 0;
}
if ((level & CHECK_CNX) && !check_cnx_obj(self->pgcnx))
return 0;
return 1;
}
/* destructor */
static void
sourceDealloc(sourceObject *self)
{
if (self->result)
PQclear(self->result);
Py_XDECREF(self->pgcnx);
PyObject_Del(self);
}
/* closes object */
static char sourceClose__doc__[] =
"close() -- close query object without deleting it\n\n"
"All instances of the query object can no longer be used after this call.\n";
static PyObject *
sourceClose(sourceObject *self, PyObject *noargs)
{
/* frees result if necessary and invalidates object */
if (self->result)
{
PQclear(self->result);
self->result_type = RESULT_EMPTY;
self->result = NULL;
}
self->valid = 0;
/* return None */
Py_INCREF(Py_None);
return Py_None;
}
/* database query */
static char sourceExecute__doc__[] =
"execute(sql) -- execute a SQL statement (string)\n\n"
"On success, this call returns the number of affected rows, or None\n"
"for DQL (SELECT, ...) statements. The fetch (fetch(), fetchone()\n"
"and fetchall()) methods can be used to get result rows.\n";
static PyObject *
sourceExecute(sourceObject *self, PyObject *sql)
{
PyObject *tmp_obj = NULL; /* auxiliary string object */
char *query;
int encoding;
/* checks validity */
if (!check_source_obj(self, CHECK_CNX))
return NULL;
encoding = PQclientEncoding(self->pgcnx->cnx);
if (PyBytes_Check(sql))
{
query = PyBytes_AsString(sql);
}
else if (PyUnicode_Check(sql))
{
tmp_obj = get_encoded_string(sql, encoding);
if (!tmp_obj) return NULL; /* pass the UnicodeEncodeError */
query = PyBytes_AsString(tmp_obj);
}
else
{
PyErr_SetString(PyExc_TypeError,
"Method execute() expects a string as argument");
return NULL;
}
/* frees previous result */
if (self->result)
{
PQclear(self->result);
self->result = NULL;
}
self->max_row = 0;
self->current_row = 0;
self->num_fields = 0;
self->encoding = encoding;
/* gets result */
Py_BEGIN_ALLOW_THREADS
self->result = PQexec(self->pgcnx->cnx, query);
Py_END_ALLOW_THREADS
/* we don't need the auxiliary string any more */
Py_XDECREF(tmp_obj);
/* checks result validity */
if (!self->result)
{
PyErr_SetString(PyExc_ValueError, PQerrorMessage(self->pgcnx->cnx));
return NULL;
}
/* this may have changed the datestyle, so we reset the date format
in order to force fetching it newly when next time requested */
self->pgcnx->date_format = date_format; /* this is normally NULL */
/* checks result status */
switch (PQresultStatus(self->result))
{
long num_rows;
char *temp;
/* query succeeded */
case PGRES_TUPLES_OK: /* DQL: returns None (DB-SIG compliant) */
self->result_type = RESULT_DQL;
self->max_row = PQntuples(self->result);
self->num_fields = PQnfields(self->result);
Py_INCREF(Py_None);
return Py_None;
case PGRES_COMMAND_OK: /* other requests */
case PGRES_COPY_OUT:
case PGRES_COPY_IN:
self->result_type = RESULT_DDL;
temp = PQcmdTuples(self->result);
num_rows = -1;
if (temp[0])
{
self->result_type = RESULT_DML;
num_rows = atol(temp);
}
return PyInt_FromLong(num_rows);
/* query failed */
case PGRES_EMPTY_QUERY:
PyErr_SetString(PyExc_ValueError, "Empty query");
break;
case PGRES_BAD_RESPONSE:
case PGRES_FATAL_ERROR:
case PGRES_NONFATAL_ERROR:
set_error(ProgrammingError, "Cannot execute command",
self->pgcnx->cnx, self->result);
break;
default:
set_error_msg(InternalError, "Internal error: "
"unknown result status");
}
/* frees result and returns error */
PQclear(self->result);
self->result = NULL;
self->result_type = RESULT_EMPTY;
return NULL;
}
/* gets oid status for last query (valid for INSERTs, 0 for other) */
static char sourceStatusOID__doc__[] =
"oidstatus() -- return oid of last inserted row (if available)";
static PyObject *
sourceStatusOID(sourceObject *self, PyObject *noargs)
{
Oid oid;
/* checks validity */
if (!check_source_obj(self, CHECK_RESULT))
return NULL;
/* retrieves oid status */
if ((oid = PQoidValue(self->result)) == InvalidOid)
{
Py_INCREF(Py_None);
return Py_None;
}
return PyInt_FromLong(oid);
}
/* fetches rows from last result */
static char sourceFetch__doc__[] =
"fetch(num) -- return the next num rows from the last result in a list\n\n"
"If num parameter is omitted arraysize attribute value is used.\n"
"If size equals -1, all rows are fetched.\n";
static PyObject *
sourceFetch(sourceObject *self, PyObject *args)
{
PyObject *reslist;
int i,
k;
long size;
#if IS_PY3
int encoding;
#endif
/* checks validity */
if (!check_source_obj(self, CHECK_RESULT | CHECK_DQL | CHECK_CNX))
return NULL;
/* checks args */
size = self->arraysize;
if (!PyArg_ParseTuple(args, "|l", &size))
{
PyErr_SetString(PyExc_TypeError,
"fetch(num), with num (integer, optional)");
return NULL;
}
/* seeks last line */
/* limit size to be within the amount of data we actually have */
if (size == -1 || (self->max_row - self->current_row) < size)
size = self->max_row - self->current_row;
/* allocate list for result */
if (!(reslist = PyList_New(0))) return NULL;
#if IS_PY3
encoding = self->encoding;
#endif
/* builds result */
for (i = 0, k = self->current_row; i < size; ++i, ++k)
{
PyObject *rowtuple;
int j;
if (!(rowtuple = PyTuple_New(self->num_fields)))
{
Py_DECREF(reslist); return NULL;
}
for (j = 0; j < self->num_fields; ++j)
{
PyObject *str;
if (PQgetisnull(self->result, k, j))
{
Py_INCREF(Py_None);
str = Py_None;
}
else
{
char *s = PQgetvalue(self->result, k, j);
Py_ssize_t size = PQgetlength(self->result, k, j);
#if IS_PY3
if (PQfformat(self->result, j) == 0) /* textual format */
{
str = get_decoded_string(s, size, encoding);
if (!str) /* cannot decode */
str = PyBytes_FromStringAndSize(s, size);
}
else
#endif
str = PyBytes_FromStringAndSize(s, size);
}
PyTuple_SET_ITEM(rowtuple, j, str);
}
if (PyList_Append(reslist, rowtuple))
{
Py_DECREF(rowtuple); Py_DECREF(reslist); return NULL;
}
Py_DECREF(rowtuple);
}
self->current_row = k;
return reslist;
}
/* changes current row (internal wrapper for all "move" methods) */
static PyObject *
pgsource_move(sourceObject *self, int move)
{
/* checks validity */
if (!check_source_obj(self, CHECK_RESULT | CHECK_DQL))
return NULL;
/* changes the current row */
switch (move)
{
case QUERY_MOVEFIRST:
self->current_row = 0;
break;
case QUERY_MOVELAST:
self->current_row = self->max_row - 1;
break;
case QUERY_MOVENEXT:
if (self->current_row != self->max_row)
++self->current_row;
break;
case QUERY_MOVEPREV:
if (self->current_row > 0)
self->current_row--;
break;
}
Py_INCREF(Py_None);
return Py_None;
}
/* move to first result row */
static char sourceMoveFirst__doc__[] =
"movefirst() -- move to first result row";
static PyObject *
sourceMoveFirst(sourceObject *self, PyObject *noargs)
{
return pgsource_move(self, QUERY_MOVEFIRST);
}
/* move to last result row */
static char sourceMoveLast__doc__[] =
"movelast() -- move to last valid result row";
static PyObject *
sourceMoveLast(sourceObject *self, PyObject *noargs)
{
return pgsource_move(self, QUERY_MOVELAST);
}
/* move to next result row */
static char sourceMoveNext__doc__[] =
"movenext() -- move to next result row";
static PyObject *
sourceMoveNext(sourceObject *self, PyObject *noargs)
{
return pgsource_move(self, QUERY_MOVENEXT);
}
/* move to previous result row */
static char sourceMovePrev__doc__[] =
"moveprev() -- move to previous result row";
static PyObject *
sourceMovePrev(sourceObject *self, PyObject *noargs)
{
return pgsource_move(self, QUERY_MOVEPREV);
}
/* put copy data */
static char sourcePutData__doc__[] =
"putdata(buffer) -- send data to server during copy from stdin";
static PyObject *
sourcePutData(sourceObject *self, PyObject *buffer)
{
PyObject *tmp_obj = NULL; /* an auxiliary object */
char *buf; /* the buffer as encoded string */
Py_ssize_t nbytes; /* length of string */
char *errormsg = NULL; /* error message */
int res; /* direct result of the operation */
PyObject *ret; /* return value */
/* checks validity */
if (!check_source_obj(self, CHECK_CNX))
return NULL;
/* make sure that the connection object is valid */
if (!self->pgcnx->cnx)
return NULL;
if (buffer == Py_None)
{
/* pass None for terminating the operation */
buf = errormsg = NULL;
}
else if (PyBytes_Check(buffer))
{
/* or pass a byte string */
PyBytes_AsStringAndSize(buffer, &buf, &nbytes);
}
else if (PyUnicode_Check(buffer))
{
/* or pass a unicode string */
tmp_obj = get_encoded_string(
buffer, PQclientEncoding(self->pgcnx->cnx));
if (!tmp_obj) return NULL; /* pass the UnicodeEncodeError */
PyBytes_AsStringAndSize(tmp_obj, &buf, &nbytes);
}
else if (PyErr_GivenExceptionMatches(buffer, PyExc_BaseException))
{
/* or pass a Python exception for sending an error message */
tmp_obj = PyObject_Str(buffer);
if (PyUnicode_Check(tmp_obj))
{
PyObject *obj = tmp_obj;
tmp_obj = get_encoded_string(
obj, PQclientEncoding(self->pgcnx->cnx));
Py_DECREF(obj);
if (!tmp_obj) return NULL; /* pass the UnicodeEncodeError */
}
errormsg = PyBytes_AsString(tmp_obj);
buf = NULL;
}
else
{
PyErr_SetString(PyExc_TypeError,
"Method putdata() expects a buffer, None"
" or an exception as argument");
return NULL;
}
/* checks validity */
if (!check_source_obj(self, CHECK_CNX | CHECK_RESULT) ||
PQresultStatus(self->result) != PGRES_COPY_IN)
{
PyErr_SetString(PyExc_IOError,
"Connection is invalid or not in copy_in state");
Py_XDECREF(tmp_obj);
return NULL;
}
if (buf)
{
res = nbytes ? PQputCopyData(self->pgcnx->cnx, buf, (int)nbytes) : 1;
}
else
{
res = PQputCopyEnd(self->pgcnx->cnx, errormsg);
}
Py_XDECREF(tmp_obj);
if (res != 1)
{
PyErr_SetString(PyExc_IOError, PQerrorMessage(self->pgcnx->cnx));
return NULL;
}
if (buf) /* buffer has been sent */
{
ret = Py_None;
Py_INCREF(ret);
}
else /* copy is done */
{
PGresult *result; /* final result of the operation */
Py_BEGIN_ALLOW_THREADS;
result = PQgetResult(self->pgcnx->cnx);
Py_END_ALLOW_THREADS;
if (PQresultStatus(result) == PGRES_COMMAND_OK)
{
char *temp;
long num_rows;
temp = PQcmdTuples(result);
num_rows = temp[0] ? atol(temp) : -1;
ret = PyInt_FromLong(num_rows);
}
else
{
if (!errormsg) errormsg = PQerrorMessage(self->pgcnx->cnx);
PyErr_SetString(PyExc_IOError, errormsg);
ret = NULL;
}
PQclear(self->result);
self->result = NULL;
self->result_type = RESULT_EMPTY;
}
return ret; /* None or number of rows */
}
/* get copy data */
static char sourceGetData__doc__[] =
"getdata(decode) -- receive data to server during copy to stdout";
static PyObject *
sourceGetData(sourceObject *self, PyObject *args)
{
int *decode = 0; /* decode flag */
char *buffer; /* the copied buffer as encoded byte string */
Py_ssize_t nbytes; /* length of the byte string */
PyObject *ret; /* return value */
/* checks validity */
if (!check_source_obj(self, CHECK_CNX))
return NULL;
/* make sure that the connection object is valid */
if (!self->pgcnx->cnx)
return NULL;
if (!PyArg_ParseTuple(args, "|i", &decode))
return NULL;
/* checks validity */
if (!check_source_obj(self, CHECK_CNX | CHECK_RESULT) ||
PQresultStatus(self->result) != PGRES_COPY_OUT)
{
PyErr_SetString(PyExc_IOError,
"Connection is invalid or not in copy_out state");
return NULL;
}
nbytes = PQgetCopyData(self->pgcnx->cnx, &buffer, 0);
if (!nbytes || nbytes < -1) /* an error occurred */
{
PyErr_SetString(PyExc_IOError, PQerrorMessage(self->pgcnx->cnx));
return NULL;
}
if (nbytes == -1) /* copy is done */
{
PGresult *result; /* final result of the operation */
Py_BEGIN_ALLOW_THREADS;
result = PQgetResult(self->pgcnx->cnx);
Py_END_ALLOW_THREADS;
if (PQresultStatus(result) == PGRES_COMMAND_OK)
{
char *temp;
long num_rows;
temp = PQcmdTuples(result);
num_rows = temp[0] ? atol(temp) : -1;
ret = PyInt_FromLong(num_rows);
}
else
{
PyErr_SetString(PyExc_IOError, PQerrorMessage(self->pgcnx->cnx));
ret = NULL;
}
PQclear(self->result);
self->result = NULL;
self->result_type = RESULT_EMPTY;
}
else /* a row has been returned */
{
ret = decode ? get_decoded_string(
buffer, nbytes, PQclientEncoding(self->pgcnx->cnx)) :
PyBytes_FromStringAndSize(buffer, nbytes);
PQfreemem(buffer);
}
return ret; /* buffer or number of rows */
}
/* finds field number from string/integer (internal use only) */
static int
sourceFieldindex(sourceObject *self, PyObject *param, const char *usage)
{
int num;
/* checks validity */
if (!check_source_obj(self, CHECK_RESULT | CHECK_DQL))
return -1;
/* gets field number */
if (PyStr_Check(param))
num = PQfnumber(self->result, PyBytes_AsString(param));
else if (PyInt_Check(param))
num = PyInt_AsLong(param);
else
{
PyErr_SetString(PyExc_TypeError, usage);
return -1;
}
/* checks field validity */
if (num < 0 || num >= self->num_fields)
{
PyErr_SetString(PyExc_ValueError, "Unknown field");
return -1;
}
return num;
}
/* builds field information from position (internal use only) */
static PyObject *
pgsource_buildinfo(sourceObject *self, int num)
{
PyObject *result;
/* allocates tuple */
result = PyTuple_New(5);
if (!result)
return NULL;
/* affects field information */
PyTuple_SET_ITEM(result, 0, PyInt_FromLong(num));
PyTuple_SET_ITEM(result, 1,
PyStr_FromString(PQfname(self->result, num)));
PyTuple_SET_ITEM(result, 2,
PyInt_FromLong(PQftype(self->result, num)));
PyTuple_SET_ITEM(result, 3,
PyInt_FromLong(PQfsize(self->result, num)));
PyTuple_SET_ITEM(result, 4,
PyInt_FromLong(PQfmod(self->result, num)));
return result;
}
/* lists fields info */
static char sourceListInfo__doc__[] =
"listinfo() -- get information for all fields (position, name, type oid)";
static PyObject *
sourceListInfo(sourceObject *self, PyObject *noargs)
{
int i;
PyObject *result,
*info;
/* checks validity */
if (!check_source_obj(self, CHECK_RESULT | CHECK_DQL))
return NULL;
/* builds result */
if (!(result = PyTuple_New(self->num_fields)))
return NULL;
for (i = 0; i < self->num_fields; ++i)
{
info = pgsource_buildinfo(self, i);
if (!info)
{
Py_DECREF(result);
return NULL;
}
PyTuple_SET_ITEM(result, i, info);
}
/* returns result */
return result;
};
/* list fields information for last result */
static char sourceFieldInfo__doc__[] =
"fieldinfo(desc) -- get specified field info (position, name, type oid)";
static PyObject *
sourceFieldInfo(sourceObject *self, PyObject *desc)
{
int num;
/* checks args and validity */
if ((num = sourceFieldindex(self, desc,
"Method fieldinfo() needs a string or integer as argument")) == -1)
return NULL;
/* returns result */
return pgsource_buildinfo(self, num);
};
/* retrieve field value */
static char sourceField__doc__[] =
"field(desc) -- return specified field value";
static PyObject *
sourceField(sourceObject *self, PyObject *desc)
{
int num;
/* checks args and validity */
if ((num = sourceFieldindex(self, desc,
"Method field() needs a string or integer as argument")) == -1)
return NULL;
return PyStr_FromString(
PQgetvalue(self->result, self->current_row, num));
}
/* get the list of source object attributes */
static PyObject *
sourceDir(connObject *self, PyObject *noargs)
{
PyObject *attrs;
attrs = PyObject_Dir(PyObject_Type((PyObject *)self));
PyObject_CallMethod(attrs, "extend", "[sssss]",
"pgcnx", "arraysize", "resulttype", "ntuples", "nfields");
return attrs;
}
/* source object methods */
static PyMethodDef sourceMethods[] = {
{"__dir__", (PyCFunction) sourceDir, METH_NOARGS, NULL},
{"close", (PyCFunction) sourceClose, METH_NOARGS, sourceClose__doc__},
{"execute", (PyCFunction) sourceExecute, METH_O, sourceExecute__doc__},
{"oidstatus", (PyCFunction) sourceStatusOID, METH_NOARGS,
sourceStatusOID__doc__},
{"fetch", (PyCFunction) sourceFetch, METH_VARARGS,
sourceFetch__doc__},
{"movefirst", (PyCFunction) sourceMoveFirst, METH_NOARGS,
sourceMoveFirst__doc__},
{"movelast", (PyCFunction) sourceMoveLast, METH_NOARGS,
sourceMoveLast__doc__},
{"movenext", (PyCFunction) sourceMoveNext, METH_NOARGS,
sourceMoveNext__doc__},
{"moveprev", (PyCFunction) sourceMovePrev, METH_NOARGS,
sourceMovePrev__doc__},
{"putdata", (PyCFunction) sourcePutData, METH_O, sourcePutData__doc__},
{"getdata", (PyCFunction) sourceGetData, METH_VARARGS,
sourceGetData__doc__},
{"field", (PyCFunction) sourceField, METH_O,
sourceField__doc__},
{"fieldinfo", (PyCFunction) sourceFieldInfo, METH_O,
sourceFieldInfo__doc__},
{"listinfo", (PyCFunction) sourceListInfo, METH_NOARGS,
sourceListInfo__doc__},
{NULL, NULL}
};
/* gets source object attributes */
static PyObject *
sourceGetAttr(sourceObject *self, PyObject *nameobj)
{
const char *name = PyStr_AsString(nameobj);
/* pg connection object */
if (!strcmp(name, "pgcnx"))
{
if (check_source_obj(self, 0))
{
Py_INCREF(self->pgcnx);
return (PyObject *) (self->pgcnx);
}
Py_INCREF(Py_None);
return Py_None;
}
/* arraysize */
if (!strcmp(name, "arraysize"))
return PyInt_FromLong(self->arraysize);
/* resulttype */
if (!strcmp(name, "resulttype"))
return PyInt_FromLong(self->result_type);
/* ntuples */
if (!strcmp(name, "ntuples"))
return PyInt_FromLong(self->max_row);
/* nfields */
if (!strcmp(name, "nfields"))
return PyInt_FromLong(self->num_fields);
/* seeks name in methods (fallback) */
return PyObject_GenericGetAttr((PyObject *) self, nameobj);
}
/* sets query object attributes */
static int
sourceSetAttr(sourceObject *self, char *name, PyObject *v)
{
/* arraysize */
if (!strcmp(name, "arraysize"))
{
if (!PyInt_Check(v))
{
PyErr_SetString(PyExc_TypeError, "arraysize must be integer");
return -1;
}
self->arraysize = PyInt_AsLong(v);
return 0;
}
/* unknown attribute */
PyErr_SetString(PyExc_TypeError, "Not a writable attribute");
return -1;
}
/* return source object as string in human readable form */
static PyObject *
sourceStr(sourceObject *self)
{
switch (self->result_type)
{
case RESULT_DQL:
return format_result(self->result);
case RESULT_DDL:
case RESULT_DML:
return PyStr_FromString(PQcmdStatus(self->result));
case RESULT_EMPTY:
default:
return PyStr_FromString("(empty PostgreSQL source object)");
}
}
static char source__doc__[] = "PyGreSQL source object";
/* source type definition */
static PyTypeObject sourceType = {
PyVarObject_HEAD_INIT(NULL, 0)
"pgdb.Source", /* tp_name */
sizeof(sourceObject), /* tp_basicsize */
0, /* tp_itemsize */
/* methods */
(destructor) sourceDealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
(setattrfunc) sourceSetAttr, /* tp_setattr */
0, /* tp_compare */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
(reprfunc) sourceStr, /* tp_str */
(getattrofunc) sourceGetAttr, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT, /* tp_flags */
source__doc__, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
sourceMethods, /* tp_methods */
};
/* connects to a database */
static char pgConnect__doc__[] =
"connect(dbname, host, port, opt) -- connect to a PostgreSQL database\n\n"
"The connection uses the specified parameters (optional, keywords aware).\n";
static PyObject *
pgConnect(PyObject *self, PyObject *args, PyObject *dict)
{
static const char *kwlist[] = {"dbname", "host", "port", "opt",
"user", "passwd", NULL};
char *pghost,
*pgopt,
*pgdbname,
*pguser,
*pgpasswd;
int pgport;
char port_buffer[20];
connObject *npgobj;
pghost = pgopt = pgdbname = pguser = pgpasswd = NULL;
pgport = -1;
/*
* parses standard arguments With the right compiler warnings, this
* will issue a diagnostic. There is really no way around it. If I
* don't declare kwlist as const char *kwlist[] then it complains when
* I try to assign all those constant strings to it.
*/
if (!PyArg_ParseTupleAndKeywords(args, dict, "|zzizzz", (char **) kwlist,
&pgdbname, &pghost, &pgport, &pgopt, &pguser, &pgpasswd))
return NULL;
#ifdef DEFAULT_VARS
/* handles defaults variables (for uninitialised vars) */
if ((!pghost) && (pg_default_host != Py_None))
pghost = PyBytes_AsString(pg_default_host);
if ((pgport == -1) && (pg_default_port != Py_None))
pgport = PyInt_AsLong(pg_default_port);
if ((!pgopt) && (pg_default_opt != Py_None))
pgopt = PyBytes_AsString(pg_default_opt);
if ((!pgdbname) && (pg_default_base != Py_None))
pgdbname = PyBytes_AsString(pg_default_base);
if ((!pguser) && (pg_default_user != Py_None))
pguser = PyBytes_AsString(pg_default_user);
if ((!pgpasswd) && (pg_default_passwd != Py_None))
pgpasswd = PyBytes_AsString(pg_default_passwd);
#endif /* DEFAULT_VARS */
if (!(npgobj = PyObject_NEW(connObject, &connType)))
{
set_error_msg(InternalError, "Can't create new connection object");
return NULL;
}
npgobj->valid = 1;
npgobj->cnx = NULL;
npgobj->date_format = date_format;
npgobj->cast_hook = NULL;
npgobj->notice_receiver = NULL;
if (pgport != -1)
{
memset(port_buffer, 0, sizeof(port_buffer));
sprintf(port_buffer, "%d", pgport);
}
Py_BEGIN_ALLOW_THREADS
npgobj->cnx = PQsetdbLogin(pghost, pgport == -1 ? NULL : port_buffer,
pgopt, NULL, pgdbname, pguser, pgpasswd);
Py_END_ALLOW_THREADS
if (PQstatus(npgobj->cnx) == CONNECTION_BAD)
{
set_error(InternalError, "Cannot connect", npgobj->cnx, NULL);
Py_XDECREF(npgobj);
return NULL;
}
return (PyObject *) npgobj;
}
static void
queryDealloc(queryObject *self)
{
Py_XDECREF(self->pgcnx);
if (self->result)
PQclear(self->result);
PyObject_Del(self);
}
/* get number of rows */
static char queryNTuples__doc__[] =
"ntuples() -- return number of tuples returned by query";
static PyObject *
queryNTuples(queryObject *self, PyObject *noargs)
{
return PyInt_FromLong((long) PQntuples(self->result));
}
/* list fields names from query result */
static char queryListFields__doc__[] =
"listfields() -- List field names from result";
static PyObject *
queryListFields(queryObject *self, PyObject *noargs)
{
int i,
n;
char *name;
PyObject *fieldstuple,
*str;
/* builds tuple */
n = PQnfields(self->result);
fieldstuple = PyTuple_New(n);
for (i = 0; i < n; ++i)
{
name = PQfname(self->result, i);
str = PyStr_FromString(name);
PyTuple_SET_ITEM(fieldstuple, i, str);
}
return fieldstuple;
}
/* get field name from last result */
static char queryFieldName__doc__[] =
"fieldname(num) -- return name of field from result from its position";
static PyObject *
queryFieldName(queryObject *self, PyObject *args)
{
int i;
char *name;
/* gets args */
if (!PyArg_ParseTuple(args, "i", &i))
{
PyErr_SetString(PyExc_TypeError,
"Method fieldname() takes an integer as argument");
return NULL;
}
/* checks number validity */
if (i >= PQnfields(self->result))
{
PyErr_SetString(PyExc_ValueError, "Invalid field number");
return NULL;
}
/* gets fields name and builds object */
name = PQfname(self->result, i);
return PyStr_FromString(name);
}
/* gets fields number from name in last result */
static char queryFieldNumber__doc__[] =
"fieldnum(name) -- return position in query for field from its name";
static PyObject *
queryFieldNumber(queryObject *self, PyObject *args)
{
int num;
char *name;
/* gets args */
if (!PyArg_ParseTuple(args, "s", &name))
{
PyErr_SetString(PyExc_TypeError,
"Method fieldnum() takes a string as argument");
return NULL;
}
/* gets field number */
if ((num = PQfnumber(self->result, name)) == -1)
{
PyErr_SetString(PyExc_ValueError, "Unknown field");
return NULL;
}
return PyInt_FromLong(num);
}
/* retrieves last result */
static char queryGetResult__doc__[] =
"getresult() -- Get the result of a query\n\n"
"The result is returned as a list of rows, each one a tuple of fields\n"
"in the order returned by the server.\n";
static PyObject *
queryGetResult(queryObject *self, PyObject *noargs)
{
PyObject *reslist;
int i, m, n, *col_types;
int encoding = self->encoding;
/* stores result in tuple */
m = PQntuples(self->result);
n = PQnfields(self->result);
if (!(reslist = PyList_New(m))) return NULL;
if (!(col_types = get_col_types(self->result, n))) return NULL;
for (i = 0; i < m; ++i)
{
PyObject *rowtuple;
int j;
if (!(rowtuple = PyTuple_New(n)))
{
Py_DECREF(reslist);
reslist = NULL;
goto exit;
}
for (j = 0; j < n; ++j)
{
PyObject * val;
if (PQgetisnull(self->result, i, j))
{
Py_INCREF(Py_None);
val = Py_None;
}
else /* not null */
{
/* get the string representation of the value */
/* note: this is always null-terminated text format */
char *s = PQgetvalue(self->result, i, j);
/* get the PyGreSQL type of the column */
int type = col_types[j];
if (type & PYGRES_ARRAY)
val = cast_array(s, PQgetlength(self->result, i, j),
encoding, type, NULL, 0);
else if (type == PYGRES_BYTEA)
val = cast_bytea_text(s);
else if (type == PYGRES_OTHER)
val = cast_other(s,
PQgetlength(self->result, i, j), encoding,
PQftype(self->result, j), self->pgcnx->cast_hook);
else if (type & PYGRES_TEXT)
val = cast_sized_text(s, PQgetlength(self->result, i, j),
encoding, type);
else
val = cast_unsized_simple(s, type);
}
if (!val)
{
Py_DECREF(reslist);
Py_DECREF(rowtuple);
reslist = NULL;
goto exit;
}
PyTuple_SET_ITEM(rowtuple, j, val);
}
PyList_SET_ITEM(reslist, i, rowtuple);
}
exit:
PyMem_Free(col_types);
/* returns list */
return reslist;
}
/* retrieves last result as a list of dictionaries*/
static char queryDictResult__doc__[] =
"dictresult() -- Get the result of a query\n\n"
"The result is returned as a list of rows, each one a dictionary with\n"
"the field names used as the labels.\n";
static PyObject *
queryDictResult(queryObject *self, PyObject *noargs)
{
PyObject *reslist;
int i,
m,
n,
*col_types;
int encoding = self->encoding;
/* stores result in list */
m = PQntuples(self->result);
n = PQnfields(self->result);
if (!(reslist = PyList_New(m))) return NULL;
if (!(col_types = get_col_types(self->result, n))) return NULL;
for (i = 0; i < m; ++i)
{
PyObject *dict;
int j;
if (!(dict = PyDict_New()))
{
Py_DECREF(reslist);
reslist = NULL;
goto exit;
}
for (j = 0; j < n; ++j)
{
PyObject * val;
if (PQgetisnull(self->result, i, j))
{
Py_INCREF(Py_None);
val = Py_None;
}
else /* not null */
{
/* get the string representation of the value */
/* note: this is always null-terminated text format */
char *s = PQgetvalue(self->result, i, j);
/* get the PyGreSQL type of the column */
int type = col_types[j];
if (type & PYGRES_ARRAY)
val = cast_array(s, PQgetlength(self->result, i, j),
encoding, type, NULL, 0);
else if (type == PYGRES_BYTEA)
val = cast_bytea_text(s);
else if (type == PYGRES_OTHER)
val = cast_other(s,
PQgetlength(self->result, i, j), encoding,
PQftype(self->result, j), self->pgcnx->cast_hook);
else if (type & PYGRES_TEXT)
val = cast_sized_text(s, PQgetlength(self->result, i, j),
encoding, type);
else
val = cast_unsized_simple(s, type);
}
if (!val)
{
Py_DECREF(dict);
Py_DECREF(reslist);
reslist = NULL;
goto exit;
}
PyDict_SetItemString(dict, PQfname(self->result, j), val);
Py_DECREF(val);
}
PyList_SET_ITEM(reslist, i, dict);
}
exit:
PyMem_Free(col_types);
/* returns list */
return reslist;
}
/* retrieves last result as named tuples */
static char queryNamedResult__doc__[] =
"namedresult() -- Get the result of a query\n\n"
"The result is returned as a list of rows, each one a tuple of fields\n"
"in the order returned by the server.\n";
static PyObject *
queryNamedResult(queryObject *self, PyObject *noargs)
{
PyObject *ret;
if (namedresult)
{
ret = PyObject_CallFunction(namedresult, "(O)", self);
if (ret == NULL)
return NULL;
}
else
{
ret = queryGetResult(self, NULL);
}
return ret;
}
/* gets notice object attributes */
static PyObject *
noticeGetAttr(noticeObject *self, PyObject *nameobj)
{
PGresult const *res = self->res;
const char *name = PyStr_AsString(nameobj);
int fieldcode;
if (!res)
{
PyErr_SetString(PyExc_TypeError, "Cannot get current notice");
return NULL;
}
/* pg connection object */
if (!strcmp(name, "pgcnx"))
{
if (self->pgcnx && check_cnx_obj(self->pgcnx))
{
Py_INCREF(self->pgcnx);
return (PyObject *) self->pgcnx;
}
else
{
Py_INCREF(Py_None);
return Py_None;
}
}
/* full message */
if (!strcmp(name, "message"))
return PyStr_FromString(PQresultErrorMessage(res));
/* other possible fields */
fieldcode = 0;
if (!strcmp(name, "severity"))
fieldcode = PG_DIAG_SEVERITY;
else if (!strcmp(name, "primary"))
fieldcode = PG_DIAG_MESSAGE_PRIMARY;
else if (!strcmp(name, "detail"))
fieldcode = PG_DIAG_MESSAGE_DETAIL;
else if (!strcmp(name, "hint"))
fieldcode = PG_DIAG_MESSAGE_HINT;
if (fieldcode)
{
char *s = PQresultErrorField(res, fieldcode);
if (s)
return PyStr_FromString(s);
else
{
Py_INCREF(Py_None); return Py_None;
}
}
return PyObject_GenericGetAttr((PyObject *) self, nameobj);
}
/* return notice as string in human readable form */
static PyObject *
noticeStr(noticeObject *self)
{
return noticeGetAttr(self, PyBytes_FromString("message"));
}
/* get the list of notice attributes */
static PyObject *
noticeDir(noticeObject *self, PyObject *noargs)
{
PyObject *attrs;
attrs = PyObject_Dir(PyObject_Type((PyObject *)self));
PyObject_CallMethod(attrs, "extend", "[ssssss]",
"pgcnx", "severity", "message", "primary", "detail", "hint");
return attrs;
}
/* notice object methods */
static struct PyMethodDef noticeMethods[] = {
{"__dir__", (PyCFunction) noticeDir, METH_NOARGS, NULL},
{NULL, NULL}
};
/* notice type definition */
static PyTypeObject noticeType = {
PyVarObject_HEAD_INIT(NULL, 0)
"pg.Notice", /* tp_name */
sizeof(noticeObject), /* tp_basicsize */
0, /* tp_itemsize */
/* methods */
0, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_compare */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
(reprfunc) noticeStr, /* tp_str */
(getattrofunc) noticeGetAttr, /* tp_getattro */
PyObject_GenericSetAttr, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT, /* tp_flags */
0, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
noticeMethods, /* tp_methods */
};
/* query object methods */
static struct PyMethodDef queryMethods[] = {
{"getresult", (PyCFunction) queryGetResult, METH_NOARGS,
queryGetResult__doc__},
{"dictresult", (PyCFunction) queryDictResult, METH_NOARGS,
queryDictResult__doc__},
{"namedresult", (PyCFunction) queryNamedResult, METH_NOARGS,
queryNamedResult__doc__},
{"fieldname", (PyCFunction) queryFieldName, METH_VARARGS,
queryFieldName__doc__},
{"fieldnum", (PyCFunction) queryFieldNumber, METH_VARARGS,
queryFieldNumber__doc__},
{"listfields", (PyCFunction) queryListFields, METH_NOARGS,
queryListFields__doc__},
{"ntuples", (PyCFunction) queryNTuples, METH_NOARGS,
queryNTuples__doc__},
{NULL, NULL}
};
/* query type definition */
static PyTypeObject queryType = {
PyVarObject_HEAD_INIT(NULL, 0)
"pg.Query", /* tp_name */
sizeof(queryObject), /* tp_basicsize */
0, /* tp_itemsize */
/* methods */
(destructor) queryDealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_compare */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
(reprfunc) queryStr, /* tp_str */
PyObject_GenericGetAttr, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT, /* tp_flags */
0, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
queryMethods, /* tp_methods */
};
/* --------------------------------------------------------------------- */
/* MODULE FUNCTIONS */
/* escape string */
static char pgEscapeString__doc__[] =
"escape_string(string) -- escape a string for use within SQL";
static PyObject *
pgEscapeString(PyObject *self, PyObject *string)
{
PyObject *tmp_obj = NULL, /* auxiliary string object */
*to_obj; /* string object to return */
char *from, /* our string argument as encoded string */
*to; /* the result as encoded string */
Py_ssize_t from_length; /* length of string */
size_t to_length; /* length of result */
int encoding = -1; /* client encoding */
if (PyBytes_Check(string))
{
PyBytes_AsStringAndSize(string, &from, &from_length);
}
else if (PyUnicode_Check(string))
{
encoding = pg_encoding_ascii;
tmp_obj = get_encoded_string(string, encoding);
if (!tmp_obj) return NULL; /* pass the UnicodeEncodeError */
PyBytes_AsStringAndSize(tmp_obj, &from, &from_length);
}
else
{
PyErr_SetString(PyExc_TypeError,
"Method escape_string() expects a string as argument");
return NULL;
}
to_length = 2*from_length + 1;
if ((Py_ssize_t)to_length < from_length) /* overflow */
{
to_length = from_length;
from_length = (from_length - 1)/2;
}
to = (char *)PyMem_Malloc(to_length);
to_length = (int)PQescapeString(to, from, (size_t)from_length);
Py_XDECREF(tmp_obj);
if (encoding == -1)
to_obj = PyBytes_FromStringAndSize(to, to_length);
else
to_obj = get_decoded_string(to, to_length, encoding);
PyMem_Free(to);
return to_obj;
}
/* escape bytea */
static char pgEscapeBytea__doc__[] =
"escape_bytea(data) -- escape binary data for use within SQL as type bytea";
static PyObject *
pgEscapeBytea(PyObject *self, PyObject *data)
{
PyObject *tmp_obj = NULL, /* auxiliary string object */
*to_obj; /* string object to return */
char *from, /* our string argument as encoded string */
*to; /* the result as encoded string */
Py_ssize_t from_length; /* length of string */
size_t to_length; /* length of result */
int encoding = -1; /* client encoding */
if (PyBytes_Check(data))
{
PyBytes_AsStringAndSize(data, &from, &from_length);
}
else if (PyUnicode_Check(data))
{
encoding = pg_encoding_ascii;
tmp_obj = get_encoded_string(data, encoding);
if (!tmp_obj) return NULL; /* pass the UnicodeEncodeError */
PyBytes_AsStringAndSize(tmp_obj, &from, &from_length);
}
else
{
PyErr_SetString(PyExc_TypeError,
"Method escape_bytea() expects a string as argument");
return NULL;
}
to = (char *)PQescapeBytea(
(unsigned char*)from, (size_t)from_length, &to_length);
Py_XDECREF(tmp_obj);
if (encoding == -1)
to_obj = PyBytes_FromStringAndSize(to, to_length - 1);
else
to_obj = get_decoded_string(to, to_length - 1, encoding);
if (to)
PQfreemem(to);
return to_obj;
}
/* unescape bytea */
static char pgUnescapeBytea__doc__[] =
"unescape_bytea(string) -- unescape bytea data retrieved as text";
static PyObject *
pgUnescapeBytea(PyObject *self, PyObject *data)
{
PyObject *tmp_obj = NULL, /* auxiliary string object */
*to_obj; /* string object to return */
char *from, /* our string argument as encoded string */
*to; /* the result as encoded string */
Py_ssize_t from_length; /* length of string */
size_t to_length; /* length of result */
if (PyBytes_Check(data))
{
PyBytes_AsStringAndSize(data, &from, &from_length);
}
else if (PyUnicode_Check(data))
{
tmp_obj = get_encoded_string(data, pg_encoding_ascii);
if (!tmp_obj) return NULL; /* pass the UnicodeEncodeError */
PyBytes_AsStringAndSize(tmp_obj, &from, &from_length);
}
else
{
PyErr_SetString(PyExc_TypeError,
"Method unescape_bytea() expects a string as argument");
return NULL;
}
to = (char *)PQunescapeBytea((unsigned char*)from, &to_length);
Py_XDECREF(tmp_obj);
if (!to) return PyErr_NoMemory();
to_obj = PyBytes_FromStringAndSize(to, to_length);
PQfreemem(to);
return to_obj;
}
/* set fixed datestyle */
static char pgSetDatestyle__doc__[] =
"set_datestyle(style) -- set which style is assumed";
static PyObject *
pgSetDatestyle(PyObject *self, PyObject *args)
{
const char *datestyle = NULL;
/* gets arguments */
if (!PyArg_ParseTuple(args, "z", &datestyle))
{
PyErr_SetString(PyExc_TypeError,
"Function set_datestyle() expects a string or None as argument");
return NULL;
}
date_format = datestyle ? date_style_to_format(datestyle) : NULL;
Py_INCREF(Py_None); return Py_None;
}
/* get fixed datestyle */
static char pgGetDatestyle__doc__[] =
"get_datestyle() -- get which date style is assumed";
static PyObject *
pgGetDatestyle(PyObject *self, PyObject *noargs)
{
if (date_format)
{
return PyStr_FromString(date_format_to_style(date_format));
}
else
{
Py_INCREF(Py_None); return Py_None;
}
}
/* get decimal point */
static char pgGetDecimalPoint__doc__[] =
"get_decimal_point() -- get decimal point to be used for money values";
static PyObject *
pgGetDecimalPoint(PyObject *self, PyObject *noargs)
{
PyObject *ret;
char s[2];
if (decimal_point)
{
s[0] = decimal_point; s[1] = '\0';
ret = PyStr_FromString(s);
}
else
{
Py_INCREF(Py_None); ret = Py_None;
}
return ret;
}
/* set decimal point */
static char pgSetDecimalPoint__doc__[] =
"set_decimal_point(char) -- set decimal point to be used for money values";
static PyObject *
pgSetDecimalPoint(PyObject *self, PyObject *args)
{
PyObject *ret = NULL;
char *s = NULL;
/* gets arguments */
if (PyArg_ParseTuple(args, "z", &s))
{
if (!s)
s = "\0";
else if (*s && (*(s+1) || !strchr(".,;: '*/_`|", *s)))
s = NULL;
}
if (s)
{
decimal_point = *s;
Py_INCREF(Py_None); ret = Py_None;
}
else
PyErr_SetString(PyExc_TypeError,
"Function set_decimal_mark() expects"
" a decimal mark character as argument");
return ret;
}
/* get decimal type */
static char pgGetDecimal__doc__[] =
"get_decimal() -- get the decimal type to be used for numeric values";
static PyObject *
pgGetDecimal(PyObject *self, PyObject *noargs)
{
PyObject *ret;
ret = decimal ? decimal : Py_None;
Py_INCREF(ret);
return ret;
}
/* set decimal type */
static char pgSetDecimal__doc__[] =
"set_decimal(cls) -- set a decimal type to be used for numeric values";
static PyObject *
pgSetDecimal(PyObject *self, PyObject *cls)
{
PyObject *ret = NULL;
if (cls == Py_None)
{
Py_XDECREF(decimal); decimal = NULL;
Py_INCREF(Py_None); ret = Py_None;
}
else if (PyCallable_Check(cls))
{
Py_XINCREF(cls); Py_XDECREF(decimal); decimal = cls;
Py_INCREF(Py_None); ret = Py_None;
}
else
PyErr_SetString(PyExc_TypeError,
"Function set_decimal() expects"
" a callable or None as argument");
return ret;
}
/* get usage of bool values */
static char pgGetBool__doc__[] =
"get_bool() -- check whether boolean values are converted to bool";
static PyObject *
pgGetBool(PyObject *self, PyObject *noargs)
{
PyObject *ret;
ret = bool_as_text ? Py_False : Py_True;
Py_INCREF(ret);
return ret;
}
/* set usage of bool values */
static char pgSetBool__doc__[] =
"set_bool(on) -- set whether boolean values should be converted to bool";
static PyObject *
pgSetBool(PyObject *self, PyObject *args)
{
PyObject *ret = NULL;
int i;
/* gets arguments */
if (PyArg_ParseTuple(args, "i", &i))
{
bool_as_text = i ? 0 : 1;
Py_INCREF(Py_None); ret = Py_None;
}
else
PyErr_SetString(PyExc_TypeError,
"Function set_bool() expects a boolean value as argument");
return ret;
}
/* get conversion of arrays to lists */
static char pgGetArray__doc__[] =
"get_array() -- check whether arrays are converted as lists";
static PyObject *
pgGetArray(PyObject *self, PyObject *noargs)
{
PyObject *ret;
ret = array_as_text ? Py_False : Py_True;
Py_INCREF(ret);
return ret;
}
/* set conversion of arrays to lists */
static char pgSetArray__doc__[] =
"set_array(on) -- set whether arrays should be converted to lists";
static PyObject *
pgSetArray(PyObject *self, PyObject *args)
{
PyObject *ret = NULL;
int i;
/* gets arguments */
if (PyArg_ParseTuple(args, "i", &i))
{
array_as_text = i ? 0 : 1;
Py_INCREF(Py_None); ret = Py_None;
}
else
PyErr_SetString(PyExc_TypeError,
"Function set_array() expects a boolean value as argument");
return ret;
}
/* check whether bytea values are unescaped */
static char pgGetByteaEscaped__doc__[] =
"get_bytea_escaped() -- check whether bytea will be returned escaped";
static PyObject *
pgGetByteaEscaped(PyObject *self, PyObject *noargs)
{
PyObject *ret;
ret = bytea_escaped ? Py_True : Py_False;
Py_INCREF(ret);
return ret;
}
/* set usage of bool values */
static char pgSetByteaEscaped__doc__[] =
"set_bytea_escaped(on) -- set whether bytea will be returned escaped";
static PyObject *
pgSetByteaEscaped(PyObject *self, PyObject *args)
{
PyObject *ret = NULL;
int i;
/* gets arguments */
if (PyArg_ParseTuple(args, "i", &i))
{
bytea_escaped = i ? 1 : 0;
Py_INCREF(Py_None); ret = Py_None;
}
else
PyErr_SetString(PyExc_TypeError,
"Function set_bytea_escaped() expects a boolean value as argument");
return ret;
}
/* get named result factory */
static char pgGetNamedresult__doc__[] =
"get_namedresult() -- get the function used for getting named results";
static PyObject *
pgGetNamedresult(PyObject *self, PyObject *noargs)
{
PyObject *ret;
ret = namedresult ? namedresult : Py_None;
Py_INCREF(ret);
return ret;
}
/* set named result factory */
static char pgSetNamedresult__doc__[] =
"set_namedresult(func) -- set a function to be used for getting named results";
static PyObject *
pgSetNamedresult(PyObject *self, PyObject *func)
{
PyObject *ret = NULL;
if (func == Py_None)
{
Py_XDECREF(namedresult); namedresult = NULL;
Py_INCREF(Py_None); ret = Py_None;
}
else if (PyCallable_Check(func))
{
Py_XINCREF(func); Py_XDECREF(namedresult); namedresult = func;
Py_INCREF(Py_None); ret = Py_None;
}
else
PyErr_SetString(PyExc_TypeError,
"Function set_namedresult() expects"
" a callable or None as argument");
return ret;
}
/* get json decode function */
static char pgGetJsondecode__doc__[] =
"get_jsondecode() -- get the function used for decoding json results";
static PyObject *
pgGetJsondecode(PyObject *self, PyObject *noargs)
{
PyObject *ret;
ret = jsondecode;
if (!ret)
ret = Py_None;
Py_INCREF(ret);
return ret;
}
/* set json decode function */
static char pgSetJsondecode__doc__[] =
"set_jsondecode(func) -- set a function to be used for decoding json results";
static PyObject *
pgSetJsondecode(PyObject *self, PyObject *func)
{
PyObject *ret = NULL;
if (func == Py_None)
{
Py_XDECREF(jsondecode); jsondecode = NULL;
Py_INCREF(Py_None); ret = Py_None;
}
else if (PyCallable_Check(func))
{
Py_XINCREF(func); Py_XDECREF(jsondecode); jsondecode = func;
Py_INCREF(Py_None); ret = Py_None;
}
else
PyErr_SetString(PyExc_TypeError,
"Function jsondecode() expects"
" a callable or None as argument");
return ret;
}
#ifdef DEFAULT_VARS
/* gets default host */
static char pgGetDefHost__doc__[] =
"get_defhost() -- return default database host";
static PyObject *
pgGetDefHost(PyObject *self, PyObject *noargs)
{
Py_XINCREF(pg_default_host);
return pg_default_host;
}
/* sets default host */
static char pgSetDefHost__doc__[] =
"set_defhost(string) -- set default database host and return previous value";
static PyObject *
pgSetDefHost(PyObject *self, PyObject *args)
{
char *temp = NULL;
PyObject *old;
/* gets arguments */
if (!PyArg_ParseTuple(args, "z", &temp))
{
PyErr_SetString(PyExc_TypeError,
"Function set_defhost() expects a string or None as argument");
return NULL;
}
/* adjusts value */
old = pg_default_host;
if (temp)
pg_default_host = PyStr_FromString(temp);
else
{
Py_INCREF(Py_None);
pg_default_host = Py_None;
}
return old;
}
/* gets default base */
static char pgGetDefBase__doc__[] =
"get_defbase() -- return default database name";
static PyObject *
pgGetDefBase(PyObject *self, PyObject *noargs)
{
Py_XINCREF(pg_default_base);
return pg_default_base;
}
/* sets default base */
static char pgSetDefBase__doc__[] =
"set_defbase(string) -- set default database name and return previous value";
static PyObject *
pgSetDefBase(PyObject *self, PyObject *args)
{
char *temp = NULL;
PyObject *old;
/* gets arguments */
if (!PyArg_ParseTuple(args, "z", &temp))
{
PyErr_SetString(PyExc_TypeError,
"Function set_defbase() Argument a string or None as argument");
return NULL;
}
/* adjusts value */
old = pg_default_base;
if (temp)
pg_default_base = PyStr_FromString(temp);
else
{
Py_INCREF(Py_None);
pg_default_base = Py_None;
}
return old;
}
/* gets default options */
static char pgGetDefOpt__doc__[] =
"get_defopt() -- return default database options";
static PyObject *
pgGetDefOpt(PyObject *self, PyObject *noargs)
{
Py_XINCREF(pg_default_opt);
return pg_default_opt;
}
/* sets default opt */
static char pgSetDefOpt__doc__[] =
"set_defopt(string) -- set default options and return previous value";
static PyObject *
pgSetDefOpt(PyObject *self, PyObject *args)
{
char *temp = NULL;
PyObject *old;
/* gets arguments */
if (!PyArg_ParseTuple(args, "z", &temp))
{
PyErr_SetString(PyExc_TypeError,
"Function set_defopt() expects a string or None as argument");
return NULL;
}
/* adjusts value */
old = pg_default_opt;
if (temp)
pg_default_opt = PyStr_FromString(temp);
else
{
Py_INCREF(Py_None);
pg_default_opt = Py_None;
}
return old;
}
/* gets default username */
static char pgGetDefUser__doc__[] =
"get_defuser() -- return default database username";
static PyObject *
pgGetDefUser(PyObject *self, PyObject *noargs)
{
Py_XINCREF(pg_default_user);
return pg_default_user;
}
/* sets default username */
static char pgSetDefUser__doc__[] =
"set_defuser(name) -- set default username and return previous value";
static PyObject *
pgSetDefUser(PyObject *self, PyObject *args)
{
char *temp = NULL;
PyObject *old;
/* gets arguments */
if (!PyArg_ParseTuple(args, "z", &temp))
{
PyErr_SetString(PyExc_TypeError,
"Function set_defuser() expects a string or None as argument");
return NULL;
}
/* adjusts value */
old = pg_default_user;
if (temp)
pg_default_user = PyStr_FromString(temp);
else
{
Py_INCREF(Py_None);
pg_default_user = Py_None;
}
return old;
}
/* sets default password */
static char pgSetDefPassword__doc__[] =
"set_defpasswd(password) -- set default database password";
static PyObject *
pgSetDefPassword(PyObject *self, PyObject *args)
{
char *temp = NULL;
/* gets arguments */
if (!PyArg_ParseTuple(args, "z", &temp))
{
PyErr_SetString(PyExc_TypeError,
"Function set_defpasswd() expects a string or None as argument");
return NULL;
}
if (temp)
pg_default_passwd = PyStr_FromString(temp);
else
{
Py_INCREF(Py_None);
pg_default_passwd = Py_None;
}
Py_INCREF(Py_None);
return Py_None;
}
/* gets default port */
static char pgGetDefPort__doc__[] =
"get_defport() -- return default database port";
static PyObject *
pgGetDefPort(PyObject *self, PyObject *noargs)
{
Py_XINCREF(pg_default_port);
return pg_default_port;
}
/* sets default port */
static char pgSetDefPort__doc__[] =
"set_defport(port) -- set default port and return previous value";
static PyObject *
pgSetDefPort(PyObject *self, PyObject *args)
{
long int port = -2;
PyObject *old;
/* gets arguments */
if ((!PyArg_ParseTuple(args, "l", &port)) || (port < -1))
{
PyErr_SetString(PyExc_TypeError,
"Function set_deport expects"
" a positive integer or -1 as argument");
return NULL;
}
/* adjusts value */
old = pg_default_port;
if (port != -1)
pg_default_port = PyInt_FromLong(port);
else
{
Py_INCREF(Py_None);
pg_default_port = Py_None;
}
return old;
}
#endif /* DEFAULT_VARS */
/* cast a string with a text representation of an array to a list */
static char pgCastArray__doc__[] =
"cast_array(string, cast=None, delim=',') -- cast a string as an array";
PyObject *
pgCastArray(PyObject *self, PyObject *args, PyObject *dict)
{
static const char *kwlist[] = {"string", "cast", "delim", NULL};
PyObject *string_obj, *cast_obj = NULL, *ret;
char *string, delim = ',';
Py_ssize_t size;
int encoding;
if (!PyArg_ParseTupleAndKeywords(args, dict, "O|Oc",
(char **) kwlist, &string_obj, &cast_obj, &delim))
return NULL;
if (PyBytes_Check(string_obj))
{
PyBytes_AsStringAndSize(string_obj, &string, &size);
string_obj = NULL;
encoding = pg_encoding_ascii;
}
else if (PyUnicode_Check(string_obj))
{
string_obj = PyUnicode_AsUTF8String(string_obj);
if (!string_obj) return NULL; /* pass the UnicodeEncodeError */
PyBytes_AsStringAndSize(string_obj, &string, &size);
encoding = pg_encoding_utf8;
}
else
{
PyErr_SetString(PyExc_TypeError,
"Function cast_array() expects a string as first argument");
return NULL;
}
if (!cast_obj || cast_obj == Py_None)
{
if (cast_obj)
{
Py_DECREF(cast_obj); cast_obj = NULL;
}
}
else if (!PyCallable_Check(cast_obj))
{
PyErr_SetString(PyExc_TypeError,
"Function cast_array() expects a callable as second argument");
return NULL;
}
ret = cast_array(string, size, encoding, 0, cast_obj, delim);
Py_XDECREF(string_obj);
return ret;
}
/* cast a string with a text representation of a record to a tuple */
static char pgCastRecord__doc__[] =
"cast_record(string, cast=None, delim=',') -- cast a string as a record";
PyObject *
pgCastRecord(PyObject *self, PyObject *args, PyObject *dict)
{
static const char *kwlist[] = {"string", "cast", "delim", NULL};
PyObject *string_obj, *cast_obj = NULL, *ret;
char *string, delim = ',';
Py_ssize_t size, len;
int encoding;
if (!PyArg_ParseTupleAndKeywords(args, dict, "O|Oc",
(char **) kwlist, &string_obj, &cast_obj, &delim))
return NULL;
if (PyBytes_Check(string_obj))
{
PyBytes_AsStringAndSize(string_obj, &string, &size);
string_obj = NULL;
encoding = pg_encoding_ascii;
}
else if (PyUnicode_Check(string_obj))
{
string_obj = PyUnicode_AsUTF8String(string_obj);
if (!string_obj) return NULL; /* pass the UnicodeEncodeError */
PyBytes_AsStringAndSize(string_obj, &string, &size);
encoding = pg_encoding_utf8;
}
else
{
PyErr_SetString(PyExc_TypeError,
"Function cast_record() expects a string as first argument");
return NULL;
}
if (!cast_obj || PyCallable_Check(cast_obj))
{
len = 0;
}
else if (cast_obj == Py_None)
{
Py_DECREF(cast_obj); cast_obj = NULL; len = 0;
}
else if (PyTuple_Check(cast_obj) || PyList_Check(cast_obj))
{
len = PySequence_Size(cast_obj);
if (!len)
{
Py_DECREF(cast_obj); cast_obj = NULL;
}
}
else
{
PyErr_SetString(PyExc_TypeError,
"Function cast_record() expects a callable"
" or tuple or list of callables as second argument");
return NULL;
}
ret = cast_record(string, size, encoding, 0, cast_obj, len, delim);
Py_XDECREF(string_obj);
return ret;
}
/* cast a string with a text representation of an hstore to a dict */
static char pgCastHStore__doc__[] =
"cast_hstore(string) -- cast a string as an hstore";
PyObject *
pgCastHStore(PyObject *self, PyObject *string)
{
PyObject *tmp_obj = NULL, *ret;
char *s;
Py_ssize_t size;
int encoding;
if (PyBytes_Check(string))
{
PyBytes_AsStringAndSize(string, &s, &size);
encoding = pg_encoding_ascii;
}
else if (PyUnicode_Check(string))
{
tmp_obj = PyUnicode_AsUTF8String(string);
if (!tmp_obj) return NULL; /* pass the UnicodeEncodeError */
PyBytes_AsStringAndSize(tmp_obj, &s, &size);
encoding = pg_encoding_utf8;
}
else
{
PyErr_SetString(PyExc_TypeError,
"Function cast_hstore() expects a string as first argument");
return NULL;
}
ret = cast_hstore(s, size, encoding);
Py_XDECREF(tmp_obj);
return ret;
}
/* List of functions defined in the module */
static struct PyMethodDef pgMethods[] = {
{"connect", (PyCFunction) pgConnect, METH_VARARGS|METH_KEYWORDS,
pgConnect__doc__},
{"escape_string", (PyCFunction) pgEscapeString, METH_O,
pgEscapeString__doc__},
{"escape_bytea", (PyCFunction) pgEscapeBytea, METH_O,
pgEscapeBytea__doc__},
{"unescape_bytea", (PyCFunction) pgUnescapeBytea, METH_O,
pgUnescapeBytea__doc__},
{"get_datestyle", (PyCFunction) pgGetDatestyle, METH_NOARGS,
pgGetDatestyle__doc__},
{"set_datestyle", (PyCFunction) pgSetDatestyle, METH_VARARGS,
pgSetDatestyle__doc__},
{"get_decimal_point", (PyCFunction) pgGetDecimalPoint, METH_NOARGS,
pgGetDecimalPoint__doc__},
{"set_decimal_point", (PyCFunction) pgSetDecimalPoint, METH_VARARGS,
pgSetDecimalPoint__doc__},
{"get_decimal", (PyCFunction) pgGetDecimal, METH_NOARGS,
pgGetDecimal__doc__},
{"set_decimal", (PyCFunction) pgSetDecimal, METH_O,
pgSetDecimal__doc__},
{"get_bool", (PyCFunction) pgGetBool, METH_NOARGS, pgGetBool__doc__},
{"set_bool", (PyCFunction) pgSetBool, METH_VARARGS, pgSetBool__doc__},
{"get_array", (PyCFunction) pgGetArray, METH_NOARGS, pgGetArray__doc__},
{"set_array", (PyCFunction) pgSetArray, METH_VARARGS, pgSetArray__doc__},
{"get_bytea_escaped", (PyCFunction) pgGetByteaEscaped, METH_NOARGS,
pgGetByteaEscaped__doc__},
{"set_bytea_escaped", (PyCFunction) pgSetByteaEscaped, METH_VARARGS,
pgSetByteaEscaped__doc__},
{"get_namedresult", (PyCFunction) pgGetNamedresult, METH_NOARGS,
pgGetNamedresult__doc__},
{"set_namedresult", (PyCFunction) pgSetNamedresult, METH_O,
pgSetNamedresult__doc__},
{"get_jsondecode", (PyCFunction) pgGetJsondecode, METH_NOARGS,
pgGetJsondecode__doc__},
{"set_jsondecode", (PyCFunction) pgSetJsondecode, METH_O,
pgSetJsondecode__doc__},
{"cast_array", (PyCFunction) pgCastArray, METH_VARARGS|METH_KEYWORDS,
pgCastArray__doc__},
{"cast_record", (PyCFunction) pgCastRecord, METH_VARARGS|METH_KEYWORDS,
pgCastRecord__doc__},
{"cast_hstore", (PyCFunction) pgCastHStore, METH_O, pgCastHStore__doc__},
#ifdef DEFAULT_VARS
{"get_defhost", pgGetDefHost, METH_NOARGS, pgGetDefHost__doc__},
{"set_defhost", pgSetDefHost, METH_VARARGS, pgSetDefHost__doc__},
{"get_defbase", pgGetDefBase, METH_NOARGS, pgGetDefBase__doc__},
{"set_defbase", pgSetDefBase, METH_VARARGS, pgSetDefBase__doc__},
{"get_defopt", pgGetDefOpt, METH_NOARGS, pgGetDefOpt__doc__},
{"set_defopt", pgSetDefOpt, METH_VARARGS, pgSetDefOpt__doc__},
{"get_defport", pgGetDefPort, METH_NOARGS, pgGetDefPort__doc__},
{"set_defport", pgSetDefPort, METH_VARARGS, pgSetDefPort__doc__},
{"get_defuser", pgGetDefUser, METH_NOARGS, pgGetDefUser__doc__},
{"set_defuser", pgSetDefUser, METH_VARARGS, pgSetDefUser__doc__},
{"set_defpasswd", pgSetDefPassword, METH_VARARGS, pgSetDefPassword__doc__},
#endif /* DEFAULT_VARS */
{NULL, NULL} /* sentinel */
};
static char pg__doc__[] = "Python interface to PostgreSQL DB";
static struct PyModuleDef moduleDef = {
PyModuleDef_HEAD_INIT,
"_pg", /* m_name */
pg__doc__, /* m_doc */
-1, /* m_size */
pgMethods /* m_methods */
};
/* Initialization function for the module */
MODULE_INIT_FUNC(_pg)
{
PyObject *mod, *dict, *s;
/* Create the module and add the functions */
mod = PyModule_Create(&moduleDef);
/* Initialize here because some Windows platforms get confused otherwise */
#if IS_PY3
connType.tp_base = noticeType.tp_base =
queryType.tp_base = sourceType.tp_base = &PyBaseObject_Type;
#ifdef LARGE_OBJECTS
largeType.tp_base = &PyBaseObject_Type;
#endif
#else
connType.ob_type = noticeType.ob_type =
queryType.ob_type = sourceType.ob_type = &PyType_Type;
#ifdef LARGE_OBJECTS
largeType.ob_type = &PyType_Type;
#endif
#endif
if (PyType_Ready(&connType)
|| PyType_Ready(¬iceType)
|| PyType_Ready(&queryType)
|| PyType_Ready(&sourceType)
#ifdef LARGE_OBJECTS
|| PyType_Ready(&largeType)
#endif
) return NULL;
dict = PyModule_GetDict(mod);
/* Exceptions as defined by DB-API 2.0 */
Error = PyErr_NewException("pg.Error", PyExc_Exception, NULL);
PyDict_SetItemString(dict, "Error", Error);
Warning = PyErr_NewException("pg.Warning", PyExc_Exception, NULL);
PyDict_SetItemString(dict, "Warning", Warning);
InterfaceError = PyErr_NewException("pg.InterfaceError", Error, NULL);
PyDict_SetItemString(dict, "InterfaceError", InterfaceError);
DatabaseError = PyErr_NewException("pg.DatabaseError", Error, NULL);
PyDict_SetItemString(dict, "DatabaseError", DatabaseError);
InternalError = PyErr_NewException("pg.InternalError", DatabaseError, NULL);
PyDict_SetItemString(dict, "InternalError", InternalError);
OperationalError =
PyErr_NewException("pg.OperationalError", DatabaseError, NULL);
PyDict_SetItemString(dict, "OperationalError", OperationalError);
ProgrammingError =
PyErr_NewException("pg.ProgrammingError", DatabaseError, NULL);
PyDict_SetItemString(dict, "ProgrammingError", ProgrammingError);
IntegrityError =
PyErr_NewException("pg.IntegrityError", DatabaseError, NULL);
PyDict_SetItemString(dict, "IntegrityError", IntegrityError);
DataError = PyErr_NewException("pg.DataError", DatabaseError, NULL);
PyDict_SetItemString(dict, "DataError", DataError);
NotSupportedError =
PyErr_NewException("pg.NotSupportedError", DatabaseError, NULL);
PyDict_SetItemString(dict, "NotSupportedError", NotSupportedError);
/* Make the version available */
s = PyStr_FromString(PyPgVersion);
PyDict_SetItemString(dict, "version", s);
PyDict_SetItemString(dict, "__version__", s);
Py_DECREF(s);
/* results type for queries */
PyDict_SetItemString(dict, "RESULT_EMPTY", PyInt_FromLong(RESULT_EMPTY));
PyDict_SetItemString(dict, "RESULT_DML", PyInt_FromLong(RESULT_DML));
PyDict_SetItemString(dict, "RESULT_DDL", PyInt_FromLong(RESULT_DDL));
PyDict_SetItemString(dict, "RESULT_DQL", PyInt_FromLong(RESULT_DQL));
/* transaction states */
PyDict_SetItemString(dict,"TRANS_IDLE",PyInt_FromLong(PQTRANS_IDLE));
PyDict_SetItemString(dict,"TRANS_ACTIVE",PyInt_FromLong(PQTRANS_ACTIVE));
PyDict_SetItemString(dict,"TRANS_INTRANS",PyInt_FromLong(PQTRANS_INTRANS));
PyDict_SetItemString(dict,"TRANS_INERROR",PyInt_FromLong(PQTRANS_INERROR));
PyDict_SetItemString(dict,"TRANS_UNKNOWN",PyInt_FromLong(PQTRANS_UNKNOWN));
#ifdef LARGE_OBJECTS
/* create mode for large objects */
PyDict_SetItemString(dict, "INV_READ", PyInt_FromLong(INV_READ));
PyDict_SetItemString(dict, "INV_WRITE", PyInt_FromLong(INV_WRITE));
/* position flags for lo_lseek */
PyDict_SetItemString(dict, "SEEK_SET", PyInt_FromLong(SEEK_SET));
PyDict_SetItemString(dict, "SEEK_CUR", PyInt_FromLong(SEEK_CUR));
PyDict_SetItemString(dict, "SEEK_END", PyInt_FromLong(SEEK_END));
#endif /* LARGE_OBJECTS */
#ifdef DEFAULT_VARS
/* prepares default values */
Py_INCREF(Py_None);
pg_default_host = Py_None;
Py_INCREF(Py_None);
pg_default_base = Py_None;
Py_INCREF(Py_None);
pg_default_opt = Py_None;
Py_INCREF(Py_None);
pg_default_port = Py_None;
Py_INCREF(Py_None);
pg_default_user = Py_None;
Py_INCREF(Py_None);
pg_default_passwd = Py_None;
#endif /* DEFAULT_VARS */
/* store common pg encoding ids */
pg_encoding_utf8 = pg_char_to_encoding("UTF8");
pg_encoding_latin1 = pg_char_to_encoding("LATIN1");
pg_encoding_ascii = pg_char_to_encoding("SQL_ASCII");
/* Check for errors */
if (PyErr_Occurred())
return NULL;
return mod;
}
|