/usr/share/phppgadmin/classes/database/Postgres.php is in phppgadmin 5.1-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957 7958 7959 7960 7961 7962 7963 7964 7965 7966 7967 7968 7969 7970 7971 7972 7973 7974 7975 7976 7977 7978 7979 7980 7981 7982 7983 7984 7985 7986 7987 7988 7989 7990 7991 7992 7993 | <?php
/**
* A Class that implements the DB Interface for Postgres
* Note: This Class uses ADODB and returns RecordSets.
*
* $Id: Postgres.php,v 1.320 2008/02/20 20:43:09 ioguix Exp $
*/
include_once('./classes/database/ADODB_base.php');
class Postgres extends ADODB_base {
var $major_version = 9.2;
// Max object name length
var $_maxNameLen = 63;
// Store the current schema
var $_schema;
// Map of database encoding names to HTTP encoding names. If a
// database encoding does not appear in this list, then its HTTP
// encoding name is the same as its database encoding name.
var $codemap = array(
'BIG5' => 'BIG5',
'EUC_CN' => 'GB2312',
'EUC_JP' => 'EUC-JP',
'EUC_KR' => 'EUC-KR',
'EUC_TW' => 'EUC-TW',
'GB18030' => 'GB18030',
'GBK' => 'GB2312',
'ISO_8859_5' => 'ISO-8859-5',
'ISO_8859_6' => 'ISO-8859-6',
'ISO_8859_7' => 'ISO-8859-7',
'ISO_8859_8' => 'ISO-8859-8',
'JOHAB' => 'CP1361',
'KOI8' => 'KOI8-R',
'LATIN1' => 'ISO-8859-1',
'LATIN2' => 'ISO-8859-2',
'LATIN3' => 'ISO-8859-3',
'LATIN4' => 'ISO-8859-4',
'LATIN5' => 'ISO-8859-9',
'LATIN6' => 'ISO-8859-10',
'LATIN7' => 'ISO-8859-13',
'LATIN8' => 'ISO-8859-14',
'LATIN9' => 'ISO-8859-15',
'LATIN10' => 'ISO-8859-16',
'SJIS' => 'SHIFT_JIS',
'SQL_ASCII' => 'US-ASCII',
'UHC' => 'WIN949',
'UTF8' => 'UTF-8',
'WIN866' => 'CP866',
'WIN874' => 'CP874',
'WIN1250' => 'CP1250',
'WIN1251' => 'CP1251',
'WIN1252' => 'CP1252',
'WIN1256' => 'CP1256',
'WIN1258' => 'CP1258'
);
var $defaultprops = array('', '', '');
// Extra "magic" types. BIGSERIAL was added in PostgreSQL 7.2.
var $extraTypes = array('SERIAL', 'BIGSERIAL');
// Foreign key stuff. First element MUST be the default.
var $fkactions = array('NO ACTION', 'RESTRICT', 'CASCADE', 'SET NULL', 'SET DEFAULT');
var $fkdeferrable = array('NOT DEFERRABLE', 'DEFERRABLE');
var $fkinitial = array('INITIALLY IMMEDIATE', 'INITIALLY DEFERRED');
var $fkmatches = array('MATCH SIMPLE', 'MATCH FULL');
// Function properties
var $funcprops = array( array('', 'VOLATILE', 'IMMUTABLE', 'STABLE'),
array('', 'CALLED ON NULL INPUT', 'RETURNS NULL ON NULL INPUT'),
array('', 'SECURITY INVOKER', 'SECURITY DEFINER'));
// Default help URL
var $help_base;
// Help sub pages
var $help_page;
// Name of id column
var $id = 'oid';
// Supported join operations for use with view wizard
var $joinOps = array('INNER JOIN' => 'INNER JOIN', 'LEFT JOIN' => 'LEFT JOIN', 'RIGHT JOIN' => 'RIGHT JOIN', 'FULL JOIN' => 'FULL JOIN');
// Map of internal language name to syntax highlighting name
var $langmap = array(
'sql' => 'SQL',
'plpgsql' => 'SQL',
'php' => 'PHP',
'phpu' => 'PHP',
'plphp' => 'PHP',
'plphpu' => 'PHP',
'perl' => 'Perl',
'perlu' => 'Perl',
'plperl' => 'Perl',
'plperlu' => 'Perl',
'java' => 'Java',
'javau' => 'Java',
'pljava' => 'Java',
'pljavau' => 'Java',
'plj' => 'Java',
'plju' => 'Java',
'python' => 'Python',
'pythonu' => 'Python',
'plpython' => 'Python',
'plpythonu' => 'Python',
'ruby' => 'Ruby',
'rubyu' => 'Ruby',
'plruby' => 'Ruby',
'plrubyu' => 'Ruby'
);
// Predefined size types
var $predefined_size_types = array('abstime','aclitem','bigserial','boolean','bytea','cid','cidr','circle','date','float4','float8','gtsvector','inet','int2','int4','int8','macaddr','money','oid','path','polygon','refcursor','regclass','regoper','regoperator','regproc','regprocedure','regtype','reltime','serial','smgr','text','tid','tinterval','tsquery','tsvector','varbit','void','xid');
// List of all legal privileges that can be applied to different types
// of objects.
var $privlist = array(
'table' => array('SELECT', 'INSERT', 'UPDATE', 'DELETE', 'REFERENCES', 'TRIGGER', 'ALL PRIVILEGES'),
'view' => array('SELECT', 'INSERT', 'UPDATE', 'DELETE', 'REFERENCES', 'TRIGGER', 'ALL PRIVILEGES'),
'sequence' => array('SELECT', 'UPDATE', 'ALL PRIVILEGES'),
'database' => array('CREATE', 'TEMPORARY', 'CONNECT', 'ALL PRIVILEGES'),
'function' => array('EXECUTE', 'ALL PRIVILEGES'),
'language' => array('USAGE', 'ALL PRIVILEGES'),
'schema' => array('CREATE', 'USAGE', 'ALL PRIVILEGES'),
'tablespace' => array('CREATE', 'ALL PRIVILEGES'),
'column' => array('SELECT', 'INSERT', 'UPDATE', 'REFERENCES','ALL PRIVILEGES')
);
// List of characters in acl lists and the privileges they
// refer to.
var $privmap = array(
'r' => 'SELECT',
'w' => 'UPDATE',
'a' => 'INSERT',
'd' => 'DELETE',
'D' => 'TRUNCATE',
'R' => 'RULE',
'x' => 'REFERENCES',
't' => 'TRIGGER',
'X' => 'EXECUTE',
'U' => 'USAGE',
'C' => 'CREATE',
'T' => 'TEMPORARY',
'c' => 'CONNECT'
);
// Rule action types
var $rule_events = array('SELECT', 'INSERT', 'UPDATE', 'DELETE');
// Select operators
var $selectOps = array('=' => 'i', '!=' => 'i', '<' => 'i', '>' => 'i', '<=' => 'i', '>=' => 'i',
'<<' => 'i', '>>' => 'i', '<<=' => 'i', '>>=' => 'i',
'LIKE' => 'i', 'NOT LIKE' => 'i', 'ILIKE' => 'i', 'NOT ILIKE' => 'i', 'SIMILAR TO' => 'i',
'NOT SIMILAR TO' => 'i', '~' => 'i', '!~' => 'i', '~*' => 'i', '!~*' => 'i',
'IS NULL' => 'p', 'IS NOT NULL' => 'p', 'IN' => 'x', 'NOT IN' => 'x',
'@@' => 'i', '@@@' => 'i', '@>' => 'i', '<@' => 'i',
'@@ to_tsquery' => 't', '@@@ to_tsquery' => 't', '@> to_tsquery' => 't', '<@ to_tsquery' => 't',
'@@ plainto_tsquery' => 't', '@@@ plainto_tsquery' => 't', '@> plainto_tsquery' => 't', '<@ plainto_tsquery' => 't');
// Array of allowed trigger events
var $triggerEvents= array('INSERT', 'UPDATE', 'DELETE', 'INSERT OR UPDATE', 'INSERT OR DELETE',
'DELETE OR UPDATE', 'INSERT OR DELETE OR UPDATE');
// When to execute the trigger
var $triggerExecTimes = array('BEFORE', 'AFTER');
// How often to execute the trigger
var $triggerFrequency = array('ROW','STATEMENT');
// Array of allowed type alignments
var $typAligns = array('char', 'int2', 'int4', 'double');
// The default type alignment
var $typAlignDef = 'int4';
// Default index type
var $typIndexDef = 'BTREE';
// Array of allowed index types
var $typIndexes = array('BTREE', 'RTREE', 'GIST', 'GIN', 'HASH');
// Array of allowed type storage attributes
var $typStorages = array('plain', 'external', 'extended', 'main');
// The default type storage
var $typStorageDef = 'plain';
/**
* Constructor
* @param $conn The database connection
*/
function Postgres($conn) {
$this->ADODB_base($conn);
}
// Formatting functions
/**
* Cleans (escapes) a string
* @param $str The string to clean, by reference
* @return The cleaned string
*/
function clean(&$str) {
if ($str === null) return null;
$str = str_replace("\r\n","\n",$str);
$str = pg_escape_string($str);
return $str;
}
/**
* Cleans (escapes) an object name (eg. table, field)
* @param $str The string to clean, by reference
* @return The cleaned string
*/
function fieldClean(&$str) {
if ($str === null) return null;
$str = str_replace('"', '""', $str);
return $str;
}
/**
* Cleans (escapes) an array of field names
* @param $arr The array to clean, by reference
* @return The cleaned array
*/
function fieldArrayClean(&$arr) {
foreach ($arr as $k => $v) {
if ($v === null) continue;
$arr[$k] = str_replace('"', '""', $v);
}
return $arr;
}
/**
* Cleans (escapes) an array
* @param $arr The array to clean, by reference
* @return The cleaned array
*/
function arrayClean(&$arr) {
foreach ($arr as $k => $v) {
if ($v === null) continue;
$arr[$k] = pg_escape_string($v);
}
return $arr;
}
/**
* Escapes bytea data for display on the screen
* @param $data The bytea data
* @return Data formatted for on-screen display
*/
function escapeBytea($data) {
return $data;
}
/**
* Outputs the HTML code for a particular field
* @param $name The name to give the field
* @param $value The value of the field. Note this could be 'numeric(7,2)' sort of thing...
* @param $type The database type of the field
* @param $extras An array of attributes name as key and attributes' values as value
*/
function printField($name, $value, $type, $extras = array()) {
global $lang;
// Determine actions string
$extra_str = '';
foreach ($extras as $k => $v) {
$extra_str .= " {$k}=\"" . htmlspecialchars($v) . "\"";
}
switch (substr($type,0,9)) {
case 'bool':
case 'boolean':
if ($value !== null && $value == '') $value = null;
elseif ($value == 'true') $value = 't';
elseif ($value == 'false') $value = 'f';
// If value is null, 't' or 'f'...
if ($value === null || $value == 't' || $value == 'f') {
echo "<select name=\"", htmlspecialchars($name), "\"{$extra_str}>\n";
echo "<option value=\"\"", ($value === null) ? ' selected="selected"' : '', "></option>\n";
echo "<option value=\"t\"", ($value == 't') ? ' selected="selected"' : '', ">{$lang['strtrue']}</option>\n";
echo "<option value=\"f\"", ($value == 'f') ? ' selected="selected"' : '', ">{$lang['strfalse']}</option>\n";
echo "</select>\n";
}
else {
echo "<input name=\"", htmlspecialchars($name), "\" value=\"", htmlspecialchars($value), "\" size=\"35\"{$extra_str} />\n";
}
break;
case 'bytea':
case 'bytea[]':
if (!is_null($value)) {
$value = $this->escapeBytea($value);
}
case 'text':
case 'text[]':
case 'xml':
case 'xml[]':
$n = substr_count($value, "\n");
$n = $n < 5 ? 5 : $n;
$n = $n > 20 ? 20 : $n;
echo "<textarea name=\"", htmlspecialchars($name), "\" rows=\"{$n}\" cols=\"75\"{$extra_str}>\n";
echo htmlspecialchars($value);
echo "</textarea>\n";
break;
case 'character':
case 'character[]':
$n = substr_count($value, "\n");
$n = $n < 5 ? 5 : $n;
$n = $n > 20 ? 20 : $n;
echo "<textarea name=\"", htmlspecialchars($name), "\" rows=\"{$n}\" cols=\"35\"{$extra_str}>\n";
echo htmlspecialchars($value);
echo "</textarea>\n";
break;
default:
echo "<input name=\"", htmlspecialchars($name), "\" value=\"", htmlspecialchars($value), "\" size=\"35\"{$extra_str} />\n";
break;
}
}
/**
* Formats a value or expression for sql purposes
* @param $type The type of the field
* @param $format VALUE or EXPRESSION
* @param $value The actual value entered in the field. Can be NULL
* @return The suitably quoted and escaped value.
*/
function formatValue($type, $format, $value) {
switch ($type) {
case 'bool':
case 'boolean':
if ($value == 't')
return 'TRUE';
elseif ($value == 'f')
return 'FALSE';
elseif ($value == '')
return 'NULL';
else
return $value;
break;
default:
// Checking variable fields is difficult as there might be a size
// attribute...
if (strpos($type, 'time') === 0) {
// Assume it's one of the time types...
if ($value == '') return "''";
elseif (strcasecmp($value, 'CURRENT_TIMESTAMP') == 0
|| strcasecmp($value, 'CURRENT_TIME') == 0
|| strcasecmp($value, 'CURRENT_DATE') == 0
|| strcasecmp($value, 'LOCALTIME') == 0
|| strcasecmp($value, 'LOCALTIMESTAMP') == 0) {
return $value;
}
elseif ($format == 'EXPRESSION')
return $value;
else {
$this->clean($value);
return "'{$value}'";
}
}
else {
if ($format == 'VALUE') {
$this->clean($value);
return "'{$value}'";
}
return $value;
}
}
}
/**
* Formats a type correctly for display. Postgres 7.0 had no 'format_type'
* built-in function, and hence we need to do it manually.
* @param $typname The name of the type
* @param $typmod The contents of the typmod field
*/
function formatType($typname, $typmod) {
// This is a specific constant in the 7.0 source
$varhdrsz = 4;
// If the first character is an underscore, it's an array type
$is_array = false;
if (substr($typname, 0, 1) == '_') {
$is_array = true;
$typname = substr($typname, 1);
}
// Show lengths on bpchar and varchar
if ($typname == 'bpchar') {
$len = $typmod - $varhdrsz;
$temp = 'character';
if ($len > 1)
$temp .= "({$len})";
}
elseif ($typname == 'varchar') {
$temp = 'character varying';
if ($typmod != -1)
$temp .= "(" . ($typmod - $varhdrsz) . ")";
}
elseif ($typname == 'numeric') {
$temp = 'numeric';
if ($typmod != -1) {
$tmp_typmod = $typmod - $varhdrsz;
$precision = ($tmp_typmod >> 16) & 0xffff;
$scale = $tmp_typmod & 0xffff;
$temp .= "({$precision}, {$scale})";
}
}
else $temp = $typname;
// Add array qualifier if it's an array
if ($is_array) $temp .= '[]';
return $temp;
}
// Help functions
/**
* Fetch a URL (or array of URLs) for a given help page.
*/
function getHelp($help) {
$this->getHelpPages();
if (isset($this->help_page[$help])) {
if (is_array($this->help_page[$help])) {
$urls = array();
foreach ($this->help_page[$help] as $link) {
$urls[] = $this->help_base . $link;
}
return $urls;
} else
return $this->help_base . $this->help_page[$help];
} else
return null;
}
function getHelpPages() {
include_once('./help/PostgresDoc92.php');
return $this->help_page;
}
// Database functions
/**
* Return all information about a particular database
* @param $database The name of the database to retrieve
* @return The database info
*/
function getDatabase($database) {
$this->clean($database);
$sql = "SELECT * FROM pg_database WHERE datname='{$database}'";
return $this->selectSet($sql);
}
/**
* Return all database available on the server
* @param $currentdatabase database name that should be on top of the resultset
*
* @return A list of databases, sorted alphabetically
*/
function getDatabases($currentdatabase = NULL) {
global $conf, $misc;
$server_info = $misc->getServerInfo();
if (isset($conf['owned_only']) && $conf['owned_only'] && !$this->isSuperUser()) {
$username = $server_info['username'];
$this->clean($username);
$clause = " AND pr.rolname='{$username}'";
}
else $clause = '';
if ($currentdatabase != NULL) {
$this->clean($currentdatabase);
$orderby = "ORDER BY pdb.datname = '{$currentdatabase}' DESC, pdb.datname";
}
else
$orderby = "ORDER BY pdb.datname";
if (!$conf['show_system'])
$where = ' AND NOT pdb.datistemplate';
else
$where = ' AND pdb.datallowconn';
$sql = "
SELECT pdb.datname AS datname, pr.rolname AS datowner, pg_encoding_to_char(encoding) AS datencoding,
(SELECT description FROM pg_catalog.pg_shdescription pd WHERE pdb.oid=pd.objoid AND pd.classoid='pg_database'::regclass) AS datcomment,
(SELECT spcname FROM pg_catalog.pg_tablespace pt WHERE pt.oid=pdb.dattablespace) AS tablespace,
CASE WHEN pg_catalog.has_database_privilege(current_user, pdb.oid, 'CONNECT')
THEN pg_catalog.pg_database_size(pdb.oid)
ELSE -1 -- set this magic value, which we will convert to no access later
END as dbsize, pdb.datcollate, pdb.datctype
FROM pg_catalog.pg_database pdb
LEFT JOIN pg_catalog.pg_roles pr ON (pdb.datdba = pr.oid)
WHERE true
{$where}
{$clause}
{$orderby}";
return $this->selectSet($sql);
}
/**
* Return the database comment of a db from the shared description table
* @param string $database the name of the database to get the comment for
* @return recordset of the db comment info
*/
function getDatabaseComment($database) {
$this->clean($database);
$sql = "SELECT description FROM pg_catalog.pg_database JOIN pg_catalog.pg_shdescription ON (oid=objoid AND classoid='pg_database'::regclass) WHERE pg_database.datname = '{$database}' ";
return $this->selectSet($sql);
}
/**
* Return the database owner of a db
* @param string $database the name of the database to get the owner for
* @return recordset of the db owner info
*/
function getDatabaseOwner($database) {
$this->clean($database);
$sql = "SELECT usename FROM pg_user, pg_database WHERE pg_user.usesysid = pg_database.datdba AND pg_database.datname = '{$database}' ";
return $this->selectSet($sql);
}
/**
* Returns the current database encoding
* @return The encoding. eg. SQL_ASCII, UTF-8, etc.
*/
function getDatabaseEncoding() {
return pg_parameter_status($this->conn->_connectionID, 'server_encoding');
}
/**
* Returns the current default_with_oids setting
* @return default_with_oids setting
*/
function getDefaultWithOid() {
$sql = "SHOW default_with_oids";
return $this->selectField($sql, 'default_with_oids');
}
/**
* Creates a database
* @param $database The name of the database to create
* @param $encoding Encoding of the database
* @param $tablespace (optional) The tablespace name
* @return 0 success
* @return -1 tablespace error
* @return -2 comment error
*/
function createDatabase($database, $encoding, $tablespace = '', $comment = '', $template = 'template1',
$lc_collate = '', $lc_ctype = '')
{
$this->fieldClean($database);
$this->clean($encoding);
$this->fieldClean($tablespace);
$this->fieldClean($template);
$this->clean($lc_collate);
$this->clean($lc_ctype);
$sql = "CREATE DATABASE \"{$database}\" WITH TEMPLATE=\"{$template}\"";
if ($encoding != '') $sql .= " ENCODING='{$encoding}'";
if ($lc_collate != '') $sql .= " LC_COLLATE='{$lc_collate}'";
if ($lc_ctype != '') $sql .= " LC_CTYPE='{$lc_ctype}'";
if ($tablespace != '' && $this->hasTablespaces()) $sql .= " TABLESPACE \"{$tablespace}\"";
$status = $this->execute($sql);
if ($status != 0) return -1;
if ($comment != '' && $this->hasSharedComments()) {
$status = $this->setComment('DATABASE',$database,'',$comment);
if ($status != 0) return -2;
}
return 0;
}
/**
* Renames a database, note that this operation cannot be
* performed on a database that is currently being connected to
* @param string $oldName name of database to rename
* @param string $newName new name of database
* @return int 0 on success
*/
function alterDatabaseRename($oldName, $newName) {
$this->fieldClean($oldName);
$this->fieldClean($newName);
if ($oldName != $newName) {
$sql = "ALTER DATABASE \"{$oldName}\" RENAME TO \"{$newName}\"";
return $this->execute($sql);
}
else //just return success, we're not going to do anything
return 0;
}
/**
* Drops a database
* @param $database The name of the database to drop
* @return 0 success
*/
function dropDatabase($database) {
$this->fieldClean($database);
$sql = "DROP DATABASE \"{$database}\"";
return $this->execute($sql);
}
/**
* Changes ownership of a database
* This can only be done by a superuser or the owner of the database
* @param string $dbName database to change ownership of
* @param string $newOwner user that will own the database
* @return int 0 on success
*/
function alterDatabaseOwner($dbName, $newOwner) {
$this->fieldClean($dbName);
$this->fieldClean($newOwner);
$sql = "ALTER DATABASE \"{$dbName}\" OWNER TO \"{$newOwner}\"";
return $this->execute($sql);
}
/**
* Alters a database
* the multiple return vals are for postgres 8+ which support more functionality in alter database
* @param $dbName The name of the database
* @param $newName new name for the database
* @param $newOwner The new owner for the database
* @return 0 success
* @return -1 transaction error
* @return -2 owner error
* @return -3 rename error
* @return -4 comment error
*/
function alterDatabase($dbName, $newName, $newOwner = '', $comment = '') {
$status = $this->beginTransaction();
if ($status != 0) {
$this->rollbackTransaction();
return -1;
}
if ($dbName != $newName) {
$status = $this->alterDatabaseRename($dbName, $newName);
if ($status != 0) {
$this->rollbackTransaction();
return -3;
}
$dbName = $newName;
}
if ($newOwner != '') {
$status = $this->alterDatabaseOwner($newName, $newOwner);
if ($status != 0) {
$this->rollbackTransaction();
return -2;
}
}
$this->fieldClean($dbName);
$status = $this->setComment('DATABASE', $dbName, '', $comment);
if ($status != 0) {
$this->rollbackTransaction();
return -4;
}
return $this->endTransaction();
}
/**
* Returns prepared transactions information
* @param $database (optional) Find only prepared transactions executed in a specific database
* @return A recordset
*/
function getPreparedXacts($database = null) {
if ($database === null)
$sql = "SELECT * FROM pg_prepared_xacts";
else {
$this->clean($database);
$sql = "SELECT transaction, gid, prepared, owner FROM pg_prepared_xacts
WHERE database='{$database}' ORDER BY owner";
}
return $this->selectSet($sql);
}
/**
* Searches all system catalogs to find objects that match a certain name.
* @param $term The search term
* @param $filter The object type to restrict to ('' means no restriction)
* @return A recordset
*/
function findObject($term, $filter) {
global $conf;
/*about escaping:
* SET standard_conforming_string is not available before 8.2
* So we must use PostgreSQL specific notation :/
* E'' notation is not available before 8.1
* $$ is available since 8.0
* Nothing specific from 7.4
**/
// Escape search term for ILIKE match
$this->clean($term);
$this->clean($filter);
$term = str_replace('_', '\_', $term);
$term = str_replace('%', '\%', $term);
// Exclude system relations if necessary
if (!$conf['show_system']) {
// XXX: The mention of information_schema here is in the wrong place, but
// it's the quickest fix to exclude the info schema from 7.4
$where = " AND pn.nspname NOT LIKE \$_PATERN_\$pg\_%\$_PATERN_\$ AND pn.nspname != 'information_schema'";
$lan_where = "AND pl.lanispl";
}
else {
$where = '';
$lan_where = '';
}
// Apply outer filter
$sql = '';
if ($filter != '') {
$sql = "SELECT * FROM (";
}
$term = "\$_PATERN_\$%{$term}%\$_PATERN_\$";
$sql .= "
SELECT 'SCHEMA' AS type, oid, NULL AS schemaname, NULL AS relname, nspname AS name
FROM pg_catalog.pg_namespace pn WHERE nspname ILIKE {$term} {$where}
UNION ALL
SELECT CASE WHEN relkind='r' THEN 'TABLE' WHEN relkind='v' THEN 'VIEW' WHEN relkind='S' THEN 'SEQUENCE' END, pc.oid,
pn.nspname, NULL, pc.relname FROM pg_catalog.pg_class pc, pg_catalog.pg_namespace pn
WHERE pc.relnamespace=pn.oid AND relkind IN ('r', 'v', 'S') AND relname ILIKE {$term} {$where}
UNION ALL
SELECT CASE WHEN pc.relkind='r' THEN 'COLUMNTABLE' ELSE 'COLUMNVIEW' END, NULL, pn.nspname, pc.relname, pa.attname FROM pg_catalog.pg_class pc, pg_catalog.pg_namespace pn,
pg_catalog.pg_attribute pa WHERE pc.relnamespace=pn.oid AND pc.oid=pa.attrelid
AND pa.attname ILIKE {$term} AND pa.attnum > 0 AND NOT pa.attisdropped AND pc.relkind IN ('r', 'v') {$where}
UNION ALL
SELECT 'FUNCTION', pp.oid, pn.nspname, NULL, pp.proname || '(' || pg_catalog.oidvectortypes(pp.proargtypes) || ')' FROM pg_catalog.pg_proc pp, pg_catalog.pg_namespace pn
WHERE pp.pronamespace=pn.oid AND NOT pp.proisagg AND pp.proname ILIKE {$term} {$where}
UNION ALL
SELECT 'INDEX', NULL, pn.nspname, pc.relname, pc2.relname FROM pg_catalog.pg_class pc, pg_catalog.pg_namespace pn,
pg_catalog.pg_index pi, pg_catalog.pg_class pc2 WHERE pc.relnamespace=pn.oid AND pc.oid=pi.indrelid
AND pi.indexrelid=pc2.oid
AND NOT EXISTS (
SELECT 1 FROM pg_catalog.pg_depend d JOIN pg_catalog.pg_constraint c
ON (d.refclassid = c.tableoid AND d.refobjid = c.oid)
WHERE d.classid = pc2.tableoid AND d.objid = pc2.oid AND d.deptype = 'i' AND c.contype IN ('u', 'p')
)
AND pc2.relname ILIKE {$term} {$where}
UNION ALL
SELECT 'CONSTRAINTTABLE', NULL, pn.nspname, pc.relname, pc2.conname FROM pg_catalog.pg_class pc, pg_catalog.pg_namespace pn,
pg_catalog.pg_constraint pc2 WHERE pc.relnamespace=pn.oid AND pc.oid=pc2.conrelid AND pc2.conrelid != 0
AND CASE WHEN pc2.contype IN ('f', 'c') THEN TRUE ELSE NOT EXISTS (
SELECT 1 FROM pg_catalog.pg_depend d JOIN pg_catalog.pg_constraint c
ON (d.refclassid = c.tableoid AND d.refobjid = c.oid)
WHERE d.classid = pc2.tableoid AND d.objid = pc2.oid AND d.deptype = 'i' AND c.contype IN ('u', 'p')
) END
AND pc2.conname ILIKE {$term} {$where}
UNION ALL
SELECT 'CONSTRAINTDOMAIN', pt.oid, pn.nspname, pt.typname, pc.conname FROM pg_catalog.pg_type pt, pg_catalog.pg_namespace pn,
pg_catalog.pg_constraint pc WHERE pt.typnamespace=pn.oid AND pt.oid=pc.contypid AND pc.contypid != 0
AND pc.conname ILIKE {$term} {$where}
UNION ALL
SELECT 'TRIGGER', NULL, pn.nspname, pc.relname, pt.tgname FROM pg_catalog.pg_class pc, pg_catalog.pg_namespace pn,
pg_catalog.pg_trigger pt WHERE pc.relnamespace=pn.oid AND pc.oid=pt.tgrelid
AND ( pt.tgconstraint = 0 OR NOT EXISTS
(SELECT 1 FROM pg_catalog.pg_depend d JOIN pg_catalog.pg_constraint c
ON (d.refclassid = c.tableoid AND d.refobjid = c.oid)
WHERE d.classid = pt.tableoid AND d.objid = pt.oid AND d.deptype = 'i' AND c.contype = 'f'))
AND pt.tgname ILIKE {$term} {$where}
UNION ALL
SELECT 'RULETABLE', NULL, pn.nspname AS schemaname, c.relname AS tablename, r.rulename FROM pg_catalog.pg_rewrite r
JOIN pg_catalog.pg_class c ON c.oid = r.ev_class
LEFT JOIN pg_catalog.pg_namespace pn ON pn.oid = c.relnamespace
WHERE c.relkind='r' AND r.rulename != '_RETURN' AND r.rulename ILIKE {$term} {$where}
UNION ALL
SELECT 'RULEVIEW', NULL, pn.nspname AS schemaname, c.relname AS tablename, r.rulename FROM pg_catalog.pg_rewrite r
JOIN pg_catalog.pg_class c ON c.oid = r.ev_class
LEFT JOIN pg_catalog.pg_namespace pn ON pn.oid = c.relnamespace
WHERE c.relkind='v' AND r.rulename != '_RETURN' AND r.rulename ILIKE {$term} {$where}
";
// Add advanced objects if show_advanced is set
if ($conf['show_advanced']) {
$sql .= "
UNION ALL
SELECT CASE WHEN pt.typtype='d' THEN 'DOMAIN' ELSE 'TYPE' END, pt.oid, pn.nspname, NULL,
pt.typname FROM pg_catalog.pg_type pt, pg_catalog.pg_namespace pn
WHERE pt.typnamespace=pn.oid AND typname ILIKE {$term}
AND (pt.typrelid = 0 OR (SELECT c.relkind = 'c' FROM pg_catalog.pg_class c WHERE c.oid = pt.typrelid))
{$where}
UNION ALL
SELECT 'OPERATOR', po.oid, pn.nspname, NULL, po.oprname FROM pg_catalog.pg_operator po, pg_catalog.pg_namespace pn
WHERE po.oprnamespace=pn.oid AND oprname ILIKE {$term} {$where}
UNION ALL
SELECT 'CONVERSION', pc.oid, pn.nspname, NULL, pc.conname FROM pg_catalog.pg_conversion pc,
pg_catalog.pg_namespace pn WHERE pc.connamespace=pn.oid AND conname ILIKE {$term} {$where}
UNION ALL
SELECT 'LANGUAGE', pl.oid, NULL, NULL, pl.lanname FROM pg_catalog.pg_language pl
WHERE lanname ILIKE {$term} {$lan_where}
UNION ALL
SELECT DISTINCT ON (p.proname) 'AGGREGATE', p.oid, pn.nspname, NULL, p.proname FROM pg_catalog.pg_proc p
LEFT JOIN pg_catalog.pg_namespace pn ON p.pronamespace=pn.oid
WHERE p.proisagg AND p.proname ILIKE {$term} {$where}
UNION ALL
SELECT DISTINCT ON (po.opcname) 'OPCLASS', po.oid, pn.nspname, NULL, po.opcname FROM pg_catalog.pg_opclass po,
pg_catalog.pg_namespace pn WHERE po.opcnamespace=pn.oid
AND po.opcname ILIKE {$term} {$where}
";
}
// Otherwise just add domains
else {
$sql .= "
UNION ALL
SELECT 'DOMAIN', pt.oid, pn.nspname, NULL,
pt.typname FROM pg_catalog.pg_type pt, pg_catalog.pg_namespace pn
WHERE pt.typnamespace=pn.oid AND pt.typtype='d' AND typname ILIKE {$term}
AND (pt.typrelid = 0 OR (SELECT c.relkind = 'c' FROM pg_catalog.pg_class c WHERE c.oid = pt.typrelid))
{$where}
";
}
if ($filter != '') {
// We use like to make RULE, CONSTRAINT and COLUMN searches work
$sql .= ") AS sub WHERE type LIKE '{$filter}%' ";
}
$sql .= "ORDER BY type, schemaname, relname, name";
return $this->selectSet($sql);
}
/**
* Returns all available variable information.
* @return A recordset
*/
function getVariables() {
$sql = "SHOW ALL";
return $this->selectSet($sql);
}
// Schema functons
/**
* Return all schemas in the current database.
* @return All schemas, sorted alphabetically
*/
function getSchemas() {
global $conf;
if (!$conf['show_system']) {
$where = "WHERE nspname NOT LIKE 'pg@_%' ESCAPE '@' AND nspname != 'information_schema'";
}
else $where = "WHERE nspname !~ '^pg_t(emp_[0-9]+|oast)$'";
$sql = "
SELECT pn.nspname, pu.rolname AS nspowner,
pg_catalog.obj_description(pn.oid, 'pg_namespace') AS nspcomment
FROM pg_catalog.pg_namespace pn
LEFT JOIN pg_catalog.pg_roles pu ON (pn.nspowner = pu.oid)
{$where}
ORDER BY nspname";
return $this->selectSet($sql);
}
/**
* Return all information relating to a schema
* @param $schema The name of the schema
* @return Schema information
*/
function getSchemaByName($schema) {
$this->clean($schema);
$sql = "
SELECT nspname, nspowner, r.rolname AS ownername, nspacl,
pg_catalog.obj_description(pn.oid, 'pg_namespace') as nspcomment
FROM pg_catalog.pg_namespace pn
LEFT JOIN pg_roles as r ON pn.nspowner = r.oid
WHERE nspname='{$schema}'";
return $this->selectSet($sql);
}
/**
* Sets the current working schema. Will also set Class variable.
* @param $schema The the name of the schema to work in
* @return 0 success
*/
function setSchema($schema) {
// Get the current schema search path, including 'pg_catalog'.
$search_path = $this->getSearchPath();
// Prepend $schema to search path
array_unshift($search_path, $schema);
$status = $this->setSearchPath($search_path);
if ($status == 0) {
$this->_schema = $schema;
return 0;
}
else return $status;
}
/**
* Sets the current schema search path
* @param $paths An array of schemas in required search order
* @return 0 success
* @return -1 Array not passed
* @return -2 Array must contain at least one item
*/
function setSearchPath($paths) {
if (!is_array($paths)) return -1;
elseif (sizeof($paths) == 0) return -2;
elseif (sizeof($paths) == 1 && $paths[0] == '') {
// Need to handle empty paths in some cases
$paths[0] = 'pg_catalog';
}
// Loop over all the paths to check that none are empty
$temp = array();
foreach ($paths as $schema) {
if ($schema != '') $temp[] = $schema;
}
$this->fieldArrayClean($temp);
$sql = 'SET SEARCH_PATH TO "' . implode('","', $temp) . '"';
return $this->execute($sql);
}
/**
* Creates a new schema.
* @param $schemaname The name of the schema to create
* @param $authorization (optional) The username to create the schema for.
* @param $comment (optional) If omitted, defaults to nothing
* @return 0 success
*/
function createSchema($schemaname, $authorization = '', $comment = '') {
$this->fieldClean($schemaname);
$this->fieldClean($authorization);
$sql = "CREATE SCHEMA \"{$schemaname}\"";
if ($authorization != '') $sql .= " AUTHORIZATION \"{$authorization}\"";
if ($comment != '') {
$status = $this->beginTransaction();
if ($status != 0) return -1;
}
// Create the new schema
$status = $this->execute($sql);
if ($status != 0) {
$this->rollbackTransaction();
return -1;
}
// Set the comment
if ($comment != '') {
$status = $this->setComment('SCHEMA', $schemaname, '', $comment);
if ($status != 0) {
$this->rollbackTransaction();
return -1;
}
return $this->endTransaction();
}
return 0;
}
/**
* Updates a schema.
* @param $schemaname The name of the schema to drop
* @param $comment The new comment for this schema
* @param $owner The new owner for this schema
* @return 0 success
*/
function updateSchema($schemaname, $comment, $name, $owner) {
$this->fieldClean($schemaname);
$this->fieldClean($name);
$this->fieldClean($owner);
$status = $this->beginTransaction();
if ($status != 0) {
$this->rollbackTransaction();
return -1;
}
$status = $this->setComment('SCHEMA', $schemaname, '', $comment);
if ($status != 0) {
$this->rollbackTransaction();
return -1;
}
$schema_rs = $this->getSchemaByName($schemaname);
/* Only if the owner change */
if ($schema_rs->fields['ownername'] != $owner) {
$sql = "ALTER SCHEMA \"{$schemaname}\" OWNER TO \"{$owner}\"";
$status = $this->execute($sql);
if ($status != 0) {
$this->rollbackTransaction();
return -1;
}
}
// Only if the name has changed
if ($name != $schemaname) {
$sql = "ALTER SCHEMA \"{$schemaname}\" RENAME TO \"{$name}\"";
$status = $this->execute($sql);
if ($status != 0) {
$this->rollbackTransaction();
return -1;
}
}
return $this->endTransaction();
}
/**
* Drops a schema.
* @param $schemaname The name of the schema to drop
* @param $cascade True to cascade drop, false to restrict
* @return 0 success
*/
function dropSchema($schemaname, $cascade) {
$this->fieldClean($schemaname);
$sql = "DROP SCHEMA \"{$schemaname}\"";
if ($cascade) $sql .= " CASCADE";
return $this->execute($sql);
}
/**
* Return the current schema search path
* @return Array of schema names
*/
function getSearchPath() {
$sql = 'SELECT current_schemas(false) AS search_path';
return $this->phpArray($this->selectField($sql, 'search_path'));
}
// Table functions
/**
* Checks to see whether or not a table has a unique id column
* @param $table The table name
* @return True if it has a unique id, false otherwise
* @return null error
**/
function hasObjectID($table) {
$c_schema = $this->_schema;
$this->clean($c_schema);
$this->clean($table);
$sql = "SELECT relhasoids FROM pg_catalog.pg_class WHERE relname='{$table}'
AND relnamespace = (SELECT oid FROM pg_catalog.pg_namespace WHERE nspname='{$c_schema}')";
$rs = $this->selectSet($sql);
if ($rs->recordCount() != 1) return null;
else {
$rs->fields['relhasoids'] = $this->phpBool($rs->fields['relhasoids']);
return $rs->fields['relhasoids'];
}
}
/**
* Returns table information
* @param $table The name of the table
* @return A recordset
*/
function getTable($table) {
$c_schema = $this->_schema;
$this->clean($c_schema);
$this->clean($table);
$sql = "
SELECT
c.relname, n.nspname, u.usename AS relowner,
pg_catalog.obj_description(c.oid, 'pg_class') AS relcomment,
(SELECT spcname FROM pg_catalog.pg_tablespace pt WHERE pt.oid=c.reltablespace) AS tablespace
FROM pg_catalog.pg_class c
LEFT JOIN pg_catalog.pg_user u ON u.usesysid = c.relowner
LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
WHERE c.relkind = 'r'
AND n.nspname = '{$c_schema}'
AND n.oid = c.relnamespace
AND c.relname = '{$table}'";
return $this->selectSet($sql);
}
/**
* Return all tables in current database (and schema)
* @param $all True to fetch all tables, false for just in current schema
* @return All tables, sorted alphabetically
*/
function getTables($all = false) {
$c_schema = $this->_schema;
$this->clean($c_schema);
if ($all) {
// Exclude pg_catalog and information_schema tables
$sql = "SELECT schemaname AS nspname, tablename AS relname, tableowner AS relowner
FROM pg_catalog.pg_tables
WHERE schemaname NOT IN ('pg_catalog', 'information_schema', 'pg_toast')
ORDER BY schemaname, tablename";
} else {
$sql = "SELECT c.relname, pg_catalog.pg_get_userbyid(c.relowner) AS relowner,
pg_catalog.obj_description(c.oid, 'pg_class') AS relcomment,
reltuples::bigint,
(SELECT spcname FROM pg_catalog.pg_tablespace pt WHERE pt.oid=c.reltablespace) AS tablespace
FROM pg_catalog.pg_class c
LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
WHERE c.relkind = 'r'
AND nspname='{$c_schema}'
ORDER BY c.relname";
}
return $this->selectSet($sql);
}
/**
* Retrieve the attribute definition of a table
* @param $table The name of the table
* @param $field (optional) The name of a field to return
* @return All attributes in order
*/
function getTableAttributes($table, $field = '') {
$c_schema = $this->_schema;
$this->clean($c_schema);
$this->clean($table);
$this->clean($field);
if ($field == '') {
// This query is made much more complex by the addition of the 'attisserial' field.
// The subquery to get that field checks to see if there is an internally dependent
// sequence on the field.
$sql = "
SELECT
a.attname, a.attnum,
pg_catalog.format_type(a.atttypid, a.atttypmod) as type,
a.atttypmod,
a.attnotnull, a.atthasdef, pg_catalog.pg_get_expr(adef.adbin, adef.adrelid, true) as adsrc,
a.attstattarget, a.attstorage, t.typstorage,
(
SELECT 1 FROM pg_catalog.pg_depend pd, pg_catalog.pg_class pc
WHERE pd.objid=pc.oid
AND pd.classid=pc.tableoid
AND pd.refclassid=pc.tableoid
AND pd.refobjid=a.attrelid
AND pd.refobjsubid=a.attnum
AND pd.deptype='i'
AND pc.relkind='S'
) IS NOT NULL AS attisserial,
pg_catalog.col_description(a.attrelid, a.attnum) AS comment
FROM
pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_attrdef adef
ON a.attrelid=adef.adrelid
AND a.attnum=adef.adnum
LEFT JOIN pg_catalog.pg_type t ON a.atttypid=t.oid
WHERE
a.attrelid = (SELECT oid FROM pg_catalog.pg_class WHERE relname='{$table}'
AND relnamespace = (SELECT oid FROM pg_catalog.pg_namespace WHERE
nspname = '{$c_schema}'))
AND a.attnum > 0 AND NOT a.attisdropped
ORDER BY a.attnum";
}
else {
$sql = "
SELECT
a.attname, a.attnum,
pg_catalog.format_type(a.atttypid, a.atttypmod) as type,
pg_catalog.format_type(a.atttypid, NULL) as base_type,
a.atttypmod,
a.attnotnull, a.atthasdef, pg_catalog.pg_get_expr(adef.adbin, adef.adrelid, true) as adsrc,
a.attstattarget, a.attstorage, t.typstorage,
pg_catalog.col_description(a.attrelid, a.attnum) AS comment
FROM
pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_attrdef adef
ON a.attrelid=adef.adrelid
AND a.attnum=adef.adnum
LEFT JOIN pg_catalog.pg_type t ON a.atttypid=t.oid
WHERE
a.attrelid = (SELECT oid FROM pg_catalog.pg_class WHERE relname='{$table}'
AND relnamespace = (SELECT oid FROM pg_catalog.pg_namespace WHERE
nspname = '{$c_schema}'))
AND a.attname = '{$field}'";
}
return $this->selectSet($sql);
}
/**
* Finds the names and schemas of parent tables (in order)
* @param $table The table to find the parents for
* @return A recordset
*/
function getTableParents($table) {
$c_schema = $this->_schema;
$this->clean($c_schema);
$this->clean($table);
$sql = "
SELECT
pn.nspname, relname
FROM
pg_catalog.pg_class pc, pg_catalog.pg_inherits pi, pg_catalog.pg_namespace pn
WHERE
pc.oid=pi.inhparent
AND pc.relnamespace=pn.oid
AND pi.inhrelid = (SELECT oid from pg_catalog.pg_class WHERE relname='{$table}'
AND relnamespace = (SELECT oid FROM pg_catalog.pg_namespace WHERE nspname = '{$c_schema}'))
ORDER BY
pi.inhseqno
";
return $this->selectSet($sql);
}
/**
* Finds the names and schemas of child tables
* @param $table The table to find the children for
* @return A recordset
*/
function getTableChildren($table) {
$c_schema = $this->_schema;
$this->clean($c_schema);
$this->clean($table);
$sql = "
SELECT
pn.nspname, relname
FROM
pg_catalog.pg_class pc, pg_catalog.pg_inherits pi, pg_catalog.pg_namespace pn
WHERE
pc.oid=pi.inhrelid
AND pc.relnamespace=pn.oid
AND pi.inhparent = (SELECT oid from pg_catalog.pg_class WHERE relname='{$table}'
AND relnamespace = (SELECT oid FROM pg_catalog.pg_namespace WHERE nspname = '{$c_schema}'))
";
return $this->selectSet($sql);
}
/**
* Returns the SQL definition for the table.
* @pre MUST be run within a transaction
* @param $table The table to define
* @param $clean True to issue drop command, false otherwise
* @return A string containing the formatted SQL code
* @return null On error
*/
function getTableDefPrefix($table, $clean = false) {
// Fetch table
$t = $this->getTable($table);
if (!is_object($t) || $t->recordCount() != 1) {
$this->rollbackTransaction();
return null;
}
$this->fieldClean($t->fields['relname']);
$this->fieldClean($t->fields['nspname']);
// Fetch attributes
$atts = $this->getTableAttributes($table);
if (!is_object($atts)) {
$this->rollbackTransaction();
return null;
}
// Fetch constraints
$cons = $this->getConstraints($table);
if (!is_object($cons)) {
$this->rollbackTransaction();
return null;
}
// Output a reconnect command to create the table as the correct user
$sql = $this->getChangeUserSQL($t->fields['relowner']) . "\n\n";
// Set schema search path
$sql .= "SET search_path = \"{$t->fields['nspname']}\", pg_catalog;\n\n";
// Begin CREATE TABLE definition
$sql .= "-- Definition\n\n";
// DROP TABLE must be fully qualified in case a table with the same name exists
// in pg_catalog.
if (!$clean) $sql .= "-- ";
$sql .= "DROP TABLE ";
$sql .= "\"{$t->fields['nspname']}\".\"{$t->fields['relname']}\";\n";
$sql .= "CREATE TABLE \"{$t->fields['nspname']}\".\"{$t->fields['relname']}\" (\n";
// Output all table columns
$col_comments_sql = ''; // Accumulate comments on columns
$num = $atts->recordCount() + $cons->recordCount();
$i = 1;
while (!$atts->EOF) {
$this->fieldClean($atts->fields['attname']);
$sql .= " \"{$atts->fields['attname']}\"";
// Dump SERIAL and BIGSERIAL columns correctly
if ($this->phpBool($atts->fields['attisserial']) &&
($atts->fields['type'] == 'integer' || $atts->fields['type'] == 'bigint')) {
if ($atts->fields['type'] == 'integer')
$sql .= " SERIAL";
else
$sql .= " BIGSERIAL";
}
else {
$sql .= " " . $this->formatType($atts->fields['type'], $atts->fields['atttypmod']);
// Add NOT NULL if necessary
if ($this->phpBool($atts->fields['attnotnull']))
$sql .= " NOT NULL";
// Add default if necessary
if ($atts->fields['adsrc'] !== null)
$sql .= " DEFAULT {$atts->fields['adsrc']}";
}
// Output comma or not
if ($i < $num) $sql .= ",\n";
else $sql .= "\n";
// Does this column have a comment?
if ($atts->fields['comment'] !== null) {
$this->clean($atts->fields['comment']);
$col_comments_sql .= "COMMENT ON COLUMN \"{$t->fields['relname']}\".\"{$atts->fields['attname']}\" IS '{$atts->fields['comment']}';\n";
}
$atts->moveNext();
$i++;
}
// Output all table constraints
while (!$cons->EOF) {
$this->fieldClean($cons->fields['conname']);
$sql .= " CONSTRAINT \"{$cons->fields['conname']}\" ";
// Nasty hack to support pre-7.4 PostgreSQL
if ($cons->fields['consrc'] !== null)
$sql .= $cons->fields['consrc'];
else {
switch ($cons->fields['contype']) {
case 'p':
$keys = $this->getAttributeNames($table, explode(' ', $cons->fields['indkey']));
$sql .= "PRIMARY KEY (" . join(',', $keys) . ")";
break;
case 'u':
$keys = $this->getAttributeNames($table, explode(' ', $cons->fields['indkey']));
$sql .= "UNIQUE (" . join(',', $keys) . ")";
break;
default:
// Unrecognised constraint
$this->rollbackTransaction();
return null;
}
}
// Output comma or not
if ($i < $num) $sql .= ",\n";
else $sql .= "\n";
$cons->moveNext();
$i++;
}
$sql .= ")";
// @@@@ DUMP CLUSTERING INFORMATION
// Inherits
/*
* XXX: This is currently commented out as handling inheritance isn't this simple.
* You also need to make sure you don't dump inherited columns and defaults, as well
* as inherited NOT NULL and CHECK constraints. So for the time being, we just do
* not claim to support inheritance.
$parents = $this->getTableParents($table);
if ($parents->recordCount() > 0) {
$sql .= " INHERITS (";
while (!$parents->EOF) {
$this->fieldClean($parents->fields['relname']);
// Qualify the parent table if it's in another schema
if ($parents->fields['schemaname'] != $this->_schema) {
$this->fieldClean($parents->fields['schemaname']);
$sql .= "\"{$parents->fields['schemaname']}\".";
}
$sql .= "\"{$parents->fields['relname']}\"";
$parents->moveNext();
if (!$parents->EOF) $sql .= ', ';
}
$sql .= ")";
}
*/
// Handle WITHOUT OIDS
if ($this->hasObjectID($table))
$sql .= " WITH OIDS";
else
$sql .= " WITHOUT OIDS";
$sql .= ";\n";
// Column storage and statistics
$atts->moveFirst();
$first = true;
while (!$atts->EOF) {
$this->fieldClean($atts->fields['attname']);
// Statistics first
if ($atts->fields['attstattarget'] >= 0) {
if ($first) {
$sql .= "\n";
$first = false;
}
$sql .= "ALTER TABLE ONLY \"{$t->fields['nspname']}\".\"{$t->fields['relname']}\" ALTER COLUMN \"{$atts->fields['attname']}\" SET STATISTICS {$atts->fields['attstattarget']};\n";
}
// Then storage
if ($atts->fields['attstorage'] != $atts->fields['typstorage']) {
switch ($atts->fields['attstorage']) {
case 'p':
$storage = 'PLAIN';
break;
case 'e':
$storage = 'EXTERNAL';
break;
case 'm':
$storage = 'MAIN';
break;
case 'x':
$storage = 'EXTENDED';
break;
default:
// Unknown storage type
$this->rollbackTransaction();
return null;
}
$sql .= "ALTER TABLE ONLY \"{$t->fields['nspname']}\".\"{$t->fields['relname']}\" ALTER COLUMN \"{$atts->fields['attname']}\" SET STORAGE {$storage};\n";
}
$atts->moveNext();
}
// Comment
if ($t->fields['relcomment'] !== null) {
$this->clean($t->fields['relcomment']);
$sql .= "\n-- Comment\n\n";
$sql .= "COMMENT ON TABLE \"{$t->fields['nspname']}\".\"{$t->fields['relname']}\" IS '{$t->fields['relcomment']}';\n";
}
// Add comments on columns, if any
if ($col_comments_sql != '') $sql .= $col_comments_sql;
// Privileges
$privs = $this->getPrivileges($table, 'table');
if (!is_array($privs)) {
$this->rollbackTransaction();
return null;
}
if (sizeof($privs) > 0) {
$sql .= "\n-- Privileges\n\n";
/*
* Always start with REVOKE ALL FROM PUBLIC, so that we don't have to
* wire-in knowledge about the default public privileges for different
* kinds of objects.
*/
$sql .= "REVOKE ALL ON TABLE \"{$t->fields['nspname']}\".\"{$t->fields['relname']}\" FROM PUBLIC;\n";
foreach ($privs as $v) {
// Get non-GRANT OPTION privs
$nongrant = array_diff($v[2], $v[4]);
// Skip empty or owner ACEs
if (sizeof($v[2]) == 0 || ($v[0] == 'user' && $v[1] == $t->fields['relowner'])) continue;
// Change user if necessary
if ($this->hasGrantOption() && $v[3] != $t->fields['relowner']) {
$grantor = $v[3];
$this->clean($grantor);
$sql .= "SET SESSION AUTHORIZATION '{$grantor}';\n";
}
// Output privileges with no GRANT OPTION
$sql .= "GRANT " . join(', ', $nongrant) . " ON TABLE \"{$t->fields['relname']}\" TO ";
switch ($v[0]) {
case 'public':
$sql .= "PUBLIC;\n";
break;
case 'user':
$this->fieldClean($v[1]);
$sql .= "\"{$v[1]}\";\n";
break;
case 'group':
$this->fieldClean($v[1]);
$sql .= "GROUP \"{$v[1]}\";\n";
break;
default:
// Unknown privilege type - fail
$this->rollbackTransaction();
return null;
}
// Reset user if necessary
if ($this->hasGrantOption() && $v[3] != $t->fields['relowner']) {
$sql .= "RESET SESSION AUTHORIZATION;\n";
}
// Output privileges with GRANT OPTION
// Skip empty or owner ACEs
if (!$this->hasGrantOption() || sizeof($v[4]) == 0) continue;
// Change user if necessary
if ($this->hasGrantOption() && $v[3] != $t->fields['relowner']) {
$grantor = $v[3];
$this->clean($grantor);
$sql .= "SET SESSION AUTHORIZATION '{$grantor}';\n";
}
$sql .= "GRANT " . join(', ', $v[4]) . " ON \"{$t->fields['relname']}\" TO ";
switch ($v[0]) {
case 'public':
$sql .= "PUBLIC";
break;
case 'user':
$this->fieldClean($v[1]);
$sql .= "\"{$v[1]}\"";
break;
case 'group':
$this->fieldClean($v[1]);
$sql .= "GROUP \"{$v[1]}\"";
break;
default:
// Unknown privilege type - fail
return null;
}
$sql .= " WITH GRANT OPTION;\n";
// Reset user if necessary
if ($this->hasGrantOption() && $v[3] != $t->fields['relowner']) {
$sql .= "RESET SESSION AUTHORIZATION;\n";
}
}
}
// Add a newline to separate data that follows (if any)
$sql .= "\n";
return $sql;
}
/**
* Returns extra table definition information that is most usefully
* dumped after the table contents for speed and efficiency reasons
* @param $table The table to define
* @return A string containing the formatted SQL code
* @return null On error
*/
function getTableDefSuffix($table) {
$sql = '';
// Indexes
$indexes = $this->getIndexes($table);
if (!is_object($indexes)) {
$this->rollbackTransaction();
return null;
}
if ($indexes->recordCount() > 0) {
$sql .= "\n-- Indexes\n\n";
while (!$indexes->EOF) {
$sql .= $indexes->fields['inddef'] . ";\n";
$indexes->moveNext();
}
}
// Triggers
$triggers = $this->getTriggers($table);
if (!is_object($triggers)) {
$this->rollbackTransaction();
return null;
}
if ($triggers->recordCount() > 0) {
$sql .= "\n-- Triggers\n\n";
while (!$triggers->EOF) {
$sql .= $triggers->fields['tgdef'];
$sql .= ";\n";
$triggers->moveNext();
}
}
// Rules
$rules = $this->getRules($table);
if (!is_object($rules)) {
$this->rollbackTransaction();
return null;
}
if ($rules->recordCount() > 0) {
$sql .= "\n-- Rules\n\n";
while (!$rules->EOF) {
$sql .= $rules->fields['definition'] . "\n";
$rules->moveNext();
}
}
return $sql;
}
/**
* Creates a new table in the database
* @param $name The name of the table
* @param $fields The number of fields
* @param $field An array of field names
* @param $type An array of field types
* @param $array An array of '' or '[]' for each type if it's an array or not
* @param $length An array of field lengths
* @param $notnull An array of not null
* @param $default An array of default values
* @param $withoutoids True if WITHOUT OIDS, false otherwise
* @param $colcomment An array of comments
* @param $comment Table comment
* @param $tablespace The tablespace name ('' means none/default)
* @param $uniquekey An Array indicating the fields that are unique (those indexes that are set)
* @param $primarykey An Array indicating the field used for the primarykey (those indexes that are set)
* @return 0 success
* @return -1 no fields supplied
*/
function createTable($name, $fields, $field, $type, $array, $length, $notnull,
$default, $withoutoids, $colcomment, $tblcomment, $tablespace,
$uniquekey, $primarykey) {
$f_schema = $this->_schema;
$this->fieldClean($f_schema);
$this->fieldClean($name);
$status = $this->beginTransaction();
if ($status != 0) return -1;
$found = false;
$first = true;
$comment_sql = ''; //Accumulate comments for the columns
$sql = "CREATE TABLE \"{$f_schema}\".\"{$name}\" (";
for ($i = 0; $i < $fields; $i++) {
$this->fieldClean($field[$i]);
$this->clean($type[$i]);
$this->clean($length[$i]);
$this->clean($colcomment[$i]);
// Skip blank columns - for user convenience
if ($field[$i] == '' || $type[$i] == '') continue;
// If not the first column, add a comma
if (!$first) $sql .= ", ";
else $first = false;
switch ($type[$i]) {
// Have to account for weird placing of length for with/without
// time zone types
case 'timestamp with time zone':
case 'timestamp without time zone':
$qual = substr($type[$i], 9);
$sql .= "\"{$field[$i]}\" timestamp";
if ($length[$i] != '') $sql .= "({$length[$i]})";
$sql .= $qual;
break;
case 'time with time zone':
case 'time without time zone':
$qual = substr($type[$i], 4);
$sql .= "\"{$field[$i]}\" time";
if ($length[$i] != '') $sql .= "({$length[$i]})";
$sql .= $qual;
break;
default:
$sql .= "\"{$field[$i]}\" {$type[$i]}";
if ($length[$i] != '') $sql .= "({$length[$i]})";
}
// Add array qualifier if necessary
if ($array[$i] == '[]') $sql .= '[]';
// Add other qualifiers
if (!isset($primarykey[$i])) {
if (isset($uniquekey[$i])) $sql .= " UNIQUE";
if (isset($notnull[$i])) $sql .= " NOT NULL";
}
if ($default[$i] != '') $sql .= " DEFAULT {$default[$i]}";
if ($colcomment[$i] != '') $comment_sql .= "COMMENT ON COLUMN \"{$name}\".\"{$field[$i]}\" IS '{$colcomment[$i]}';\n";
$found = true;
}
if (!$found) return -1;
// PRIMARY KEY
$primarykeycolumns = array();
for ($i = 0; $i < $fields; $i++) {
if (isset($primarykey[$i])) {
$primarykeycolumns[] = "\"{$field[$i]}\"";
}
}
if (count($primarykeycolumns) > 0) {
$sql .= ", PRIMARY KEY (" . implode(", ", $primarykeycolumns) . ")";
}
$sql .= ")";
// WITHOUT OIDS
if ($withoutoids)
$sql .= ' WITHOUT OIDS';
else
$sql .= ' WITH OIDS';
// Tablespace
if ($this->hasTablespaces() && $tablespace != '') {
$this->fieldClean($tablespace);
$sql .= " TABLESPACE \"{$tablespace}\"";
}
$status = $this->execute($sql);
if ($status) {
$this->rollbackTransaction();
return -1;
}
if ($tblcomment != '') {
$status = $this->setComment('TABLE', '', $name, $tblcomment, true);
if ($status) {
$this->rollbackTransaction();
return -1;
}
}
if ($comment_sql != '') {
$status = $this->execute($comment_sql);
if ($status) {
$this->rollbackTransaction();
return -1;
}
}
return $this->endTransaction();
}
/**
* Creates a new table in the database copying attribs and other properties from another table
* @param $name The name of the table
* @param $like an array giving the schema ans the name of the table from which attribs are copying from:
* array(
* 'table' => table name,
* 'schema' => the schema name,
* )
* @param $defaults if true, copy the defaults values as well
* @param $constraints if true, copy the constraints as well (CHECK on table & attr)
* @param $tablespace The tablespace name ('' means none/default)
*/
function createTableLike($name, $like, $defaults = false, $constraints = false, $idx = false, $tablespace = '') {
$f_schema = $this->_schema;
$this->fieldClean($f_schema);
$this->fieldClean($name);
$this->fieldClean($like['schema']);
$this->fieldClean($like['table']);
$like = "\"{$like['schema']}\".\"{$like['table']}\"";
$status = $this->beginTransaction();
if ($status != 0) return -1;
$sql = "CREATE TABLE \"{$f_schema}\".\"{$name}\" (LIKE {$like}";
if ($defaults) $sql .= " INCLUDING DEFAULTS";
if ($this->hasCreateTableLikeWithConstraints() && $constraints) $sql .= " INCLUDING CONSTRAINTS";
if ($this->hasCreateTableLikeWithIndexes() && $idx) $sql .= " INCLUDING INDEXES";
$sql .= ")";
if ($this->hasTablespaces() && $tablespace != '') {
$this->fieldClean($tablespace);
$sql .= " TABLESPACE \"{$tablespace}\"";
}
$status = $this->execute($sql);
if ($status) {
$this->rollbackTransaction();
return -1;
}
return $this->endTransaction();
}
/**
* Alter a table's name
* /!\ this function is called from _alterTable which take care of escaping fields
* @param $tblrs The table RecordSet returned by getTable()
* @param $name The new table's name
* @return 0 success
*/
function alterTableName($tblrs, $name = null) {
/* vars cleaned in _alterTable */
// Rename (only if name has changed)
if (!empty($name) && ($name != $tblrs->fields['relname'])) {
$f_schema = $this->_schema;
$this->fieldClean($f_schema);
$sql = "ALTER TABLE \"{$f_schema}\".\"{$tblrs->fields['relname']}\" RENAME TO \"{$name}\"";
$status = $this->execute($sql);
if ($status == 0)
$tblrs->fields['relname'] = $name;
else
return $status;
}
return 0;
}
/**
* Alter a table's owner
* /!\ this function is called from _alterTable which take care of escaping fields
* @param $tblrs The table RecordSet returned by getTable()
* @param $name The new table's owner
* @return 0 success
*/
function alterTableOwner($tblrs, $owner = null) {
/* vars cleaned in _alterTable */
if (!empty($owner) && ($tblrs->fields['relowner'] != $owner)) {
$f_schema = $this->_schema;
$this->fieldClean($f_schema);
// If owner has been changed, then do the alteration. We are
// careful to avoid this generally as changing owner is a
// superuser only function.
$sql = "ALTER TABLE \"{$f_schema}\".\"{$tblrs->fields['relname']}\" OWNER TO \"{$owner}\"";
return $this->execute($sql);
}
return 0;
}
/**
* Alter a table's tablespace
* /!\ this function is called from _alterTable which take care of escaping fields
* @param $tblrs The table RecordSet returned by getTable()
* @param $name The new table's tablespace
* @return 0 success
*/
function alterTableTablespace($tblrs, $tablespace = null) {
/* vars cleaned in _alterTable */
if (!empty($tablespace) && ($tblrs->fields['tablespace'] != $tablespace)) {
$f_schema = $this->_schema;
$this->fieldClean($f_schema);
// If tablespace has been changed, then do the alteration. We
// don't want to do this unnecessarily.
$sql = "ALTER TABLE \"{$f_schema}\".\"{$tblrs->fields['relname']}\" SET TABLESPACE \"{$tablespace}\"";
return $this->execute($sql);
}
return 0;
}
/**
* Alter a table's schema
* /!\ this function is called from _alterTable which take care of escaping fields
* @param $tblrs The table RecordSet returned by getTable()
* @param $name The new table's schema
* @return 0 success
*/
function alterTableSchema($tblrs, $schema = null) {
/* vars cleaned in _alterTable */
if (!empty($schema) && ($tblrs->fields['nspname'] != $schema)) {
$f_schema = $this->_schema;
$this->fieldClean($f_schema);
// If tablespace has been changed, then do the alteration. We
// don't want to do this unnecessarily.
$sql = "ALTER TABLE \"{$f_schema}\".\"{$tblrs->fields['relname']}\" SET SCHEMA \"{$schema}\"";
return $this->execute($sql);
}
return 0;
}
/**
* Protected method which alter a table
* SHOULDN'T BE CALLED OUTSIDE OF A TRANSACTION
* @param $tblrs The table recordSet returned by getTable()
* @param $name The new name for the table
* @param $owner The new owner for the table
* @param $schema The new schema for the table
* @param $comment The comment on the table
* @param $tablespace The new tablespace for the table ('' means leave as is)
* @return 0 success
* @return -3 rename error
* @return -4 comment error
* @return -5 owner error
* @return -6 tablespace error
* @return -7 schema error
*/
protected
function _alterTable($tblrs, $name, $owner, $schema, $comment, $tablespace) {
$this->fieldArrayClean($tblrs->fields);
// Comment
$status = $this->setComment('TABLE', '', $tblrs->fields['relname'], $comment);
if ($status != 0) return -4;
// Owner
$this->fieldClean($owner);
$status = $this->alterTableOwner($tblrs, $owner);
if ($status != 0) return -5;
// Tablespace
$this->fieldClean($tablespace);
$status = $this->alterTableTablespace($tblrs, $tablespace);
if ($status != 0) return -6;
// Rename
$this->fieldClean($name);
$status = $this->alterTableName($tblrs, $name);
if ($status != 0) return -3;
// Schema
$this->fieldClean($schema);
$status = $this->alterTableSchema($tblrs, $schema);
if ($status != 0) return -7;
return 0;
}
/**
* Alter table properties
* @param $table The name of the table
* @param $name The new name for the table
* @param $owner The new owner for the table
* @param $schema The new schema for the table
* @param $comment The comment on the table
* @param $tablespace The new tablespace for the table ('' means leave as is)
* @return 0 success
* @return -1 transaction error
* @return -2 get existing table error
* @return $this->_alterTable error code
*/
function alterTable($table, $name, $owner, $schema, $comment, $tablespace) {
$data = $this->getTable($table);
if ($data->recordCount() != 1)
return -2;
$status = $this->beginTransaction();
if ($status != 0) {
$this->rollbackTransaction();
return -1;
}
$status = $this->_alterTable($data, $name, $owner, $schema, $comment, $tablespace);
if ($status != 0) {
$this->rollbackTransaction();
return $status;
}
return $this->endTransaction();
}
/**
* Returns the SQL for changing the current user
* @param $user The user to change to
* @return The SQL
*/
function getChangeUserSQL($user) {
$this->clean($user);
return "SET SESSION AUTHORIZATION '{$user}';";
}
/**
* Given an array of attnums and a relation, returns an array mapping
* attribute number to attribute name.
* @param $table The table to get attributes for
* @param $atts An array of attribute numbers
* @return An array mapping attnum to attname
* @return -1 $atts must be an array
* @return -2 wrong number of attributes found
*/
function getAttributeNames($table, $atts) {
$c_schema = $this->_schema;
$this->clean($c_schema);
$this->clean($table);
$this->arrayClean($atts);
if (!is_array($atts)) return -1;
if (sizeof($atts) == 0) return array();
$sql = "SELECT attnum, attname FROM pg_catalog.pg_attribute WHERE
attrelid=(SELECT oid FROM pg_catalog.pg_class WHERE relname='{$table}' AND
relnamespace=(SELECT oid FROM pg_catalog.pg_namespace WHERE nspname='{$c_schema}'))
AND attnum IN ('" . join("','", $atts) . "')";
$rs = $this->selectSet($sql);
if ($rs->recordCount() != sizeof($atts)) {
return -2;
}
else {
$temp = array();
while (!$rs->EOF) {
$temp[$rs->fields['attnum']] = $rs->fields['attname'];
$rs->moveNext();
}
return $temp;
}
}
/**
* Empties a table in the database
* @param $table The table to be emptied
* @return 0 success
*/
function emptyTable($table) {
$f_schema = $this->_schema;
$this->fieldClean($f_schema);
$this->fieldClean($table);
$sql = "DELETE FROM \"{$f_schema}\".\"{$table}\"";
return $this->execute($sql);
}
/**
* Removes a table from the database
* @param $table The table to drop
* @param $cascade True to cascade drop, false to restrict
* @return 0 success
*/
function dropTable($table, $cascade) {
$f_schema = $this->_schema;
$this->fieldClean($f_schema);
$this->fieldClean($table);
$sql = "DROP TABLE \"{$f_schema}\".\"{$table}\"";
if ($cascade) $sql .= " CASCADE";
return $this->execute($sql);
}
/**
* Add a new column to a table
* @param $table The table to add to
* @param $column The name of the new column
* @param $type The type of the column
* @param $array True if array type, false otherwise
* @param $notnull True if NOT NULL, false otherwise
* @param $default The default for the column. '' for none.
* @param $length The optional size of the column (ie. 30 for varchar(30))
* @return 0 success
*/
function addColumn($table, $column, $type, $array, $length, $notnull, $default, $comment) {
$f_schema = $this->_schema;
$this->fieldClean($f_schema);
$this->fieldClean($table);
$this->fieldClean($column);
$this->clean($type);
$this->clean($length);
if ($length == '')
$sql = "ALTER TABLE \"{$f_schema}\".\"{$table}\" ADD COLUMN \"{$column}\" {$type}";
else {
switch ($type) {
// Have to account for weird placing of length for with/without
// time zone types
case 'timestamp with time zone':
case 'timestamp without time zone':
$qual = substr($type, 9);
$sql = "ALTER TABLE \"{$f_schema}\".\"{$table}\" ADD COLUMN \"{$column}\" timestamp({$length}){$qual}";
break;
case 'time with time zone':
case 'time without time zone':
$qual = substr($type, 4);
$sql = "ALTER TABLE \"{$f_schema}\".\"{$table}\" ADD COLUMN \"{$column}\" time({$length}){$qual}";
break;
default:
$sql = "ALTER TABLE \"{$f_schema}\".\"{$table}\" ADD COLUMN \"{$column}\" {$type}({$length})";
}
}
// Add array qualifier, if requested
if ($array) $sql .= '[]';
// If we have advanced column adding, add the extra qualifiers
if ($this->hasCreateFieldWithConstraints()) {
// NOT NULL clause
if ($notnull) $sql .= ' NOT NULL';
// DEFAULT clause
if ($default != '') $sql .= ' DEFAULT ' . $default;
}
$status = $this->beginTransaction();
if ($status != 0) return -1;
$status = $this->execute($sql);
if ($status != 0) {
$this->rollbackTransaction();
return -1;
}
$status = $this->setComment('COLUMN', $column, $table, $comment);
if ($status != 0) {
$this->rollbackTransaction();
return -1;
}
return $this->endTransaction();
}
/**
* Alters a column in a table
* @param $table The table in which the column resides
* @param $column The column to alter
* @param $name The new name for the column
* @param $notnull (boolean) True if not null, false otherwise
* @param $oldnotnull (boolean) True if column is already not null, false otherwise
* @param $default The new default for the column
* @param $olddefault The old default for the column
* @param $type The new type for the column
* @param $array True if array type, false otherwise
* @param $length The optional size of the column (ie. 30 for varchar(30))
* @param $oldtype The old type for the column
* @param $comment Comment for the column
* @return 0 success
* @return -1 batch alteration failed
* @return -4 rename column error
* @return -5 comment error
* @return -6 transaction error
*/
function alterColumn($table, $column, $name, $notnull, $oldnotnull, $default, $olddefault,
$type, $length, $array, $oldtype, $comment)
{
// Begin transaction
$status = $this->beginTransaction();
if ($status != 0) {
$this->rollbackTransaction();
return -6;
}
// Rename the column, if it has been changed
if ($column != $name) {
$status = $this->renameColumn($table, $column, $name);
if ($status != 0) {
$this->rollbackTransaction();
return -4;
}
}
$f_schema = $this->_schema;
$this->fieldClean($f_schema);
$this->fieldClean($name);
$this->fieldClean($table);
$this->fieldClean($column);
$toAlter = array();
// Create the command for changing nullability
if ($notnull != $oldnotnull) {
$toAlter[] = "ALTER COLUMN \"{$name}\" ". (($notnull) ? 'SET' : 'DROP') . " NOT NULL";
}
// Add default, if it has changed
if ($default != $olddefault) {
if ($default == '') {
$toAlter[] = "ALTER COLUMN \"{$name}\" DROP DEFAULT";
}
else {
$toAlter[] = "ALTER COLUMN \"{$name}\" SET DEFAULT {$default}";
}
}
// Add type, if it has changed
if ($length == '')
$ftype = $type;
else {
switch ($type) {
// Have to account for weird placing of length for with/without
// time zone types
case 'timestamp with time zone':
case 'timestamp without time zone':
$qual = substr($type, 9);
$ftype = "timestamp({$length}){$qual}";
break;
case 'time with time zone':
case 'time without time zone':
$qual = substr($type, 4);
$ftype = "time({$length}){$qual}";
break;
default:
$ftype = "{$type}({$length})";
}
}
// Add array qualifier, if requested
if ($array) $ftype .= '[]';
if ($ftype != $oldtype) {
$toAlter[] = "ALTER COLUMN \"{$name}\" TYPE {$ftype}";
}
// Attempt to process the batch alteration, if anything has been changed
if (!empty($toAlter)) {
// Initialise an empty SQL string
$sql = "ALTER TABLE \"{$f_schema}\".\"{$table}\" "
. implode(',', $toAlter);
$status = $this->execute($sql);
if ($status != 0) {
$this->rollbackTransaction();
return -1;
}
}
// Update the comment on the column
$status = $this->setComment('COLUMN', $name, $table, $comment);
if ($status != 0) {
$this->rollbackTransaction();
return -5;
}
return $this->endTransaction();
}
/**
* Renames a column in a table
* @param $table The table containing the column to be renamed
* @param $column The column to be renamed
* @param $newName The new name for the column
* @return 0 success
*/
function renameColumn($table, $column, $newName) {
$f_schema = $this->_schema;
$this->fieldClean($f_schema);
$this->fieldClean($table);
$this->fieldClean($column);
$this->fieldClean($newName);
$sql = "ALTER TABLE \"{$f_schema}\".\"{$table}\" RENAME COLUMN \"{$column}\" TO \"{$newName}\"";
return $this->execute($sql);
}
/**
* Sets default value of a column
* @param $table The table from which to drop
* @param $column The column name to set
* @param $default The new default value
* @return 0 success
*/
function setColumnDefault($table, $column, $default) {
$f_schema = $this->_schema;
$this->fieldClean($f_schema);
$this->fieldClean($table);
$this->fieldClean($column);
$sql = "ALTER TABLE \"{$f_schema}\".\"{$table}\" ALTER COLUMN \"{$column}\" SET DEFAULT {$default}";
return $this->execute($sql);
}
/**
* Sets whether or not a column can contain NULLs
* @param $table The table that contains the column
* @param $column The column to alter
* @param $state True to set null, false to set not null
* @return 0 success
*/
function setColumnNull($table, $column, $state) {
$f_schema = $this->_schema;
$this->fieldClean($f_schema);
$this->fieldClean($table);
$this->fieldClean($column);
$sql = "ALTER TABLE \"{$f_schema}\".\"{$table}\" ALTER COLUMN \"{$column}\" " . (($state) ? 'DROP' : 'SET') . " NOT NULL";
return $this->execute($sql);
}
/**
* Drops a column from a table
* @param $table The table from which to drop a column
* @param $column The column to be dropped
* @param $cascade True to cascade drop, false to restrict
* @return 0 success
*/
function dropColumn($table, $column, $cascade) {
$f_schema = $this->_schema;
$this->fieldClean($f_schema);
$this->fieldClean($table);
$this->fieldClean($column);
$sql = "ALTER TABLE \"{$f_schema}\".\"{$table}\" DROP COLUMN \"{$column}\"";
if ($cascade) $sql .= " CASCADE";
return $this->execute($sql);
}
/**
* Drops default value of a column
* @param $table The table from which to drop
* @param $column The column name to drop default
* @return 0 success
*/
function dropColumnDefault($table, $column) {
$f_schema = $this->_schema;
$this->fieldClean($f_schema);
$this->fieldClean($table);
$this->fieldClean($column);
$sql = "ALTER TABLE \"{$f_schema}\".\"{$table}\" ALTER COLUMN \"{$column}\" DROP DEFAULT";
return $this->execute($sql);
}
/**
* Sets up the data object for a dump. eg. Starts the appropriate
* transaction, sets variables, etc.
* @return 0 success
*/
function beginDump() {
// Begin serializable transaction (to dump consistent data)
$status = $this->beginTransaction();
if ($status != 0) return -1;
// Set serializable
$sql = "SET TRANSACTION ISOLATION LEVEL SERIALIZABLE";
$status = $this->execute($sql);
if ($status != 0) {
$this->rollbackTransaction();
return -1;
}
// Set datestyle to ISO
$sql = "SET DATESTYLE = ISO";
$status = $this->execute($sql);
if ($status != 0) {
$this->rollbackTransaction();
return -1;
}
// Set extra_float_digits to 2
$sql = "SET extra_float_digits TO 2";
$status = $this->execute($sql);
if ($status != 0) {
$this->rollbackTransaction();
return -1;
}
return 0;
}
/**
* Ends the data object for a dump.
* @return 0 success
*/
function endDump() {
return $this->endTransaction();
}
/**
* Returns a recordset of all columns in a relation. Used for data export.
* @@ Note: Really needs to use a cursor
* @param $relation The name of a relation
* @return A recordset on success
* @return -1 Failed to set datestyle
*/
function dumpRelation($relation, $oids) {
$this->fieldClean($relation);
// Actually retrieve the rows
if ($oids) $oid_str = $this->id . ', ';
else $oid_str = '';
return $this->selectSet("SELECT {$oid_str}* FROM \"{$relation}\"");
}
/**
* Returns all available autovacuum per table information.
* @param $table if given, return autovacuum info for the given table or return all informations for all table
*
* @return A recordset
*/
function getTableAutovacuum($table='') {
$sql = '';
if ($table !== '') {
$this->clean($table);
$c_schema = $this->_schema;
$this->clean($c_schema);
$sql = "SELECT c.oid, nspname, relname, pg_catalog.array_to_string(reloptions, E',') AS reloptions
FROM pg_class c
LEFT JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE c.relkind = 'r'::\"char\"
AND n.nspname NOT IN ('pg_catalog','information_schema')
AND c.reloptions IS NOT NULL
AND c.relname = '{$table}' AND n.nspname = '{$c_schema}'
ORDER BY nspname, relname";
}
else {
$sql = "SELECT c.oid, nspname, relname, pg_catalog.array_to_string(reloptions, E',') AS reloptions
FROM pg_class c
LEFT JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE c.relkind = 'r'::\"char\"
AND n.nspname NOT IN ('pg_catalog','information_schema')
AND c.reloptions IS NOT NULL
ORDER BY nspname, relname";
}
/* tmp var to parse the results */
$_autovacs = $this->selectSet($sql);
/* result aray to return as RS */
$autovacs = array();
while (!$_autovacs->EOF) {
$_ = array(
'nspname' => $_autovacs->fields['nspname'],
'relname' => $_autovacs->fields['relname']
);
foreach (explode(',', $_autovacs->fields['reloptions']) AS $var) {
list($o, $v) = explode('=', $var);
$_[$o] = $v;
}
$autovacs[] = $_;
$_autovacs->moveNext();
}
include_once('./classes/ArrayRecordSet.php');
return new ArrayRecordSet($autovacs);
}
// Row functions
/**
* Get the fields for uniquely identifying a row in a table
* @param $table The table for which to retrieve the identifier
* @return An array mapping attribute number to attribute name, empty for no identifiers
* @return -1 error
*/
function getRowIdentifier($table) {
$oldtable = $table;
$c_schema = $this->_schema;
$this->clean($c_schema);
$this->clean($table);
$status = $this->beginTransaction();
if ($status != 0) return -1;
// Get the first primary or unique index (sorting primary keys first) that
// is NOT a partial index.
$sql = "
SELECT indrelid, indkey
FROM pg_catalog.pg_index
WHERE indisunique AND indrelid=(
SELECT oid FROM pg_catalog.pg_class
WHERE relname='{$table}' AND relnamespace=(
SELECT oid FROM pg_catalog.pg_namespace
WHERE nspname='{$c_schema}'
)
) AND indpred IS NULL AND indexprs IS NULL
ORDER BY indisprimary DESC LIMIT 1";
$rs = $this->selectSet($sql);
// If none, check for an OID column. Even though OIDs can be duplicated, the edit and delete row
// functions check that they're only modiying a single row. Otherwise, return empty array.
if ($rs->recordCount() == 0) {
// Check for OID column
$temp = array();
if ($this->hasObjectID($table)) {
$temp = array('oid');
}
$this->endTransaction();
return $temp;
}
// Otherwise find the names of the keys
else {
$attnames = $this->getAttributeNames($oldtable, explode(' ', $rs->fields['indkey']));
if (!is_array($attnames)) {
$this->rollbackTransaction();
return -1;
}
else {
$this->endTransaction();
return $attnames;
}
}
}
/**
* Adds a new row to a table
* @param $table The table in which to insert
* @param $fields Array of given field in values
* @param $values Array of new values for the row
* @param $nulls An array mapping column => something if it is to be null
* @param $format An array of the data type (VALUE or EXPRESSION)
* @param $types An array of field types
* @return 0 success
* @return -1 invalid parameters
*/
function insertRow($table, $fields, $values, $nulls, $format, $types) {
if (!is_array($fields) || !is_array($values) || !is_array($nulls)
|| !is_array($format) || !is_array($types)
|| (count($fields) != count($values))
) {
return -1;
}
else {
// Build clause
if (count($values) > 0) {
// Escape all field names
$fields = array_map(array('Postgres','fieldClean'), $fields);
$f_schema = $this->_schema;
$this->fieldClean($table);
$this->fieldClean($f_schema);
$sql = '';
foreach($values as $i => $value) {
// Handle NULL values
if (isset($nulls[$i]))
$sql .= ',NULL';
else
$sql .= ',' . $this->formatValue($types[$i], $format[$i], $value);
}
$sql = "INSERT INTO \"{$f_schema}\".\"{$table}\" (\"". implode('","', $fields) ."\")
VALUES (". substr($sql, 1) .")";
return $this->execute($sql);
}
}
return -1;
}
/**
* Updates a row in a table
* @param $table The table in which to update
* @param $vars An array mapping new values for the row
* @param $nulls An array mapping column => something if it is to be null
* @param $format An array of the data type (VALUE or EXPRESSION)
* @param $types An array of field types
* @param $keyarr An array mapping column => value to update
* @return 0 success
* @return -1 invalid parameters
*/
function editRow($table, $vars, $nulls, $format, $types, $keyarr) {
if (!is_array($vars) || !is_array($nulls) || !is_array($format) || !is_array($types))
return -1;
else {
$f_schema = $this->_schema;
$this->fieldClean($f_schema);
$this->fieldClean($table);
// Build clause
if (sizeof($vars) > 0) {
foreach($vars as $key => $value) {
$this->fieldClean($key);
// Handle NULL values
if (isset($nulls[$key])) $tmp = 'NULL';
else $tmp = $this->formatValue($types[$key], $format[$key], $value);
if (isset($sql)) $sql .= ", \"{$key}\"={$tmp}";
else $sql = "UPDATE \"{$f_schema}\".\"{$table}\" SET \"{$key}\"={$tmp}";
}
$first = true;
foreach ($keyarr as $k => $v) {
$this->fieldClean($k);
$this->clean($v);
if ($first) {
$sql .= " WHERE \"{$k}\"='{$v}'";
$first = false;
}
else $sql .= " AND \"{$k}\"='{$v}'";
}
}
// Begin transaction. We do this so that we can ensure only one row is
// edited
$status = $this->beginTransaction();
if ($status != 0) {
$this->rollbackTransaction();
return -1;
}
$status = $this->execute($sql);
if ($status != 0) { // update failed
$this->rollbackTransaction();
return -1;
} elseif ($this->conn->Affected_Rows() != 1) { // more than one row could be updated
$this->rollbackTransaction();
return -2;
}
// End transaction
return $this->endTransaction();
}
}
/**
* Delete a row from a table
* @param $table The table from which to delete
* @param $key An array mapping column => value to delete
* @return 0 success
*/
function deleteRow($table, $key, $schema=false) {
if (!is_array($key)) return -1;
else {
// Begin transaction. We do this so that we can ensure only one row is
// deleted
$status = $this->beginTransaction();
if ($status != 0) {
$this->rollbackTransaction();
return -1;
}
if ($schema === false) $schema = $this->_schema;
$status = $this->delete($table, $key, $schema);
if ($status != 0 || $this->conn->Affected_Rows() != 1) {
$this->rollbackTransaction();
return -2;
}
// End transaction
return $this->endTransaction();
}
}
// Sequence functions
/**
* Returns properties of a single sequence
* @param $sequence Sequence name
* @return A recordset
*/
function getSequence($sequence) {
$c_schema = $this->_schema;
$this->clean($c_schema);
$c_sequence = $sequence;
$this->fieldClean($sequence);
$this->clean($c_sequence);
$sql = "
SELECT c.relname AS seqname, s.*,
pg_catalog.obj_description(s.tableoid, 'pg_class') AS seqcomment,
u.usename AS seqowner, n.nspname
FROM \"{$sequence}\" AS s, pg_catalog.pg_class c, pg_catalog.pg_user u, pg_catalog.pg_namespace n
WHERE c.relowner=u.usesysid AND c.relnamespace=n.oid
AND c.relname = '{$c_sequence}' AND c.relkind = 'S' AND n.nspname='{$c_schema}'
AND n.oid = c.relnamespace";
return $this->selectSet( $sql );
}
/**
* Returns all sequences in the current database
* @return A recordset
*/
function getSequences($all = false) {
if ($all) {
// Exclude pg_catalog and information_schema tables
$sql = "SELECT n.nspname, c.relname AS seqname, u.usename AS seqowner
FROM pg_catalog.pg_class c, pg_catalog.pg_user u, pg_catalog.pg_namespace n
WHERE c.relowner=u.usesysid AND c.relnamespace=n.oid
AND c.relkind = 'S'
AND n.nspname NOT IN ('pg_catalog', 'information_schema', 'pg_toast')
ORDER BY nspname, seqname";
} else {
$c_schema = $this->_schema;
$this->clean($c_schema);
$sql = "SELECT c.relname AS seqname, u.usename AS seqowner, pg_catalog.obj_description(c.oid, 'pg_class') AS seqcomment,
(SELECT spcname FROM pg_catalog.pg_tablespace pt WHERE pt.oid=c.reltablespace) AS tablespace
FROM pg_catalog.pg_class c, pg_catalog.pg_user u, pg_catalog.pg_namespace n
WHERE c.relowner=u.usesysid AND c.relnamespace=n.oid
AND c.relkind = 'S' AND n.nspname='{$c_schema}' ORDER BY seqname";
}
return $this->selectSet( $sql );
}
/**
* Execute nextval on a given sequence
* @param $sequence Sequence name
* @return 0 success
* @return -1 sequence not found
*/
function nextvalSequence($sequence) {
/* This double-cleaning is deliberate */
$f_schema = $this->_schema;
$this->fieldClean($f_schema);
$this->clean($f_schema);
$this->fieldClean($sequence);
$this->clean($sequence);
$sql = "SELECT pg_catalog.NEXTVAL('\"{$f_schema}\".\"{$sequence}\"')";
return $this->execute($sql);
}
/**
* Execute setval on a given sequence
* @param $sequence Sequence name
* @param $nextvalue The next value
* @return 0 success
* @return -1 sequence not found
*/
function setvalSequence($sequence, $nextvalue) {
/* This double-cleaning is deliberate */
$f_schema = $this->_schema;
$this->fieldClean($f_schema);
$this->clean($f_schema);
$this->fieldClean($sequence);
$this->clean($sequence);
$this->clean($nextvalue);
$sql = "SELECT pg_catalog.SETVAL('\"{$f_schema}\".\"{$sequence}\"', '{$nextvalue}')";
return $this->execute($sql);
}
/**
* Restart a given sequence to its start value
* @param $sequence Sequence name
* @return 0 success
* @return -1 sequence not found
*/
function restartSequence($sequence) {
$f_schema = $this->_schema;
$this->fieldClean($f_schema);
$this->fieldClean($sequence);
$sql = "ALTER SEQUENCE \"{$f_schema}\".\"{$sequence}\" RESTART;";
return $this->execute($sql);
}
/**
* Resets a given sequence to min value of sequence
* @param $sequence Sequence name
* @return 0 success
* @return -1 sequence not found
*/
function resetSequence($sequence) {
// Get the minimum value of the sequence
$seq = $this->getSequence($sequence);
if ($seq->recordCount() != 1) return -1;
$minvalue = $seq->fields['min_value'];
$f_schema = $this->_schema;
$this->fieldClean($f_schema);
/* This double-cleaning is deliberate */
$this->fieldClean($sequence);
$this->clean($sequence);
$sql = "SELECT pg_catalog.SETVAL('\"{$f_schema}\".\"{$sequence}\"', {$minvalue})";
return $this->execute($sql);
}
/**
* Creates a new sequence
* @param $sequence Sequence name
* @param $increment The increment
* @param $minvalue The min value
* @param $maxvalue The max value
* @param $startvalue The starting value
* @param $cachevalue The cache value
* @param $cycledvalue True if cycled, false otherwise
* @return 0 success
*/
function createSequence($sequence, $increment, $minvalue, $maxvalue,
$startvalue, $cachevalue, $cycledvalue) {
$f_schema = $this->_schema;
$this->fieldClean($f_schema);
$this->fieldClean($sequence);
$this->clean($increment);
$this->clean($minvalue);
$this->clean($maxvalue);
$this->clean($startvalue);
$this->clean($cachevalue);
$sql = "CREATE SEQUENCE \"{$f_schema}\".\"{$sequence}\"";
if ($increment != '') $sql .= " INCREMENT {$increment}";
if ($minvalue != '') $sql .= " MINVALUE {$minvalue}";
if ($maxvalue != '') $sql .= " MAXVALUE {$maxvalue}";
if ($startvalue != '') $sql .= " START {$startvalue}";
if ($cachevalue != '') $sql .= " CACHE {$cachevalue}";
if ($cycledvalue) $sql .= " CYCLE";
return $this->execute($sql);
}
/**
* Rename a sequence
* @param $seqrs The sequence RecordSet returned by getSequence()
* @param $name The new name for the sequence
* @return 0 success
*/
function alterSequenceName($seqrs, $name) {
/* vars are cleaned in _alterSequence */
if (!empty($name) && ($seqrs->fields['seqname'] != $name)) {
$f_schema = $this->_schema;
$this->fieldClean($f_schema);
$sql = "ALTER SEQUENCE \"{$f_schema}\".\"{$seqrs->fields['seqname']}\" RENAME TO \"{$name}\"";
$status = $this->execute($sql);
if ($status == 0)
$seqrs->fields['seqname'] = $name;
else
return $status;
}
return 0;
}
/**
* Alter a sequence's owner
* @param $seqrs The sequence RecordSet returned by getSequence()
* @param $name The new owner for the sequence
* @return 0 success
*/
function alterSequenceOwner($seqrs, $owner) {
// If owner has been changed, then do the alteration. We are
// careful to avoid this generally as changing owner is a
// superuser only function.
/* vars are cleaned in _alterSequence */
if (!empty($owner) && ($seqrs->fields['seqowner'] != $owner)) {
$f_schema = $this->_schema;
$this->fieldClean($f_schema);
$sql = "ALTER SEQUENCE \"{$f_schema}\".\"{$seqrs->fields['seqname']}\" OWNER TO \"{$owner}\"";
return $this->execute($sql);
}
return 0;
}
/**
* Alter a sequence's schema
* @param $seqrs The sequence RecordSet returned by getSequence()
* @param $name The new schema for the sequence
* @return 0 success
*/
function alterSequenceSchema($seqrs, $schema) {
/* vars are cleaned in _alterSequence */
if (!empty($schema) && ($seqrs->fields['nspname'] != $schema)) {
$f_schema = $this->_schema;
$this->fieldClean($f_schema);
$sql = "ALTER SEQUENCE \"{$f_schema}\".\"{$seqrs->fields['seqname']}\" SET SCHEMA {$schema}";
return $this->execute($sql);
}
return 0;
}
/**
* Alter a sequence's properties
* @param $seqrs The sequence RecordSet returned by getSequence()
* @param $increment The sequence incremental value
* @param $minvalue The sequence minimum value
* @param $maxvalue The sequence maximum value
* @param $restartvalue The sequence current value
* @param $cachevalue The sequence cache value
* @param $cycledvalue Sequence can cycle ?
* @param $startvalue The sequence start value when issueing a restart
* @return 0 success
*/
function alterSequenceProps($seqrs, $increment, $minvalue, $maxvalue,
$restartvalue, $cachevalue, $cycledvalue, $startvalue) {
$sql = '';
/* vars are cleaned in _alterSequence */
if (!empty($increment) && ($increment != $seqrs->fields['increment_by'])) $sql .= " INCREMENT {$increment}";
if (!empty($minvalue) && ($minvalue != $seqrs->fields['min_value'])) $sql .= " MINVALUE {$minvalue}";
if (!empty($maxvalue) && ($maxvalue != $seqrs->fields['max_value'])) $sql .= " MAXVALUE {$maxvalue}";
if (!empty($restartvalue) && ($restartvalue != $seqrs->fields['last_value'])) $sql .= " RESTART {$restartvalue}";
if (!empty($cachevalue) && ($cachevalue != $seqrs->fields['cache_value'])) $sql .= " CACHE {$cachevalue}";
if (!empty($startvalue) && ($startvalue != $seqrs->fields['start_value'])) $sql .= " START {$startvalue}";
// toggle cycle yes/no
if (!is_null($cycledvalue)) $sql .= (!$cycledvalue ? ' NO ' : '') . " CYCLE";
if ($sql != '') {
$f_schema = $this->_schema;
$this->fieldClean($f_schema);
$sql = "ALTER SEQUENCE \"{$f_schema}\".\"{$seqrs->fields['seqname']}\" {$sql}";
return $this->execute($sql);
}
return 0;
}
/**
* Protected method which alter a sequence
* SHOULDN'T BE CALLED OUTSIDE OF A TRANSACTION
* @param $seqrs The sequence recordSet returned by getSequence()
* @param $name The new name for the sequence
* @param $comment The comment on the sequence
* @param $owner The new owner for the sequence
* @param $schema The new schema for the sequence
* @param $increment The increment
* @param $minvalue The min value
* @param $maxvalue The max value
* @param $restartvalue The starting value
* @param $cachevalue The cache value
* @param $cycledvalue True if cycled, false otherwise
* @param $startvalue The sequence start value when issueing a restart
* @return 0 success
* @return -3 rename error
* @return -4 comment error
* @return -5 owner error
* @return -6 get sequence props error
* @return -7 schema error
*/
protected
function _alterSequence($seqrs, $name, $comment, $owner, $schema, $increment,
$minvalue, $maxvalue, $restartvalue, $cachevalue, $cycledvalue, $startvalue) {
$this->fieldArrayClean($seqrs->fields);
// Comment
$status = $this->setComment('SEQUENCE', $seqrs->fields['seqname'], '', $comment);
if ($status != 0)
return -4;
// Owner
$this->fieldClean($owner);
$status = $this->alterSequenceOwner($seqrs, $owner);
if ($status != 0)
return -5;
// Props
$this->clean($increment);
$this->clean($minvalue);
$this->clean($maxvalue);
$this->clean($restartvalue);
$this->clean($cachevalue);
$this->clean($cycledvalue);
$this->clean($startvalue);
$status = $this->alterSequenceProps($seqrs, $increment, $minvalue,
$maxvalue, $restartvalue, $cachevalue, $cycledvalue, $startvalue);
if ($status != 0)
return -6;
// Rename
$this->fieldClean($name);
$status = $this->alterSequenceName($seqrs, $name);
if ($status != 0)
return -3;
// Schema
$this->clean($schema);
$status = $this->alterSequenceSchema($seqrs, $schema);
if ($status != 0)
return -7;
return 0;
}
/**
* Alters a sequence
* @param $sequence The name of the sequence
* @param $name The new name for the sequence
* @param $comment The comment on the sequence
* @param $owner The new owner for the sequence
* @param $schema The new schema for the sequence
* @param $increment The increment
* @param $minvalue The min value
* @param $maxvalue The max value
* @param $restartvalue The starting value
* @param $cachevalue The cache value
* @param $cycledvalue True if cycled, false otherwise
* @param $startvalue The sequence start value when issueing a restart
* @return 0 success
* @return -1 transaction error
* @return -2 get existing sequence error
* @return $this->_alterSequence error code
*/
function alterSequence($sequence, $name, $comment, $owner=null, $schema=null, $increment=null,
$minvalue=null, $maxvalue=null, $restartvalue=null, $cachevalue=null, $cycledvalue=null, $startvalue=null) {
$this->fieldClean($sequence);
$data = $this->getSequence($sequence);
if ($data->recordCount() != 1)
return -2;
$status = $this->beginTransaction();
if ($status != 0) {
$this->rollbackTransaction();
return -1;
}
$status = $this->_alterSequence($data, $name, $comment, $owner, $schema, $increment,
$minvalue, $maxvalue, $restartvalue, $cachevalue, $cycledvalue, $startvalue);
if ($status != 0) {
$this->rollbackTransaction();
return $status;
}
return $this->endTransaction();
}
/**
* Drops a given sequence
* @param $sequence Sequence name
* @param $cascade True to cascade drop, false to restrict
* @return 0 success
*/
function dropSequence($sequence, $cascade) {
$f_schema = $this->_schema;
$this->fieldClean($f_schema);
$this->fieldClean($sequence);
$sql = "DROP SEQUENCE \"{$f_schema}\".\"{$sequence}\"";
if ($cascade) $sql .= " CASCADE";
return $this->execute($sql);
}
// View functions
/**
* Returns all details for a particular view
* @param $view The name of the view to retrieve
* @return View info
*/
function getView($view) {
$c_schema = $this->_schema;
$this->clean($c_schema);
$this->clean($view);
$sql = "
SELECT c.relname, n.nspname, pg_catalog.pg_get_userbyid(c.relowner) AS relowner,
pg_catalog.pg_get_viewdef(c.oid, true) AS vwdefinition,
pg_catalog.obj_description(c.oid, 'pg_class') AS relcomment
FROM pg_catalog.pg_class c
LEFT JOIN pg_catalog.pg_namespace n ON (n.oid = c.relnamespace)
WHERE (c.relname = '{$view}') AND n.nspname='{$c_schema}'";
return $this->selectSet($sql);
}
/**
* Returns a list of all views in the database
* @return All views
*/
function getViews() {
$c_schema = $this->_schema;
$this->clean($c_schema);
$sql = "
SELECT c.relname, pg_catalog.pg_get_userbyid(c.relowner) AS relowner,
pg_catalog.obj_description(c.oid, 'pg_class') AS relcomment
FROM pg_catalog.pg_class c
LEFT JOIN pg_catalog.pg_namespace n ON (n.oid = c.relnamespace)
WHERE (n.nspname='{$c_schema}') AND (c.relkind = 'v'::\"char\")
ORDER BY relname";
return $this->selectSet($sql);
}
/**
* Updates a view.
* @param $viewname The name fo the view to update
* @param $definition The new definition for the view
* @return 0 success
* @return -1 transaction error
* @return -2 drop view error
* @return -3 create view error
*/
function setView($viewname, $definition,$comment) {
return $this->createView($viewname, $definition, true, $comment);
}
/**
* Creates a new view.
* @param $viewname The name of the view to create
* @param $definition The definition for the new view
* @param $replace True to replace the view, false otherwise
* @return 0 success
*/
function createView($viewname, $definition, $replace, $comment) {
$status = $this->beginTransaction();
if ($status != 0) return -1;
$f_schema = $this->_schema;
$this->fieldClean($f_schema);
$this->fieldClean($viewname);
// Note: $definition not cleaned
$sql = "CREATE ";
if ($replace) $sql .= "OR REPLACE ";
$sql .= "VIEW \"{$f_schema}\".\"{$viewname}\" AS {$definition}";
$status = $this->execute($sql);
if ($status) {
$this->rollbackTransaction();
return -1;
}
if ($comment != '') {
$status = $this->setComment('VIEW', $viewname, '', $comment);
if ($status) {
$this->rollbackTransaction();
return -1;
}
}
return $this->endTransaction();
}
/**
* Rename a view
* @param $vwrs The view recordSet returned by getView()
* @param $name The new view's name
* @return 0 success
*/
function alterViewName($vwrs, $name) {
// Rename (only if name has changed)
/* $vwrs and $name are cleaned in _alterView */
if (!empty($name) && ($name != $vwrs->fields['relname'])) {
$f_schema = $this->_schema;
$this->fieldClean($f_schema);
$sql = "ALTER VIEW \"{$f_schema}\".\"{$vwrs->fields['relname']}\" RENAME TO \"{$name}\"";
$status = $this->execute($sql);
if ($status == 0)
$vwrs->fields['relname'] = $name;
else
return $status;
}
return 0;
}
/**
* Alter a view's owner
* @param $vwrs The view recordSet returned by getView()
* @param $name The new view's owner
* @return 0 success
*/
function alterViewOwner($vwrs, $owner = null) {
/* $vwrs and $owner are cleaned in _alterView */
if ((!empty($owner)) && ($vwrs->fields['relowner'] != $owner)) {
$f_schema = $this->_schema;
$this->fieldClean($f_schema);
// If owner has been changed, then do the alteration. We are
// careful to avoid this generally as changing owner is a
// superuser only function.
$sql = "ALTER TABLE \"{$f_schema}\".\"{$vwrs->fields['relname']}\" OWNER TO \"{$owner}\"";
return $this->execute($sql);
}
return 0;
}
/**
* Alter a view's schema
* @param $vwrs The view recordSet returned by getView()
* @param $name The new view's schema
* @return 0 success
*/
function alterViewSchema($vwrs, $schema) {
/* $vwrs and $schema are cleaned in _alterView */
if (!empty($schema) && ($vwrs->fields['nspname'] != $schema)) {
$f_schema = $this->_schema;
$this->fieldClean($f_schema);
// If tablespace has been changed, then do the alteration. We
// don't want to do this unnecessarily.
$sql = "ALTER TABLE \"{$f_schema}\".\"{$vwrs->fields['relname']}\" SET SCHEMA \"{$schema}\"";
return $this->execute($sql);
}
return 0;
}
/**
* Protected method which alter a view
* SHOULDN'T BE CALLED OUTSIDE OF A TRANSACTION
* @param $vwrs The view recordSet returned by getView()
* @param $name The new name for the view
* @param $owner The new owner for the view
* @param $comment The comment on the view
* @return 0 success
* @return -3 rename error
* @return -4 comment error
* @return -5 owner error
* @return -6 schema error
*/
protected
function _alterView($vwrs, $name, $owner, $schema, $comment) {
$this->fieldArrayClean($vwrs->fields);
// Comment
if ($this->setComment('VIEW', $vwrs->fields['relname'], '', $comment) != 0)
return -4;
// Owner
$this->fieldClean($owner);
$status = $this->alterViewOwner($vwrs, $owner);
if ($status != 0) return -5;
// Rename
$this->fieldClean($name);
$status = $this->alterViewName($vwrs, $name);
if ($status != 0) return -3;
// Schema
$this->fieldClean($schema);
$status = $this->alterViewSchema($vwrs, $schema);
if ($status != 0) return -6;
return 0;
}
/**
* Alter view properties
* @param $view The name of the view
* @param $name The new name for the view
* @param $owner The new owner for the view
* @param $schema The new schema for the view
* @param $comment The comment on the view
* @return 0 success
* @return -1 transaction error
* @return -2 get existing view error
* @return $this->_alterView error code
*/
function alterView($view, $name, $owner, $schema, $comment) {
$data = $this->getView($view);
if ($data->recordCount() != 1)
return -2;
$status = $this->beginTransaction();
if ($status != 0) {
$this->rollbackTransaction();
return -1;
}
$status = $this->_alterView($data, $name, $owner, $schema, $comment);
if ($status != 0) {
$this->rollbackTransaction();
return $status;
}
return $this->endTransaction();
}
/**
* Drops a view.
* @param $viewname The name of the view to drop
* @param $cascade True to cascade drop, false to restrict
* @return 0 success
*/
function dropView($viewname, $cascade) {
$f_schema = $this->_schema;
$this->fieldClean($f_schema);
$this->fieldClean($viewname);
$sql = "DROP VIEW \"{$f_schema}\".\"{$viewname}\"";
if ($cascade) $sql .= " CASCADE";
return $this->execute($sql);
}
// Index functions
/**
* Grabs a list of indexes for a table
* @param $table The name of a table whose indexes to retrieve
* @param $unique Only get unique/pk indexes
* @return A recordset
*/
function getIndexes($table = '', $unique = false) {
$this->clean($table);
$sql = "
SELECT c2.relname AS indname, i.indisprimary, i.indisunique, i.indisclustered,
pg_catalog.pg_get_indexdef(i.indexrelid, 0, true) AS inddef
FROM pg_catalog.pg_class c, pg_catalog.pg_class c2, pg_catalog.pg_index i
WHERE c.relname = '{$table}' AND pg_catalog.pg_table_is_visible(c.oid)
AND c.oid = i.indrelid AND i.indexrelid = c2.oid
";
if ($unique) $sql .= " AND i.indisunique ";
$sql .= " ORDER BY c2.relname";
return $this->selectSet($sql);
}
/**
* test if a table has been clustered on an index
* @param $table The table to test
*
* @return true if the table has been already clustered
*/
function alreadyClustered($table) {
$c_schema = $this->_schema;
$this->clean($c_schema);
$this->clean($table);
$sql = "SELECT i.indisclustered
FROM pg_catalog.pg_class c, pg_catalog.pg_index i
WHERE c.relname = '{$table}'
AND c.oid = i.indrelid AND i.indisclustered
AND c.relnamespace = (SELECT oid FROM pg_catalog.pg_namespace
WHERE nspname='{$c_schema}')
";
$v = $this->selectSet($sql);
if ($v->recordCount() == 0)
return false;
return true;
}
/**
* Creates an index
* @param $name The index name
* @param $table The table on which to add the index
* @param $columns An array of columns that form the index
* or a string expression for a functional index
* @param $type The index type
* @param $unique True if unique, false otherwise
* @param $where Index predicate ('' for none)
* @param $tablespace The tablespaces ('' means none/default)
* @return 0 success
*/
function createIndex($name, $table, $columns, $type, $unique, $where, $tablespace, $concurrently) {
$f_schema = $this->_schema;
$this->fieldClean($f_schema);
$this->fieldClean($name);
$this->fieldClean($table);
$sql = "CREATE";
if ($unique) $sql .= " UNIQUE";
$sql .= " INDEX";
if ($concurrently) $sql .= " CONCURRENTLY";
$sql .= " \"{$name}\" ON \"{$f_schema}\".\"{$table}\" USING {$type} ";
if (is_array($columns)) {
$this->arrayClean($columns);
$sql .= "(\"" . implode('","', $columns) . "\")";
} else {
$sql .= "(" . $columns .")";
}
// Tablespace
if ($this->hasTablespaces() && $tablespace != '') {
$this->fieldClean($tablespace);
$sql .= " TABLESPACE \"{$tablespace}\"";
}
// Predicate
if (trim($where) != '') {
$sql .= " WHERE ({$where})";
}
return $this->execute($sql);
}
/**
* Removes an index from the database
* @param $index The index to drop
* @param $cascade True to cascade drop, false to restrict
* @return 0 success
*/
function dropIndex($index, $cascade) {
$f_schema = $this->_schema;
$this->fieldClean($f_schema);
$this->fieldClean($index);
$sql = "DROP INDEX \"{$f_schema}\".\"{$index}\"";
if ($cascade) $sql .= " CASCADE";
return $this->execute($sql);
}
/**
* Rebuild indexes
* @param $type 'DATABASE' or 'TABLE' or 'INDEX'
* @param $name The name of the specific database, table, or index to be reindexed
* @param $force If true, recreates indexes forcedly in PostgreSQL 7.0-7.1, forces rebuild of system indexes in 7.2-7.3, ignored in >=7.4
*/
function reindex($type, $name, $force = false) {
$f_schema = $this->_schema;
$this->fieldClean($f_schema);
$this->fieldClean($name);
switch($type) {
case 'DATABASE':
$sql = "REINDEX {$type} \"{$name}\"";
if ($force) $sql .= ' FORCE';
break;
case 'TABLE':
case 'INDEX':
$sql = "REINDEX {$type} \"{$f_schema}\".\"{$name}\"";
if ($force) $sql .= ' FORCE';
break;
default:
return -1;
}
return $this->execute($sql);
}
/**
* Clusters an index
* @param $index The name of the index
* @param $table The table the index is on
* @return 0 success
*/
function clusterIndex($table='', $index='') {
$sql = 'CLUSTER';
// We don't bother with a transaction here, as there's no point rolling
// back an expensive cluster if a cheap analyze fails for whatever reason
if (!empty($table)) {
$f_schema = $this->_schema;
$this->fieldClean($f_schema);
$this->fieldClean($table);
$sql .= " \"{$f_schema}\".\"{$table}\"";
if (!empty($index)) {
$this->fieldClean($index);
$sql .= " USING \"{$index}\"";
}
}
return $this->execute($sql);
}
// Constraint functions
/**
* Returns a list of all constraints on a table
* @param $table The table to find rules for
* @return A recordset
*/
function getConstraints($table) {
$c_schema = $this->_schema;
$this->clean($c_schema);
$this->clean($table);
// This SQL is greatly complicated by the need to retrieve
// index clustering information for primary and unique constraints
$sql = "SELECT
pc.conname,
pg_catalog.pg_get_constraintdef(pc.oid, true) AS consrc,
pc.contype,
CASE WHEN pc.contype='u' OR pc.contype='p' THEN (
SELECT
indisclustered
FROM
pg_catalog.pg_depend pd,
pg_catalog.pg_class pl,
pg_catalog.pg_index pi
WHERE
pd.refclassid=pc.tableoid
AND pd.refobjid=pc.oid
AND pd.objid=pl.oid
AND pl.oid=pi.indexrelid
) ELSE
NULL
END AS indisclustered
FROM
pg_catalog.pg_constraint pc
WHERE
pc.conrelid = (SELECT oid FROM pg_catalog.pg_class WHERE relname='{$table}'
AND relnamespace = (SELECT oid FROM pg_catalog.pg_namespace
WHERE nspname='{$c_schema}'))
ORDER BY
1
";
return $this->selectSet($sql);
}
/**
* Returns a list of all constraints on a table,
* including constraint name, definition, related col and referenced namespace,
* table and col if needed
* @param $table the table where we are looking for fk
* @return a recordset
*/
function getConstraintsWithFields($table) {
$c_schema = $this->_schema;
$this->clean($c_schema);
$this->clean($table);
// get the max number of col used in a constraint for the table
$sql = "SELECT DISTINCT
max(SUBSTRING(array_dims(c.conkey) FROM \$patern\$^\\[.*:(.*)\\]$\$patern\$)) as nb
FROM pg_catalog.pg_constraint AS c
JOIN pg_catalog.pg_class AS r ON (c.conrelid=r.oid)
JOIN pg_catalog.pg_namespace AS ns ON (r.relnamespace=ns.oid)
WHERE
r.relname = '{$table}' AND ns.nspname='{$c_schema}'";
$rs = $this->selectSet($sql);
if ($rs->EOF) $max_col = 0;
else $max_col = $rs->fields['nb'];
$sql = '
SELECT
c.oid AS conid, c.contype, c.conname, pg_catalog.pg_get_constraintdef(c.oid, true) AS consrc,
ns1.nspname as p_schema, r1.relname as p_table, ns2.nspname as f_schema,
r2.relname as f_table, f1.attname as p_field, f1.attnum AS p_attnum, f2.attname as f_field,
f2.attnum AS f_attnum, pg_catalog.obj_description(c.oid, \'pg_constraint\') AS constcomment,
c.conrelid, c.confrelid
FROM
pg_catalog.pg_constraint AS c
JOIN pg_catalog.pg_class AS r1 ON (c.conrelid=r1.oid)
JOIN pg_catalog.pg_attribute AS f1 ON (f1.attrelid=r1.oid AND (f1.attnum=c.conkey[1]';
for ($i = 2; $i <= $rs->fields['nb']; $i++) {
$sql.= " OR f1.attnum=c.conkey[$i]";
}
$sql.= '))
JOIN pg_catalog.pg_namespace AS ns1 ON r1.relnamespace=ns1.oid
LEFT JOIN (
pg_catalog.pg_class AS r2 JOIN pg_catalog.pg_namespace AS ns2 ON (r2.relnamespace=ns2.oid)
) ON (c.confrelid=r2.oid)
LEFT JOIN pg_catalog.pg_attribute AS f2 ON
(f2.attrelid=r2.oid AND ((c.confkey[1]=f2.attnum AND c.conkey[1]=f1.attnum)';
for ($i = 2; $i <= $rs->fields['nb']; $i++)
$sql.= " OR (c.confkey[$i]=f2.attnum AND c.conkey[$i]=f1.attnum)";
$sql .= sprintf("))
WHERE
r1.relname = '%s' AND ns1.nspname='%s'
ORDER BY 1", $table, $c_schema);
return $this->selectSet($sql);
}
/**
* Adds a primary key constraint to a table
* @param $table The table to which to add the primery key
* @param $fields (array) An array of fields over which to add the primary key
* @param $name (optional) The name to give the key, otherwise default name is assigned
* @param $tablespace (optional) The tablespace for the schema, '' indicates default.
* @return 0 success
* @return -1 no fields given
*/
function addPrimaryKey($table, $fields, $name = '', $tablespace = '') {
if (!is_array($fields) || sizeof($fields) == 0) return -1;
$f_schema = $this->_schema;
$this->fieldClean($f_schema);
$this->fieldClean($table);
$this->fieldArrayClean($fields);
$this->fieldClean($name);
$this->fieldClean($tablespace);
$sql = "ALTER TABLE \"{$f_schema}\".\"{$table}\" ADD ";
if ($name != '') $sql .= "CONSTRAINT \"{$name}\" ";
$sql .= "PRIMARY KEY (\"" . join('","', $fields) . "\")";
if ($tablespace != '' && $this->hasTablespaces())
$sql .= " USING INDEX TABLESPACE \"{$tablespace}\"";
return $this->execute($sql);
}
/**
* Adds a unique constraint to a table
* @param $table The table to which to add the unique key
* @param $fields (array) An array of fields over which to add the unique key
* @param $name (optional) The name to give the key, otherwise default name is assigned
* @param $tablespace (optional) The tablespace for the schema, '' indicates default.
* @return 0 success
* @return -1 no fields given
*/
function addUniqueKey($table, $fields, $name = '', $tablespace = '') {
if (!is_array($fields) || sizeof($fields) == 0) return -1;
$f_schema = $this->_schema;
$this->fieldClean($f_schema);
$this->fieldClean($table);
$this->fieldArrayClean($fields);
$this->fieldClean($name);
$this->fieldClean($tablespace);
$sql = "ALTER TABLE \"{$f_schema}\".\"{$table}\" ADD ";
if ($name != '') $sql .= "CONSTRAINT \"{$name}\" ";
$sql .= "UNIQUE (\"" . join('","', $fields) . "\")";
if ($tablespace != '' && $this->hasTablespaces())
$sql .= " USING INDEX TABLESPACE \"{$tablespace}\"";
return $this->execute($sql);
}
/**
* Adds a check constraint to a table
* @param $table The table to which to add the check
* @param $definition The definition of the check
* @param $name (optional) The name to give the check, otherwise default name is assigned
* @return 0 success
*/
function addCheckConstraint($table, $definition, $name = '') {
$f_schema = $this->_schema;
$this->fieldClean($f_schema);
$this->fieldClean($table);
$this->fieldClean($name);
// @@ How the heck do you clean a definition???
$sql = "ALTER TABLE \"{$f_schema}\".\"{$table}\" ADD ";
if ($name != '') $sql .= "CONSTRAINT \"{$name}\" ";
$sql .= "CHECK ({$definition})";
return $this->execute($sql);
}
/**
* Drops a check constraint from a table
* @param $table The table from which to drop the check
* @param $name The name of the check to be dropped
* @return 0 success
* @return -2 transaction error
* @return -3 lock error
* @return -4 check drop error
*/
function dropCheckConstraint($table, $name) {
$f_schema = $this->_schema;
$this->fieldClean($f_schema);
$c_schema = $this->_schema;
$this->clean($c_schema);
$c_table = $table;
$this->fieldClean($table);
$this->clean($c_table);
$this->clean($name);
// Begin transaction
$status = $this->beginTransaction();
if ($status != 0) return -2;
// Properly lock the table
$sql = "LOCK TABLE \"{$f_schema}\".\"{$table}\" IN ACCESS EXCLUSIVE MODE";
$status = $this->execute($sql);
if ($status != 0) {
$this->rollbackTransaction();
return -3;
}
// Delete the check constraint
$sql = "DELETE FROM pg_relcheck WHERE rcrelid=(SELECT oid FROM pg_catalog.pg_class WHERE relname='{$c_table}'
AND relnamespace = (SELECT oid FROM pg_catalog.pg_namespace WHERE
nspname = '{$c_schema}')) AND rcname='{$name}'";
$status = $this->execute($sql);
if ($status != 0) {
$this->rollbackTransaction();
return -4;
}
// Update the pg_class catalog to reflect the new number of checks
$sql = "UPDATE pg_class SET relchecks=(SELECT COUNT(*) FROM pg_relcheck WHERE
rcrelid=(SELECT oid FROM pg_catalog.pg_class WHERE relname='{$c_table}'
AND relnamespace = (SELECT oid FROM pg_catalog.pg_namespace WHERE
nspname = '{$c_schema}')))
WHERE relname='{$c_table}'";
$status = $this->execute($sql);
if ($status != 0) {
$this->rollbackTransaction();
return -4;
}
// Otherwise, close the transaction
return $this->endTransaction();
}
/**
* Adds a foreign key constraint to a table
* @param $targschema The schema that houses the target table to which to add the foreign key
* @param $targtable The table to which to add the foreign key
* @param $target The table that contains the target columns
* @param $sfields (array) An array of source fields over which to add the foreign key
* @param $tfields (array) An array of target fields over which to add the foreign key
* @param $upd_action The action for updates (eg. RESTRICT)
* @param $del_action The action for deletes (eg. RESTRICT)
* @param $match The match type (eg. MATCH FULL)
* @param $deferrable The deferrability (eg. NOT DEFERRABLE)
* @param $intially The initial deferrability (eg. INITIALLY IMMEDIATE)
* @param $name (optional) The name to give the key, otherwise default name is assigned
* @return 0 success
* @return -1 no fields given
*/
function addForeignKey($table, $targschema, $targtable, $sfields, $tfields, $upd_action, $del_action,
$match, $deferrable, $initially, $name = '') {
if (!is_array($sfields) || sizeof($sfields) == 0 ||
!is_array($tfields) || sizeof($tfields) == 0) return -1;
$f_schema = $this->_schema;
$this->fieldClean($f_schema);
$this->fieldClean($table);
$this->fieldClean($targschema);
$this->fieldClean($targtable);
$this->fieldArrayClean($sfields);
$this->fieldArrayClean($tfields);
$this->fieldClean($name);
$sql = "ALTER TABLE \"{$f_schema}\".\"{$table}\" ADD ";
if ($name != '') $sql .= "CONSTRAINT \"{$name}\" ";
$sql .= "FOREIGN KEY (\"" . join('","', $sfields) . "\") ";
// Target table needs to be fully qualified
$sql .= "REFERENCES \"{$targschema}\".\"{$targtable}\"(\"" . join('","', $tfields) . "\") ";
if ($match != $this->fkmatches[0]) $sql .= " {$match}";
if ($upd_action != $this->fkactions[0]) $sql .= " ON UPDATE {$upd_action}";
if ($del_action != $this->fkactions[0]) $sql .= " ON DELETE {$del_action}";
if ($deferrable != $this->fkdeferrable[0]) $sql .= " {$deferrable}";
if ($initially != $this->fkinitial[0]) $sql .= " {$initially}";
return $this->execute($sql);
}
/**
* Removes a constraint from a relation
* @param $constraint The constraint to drop
* @param $relation The relation from which to drop
* @param $type The type of constraint (c, f, u or p)
* @param $cascade True to cascade drop, false to restrict
* @return 0 success
*/
function dropConstraint($constraint, $relation, $type, $cascade) {
$f_schema = $this->_schema;
$this->fieldClean($f_schema);
$this->fieldClean($constraint);
$this->fieldClean($relation);
$sql = "ALTER TABLE \"{$f_schema}\".\"{$relation}\" DROP CONSTRAINT \"{$constraint}\"";
if ($cascade) $sql .= " CASCADE";
return $this->execute($sql);
}
/**
* A function for getting all columns linked by foreign keys given a group of tables
* @param $tables multi dimensional assoc array that holds schema and table name
* @return A recordset of linked tables and columns
* @return -1 $tables isn't an array
*/
function getLinkingKeys($tables) {
if (!is_array($tables)) return -1;
$this->clean($tables[0]['tablename']);
$this->clean($tables[0]['schemaname']);
$tables_list = "'{$tables[0]['tablename']}'";
$schema_list = "'{$tables[0]['schemaname']}'";
$schema_tables_list = "'{$tables[0]['schemaname']}.{$tables[0]['tablename']}'";
for ($i = 1; $i < sizeof($tables); $i++) {
$this->clean($tables[$i]['tablename']);
$this->clean($tables[$i]['schemaname']);
$tables_list .= ", '{$tables[$i]['tablename']}'";
$schema_list .= ", '{$tables[$i]['schemaname']}'";
$schema_tables_list .= ", '{$tables[$i]['schemaname']}.{$tables[$i]['tablename']}'";
}
$maxDimension = 1;
$sql = "
SELECT DISTINCT
array_dims(pc.conkey) AS arr_dim,
pgc1.relname AS p_table
FROM
pg_catalog.pg_constraint AS pc,
pg_catalog.pg_class AS pgc1
WHERE
pc.contype = 'f'
AND (pc.conrelid = pgc1.relfilenode OR pc.confrelid = pgc1.relfilenode)
AND pgc1.relname IN ($tables_list)
";
//parse our output to find the highest dimension of foreign keys since pc.conkey is stored in an array
$rs = $this->selectSet($sql);
while (!$rs->EOF) {
$arrData = explode(':', $rs->fields['arr_dim']);
$tmpDimension = intval(substr($arrData[1], 0, strlen($arrData[1] - 1)));
$maxDimension = $tmpDimension > $maxDimension ? $tmpDimension : $maxDimension;
$rs->MoveNext();
}
//we know the highest index for foreign keys that conkey goes up to, expand for us in an IN query
$cons_str = '( (pfield.attnum = conkey[1] AND cfield.attnum = confkey[1]) ';
for ($i = 2; $i <= $maxDimension; $i++) {
$cons_str .= "OR (pfield.attnum = conkey[{$i}] AND cfield.attnum = confkey[{$i}]) ";
}
$cons_str .= ') ';
$sql = "
SELECT
pgc1.relname AS p_table,
pgc2.relname AS f_table,
pfield.attname AS p_field,
cfield.attname AS f_field,
pgns1.nspname AS p_schema,
pgns2.nspname AS f_schema
FROM
pg_catalog.pg_constraint AS pc,
pg_catalog.pg_class AS pgc1,
pg_catalog.pg_class AS pgc2,
pg_catalog.pg_attribute AS pfield,
pg_catalog.pg_attribute AS cfield,
(SELECT oid AS ns_id, nspname FROM pg_catalog.pg_namespace WHERE nspname IN ($schema_list) ) AS pgns1,
(SELECT oid AS ns_id, nspname FROM pg_catalog.pg_namespace WHERE nspname IN ($schema_list) ) AS pgns2
WHERE
pc.contype = 'f'
AND pgc1.relnamespace = pgns1.ns_id
AND pgc2.relnamespace = pgns2.ns_id
AND pc.conrelid = pgc1.relfilenode
AND pc.confrelid = pgc2.relfilenode
AND pfield.attrelid = pc.conrelid
AND cfield.attrelid = pc.confrelid
AND $cons_str
AND pgns1.nspname || '.' || pgc1.relname IN ($schema_tables_list)
AND pgns2.nspname || '.' || pgc2.relname IN ($schema_tables_list)
";
return $this->selectSet($sql);
}
/**
* Finds the foreign keys that refer to the specified table
* @param $table The table to find referrers for
* @return A recordset
*/
function getReferrers($table) {
$this->clean($table);
$status = $this->beginTransaction();
if ($status != 0) return -1;
$c_schema = $this->_schema;
$this->clean($c_schema);
$sql = "
SELECT
pn.nspname,
pl.relname,
pc.conname,
pg_catalog.pg_get_constraintdef(pc.oid) AS consrc
FROM
pg_catalog.pg_constraint pc,
pg_catalog.pg_namespace pn,
pg_catalog.pg_class pl
WHERE
pc.connamespace = pn.oid
AND pc.conrelid = pl.oid
AND pc.contype = 'f'
AND confrelid = (SELECT oid FROM pg_catalog.pg_class WHERE relname='{$table}'
AND relnamespace = (SELECT oid FROM pg_catalog.pg_namespace
WHERE nspname='{$c_schema}'))
ORDER BY 1,2,3
";
return $this->selectSet($sql);
}
// Domain functions
/**
* Gets all information for a single domain
* @param $domain The name of the domain to fetch
* @return A recordset
*/
function getDomain($domain) {
$c_schema = $this->_schema;
$this->clean($c_schema);
$this->clean($domain);
$sql = "
SELECT
t.typname AS domname,
pg_catalog.format_type(t.typbasetype, t.typtypmod) AS domtype,
t.typnotnull AS domnotnull,
t.typdefault AS domdef,
pg_catalog.pg_get_userbyid(t.typowner) AS domowner,
pg_catalog.obj_description(t.oid, 'pg_type') AS domcomment
FROM
pg_catalog.pg_type t
WHERE
t.typtype = 'd'
AND t.typname = '{$domain}'
AND t.typnamespace = (SELECT oid FROM pg_catalog.pg_namespace
WHERE nspname = '{$c_schema}')";
return $this->selectSet($sql);
}
/**
* Return all domains in current schema. Excludes domain constraints.
* @return All tables, sorted alphabetically
*/
function getDomains() {
$c_schema = $this->_schema;
$this->clean($c_schema);
$sql = "
SELECT
t.typname AS domname,
pg_catalog.format_type(t.typbasetype, t.typtypmod) AS domtype,
t.typnotnull AS domnotnull,
t.typdefault AS domdef,
pg_catalog.pg_get_userbyid(t.typowner) AS domowner,
pg_catalog.obj_description(t.oid, 'pg_type') AS domcomment
FROM
pg_catalog.pg_type t
WHERE
t.typtype = 'd'
AND t.typnamespace = (SELECT oid FROM pg_catalog.pg_namespace
WHERE nspname='{$c_schema}')
ORDER BY t.typname";
return $this->selectSet($sql);
}
/**
* Get domain constraints
* @param $domain The name of the domain whose constraints to fetch
* @return A recordset
*/
function getDomainConstraints($domain) {
$c_schema = $this->_schema;
$this->clean($c_schema);
$this->clean($domain);
$sql = "
SELECT
conname,
contype,
pg_catalog.pg_get_constraintdef(oid, true) AS consrc
FROM
pg_catalog.pg_constraint
WHERE
contypid = (
SELECT oid FROM pg_catalog.pg_type
WHERE typname='{$domain}'
AND typnamespace = (
SELECT oid FROM pg_catalog.pg_namespace
WHERE nspname = '{$c_schema}')
)
ORDER BY conname";
return $this->selectSet($sql);
}
/**
* Creates a domain
* @param $domain The name of the domain to create
* @param $type The base type for the domain
* @param $length Optional type length
* @param $array True for array type, false otherwise
* @param $notnull True for NOT NULL, false otherwise
* @param $default Default value for domain
* @param $check A CHECK constraint if there is one
* @return 0 success
*/
function createDomain($domain, $type, $length, $array, $notnull, $default, $check) {
$f_schema = $this->_schema;
$this->fieldClean($f_schema);
$this->fieldClean($domain);
$sql = "CREATE DOMAIN \"{$f_schema}\".\"{$domain}\" AS ";
if ($length == '')
$sql .= $type;
else {
switch ($type) {
// Have to account for weird placing of length for with/without
// time zone types
case 'timestamp with time zone':
case 'timestamp without time zone':
$qual = substr($type, 9);
$sql .= "timestamp({$length}){$qual}";
break;
case 'time with time zone':
case 'time without time zone':
$qual = substr($type, 4);
$sql .= "time({$length}){$qual}";
break;
default:
$sql .= "{$type}({$length})";
}
}
// Add array qualifier, if requested
if ($array) $sql .= '[]';
if ($notnull) $sql .= ' NOT NULL';
if ($default != '') $sql .= " DEFAULT {$default}";
if ($this->hasDomainConstraints() && $check != '') $sql .= " CHECK ({$check})";
return $this->execute($sql);
}
/**
* Alters a domain
* @param $domain The domain to alter
* @param $domdefault The domain default
* @param $domnotnull True for NOT NULL, false otherwise
* @param $domowner The domain owner
* @return 0 success
* @return -1 transaction error
* @return -2 default error
* @return -3 not null error
* @return -4 owner error
*/
function alterDomain($domain, $domdefault, $domnotnull, $domowner) {
$f_schema = $this->_schema;
$this->fieldClean($f_schema);
$this->fieldClean($domain);
$this->fieldClean($domowner);
$status = $this->beginTransaction();
if ($status != 0) {
$this->rollbackTransaction();
return -1;
}
// Default
if ($domdefault == '')
$sql = "ALTER DOMAIN \"{$f_schema}\".\"{$domain}\" DROP DEFAULT";
else
$sql = "ALTER DOMAIN \"{$f_schema}\".\"{$domain}\" SET DEFAULT {$domdefault}";
$status = $this->execute($sql);
if ($status != 0) {
$this->rollbackTransaction();
return -2;
}
// NOT NULL
if ($domnotnull)
$sql = "ALTER DOMAIN \"{$f_schema}\".\"{$domain}\" SET NOT NULL";
else
$sql = "ALTER DOMAIN \"{$f_schema}\".\"{$domain}\" DROP NOT NULL";
$status = $this->execute($sql);
if ($status != 0) {
$this->rollbackTransaction();
return -3;
}
// Owner
$sql = "ALTER DOMAIN \"{$f_schema}\".\"{$domain}\" OWNER TO \"{$domowner}\"";
$status = $this->execute($sql);
if ($status != 0) {
$this->rollbackTransaction();
return -4;
}
return $this->endTransaction();
}
/**
* Drops a domain.
* @param $domain The name of the domain to drop
* @param $cascade True to cascade drop, false to restrict
* @return 0 success
*/
function dropDomain($domain, $cascade) {
$f_schema = $this->_schema;
$this->fieldClean($f_schema);
$this->fieldClean($domain);
$sql = "DROP DOMAIN \"{$f_schema}\".\"{$domain}\"";
if ($cascade) $sql .= " CASCADE";
return $this->execute($sql);
}
/**
* Adds a check constraint to a domain
* @param $domain The domain to which to add the check
* @param $definition The definition of the check
* @param $name (optional) The name to give the check, otherwise default name is assigned
* @return 0 success
*/
function addDomainCheckConstraint($domain, $definition, $name = '') {
$f_schema = $this->_schema;
$this->fieldClean($f_schema);
$this->fieldClean($domain);
$this->fieldClean($name);
$sql = "ALTER DOMAIN \"{$f_schema}\".\"{$domain}\" ADD ";
if ($name != '') $sql .= "CONSTRAINT \"{$name}\" ";
$sql .= "CHECK ({$definition})";
return $this->execute($sql);
}
/**
* Drops a domain constraint
* @param $domain The domain from which to remove the constraint
* @param $constraint The constraint to remove
* @param $cascade True to cascade, false otherwise
* @return 0 success
*/
function dropDomainConstraint($domain, $constraint, $cascade) {
$f_schema = $this->_schema;
$this->fieldClean($f_schema);
$this->fieldClean($domain);
$this->fieldClean($constraint);
$sql = "ALTER DOMAIN \"{$f_schema}\".\"{$domain}\" DROP CONSTRAINT \"{$constraint}\"";
if ($cascade) $sql .= " CASCADE";
return $this->execute($sql);
}
// Function functions
/**
* Returns all details for a particular function
* @param $func The name of the function to retrieve
* @return Function info
*/
function getFunction($function_oid) {
$this->clean($function_oid);
$sql = "
SELECT
pc.oid AS prooid, proname, pg_catalog.pg_get_userbyid(proowner) AS proowner,
nspname as proschema, lanname as prolanguage, procost, prorows,
pg_catalog.format_type(prorettype, NULL) as proresult, prosrc,
probin, proretset, proisstrict, provolatile, prosecdef,
pg_catalog.oidvectortypes(pc.proargtypes) AS proarguments,
proargnames AS proargnames,
pg_catalog.obj_description(pc.oid, 'pg_proc') AS procomment,
proconfig
FROM
pg_catalog.pg_proc pc, pg_catalog.pg_language pl,
pg_catalog.pg_namespace pn
WHERE
pc.oid = '{$function_oid}'::oid AND pc.prolang = pl.oid
AND pc.pronamespace = pn.oid
";
return $this->selectSet($sql);
}
/**
* Returns a list of all functions in the database
* @param $all If true, will find all available functions, if false just those in search path
* @param $type If not null, will find all functions with return value = type
*
* @return All functions
*/
function getFunctions($all = false, $type = null) {
if ($all) {
$where = 'pg_catalog.pg_function_is_visible(p.oid)';
$distinct = 'DISTINCT ON (p.proname)';
if ($type) {
$where .= " AND p.prorettype = (select oid from pg_catalog.pg_type p where p.typname = 'trigger') ";
}
}
else {
$c_schema = $this->_schema;
$this->clean($c_schema);
$where = "n.nspname = '{$c_schema}'";
$distinct = '';
}
$sql = "
SELECT
{$distinct}
p.oid AS prooid,
p.proname,
p.proretset,
pg_catalog.format_type(p.prorettype, NULL) AS proresult,
pg_catalog.oidvectortypes(p.proargtypes) AS proarguments,
pl.lanname AS prolanguage,
pg_catalog.obj_description(p.oid, 'pg_proc') AS procomment,
p.proname || ' (' || pg_catalog.oidvectortypes(p.proargtypes) || ')' AS proproto,
CASE WHEN p.proretset THEN 'setof ' ELSE '' END || pg_catalog.format_type(p.prorettype, NULL) AS proreturns,
u.usename AS proowner
FROM pg_catalog.pg_proc p
INNER JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace
INNER JOIN pg_catalog.pg_language pl ON pl.oid = p.prolang
LEFT JOIN pg_catalog.pg_user u ON u.usesysid = p.proowner
WHERE NOT p.proisagg
AND {$where}
ORDER BY p.proname, proresult
";
return $this->selectSet($sql);
}
/**
* Returns an array containing a function's properties
* @param $f The array of data for the function
* @return An array containing the properties
*/
function getFunctionProperties($f) {
$temp = array();
// Volatility
if ($f['provolatile'] == 'v')
$temp[] = 'VOLATILE';
elseif ($f['provolatile'] == 'i')
$temp[] = 'IMMUTABLE';
elseif ($f['provolatile'] == 's')
$temp[] = 'STABLE';
else
return -1;
// Null handling
$f['proisstrict'] = $this->phpBool($f['proisstrict']);
if ($f['proisstrict'])
$temp[] = 'RETURNS NULL ON NULL INPUT';
else
$temp[] = 'CALLED ON NULL INPUT';
// Security
$f['prosecdef'] = $this->phpBool($f['prosecdef']);
if ($f['prosecdef'])
$temp[] = 'SECURITY DEFINER';
else
$temp[] = 'SECURITY INVOKER';
return $temp;
}
/**
* Updates (replaces) a function.
* @param $function_oid The OID of the function
* @param $funcname The name of the function to create
* @param $newname The new name for the function
* @param $args The array of argument types
* @param $returns The return type
* @param $definition The definition for the new function
* @param $language The language the function is written for
* @param $flags An array of optional flags
* @param $setof True if returns a set, false otherwise
* @param $comment The comment on the function
* @return 0 success
* @return -1 transaction error
* @return -3 create function error
* @return -4 comment error
* @return -5 rename function error
* @return -6 alter owner error
* @return -7 alter schema error
*/
function setFunction($function_oid, $funcname, $newname, $args, $returns, $definition, $language, $flags, $setof, $funcown, $newown, $funcschema, $newschema, $cost, $rows, $comment) {
// Begin a transaction
$status = $this->beginTransaction();
if ($status != 0) {
$this->rollbackTransaction();
return -1;
}
// Replace the existing function
$status = $this->createFunction($funcname, $args, $returns, $definition, $language, $flags, $setof, $cost, $rows, $comment, true);
if ($status != 0) {
$this->rollbackTransaction();
return $status;
}
$f_schema = $this->_schema;
$this->fieldClean($f_schema);
// Rename the function, if necessary
$this->fieldClean($newname);
/* $funcname is escaped in createFunction */
if ($funcname != $newname) {
$sql = "ALTER FUNCTION \"{$f_schema}\".\"{$funcname}\"({$args}) RENAME TO \"{$newname}\"";
$status = $this->execute($sql);
if ($status != 0) {
$this->rollbackTransaction();
return -5;
}
$funcname = $newname;
}
// Alter the owner, if necessary
if ($this->hasFunctionAlterOwner()) {
$this->fieldClean($newown);
if ($funcown != $newown) {
$sql = "ALTER FUNCTION \"{$f_schema}\".\"{$funcname}\"({$args}) OWNER TO \"{$newown}\"";
$status = $this->execute($sql);
if ($status != 0) {
$this->rollbackTransaction();
return -6;
}
}
}
// Alter the schema, if necessary
if ($this->hasFunctionAlterSchema()) {
$this->fieldClean($newschema);
/* $funcschema is escaped in createFunction */
if ($funcschema != $newschema) {
$sql = "ALTER FUNCTION \"{$f_schema}\".\"{$funcname}\"({$args}) SET SCHEMA \"{$newschema}\"";
$status = $this->execute($sql);
if ($status != 0) {
$this->rollbackTransaction();
return -7;
}
}
}
return $this->endTransaction();
}
/**
* Creates a new function.
* @param $funcname The name of the function to create
* @param $args A comma separated string of types
* @param $returns The return type
* @param $definition The definition for the new function
* @param $language The language the function is written for
* @param $flags An array of optional flags
* @param $setof True if it returns a set, false otherwise
* @param $rows number of rows planner should estimate will be returned
* @param $cost cost the planner should use in the function execution step
* @param $comment Comment for the function
* @param $replace (optional) True if OR REPLACE, false for normal
* @return 0 success
* @return -3 create function failed
* @return -4 set comment failed
*/
function createFunction($funcname, $args, $returns, $definition, $language, $flags, $setof, $cost, $rows, $comment, $replace = false) {
// Begin a transaction
$status = $this->beginTransaction();
if ($status != 0) {
$this->rollbackTransaction();
return -1;
}
$this->fieldClean($funcname);
$this->clean($args);
$this->fieldClean($language);
$this->arrayClean($flags);
$this->clean($cost);
$this->clean($rows);
$f_schema = $this->_schema;
$this->fieldClean($f_schema);
$sql = "CREATE";
if ($replace) $sql .= " OR REPLACE";
$sql .= " FUNCTION \"{$f_schema}\".\"{$funcname}\" (";
if ($args != '')
$sql .= $args;
// For some reason, the returns field cannot have quotes...
$sql .= ") RETURNS ";
if ($setof) $sql .= "SETOF ";
$sql .= "{$returns} AS ";
if (is_array($definition)) {
$this->arrayClean($definition);
$sql .= "'" . $definition[0] . "'";
if ($definition[1]) {
$sql .= ",'" . $definition[1] . "'";
}
} else {
$this->clean($definition);
$sql .= "'" . $definition . "'";
}
$sql .= " LANGUAGE \"{$language}\"";
// Add costs
if (!empty($cost))
$sql .= " COST {$cost}";
if ($rows <> 0 ){
$sql .= " ROWS {$rows}";
}
// Add flags
foreach ($flags as $v) {
// Skip default flags
if ($v == '') continue;
else $sql .= "\n{$v}";
}
$status = $this->execute($sql);
if ($status != 0) {
$this->rollbackTransaction();
return -3;
}
/* set the comment */
$status = $this->setComment('FUNCTION', "\"{$funcname}\"({$args})", null, $comment);
if ($status != 0) {
$this->rollbackTransaction();
return -4;
}
return $this->endTransaction();
}
/**
* Drops a function.
* @param $function_oid The OID of the function to drop
* @param $cascade True to cascade drop, false to restrict
* @return 0 success
*/
function dropFunction($function_oid, $cascade) {
// Function comes in with $object as function OID
$fn = $this->getFunction($function_oid);
$f_schema = $this->_schema;
$this->fieldClean($f_schema);
$this->fieldClean($fn->fields['proname']);
$sql = "DROP FUNCTION \"{$f_schema}\".\"{$fn->fields['proname']}\"({$fn->fields['proarguments']})";
if ($cascade) $sql .= " CASCADE";
return $this->execute($sql);
}
// Type functions
/**
* Returns all details for a particular type
* @param $typname The name of the view to retrieve
* @return Type info
*/
function getType($typname) {
$this->clean($typname);
$sql = "SELECT typtype, typbyval, typname, typinput AS typin, typoutput AS typout, typlen, typalign
FROM pg_type WHERE typname='{$typname}'";
return $this->selectSet($sql);
}
/**
* Returns a list of all types in the database
* @param $all If true, will find all available types, if false just those in search path
* @param $tabletypes If true, will include table types
* @param $domains If true, will include domains
* @return A recordet
*/
function getTypes($all = false, $tabletypes = false, $domains = false) {
if ($all)
$where = '1 = 1';
else {
$c_schema = $this->_schema;
$this->clean($c_schema);
$where = "n.nspname = '{$c_schema}'";
}
// Never show system table types
$where2 = "AND c.relnamespace NOT IN (SELECT oid FROM pg_catalog.pg_namespace WHERE nspname LIKE 'pg@_%' ESCAPE '@')";
// Create type filter
$tqry = "'c'";
if ($tabletypes)
$tqry .= ", 'r', 'v'";
// Create domain filter
if (!$domains)
$where .= " AND t.typtype != 'd'";
$sql = "SELECT
t.typname AS basename,
pg_catalog.format_type(t.oid, NULL) AS typname,
pu.usename AS typowner,
t.typtype,
pg_catalog.obj_description(t.oid, 'pg_type') AS typcomment
FROM (pg_catalog.pg_type t
LEFT JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace)
LEFT JOIN pg_catalog.pg_user pu ON t.typowner = pu.usesysid
WHERE (t.typrelid = 0 OR (SELECT c.relkind IN ({$tqry}) FROM pg_catalog.pg_class c WHERE c.oid = t.typrelid {$where2}))
AND t.typname !~ '^_'
AND {$where}
ORDER BY typname
";
return $this->selectSet($sql);
}
/**
* Creates a new type
* @param ...
* @return 0 success
*/
function createType($typname, $typin, $typout, $typlen, $typdef,
$typelem, $typdelim, $typbyval, $typalign, $typstorage) {
$f_schema = $this->_schema;
$this->fieldClean($f_schema);
$this->fieldClean($typname);
$this->fieldClean($typin);
$this->fieldClean($typout);
$sql = "
CREATE TYPE \"{$f_schema}\".\"{$typname}\" (
INPUT = \"{$typin}\",
OUTPUT = \"{$typout}\",
INTERNALLENGTH = {$typlen}";
if ($typdef != '') $sql .= ", DEFAULT = {$typdef}";
if ($typelem != '') $sql .= ", ELEMENT = {$typelem}";
if ($typdelim != '') $sql .= ", DELIMITER = {$typdelim}";
if ($typbyval) $sql .= ", PASSEDBYVALUE, ";
if ($typalign != '') $sql .= ", ALIGNMENT = {$typalign}";
if ($typstorage != '') $sql .= ", STORAGE = {$typstorage}";
$sql .= ")";
return $this->execute($sql);
}
/**
* Drops a type.
* @param $typname The name of the type to drop
* @param $cascade True to cascade drop, false to restrict
* @return 0 success
*/
function dropType($typname, $cascade) {
$f_schema = $this->_schema;
$this->fieldClean($f_schema);
$this->fieldClean($typname);
$sql = "DROP TYPE \"{$f_schema}\".\"{$typname}\"";
if ($cascade) $sql .= " CASCADE";
return $this->execute($sql);
}
/**
* Creates a new enum type in the database
* @param $name The name of the type
* @param $values An array of values
* @param $typcomment Type comment
* @return 0 success
* @return -1 transaction error
* @return -2 no values supplied
*/
function createEnumType($name, $values, $typcomment) {
$f_schema = $this->_schema;
$this->fieldClean($f_schema);
$this->fieldClean($name);
if (empty($values)) return -2;
$status = $this->beginTransaction();
if ($status != 0) return -1;
$values = array_unique($values);
$nbval = count($values);
for ($i = 0; $i < $nbval; $i++)
$this->clean($values[$i]);
$sql = "CREATE TYPE \"{$f_schema}\".\"{$name}\" AS ENUM ('";
$sql.= implode("','", $values);
$sql .= "')";
$status = $this->execute($sql);
if ($status) {
$this->rollbackTransaction();
return -1;
}
if ($typcomment != '') {
$status = $this->setComment('TYPE', $name, '', $typcomment, true);
if ($status) {
$this->rollbackTransaction();
return -1;
}
}
return $this->endTransaction();
}
/**
* Get defined values for a given enum
* @return A recordset
*/
function getEnumValues($name) {
$this->clean($name);
$sql = "SELECT enumlabel AS enumval
FROM pg_catalog.pg_type t JOIN pg_catalog.pg_enum e ON (t.oid=e.enumtypid)
WHERE t.typname = '{$name}' ORDER BY e.oid";
return $this->selectSet($sql);
}
/**
* Creates a new composite type in the database
* @param $name The name of the type
* @param $fields The number of fields
* @param $field An array of field names
* @param $type An array of field types
* @param $array An array of '' or '[]' for each type if it's an array or not
* @param $length An array of field lengths
* @param $colcomment An array of comments
* @param $typcomment Type comment
* @return 0 success
* @return -1 no fields supplied
*/
function createCompositeType($name, $fields, $field, $type, $array, $length, $colcomment, $typcomment) {
$f_schema = $this->_schema;
$this->fieldClean($f_schema);
$this->fieldClean($name);
$status = $this->beginTransaction();
if ($status != 0) return -1;
$found = false;
$first = true;
$comment_sql = ''; // Accumulate comments for the columns
$sql = "CREATE TYPE \"{$f_schema}\".\"{$name}\" AS (";
for ($i = 0; $i < $fields; $i++) {
$this->fieldClean($field[$i]);
$this->clean($type[$i]);
$this->clean($length[$i]);
$this->clean($colcomment[$i]);
// Skip blank columns - for user convenience
if ($field[$i] == '' || $type[$i] == '') continue;
// If not the first column, add a comma
if (!$first) $sql .= ", ";
else $first = false;
switch ($type[$i]) {
// Have to account for weird placing of length for with/without
// time zone types
case 'timestamp with time zone':
case 'timestamp without time zone':
$qual = substr($type[$i], 9);
$sql .= "\"{$field[$i]}\" timestamp";
if ($length[$i] != '') $sql .= "({$length[$i]})";
$sql .= $qual;
break;
case 'time with time zone':
case 'time without time zone':
$qual = substr($type[$i], 4);
$sql .= "\"{$field[$i]}\" time";
if ($length[$i] != '') $sql .= "({$length[$i]})";
$sql .= $qual;
break;
default:
$sql .= "\"{$field[$i]}\" {$type[$i]}";
if ($length[$i] != '') $sql .= "({$length[$i]})";
}
// Add array qualifier if necessary
if ($array[$i] == '[]') $sql .= '[]';
if ($colcomment[$i] != '') $comment_sql .= "COMMENT ON COLUMN \"{$f_schema}\".\"{$name}\".\"{$field[$i]}\" IS '{$colcomment[$i]}';\n";
$found = true;
}
if (!$found) return -1;
$sql .= ")";
$status = $this->execute($sql);
if ($status) {
$this->rollbackTransaction();
return -1;
}
if ($typcomment != '') {
$status = $this->setComment('TYPE', $name, '', $typcomment, true);
if ($status) {
$this->rollbackTransaction();
return -1;
}
}
if ($comment_sql != '') {
$status = $this->execute($comment_sql);
if ($status) {
$this->rollbackTransaction();
return -1;
}
}
return $this->endTransaction();
}
/**
* Returns a list of all casts in the database
* @return All casts
*/
function getCasts() {
global $conf;
if ($conf['show_system'])
$where = '';
else
$where = '
AND n1.nspname NOT LIKE $$pg\_%$$
AND n2.nspname NOT LIKE $$pg\_%$$
AND n3.nspname NOT LIKE $$pg\_%$$
';
$sql = "
SELECT
c.castsource::pg_catalog.regtype AS castsource,
c.casttarget::pg_catalog.regtype AS casttarget,
CASE WHEN c.castfunc=0 THEN NULL
ELSE c.castfunc::pg_catalog.regprocedure END AS castfunc,
c.castcontext,
obj_description(c.oid, 'pg_cast') as castcomment
FROM
(pg_catalog.pg_cast c LEFT JOIN pg_catalog.pg_proc p ON c.castfunc=p.oid JOIN pg_catalog.pg_namespace n3 ON p.pronamespace=n3.oid),
pg_catalog.pg_type t1,
pg_catalog.pg_type t2,
pg_catalog.pg_namespace n1,
pg_catalog.pg_namespace n2
WHERE
c.castsource=t1.oid
AND c.casttarget=t2.oid
AND t1.typnamespace=n1.oid
AND t2.typnamespace=n2.oid
{$where}
ORDER BY 1, 2
";
return $this->selectSet($sql);
}
/**
* Returns a list of all conversions in the database
* @return All conversions
*/
function getConversions() {
$c_schema = $this->_schema;
$this->clean($c_schema);
$sql = "
SELECT
c.conname,
pg_catalog.pg_encoding_to_char(c.conforencoding) AS conforencoding,
pg_catalog.pg_encoding_to_char(c.contoencoding) AS contoencoding,
c.condefault,
pg_catalog.obj_description(c.oid, 'pg_conversion') AS concomment
FROM pg_catalog.pg_conversion c, pg_catalog.pg_namespace n
WHERE n.oid = c.connamespace
AND n.nspname='{$c_schema}'
ORDER BY 1;
";
return $this->selectSet($sql);
}
// Rule functions
/**
* Returns a list of all rules on a table OR view
* @param $table The table to find rules for
* @return A recordset
*/
function getRules($table) {
$c_schema = $this->_schema;
$this->clean($c_schema);
$this->clean($table);
$sql = "
SELECT *
FROM pg_catalog.pg_rules
WHERE
schemaname='{$c_schema}' AND tablename='{$table}'
ORDER BY rulename
";
return $this->selectSet($sql);
}
/**
* Edits a rule on a table OR view
* @param $name The name of the new rule
* @param $event SELECT, INSERT, UPDATE or DELETE
* @param $table Table on which to create the rule
* @param $where When to execute the rule, '' indicates always
* @param $instead True if an INSTEAD rule, false otherwise
* @param $type NOTHING for a do nothing rule, SOMETHING to use given action
* @param $action The action to take
* @return 0 success
* @return -1 invalid event
*/
function setRule($name, $event, $table, $where, $instead, $type, $action) {
return $this->createRule($name, $event, $table, $where, $instead, $type, $action, true);
}
/**
* Creates a rule
* @param $name The name of the new rule
* @param $event SELECT, INSERT, UPDATE or DELETE
* @param $table Table on which to create the rule
* @param $where When to execute the rule, '' indicates always
* @param $instead True if an INSTEAD rule, false otherwise
* @param $type NOTHING for a do nothing rule, SOMETHING to use given action
* @param $action The action to take
* @param $replace (optional) True to replace existing rule, false otherwise
* @return 0 success
* @return -1 invalid event
*/
function createRule($name, $event, $table, $where, $instead, $type, $action, $replace = false) {
$f_schema = $this->_schema;
$this->fieldClean($f_schema);
$this->fieldClean($name);
$this->fieldClean($table);
if (!in_array($event, $this->rule_events)) return -1;
$sql = "CREATE";
if ($replace) $sql .= " OR REPLACE";
$sql .= " RULE \"{$name}\" AS ON {$event} TO \"{$f_schema}\".\"{$table}\"";
// Can't escape WHERE clause
if ($where != '') $sql .= " WHERE {$where}";
$sql .= " DO";
if ($instead) $sql .= " INSTEAD";
if ($type == 'NOTHING')
$sql .= " NOTHING";
else $sql .= " ({$action})";
return $this->execute($sql);
}
/**
* Removes a rule from a table OR view
* @param $rule The rule to drop
* @param $relation The relation from which to drop
* @param $cascade True to cascade drop, false to restrict
* @return 0 success
*/
function dropRule($rule, $relation, $cascade) {
$f_schema = $this->_schema;
$this->fieldClean($f_schema);
$this->fieldClean($rule);
$this->fieldClean($relation);
$sql = "DROP RULE \"{$rule}\" ON \"{$f_schema}\".\"{$relation}\"";
if ($cascade) $sql .= " CASCADE";
return $this->execute($sql);
}
// Trigger functions
/**
* Grabs a single trigger
* @param $table The name of a table whose triggers to retrieve
* @param $trigger The name of the trigger to retrieve
* @return A recordset
*/
function getTrigger($table, $trigger) {
$c_schema = $this->_schema;
$this->clean($c_schema);
$this->clean($table);
$this->clean($trigger);
$sql = "
SELECT * FROM pg_catalog.pg_trigger t, pg_catalog.pg_class c
WHERE t.tgrelid=c.oid AND c.relname='{$table}' AND t.tgname='{$trigger}'
AND c.relnamespace=(
SELECT oid FROM pg_catalog.pg_namespace
WHERE nspname='{$c_schema}')";
return $this->selectSet($sql);
}
/**
* Grabs a list of triggers on a table
* @param $table The name of a table whose triggers to retrieve
* @return A recordset
*/
function getTriggers($table = '') {
$c_schema = $this->_schema;
$this->clean($c_schema);
$this->clean($table);
$sql = "SELECT
t.tgname, pg_catalog.pg_get_triggerdef(t.oid) AS tgdef,
CASE WHEN t.tgenabled = 'D' THEN FALSE ELSE TRUE END AS tgenabled, p.oid AS prooid,
p.proname || ' (' || pg_catalog.oidvectortypes(p.proargtypes) || ')' AS proproto,
ns.nspname AS pronamespace
FROM pg_catalog.pg_trigger t, pg_catalog.pg_proc p, pg_catalog.pg_namespace ns
WHERE t.tgrelid = (SELECT oid FROM pg_catalog.pg_class WHERE relname='{$table}'
AND relnamespace=(SELECT oid FROM pg_catalog.pg_namespace WHERE nspname='{$c_schema}'))
AND ( tgconstraint = 0 OR NOT EXISTS
(SELECT 1 FROM pg_catalog.pg_depend d JOIN pg_catalog.pg_constraint c
ON (d.refclassid = c.tableoid AND d.refobjid = c.oid)
WHERE d.classid = t.tableoid AND d.objid = t.oid AND d.deptype = 'i' AND c.contype = 'f'))
AND p.oid=t.tgfoid
AND p.pronamespace = ns.oid";
return $this->selectSet($sql);
}
/**
* A helper function for getTriggers that translates
* an array of attribute numbers to an array of field names.
* Note: Only needed for pre-7.4 servers, this function is deprecated
* @param $trigger An array containing fields from the trigger table
* @return The trigger definition string
*/
function getTriggerDef($trigger) {
$this->fieldArrayClean($trigger);
// Constants to figure out tgtype
if (!defined('TRIGGER_TYPE_ROW')) define ('TRIGGER_TYPE_ROW', (1 << 0));
if (!defined('TRIGGER_TYPE_BEFORE')) define ('TRIGGER_TYPE_BEFORE', (1 << 1));
if (!defined('TRIGGER_TYPE_INSERT')) define ('TRIGGER_TYPE_INSERT', (1 << 2));
if (!defined('TRIGGER_TYPE_DELETE')) define ('TRIGGER_TYPE_DELETE', (1 << 3));
if (!defined('TRIGGER_TYPE_UPDATE')) define ('TRIGGER_TYPE_UPDATE', (1 << 4));
$trigger['tgisconstraint'] = $this->phpBool($trigger['tgisconstraint']);
$trigger['tgdeferrable'] = $this->phpBool($trigger['tgdeferrable']);
$trigger['tginitdeferred'] = $this->phpBool($trigger['tginitdeferred']);
// Constraint trigger or normal trigger
if ($trigger['tgisconstraint'])
$tgdef = 'CREATE CONSTRAINT TRIGGER ';
else
$tgdef = 'CREATE TRIGGER ';
$tgdef .= "\"{$trigger['tgname']}\" ";
// Trigger type
$findx = 0;
if (($trigger['tgtype'] & TRIGGER_TYPE_BEFORE) == TRIGGER_TYPE_BEFORE)
$tgdef .= 'BEFORE';
else
$tgdef .= 'AFTER';
if (($trigger['tgtype'] & TRIGGER_TYPE_INSERT) == TRIGGER_TYPE_INSERT) {
$tgdef .= ' INSERT';
$findx++;
}
if (($trigger['tgtype'] & TRIGGER_TYPE_DELETE) == TRIGGER_TYPE_DELETE) {
if ($findx > 0)
$tgdef .= ' OR DELETE';
else {
$tgdef .= ' DELETE';
$findx++;
}
}
if (($trigger['tgtype'] & TRIGGER_TYPE_UPDATE) == TRIGGER_TYPE_UPDATE) {
if ($findx > 0)
$tgdef .= ' OR UPDATE';
else
$tgdef .= ' UPDATE';
}
$f_schema = $this->_schema;
$this->fieldClean($f_schema);
// Table name
$tgdef .= " ON \"{$f_schema}\".\"{$trigger['relname']}\" ";
// Deferrability
if ($trigger['tgisconstraint']) {
if ($trigger['tgconstrrelid'] != 0) {
// Assume constrelname is not null
$tgdef .= " FROM \"{$trigger['tgconstrrelname']}\" ";
}
if (!$trigger['tgdeferrable'])
$tgdef .= 'NOT ';
$tgdef .= 'DEFERRABLE INITIALLY ';
if ($trigger['tginitdeferred'])
$tgdef .= 'DEFERRED ';
else
$tgdef .= 'IMMEDIATE ';
}
// Row or statement
if ($trigger['tgtype'] & TRIGGER_TYPE_ROW == TRIGGER_TYPE_ROW)
$tgdef .= 'FOR EACH ROW ';
else
$tgdef .= 'FOR EACH STATEMENT ';
// Execute procedure
$tgdef .= "EXECUTE PROCEDURE \"{$trigger['tgfname']}\"(";
// Parameters
// Escape null characters
$v = addCSlashes($trigger['tgargs'], "\0");
// Split on escaped null characters
$params = explode('\\000', $v);
for ($findx = 0; $findx < $trigger['tgnargs']; $findx++) {
$param = "'" . str_replace('\'', '\\\'', $params[$findx]) . "'";
$tgdef .= $param;
if ($findx < ($trigger['tgnargs'] - 1))
$tgdef .= ', ';
}
// Finish it off
$tgdef .= ')';
return $tgdef;
}
/**
* Returns a list of all functions that can be used in triggers
*/
function getTriggerFunctions() {
return $this->getFunctions(true, 'trigger');
}
/**
* Creates a trigger
* @param $tgname The name of the trigger to create
* @param $table The name of the table
* @param $tgproc The function to execute
* @param $tgtime BEFORE or AFTER
* @param $tgevent Event
* @param $tgargs The function arguments
* @return 0 success
*/
function createTrigger($tgname, $table, $tgproc, $tgtime, $tgevent, $tgfrequency, $tgargs) {
$f_schema = $this->_schema;
$this->fieldClean($f_schema);
$this->fieldClean($tgname);
$this->fieldClean($table);
$this->fieldClean($tgproc);
/* No Statement Level Triggers in PostgreSQL (by now) */
$sql = "CREATE TRIGGER \"{$tgname}\" {$tgtime}
{$tgevent} ON \"{$f_schema}\".\"{$table}\"
FOR EACH {$tgfrequency} EXECUTE PROCEDURE \"{$tgproc}\"({$tgargs})";
return $this->execute($sql);
}
/**
* Alters a trigger
* @param $table The name of the table containing the trigger
* @param $trigger The name of the trigger to alter
* @param $name The new name for the trigger
* @return 0 success
*/
function alterTrigger($table, $trigger, $name) {
$f_schema = $this->_schema;
$this->fieldClean($f_schema);
$this->fieldClean($table);
$this->fieldClean($trigger);
$this->fieldClean($name);
$sql = "ALTER TRIGGER \"{$trigger}\" ON \"{$f_schema}\".\"{$table}\" RENAME TO \"{$name}\"";
return $this->execute($sql);
}
/**
* Drops a trigger
* @param $tgname The name of the trigger to drop
* @param $table The table from which to drop the trigger
* @param $cascade True to cascade drop, false to restrict
* @return 0 success
*/
function dropTrigger($tgname, $table, $cascade) {
$f_schema = $this->_schema;
$this->fieldClean($f_schema);
$this->fieldClean($tgname);
$this->fieldClean($table);
$sql = "DROP TRIGGER \"{$tgname}\" ON \"{$f_schema}\".\"{$table}\"";
if ($cascade) $sql .= " CASCADE";
return $this->execute($sql);
}
/**
* Enables a trigger
* @param $tgname The name of the trigger to enable
* @param $table The table in which to enable the trigger
* @return 0 success
*/
function enableTrigger($tgname, $table) {
$f_schema = $this->_schema;
$this->fieldClean($f_schema);
$this->fieldClean($tgname);
$this->fieldClean($table);
$sql = "ALTER TABLE \"{$f_schema}\".\"{$table}\" ENABLE TRIGGER \"{$tgname}\"";
return $this->execute($sql);
}
/**
* Disables a trigger
* @param $tgname The name of the trigger to disable
* @param $table The table in which to disable the trigger
* @return 0 success
*/
function disableTrigger($tgname, $table) {
$f_schema = $this->_schema;
$this->fieldClean($f_schema);
$this->fieldClean($tgname);
$this->fieldClean($table);
$sql = "ALTER TABLE \"{$f_schema}\".\"{$table}\" DISABLE TRIGGER \"{$tgname}\"";
return $this->execute($sql);
}
// Operator functions
/**
* Returns a list of all operators in the database
* @return All operators
*/
function getOperators() {
$c_schema = $this->_schema;
$this->clean($c_schema);
// We stick with the subselects here, as you cannot ORDER BY a regtype
$sql = "
SELECT
po.oid, po.oprname,
(SELECT pg_catalog.format_type(oid, NULL) FROM pg_catalog.pg_type pt WHERE pt.oid=po.oprleft) AS oprleftname,
(SELECT pg_catalog.format_type(oid, NULL) FROM pg_catalog.pg_type pt WHERE pt.oid=po.oprright) AS oprrightname,
po.oprresult::pg_catalog.regtype AS resultname,
pg_catalog.obj_description(po.oid, 'pg_operator') AS oprcomment
FROM
pg_catalog.pg_operator po
WHERE
po.oprnamespace = (SELECT oid FROM pg_catalog.pg_namespace WHERE nspname='{$c_schema}')
ORDER BY
po.oprname, oprleftname, oprrightname
";
return $this->selectSet($sql);
}
/**
* Returns all details for a particular operator
* @param $operator_oid The oid of the operator
* @return Function info
*/
function getOperator($operator_oid) {
$this->clean($operator_oid);
$sql = "
SELECT
po.oid, po.oprname,
oprleft::pg_catalog.regtype AS oprleftname,
oprright::pg_catalog.regtype AS oprrightname,
oprresult::pg_catalog.regtype AS resultname,
po.oprcanhash,
oprcanmerge,
oprcom::pg_catalog.regoperator AS oprcom,
oprnegate::pg_catalog.regoperator AS oprnegate,
po.oprcode::pg_catalog.regproc AS oprcode,
po.oprrest::pg_catalog.regproc AS oprrest,
po.oprjoin::pg_catalog.regproc AS oprjoin
FROM
pg_catalog.pg_operator po
WHERE
po.oid='{$operator_oid}'
";
return $this->selectSet($sql);
}
/**
* Drops an operator
* @param $operator_oid The OID of the operator to drop
* @param $cascade True to cascade drop, false to restrict
* @return 0 success
*/
function dropOperator($operator_oid, $cascade) {
// Function comes in with $object as operator OID
$opr = $this->getOperator($operator_oid);
$f_schema = $this->_schema;
$this->fieldClean($f_schema);
$this->fieldClean($opr->fields['oprname']);
$sql = "DROP OPERATOR \"{$f_schema}\".{$opr->fields['oprname']} (";
// Quoting or formatting here???
if ($opr->fields['oprleftname'] !== null) $sql .= $opr->fields['oprleftname'] . ', ';
else $sql .= "NONE, ";
if ($opr->fields['oprrightname'] !== null) $sql .= $opr->fields['oprrightname'] . ')';
else $sql .= "NONE)";
if ($cascade) $sql .= " CASCADE";
return $this->execute($sql);
}
// Operator Class functions
/**
* Gets all opclasses
*
* @return A recordset
*/
function getOpClasses() {
$c_schema = $this->_schema;
$this->clean($c_schema);
$sql = "
SELECT
pa.amname, po.opcname,
po.opcintype::pg_catalog.regtype AS opcintype,
po.opcdefault,
pg_catalog.obj_description(po.oid, 'pg_opclass') AS opccomment
FROM
pg_catalog.pg_opclass po, pg_catalog.pg_am pa, pg_catalog.pg_namespace pn
WHERE
po.opcmethod=pa.oid
AND po.opcnamespace=pn.oid
AND pn.nspname='{$c_schema}'
ORDER BY 1,2
";
return $this->selectSet($sql);
}
// FTS functions
/**
* Creates a new FTS configuration.
* @param string $cfgname The name of the FTS configuration to create
* @param string $parser The parser to be used in new FTS configuration
* @param string $locale Locale of the FTS configuration
* @param string $template The existing FTS configuration to be used as template for the new one
* @param string $withmap Should we copy whole map of existing FTS configuration to the new one
* @param string $makeDefault Should this configuration be the default for locale given
* @param string $comment If omitted, defaults to nothing
*
* @return 0 success
*/
function createFtsConfiguration($cfgname, $parser = '', $template = '', $comment = '') {
$f_schema = $this->_schema;
$this->fieldClean($f_schema);
$this->fieldClean($cfgname);
$sql = "CREATE TEXT SEARCH CONFIGURATION \"{$f_schema}\".\"{$cfgname}\" (";
if ($parser != '') {
$this->fieldClean($parser['schema']);
$this->fieldClean($parser['parser']);
$parser = "\"{$parser['schema']}\".\"{$parser['parser']}\"";
$sql .= " PARSER = {$parser}";
}
if ($template != '') {
$this->fieldClean($template['schema']);
$this->fieldClean($template['name']);
$sql .= " COPY = \"{$template['schema']}\".\"{$template['name']}\"";
}
$sql .= ")";
if ($comment != '') {
$status = $this->beginTransaction();
if ($status != 0) return -1;
}
// Create the FTS configuration
$status = $this->execute($sql);
if ($status != 0) {
$this->rollbackTransaction();
return -1;
}
// Set the comment
if ($comment != '') {
$status = $this->setComment('TEXT SEARCH CONFIGURATION', $cfgname, '', $comment);
if ($status != 0) {
$this->rollbackTransaction();
return -1;
}
return $this->endTransaction();
}
return 0;
}
/**
* Returns available FTS configurations
* @param $all if false, returns schema qualified FTS confs
*
* @return A recordset
*/
function getFtsConfigurations($all = true) {
$c_schema = $this->_schema;
$this->clean($c_schema);
$sql = "
SELECT
n.nspname as schema,
c.cfgname as name,
pg_catalog.obj_description(c.oid, 'pg_ts_config') as comment
FROM
pg_catalog.pg_ts_config c
JOIN pg_catalog.pg_namespace n ON n.oid = c.cfgnamespace
WHERE
pg_catalog.pg_ts_config_is_visible(c.oid)";
if (!$all)
$sql.= " AND n.nspname='{$c_schema}'\n";
$sql.= "ORDER BY name";
return $this->selectSet($sql);
}
/**
* Return all information related to a FTS configuration
* @param $ftscfg The name of the FTS configuration
*
* @return FTS configuration information
*/
function getFtsConfigurationByName($ftscfg) {
$c_schema = $this->_schema;
$this->clean($c_schema);
$this->clean($ftscfg);
$sql = "
SELECT
n.nspname as schema,
c.cfgname as name,
p.prsname as parser,
c.cfgparser as parser_id,
pg_catalog.obj_description(c.oid, 'pg_ts_config') as comment
FROM pg_catalog.pg_ts_config c
LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.cfgnamespace
LEFT JOIN pg_catalog.pg_ts_parser p ON p.oid = c.cfgparser
WHERE pg_catalog.pg_ts_config_is_visible(c.oid)
AND c.cfgname = '{$ftscfg}'
AND n.nspname='{$c_schema}'";
return $this->selectSet($sql);
}
/**
* Returns the map of FTS configuration given
* (list of mappings (tokens) and their processing dictionaries)
* @param string $ftscfg Name of the FTS configuration
*
* @return RecordSet
*/
function getFtsConfigurationMap($ftscfg) {
$c_schema = $this->_schema;
$this->clean($c_schema);
$this->fieldClean($ftscfg);
$oidSet = $this->selectSet("SELECT c.oid
FROM pg_catalog.pg_ts_config AS c
LEFT JOIN pg_catalog.pg_namespace n ON (n.oid = c.cfgnamespace)
WHERE c.cfgname = '{$ftscfg}'
AND n.nspname='{$c_schema}'");
$oid = $oidSet->fields['oid'];
$sql = "
SELECT
(SELECT t.alias FROM pg_catalog.ts_token_type(c.cfgparser) AS t WHERE t.tokid = m.maptokentype) AS name,
(SELECT t.description FROM pg_catalog.ts_token_type(c.cfgparser) AS t WHERE t.tokid = m.maptokentype) AS description,
c.cfgname AS cfgname, n.nspname ||'.'|| d.dictname as dictionaries
FROM
pg_catalog.pg_ts_config AS c, pg_catalog.pg_ts_config_map AS m, pg_catalog.pg_ts_dict d,
pg_catalog.pg_namespace n
WHERE
c.oid = {$oid}
AND m.mapcfg = c.oid
AND m.mapdict = d.oid
AND d.dictnamespace = n.oid
ORDER BY name
";
return $this->selectSet($sql);
}
/**
* Returns FTS parsers available
* @param $all if false, return only Parsers from the current schema
*
* @return RecordSet
*/
function getFtsParsers($all = true) {
$c_schema = $this->_schema;
$this->clean($c_schema);
$sql = "
SELECT
n.nspname as schema,
p.prsname as name,
pg_catalog.obj_description(p.oid, 'pg_ts_parser') as comment
FROM pg_catalog.pg_ts_parser p
LEFT JOIN pg_catalog.pg_namespace n ON (n.oid = p.prsnamespace)
WHERE pg_catalog.pg_ts_parser_is_visible(p.oid)";
if (!$all)
$sql.= " AND n.nspname='{$c_schema}'\n";
$sql.= "ORDER BY name";
return $this->selectSet($sql);
}
/**
* Returns FTS dictionaries available
* @param $all if false, return only Dics from the current schema
*
* @returns RecordSet
*/
function getFtsDictionaries($all = true) {
$c_schema = $this->_schema;
$this->clean($c_schema);
$sql = "
SELECT
n.nspname as schema, d.dictname as name,
pg_catalog.obj_description(d.oid, 'pg_ts_dict') as comment
FROM pg_catalog.pg_ts_dict d
LEFT JOIN pg_catalog.pg_namespace n ON n.oid = d.dictnamespace
WHERE pg_catalog.pg_ts_dict_is_visible(d.oid)";
if (!$all)
$sql.= " AND n.nspname='{$c_schema}'\n";
$sql.= "ORDER BY name;";
return $this->selectSet($sql);
}
/**
* Returns all FTS dictionary templates available
*/
function getFtsDictionaryTemplates() {
$sql = "
SELECT
n.nspname as schema,
t.tmplname as name,
( SELECT COALESCE(np.nspname, '(null)')::pg_catalog.text || '.' || p.proname
FROM pg_catalog.pg_proc p
LEFT JOIN pg_catalog.pg_namespace np ON np.oid = p.pronamespace
WHERE t.tmplinit = p.oid ) AS init,
( SELECT COALESCE(np.nspname, '(null)')::pg_catalog.text || '.' || p.proname
FROM pg_catalog.pg_proc p
LEFT JOIN pg_catalog.pg_namespace np ON np.oid = p.pronamespace
WHERE t.tmpllexize = p.oid ) AS lexize,
pg_catalog.obj_description(t.oid, 'pg_ts_template') as comment
FROM pg_catalog.pg_ts_template t
LEFT JOIN pg_catalog.pg_namespace n ON n.oid = t.tmplnamespace
WHERE pg_catalog.pg_ts_template_is_visible(t.oid)
ORDER BY name;";
return $this->selectSet($sql);
}
/**
* Drops FTS coniguration
* @param $ftscfg The configuration's name
* @param $cascade Cascade to dependenced objects
*
* @return 0 on success
*/
function dropFtsConfiguration($ftscfg, $cascade) {
$f_schema = $this->_schema;
$this->fieldClean($f_schema);
$this->fieldClean($ftscfg);
$sql = "DROP TEXT SEARCH CONFIGURATION \"{$f_schema}\".\"{$ftscfg}\"";
if ($cascade) $sql .= ' CASCADE';
return $this->execute($sql);
}
/**
* Drops FTS dictionary
* @param $ftsdict The dico's name
* @param $cascade Cascade to dependenced objects
*
* @todo Support of dictionary templates dropping
* @return 0 on success
*/
function dropFtsDictionary($ftsdict, $cascade) {
$f_schema = $this->_schema;
$this->fieldClean($f_schema);
$this->fieldClean($ftsdict);
$sql = "DROP TEXT SEARCH DICTIONARY";
$sql .= " \"{$f_schema}\".\"{$ftsdict}\"";
if ($cascade) $sql .= ' CASCADE';
return $this->execute($sql);
}
/**
* Alters FTS configuration
* @param $cfgname The conf's name
* @param $comment A comment on for the conf
* @param $name The new conf name
*
* @return 0 on success
*/
function updateFtsConfiguration($cfgname, $comment, $name) {
$status = $this->beginTransaction();
if ($status != 0) {
$this->rollbackTransaction();
return -1;
}
$this->fieldClean($cfgname);
$status = $this->setComment('TEXT SEARCH CONFIGURATION', $cfgname, '', $comment);
if ($status != 0) {
$this->rollbackTransaction();
return -1;
}
// Only if the name has changed
if ($name != $cfgname) {
$f_schema = $this->_schema;
$this->fieldClean($f_schema);
$this->fieldClean($name);
$sql = "ALTER TEXT SEARCH CONFIGURATION \"{$f_schema}\".\"{$cfgname}\" RENAME TO \"{$name}\"";
$status = $this->execute($sql);
if ($status != 0) {
$this->rollbackTransaction();
return -1;
}
}
return $this->endTransaction();
}
/**
* Creates a new FTS dictionary or FTS dictionary template.
* @param string $dictname The name of the FTS dictionary to create
* @param boolean $isTemplate Flag whether we create usual dictionary or dictionary template
* @param string $template The existing FTS dictionary to be used as template for the new one
* @param string $lexize The name of the function, which does transformation of input word
* @param string $init The name of the function, which initializes dictionary
* @param string $option Usually, it stores various options required for the dictionary
* @param string $comment If omitted, defaults to nothing
*
* @return 0 success
*/
function createFtsDictionary($dictname, $isTemplate = false, $template = '', $lexize = '',
$init = '', $option = '', $comment = '') {
$f_schema = $this->_schema;
$this->fieldClean($f_schema);
$this->fieldClean($dictname);
$this->fieldClean($template);
$this->fieldClean($lexize);
$this->fieldClean($init);
$this->fieldClean($option);
$sql = "CREATE TEXT SEARCH";
if ($isTemplate) {
$sql .= " TEMPLATE \"{$f_schema}\".\"{$dictname}\" (";
if ($lexize != '') $sql .= " LEXIZE = {$lexize}";
if ($init != '') $sql .= ", INIT = {$init}";
$sql .= ")";
$whatToComment = 'TEXT SEARCH TEMPLATE';
} else {
$sql .= " DICTIONARY \"{$f_schema}\".\"{$dictname}\" (";
if ($template != '') {
$this->fieldClean($template['schema']);
$this->fieldClean($template['name']);
$template = "\"{$template['schema']}\".\"{$template['name']}\"";
$sql .= " TEMPLATE = {$template}";
}
if ($option != '') $sql .= ", {$option}";
$sql .= ")";
$whatToComment = 'TEXT SEARCH DICTIONARY';
}
/* if comment, begin a transaction to
* run both commands */
if ($comment != '') {
$status = $this->beginTransaction();
if ($status != 0) return -1;
}
// Create the FTS dictionary
$status = $this->execute($sql);
if ($status != 0) {
$this->rollbackTransaction();
return -1;
}
// Set the comment
if ($comment != '') {
$status = $this->setComment($whatToComment, $dictname, '', $comment);
if ($status != 0) {
$this->rollbackTransaction();
return -1;
}
}
return $this->endTransaction();
}
/**
* Alters FTS dictionary or dictionary template
* @param $dictname The dico's name
* @param $comment The comment
* @param $name The new dico's name
*
* @return 0 on success
*/
function updateFtsDictionary($dictname, $comment, $name) {
$status = $this->beginTransaction();
if ($status != 0) {
$this->rollbackTransaction();
return -1;
}
$this->fieldClean($dictname);
$status = $this->setComment('TEXT SEARCH DICTIONARY', $dictname, '', $comment);
if ($status != 0) {
$this->rollbackTransaction();
return -1;
}
// Only if the name has changed
if ($name != $dictname) {
$f_schema = $this->_schema;
$this->fieldClean($f_schema);
$this->fieldClean($name);
$sql = "ALTER TEXT SEARCH DICTIONARY \"{$f_schema}\".\"{$dictname}\" RENAME TO \"{$name}\"";
$status = $this->execute($sql);
if ($status != 0) {
$this->rollbackTransaction();
return -1;
}
}
return $this->endTransaction();
}
/**
* Return all information relating to a FTS dictionary
* @param $ftsdict The name of the FTS dictionary
*
* @return RecordSet of FTS dictionary information
*/
function getFtsDictionaryByName($ftsdict) {
$c_schema = $this->_schema;
$this->clean($c_schema);
$this->clean($ftsdict);
$sql = "SELECT
n.nspname as schema,
d.dictname as name,
( SELECT COALESCE(nt.nspname, '(null)')::pg_catalog.text || '.' || t.tmplname FROM
pg_catalog.pg_ts_template t
LEFT JOIN pg_catalog.pg_namespace nt ON nt.oid = t.tmplnamespace
WHERE d.dicttemplate = t.oid ) AS template,
d.dictinitoption as init,
pg_catalog.obj_description(d.oid, 'pg_ts_dict') as comment
FROM pg_catalog.pg_ts_dict d
LEFT JOIN pg_catalog.pg_namespace n ON n.oid = d.dictnamespace
WHERE d.dictname = '{$ftsdict}'
AND pg_catalog.pg_ts_dict_is_visible(d.oid)
AND n.nspname='{$c_schema}'
ORDER BY name";
return $this->selectSet($sql);
}
/**
* Creates/updates/deletes FTS mapping.
* @param string $cfgname The name of the FTS configuration to alter
* @param array $mapping Array of tokens' names
* @param string $action What to do with the mapping: add, alter or drop
* @param string $dictname Dictionary that will process tokens given or null in case of drop action
*
* @return 0 success
*/
function changeFtsMapping($ftscfg, $mapping, $action, $dictname = null) {
if (count($mapping) > 0) {
$f_schema = $this->_schema;
$this->fieldClean($f_schema);
$this->fieldClean($ftscfg);
$this->fieldClean($dictname);
$this->arrayClean($mapping);
switch ($action) {
case 'alter':
$whatToDo = "ALTER";
break;
case 'drop':
$whatToDo = "DROP";
break;
default:
$whatToDo = "ADD";
break;
}
$sql = "ALTER TEXT SEARCH CONFIGURATION \"{$f_schema}\".\"{$ftscfg}\" {$whatToDo} MAPPING FOR ";
$sql .= implode(",", $mapping);
if ($action != 'drop' && !empty($dictname)) {
$sql .= " WITH {$dictname}";
}
return $this->execute($sql);
}
else {
return -1;
}
}
/**
* Return all information related to a given FTS configuration's mapping
* @param $ftscfg The name of the FTS configuration
* @param $mapping The name of the mapping
*
* @return FTS configuration information
*/
function getFtsMappingByName($ftscfg, $mapping) {
$c_schema = $this->_schema;
$this->clean($c_schema);
$this->clean($ftscfg);
$this->clean($mapping);
$oidSet = $this->selectSet("SELECT c.oid, cfgparser
FROM pg_catalog.pg_ts_config AS c
LEFT JOIN pg_catalog.pg_namespace AS n ON n.oid = c.cfgnamespace
WHERE c.cfgname = '{$ftscfg}'
AND n.nspname='{$c_schema}'");
$oid = $oidSet->fields['oid'];
$cfgparser = $oidSet->fields['cfgparser'];
$tokenIdSet = $this->selectSet("SELECT tokid
FROM pg_catalog.ts_token_type({$cfgparser})
WHERE alias = '{$mapping}'");
$tokid = $tokenIdSet->fields['tokid'];
$sql = "SELECT
(SELECT t.alias FROM pg_catalog.ts_token_type(c.cfgparser) AS t WHERE t.tokid = m.maptokentype) AS name,
d.dictname as dictionaries
FROM pg_catalog.pg_ts_config AS c, pg_catalog.pg_ts_config_map AS m, pg_catalog.pg_ts_dict d
WHERE c.oid = {$oid} AND m.mapcfg = c.oid AND m.maptokentype = {$tokid} AND m.mapdict = d.oid
LIMIT 1;";
return $this->selectSet($sql);
}
/**
* Return list of FTS mappings possible for given parser
* (specified by given configuration since configuration can only have 1 parser)
* @param $ftscfg The config's name that use the parser
*
* @return 0 on success
*/
function getFtsMappings($ftscfg) {
$cfg = $this->getFtsConfigurationByName($ftscfg);
$sql = "SELECT alias AS name, description
FROM pg_catalog.ts_token_type({$cfg->fields['parser_id']})
ORDER BY name";
return $this->selectSet($sql);
}
// Language functions
/**
* Gets all languages
* @param $all True to get all languages, regardless of show_system
* @return A recordset
*/
function getLanguages($all = false) {
global $conf;
if ($conf['show_system'] || $all)
$where = '';
else
$where = 'WHERE lanispl';
$sql = "
SELECT
lanname, lanpltrusted,
lanplcallfoid::pg_catalog.regproc AS lanplcallf
FROM
pg_catalog.pg_language
{$where}
ORDER BY lanname
";
return $this->selectSet($sql);
}
// Aggregate functions
/**
* Creates a new aggregate in the database
* @param $name The name of the aggregate
* @param $basetype The input data type of the aggregate
* @param $sfunc The name of the state transition function for the aggregate
* @param $stype The data type for the aggregate's state value
* @param $ffunc The name of the final function for the aggregate
* @param $initcond The initial setting for the state value
* @param $sortop The sort operator for the aggregate
* @param $comment Aggregate comment
* @return 0 success
* @return -1 error
*/
function createAggregate($name, $basetype, $sfunc, $stype, $ffunc, $initcond, $sortop, $comment) {
$f_schema = $this->_schema;
$this->fieldClean($f_schema);
$this->fieldClean($name);
$this->fieldClean($basetype);
$this->fieldClean($sfunc);
$this->fieldClean($stype);
$this->fieldClean($ffunc);
$this->fieldClean($initcond);
$this->fieldClean($sortop);
$this->beginTransaction();
$sql = "CREATE AGGREGATE \"{$f_schema}\".\"{$name}\" (BASETYPE = \"{$basetype}\", SFUNC = \"{$sfunc}\", STYPE = \"{$stype}\"";
if(trim($ffunc) != '') $sql .= ", FINALFUNC = \"{$ffunc}\"";
if(trim($initcond) != '') $sql .= ", INITCOND = \"{$initcond}\"";
if(trim($sortop) != '') $sql .= ", SORTOP = \"{$sortop}\"";
$sql .= ")";
$status = $this->execute($sql);
if ($status) {
$this->rollbackTransaction();
return -1;
}
if (trim($comment) != '') {
$status = $this->setComment('AGGREGATE', $name, '', $comment, $basetype);
if ($status) {
$this->rollbackTransaction();
return -1;
}
}
return $this->endTransaction();
}
/**
* Renames an aggregate function
* @param $aggrname The actual name of the aggregate
* @param $aggrtype The actual input data type of the aggregate
* @param $newaggrname The new name of the aggregate
* @return 0 success
*/
function renameAggregate($aggrschema, $aggrname, $aggrtype, $newaggrname) {
/* this function is called from alterAggregate where params are cleaned */
$sql = "ALTER AGGREGATE \"{$aggrschema}\"" . '.' . "\"{$aggrname}\" (\"{$aggrtype}\") RENAME TO \"{$newaggrname}\"";
return $this->execute($sql);
}
/**
* Removes an aggregate function from the database
* @param $aggrname The name of the aggregate
* @param $aggrtype The input data type of the aggregate
* @param $cascade True to cascade drop, false to restrict
* @return 0 success
*/
function dropAggregate($aggrname, $aggrtype, $cascade) {
$f_schema = $this->_schema;
$this->fieldClean($f_schema);
$this->fieldClean($aggrname);
$this->fieldClean($aggrtype);
$sql = "DROP AGGREGATE \"{$f_schema}\".\"{$aggrname}\" (\"{$aggrtype}\")";
if ($cascade) $sql .= " CASCADE";
return $this->execute($sql);
}
/**
* Gets all information for an aggregate
* @param $name The name of the aggregate
* @param $basetype The input data type of the aggregate
* @return A recordset
*/
function getAggregate($name, $basetype) {
$c_schema = $this->_schema;
$this->clean($c_schema);
$this->fieldclean($name);
$this->fieldclean($basetype);
$sql = "
SELECT p.proname, CASE p.proargtypes[0]
WHEN 'pg_catalog.\"any\"'::pg_catalog.regtype THEN NULL
ELSE pg_catalog.format_type(p.proargtypes[0], NULL) END AS proargtypes,
a.aggtransfn, format_type(a.aggtranstype, NULL) AS aggstype, a.aggfinalfn,
a.agginitval, a.aggsortop, u.usename, pg_catalog.obj_description(p.oid, 'pg_proc') AS aggrcomment
FROM pg_catalog.pg_proc p, pg_catalog.pg_namespace n, pg_catalog.pg_user u, pg_catalog.pg_aggregate a
WHERE n.oid = p.pronamespace AND p.proowner=u.usesysid AND p.oid=a.aggfnoid
AND p.proisagg AND n.nspname='{$c_schema}'
AND p.proname='" . $name . "'
AND CASE p.proargtypes[0]
WHEN 'pg_catalog.\"any\"'::pg_catalog.regtype THEN ''
ELSE pg_catalog.format_type(p.proargtypes[0], NULL)
END ='" . $basetype . "'";
return $this->selectSet($sql);
}
/**
* Gets all aggregates
* @return A recordset
*/
function getAggregates() {
$c_schema = $this->_schema;
$this->clean($c_schema);
$sql = "SELECT p.proname, CASE p.proargtypes[0] WHEN 'pg_catalog.\"any\"'::pg_catalog.regtype THEN NULL ELSE
pg_catalog.format_type(p.proargtypes[0], NULL) END AS proargtypes, a.aggtransfn, u.usename,
pg_catalog.obj_description(p.oid, 'pg_proc') AS aggrcomment
FROM pg_catalog.pg_proc p, pg_catalog.pg_namespace n, pg_catalog.pg_user u, pg_catalog.pg_aggregate a
WHERE n.oid = p.pronamespace AND p.proowner=u.usesysid AND p.oid=a.aggfnoid
AND p.proisagg AND n.nspname='{$c_schema}' ORDER BY 1, 2";
return $this->selectSet($sql);
}
/**
* Changes the owner of an aggregate function
* @param $aggrname The name of the aggregate
* @param $aggrtype The input data type of the aggregate
* @param $newaggrowner The new owner of the aggregate
* @return 0 success
*/
function changeAggregateOwner($aggrname, $aggrtype, $newaggrowner) {
$f_schema = $this->_schema;
$this->fieldClean($f_schema);
$this->fieldClean($aggrname);
$this->fieldClean($newaggrowner);
$sql = "ALTER AGGREGATE \"{$f_schema}\".\"{$aggrname}\" (\"{$aggrtype}\") OWNER TO \"{$newaggrowner}\"";
return $this->execute($sql);
}
/**
* Changes the schema of an aggregate function
* @param $aggrname The name of the aggregate
* @param $aggrtype The input data type of the aggregate
* @param $newaggrschema The new schema for the aggregate
* @return 0 success
*/
function changeAggregateSchema($aggrname, $aggrtype, $newaggrschema) {
$f_schema = $this->_schema;
$this->fieldClean($f_schema);
$this->fieldClean($aggrname);
$this->fieldClean($newaggrschema);
$sql = "ALTER AGGREGATE \"{$f_schema}\".\"{$aggrname}\" (\"{$aggrtype}\") SET SCHEMA \"{$newaggrschema}\"";
return $this->execute($sql);
}
/**
* Alters an aggregate
* @param $aggrname The actual name of the aggregate
* @param $aggrtype The actual input data type of the aggregate
* @param $aggrowner The actual owner of the aggregate
* @param $aggrschema The actual schema the aggregate belongs to
* @param $aggrcomment The actual comment for the aggregate
* @param $newaggrname The new name of the aggregate
* @param $newaggrowner The new owner of the aggregate
* @param $newaggrschema The new schema where the aggregate will belong to
* @param $newaggrcomment The new comment for the aggregate
* @return 0 success
* @return -1 change owner error
* @return -2 change comment error
* @return -3 change schema error
* @return -4 change name error
*/
function alterAggregate($aggrname, $aggrtype, $aggrowner, $aggrschema, $aggrcomment, $newaggrname, $newaggrowner, $newaggrschema, $newaggrcomment) {
// Clean fields
$this->fieldClean($aggrname);
$this->fieldClean($aggrtype);
$this->fieldClean($aggrowner);
$this->fieldClean($aggrschema);
$this->fieldClean($newaggrname);
$this->fieldClean($newaggrowner);
$this->fieldClean($newaggrschema);
$this->beginTransaction();
// Change the owner, if it has changed
if($aggrowner != $newaggrowner) {
$status = $this->changeAggregateOwner($aggrname, $aggrtype, $newaggrowner);
if($status != 0) {
$this->rollbackTransaction();
return -1;
}
}
// Set the comment, if it has changed
if($aggrcomment != $newaggrcomment) {
$status = $this->setComment('AGGREGATE', $aggrname, '', $newaggrcomment, $aggrtype);
if ($status) {
$this->rollbackTransaction();
return -2;
}
}
// Change the schema, if it has changed
if($aggrschema != $newaggrschema) {
$status = $this->changeAggregateSchema($aggrname, $aggrtype, $newaggrschema);
if($status != 0) {
$this->rollbackTransaction();
return -3;
}
}
// Rename the aggregate, if it has changed
if($aggrname != $newaggrname) {
$status = $this->renameAggregate($newaggrschema, $aggrname, $aggrtype, $newaggrname);
if($status != 0) {
$this->rollbackTransaction();
return -4;
}
}
return $this->endTransaction();
}
// Role, User/Group functions
/**
* Returns all roles in the database cluster
* @param $rolename (optional) The role name to exclude from the select
* @return All roles
*/
function getRoles($rolename = '') {
$sql = '
SELECT rolname, rolsuper, rolcreatedb, rolcreaterole, rolinherit,
rolcanlogin, rolconnlimit, rolvaliduntil, rolconfig
FROM pg_catalog.pg_roles';
if($rolename) $sql .= " WHERE rolname!='{$rolename}'";
$sql .= ' ORDER BY rolname';
return $this->selectSet($sql);
}
/**
* Returns information about a single role
* @param $rolename The name of the role to retrieve
* @return The role's data
*/
function getRole($rolename) {
$this->clean($rolename);
$sql = "
SELECT rolname, rolsuper, rolcreatedb, rolcreaterole, rolinherit,
rolcanlogin, rolconnlimit, rolvaliduntil, rolconfig
FROM pg_catalog.pg_roles WHERE rolname='{$rolename}'";
return $this->selectSet($sql);
}
/**
* Grants membership in a role
* @param $role The name of the target role
* @param $rolename The name of the role that will belong to the target role
* @param $admin (optional) Flag to grant the admin option
* @return 0 success
*/
function grantRole($role, $rolename, $admin=0) {
$this->fieldClean($role);
$this->fieldClean($rolename);
$sql = "GRANT \"{$role}\" TO \"{$rolename}\"";
if($admin == 1) $sql .= ' WITH ADMIN OPTION';
return $this->execute($sql);
}
/**
* Revokes membership in a role
* @param $role The name of the target role
* @param $rolename The name of the role that will not belong to the target role
* @param $admin (optional) Flag to revoke only the admin option
* @param $type (optional) Type of revoke: RESTRICT | CASCADE
* @return 0 success
*/
function revokeRole($role, $rolename, $admin = 0, $type = 'RESTRICT') {
$this->fieldClean($role);
$this->fieldClean($rolename);
$sql = "REVOKE ";
if($admin == 1) $sql .= 'ADMIN OPTION FOR ';
$sql .= "\"{$role}\" FROM \"{$rolename}\" {$type}";
return $this->execute($sql);
}
/**
* Returns all users in the database cluster
* @return All users
*/
function getUsers() {
$sql = "SELECT usename, usesuper, usecreatedb, valuntil AS useexpires, useconfig
FROM pg_user
ORDER BY usename";
return $this->selectSet($sql);
}
/**
* Returns information about a single user
* @param $username The username of the user to retrieve
* @return The user's data
*/
function getUser($username) {
$this->clean($username);
$sql = "SELECT usename, usesuper, usecreatedb, valuntil AS useexpires, useconfig
FROM pg_user
WHERE usename='{$username}'";
return $this->selectSet($sql);
}
/**
* Creates a new role
* @param $rolename The name of the role to create
* @param $password A password for the role
* @param $superuser Boolean whether or not the role is a superuser
* @param $createdb Boolean whether or not the role can create databases
* @param $createrole Boolean whether or not the role can create other roles
* @param $inherits Boolean whether or not the role inherits the privileges from parent roles
* @param $login Boolean whether or not the role will be allowed to login
* @param $connlimit Number of concurrent connections the role can make
* @param $expiry String Format 'YYYY-MM-DD HH:MM:SS'. '' means never expire
* @param $memberof (array) Roles to which the new role will be immediately added as a new member
* @param $members (array) Roles which are automatically added as members of the new role
* @param $adminmembers (array) Roles which are automatically added as admin members of the new role
* @return 0 success
*/
function createRole($rolename, $password, $superuser, $createdb, $createrole, $inherits, $login, $connlimit, $expiry, $memberof, $members, $adminmembers) {
$enc = $this->_encryptPassword($rolename, $password);
$this->fieldClean($rolename);
$this->clean($enc);
$this->clean($connlimit);
$this->clean($expiry);
$this->fieldArrayClean($memberof);
$this->fieldArrayClean($members);
$this->fieldArrayClean($adminmembers);
$sql = "CREATE ROLE \"{$rolename}\"";
if ($password != '') $sql .= " WITH ENCRYPTED PASSWORD '{$enc}'";
$sql .= ($superuser) ? ' SUPERUSER' : ' NOSUPERUSER';
$sql .= ($createdb) ? ' CREATEDB' : ' NOCREATEDB';
$sql .= ($createrole) ? ' CREATEROLE' : ' NOCREATEROLE';
$sql .= ($inherits) ? ' INHERIT' : ' NOINHERIT';
$sql .= ($login) ? ' LOGIN' : ' NOLOGIN';
if ($connlimit != '') $sql .= " CONNECTION LIMIT {$connlimit}"; else $sql .= ' CONNECTION LIMIT -1';
if ($expiry != '') $sql .= " VALID UNTIL '{$expiry}'"; else $sql .= " VALID UNTIL 'infinity'";
if (is_array($memberof) && sizeof($memberof) > 0) $sql .= ' IN ROLE "' . join('", "', $memberof) . '"';
if (is_array($members) && sizeof($members) > 0) $sql .= ' ROLE "' . join('", "', $members) . '"';
if (is_array($adminmembers) && sizeof($adminmembers) > 0) $sql .= ' ADMIN "' . join('", "', $adminmembers) . '"';
return $this->execute($sql);
}
/**
* Adjusts a role's info
* @param $rolename The name of the role to adjust
* @param $password A password for the role
* @param $superuser Boolean whether or not the role is a superuser
* @param $createdb Boolean whether or not the role can create databases
* @param $createrole Boolean whether or not the role can create other roles
* @param $inherits Boolean whether or not the role inherits the privileges from parent roles
* @param $login Boolean whether or not the role will be allowed to login
* @param $connlimit Number of concurrent connections the role can make
* @param $expiry string Format 'YYYY-MM-DD HH:MM:SS'. '' means never expire
* @param $memberof (array) Roles to which the role will be immediately added as a new member
* @param $members (array) Roles which are automatically added as members of the role
* @param $adminmembers (array) Roles which are automatically added as admin members of the role
* @param $memberofold (array) Original roles whose the role belongs to
* @param $membersold (array) Original roles that are members of the role
* @param $adminmembersold (array) Original roles that are admin members of the role
* @return 0 success
*/
function setRole($rolename, $password, $superuser, $createdb, $createrole, $inherits, $login, $connlimit, $expiry, $memberof, $members, $adminmembers, $memberofold, $membersold, $adminmembersold) {
$enc = $this->_encryptPassword($rolename, $password);
$this->fieldClean($rolename);
$this->clean($enc);
$this->clean($connlimit);
$this->clean($expiry);
$this->fieldArrayClean($memberof);
$this->fieldArrayClean($members);
$this->fieldArrayClean($adminmembers);
$sql = "ALTER ROLE \"{$rolename}\"";
if ($password != '') $sql .= " WITH ENCRYPTED PASSWORD '{$enc}'";
$sql .= ($superuser) ? ' SUPERUSER' : ' NOSUPERUSER';
$sql .= ($createdb) ? ' CREATEDB' : ' NOCREATEDB';
$sql .= ($createrole) ? ' CREATEROLE' : ' NOCREATEROLE';
$sql .= ($inherits) ? ' INHERIT' : ' NOINHERIT';
$sql .= ($login) ? ' LOGIN' : ' NOLOGIN';
if ($connlimit != '') $sql .= " CONNECTION LIMIT {$connlimit}"; else $sql .= ' CONNECTION LIMIT -1';
if ($expiry != '') $sql .= " VALID UNTIL '{$expiry}'"; else $sql .= " VALID UNTIL 'infinity'";
$status = $this->execute($sql);
if ($status != 0) return -1;
//memberof
$old = explode(',', $memberofold);
foreach ($memberof as $m) {
if (!in_array($m, $old)) {
$status = $this->grantRole($m, $rolename);
if ($status != 0) return -1;
}
}
if($memberofold)
{
foreach ($old as $o) {
if (!in_array($o, $memberof)) {
$status = $this->revokeRole($o, $rolename, 0, 'CASCADE');
if ($status != 0) return -1;
}
}
}
//members
$old = explode(',', $membersold);
foreach ($members as $m) {
if (!in_array($m, $old)) {
$status = $this->grantRole($rolename, $m);
if ($status != 0) return -1;
}
}
if($membersold)
{
foreach ($old as $o) {
if (!in_array($o, $members)) {
$status = $this->revokeRole($rolename, $o, 0, 'CASCADE');
if ($status != 0) return -1;
}
}
}
//adminmembers
$old = explode(',', $adminmembersold);
foreach ($adminmembers as $m) {
if (!in_array($m, $old)) {
$status = $this->grantRole($rolename, $m, 1);
if ($status != 0) return -1;
}
}
if($adminmembersold)
{
foreach ($old as $o) {
if (!in_array($o, $adminmembers)) {
$status = $this->revokeRole($rolename, $o, 1, 'CASCADE');
if ($status != 0) return -1;
}
}
}
return $status;
}
/**
* Renames a role
* @param $rolename The name of the role to rename
* @param $newrolename The new name of the role
* @return 0 success
*/
function renameRole($rolename, $newrolename){
$this->fieldClean($rolename);
$this->fieldClean($newrolename);
$sql = "ALTER ROLE \"{$rolename}\" RENAME TO \"{$newrolename}\"";
return $this->execute($sql);
}
/**
* Adjusts a role's info and renames it
* @param $rolename The name of the role to adjust
* @param $password A password for the role
* @param $superuser Boolean whether or not the role is a superuser
* @param $createdb Boolean whether or not the role can create databases
* @param $createrole Boolean whether or not the role can create other roles
* @param $inherits Boolean whether or not the role inherits the privileges from parent roles
* @param $login Boolean whether or not the role will be allowed to login
* @param $connlimit Number of concurrent connections the role can make
* @param $expiry string Format 'YYYY-MM-DD HH:MM:SS'. '' means never expire
* @param $memberof (array) Roles to which the role will be immediately added as a new member
* @param $members (array) Roles which are automatically added as members of the role
* @param $adminmembers (array) Roles which are automatically added as admin members of the role
* @param $memberofold (array) Original roles whose the role belongs to
* @param $membersold (array) Original roles that are members of the role
* @param $adminmembersold (array) Original roles that are admin members of the role
* @param $newrolename The new name of the role
* @return 0 success
* @return -1 transaction error
* @return -2 set role attributes error
* @return -3 rename error
*/
function setRenameRole($rolename, $password, $superuser, $createdb, $createrole,
$inherits, $login, $connlimit, $expiry, $memberof, $members, $adminmembers,
$memberofold, $membersold, $adminmembersold, $newrolename) {
$status = $this->beginTransaction();
if ($status != 0) return -1;
if ($rolename != $newrolename){
$status = $this->renameRole($rolename, $newrolename);
if ($status != 0) {
$this->rollbackTransaction();
return -3;
}
$rolename = $newrolename;
}
$status = $this->setRole($rolename, $password, $superuser, $createdb, $createrole, $inherits, $login, $connlimit, $expiry, $memberof, $members, $adminmembers, $memberofold, $membersold, $adminmembersold);
if ($status != 0) {
$this->rollbackTransaction();
return -2;
}
return $this->endTransaction();
}
/**
* Removes a role
* @param $rolename The name of the role to drop
* @return 0 success
*/
function dropRole($rolename) {
$this->fieldClean($rolename);
$sql = "DROP ROLE \"{$rolename}\"";
return $this->execute($sql);
}
/**
* Creates a new user
* @param $username The username of the user to create
* @param $password A password for the user
* @param $createdb boolean Whether or not the user can create databases
* @param $createuser boolean Whether or not the user can create other users
* @param $expiry string Format 'YYYY-MM-DD HH:MM:SS'. '' means never expire
* @param $group (array) The groups to create the user in
* @return 0 success
*/
function createUser($username, $password, $createdb, $createuser, $expiry, $groups) {
$enc = $this->_encryptPassword($username, $password);
$this->fieldClean($username);
$this->clean($enc);
$this->clean($expiry);
$this->fieldArrayClean($groups);
$sql = "CREATE USER \"{$username}\"";
if ($password != '') $sql .= " WITH ENCRYPTED PASSWORD '{$enc}'";
$sql .= ($createdb) ? ' CREATEDB' : ' NOCREATEDB';
$sql .= ($createuser) ? ' CREATEUSER' : ' NOCREATEUSER';
if (is_array($groups) && sizeof($groups) > 0) $sql .= " IN GROUP \"" . join('", "', $groups) . "\"";
if ($expiry != '') $sql .= " VALID UNTIL '{$expiry}'";
else $sql .= " VALID UNTIL 'infinity'";
return $this->execute($sql);
}
/**
* Renames a user
* @param $username The username of the user to rename
* @param $newname The new name of the user
* @return 0 success
*/
function renameUser($username, $newname){
$this->fieldClean($username);
$this->fieldClean($newname);
$sql = "ALTER USER \"{$username}\" RENAME TO \"{$newname}\"";
return $this->execute($sql);
}
/**
* Adjusts a user's info
* @param $username The username of the user to modify
* @param $password A new password for the user
* @param $createdb boolean Whether or not the user can create databases
* @param $createuser boolean Whether or not the user can create other users
* @param $expiry string Format 'YYYY-MM-DD HH:MM:SS'. '' means never expire.
* @return 0 success
*/
function setUser($username, $password, $createdb, $createuser, $expiry) {
$enc = $this->_encryptPassword($username, $password);
$this->fieldClean($username);
$this->clean($enc);
$this->clean($expiry);
$sql = "ALTER USER \"{$username}\"";
if ($password != '') $sql .= " WITH ENCRYPTED PASSWORD '{$enc}'";
$sql .= ($createdb) ? ' CREATEDB' : ' NOCREATEDB';
$sql .= ($createuser) ? ' CREATEUSER' : ' NOCREATEUSER';
if ($expiry != '') $sql .= " VALID UNTIL '{$expiry}'";
else $sql .= " VALID UNTIL 'infinity'";
return $this->execute($sql);
}
/**
* Adjusts a user's info and renames the user
* @param $username The username of the user to modify
* @param $password A new password for the user
* @param $createdb boolean Whether or not the user can create databases
* @param $createuser boolean Whether or not the user can create other users
* @param $expiry string Format 'YYYY-MM-DD HH:MM:SS'. '' means never expire.
* @param $newname The new name of the user
* @return 0 success
* @return -1 transaction error
* @return -2 set user attributes error
* @return -3 rename error
*/
function setRenameUser($username, $password, $createdb, $createuser, $expiry, $newname) {
$status = $this->beginTransaction();
if ($status != 0) return -1;
if ($username != $newname){
$status = $this->renameUser($username, $newname);
if ($status != 0) {
$this->rollbackTransaction();
return -3;
}
$username = $newname;
}
$status = $this->setUser($username, $password, $createdb, $createuser, $expiry);
if ($status != 0) {
$this->rollbackTransaction();
return -2;
}
return $this->endTransaction();
}
/**
* Removes a user
* @param $username The username of the user to drop
* @return 0 success
*/
function dropUser($username) {
$this->fieldClean($username);
$sql = "DROP USER \"{$username}\"";
return $this->execute($sql);
}
/**
* Determines whether or not a user is a super user
* @param $username The username of the user
* @return True if is a super user, false otherwise
*/
function isSuperUser($username = '') {
$this->clean($username);
if (empty($usename)) {
$val = pg_parameter_status($this->conn->_connectionID, 'is_superuser');
if ($val !== false) return $val == 'on';
}
$sql = "SELECT usesuper FROM pg_user WHERE usename='{$username}'";
$usesuper = $this->selectField($sql, 'usesuper');
if ($usesuper == -1) return false;
else return $usesuper == 't';
}
/**
* Changes a role's password
* @param $rolename The role name
* @param $password The new password
* @return 0 success
*/
function changePassword($rolename, $password) {
$enc = $this->_encryptPassword($rolename, $password);
$this->fieldClean($rolename);
$this->clean($enc);
$sql = "ALTER ROLE \"{$rolename}\" WITH ENCRYPTED PASSWORD '{$enc}'";
return $this->execute($sql);
}
/**
* Adds a group member
* @param $groname The name of the group
* @param $user The name of the user to add to the group
* @return 0 success
*/
function addGroupMember($groname, $user) {
$this->fieldClean($groname);
$this->fieldClean($user);
$sql = "ALTER GROUP \"{$groname}\" ADD USER \"{$user}\"";
return $this->execute($sql);
}
/**
* Returns all role names which the role belongs to
* @param $rolename The role name
* @return All role names
*/
function getMemberOf($rolename) {
$this->clean($rolename);
$sql = "
SELECT rolname FROM pg_catalog.pg_roles R, pg_auth_members M
WHERE R.oid=M.roleid
AND member IN (
SELECT oid FROM pg_catalog.pg_roles
WHERE rolname='{$rolename}')
ORDER BY rolname";
return $this->selectSet($sql);
}
/**
* Returns all role names that are members of a role
* @param $rolename The role name
* @param $admin (optional) Find only admin members
* @return All role names
*/
function getMembers($rolename, $admin = 'f') {
$this->clean($rolename);
$sql = "
SELECT rolname FROM pg_catalog.pg_roles R, pg_auth_members M
WHERE R.oid=M.member AND admin_option='{$admin}'
AND roleid IN (SELECT oid FROM pg_catalog.pg_roles
WHERE rolname='{$rolename}')
ORDER BY rolname";
return $this->selectSet($sql);
}
/**
* Removes a group member
* @param $groname The name of the group
* @param $user The name of the user to remove from the group
* @return 0 success
*/
function dropGroupMember($groname, $user) {
$this->fieldClean($groname);
$this->fieldClean($user);
$sql = "ALTER GROUP \"{$groname}\" DROP USER \"{$user}\"";
return $this->execute($sql);
}
/**
* Return users in a specific group
* @param $groname The name of the group
* @return All users in the group
*/
function getGroup($groname) {
$this->clean($groname);
$sql = "
SELECT s.usename FROM pg_catalog.pg_user s, pg_catalog.pg_group g
WHERE g.groname='{$groname}' AND s.usesysid = ANY (g.grolist)
ORDER BY s.usename";
return $this->selectSet($sql);
}
/**
* Returns all groups in the database cluser
* @return All groups
*/
function getGroups() {
$sql = "SELECT groname FROM pg_group ORDER BY groname";
return $this->selectSet($sql);
}
/**
* Creates a new group
* @param $groname The name of the group
* @param $users An array of users to add to the group
* @return 0 success
*/
function createGroup($groname, $users) {
$this->fieldClean($groname);
$sql = "CREATE GROUP \"{$groname}\"";
if (is_array($users) && sizeof($users) > 0) {
$this->fieldArrayClean($users);
$sql .= ' WITH USER "' . join('", "', $users) . '"';
}
return $this->execute($sql);
}
/**
* Removes a group
* @param $groname The name of the group to drop
* @return 0 success
*/
function dropGroup($groname) {
$this->fieldClean($groname);
$sql = "DROP GROUP \"{$groname}\"";
return $this->execute($sql);
}
/**
* Internal function used for parsing ACLs
* @param $acl The ACL to parse (of type aclitem[])
* @return Privileges array
*/
function _parseACL($acl) {
// Take off the first and last characters (the braces)
$acl = substr($acl, 1, strlen($acl) - 2);
// Pick out individual ACE's by carefully parsing. This is necessary in order
// to cope with usernames and stuff that contain commas
$aces = array();
$i = $j = 0;
$in_quotes = false;
while ($i < strlen($acl)) {
// If current char is a double quote and it's not escaped, then
// enter quoted bit
$char = substr($acl, $i, 1);
if ($char == '"' && ($i == 0 || substr($acl, $i - 1, 1) != '\\'))
$in_quotes = !$in_quotes;
elseif ($char == ',' && !$in_quotes) {
// Add text so far to the array
$aces[] = substr($acl, $j, $i - $j);
$j = $i + 1;
}
$i++;
}
// Add final text to the array
$aces[] = substr($acl, $j);
// Create the array to be returned
$temp = array();
// For each ACE, generate an entry in $temp
foreach ($aces as $v) {
// If the ACE begins with a double quote, strip them off both ends
// and unescape backslashes and double quotes
$unquote = false;
if (strpos($v, '"') === 0) {
$v = substr($v, 1, strlen($v) - 2);
$v = str_replace('\\"', '"', $v);
$v = str_replace('\\\\', '\\', $v);
}
// Figure out type of ACE (public, user or group)
if (strpos($v, '=') === 0)
$atype = 'public';
else if ($this->hasRoles()) {
$atype = 'role';
}
else if (strpos($v, 'group ') === 0) {
$atype = 'group';
// Tear off 'group' prefix
$v = substr($v, 6);
}
else
$atype = 'user';
// Break on unquoted equals sign...
$i = 0;
$in_quotes = false;
$entity = null;
$chars = null;
while ($i < strlen($v)) {
// If current char is a double quote and it's not escaped, then
// enter quoted bit
$char = substr($v, $i, 1);
$next_char = substr($v, $i + 1, 1);
if ($char == '"' && ($i == 0 || $next_char != '"')) {
$in_quotes = !$in_quotes;
}
// Skip over escaped double quotes
elseif ($char == '"' && $next_char == '"') {
$i++;
}
elseif ($char == '=' && !$in_quotes) {
// Split on current equals sign
$entity = substr($v, 0, $i);
$chars = substr($v, $i + 1);
break;
}
$i++;
}
// Check for quoting on entity name, and unescape if necessary
if (strpos($entity, '"') === 0) {
$entity = substr($entity, 1, strlen($entity) - 2);
$entity = str_replace('""', '"', $entity);
}
// New row to be added to $temp
// (type, grantee, privileges, grantor, grant option?
$row = array($atype, $entity, array(), '', array());
// Loop over chars and add privs to $row
for ($i = 0; $i < strlen($chars); $i++) {
// Append to row's privs list the string representing
// the privilege
$char = substr($chars, $i, 1);
if ($char == '*')
$row[4][] = $this->privmap[substr($chars, $i - 1, 1)];
elseif ($char == '/') {
$grantor = substr($chars, $i + 1);
// Check for quoting
if (strpos($grantor, '"') === 0) {
$grantor = substr($grantor, 1, strlen($grantor) - 2);
$grantor = str_replace('""', '"', $grantor);
}
$row[3] = $grantor;
break;
}
else {
if (!isset($this->privmap[$char]))
return -3;
else
$row[2][] = $this->privmap[$char];
}
}
// Append row to temp
$temp[] = $row;
}
return $temp;
}
/**
* Grabs an array of users and their privileges for an object,
* given its type.
* @param $object The name of the object whose privileges are to be retrieved
* @param $type The type of the object (eg. database, schema, relation, function or language)
* @param $table Optional, column's table if type = column
* @return Privileges array
* @return -1 invalid type
* @return -2 object not found
* @return -3 unknown privilege type
*/
function getPrivileges($object, $type, $table = null) {
$c_schema = $this->_schema;
$this->clean($c_schema);
$this->clean($object);
switch ($type) {
case 'column':
$this->clean($table);
$sql = "
SELECT E'{' || pg_catalog.array_to_string(attacl, E',') || E'}' as acl
FROM pg_catalog.pg_attribute a
LEFT JOIN pg_catalog.pg_class c ON (a.attrelid = c.oid)
LEFT JOIN pg_catalog.pg_namespace n ON (c.relnamespace=n.oid)
WHERE n.nspname='{$c_schema}'
AND c.relname='{$table}'
AND a.attname='{$object}'";
break;
case 'table':
case 'view':
case 'sequence':
$sql = "
SELECT relacl AS acl FROM pg_catalog.pg_class
WHERE relname='{$object}'
AND relnamespace=(SELECT oid FROM pg_catalog.pg_namespace
WHERE nspname='{$c_schema}')";
break;
case 'database':
$sql = "SELECT datacl AS acl FROM pg_catalog.pg_database WHERE datname='{$object}'";
break;
case 'function':
// Since we fetch functions by oid, they are already constrained to
// the current schema.
$sql = "SELECT proacl AS acl FROM pg_catalog.pg_proc WHERE oid='{$object}'";
break;
case 'language':
$sql = "SELECT lanacl AS acl FROM pg_catalog.pg_language WHERE lanname='{$object}'";
break;
case 'schema':
$sql = "SELECT nspacl AS acl FROM pg_catalog.pg_namespace WHERE nspname='{$object}'";
break;
case 'tablespace':
$sql = "SELECT spcacl AS acl FROM pg_catalog.pg_tablespace WHERE spcname='{$object}'";
break;
default:
return -1;
}
// Fetch the ACL for object
$acl = $this->selectField($sql, 'acl');
if ($acl == -1) return -2;
elseif ($acl == '' || $acl == null) return array();
else return $this->_parseACL($acl);
}
/**
* Grants a privilege to a user, group or public
* @param $mode 'GRANT' or 'REVOKE';
* @param $type The type of object
* @param $object The name of the object
* @param $public True to grant to public, false otherwise
* @param $usernames The array of usernames to grant privs to.
* @param $groupnames The array of group names to grant privs to.
* @param $privileges The array of privileges to grant (eg. ('SELECT', 'ALL PRIVILEGES', etc.) )
* @param $grantoption True if has grant option, false otherwise
* @param $cascade True for cascade revoke, false otherwise
* @param $table the column's table if type=column
* @return 0 success
* @return -1 invalid type
* @return -2 invalid entity
* @return -3 invalid privileges
* @return -4 not granting to anything
* @return -4 invalid mode
*/
function setPrivileges($mode, $type, $object, $public, $usernames, $groupnames,
$privileges, $grantoption, $cascade, $table
) {
$f_schema = $this->_schema;
$this->fieldClean($f_schema);
$this->fieldArrayClean($usernames);
$this->fieldArrayClean($groupnames);
// Input checking
if (!is_array($privileges) || sizeof($privileges) == 0) return -3;
if (!is_array($usernames) || !is_array($groupnames) ||
(!$public && sizeof($usernames) == 0 && sizeof($groupnames) == 0)) return -4;
if ($mode != 'GRANT' && $mode != 'REVOKE') return -5;
$sql = $mode;
// Grant option
if ($this->hasGrantOption() && $mode == 'REVOKE' && $grantoption) {
$sql .= ' GRANT OPTION FOR';
}
if (in_array('ALL PRIVILEGES', $privileges)) {
$sql .= ' ALL PRIVILEGES';
}
else {
if ($type == 'column') {
$this->fieldClean($object);
$sql .= ' ' . join(" (\"{$object}\"), ", $privileges);
}
else {
$sql .= ' ' . join(', ', $privileges);
}
}
switch ($type) {
case 'column':
$sql .= " (\"{$object}\")";
$object = $table;
case 'table':
case 'view':
case 'sequence':
$this->fieldClean($object);
$sql .= " ON \"{$f_schema}\".\"{$object}\"";
break;
case 'database':
$this->fieldClean($object);
$sql .= " ON DATABASE \"{$object}\"";
break;
case 'function':
// Function comes in with $object as function OID
$fn = $this->getFunction($object);
$this->fieldClean($fn->fields['proname']);
$sql .= " ON FUNCTION \"{$f_schema}\".\"{$fn->fields['proname']}\"({$fn->fields['proarguments']})";
break;
case 'language':
$this->fieldClean($object);
$sql .= " ON LANGUAGE \"{$object}\"";
break;
case 'schema':
$this->fieldClean($object);
$sql .= " ON SCHEMA \"{$object}\"";
break;
case 'tablespace':
$this->fieldClean($object);
$sql .= " ON TABLESPACE \"{$object}\"";
break;
default:
return -1;
}
// Dump PUBLIC
$first = true;
$sql .= ($mode == 'GRANT') ? ' TO ' : ' FROM ';
if ($public) {
$sql .= 'PUBLIC';
$first = false;
}
// Dump users
foreach ($usernames as $v) {
if ($first) {
$sql .= "\"{$v}\"";
$first = false;
}
else {
$sql .= ", \"{$v}\"";
}
}
// Dump groups
foreach ($groupnames as $v) {
if ($first) {
$sql .= "GROUP \"{$v}\"";
$first = false;
}
else {
$sql .= ", GROUP \"{$v}\"";
}
}
// Grant option
if ($this->hasGrantOption() && $mode == 'GRANT' && $grantoption) {
$sql .= ' WITH GRANT OPTION';
}
// Cascade revoke
if ($this->hasGrantOption() && $mode == 'REVOKE' && $cascade) {
$sql .= ' CASCADE';
}
return $this->execute($sql);
}
/**
* Helper function that computes encypted PostgreSQL passwords
* @param $username The username
* @param $password The password
*/
function _encryptPassword($username, $password) {
return 'md5' . md5($password . $username);
}
// Tablespace functions
/**
* Retrieves information for all tablespaces
* @param $all Include all tablespaces (necessary when moving objects back to the default space)
* @return A recordset
*/
function getTablespaces($all = false) {
global $conf;
$sql = "SELECT spcname, pg_catalog.pg_get_userbyid(spcowner) AS spcowner, pg_catalog.pg_tablespace_location(oid) as spclocation,
(SELECT description FROM pg_catalog.pg_shdescription pd WHERE pg_tablespace.oid=pd.objoid AND pd.classoid='pg_tablespace'::regclass) AS spccomment
FROM pg_catalog.pg_tablespace";
if (!$conf['show_system'] && !$all) {
$sql .= ' WHERE spcname NOT LIKE $$pg\_%$$';
}
$sql .= " ORDER BY spcname";
return $this->selectSet($sql);
}
/**
* Retrieves a tablespace's information
* @return A recordset
*/
function getTablespace($spcname) {
$this->clean($spcname);
$sql = "SELECT spcname, pg_catalog.pg_get_userbyid(spcowner) AS spcowner, pg_catalog.pg_tablespace_location(oid) as spclocation,
(SELECT description FROM pg_catalog.pg_shdescription pd WHERE pg_tablespace.oid=pd.objoid AND pd.classoid='pg_tablespace'::regclass) AS spccomment
FROM pg_catalog.pg_tablespace WHERE spcname='{$spcname}'";
return $this->selectSet($sql);
}
/**
* Creates a tablespace
* @param $spcname The name of the tablespace to create
* @param $spcowner The owner of the tablespace. '' for current
* @param $spcloc The directory in which to create the tablespace
* @return 0 success
*/
function createTablespace($spcname, $spcowner, $spcloc, $comment='') {
$this->fieldClean($spcname);
$this->clean($spcloc);
$sql = "CREATE TABLESPACE \"{$spcname}\"";
if ($spcowner != '') {
$this->fieldClean($spcowner);
$sql .= " OWNER \"{$spcowner}\"";
}
$sql .= " LOCATION '{$spcloc}'";
$status = $this->execute($sql);
if ($status != 0) return -1;
if ($comment != '' && $this->hasSharedComments()) {
$status = $this->setComment('TABLESPACE',$spcname,'',$comment);
if ($status != 0) return -2;
}
return 0;
}
/**
* Alters a tablespace
* @param $spcname The name of the tablespace
* @param $name The new name for the tablespace
* @param $owner The new owner for the tablespace
* @return 0 success
* @return -1 transaction error
* @return -2 owner error
* @return -3 rename error
* @return -4 comment error
*/
function alterTablespace($spcname, $name, $owner, $comment='') {
$this->fieldClean($spcname);
$this->fieldClean($name);
$this->fieldClean($owner);
// Begin transaction
$status = $this->beginTransaction();
if ($status != 0) return -1;
// Owner
$sql = "ALTER TABLESPACE \"{$spcname}\" OWNER TO \"{$owner}\"";
$status = $this->execute($sql);
if ($status != 0) {
$this->rollbackTransaction();
return -2;
}
// Rename (only if name has changed)
if ($name != $spcname) {
$sql = "ALTER TABLESPACE \"{$spcname}\" RENAME TO \"{$name}\"";
$status = $this->execute($sql);
if ($status != 0) {
$this->rollbackTransaction();
return -3;
}
$spcname = $name;
}
// Set comment if it has changed
if (trim($comment) != '' && $this->hasSharedComments()) {
$status = $this->setComment('TABLESPACE',$spcname,'',$comment);
if ($status != 0) return -4;
}
return $this->endTransaction();
}
/**
* Drops a tablespace
* @param $spcname The name of the domain to drop
* @return 0 success
*/
function dropTablespace($spcname) {
$this->fieldClean($spcname);
$sql = "DROP TABLESPACE \"{$spcname}\"";
return $this->execute($sql);
}
// Administration functions
/**
* Analyze a database
* @param $table (optional) The table to analyze
*/
function analyzeDB($table = '') {
if ($table != '') {
$f_schema = $this->_schema;
$this->fieldClean($f_schema);
$this->fieldClean($table);
$sql = "ANALYZE \"{$f_schema}\".\"{$table}\"";
}
else
$sql = "ANALYZE";
return $this->execute($sql);
}
/**
* Vacuums a database
* @param $table The table to vacuum
* @param $analyze If true, also does analyze
* @param $full If true, selects "full" vacuum
* @param $freeze If true, selects aggressive "freezing" of tuples
*/
function vacuumDB($table = '', $analyze = false, $full = false, $freeze = false) {
$sql = "VACUUM";
if ($full) $sql .= " FULL";
if ($freeze) $sql .= " FREEZE";
if ($analyze) $sql .= " ANALYZE";
if ($table != '') {
$f_schema = $this->_schema;
$this->fieldClean($f_schema);
$this->fieldClean($table);
$sql .= " \"{$f_schema}\".\"{$table}\"";
}
return $this->execute($sql);
}
/**
* Returns all autovacuum global configuration
* @return associative array array( param => value, ...)
*/
function getAutovacuum() {
$_defaults = $this->selectSet("SELECT name, setting
FROM pg_catalog.pg_settings
WHERE
name = 'autovacuum'
OR name = 'autovacuum_vacuum_threshold'
OR name = 'autovacuum_vacuum_scale_factor'
OR name = 'autovacuum_analyze_threshold'
OR name = 'autovacuum_analyze_scale_factor'
OR name = 'autovacuum_vacuum_cost_delay'
OR name = 'autovacuum_vacuum_cost_limit'
OR name = 'vacuum_freeze_min_age'
OR name = 'autovacuum_freeze_max_age'
"
);
$ret = array();
while (!$_defaults->EOF) {
$ret[$_defaults->fields['name']] = $_defaults->fields['setting'];
$_defaults->moveNext();
}
return $ret;
}
/**
* Returns all available autovacuum per table information.
* @return A recordset
*/
function saveAutovacuum($table, $vacenabled, $vacthreshold, $vacscalefactor, $anathresold,
$anascalefactor, $vaccostdelay, $vaccostlimit)
{
$f_schema = $this->_schema;
$this->fieldClean($f_schema);
$this->fieldClean($table);
$sql = "ALTER TABLE \"{$f_schema}\".\"{$table}\" SET (";
if (!empty($vacenabled)) {
$this->clean($vacenabled);
$params[] = "autovacuum_enabled='{$vacenabled}'";
}
if (!empty($vacthreshold)) {
$this->clean($vacthreshold);
$params[] = "autovacuum_vacuum_threshold='{$vacthreshold}'";
}
if (!empty($vacscalefactor)) {
$this->clean($vacscalefactor);
$params[] = "autovacuum_vacuum_scale_factor='{$vacscalefactor}'";
}
if (!empty($anathresold)) {
$this->clean($anathresold);
$params[] = "autovacuum_analyze_threshold='{$anathresold}'";
}
if (!empty($anascalefactor)) {
$this->clean($anascalefactor);
$params[] = "autovacuum_analyze_scale_factor='{$anascalefactor}'";
}
if (!empty($vaccostdelay)) {
$this->clean($vaccostdelay);
$params[] = "autovacuum_vacuum_cost_delay='{$vaccostdelay}'";
}
if (!empty($vaccostlimit)) {
$this->clean($vaccostlimit);
$params[] = "autovacuum_vacuum_cost_limit='{$vaccostlimit}'";
}
$sql = $sql . implode(',', $params) . ');';
return $this->execute($sql);
}
function dropAutovacuum($table) {
$f_schema = $this->_schema;
$this->fieldClean($f_schema);
$this->fieldClean($table);
return $this->execute("
ALTER TABLE \"{$f_schema}\".\"{$table}\" RESET (autovacuum_enabled, autovacuum_vacuum_threshold,
autovacuum_vacuum_scale_factor, autovacuum_analyze_threshold, autovacuum_analyze_scale_factor,
autovacuum_vacuum_cost_delay, autovacuum_vacuum_cost_limit
);"
);
}
/**
* Returns all available process information.
* @param $database (optional) Find only connections to specified database
* @return A recordset
*/
function getProcesses($database = null) {
if ($database === null)
$sql = "SELECT datname, usename, pid, query, query_start
FROM pg_catalog.pg_stat_activity
ORDER BY datname, usename, pid";
else {
$this->clean($database);
$sql = "SELECT datname, usename, pid, query, query_start
FROM pg_catalog.pg_stat_activity
WHERE datname='{$database}'
ORDER BY usename, pid";
}
return $this->selectSet($sql);
}
/**
* Returns table locks information in the current database
* @return A recordset
*/
function getLocks() {
global $conf;
if (!$conf['show_system'])
$where = 'AND pn.nspname NOT LIKE $$pg\_%$$';
else
$where = "AND nspname !~ '^pg_t(emp_[0-9]+|oast)$'";
$sql = "
SELECT
pn.nspname, pc.relname AS tablename, pl.pid, pl.mode, pl.granted, pl.virtualtransaction,
(select transactionid from pg_catalog.pg_locks l2 where l2.locktype='transactionid'
and l2.mode='ExclusiveLock' and l2.virtualtransaction=pl.virtualtransaction) as transaction
FROM
pg_catalog.pg_locks pl,
pg_catalog.pg_class pc,
pg_catalog.pg_namespace pn
WHERE
pl.relation = pc.oid AND pc.relnamespace=pn.oid
{$where}
ORDER BY pid,nspname,tablename";
return $this->selectSet($sql);
}
/**
* Sends a cancel or kill command to a process
* @param $pid The ID of the backend process
* @param $signal 'CANCEL'
* @return 0 success
* @return -1 invalid signal type
*/
function sendSignal($pid, $signal) {
// Clean
$pid = (int)$pid;
if ($signal == 'CANCEL')
$sql = "SELECT pg_catalog.pg_cancel_backend({$pid}) AS val";
elseif ($signal == 'KILL')
$sql = "SELECT pg_catalog.pg_terminate_backend({$pid}) AS val";
else
return -1;
// Execute the query
$val = $this->selectField($sql, 'val');
if ($val === 'f') return -1;
elseif ($val === 't') return 0;
else return -1;
}
// Misc functions
/**
* Sets the comment for an object in the database
* @pre All parameters must already be cleaned
* @param $obj_type One of 'TABLE' | 'COLUMN' | 'VIEW' | 'SCHEMA' | 'SEQUENCE' | 'TYPE' | 'FUNCTION' | 'AGGREGATE'
* @param $obj_name The name of the object for which to attach a comment.
* @param $table Name of table that $obj_name belongs to. Ignored unless $obj_type is 'TABLE' or 'COLUMN'.
* @param $comment The comment to add.
* @return 0 success
*/
function setComment($obj_type, $obj_name, $table, $comment, $basetype = NULL) {
$sql = "COMMENT ON {$obj_type} " ;
$f_schema = $this->_schema;
$this->fieldClean($f_schema);
$this->clean($comment); // Passing in an already cleaned comment will lead to double escaped data
// So, while counter-intuitive, it is important to not clean comments before
// calling setComment. We will clean it here instead.
/*
$this->fieldClean($table);
$this->fieldClean($obj_name);
*/
switch ($obj_type) {
case 'TABLE':
$sql .= "\"{$f_schema}\".\"{$table}\" IS ";
break;
case 'COLUMN':
$sql .= "\"{$f_schema}\".\"{$table}\".\"{$obj_name}\" IS ";
break;
case 'SEQUENCE':
case 'VIEW':
case 'TEXT SEARCH CONFIGURATION':
case 'TEXT SEARCH DICTIONARY':
case 'TEXT SEARCH TEMPLATE':
case 'TEXT SEARCH PARSER':
case 'TYPE':
$sql .= "\"{$f_schema}\".";
case 'DATABASE':
case 'ROLE':
case 'SCHEMA':
case 'TABLESPACE':
$sql .= "\"{$obj_name}\" IS ";
break;
case 'FUNCTION':
$sql .= "\"{$f_schema}\".{$obj_name} IS ";
break;
case 'AGGREGATE':
$sql .= "\"{$f_schema}\".\"{$obj_name}\" (\"{$basetype}\") IS ";
break;
default:
// Unknown object type
return -1;
}
if ($comment != '')
$sql .= "'{$comment}';";
else
$sql .= 'NULL;';
return $this->execute($sql);
}
/**
* A private helper method for executeScript that advances the
* character by 1. In psql this is careful to take into account
* multibyte languages, but we don't at the moment, so this function
* is someone redundant, since it will always advance by 1
* @param &$i The current character position in the line
* @param &$prevlen Length of previous character (ie. 1)
* @param &$thislen Length of current character (ie. 1)
*/
private
function advance_1(&$i, &$prevlen, &$thislen) {
$prevlen = $thislen;
$i += $thislen;
$thislen = 1;
}
/**
* Private helper method to detect a valid $foo$ quote delimiter at
* the start of the parameter dquote
* @return True if valid, false otherwise
*/
private
function valid_dolquote($dquote) {
// XXX: support multibyte
return (preg_match('/^[$][$]/', $dquote) || preg_match('/^[$][_[:alpha:]][_[:alnum:]]*[$]/', $dquote));
}
/**
* Executes an SQL script as a series of SQL statements. Returns
* the result of the final step. This is a very complicated lexer
* based on the REL7_4_STABLE src/bin/psql/mainloop.c lexer in
* the PostgreSQL source code.
* XXX: It does not handle multibyte languages properly.
* @param $name Entry in $_FILES to use
* @param $callback (optional) Callback function to call with each query,
its result and line number.
* @return True for general success, false on any failure.
*/
function executeScript($name, $callback = null) {
global $data;
// This whole function isn't very encapsulated, but hey...
$conn = $data->conn->_connectionID;
if (!is_uploaded_file($_FILES[$name]['tmp_name'])) return false;
$fd = fopen($_FILES[$name]['tmp_name'], 'r');
if (!$fd) return false;
// Build up each SQL statement, they can be multiline
$query_buf = null;
$query_start = 0;
$in_quote = 0;
$in_xcomment = 0;
$bslash_count = 0;
$dol_quote = null;
$paren_level = 0;
$len = 0;
$i = 0;
$prevlen = 0;
$thislen = 0;
$lineno = 0;
// Loop over each line in the file
while (!feof($fd)) {
$line = fgets($fd);
$lineno++;
// Nothing left on line? Then ignore...
if (trim($line) == '') continue;
$len = strlen($line);
$query_start = 0;
/*
* Parse line, looking for command separators.
*
* The current character is at line[i], the prior character at line[i
* - prevlen], the next character at line[i + thislen].
*/
$prevlen = 0;
$thislen = ($len > 0) ? 1 : 0;
for ($i = 0; $i < $len; $this->advance_1($i, $prevlen, $thislen)) {
/* was the previous character a backslash? */
if ($i > 0 && substr($line, $i - $prevlen, 1) == '\\')
$bslash_count++;
else
$bslash_count = 0;
/*
* It is important to place the in_* test routines before the
* in_* detection routines. i.e. we have to test if we are in
* a quote before testing for comments.
*/
/* in quote? */
if ($in_quote !== 0)
{
/*
* end of quote if matching non-backslashed character.
* backslashes don't count for double quotes, though.
*/
if (substr($line, $i, 1) == $in_quote &&
($bslash_count % 2 == 0 || $in_quote == '"'))
$in_quote = 0;
}
/* in or end of $foo$ type quote? */
else if ($dol_quote) {
if (strncmp(substr($line, $i), $dol_quote, strlen($dol_quote)) == 0) {
$this->advance_1($i, $prevlen, $thislen);
while(substr($line, $i, 1) != '$')
$this->advance_1($i, $prevlen, $thislen);
$dol_quote = null;
}
}
/* start of extended comment? */
else if (substr($line, $i, 2) == '/*')
{
$in_xcomment++;
if ($in_xcomment == 1)
$this->advance_1($i, $prevlen, $thislen);
}
/* in or end of extended comment? */
else if ($in_xcomment)
{
if (substr($line, $i, 2) == '*/' && !--$in_xcomment)
$this->advance_1($i, $prevlen, $thislen);
}
/* start of quote? */
else if (substr($line, $i, 1) == '\'' || substr($line, $i, 1) == '"') {
$in_quote = substr($line, $i, 1);
}
/*
* start of $foo$ type quote?
*/
else if (!$dol_quote && $this->valid_dolquote(substr($line, $i))) {
$dol_end = strpos(substr($line, $i + 1), '$');
$dol_quote = substr($line, $i, $dol_end + 1);
$this->advance_1($i, $prevlen, $thislen);
while (substr($line, $i, 1) != '$') {
$this->advance_1($i, $prevlen, $thislen);
}
}
/* single-line comment? truncate line */
else if (substr($line, $i, 2) == '--')
{
$line = substr($line, 0, $i); /* remove comment */
break;
}
/* count nested parentheses */
else if (substr($line, $i, 1) == '(') {
$paren_level++;
}
else if (substr($line, $i, 1) == ')' && $paren_level > 0) {
$paren_level--;
}
/* semicolon? then send query */
else if (substr($line, $i, 1) == ';' && !$bslash_count && !$paren_level)
{
$subline = substr(substr($line, 0, $i), $query_start);
/* is there anything else on the line? */
if (strspn($subline, " \t\n\r") != strlen($subline))
{
/*
* insert a cosmetic newline, if this is not the first
* line in the buffer
*/
if (strlen($query_buf) > 0)
$query_buf .= "\n";
/* append the line to the query buffer */
$query_buf .= $subline;
$query_buf .= ';';
// Execute the query. PHP cannot execute
// empty queries, unlike libpq
$res = @pg_query($conn, $query_buf);
// Call the callback function for display
if ($callback !== null) $callback($query_buf, $res, $lineno);
// Check for COPY request
if (pg_result_status($res) == 4) { // 4 == PGSQL_COPY_FROM
while (!feof($fd)) {
$copy = fgets($fd, 32768);
$lineno++;
pg_put_line($conn, $copy);
if ($copy == "\\.\n" || $copy == "\\.\r\n") {
pg_end_copy($conn);
break;
}
}
}
}
$query_buf = null;
$query_start = $i + $thislen;
}
/*
* keyword or identifier?
* We grab the whole string so that we don't
* mistakenly see $foo$ inside an identifier as the start
* of a dollar quote.
*/
// XXX: multibyte here
else if (preg_match('/^[_[:alpha:]]$/', substr($line, $i, 1))) {
$sub = substr($line, $i, $thislen);
while (preg_match('/^[\$_A-Za-z0-9]$/', $sub)) {
/* keep going while we still have identifier chars */
$this->advance_1($i, $prevlen, $thislen);
$sub = substr($line, $i, $thislen);
}
// Since we're now over the next character to be examined, it is necessary
// to move back one space.
$i-=$prevlen;
}
} // end for
/* Put the rest of the line in the query buffer. */
$subline = substr($line, $query_start);
if ($in_quote || $dol_quote || strspn($subline, " \t\n\r") != strlen($subline))
{
if (strlen($query_buf) > 0)
$query_buf .= "\n";
$query_buf .= $subline;
}
$line = null;
} // end while
/*
* Process query at the end of file without a semicolon, so long as
* it's non-empty.
*/
if (strlen($query_buf) > 0 && strspn($query_buf, " \t\n\r") != strlen($query_buf))
{
// Execute the query
$res = @pg_query($conn, $query_buf);
// Call the callback function for display
if ($callback !== null) $callback($query_buf, $res, $lineno);
// Check for COPY request
if (pg_result_status($res) == 4) { // 4 == PGSQL_COPY_FROM
while (!feof($fd)) {
$copy = fgets($fd, 32768);
$lineno++;
pg_put_line($conn, $copy);
if ($copy == "\\.\n" || $copy == "\\.\r\n") {
pg_end_copy($conn);
break;
}
}
}
}
fclose($fd);
return true;
}
/**
* Generates the SQL for the 'select' function
* @param $table The table from which to select
* @param $show An array of columns to show. Empty array means all columns.
* @param $values An array mapping columns to values
* @param $ops An array of the operators to use
* @param $orderby (optional) An array of column numbers or names (one based)
* mapped to sort direction (asc or desc or '' or null) to order by
* @return The SQL query
*/
function getSelectSQL($table, $show, $values, $ops, $orderby = array()) {
$this->fieldArrayClean($show);
// If an empty array is passed in, then show all columns
if (sizeof($show) == 0) {
if ($this->hasObjectID($table))
$sql = "SELECT \"{$this->id}\", * FROM ";
else
$sql = "SELECT * FROM ";
}
else {
// Add oid column automatically to results for editing purposes
if (!in_array($this->id, $show) && $this->hasObjectID($table))
$sql = "SELECT \"{$this->id}\", \"";
else
$sql = "SELECT \"";
$sql .= join('","', $show) . "\" FROM ";
}
$this->fieldClean($table);
if (isset($_REQUEST['schema'])) {
$f_schema = $_REQUEST['schema'];
$this->fieldClean($f_schema);
$sql .= "\"{$f_schema}\".";
}
$sql .= "\"{$table}\"";
// If we have values specified, add them to the WHERE clause
$first = true;
if (is_array($values) && sizeof($values) > 0) {
foreach ($values as $k => $v) {
if ($v != '' || $this->selectOps[$ops[$k]] == 'p') {
$this->fieldClean($k);
if ($first) {
$sql .= " WHERE ";
$first = false;
} else {
$sql .= " AND ";
}
// Different query format depending on operator type
switch ($this->selectOps[$ops[$k]]) {
case 'i':
// Only clean the field for the inline case
// this is because (x), subqueries need to
// to allow 'a','b' as input.
$this->clean($v);
$sql .= "\"{$k}\" {$ops[$k]} '{$v}'";
break;
case 'p':
$sql .= "\"{$k}\" {$ops[$k]}";
break;
case 'x':
$sql .= "\"{$k}\" {$ops[$k]} ({$v})";
break;
case 't':
$sql .= "\"{$k}\" {$ops[$k]}('{$v}')";
break;
default:
// Shouldn't happen
}
}
}
}
// ORDER BY
if (is_array($orderby) && sizeof($orderby) > 0) {
$sql .= " ORDER BY ";
$first = true;
foreach ($orderby as $k => $v) {
if ($first) $first = false;
else $sql .= ', ';
if (preg_match('/^[0-9]+$/', $k)) {
$sql .= $k;
}
else {
$this->fieldClean($k);
$sql .= '"' . $k . '"';
}
if (strtoupper($v) == 'DESC') $sql .= " DESC";
}
}
return $sql;
}
/**
* Returns a recordset of all columns in a query. Supports paging.
* @param $type Either 'QUERY' if it is an SQL query, or 'TABLE' if it is a table identifier,
* or 'SELECT" if it's a select query
* @param $table The base table of the query. NULL for no table.
* @param $query The query that is being executed. NULL for no query.
* @param $sortkey The column number to sort by, or '' or null for no sorting
* @param $sortdir The direction in which to sort the specified column ('asc' or 'desc')
* @param $page The page of the relation to retrieve
* @param $page_size The number of rows per page
* @param &$max_pages (return-by-ref) The max number of pages in the relation
* @return A recordset on success
* @return -1 transaction error
* @return -2 counting error
* @return -3 page or page_size invalid
* @return -4 unknown type
* @return -5 failed setting transaction read only
*/
function browseQuery($type, $table, $query, $sortkey, $sortdir, $page, $page_size, &$max_pages) {
// Check that we're not going to divide by zero
if (!is_numeric($page_size) || $page_size != (int)$page_size || $page_size <= 0) return -3;
// If $type is TABLE, then generate the query
switch ($type) {
case 'TABLE':
if (preg_match('/^[0-9]+$/', $sortkey) && $sortkey > 0) $orderby = array($sortkey => $sortdir);
else $orderby = array();
$query = $this->getSelectSQL($table, array(), array(), array(), $orderby);
break;
case 'QUERY':
case 'SELECT':
// Trim query
$query = trim($query);
// Trim off trailing semi-colon if there is one
if (substr($query, strlen($query) - 1, 1) == ';')
$query = substr($query, 0, strlen($query) - 1);
break;
default:
return -4;
}
// Generate count query
$count = "SELECT COUNT(*) AS total FROM ($query) AS sub";
// Open a transaction
$status = $this->beginTransaction();
if ($status != 0) return -1;
// If backend supports read only queries, then specify read only mode
// to avoid side effects from repeating queries that do writes.
if ($this->hasReadOnlyQueries()) {
$status = $this->execute("SET TRANSACTION READ ONLY");
if ($status != 0) {
$this->rollbackTransaction();
return -5;
}
}
// Count the number of rows
$total = $this->browseQueryCount($query, $count);
if ($total < 0) {
$this->rollbackTransaction();
return -2;
}
// Calculate max pages
$max_pages = ceil($total / $page_size);
// Check that page is less than or equal to max pages
if (!is_numeric($page) || $page != (int)$page || $page > $max_pages || $page < 1) {
$this->rollbackTransaction();
return -3;
}
// Set fetch mode to NUM so that duplicate field names are properly returned
// for non-table queries. Since the SELECT feature only allows selecting one
// table, duplicate fields shouldn't appear.
if ($type == 'QUERY') $this->conn->setFetchMode(ADODB_FETCH_NUM);
// Figure out ORDER BY. Sort key is always the column number (based from one)
// of the column to order by. Only need to do this for non-TABLE queries
if ($type != 'TABLE' && preg_match('/^[0-9]+$/', $sortkey) && $sortkey > 0) {
$orderby = " ORDER BY {$sortkey}";
// Add sort order
if ($sortdir == 'desc')
$orderby .= ' DESC';
else
$orderby .= ' ASC';
}
else $orderby = '';
// Actually retrieve the rows, with offset and limit
$rs = $this->selectSet("SELECT * FROM ({$query}) AS sub {$orderby} LIMIT {$page_size} OFFSET " . ($page - 1) * $page_size);
$status = $this->endTransaction();
if ($status != 0) {
$this->rollbackTransaction();
return -1;
}
return $rs;
}
/**
* Finds the number of rows that would be returned by a
* query.
* @param $query The SQL query
* @param $count The count query
* @return The count of rows
* @return -1 error
*/
function browseQueryCount($query, $count) {
return $this->selectField($count, 'total');
}
/**
* Returns a recordset of all columns in a table
* @param $table The name of a table
* @param $key The associative array holding the key to retrieve
* @return A recordset
*/
function browseRow($table, $key) {
$f_schema = $this->_schema;
$this->fieldClean($f_schema);
$this->fieldClean($table);
$sql = "SELECT * FROM \"{$f_schema}\".\"{$table}\"";
if (is_array($key) && sizeof($key) > 0) {
$sql .= " WHERE true";
foreach ($key as $k => $v) {
$this->fieldClean($k);
$this->clean($v);
$sql .= " AND \"{$k}\"='{$v}'";
}
}
return $this->selectSet($sql);
}
// Type conversion routines
/**
* Change the value of a parameter to 't' or 'f' depending on whether it evaluates to true or false
* @param $parameter the parameter
*/
function dbBool(&$parameter) {
if ($parameter) $parameter = 't';
else $parameter = 'f';
return $parameter;
}
/**
* Change a parameter from 't' or 'f' to a boolean, (others evaluate to false)
* @param $parameter the parameter
*/
function phpBool($parameter) {
$parameter = ($parameter == 't');
return $parameter;
}
// interfaces Statistics collector functions
/**
* Fetches statistics for a database
* @param $database The database to fetch stats for
* @return A recordset
*/
function getStatsDatabase($database) {
$this->clean($database);
$sql = "SELECT * FROM pg_stat_database WHERE datname='{$database}'";
return $this->selectSet($sql);
}
/**
* Fetches tuple statistics for a table
* @param $table The table to fetch stats for
* @return A recordset
*/
function getStatsTableTuples($table) {
$c_schema = $this->_schema;
$this->clean($c_schema);
$this->clean($table);
$sql = "SELECT * FROM pg_stat_all_tables
WHERE schemaname='{$c_schema}' AND relname='{$table}'";
return $this->selectSet($sql);
}
/**
* Fetches I/0 statistics for a table
* @param $table The table to fetch stats for
* @return A recordset
*/
function getStatsTableIO($table) {
$c_schema = $this->_schema;
$this->clean($c_schema);
$this->clean($table);
$sql = "SELECT * FROM pg_statio_all_tables
WHERE schemaname='{$c_schema}' AND relname='{$table}'";
return $this->selectSet($sql);
}
/**
* Fetches tuple statistics for all indexes on a table
* @param $table The table to fetch index stats for
* @return A recordset
*/
function getStatsIndexTuples($table) {
$c_schema = $this->_schema;
$this->clean($c_schema);
$this->clean($table);
$sql = "SELECT * FROM pg_stat_all_indexes
WHERE schemaname='{$c_schema}' AND relname='{$table}' ORDER BY indexrelname";
return $this->selectSet($sql);
}
/**
* Fetches I/0 statistics for all indexes on a table
* @param $table The table to fetch index stats for
* @return A recordset
*/
function getStatsIndexIO($table) {
$c_schema = $this->_schema;
$this->clean($c_schema);
$this->clean($table);
$sql = "SELECT * FROM pg_statio_all_indexes
WHERE schemaname='{$c_schema}' AND relname='{$table}'
ORDER BY indexrelname";
return $this->selectSet($sql);
}
// Capabilities
function hasAggregateSortOp() { return true; }
function hasAlterAggregate() { return true; }
function hasAlterColumnType() { return true; }
function hasAlterDatabaseOwner() { return true; }
function hasAlterDatabaseRename() { return true; }
function hasAlterSchema() { return true; }
function hasAlterSchemaOwner() { return true; }
function hasAlterSequenceSchema() { return true; }
function hasAlterSequenceStart() { return true; }
function hasAlterTableSchema() { return true; }
function hasAutovacuum() { return true; }
function hasCreateTableLike() { return true; }
function hasCreateTableLikeWithConstraints() { return true; }
function hasCreateTableLikeWithIndexes() { return true; }
function hasCreateFieldWithConstraints() { return true; }
function hasDisableTriggers() { return true; }
function hasAlterDomains() { return true; }
function hasDomainConstraints() { return true; }
function hasEnumTypes() { return true; }
function hasFTS() { return true; }
function hasFunctionAlterOwner() { return true; }
function hasFunctionAlterSchema() { return true; }
function hasFunctionCosting() { return true; }
function hasFunctionGUC() { return true; }
function hasGrantOption() { return true; }
function hasNamedParams() { return true; }
function hasPrepare() { return true; }
function hasPreparedXacts() { return true; }
function hasReadOnlyQueries() { return true; }
function hasRecluster() { return true; }
function hasRoles() { return true; }
function hasServerAdminFuncs() { return true; }
function hasSharedComments() { return true; }
function hasQueryCancel() { return true; }
function hasTablespaces() { return true; }
function hasUserRename() { return true; }
function hasVirtualTransactionId() { return true; }
function hasAlterDatabase() { return $this->hasAlterDatabaseRename(); }
function hasDatabaseCollation() { return true; }
function hasMagicTypes() { return true; }
function hasQueryKill() { return true; }
function hasConcurrentIndexBuild() { return true; }
function hasForceReindex() { return false; }
function hasByteaHexDefault() { return true; }
}
?>
|