gpcheckcat 169.2 KB
Newer Older
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
#!/usr/bin/env python
'''
Usage: gpcheckcat [<option>] [dbname]

    -? 
    -B parallel: number of worker threads
    -g dir     : generate SQL to rectify catalog corruption, put it in dir
    -p port    : DB port number
    -P passwd  : DB password
    -U uname   : DB User Name
    -v         : verbose
    -A         : all databases
    -S option  : shared table options (none, only)
    -O         : Online 
    -l         : list all tests
    -R test    : run this particular test
    -C catname : run cross consistency, FK and ACL tests for this catalog table

'''
import sys, os, subprocess, tempfile, stat, re
from threading import Thread
from datetime import datetime
from time import localtime, strftime
import time
import getopt

TIMESTAMP = datetime.now().strftime("%Y%m%d%H%M%S")
REPAIR_SCRIPT='runsql_%s.sh' % TIMESTAMP

try:
    from gppylib.db import dbconn
    from gppylib.gplog import *
    from gppylib.gpcatalog import *
    from gppylib.commands.unix import *
    from pygresql.pgdb import DatabaseError
    from pygresql import pg
except ImportError, e:
    sys.exit('Error: unable to import module: ' + str(e))

parallelism = 8
# cache OID -> object name cache
oidmap = {}

#-------------------------------------------------------------------------------
EXECNAME = os.path.split(__file__)[-1]
setup_tool_logging(EXECNAME,getLocalHostname(),getUserName())
very_quiet_stdout_logging()
logger = get_default_logger()
#-------------------------------------------------------------------------------

################
def parse_int(val):
    try: val = int(val)
    except ValueError: val = 0
    return val

###############################
def quote_value(name):
    """Add surrounding single quote, double interior single quote."""
    assert isinstance(name,str)
    return "'" + "''".join(name.split("'")) + "'"


SUCCESS=0
ERROR_REMOVE=1
ERROR_RESYNC=2
ERROR_NOREPAIR=3
def setError(level):
    '''
    Increases the error level to the specified level, if specified level is
    lower than the existing level no change is made.
    
    error level 0 => success
    error level 1 => error, with repair script removes objects
    error level 2 => error, with repair script that resynchronizes objects
    error level 3 => error, no repair script
    '''
    GV.retcode = max(level, GV.retcode)


###############################
class Global():

    def __init__(self):
        self.retcode   = SUCCESS
        self.opt       = {}
        self.opt['-h'] = None
        self.opt['-p'] = None
        self.opt['-P'] = None
        self.opt['-U'] = None
        self.opt['-v'] = False
        self.opt['-V'] = False
        self.opt['-t'] = False
    
        self.opt['-g'] = 'gpcheckcat.repair.' + strftime('%Y-%m-%d.%H.%M.%S', localtime())
        self.opt['-B'] = parallelism
        self.opt['-T'] = None
    
        self.opt['-A'] = False
        self.opt['-S'] = None
        self.opt['-O'] = False
    
        self.opt['-R'] = None
        self.opt['-C'] = None
        self.opt['-l'] = False
    
        self.cfg       = None
        self.dbname    = None
        self.firstdb   = None
        self.alldb     = []
        self.db        = {}
        self.tmpdir    = None
    
        self.reset_stmt_queues()
        
        self.home = os.environ.get('HOME')
        if self.home == None:
            usage('Error: $HOME must be set')
        self.user = os.environ.get('USER') or os.environ.get('LOGNAME')
        if self.user == None:
            usage('Error: either $USER or $LOGNAME must be set')
    
        self.catalog = None
        self.max_content = 0
        self.report_cfg = {}
        
    def reset_stmt_queues(self):

        # dictionary of SQL statements. Key is dbid
        self.Remove = {}
    
        # dictionary of SQL statements. Key is dbid
        self.AdjustConname = {}
    
        # dictionary of SQL statements. Key is dbid
        self.DemoteConstraint = {}
    
        # array of SQL statements. Key is dbid
        self.ReSync = {}
    
        # Indexes to rebuild
        self.Reindex = []
    
        # constraints which are actually unenforcable
        self.Constraints = []
    
        # ownership fixups
        self.Owners = []
    
        # drop leaked temporary schemas
        self.Schemas = []
    
        # fix distribution policies
        self.Policies = []
        
        self.missingEntryStatus = None
        self.inconsistentEntryStatus = None
        self.foreignKeyStatus = None
        self.aclStatus = None


        # the following variables used for reporting purposes
        self.elapsedTime = 0
        self.totalTestRun = 0
        self.testStatus = True
        self.failedTest = []

GV = Global()



###############################
def usage(exitarg = None):
    print __doc__
    sys.exit(exitarg)


###############################

def getversion():
    versions = ["3.2", "3.3", "4.0", "4.1", "main"]
    db = connect()
    curs = db.query('''
    select regexp_replace(version(), 
       E'.*PostgreSQL [^ ]+ .Greenplum Database ([1-9]+.[0-9]+|main).*', 
       E'\\\\1') as ver;''')

    row = curs.getresult()[0]
    version = row[0]

    logger.debug('got version %s' % version)
    return version

###############################
def getalldbs():
    """
    get all connectable databases
    """
    db = connect()
    curs = db.query('''
    select datname from pg_database where datallowconn order by datname ''')
    row = curs.getresult()
    return row

###############################
def parseCommandLine():
    try:
        (options, args) = getopt.getopt(sys.argv[1:], '?p:P:U:B:vg:t:AOS:R:C:l')
    except Exception, e:
        usage('Error: ' + str(e))

    for (switch, val) in options:
        if switch == '-?':      usage(0)
        elif switch[1] in 'pBPUgSRC': GV.opt[switch] = val
        elif switch[1] in 'vtAOl':   GV.opt[switch] = True

    def setdef(x, v):
        if not GV.opt[x]:
            t = os.environ.get(v)
            GV.opt[x] = t
            if t:
                logger.debug('%s not specified; default to %s (from %s)' % 
                        (x, t, v))

    if GV.opt['-l']: return

    if GV.opt['-v']:
        enable_verbose_logging()

    setdef('-P', 'PGPASSWORD')
    setdef('-U', 'PGUSER')
    setdef('-U', 'USER')
    setdef('-p', 'PGPORT')
    if not GV.opt['-p']:
        usage('Please specify -p port')
    GV.opt['-p'] = parse_int(GV.opt['-p'])

    GV.opt['-h'] = 'localhost'
    logger.debug('Set default hostname to %s' % GV.opt['-h'])
    
    if GV.opt['-R']:
        logger.debug('Run this test: %s' % GV.opt['-R'])

    if GV.opt['-C']:
        GV.opt['-C'] = GV.opt['-C'].lower()
        logger.debug('Run cross consistency test for table: %s' % GV.opt['-C'])

    if (len(args) != 0 and len(args) != 1):
        usage('Too many arguments')

    if len(args) == 0:
        GV.dbname = os.environ.get('PGDATABASE') 
        if GV.dbname is None:
            GV.dbname = 'template1'
        logger.debug('database is %s' % GV.dbname)
    else:
        GV.dbname = args[0]
    
    GV.firstdb = GV.dbname
    GV.alldb.append(GV.firstdb)

    # build list of all connectable databases
    if GV.opt['-A']:
        alldb = getalldbs()
        GV.alldb.pop()
        for adbname in alldb:
            GV.alldb.append(adbname[0])

    if GV.opt['-S']:
        if not re.match("none|only", GV.opt['-S'], re.I):
            usage('Error: invalid value \'%s\' for shared table option. Legal values are (none, only)'% GV.opt['-S']);
        GV.opt['-S'] = GV.opt['-S'].lower()

    logger.debug('master at host %s, port %s, user %s, database %s' % 
           (GV.opt['-h'], GV.opt['-p'], GV.opt['-U'], GV.dbname))

    try:
        GV.opt['-B'] = int(GV.opt['-B'])
    except Exception, e:
        usage('Error: ' + str(e))

    if GV.opt['-B'] < 1:
        usage('Error: parallelism must be 1 or greater')

    logger.debug('degree of parallelism: %s' % GV.opt['-B'])
    
#############
def connect(user=None, password=None, host=None, port=None, 
            database=None, utilityMode=False):
    '''Connect to DB using parameters in GV'''
    options = utilityMode and '-c gp_session_role=utility' or None
    if not user: user = GV.opt['-U']
    if not password: password = GV.opt['-P']
    if not host: host = GV.opt['-h']
    if not port: port = GV.opt['-p']
    if not database: database = GV.dbname
    try:
        logger.debug('connecting to %s:%s %s' % (host, port, database))
        db = pg.connect(host=host, port=port, user=user,
                        passwd=password, dbname=database, opt=options)
    except pg.InternalError, ex:
        logger.fatal('could not connect to %s: "%s"' % 
            (database, str(ex).strip()))
        exit(1)
    
    logger.debug('connected with %s:%s %s' % (host, port, database))     
    return db

#############
def connect2(cfgrec, user=None, password=None, database=None, utilityMode=True):
    host = cfgrec['address']
    port = cfgrec['port']
    datadir = cfgrec['datadir']
    logger.debug('connect %s:%s:%s' % (host, port, datadir))
    if not database: database = GV.dbname
    if cfgrec['content'] == -1:
        utilityMode = False

    key = "%s.%s.%s.%s.%s.%s.%s" % (host, port, datadir, user, password, database,
                                 str(utilityMode))
    conns = GV.db.get(key)
    if conns:
        return conns[0]

    conn = connect(host=host, port=port, user=user, password=password, 
                   database=database, utilityMode=utilityMode)
    if conn:
        GV.db[key] = [conn, cfgrec]
    
    return conn

class execThread(Thread):
    def __init__(self, cfg, db, qry):
        self.cfg = cfg
        self.db = db
        self.qry = qry
        self.curs = None
        self.error = None
        Thread.__init__(self)

    def run(self):
        try:
            self.curs = self.db.query(self.qry)
        except BaseException, e:
            self.error = e
    

def processThread(threads):
    batch = []
    for th in threads:
        logger.debug('waiting on thread %s' % th.getName())
        th.join()
        if th.error:
            setError(ERROR_NOREPAIR)
            myprint("%s:%d:%s : %s" % 
                     (th.cfg['hostname'],
                      th.cfg['port'],
                      th.cfg['datadir'],
                      str(th.error)))
        else:
            batch.append([th.cfg, th.curs])
    return batch


#############
def connect2run(qry, col=None):
    logger.debug('%s' % qry)
        
    batch = []
    threads = []
    i = 1

    # parallelise queries
    for dbid in GV.cfg:
        c = GV.cfg[dbid]
        db = connect2(c)

        thread = execThread(c, db, qry)
        thread.start()
        logger.debug('launching query thread %s for dbid %i' % 
                (thread.getName(), dbid))
        threads.append(thread)

        # we don't want too much going on at once
        if (i % GV.opt['-B']) == 0:
            # process this batch of threads
            batch.extend(processThread(threads))
            threads = []

        i += 1

    # process the rest of threads
    batch.extend(processThread(threads))

    err = []
    for [cfg, curs] in batch:
        if col == None:
            col = curs.listfields()
        for row in curs.dictresult():
            err.append([cfg, col, row])

    return err

def formatErr(c, col, row):
    s = ('%s:%s:%s, content %s, dbid %s' % 
        (c['hostname'], c['port'], c['datadir'],
         c['content'], c['dbid']))
    for i in col:
        s = '%s, %s %s' % (s, i, row[i])
    return s

#############
def getGPConfiguration():
    cfg = {}
    db = connect()
    # note that in 4.0, sql commands cannot be run against the segment mirrors directly
    # so we filter out non-primary segment databases in the query
    qry = '''
          SELECT content, preferred_role = 'p' as definedprimary,
                 dbid, role = 'p' as isprimary, hostname, address, port, 
                 fselocation as datadir
            FROM gp_segment_configuration JOIN pg_filespace_entry on (dbid = fsedbid)
           WHERE fsefsoid = (select oid from pg_filespace where fsname='pg_system')
             AND (role = 'p' or content < 0 )
          '''
    curs = db.query(qry)
    for row in curs.dictresult():
        if row['content'] == -1 and row['isprimary'] != 't':
            continue    # skip standby master
        cfg[row['dbid']] = row
    db.close()
    return cfg

def checkDistribPolicy():
    logger.info('-----------------------------------')
    logger.info('Checking constraints on randomly distributed tables')
    qry = '''
    select n.nspname, rel.relname, pk.conname as constraint
    from   pg_constraint pk
      join pg_class rel on (pk.conrelid = rel.oid)
      join pg_namespace n on (rel.relnamespace = n.oid)
      join gp_distribution_policy d on (rel.oid = d.localoid)
    where pk.contype in('p', 'u') and d.attrnums is null
    '''

    db = connect2(GV.cfg[1])
    try:
        curs = db.query(qry)
        err = []
        for row in curs.dictresult():
            err.append([GV.cfg[1], ('nspname', 'relname', 'constraint'), row])

        if not err:
            logger.info('[OK] randomly distributed tables')
        else:
            GV.testStatus = False
            setError(ERROR_REMOVE)
            logger.info('[FAIL] randomly distributed tables')
            logger.error('pg_constraint has %d issue(s)' % len(err))
            logger.error(qry)
            for e in err: 
                logger.error(formatErr(e[0], e[1], e[2]))
            for e in err:
                cons = e[2]
                removeIndexConstraint(cons['nspname'], cons['relname'],
                                  cons['constraint'])
    except Exception, e:
        setError(ERROR_NOREPAIR)
        myprint('[ERROR] executing test: checkDistribPolicy')
        myprint('  Execution error: ' + str(e))


    logger.info('-----------------------------------')
    logger.info('Checking that unique constraints are only on distribution columns')

    # final part of the WHERE clause here is a little tricky: we want to make
    # sure that the set of distribution columns is a left subset of the
    # constraint. 
    qry = '''
    select  n.nspname, rel.relname, pk.conname as constraint
    from    pg_constraint pk
      join  pg_class rel on (pk.conrelid = rel.oid)
      join  pg_namespace n on (rel.relnamespace = n.oid)
      join  gp_distribution_policy d on (rel.oid = d.localoid)
    where pk.contype in ('p', 'u') and
          (d.attrnums is null or not 
           d.attrnums operator(pg_catalog.<@) pk.conkey)
    '''
    try:
        curs = db.query(qry)

        err = []
        for row in curs.dictresult():
            err.append([GV.cfg[1], ('nspname', 'relname', 'constraint'), row])

        if not err:
            logger.info('[OK] unique constraints')
        else:
            GV.testStatus = False
            setError(ERROR_REMOVE)
            logger.info('[FAIL] unique constraints')
            logger.error('pg_constraint has %d issue(s)' % len(err))
            logger.error(qry)
            for e in err: logger.error(formatErr(e[0], e[1], e[2]))
            for e in err:
                cons = e[2]
                removeIndexConstraint(cons['nspname'], cons['relname'],
                                  cons['constraint'])
    except Exception, e:
        setError(ERROR_NOREPAIR)
        myprint('[ERROR] executing test: checkDistribPolicy')
        myprint('  Execution error: ' + str(e))


#############
def checkPartitionIntegrity():
    #
    # MPP-8558: look for data in branch (not leaf) partitions
    #
    logger.info('-----------------------------------')
    logger.info('Checking pg_partition ...')
    err = []
    db = connect()
    qry = ''' 
    select distinct 
           quote_ident(n.nspname) || '.' || quote_ident(c.relname) as parname
    from   pg_partition_rule r1
      join pg_partition_rule r2 on (r1.oid = r2.parparentrule)
      join pg_class c on (r1.parchildrelid = c.oid)
      join pg_namespace n on (c.relnamespace = n.oid)
    where  r1.parchildrelid <> 0 and r2.parchildrelid <> 0
    '''
    try:
        curs = db.query(qry)
        for row in curs.dictresult():
            qy2 = ('select count(*) as cc from (select 1 from only %s limit(2)) q'
                   % (row['parname']))

            # logger.info(qy2)
            curs2 = db.query(qy2)
            for row2 in curs2.dictresult():
                if row2['cc'] == 0 :
                    continue
                err.append([row['parname']])

        if not err:
            logger.info('[OK] pg_partition branch integrity')
        else:
            GV.testStatus = False
            setError(ERROR_NOREPAIR)
            logger.info('[FAIL] pg_partition branch integrity')
            logger.error('pg_partition has %d issue(s)' % len(err))
            logger.error('Discovered row data in branch partitions')
            for e in err: 
               logger.error('  partition table name:  %s' % (e[0]))

    except Exception, e:
        setError(ERROR_NOREPAIR)
        myprint('[ERROR] executing test: checkPartitionIntegrity')
        myprint('  Execution error: ' + str(e))

    # MPP-9283: look for partitions create "with oids".
    qry = '''
    select n1.nspname, pc.relname, pc.oid
    from   pg_class pc, pg_partition_rule pr, pg_namespace n1
    where  pr.parchildrelid = pc.oid and pc.relnamespace = n1.oid and pc.relhasoids
    union
    select n1.nspname, pc.relname, pc.oid
    from   pg_class pc, pg_partition pp, pg_namespace n1
    where  pp.parrelid = pc.oid and pc.relnamespace = n1.oid and pc.relhasoids
    '''
    try:
        curs = db.query(qry)
        err = []
        for row in curs.dictresult():
            err.append([GV.cfg[1], ('nspname', 'relname', 'oid'), row])

        if not err:
            logger.info('[OK] partition with oids check')
        else:
            GV.testStatus = False
            setError(ERROR_NOREPAIR)
            logger.info('[FAIL] partition with oids check')
            logger.error('partition with oids check found %d issue(s)' % len(err))
            logger.error(qry)
            for e in err[0:100]: 
                row = e[2]
                logger.error(" table %s.%s oid %s" % 
                         (row['nspname'], row['relname'], row['oid']))
            if len(err) > 100:
                logger.error("...")
    except Exception, e:
        setError(ERROR_NOREPAIR)
        myprint('[ERROR] executing test: checkPartitionIntegrity')
        myprint('  Execution error: ' + str(e))

        # TODO: add repair script


    # MPP-11120: check for child partitions with different
    # distribution policies The complexity of this query is due to
    # having to account for the possibility of partitions with "holes"
    # which would make similar distribution policies appear different
    # in gp_distribution_policy.  This is handled by unnesting both
    # distribution
    qry = '''
    select
      parrelid, 
      parchildrelid, 
      d1.attrnums as parpolicy, 
      d2.attrnums as parchildpolicy
    from
      (
        select distinct
          coalesce(p1.parrelid, p2.parrelid)::regclass as parrelid,
          coalesce(p1.parchildrelid, p2.parchildrelid)::regclass as parchildrelid
        from
          (
            select parrelid, parchildrelid, g1.attname, g1.index
            from   pg_partition_rule pr 
                   join pg_partition p on (pr.paroid = p.oid)
                   join (
                     select localoid, attname, index
                     from (
                       select
                         localoid,
                         unnest(attrnums) as offset,
                         generate_series(1, array_upper(attrnums, 1)) as index
                       from
                         gp_distribution_policy
                      ) d
                      join pg_attribute a on (a.attrelid = d.localoid and a.attnum = d.offset)
                   ) g1 on (parrelid = g1.localoid)
            where  parchildrelid != 0
          ) p1
          full outer join
          (
            select parrelid, parchildrelid, g2.attname, g2.index
            from   pg_partition_rule pr 
                   join pg_partition p on (pr.paroid = p.oid)
                   join (
                     select localoid, attname, index
                     from (
                       select
                         localoid,
                         unnest(attrnums) as offset,
                         generate_series(1, array_upper(attrnums, 1)) as index
                       from
                         gp_distribution_policy
                      ) d
                      join pg_attribute a on (a.attrelid = d.localoid and a.attnum = d.offset)
                   ) g2 on (parchildrelid = g2.localoid)
            where  parchildrelid != 0
          ) p2
          on (p1.parrelid = p2.parrelid and
              p1.parchildrelid = p2.parchildrelid and
              p1.index = p2.index)
        where p1.attname is distinct from p2.attname
      ) p
    join gp_distribution_policy d1 on (d1.localoid = p.parrelid)
    join gp_distribution_policy d2 on (d2.localoid = p.parchildrelid)
    where d2.attrnums is not null
    '''
    try:
        curs = db.query(qry)
        cols = ('parrelid', 'parchildrelid', 'parpolicy', 'parchildpolicy')

        err = []
        for row in curs.dictresult():
            err.append([GV.cfg[1], cols, row])

        if not err:
            logger.info('[OK] partition distribution policy check')
        else:
            GV.testStatus = False
            setError(ERROR_REMOVE)
            logger.info('[FAIL] partition distribution policy check')
            logger.error('partition distribution policy check found %d issue(s)' % len(err))
            if len(err) > 100:
                logger.error(qry)

            count = 0
            for e in err:
                cfg = e[0]
                col = e[1]
                row = e[2]

                # generate repair script for this row
                distributeRandomly(row['parchildrelid'])

                # report at most 100 rows, for brevity
                if count == 100:
                    logger.error("...")
                    count += 1
                if count > 100:
                    continue

                if count == 0:
                    logger.error("--------")
                    logger.error("  " + " | ".join(map(str, col)))
                    logger.error("  " + "-+-".join(['-'*len(x) for x in col]))

            
                logger.error("  " + " | ".join([str(row[x]) for x in col]))
                count += 1

    except Exception, e:
        setError(ERROR_NOREPAIR)
        myprint('[ERROR] executing test: checkPartitionIntegrity')
        myprint('  Execution error: ' + str(e))


    db.close()

#############
# A dictionary of SQL statements for checkPartitionRegularity()

partitionRegularityChecks = {
    # Query: irreg_user_constraint
    # 
    #     A row represents an irregular user-defined constraint.
    # 
    #     This view just filters ptable_user_con_info so that it returns no rows
    #     if no irregular user-defined constraints exist.
    #     
    #     An irregular user-constraint is a constraint whose definition (DDL expression
    #     format) appears on the root table of a partitioned table, and doesn't appear
    #     on every part table of the partitioned table.  It is possible to construct
    #     these using sequences of DDL operations on release prior to Rio.  In Rio,
    #     it is possible to construct them with FOREIGN KEY constraints, but not with
    #     other constraint types.
    # 
    # tableid:  pg_class.oid of the partitioned table
    # conname:  name of the constraint on the partitioned table
    # contype:  type of constraint (same on part and table)
    # condef:  specification of constraint (same on part and table)
    # numexpected:  number of constraint occurrences expected (incl table)
    # numactual:  number of constraint occurrences observed (incl table)
    'irreg_user_constraint' :
    """select 
	    tableid,
	    tableconname,
	    contype,
	    condef,
	    numexpected,
	    numactual
	from
	    (
			select 
				c.tableid, 
				c.tableconname, 
				c.contype, 
				c.condef, 
				i.tableparts + 1, 
				count(c.partid), 
				count(distinct c.partconname) 
			from 
				(
					select
						u.tableid,
						u.conname, 
						u.contype,
						u.condef, 
						p.partid, 
						p.conid,
						coalesce(p.conname) 
					from
						(
							select
								p.tableid,
								c.conname,
								c.contype,
								pg_get_constraintdef(c.oid) as condef
							from 
								(
									select 
										parrelid::regclass,
										max(parlevel)+1
									from
										pg_partition
									group by parrelid
								) as p(tableid, tabledepth) ,
								pg_constraint c
							where
								p.tableid = c.conrelid
						) as u(tableid, conname, contype, condef) 
							join
						(
							select 
								x.tableid::regclass as tableid,
								c.conrelid::regclass as partid,
								c.oid as conid,
								c.conname,
								c.contype,
								pg_get_constraintdef(c.oid) as condef
							from 
								pg_constraint c,
								(
									select 
										tableid,  
										tabledepth,
										tableid::regclass partid, 
										0 as partdepth, 
										0 as partordinal,
										'r'::char as partstatus
									from 
										(
											select 
												parrelid::regclass,
												max(parlevel)+1
											from
												pg_partition
											group by parrelid
										) as ptable(tableid, tabledepth) 
									union all
									select 
										parrelid::regclass as tableid,  
										t.tabledepth as tabledepth,
										r.parchildrelid::regclass partid, 
										p.parlevel + 1 as partdepth, 
										r.parruleord as partordinal,
										case
											when t.tabledepth = p.parlevel + 1 then 'l'::char
											else 'i'::char
										end as partstatus
									from 
										pg_partition p, 
										pg_partition_rule r,
										 (
											select 
												parrelid::regclass,
												max(parlevel)+1
											from
												pg_partition
											group by parrelid
										) as t(tableid, tabledepth) 
									where 
										p.oid = r.paroid
										and not p.paristemplate
										and p.parrelid = t.tableid
								) as x(tableid, tabledepth, partid, partdepth, partordinal, partstatus) 
							where
								x.partid = c.conrelid
						) as p(tableid, partid, conid, conname, contype, condef) 
							on (
								u.tableid = p.tableid and
								u.contype = p.contype and
								u.condef = p.condef
								)
				) as c(tableid, tableconname, contype, condef, partid, partconid, partconname) ,
				(
					select
						t.tableid,
						t.tabledepth,
						n.nparts as tableparts,
						r.nspname,
						r.relname
					from
						(
							select 
								parrelid::regclass,
								max(parlevel)+1
							from
								pg_partition
							group by parrelid
						) as t(tableid, tabledepth) ,
						(
							select 
								c.oid::regclass as relid,
								n.nspname,
								c.relname, 
								c.relkind
							from
								pg_class c,
								pg_namespace n
							where
								c.relnamespace = n.oid
						) as r(relid, nspname, relname, relkind) ,
						(
							select tableid, count(*) 
							from (
									select 
										t.tableid::regclass,
										p.parchildrelid::regclass as partid
									from 
										( 
											select pg_partition.parrelid, pg_partition.oid
											from pg_partition
											where not pg_partition.paristemplate
										) t(tableid, partid), 
										pg_partition_rule p
									where p.paroid = t.partid
								) as contains_part(tableid, partid)  
							group by tableid
						) n(tableid, nparts)
					where 
						t.tableid = r.relid and
						t.tableid = n.tableid 
				) as i(tableid, tabledepth, tableparts, nspname, relname) 
			where
				c.tableid = i.tableid
			group by 
				c.tableid, 
				c.tableconname, 
				c.contype, 
				c.condef,
				i.tableparts
		) as ptable_user_con_info(tableid, tableconname, contype, condef, numexpected, numactual, numnames) 
	where
	    contype != 'f' and -- no FK consistency in Rio
	    numexpected != numactual""",
    
    # Query: irreg_sys_constraint
    # 
    #     A row represents an irregular system-defined constraint.
    # 
    #     An irregular system constraint is a constraint whose definition (DDL
    #     expression format) appears on some part tables and that is not a system-
    #     defined partition constraint.
    #     
    #     This view doesn't actually test this.  Instead, it checks for an
    #     expected pattern of system-defined constraints.
    #     1. The constraints checked are those that don't appear on the root.
    #     2. Each part has as many constraints as its depth in the partition
    #        less any default parts on its path.
    #     Violators are listed as results.
    # 
    # tableid:  pg_class.oid of the partitioned table
    # partid:  pg_class.oid of the (constrained) part table
    # expected:  number of constraint occurrences expected
    # actual:  number of constraint occurrences observed
    'irreg_sys_constraint' :
    """select 
		coalesce(x.partid, a.partid) as partid,
		x.tableid, 
		x.expected, 
		coalesce(a.actual, 0) as actual                                                                                                                                                                                                                                                                                                                                             
	from
		(
		{expected}
		) x
		  full join 
		(
		{actual}
		) a                                                                                                                                                                                                                                                                                                                                      
		  on (x.partid = a.partid) 
	where 
		x.expected != a.actual or 
		x.expected is null or
		x.expected != coalesce(a.actual,0);""",
        
    
    # Query based on view: unenforced_constraint_info
    # 
    #     a row represents an unenforced unique constraint to be fixed.
    # 
    # tableid
    # partid
    # indexid
    # partoid
    # indexoid
    # contype
    # conname
    # refobjid
    
    'unenforced_constraint_info' :
    """select
        c.tableid,
        c.partid,
        b.indexid,
        c.partid::int as partoid,
        b.indexid::int as indexoid,
        b.contype,
        b.conname,
        b.refobjid
    from 
        (
            select
                k.tableid,
                k.distkey,
                k.partkey,
                c.conid,
                c.conname,
                c.contype,
                i.indrelid::regclass,
                i.indkey::smallint[]
            from 
                pg_index i, 
                (
                    select 
                        k.tableid, 
                        d.attrcnt,
                        d.attrnums,
                        sum(k.partkeylen),
                        array_agg(k.partkey[g.g])  
                    from 
                        (
                            select
                                p.parrelid::regclass,
                                t.tabledepth,
                                p.parlevel,
                                p.parnatts,
                                p.paratts
                            from 
                                pg_partition p,
                                (
                                    select 
                                        parrelid::regclass,
                                        max(parlevel)+1
                                    from
                                        pg_partition
                                    group by parrelid
                                ) as t(tableid, tabledepth) 
                            where 
                                p.parrelid = t.tableid and
                                p.paristemplate is false
                        ) as k(tableid, tabledepth, partdepth, partkeylen, partkey) , 
                        generate_series(0, (select max(partkeylen) from (
                            select
                                p.parrelid::regclass,
                                t.tabledepth,
                                p.parlevel,
                                p.parnatts,
                                p.paratts
                            from 
                                pg_partition p,
                                (
                                    select 
                                        parrelid::regclass,
                                        max(parlevel)+1
                                    from
                                        pg_partition
                                    group by parrelid
                                ) as t(tableid, tabledepth) 
                            where 
                                p.parrelid = t.tableid and
                                p.paristemplate is false
                        ) as partition_level(tableid, tabledepth, partdepth, partkeylen, partkey) )-1) g(g),
                        (
                            select 
                                localoid::regclass, 
                                attrnums,
                                coalesce(1+array_upper(attrnums,1)-array_lower(attrnums,1),0)
                            from 
                                gp_distribution_policy
                        ) as d(relid, attrnums, attrcnt) 
                    where 
                        g.g < k.partkeylen and
                        k.tableid = d.relid
                    group by 
                        k.tableid,
                        d.attrcnt,
                        d.attrnums 
                ) as k(tableid, distkeylen, distkey, partkeylen, partkey) ,
                (
                    select
                        relid,
                        conid,
                        conname,
                        contype,
                        indexid        
                    from 
                        (
                            select  
                                r.oid::regclass as relid, 
                                c.oid as conid,
                                c.conname,
                                c.contype,
                                c.consrc,
                                pg_get_constraintdef(c.oid) as condef,
                                d.objid::regclass as indexid
                            from 
                                (
                                    pg_class r
                                        join
                                        pg_constraint c
                                        on 
                                            r.oid = c.conrelid
                                            and r.relkind = 'r'
                                )
                                    left join
                                    pg_depend d
                                    on 
                                        d.refobjid = c.oid
                                        and d.classid = 'pg_class'::regclass
                                        and d.refclassid = 'pg_constraint'::regclass
                                        and d.deptype = 'i'
                            ) as relconstraint(relid, conid, conname, contype, consrc, condef, indexid) 
                    where 
                        indexid is not null
                        or contype in ('p', 'u') 
                ) as c(relid, conid, conname, contype, indexid) 
            where 
                c.relid = k.tableid and
                i.indrelid = k.tableid and
                i.indexrelid = c.indexid and 
                not i.indkey::smallint[] @> array_cat(k.distkey, k.partkey)
        ) as x(tableid, distkey, partkey, conid, conname, contype, indrelid, indkey) , 
        (
            select 
                tableid,  
                tabledepth,
                tableid::regclass partid, 
                0 as partdepth, 
                0 as partordinal,
                'r'::char as partstatus
            from 
                (
                    select 
                        parrelid::regclass,
                        max(parlevel)+1
                    from
                        pg_partition
                    group by parrelid
                ) as ptable(tableid, tabledepth) 
            union all
            select 
                parrelid::regclass as tableid,  
                t.tabledepth as tabledepth,
                r.parchildrelid::regclass partid, 
                p.parlevel + 1 as partdepth, 
                r.parruleord as partordinal,
                case
                    when t.tabledepth = p.parlevel + 1 then 'l'::char
                    else 'i'::char
                end as partstatus
            from 
                pg_partition p, 
                pg_partition_rule r,
                 (
                    select 
                        parrelid::regclass,
                        max(parlevel)+1
                    from
                        pg_partition
                    group by parrelid
                ) as t(tableid, tabledepth) 
            where 
                p.oid = r.paroid
                and not p.paristemplate
                and p.parrelid = t.tableid
        ) as c(tableid, tabledepth, partid, partdepth, partordinal, partstatus) ,
        (
            select
                r.oid::regclass as relid,
                i.oid::regclass as indexid,
                c.oid as conid,
                c.contype,
                c.conname,
                pg_get_constraintdef(c.oid) as condef,
                d.classid,
                d.objid,
                d.objsubid,
                d.refclassid,
                d.refobjid,
                d.refobjsubid,
                d.deptype
            from 
                pg_constraint c,
                pg_class i, 
                pg_depend d,
                pg_index x, 
                pg_class r
            where
                d.classid = 'pg_class'::regclass and
                d.objid = i.oid and
                d.objsubid = 0 and
                d.refclassid = 'pg_constraint'::regclass and
                d.refobjid = c.oid and
                d.refobjsubid = 0 and
                d.deptype = 'i' and
                i.relkind = 'i' and
                i.oid = x.indexrelid and
                r.oid = x.indrelid
        ) as b(relid, indexid, conid, contype, conname, condef, classid, objid, objsubid, refclassid, refobjid, refobjsubid, deptype)  
    where 
        x.tableid = c.tableid and
        c.partid = b.relid and
        b.classid = 'pg_class'::regclass and
        b.objsubid = 0 and
        b.refclassid = 'pg_constraint'::regclass and
        b.refobjsubid = 0 and
        b.deptype = 'i'""",
        
        # Repair sequence for issues identified by unenforced_constraint_info.
        # Must substitute values from a row of that query, before running.
        
        'unenforced_constraint_repairs' :
        """--Demote type-{contype} constraint {conname} on part {partid}
--of partitioned table {tableid} to simple unique index.

--Disconnect index {indexid} from constraint {conname} 
delete
from 
    pg_depend
where
    (classid, objid, objsubid, refclassid, refobjid, refobjsubid, deptype) =
    (
        select  
            d.classid,
            d.objid,
            d.objsubid,
            d.refclassid,
            d.refobjid,
            d.refobjsubid,
            d.deptype
        from 
            pg_index i,
            pg_depend d
        where 
            i.indexrelid = {indexoid} and
            d.classid = 'pg_class'::regclass and 
            d.objid = i.indexrelid and 
            d.objsubid = 0 and 
            d.refclassid = 'pg_constraint'::regclass and 
            d.refobjid = (
                select oid
                from pg_constraint
                where
                   conrelid = {partoid} and
                   conname = {quoted_conname} and
                   contypid = 0 and
                   contype = {quoted_contype}
            ) and
            d.refobjsubid = 0 and 
            d.deptype = 'i'
    );
--Replace dependency of constraint {conname} on table columns of {partid}
--with dependency of index {indexoid} on same.
update 
    pg_depend
set
    classid = 'pg_class'::regclass,
    objid = {indexoid}
where
    classid = 'pg_constraint'::regclass and
    objid = (
             select oid
               from pg_constraint
              where
                    conrelid = {partoid} and
                    conname = {quoted_conname} and
                    contypid = 0 and
                    contype = {quoted_contype}
         ) and
    objsubid = 0 and
    refclassid = 'pg_class'::regclass and
    refobjid = {partoid} and
    refobjsubid <> 0 and
    deptype = 'a';
--Delete constraint {conname} leaving its index {indexid}
delete 
from
    pg_constraint
where 
    conrelid = {partoid} and
    conname = {quoted_conname} and
    contypid = 0 and
    contype = {quoted_contype};""",
    
    # Query: fix_ill_named_constraint
    # 
    #     a row represents the data for a fixup of an ill-named constraint
    # 
    # tableid:  pg_class.oid of the partitioned table as regclass
    # tableconname:  pg_constraint.conname on the partitioned table
    # partid:  pg_class.oid of the part table as regclass
    # partrelid:  pg_class.oid of the part table as int
    # partconname:  pg_constraint.conname on the part or partitioned table

    'fix_ill_named_constraint' :
    """select 
        tableid, 
        tableconname, 
        partid, 
        partid::int as partrelid, 
        partconname
    from (
			select
				u.tableid,
				u.conname, 
				u.contype,
				u.condef, 
				p.partid, 
				p.conid,
				coalesce(p.conname) 
			from
				(
					select
						p.tableid,
						c.conname,
						c.contype,
						pg_get_constraintdef(c.oid) as condef
					from 
						(
							select 
								parrelid::regclass,
								max(parlevel)+1
							from
								pg_partition
							group by parrelid
						) as p(tableid, tabledepth) ,
						pg_constraint c
					where
						p.tableid = c.conrelid
				) as u(tableid, conname, contype, condef) 
					join
				(
					select 
						x.tableid::regclass as tableid,
						c.conrelid::regclass as partid,
						c.oid as conid,
						c.conname,
						c.contype,
						pg_get_constraintdef(c.oid) as condef
					from 
						pg_constraint c,
						(
							select 
								tableid,  
								tabledepth,
								tableid::regclass partid, 
								0 as partdepth, 
								0 as partordinal,
								'r'::char as partstatus
							from 
								(
									select 
										parrelid::regclass,
										max(parlevel)+1
									from
										pg_partition
									group by parrelid
								) as ptable(tableid, tabledepth) 
							union all
							select 
								parrelid::regclass as tableid,  
								t.tabledepth as tabledepth,
								r.parchildrelid::regclass partid, 
								p.parlevel + 1 as partdepth, 
								r.parruleord as partordinal,
								case
									when t.tabledepth = p.parlevel + 1 then 'l'::char
									else 'i'::char
								end as partstatus
							from 
								pg_partition p, 
								pg_partition_rule r,
								 (
									select 
										parrelid::regclass,
										max(parlevel)+1
									from
										pg_partition
									group by parrelid
								) as t(tableid, tabledepth) 
							where 
								p.oid = r.paroid
								and not p.paristemplate
								and p.parrelid = t.tableid
						) as x(tableid, tabledepth, partid, partdepth, partordinal, partstatus) 
					where
						x.partid = c.conrelid
				) as p(tableid, partid, conid, conname, contype, condef) 
					on (
						u.tableid = p.tableid and
						u.contype = p.contype and
						u.condef = p.condef
						)
		) as part_user_constraint(tableid, tableconname, contype, condef, partid, partconid, partconname) 
    where partconname != tableconname""",
    
    # Query based on view: part_sys_actual
	# tableid
	# partid
	# actual observed number of system-constraints

    "actual_part_con_query" :
    """select 
		tableid, 
		partid, 
		count(*) as actual  
	from (
			select 
				tableid,
				partid,
				conid,
				conname,
				contype,
				condef 
			from (
					select 
						x.tableid::regclass as tableid,
						c.conrelid::regclass as partid,
						c.oid as conid,
						c.conname,
						c.contype,
						pg_get_constraintdef(c.oid) as condef
					from 
						pg_constraint c,
						(
							select 
								tableid,  
								tabledepth,
								tableid::regclass partid, 
								0 as partdepth, 
								0 as partordinal,
								'r'::char as partstatus
							from 
								(
									select 
										parrelid::regclass,
										max(parlevel)+1
									from
										pg_partition
									group by parrelid
								) as ptable(tableid, tabledepth) 
							union all
							select 
								parrelid::regclass as tableid,  
								t.tabledepth as tabledepth,
								r.parchildrelid::regclass partid, 
								p.parlevel + 1 as partdepth, 
								r.parruleord as partordinal,
								case
									when t.tabledepth = p.parlevel + 1 then 'l'::char
									else 'i'::char
								end as partstatus
							from 
								pg_partition p, 
								pg_partition_rule r,
								 (
									select 
										parrelid::regclass,
										max(parlevel)+1
									from
										pg_partition
									group by parrelid
								) as t(tableid, tabledepth) 
							where 
								p.oid = r.paroid
								and not p.paristemplate
								and p.parrelid = t.tableid
						) as x(tableid, tabledepth, partid, partdepth, partordinal, partstatus) 
					where
						x.partid = c.conrelid
				) as part_constraint(tableid, partid, conid, conname, contype, condef)  
			where 
				(partid, condef) not in 
					(
						select partid, condef 
						from (
							select
								u.tableid,
								u.conname, 
								u.contype,
								u.condef, 
								p.partid, 
								p.conid,
								coalesce(p.conname) 
							from
								(
									select
										p.tableid,
										c.conname,
										c.contype,
										pg_get_constraintdef(c.oid) as condef
									from 
										(
											select 
												parrelid::regclass,
												max(parlevel)+1
											from
												pg_partition
											group by parrelid
										) as p(tableid, tabledepth) ,
										pg_constraint c
									where
										p.tableid = c.conrelid
								) as u(tableid, conname, contype, condef) 
									join
								(
									select 
										x.tableid::regclass as tableid,
										c.conrelid::regclass as partid,
										c.oid as conid,
										c.conname,
										c.contype,
										pg_get_constraintdef(c.oid) as condef
									from 
										pg_constraint c,
										(
											select 
												tableid,  
												tabledepth,
												tableid::regclass partid, 
												0 as partdepth, 
												0 as partordinal,
												'r'::char as partstatus
											from 
												(
													select 
														parrelid::regclass,
														max(parlevel)+1
													from
														pg_partition
													group by parrelid
												) as ptable(tableid, tabledepth) 
											union all
											select 
												parrelid::regclass as tableid,  
												t.tabledepth as tabledepth,
												r.parchildrelid::regclass partid, 
												p.parlevel + 1 as partdepth, 
												r.parruleord as partordinal,
												case
													when t.tabledepth = p.parlevel + 1 then 'l'::char
													else 'i'::char
												end as partstatus
											from 
												pg_partition p, 
												pg_partition_rule r,
												 (
													select 
														parrelid::regclass,
														max(parlevel)+1
													from
														pg_partition
													group by parrelid
												) as t(tableid, tabledepth) 
											where 
												p.oid = r.paroid
												and not p.paristemplate
												and p.parrelid = t.tableid
										) as x(tableid, tabledepth, partid, partdepth, partordinal, partstatus) 
									where
										x.partid = c.conrelid
								) as p(tableid, partid, conid, conname, contype, condef) 
									on (
										u.tableid = p.tableid and
										u.contype = p.contype and
										u.condef = p.condef
										)
						) as part_user_constraint(tableid, tableconname, contype, condef, partid, partconid, partconname) 
					)  
		) as part_sys_constraint(tableid, partid, conid, conname, contype, condef)  
	group by tableid, partid""",
	
	# Query contains_directly has a row per step along a path from
	# root to leaf.  The columns are
	# tableid - pg_class.oid of the partitioned table.
	# parentid - pg_class.oid of the "from" table.
	# childid - pg_class.oid of the "to" table, the target of the step.
	# npcon - constraint count for this step: 0 if "to" is default, else 1.
	#    
	 
	'contains_directly' :
	"""(
		select
			r.parrelid::regclass as tableid,
			coalesce(p.parchildrelid, r.parrelid)::regclass as parentid,
			c.parchildrelid::regclass as childid,
			case when c.parisdefault then 0 else 1 end as npcon
		from
			pg_partition r,
			pg_partition_rule c
				left join pg_partition_rule p on (c.parparentrule = p.oid)
		where
			not r.paristemplate and
			not c.parchildrelid = 0 and
			c.paroid = r.oid 
		) {alias}""",
	
	# The base case is the length 1 path from root or branch to branch 
	# or leaf. This is always the first union term.
	
	'base_query' :
	"""select
		start.tableid,
		start.parentid,
		start.childid,
		start.npcon
	from 
		{contains_directly_start}""",
	
	# A union term is an N-way self join of contains_directly and
	# identifies paths of length N.  Note that the length of a path
	# to a part at depth N+1 is N. 
	 
	'union_term' :
	"""select
		start.tableid,
		start.parentid,
		stop.childid,
		start.npcon -- stop.npcon
	from
		{contains_directly_start},
		{contains_directly_stop}{intermediate_path_from}
	where
		start.childid {intermediate_path_where}
		= stop.parentid""",
	
	#
	
	'union_query' :
	"""select tableid, childid as partid, sum(npcon) as expected
	from (
		{open_union}
		) r
	group by tableid, childid"""

    }

#############

# For partitionRegularityChecks.
def make_union_term(depth):
    assert depth > 0

    union_term = partitionRegularityChecks['union_term']
    contains_directly = partitionRegularityChecks['contains_directly']
    
    path_from = []
    path_where = []
    
    if depth > 1: # for later .join()
        path_from.append('')
        path_where.append('')
    
    for i in range(1, depth):
        path_alias = "path%d" % i
        path_from.append(contains_directly.format(alias = path_alias))
        path_where.append("    = %s.parentid and %s.childid" 
            % (path_alias, path_alias) )
    
    return union_term.format(
        contains_directly_start = contains_directly.format(alias = 'start'),
        contains_directly_stop = contains_directly.format(alias = 'stop'),
        intermediate_path_from = ",\n    ".join(path_from),
        intermediate_path_where = "\n".join(path_where)
        )
    
# For partitionRegularityChecks.
def expected_part_con_query(maxdepth):
    cds = partitionRegularityChecks['contains_directly'].format(alias = 'start')
    base_query = partitionRegularityChecks['base_query']
    terms = [base_query.format(contains_directly_start=cds)]
    
    for depth in range(1, maxdepth+1):
        terms.append(make_union_term(depth))
    
    return partitionRegularityChecks['union_query'].format(
        open_union = '\n\nunion all\n\n'.join(terms))

# For partitionRegularityChecks.
def make_irregular_sys_con_query(maxdepth):
    expected = expected_part_con_query(maxdepth)
    actual = partitionRegularityChecks['actual_part_con_query']
    qry = partitionRegularityChecks['irreg_sys_constraint']
    return qry.format(expected = expected, actual = actual)


#############
def checkPartitionRegularity():
    #
    # Rio partitioning changes introduce new regularity requirements for constraints
    # on partitioned tables.  These are the checks.
    #
    okayToRun = GV.missingEntryStatus and GV.inconsistentEntryStatus and GV.foreignKeyStatus
    irregular = False

    logger.info('-----------------------------------')
    logger.info('Checking pg_partition/pg_constraint regularity ...')
    
    if not okayToRun:
        logger.warn('unable to run pg_partition/pg_constraint regularity checks')
        logger.warn('prerequisite tests failed or not run')
        return
    
    db = connect()

    testname = 'user-defined constraint regularity on partitioned tables'
    
    qry = partitionRegularityChecks['irreg_user_constraint']    
    err = []

    try:
        curs = db.query(qry)
    
        for row in curs.dictresult():
            err.append( (row['tableconname'], row['tableid'], row['numactual'], row['numexpected']) )

        if not err:
            logger.info('[OK]  %s' % testname)
        else:
            irregular = True
            GV.testStatus = False
            setError(ERROR_NOREPAIR)
            logger.info('[FAIL]  %s' % testname)
            logger.error(' %s test has %d issue(s)' % (testname, len(err)) )
            efmt = '  Constraint "%s" of partitioned table "%s" occurs %d times, %d expected.'
            for e in err: 
                logger.error(efmt % e)

    except Exception, e:
        setError(ERROR_NOREPAIR)
        myprint('[ERROR] executing test: %s' % testname)
        myprint('  Execution error: ' + str(e))

    testname = 'system-defined partition constraint regularity on partitioned tables'
    
    # Determine maximum number of partitioning levels in this database
    try:
        qry = """select max(parlevel)+1 as maxdepth from pg_partition;"""
        curs = db.query(qry)
        assert len(curs.dictresult()) == 1 # scalar aggregation!
        maxdepth = curs.dictresult()[0]['maxdepth']
        
        err = []
        if isinstance(maxdepth, int):
            qry = make_irregular_sys_con_query(maxdepth)
            curs = db.query(qry)
            for row in curs.dictresult():
                err.append( (row['partid'], row['tableid'], row['actual'], row['expected']) )

        if not err:
            logger.info('[OK]  %s' % testname)
        else:
            irregular = True
            GV.testStatus = False
            setError(ERROR_NOREPAIR)
            logger.info('[FAIL]  %s' % testname)
            logger.error(' %s test has %d issue(s)' % ( testname, len(err)) )
            efmt = '  Part table "%s" of partitioned table "%s" has %d system-defined constraints, %d expected.'
            for e in err:
                logger.error(efmt % e)

    except Exception, e:
        setError(ERROR_NOREPAIR)
        myprint('[ERROR] executing test: %s' % testname)
        myprint('  Execution error: ' + str(e))

    testname = 'unenforced unique constraints on partitioned tables'
    
    if irregular:
        logger.warn('skipping test %s due to constraint irregularities' % testname)
    elif GV.Remove:
        logger.warn('skipping test %s due to required removals' % testname)
    else:
        # logger.info('Checking %s ...' % testname)

        qry = partitionRegularityChecks['unenforced_constraint_info']
        err = []
        try:
            curs = db.query(qry)
            for row in curs.dictresult():
                row['con_type_phrase'] = 'primary key' if row['contype'] == 'p' else 'unique'
                row['quoted_conname'] = quote_value(row['conname'])
                row['quoted_contype'] = quote_value(row['contype'])
                err.append(row)
   
            if not err:
                logger.info('[OK]  %s' % testname)
            else:
                GV.testStatus = False
                setError(ERROR_REMOVE)
                logger.info('[FAIL]  %s' % testname)
                logger.error(' %s test has %d issue(s)' % ( testname, len(err) ) )
                efmt = '  partitioned table "{tableid}" has unenforced {con_type_phrase} constraint: "{partid}"'
                repair_fmt = partitionRegularityChecks['unenforced_constraint_repairs']
                n = 0
                for e in err:
                    n = n+1
                    if n <= 100:
                        logger.error(efmt.format(**e))
                    repair_sequence = repair_fmt.format(**e)
                    for dbid in GV.cfg:
                        addDemoteConstraint(dbid, repair_sequence)
                    if len(err) > 100:
                        logger.error("...")

        except Exception, e:
            setError(ERROR_NOREPAIR)
            myprint('[ERROR] executing test: %s' % testname)
            myprint('  Execution error: ' + str(e))
          

    testname = 'inconsistently named constraint in partitioned table'
    
    if irregular:
        logger.warn('skipping test %s due to constraint irregularities' % testname)
    elif GV.Remove:
        logger.warn('skipping test %s due to required removals' % testname)
    elif GV.DemoteConstraint:
        logger.warn('skipping test %s due to unenforced constraint removals' % testname)
    else:
        # logger.info('Checking %s ...' % testname)
        
        qry = partitionRegularityChecks['fix_ill_named_constraint']    
        err = []
        try:
            curs = db.query(qry)
            for row in curs.dictresult():
                err.append( row ) 
    
            if not err:
                logger.info('[OK]  %s' % testname)
            else:
                GV.testStatus = False
                setError(ERROR_REMOVE)
                logger.info('[FAIL]  %s' % testname)
                logger.error(' %s test has %d issue(s)' % ( testname, len(err) ) )
                efmt = '  part table "%s" has constraint named "%s"; should be "%s"'
                n = 0
                for e in err:
                    n = n+1
                    if n <= 100:
                        # part name, wrong constraint name, right constraint name
                       logger.error(efmt % (e['partid'], e['partconname'], e['tableconname']))
                    for dbid in GV.cfg:
                        buildAdjustConname(
					     	dbid, e['tableid'], int(e['partrelid']), 
		    				quote_value(e['partconname']), 
			    			quote_value(e['tableconname']) )
                if len(err) > 100:
                    logger.error("...")

        except Exception, e:
            setError(ERROR_NOREPAIR)
            myprint('[ERROR] executing test: %s' % testname)
            myprint('  Execution error: ' + str(e))

    db.close()

#############
def checkPGClass():
    logger.info('-----------------------------------')
    logger.info('Checking pg_class ...')
    qry = '''
    SELECT relname, relkind, tc.oid as oid,
           reltoastrelid, reltoastidxid 
    FROM   pg_class tc left outer join 
           pg_attribute ta on (tc.oid = ta.attrelid)
    WHERE  ta.attrelid is NULL
    '''
    err = connect2run(qry, ('relname', 'relkind', 'oid'))
    if not err:
        logger.info('[OK] pg_class')
    else:
        GV.testStatus = False
        setError(ERROR_NOREPAIR)
        logger.info('[FAIL] pg_class')
        logger.error('pg_class has %d issue(s)' % len(err))
        logger.error(qry)
        for e in err[0:100]: 
            logger.error(formatErr(e[0], e[1], e[2]))
        if len(err) > 100:
            logger.error("...")


#############
def checkPGNamespace():
    logger.info('-----------------------------------')
    logger.info('Checking for leaked temporary schemas')
    db = connect2(GV.cfg[1], utilityMode=False)
    
    # The simpler form of this query that pushed the union into the
    # inner select does not run correctly on 3.2.x
    qry = '''
    SELECT distinct nspname as schema
    FROM (
      SELECT nspname, replace(nspname, 'pg_temp_','')::int as sess_id
      FROM   gp_dist_random('pg_namespace')
      WHERE  nspname ~ '^pg_temp_[0-9]+'
    ) n LEFT OUTER JOIN pg_stat_activity x using (sess_id)
    WHERE x.sess_id is null
    UNION
    SELECT nspname as schema
    FROM (
      SELECT nspname, replace(nspname, 'pg_temp_','')::int as sess_id
      FROM   pg_namespace
      WHERE  nspname ~ '^pg_temp_[0-9]+'
    ) n LEFT OUTER JOIN pg_stat_activity x using (sess_id)
    WHERE x.sess_id is null
    '''
    try:
        curs = db.query(qry)
        if curs.ntuples() == 0:
            logger.info('[OK] temporary schemas')
        else: 
            GV.testStatus = False
            setError(ERROR_REMOVE)
            logger.info('[FAIL] temporary schemas')
            logger.error('found %d unbound temporary schemas' % curs.ntuples())
            for row in curs.getresult():
                logger.error("  ... %s" % row[0])
                GV.Schemas.append(row[0])
    except Exception, e:
        setError(ERROR_NOREPAIR)
        myprint('[ERROR] executing test: checkPGNamespace')
        myprint('  Execution error: ' + str(e))

    # Check for objects in various catalogs that are in a schema that has
    # been dropped.
    logger.info('Checking missing schema definitions ...')
    qry = '''
    SELECT o.catalog, o.nsp
    FROM pg_namespace n right outer join 
         (select 'pg_class' as catalog, relnamespace as nsp from pg_class 
          union
          select 'pg_type' as catalog, typnamespace as nsp from pg_type 
          union
          select 'pg_operator' as catalog, oprnamespace as nsp from pg_operator
          union
          select 'pg_proc' as catalog,pronamespace as nsp from pg_proc) o on
          (n.oid = o.nsp)
    WHERE n.oid is NULL
    '''
    err = connect2run(qry, ('catalog', 'nsp'))
    if not err:
        logger.info('[OK] missing schema definitions')
    else:
        GV.testStatus = False
        setError(ERROR_NOREPAIR)
        logger.info('[FAIL] missing schema definitons')
        logger.error('found %d references to non-existent schemas' % len(err))
        logger.error(qry)
        for e in err: 
            logger.error(formatErr(e[0], e[1], e[2]))

#############
'''
Produce repair scripts to remove dangling entries of gp_fastsequence:
	- one file per segment dbid
	- contains DELETE statements to remove catalog entry
'''
def removeFastSequence(db):
    '''
    MPP-14758: gp_fastsequence does not get cleanup after a failed transaction (AO/CO)
    Note: this is slightly different from the normal foreign key check 
          because it streches the cross reference across segments. 
          This makes it safe in the event of cross consistency issues with pg_class, 
          but may not repair some issues when there are cross consistency problems
    '''
    try:
        qry = """ 
              SELECT dbid, objid 
                FROM gp_segment_configuration AS cfg JOIN
			         (SELECT gp_segment_id, objid
                        FROM (select gp_segment_id, objid from gp_fastsequence
                              union
                              select gp_segment_id, objid from gp_dist_random('gp_fastsequence')) AS fs
                        LEFT OUTER JOIN 
                             (select oid from pg_class 
                              union
                              select oid from gp_dist_random('pg_class')) AS c
                        ON (fs.objid = c.oid)
                     WHERE c.oid IS NULL) AS r
                  ON r.gp_segment_id = cfg.content 
               WHERE cfg.role = 'p';
              """
        curs = db.query(qry)
        for row in curs.dictresult():
            seg     = row['dbid']				# dbid of targetted segment
            name    = 'gp_fastsequence tuple'	# for comment purposes 
            table   = 'gp_fastsequence' 		# table name
            cols    = {'objid': row['objid']} 	# column name and value
            objname = 'gp_fastsequence'			# for comment purposes 
            buildRemove(seg, name, table, cols, objname)
    except Exception, e:
        logger.error('removeFastSequence: ' + str(e))


#############

def removeIndexConstraint(nspname, relname, constraint):
    GV.Constraints.append('ALTER TABLE "%s"."%s" DROP CONSTRAINT "%s" CASCADE;' % \
            (nspname, relname, constraint))

def distributeRandomly(rel):
    GV.Policies.append('ALTER TABLE %s SET DISTRIBUTED RANDOMLY;' % rel)

def buildRemove(seg, name, table, cols, objname):
    first = False
    fullstr = ''
    str = ''
    for col in cols:
        if not first:
            fullstr = '--Object Name: %s\n--Remove %s for %i\n' %  \
                (objname, name, cols[col])
        if len(str) > 0:
            str += ' or '
        str += '%s = \'%s\'' % (col, cols[col])
    fullstr += 'DELETE FROM %s WHERE %s;' % (table, str)
    addRemove(seg, fullstr)

def addRemove(seg, line):
    if not GV.Remove.has_key(seg):
        GV.Remove[seg] = []
    GV.Remove[seg].append(line)

def buildAdjustConname(seg, relname, relid, oldconname, newconname):
    # relname text
    # relid oid as int
    # old/newconname text
    stmt = '--Constraint Name: %s on %s becomes %s\n' % \
        (oldconname, relname, newconname)
    stmt += 'UPDATE pg_constraint\n'
    stmt += 'SET conname = %s\n' % newconname
    stmt += 'WHERE conrelid = %d and conname = %s;' % (relid, oldconname)
    addAdjustConname(seg, stmt)

def addAdjustConname(seg, stmt):
    if not GV.AdjustConname.has_key(seg):
        GV.AdjustConname[seg] = []
    GV.AdjustConname[seg].append(stmt)

def addDemoteConstraint(seg, repair_sequence):
    if not GV.DemoteConstraint.has_key(seg):
        GV.DemoteConstraint[seg] = []
    GV.DemoteConstraint[seg].append(repair_sequence)    


#############
def checkDepend():
    # Check for dependencies on non-existent objects
    logger.info('-----------------------------------')
    logger.info('Checking Object Dependencies')

    db = connect2(GV.cfg[1], utilityMode=False)

    # Catalogs that link up to pg_depend/pg_shdepend
    qry = "select relname from pg_class where relnamespace=11 and relhasoids"
    curs = db.query(qry)
    catalogs = []
    for row in curs.getresult():
        catalogs.append(row[0])

    # For each catalog construct the subquery for that catalog
    #
    # It would be desireable to switch these queries to a gp_dist_random
    # type query rather than issueing it in utility mode on every segment,
    # however because there are numerous issues remaining with oid 
    # inconsistencies (see crossDBCheck()) that doesn't work out well.
    deps = []
    for cat in catalogs:
        qry = """
          SELECT '{catalog}' as catalog, objid FROM (
            SELECT objid FROM pg_depend 
              WHERE classid = '{catalog}'::regclass
            UNION ALL
            SELECT refobjid FROM pg_depend 
              WHERE refclassid = '{catalog}'::regclass
          ) d 
          LEFT OUTER JOIN {catalog} c on (d.objid = c.oid)
          WHERE c.oid is NULL
          UNION ALL
          SELECT '{catalog}' as catalog, objid FROM (
            SELECT dbid, objid FROM pg_shdepend
              WHERE classid = '{catalog}'::regclass
            UNION ALL
            SELECT dbid, refobjid FROM pg_shdepend
              WHERE refclassid = '{catalog}'::regclass
          ) d JOIN pg_database db 
            ON (d.dbid = db.oid and datname= current_database())
          LEFT OUTER JOIN {catalog} c on (d.objid = c.oid)
          WHERE c.oid is NULL
          """.format(catalog=cat)
        deps.append(qry)

    qry = """
    SELECT distinct catalog, objid 
    FROM (%s
    ) q
    """ % "UNION ALL".join(deps)
    try:
        err = connect2run(qry)
        if not err:
            logger.info('[OK] basic object dependencies')
        else:   
            GV.testStatus = False
            setError(ERROR_NOREPAIR)
            logger.info('[FAIL] basic object dependencies')
            logger.error('  found %d dependencies on dropped objects' % len(err))
            # logger.info(qry)

    except Exception, e:
        setError(ERROR_NOREPAIR)
        myprint("[ERROR] executing test: basic object dependencies")
        myprint("  Execution error: " + str(e))
        myprint(qry)
        

def fixupowners(nspname, relname, oldrole, newrole):
    
    # Must first alter the table to the wrong owner, then back to the right
    # owner.  The purpose of this is that AT doesn't dispatch the change unless
    # it think the table actually changed owner.
    #
    # Note: this means that the Owners list must be run in the order given.
    #
    GV.Owners.append('-- owner for "%s"."%s"' % (nspname, relname))
    GV.Owners.append('ALTER TABLE "%s"."%s" OWNER TO "%s";' % 
                  (nspname, relname, oldrole))
    GV.Owners.append('ALTER TABLE "%s"."%s" OWNER TO "%s";' % 
                  (nspname, relname, newrole))


def checkOwners():
    logger.info('-----------------------------------')
    logger.info('Checking table ownership')

    # Check owners in pg_class
    #
    #  - Report each table that has an inconsistency with the master database,
    #    this can be on the table directly, or on one of the table subobjects
    #    (pg_toast, pg_aoseg, etc)
    #
    #  - Theoretically this could result in multiple corrections for a given
    #    table based on having multiple "wrong" owners.  Realistically most
    #    of the problems we have seen with this problem the wrong owner is
    #    almost always the gpadmin user, so this is not expected.  If it does
    #    occur it won't be a problem, but we will issue more ALTER TABLE 
    #    commands than is strictly necessary.
    #
    #  - Between 3.3 and 4.0 the ao segment columns migrated from pg_class
    #    to pg_appendonly.
    db = connect2(GV.cfg[1], utilityMode=False)
    qry = '''
    select distinct n.nspname, coalesce(o.relname, c.relname) as relname,
                    a.rolname, m.rolname as master_rolname
    from gp_dist_random('pg_class') r
      join pg_class c on (c.oid = r.oid)
      left join pg_appendonly ao on (c.oid = ao.segrelid or 
                                     c.oid = ao.segidxid or
                                     c.oid = ao.blkdirrelid or 
                                     c.oid = ao.blkdiridxid)
      left join pg_class t on (t.reltoastidxid = c.oid)
      left join pg_class o on (o.oid = ao.relid or 
                               o.reltoastrelid = t.oid or
                               o.reltoastrelid = c.oid)
      join pg_authid a on (a.oid = r.relowner)
      join pg_authid m on (m.oid = coalesce(o.relowner, c.relowner))
      join pg_namespace n on (n.oid = coalesce(o.relnamespace, c.relnamespace))
    where c.relowner <> r.relowner
    '''
    try:
        curs = db.query(qry)

        rows = []
        for row in curs.dictresult():
            rows.append(row)

        if len(rows) == 0:
            logger.info('[OK] table ownership')
        else: 
            GV.testStatus = False
            setError(ERROR_REMOVE)
            logger.info('[FAIL] table ownership')
            logger.error('found %d table ownership issue(s)' % len(rows))
            logger.error('%s' % qry)
            for row in rows[0:100]:
                logger.error('  %s.%s relowner %s != %s'
                    % (row['nspname'], row['relname'], row['rolname'],
                       row['master_rolname']))
            if len(rows) > 100:
                logger.error("...")
            for row in rows:
                fixupowners(row['nspname'], row['relname'], row['rolname'],
                            row['master_rolname'])
    except Exception, e:
        setError(ERROR_NOREPAIR)
        myprint("[ERROR] executing: check table ownership")
        myprint("  Execution error: " + str(e))
        myprint(qry)

    # TODO: add a check that subobject owners agree with the main object owner.
    # (The above checks only compare master vs segment)


    # Check owners in pg_type
    #  - Ignore implementation types of pg_class entries - they should be
    #    in the check above since ALTER TABLE is required to fix them, not
    #    ALTER TYPE.
    db = connect2(GV.cfg[1], utilityMode=False)
    qry = '''
    select distinct n.nspname, t.typname, a.rolname, m.rolname as master_rolname
    from gp_dist_random('pg_type') r
      join pg_type t on (t.oid = r.oid)
      join pg_namespace n on (n.oid = t.typnamespace)
      join pg_authid a on (a.oid = r.typowner)
      join pg_authid m on (m.oid = t.typowner)
    where r.typowner <> t.typowner and r.typrelid = 0
    '''
    try:
        curs = db.query(qry)

        rows = []
        for row in curs.dictresult():
            rows.append(row)

        if len(rows) == 0:
            logger.info('[OK] type ownership')
        else:
            GV.testStatus = False
            setError(ERROR_NOREPAIR)
            logger.info('[FAIL] type ownership')
            logger.error('found %d type ownership issue(s)' % len(rows))
            logger.error('%s' % qry)
            for row in rows[0:100]:
                logger.error('  %s.%s typeowner %s != %s'
                    % (row['nspname'], row['typname'], row['rolname'],
                       row['master_rolname']))
            if len(rows) > 100:
                logger.error("...")

    except Exception, e:
        setError(ERROR_NOREPAIR)
        myprint("[ERROR] executing test: check type ownership")
        myprint("  Execution error: " + str(e))
        myprint(qry)

        # FIXME: add repair script
        # NOTE: types with typrelid probably will be repaired by the
        # script generated by the table ownership test above.

    # TODO:
    # Check owners in pg_proc
    # Check owners in pg_database
    # Check owners in pg_tablespace
    # Check owners in pg_filespace
    # Check owners in pg_namespace
    # Check owners in pg_operator
    # Check owners in pg_opclass
    # ...


def checkPersistentTables():
    logger.info('-----------------------------------')
    logger.info('Checking persistent tables')


    # Some of the persistency checks modified depending on if we are in
    # change tracking or not.  For instance when we are in-sync we 
    # shouldn't have persistent entries stuck in "drop pending", but this
    # is a perfectly valid state to maintain while in change-tracking.
    db = connect2(GV.cfg[1], utilityMode=False)
    qry = "SELECT count(*) FROM gp_segment_configuration WHERE mode != 's'"
    curs = db.query(qry)
    in_sync = (curs.getresult()[0][0] == 0)
    if in_sync:
        logger.info("[OK] System is synchronized")
    else:
        logger.warn("System requires recovery via gprecoverseg")

    queries = []

    # Checks on FILESPACE
    qname = "gp_persistent_filespace_node state check"
    qry = """
    SELECT p.filespace_oid,
       case when p.persistent_state = 0 then 'free'
            when p.persistent_state = 1 then 'create pending'
            when p.persistent_state = 2 then 'created'
            when p.persistent_state = 3 then 'drop pending'
            when p.persistent_state = 4 then 'abort create'
            when p.persistent_state = 5 then 'JIT create pending'
            when p.persistent_state = 6 then 'bulk load create pending'
            else 'unknown state: ' || p.persistent_state
       end as persistent_state,
       case when p.mirror_existence_state = 0 then 'mirror free'
             when p.mirror_existence_state = 1 then 'not mirrored'
             when p.mirror_existence_state = 2 then 'mirror create pending'
             when p.mirror_existence_state = 3 then 'mirror created'
             when p.mirror_existence_state = 4 then 'mirror down before create'
             when p.mirror_existence_state = 5 then 'mirror down during create'
             when p.mirror_existence_state = 6 then 'mirror drop pending'
             when p.mirror_existence_state = 7 then 'mirror only drop remains'
             else 'unknown state: ' || p.mirror_existence_state
        end as mirror_existence_state
    FROM gp_persistent_filespace_node p
    WHERE p.persistent_state not in (0, 2) 
       or p.mirror_existence_state not in (0,1,3)
    """
    if in_sync:
        queries.append([qname, qry])

    qname = "gp_persistent_filespace_node  <=> pg_filespace"
    qry = """
    SELECT  coalesce(f.oid, p.filespace_oid) as filespace_oid, 
        f.fsname as "filespace"
    FROM (SELECT * FROM gp_persistent_filespace_node 
          WHERE persistent_state = 2) p 
      FULL OUTER JOIN (SELECT oid, fsname FROM pg_filespace 
                       WHERE oid != 3052) f 
        ON (p.filespace_oid = f.oid)
    WHERE  (p.filespace_oid is NULL OR f.oid is NULL)
    """
    queries.append([qname, qry])

    qname = "gp_persistent_filespace_node  <=> gp_global_sequence"
    qry = """
    SELECT  p.filespace_oid, f.fsname as "filespace", 
        case when p.persistent_state = 0 then 'free'
             when p.persistent_state = 1 then 'create pending'
             when p.persistent_state = 2 then 'created'
             when p.persistent_state = 3 then 'drop pending'
             when p.persistent_state = 4 then 'abort create'
             when p.persistent_state = 5 then 'JIT create pending'
             when p.persistent_state = 6 then 'bulk load create pending'
             else 'unknown state: ' || p.persistent_state
        end as persistent_state,
        p.persistent_serial_num, s.sequence_num
    FROM    gp_global_sequence s, gp_persistent_filespace_node p
      LEFT JOIN pg_filespace f ON (f.oid = p.filespace_oid)
    WHERE   s.ctid = '(0,4)' and p.persistent_serial_num > s.sequence_num
    """
    queries.append([qname, qry])

    # Checks on DATABASE
    qname = "gp_persistent_database_node state check"
    qry = """
    SELECT p.tablespace_oid, p.database_oid,
       case when p.persistent_state = 0 then 'free'
            when p.persistent_state = 1 then 'create pending'
            when p.persistent_state = 2 then 'created'
            when p.persistent_state = 3 then 'drop pending'
            when p.persistent_state = 4 then 'abort create'
            when p.persistent_state = 5 then 'JIT create pending'
            when p.persistent_state = 6 then 'bulk load create pending'
            else 'unknown state: ' || p.persistent_state
       end as persistent_state,
       case when p.mirror_existence_state = 0 then 'mirror free'
             when p.mirror_existence_state = 1 then 'not mirrored'
             when p.mirror_existence_state = 2 then 'mirror create pending'
             when p.mirror_existence_state = 3 then 'mirror created'
             when p.mirror_existence_state = 4 then 'mirror down before create'
             when p.mirror_existence_state = 5 then 'mirror down during create'
             when p.mirror_existence_state = 6 then 'mirror drop pending'
             when p.mirror_existence_state = 7 then 'mirror only drop remains'
             else 'unknown state: ' || p.mirror_existence_state
        end as mirror_existence_state
    FROM gp_persistent_database_node p
    WHERE p.persistent_state not in (0, 2) 
       or p.mirror_existence_state not in (0,1,3)
    """
    if in_sync:
        queries.append([qname, qry])
    
    qname = "gp_persistent_database_node   <=> pg_database"
    qry = """
    SELECT coalesce(d.oid, p.database_oid) as database_oid,
       d.datname as database
    FROM (SELECT * FROM gp_persistent_database_node 
          WHERE persistent_state = 2) p
      FULL OUTER JOIN pg_database d 
        ON (d.oid = p.database_oid)
    WHERE (d.datname is null or p.database_oid is null)
    """
    queries.append([qname, qry])
 
    qname = "gp_persistent_database_node   <=> pg_tablespace"
    qry = """
    SELECT  coalesce(t.oid, p.database_oid) as database_oid, 
        t.spcname as tablespace
    FROM (SELECT * FROM gp_persistent_database_node 
          WHERE persistent_state = 2) p
      LEFT OUTER JOIN (SELECT oid, spcname FROM pg_tablespace 
                       WHERE oid != 1664) t
        ON (t.oid = p.tablespace_oid)
    WHERE  t.spcname is null
    """
    queries.append([qname, qry])


    qname = "gp_persistent_database_node   <=> gp_global_sequence"
    qry = """
    SELECT  p.database_oid, p.tablespace_oid, d.datname as "database",
        case when p.persistent_state = 0 then 'free'
             when p.persistent_state = 1 then 'create pending'
             when p.persistent_state = 2 then 'created'
             when p.persistent_state = 3 then 'drop pending'
             when p.persistent_state = 4 then 'abort create'
             when p.persistent_state = 5 then 'JIT create pending'
             when p.persistent_state = 6 then 'bulk load create pending'
             else 'unknown state: ' || p.persistent_state
        end as persistent_state,
        p.persistent_serial_num, s.sequence_num
    FROM    gp_global_sequence s, gp_persistent_database_node p
      LEFT JOIN pg_database d ON (d.oid = p.database_oid)
    WHERE   s.ctid = '(0,2)' and p.persistent_serial_num > s.sequence_num
    """
    queries.append([qname, qry])

    # Checks on TABLESPACE
    qname = "gp_persistent_tablespace_node state check"
    qry = """
    SELECT p.filespace_oid, p.tablespace_oid,
       case when p.persistent_state = 0 then 'free'
            when p.persistent_state = 1 then 'create pending'
            when p.persistent_state = 2 then 'created'
            when p.persistent_state = 3 then 'drop pending'
            when p.persistent_state = 4 then 'abort create'
            when p.persistent_state = 5 then 'JIT create pending'
            when p.persistent_state = 6 then 'bulk load create pending'
            else 'unknown state: ' || p.persistent_state
       end as persistent_state,
       case when p.mirror_existence_state = 0 then 'mirror free'
             when p.mirror_existence_state = 1 then 'not mirrored'
             when p.mirror_existence_state = 2 then 'mirror create pending'
             when p.mirror_existence_state = 3 then 'mirror created'
             when p.mirror_existence_state = 4 then 'mirror down before create'
             when p.mirror_existence_state = 5 then 'mirror down during create'
             when p.mirror_existence_state = 6 then 'mirror drop pending'
             when p.mirror_existence_state = 7 then 'mirror only drop remains'
             else 'unknown state: ' || p.mirror_existence_state
        end as mirror_existence_state
    FROM gp_persistent_tablespace_node p
    WHERE p.persistent_state not in (0, 2) 
       or p.mirror_existence_state not in (0,1,3)
    """
    if in_sync:
        queries.append([qname, qry])

    qname = "gp_persistent_tablespace_node <=> pg_tablespace"
    qry = """
    SELECT  coalesce(t.oid, p.tablespace_oid) as tablespace_oid, 
        t.spcname as tablespace
    FROM (SELECT * FROM gp_persistent_tablespace_node 
          WHERE persistent_state = 2) p 
      FULL OUTER JOIN (
        SELECT oid, spcname FROM pg_tablespace WHERE oid not in (1663, 1664)
      ) t ON (t.oid = p.tablespace_oid)
    WHERE  t.spcname is null or p.tablespace_oid is null
    """
    queries.append([qname, qry])

    qname = "gp_persistent_tablespace_node <=> pg_filespace"
    qry = """
    SELECT  p.filespace_oid, f.fsname as "filespace"
    FROM (SELECT * FROM gp_persistent_tablespace_node 
          WHERE persistent_state = 2) p
      LEFT OUTER JOIN pg_filespace f 
        ON (f.oid = p.filespace_oid)
    WHERE  f.fsname is null
    """
    queries.append([qname, qry])

    qname = "gp_persistent_tablespace_node <=> gp_global_sequence"
    qry = """
    SELECT  p.filespace_oid, p.tablespace_oid, t.spcname as "tablespace",
        case when p.persistent_state = 0 then 'free'
             when p.persistent_state = 1 then 'create pending'
             when p.persistent_state = 2 then 'created'
             when p.persistent_state = 3 then 'drop pending'
             when p.persistent_state = 4 then 'abort create'
             when p.persistent_state = 5 then 'JIT create pending'
             when p.persistent_state = 6 then 'bulk load create pending'
             else 'unknown state: ' || p.persistent_state
        end as persistent_state,
        p.persistent_serial_num, s.sequence_num
    FROM    gp_global_sequence s, gp_persistent_tablespace_node p
      LEFT JOIN pg_tablespace t ON (t.oid = p.tablespace_oid)
    WHERE   s.ctid = '(0,3)' and p.persistent_serial_num > s.sequence_num
    """
    queries.append([qname, qry])

    # Checks on RELATION
    qname = "gp_persistent_relation_node state check"
    qry = """
    SELECT p.tablespace_oid, p.relfilenode_oid, p.segment_file_num,
       case when p.persistent_state = 0 then 'free'
            when p.persistent_state = 1 then 'create pending'
            when p.persistent_state = 2 then 'created'
            when p.persistent_state = 3 then 'drop pending'
            when p.persistent_state = 4 then 'abort create'
            when p.persistent_state = 5 then 'JIT create pending'
            when p.persistent_state = 6 then 'bulk load create pending'
            else 'unknown state: ' || p.persistent_state
       end as persistent_state,
       case when p.mirror_existence_state = 0 then 'mirror free'
             when p.mirror_existence_state = 1 then 'not mirrored'
             when p.mirror_existence_state = 2 then 'mirror create pending'
             when p.mirror_existence_state = 3 then 'mirror created'
             when p.mirror_existence_state = 4 then 'mirror down before create'
             when p.mirror_existence_state = 5 then 'mirror down during create'
             when p.mirror_existence_state = 6 then 'mirror drop pending'
             when p.mirror_existence_state = 7 then 'mirror only drop remains'
             else 'unknown state: ' || p.mirror_existence_state
        end as mirror_existence_state
    FROM gp_persistent_relation_node p
    WHERE (p.persistent_state not in (0, 2) 
           or p.mirror_existence_state not in (0,1,3))
      and p.database_oid in (
        SELECT oid FROM pg_database WHERE datname = current_database()
      )
    """
    if in_sync:
        queries.append([qname, qry])


    qname = "gp_persistent_relation_node   <=> pg_tablespace"
    qry = """
    SELECT  distinct p.tablespace_oid
    FROM (SELECT * FROM gp_persistent_relation_node 
          WHERE persistent_state = 2 
            AND database_oid in (
              SELECT oid FROM pg_database 
              WHERE datname = current_database()
              UNION ALL
              SELECT 0)) p
      LEFT OUTER JOIN pg_tablespace t 
        ON (t.oid = p.tablespace_oid)
    WHERE  t.oid is null
    """
    queries.append([qname, qry])

    qname = "gp_persistent_relation_node   <=> pg_database"
    qry = """
    SELECT  datname, oid, count(*)
    FROM (
      SELECT  d.datname as datname, p.database_oid as oid
      FROM (SELECT * FROM gp_persistent_relation_node 
            WHERE database_oid != 0 and persistent_state = 2
           ) p
        full outer join pg_database d ON (d.oid = p.database_oid)
    ) x
    GROUP BY 1,2
    HAVING  datname is null or oid is null or count(*) < 100
    """
    queries.append([qname, qry])

    qname = "gp_persistent_relation_node   <=> gp_relation_node"
    qry = """
    SELECT  coalesce(p.relfilenode_oid, r.relfilenode_oid) as relfilenode,
        p.ctid, r.persistent_tid
    FROM  (
      SELECT p.ctid, p.* FROM gp_persistent_relation_node p
      WHERE persistent_state = 2 AND p.database_oid in (
        SELECT oid FROM pg_database WHERE datname = current_database()
        UNION ALL
        SELECT 0
        )
      ) p
      FULL OUTER JOIN gp_relation_node r
        ON (p.relfilenode_oid = r.relfilenode_oid and
            p.segment_file_num = r.segment_file_num)
    WHERE  (p.relfilenode_oid is NULL OR 
            r.relfilenode_oid is NULL OR 
            p.ctid != r.persistent_tid)
    """
    queries.append([qname, qry])

    qname = "gp_persistent_relation_node   <=> pg_class"
    qry = """
    SELECT  coalesce(p.relfilenode_oid, c.relfilenode) as relfilenode,
        c.nspname, c.relname, c.relkind, c.relstorage
    FROM (
      SELECT * FROM gp_persistent_relation_node
      WHERE persistent_state = 2 AND database_oid in (
        SELECT oid FROM pg_database WHERE datname = current_database()
        UNION ALL
        SELECT 0
        )
      ) p
      FULL OUTER JOIN (
        SELECT  n.nspname, c.relname, c.relfilenode, c.relstorage, c.relkind
        FROM  pg_class c 
          LEFT OUTER JOIN pg_namespace n ON (c.relnamespace = n.oid)
        WHERE  c.relstorage not in ('v', 'x', 'f')
      ) c ON (p.relfilenode_oid = c.relfilenode)
    WHERE  p.relfilenode_oid is NULL OR c.relfilenode is NULL
    """
    queries.append([qname, qry])

    qname = "gp_persistent_relation_node   <=> gp_global_sequence"
    qry = """
    SELECT  p.tablespace_oid, p.database_oid, p.relfilenode_oid,
        p.segment_file_num, 
        case when p.persistent_state = 0 then 'free'
             when p.persistent_state = 1 then 'create pending'
             when p.persistent_state = 2 then 'created'
             when p.persistent_state = 3 then 'drop pending'
             when p.persistent_state = 4 then 'abort create'
             when p.persistent_state = 5 then 'JIT create pending'
             when p.persistent_state = 6 then 'bulk load create pending'
             else 'unknown state: ' || p.persistent_state
        end as persistent_state,
        p.persistent_serial_num, s.sequence_num
    FROM    gp_global_sequence s, gp_persistent_relation_node p
      LEFT JOIN pg_tablespace t ON (t.oid = p.tablespace_oid)
    WHERE   s.ctid = '(0,1)' and p.persistent_serial_num > s.sequence_num
    """
    queries.append([qname, qry])

    # Look for extra/missing files in the filesystem
    #
    # Note: heap tables only ever store segment_file_num 0 in the persistent
    # tables, while ao/co tables will store every segment_file_num that they
    # use.  This results in the segment_file_num/relstorage where clause.
    qname = "gp_persistent_relation_node   <=> filesystem"
    qry = """
    SELECT coalesce(a.tablespace_oid, b.tablespace_oid) as tablespace_oid,
       coalesce(a.database_oid, b.database_oid) as database_oid,
       coalesce(a.relfilenode_oid, b.relfilenode_oid) as relfilenode_oid,
       coalesce(a.segment_file_num, b.segment_file_num) as segment_file_num,
       a.relfilenode_oid is null as filesystem,
       b.relfilenode_oid is null as persistent,
       b.relkind, b.relstorage
    FROM   gp_persistent_relation_node a
    FULL OUTER JOIN (
      SELECT p.*, c.relkind, c.relstorage
      FROM   gp_persistent_relation_node_check() p
        LEFT OUTER JOIN pg_class c 
          ON (p.relfilenode_oid = c.relfilenode)
      WHERE (p.segment_file_num = 0 or c.relstorage != 'h')
    ) b ON (a.tablespace_oid   = b.tablespace_oid    and
            a.database_oid     = b.database_oid      and
            a.relfilenode_oid  = b.relfilenode_oid   and
            a.segment_file_num = b.segment_file_num)
    WHERE (a.relfilenode_oid is null OR 
	   (a.persistent_state = 2 and b.relfilenode_oid is null))  and
      coalesce(a.database_oid, b.database_oid) in (
        SELECT oid FROM pg_database WHERE datname = current_database()
        UNION ALL
        SELECT 0
      );
    """
    queries.append([qname, qry])

    # Look for databases in the filesystem that have been dropped but still
    # have dangling files.
    qname = "pg_database                   <=> filesystem"
    qry = """
    SELECT tablespace_oid, database_oid, count(*)
    FROM   gp_persistent_relation_node_check() p 
      LEFT OUTER JOIN pg_database d 
      ON (p.database_oid = d.oid) 
    WHERE  d.oid is null and database_oid != 0
    GROUP BY tablespace_oid, database_oid;
    """
    queries.append([qname, qry])


    # Phew, that was a lot of queries, eh?
    # now execute them on every segment.
    for (qname, qry) in queries:
        err = connect2run(qry)
        if not err:
            logger.info('[OK] ' + qname)
        else:
            GV.testStatus = False
            setError(ERROR_NOREPAIR)
            logger.info('[FAIL] ' + qname)
            logger.error('%s found %d issue(s)' % (qname, len(err)))
            logger.error(qry)
            
            # Report at most 100 rows per segment, for brevity
            last    = None
            count   = 0
            for e in err:
                cfg = e[0]
                col = e[1]
                row = e[2]
                
                # If this is a new host start again
                if last != cfg:
                    count = 0
                    last = cfg

                if count == 100:
                    logger.error("...")
                    count += 1
                if count > 100:
                    continue

                # Actual formatting could be prettied up more
                if count == 0:
                    logger.error("--------")
                    logger.error("%s:%s:%s" % (cfg['hostname'], 
                                               cfg['port'], 
                                               cfg['datadir']))
                    logger.error("  " + " | ".join(map(str, col)))
                logger.error("  " + " | ".join([str(row[x]) for x in col]))
                count += 1

    return


def closeDbs():
    for key, conns in GV.db.iteritems():
        db = conns[0]
        db.close()
    GV.db = {} # remove everything


#-------------------------------------------------------------------------------
def getCatObj(namestr):

    db = connect2(GV.cfg[1], utilityMode=False)
    try:
        cat = GV.catalog.getCatalogTable(namestr)
    except Exception, e:
        myprint("No such catalog table: %s\n" % str(namestr))
        raise
    return cat


#-------------------------------------------------------------------------------
def checkACL():
    logger.info('-----------------------------------')
    logger.info('Performing cross database ACL tests')

    # looks up information in the catalog:
    tables = GV.catalog.getCatalogTables()

    for cat in sorted(tables):
        checkTableACL(cat)

#-------------------------------------------------------------------------------
def checkTableACL(cat):

    catname  = cat.getTableName()
    pkey     = cat.getPrimaryKey()
    master   = cat.isMasterOnly()
    isShared = cat.isShared()
    acl      = cat.getTableAcl()

    if GV.aclStatus == None:
        GV.aclStatus = True
        
    # Skip:
    #   - master only tables
    #   - tables without a primary key
    #   - tables without acls
    if master or pkey == [] or acl == None:
        return

    # skip shared/non-shared tables
    if GV.opt['-S']:
        if re.match("none", GV.opt['-S'], re.I) and isShared:
            return
        if re.match("only", GV.opt['-S'], re.I) and not isShared:
            return

    # Comparing ACLs cannot be done with a simple equality comparison
    # since it is valid for the ACLs to have different order.  Instead
    # we compare that both acls are subsets of each other => equality.

    mPkey = ['m.'+i for i in pkey]
    if cat.tableHasConsistentOids():
        mPkey = ['m.oid']

    qry = """
    SELECT s.gp_segment_id as segid, {mPkey},
           m.{acl} as master_acl, s.{acl} as segment_acl
    FROM {catalog} m
    JOIN gp_dist_random('{catalog}') s using ({primary_key})
    WHERE  not (m.{acl} @> s.{acl} and s.{acl} @> m.{acl}) or
           (m.{acl} is null and s.{acl} is not null) or
           (s.{acl} is null and m.{acl} is not null)
    ORDER BY {primary_key}, s.gp_segment_id
    """.format(catalog     = catname,
               primary_key = ', '.join(pkey),
               mPkey       = ', '.join(mPkey),
               acl         = acl)

    # Execute the query
    try:
        db = connect2(GV.cfg[1], utilityMode=False)
        curs  = db.query(qry)
        nrows = curs.ntuples()

        if nrows == 0:
            logger.info('[OK] Cross consistency acl check for ' + catname)
        else:
            GV.testStatus = False
            setError(ERROR_NOREPAIR)
            GV.aclStatus = False
            logger.info('[FAIL] Cross consistency acl check for ' + catname)
            logger.error('  %s acl check has %d issue(s)' % (catname, nrows))
            # logger.error(qry)

            fields = curs.listfields()
            log_literal(logger,logging.ERROR,"    " + " | ".join(fields))
            for row in curs.getresult():
                log_literal(logger,logging.ERROR,"    " + " | ".join(map(str, row)))
            processACLResult(catname, fields, curs.getresult())

    except Exception, e:
        setError(ERROR_NOREPAIR)
        GV.aclStatus = False
        myprint('[ERROR] executing: Cross consistency check for ' + catname)
        myprint('  Execution error: ' + str(e))
        myprint(qry)


#-------------------------------------------------------------------------------
def checkForeignKey():

    logger.info('-----------------------------------')
    logger.info('Performing foreign key tests')

    if GV.foreignKeyStatus == None:
        GV.foreignKeyStatus = True
    
    # looks up information in the catalog:
    tables = GV.catalog.getCatalogTables()

    for cat in sorted(tables):
        checkTableForeignKey(cat)

#-------------------------------------------------------------------------------
def checkTableForeignKey(cat):
    
    catname  = cat.getTableName()
    fkeylist = cat.getForeignKeys()
    isShared = cat.isShared()
    pkeylist = cat.getPrimaryKey()
    coltypes = cat.getTableColtypes()

    # skip tables without fkey
    if len(fkeylist) <= 0:
        return
    if len(cat.getPrimaryKey()) <= 0:
        return

    # skip these master-only tables
    skipped_masteronly = ['gp_relation_node', 'pg_description', 'pg_shdescription', 
                          'pg_stat_last_operation', 'pg_stat_last_shoperation', 'pg_statistic']

    if catname in skipped_masteronly:
        return

    # skip shared/non-shared tables
    if GV.opt['-S']:
        if re.match("none", GV.opt['-S'], re.I) and isShared:
            return
        if re.match("only", GV.opt['-S'], re.I) and not isShared:
            return
 
    # primary key lists
    cat1pkeys = []
    pkeys     = []

    # build array of catalog primary keys (with aliases) and
    # primary key alias list
    for pk in pkeylist:
        cat1pkeys.append('cat1.' + pk + ' as %s_%s' % (catname,pk))
        pkeys.append('%s_%s' % (catname,pk))

    logger.info('Building %d queries to check FK constraint on table %s' % (len(fkeylist),catname))
    for fkeydef in fkeylist:
        castedFkey  = [c+autoCast.get(coltypes[c],'') for c in fkeydef.getColumns()]
        fkeystr     = ', '.join(castedFkey)
        cat1fkeystr = 'cat1.' + ', cat1.'.join(fkeydef.getColumns())
        pkeystr     = ', '.join(fkeydef.getPKey())
        pkcatname   = fkeydef.getPkeyTableName()

        qry = fkQuery(catname, pkcatname, fkeystr, pkeystr, pkeys, cat1pkeys)
       
        # Execute the query
        try:
            db = connect2(GV.cfg[1], utilityMode=False)
            curs  = db.query(qry)
            nrows = curs.ntuples()

            if nrows == 0:
                logger.info('[OK] Foreign key check for %s(%s) referencing %s(%s)'%
                            (catname, fkeystr, pkcatname, pkeystr))
            else:
                GV.testStatus = False
                setError(ERROR_NOREPAIR)
                GV.foreignKeyStatus = False
                logger.info('[FAIL] Foreign key check for %s(%s) referencing %s(%s)'%
                            (catname, fkeystr, pkcatname, pkeystr))
                logger.error('  %s has %d issue(s): entry has NULL reference of %s(%s)'% 
                            (catname, nrows, pkcatname, pkeystr))

                fields = curs.listfields()
                log_literal(logger,logging.ERROR,"    " + " | ".join(fields))
                for row in curs.getresult():
                    log_literal(logger,logging.ERROR,"    " + " | ".join(map(str, row)))
                processForeignKeyResult(catname, pkcatname, fields, curs.getresult())

                if catname == 'gp_fastsequence' and pkcatname == 'pg_class':
                    setError(ERROR_REMOVE)
                    removeFastSequence(db)

        except Exception, e:
            setError(ERROR_NOREPAIR)
            GV.foreignKeyStatus = False
            myprint('[ERROR] executing: Foreign key check for ' + catname)
            myprint('  Execution error: ' + str(e))
            myprint(qry)


#-------------------------------------------------------------------------------
def fkQuery(catname, pkcatname, fkeystr, pkeystr, pkeys, cat1pkeys):

    qry = """
          SELECT {primary_key_alias}, {cat2_dot_pk},
                 array_agg(gp_segment_id order by gp_segment_id) as segids
          FROM (
                SELECT cat1.gp_segment_id, {cat1_dot_pk}, cat1.{FK1} as {cat2_dot_pk} 
                FROM
                    gp_dist_random('{CATALOG1}') cat1 LEFT OUTER JOIN
                    gp_dist_random('{CATALOG2}') cat2
                    ON (cat1.gp_segment_id = cat2.gp_segment_id AND
                        cat1.{FK1} = cat2.{PK2} )
                WHERE cat2.{PK2} is NULL
                  AND cat1.{FK1} != 0
                UNION ALL
                SELECT -1 as gp_segment_id, {cat1_dot_pk}, cat1.{FK1} as {cat2_dot_pk} 
                FROM
                    {CATALOG1} cat1 LEFT OUTER JOIN
                    {CATALOG2} cat2
                    ON (cat1.gp_segment_id = cat2.gp_segment_id AND
                        cat1.{FK1} = cat2.{PK2} )
                WHERE cat2.{PK2} is NULL
                  AND cat1.{FK1} != 0
                ORDER BY {primary_key_alias}, gp_segment_id
          ) allresults
          GROUP BY {primary_key_alias}, {cat2_dot_pk}
          """.format(FK1      = fkeystr,
                     PK2      = pkeystr,
                     CATALOG1 = catname,
                     CATALOG2 = pkcatname,
                     cat1_dot_pk = ', '.join(cat1pkeys) ,
                     cat2_dot_pk = '%s_%s' % (pkcatname,pkeystr),
                     primary_key_alias    = ', '.join(pkeys))

    return qry



#-------------------------------------------------------------------------------
def checkMissingEntry():
    logger.info('-----------------------------------')
    logger.info('Performing cross consistency tests: check for missing or extraneous entries')
    
    if GV.missingEntryStatus == None:
        GV.missingEntryStatus = True

    # looks up information in the catalog:
    tables = GV.catalog.getCatalogTables()

    for cat in sorted(tables):
        checkTableMissingEntry(cat)


#-------------------------------------------------------------------------------
def checkTableMissingEntry(cat):
   
    catname  = cat.getTableName()
    pkey     = cat.getPrimaryKey()
    master   = cat.isMasterOnly()
    isShared = cat.isShared()
    coltypes = cat.getTableColtypes()

    # Skip master only tables
    if master:
        return

    # skip shared/non-shared tables
    if GV.opt['-S']:
        if re.match("none", GV.opt['-S'], re.I) and isShared:
            return
        if re.match("only", GV.opt['-S'], re.I) and not isShared:
            return

    # Skip catalogs without primary key
    if pkey == []:
        logger.warn("[WARN] Skipped missing/extra entry check for %s" %
                    catname)
        return

    castedPkey = cat.getPrimaryKey()
    castedPkey = [ c+autoCast.get(coltypes[c],'') for c in castedPkey ]
 
    if cat.tableHasConsistentOids():
        qry = missingEntryQuery(GV.max_content, catname, ['oid'], ['oid'])
    else:
        qry = missingEntryQuery(GV.max_content, catname, pkey, castedPkey)

    # Execute the query
    try:
        db = connect2(GV.cfg[1], utilityMode=False)
        curs  = db.query(qry)
        nrows = curs.ntuples()

        if nrows == 0:
            logger.info('[OK] Checking for missing or extraneous entries for ' + catname)
        else:
            if catname in ['pg_constraint']:
                logger_with_level = logger.warning
                log_level = logging.WARNING
            else:
                GV.testStatus = False
                setError(ERROR_NOREPAIR)
                GV.missingEntryStatus = False
                logger_with_level = logger.error
                log_level = logging.ERROR

            logger.info(('[%s] Checking for missing or extraneous entries for ' + catname) % 
                        ('WARNING' if log_level == logging.WARNING else 'FAIL'))
            logger_with_level('  %s has %d issue(s)' % (catname, nrows))
            fields = curs.listfields()
            log_literal(logger,log_level,"    " + " | ".join(fields))
            for row in curs.getresult():
                log_literal(logger,log_level,"    " + " | ".join(map(str, row)))
            results = curs.getresult()
            processMissingDuplicateEntryResult(catname, fields, results, "missing")
            if catname == 'pg_type':
            	generateVerifyFile(catname, fields, results, 'missing_extraneous')
    except Exception, e:
        setError(ERROR_NOREPAIR)
        GV.missingEntryStatus = False
        myprint('[ERROR] executing: Missing or extraneous entries check for ' + catname)
        myprint('  Execution error: ' + str(e))
        myprint(qry)



#-------------------------------------------------------------------------------
def missingEntryQuery(max_content, catname, pkey, castedPkey):

    # =================
    #  Missing / Extra
    # =================
    #   Cross product 
    #       (all unique {primary_key} present on any segment)
    #       (all unique segment_ids in the system)
    #   Left join
    #       (actual ({primary_key}, segment_id) present in the catalog)
    #   
    #   Count number not null vs number null in the join:
    #     If the nulls are <= 1/2 the result report those segments as "missing"
    #     If the non-nulls are <= 1/2 the result report those segments as "extra"

    qry = """
          SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
          
          -- distribute catalog table from master, so that we can avoid to gather
          CREATE TEMPORARY TABLE _tmp_master ON COMMIT DROP AS
              SELECT gp_segment_id segid, {primary_key} FROM {catalog};
          SELECT {oidcasted_pk}, exists, array_agg(segid order by segid) as segids
          FROM
          (
            SELECT ideal.*,
                   case when actual.segid is null then 'missing' else 'extra' end as exists,
                   count(*) over (partition by {primary_key}, actual.segid is null) as subcount
            FROM (
                 SELECT segid, {primary_key}
                 FROM(  SELECT distinct {primary_key} FROM _tmp_master
                        UNION 
                        SELECT distinct {primary_key} FROM gp_dist_random('{catalog}') ) all_pks,
                      ( SELECT distinct content as segid from gp_segment_configuration) all_segs
               ) ideal
               LEFT OUTER JOIN
               ( SELECT segid, {primary_key} FROM _tmp_master
                 UNION ALL
                 SELECT gp_segment_id as segid, {primary_key} FROM gp_dist_random('{catalog}')
               ) actual USING (segid, {primary_key})
          ) missing_extra
          WHERE subcount <= ({max_content}+2)/2.0
          GROUP BY {oidcasted_pk}, exists;
          """.format(oidcasted_pk = ','.join(castedPkey),
                     primary_key = ','.join(pkey),
                     catalog = catname,
                     max_content = max_content)

    return qry

def transformTextArrayCols(catname, columns, colnames, coltypes):
    # Distributing by hash(text[]) is potentially dangerous,
    # so if the table has text[] column, then we need array_to_string
    #
    # We should fix the text[] hash expression issue, but
    # for this script, this seems like a reasonable workaround.

    transformed = []
    for i in range(len(columns)):
        if coltypes[colnames[i]] == '_text':
            transformed.append("array_to_string(" + columns[i] + ", ',')")
        else:
            transformed.append(columns[i])

    return transformed

#-------------------------------------------------------------------------------
def checkInconsistentEntry():
    logger.info('-----------------------------------')
    logger.info('Performing cross consistency test: check for inconsistent entries')
    
    if GV.inconsistentEntryStatus == None:
        GV.inconsistentEntryStatus = True

    # looks up information in the catalog:
    tables = GV.catalog.getCatalogTables()

    for cat in sorted(tables):
        checkTableInconsistentEntry(cat)


#-------------------------------------------------------------------------------
def checkTableInconsistentEntry(cat):
   
    catname  = cat.getTableName()
    pkey     = cat.getPrimaryKey()
    master   = cat.isMasterOnly()
    isShared = cat.isShared()
    columns  = cat.getTableColumns(with_acl=False)
    coltypes = cat.getTableColtypes()
   
    # Skip master only tables
    if master:
        return

    # skip shared/non-shared tables
    if GV.opt['-S']:
        if re.match("none", GV.opt['-S'], re.I) and isShared:
            return
        if re.match("only", GV.opt['-S'], re.I) and not isShared:
            return

    # Skip catalogs without primary key
    if pkey == []:
        logger.warn("[WARN] Skipped cross consistency check for %s" %
                    catname)
        return

    castedPkey = cat.getPrimaryKey()
    castedPkey = [ c+autoCast.get(coltypes[c],'') for c in castedPkey ]
    castcols = [ c+autoCast.get(coltypes[c],'') for c in columns ]

    # transform text[] cols for sure. See comments on transformTextArrayCols
    castcols = transformTextArrayCols(catname, castcols, columns, cat.getTableColtypes())
    castcols = [castcols[i] + ' AS ' + columns[i] for i in range(len(columns))]
    if cat.tableHasConsistentOids():
        qry = inconsistentEntryQuery(GV.max_content, catname, ['oid'], columns, castcols)
    else:
        qry = inconsistentEntryQuery(GV.max_content, catname, castedPkey, columns, castcols)

    # Execute the query
    try:
        db = connect2(GV.cfg[1], utilityMode=False)
        curs  = db.query(qry)
        nrows = curs.ntuples()

        if nrows == 0:
            logger.info('[OK] Checking for inconsistent entries for ' + catname)
        else:
            GV.testStatus = False
            setError(ERROR_NOREPAIR)
            GV.inconsistentEntryStatus = False
            logger.info('[FAIL] Checking for inconsistent entries for ' + catname)
            logger.error('  %s has %d issue(s)' % (catname, nrows))

            fields = curs.listfields()
            log_literal(logger,logging.ERROR,"    " + " | ".join(fields))
            for row in curs.getresult():
                log_literal(logger,logging.ERROR,"    " + " | ".join(map(str, row)))
            results = curs.getresult()
            processInconsistentEntryResult(catname, pkey, fields, results)
            if catname == 'pg_type':
                generateVerifyFile(catname, fields, results, 'duplicate')


    except Exception, e:
        setError(ERROR_NOREPAIR)
        GV.inconsistentEntryStatus = False
        myprint('[ERROR] executing: Inconsistent entries check for ' + catname)
        myprint('  Execution error: ' + str(e))
        myprint(qry)

#-------------------------------------------------------------------------------
def inconsistentEntryQuery(max_content, catname, pkey, columns, castcols):

        #-- ==============
        #--  Inconsistent
        #-- ==============
        #--   Build set of all values in the instance
        #--
        #--   Count number of unique values for the primary key
        #--     - Ignore rows where this does not equal number of segments
        #--       (These are the missing/extra rows and are covered by other checks)
        #--
        #--   Count number of unique values for all columns
        #--     - Ignore rows where this equals number of segments
        #--  
        #--   Group the majority opinion into one bucket and report everyone who disagrees with
        #--   the majority individually. 
        #-- 
        #--   Majority gets reported with gp_segment_id == null
        #--
        #-- SET GUC due to MPP-14531:

        qry = """
              SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
              
              SET gp_enable_mk_sort=off; 

              -- distribute catalog table from master, so that we can avoid to gather
              CREATE TEMPORARY TABLE _tmp_master ON COMMIT DROP AS
                  SELECT gp_segment_id segid, {columns} FROM {catalog};
              SELECT {columns}, array_agg(gp_segment_id order by gp_segment_id) as segids
              FROM
              (
                 SELECT DISTINCT
                   case when dcount <= ({max_content}+2)/2.0 then gp_segment_id else null end as gp_segment_id, {columns}
                 FROM
                 (
                   select count(*) over (partition by {columns}) as dcount,
                          count(*) over (partition by {pkey}) as pcount,
                          gp_segment_id, {columns}
                   from (
                     select segid gp_segment_id, {castcols} from _tmp_master
                     union all
                     select gp_segment_id, {castcols}
                     from   gp_dist_random('{catalog}')
                   ) all_segments
                 ) counted_segments
                 WHERE dcount != {max_content}+2 and pcount = {max_content}+2
                 ORDER BY {pkey}, gp_segment_id
              ) rowresult
              GROUP BY {columns}
              ORDER BY {pkey}, segids;
              """.format(pkey = ','.join(pkey),
                         catalog = catname,
                         columns = ','.join(columns),
                         castcols = ','.join(castcols),
                         max_content = max_content)

        return qry


#-------------------------------------------------------------------------------
def checkDuplicateEntry():
    logger.info('-----------------------------------')
    logger.info('Performing test: checking for duplicate entries')

    # looks up information in the catalog:
    tables = GV.catalog.getCatalogTables()

    for cat in sorted(tables):
        checkTableDuplicateEntry(cat)


#-------------------------------------------------------------------------------
def checkTableDuplicateEntry(cat):

    catname  = cat.getTableName()
    pkey     = cat.getPrimaryKey()
    master   = cat.isMasterOnly()
    isShared = cat.isShared()
    columns  = cat.getTableColumns(with_acl=False)
    coltypes = cat.getTableColtypes()

    # Skip master only tables
    if master:
        return

    # skip shared/non-shared tables
    if GV.opt['-S']:
        if re.match("none", GV.opt['-S'], re.I) and isShared:
            return
        if re.match("only", GV.opt['-S'], re.I) and not isShared:
            return

    # Skip catalogs without primary key
    if pkey == []:
        logger.warn("[WARN] Skipped duplicate check for %s" %
                    catname)
        return

    pkey = [ c+autoCast.get(coltypes[c],'') for c in pkey ]
    if cat.tableHasConsistentOids():
        qry = duplicateEntryQuery(catname, ['oid'])
    else:
        qry = duplicateEntryQuery(catname, pkey)

    # Execute the query
    try:
        db = connect2(GV.cfg[1], utilityMode=False)
        curs  = db.query(qry)
        nrows = curs.ntuples()

        if nrows == 0:
            logger.info('[OK] Checking for duplicate entries for ' + catname)
        else:
            GV.testStatus = False
            setError(ERROR_NOREPAIR)
            logger.error('[FAIL] Checking for duplicate entries for ' + catname)
            logger.error('  %s has %d issue(s)' % (catname, nrows))

            fields = curs.listfields()
            log_literal(logger,logging.ERROR,"    " + " | ".join(fields))
            for row in curs.getresult():
                log_literal(logger,logging.ERROR,"    " + " | ".join(map(str, row)))
            results = curs.getresult()
            processMissingDuplicateEntryResult(catname, fields, results, "duplicate")
            if catname == 'pg_type':
                generateVerifyFile(catname, fields, results, 'duplicate')
    except Exception, e:
        setError(ERROR_NOREPAIR)
        myprint('[ERROR] executing: duplicate entries check for ' + catname)
        myprint('  Execution error: ' + str(e))
        myprint(qry)


#-------------------------------------------------------------------------------
def duplicateEntryQuery(catname, pkey):

    #-- ===========
    #--  Duplicate
    #-- ===========
    #--   Return any rows having count > 1 for a given segid, {unique_key} pair
    #--

    qry = """
          SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;

          -- distribute catalog table from master, so that we can avoid to gather
          CREATE TEMPORARY TABLE _tmp_master ON COMMIT DROP AS
              SELECT gp_segment_id segid, {pkey} FROM {catalog};
          SELECT {pkey}, total, array_agg(segid order by segid) as segids
          FROM (
              SELECT segid, {pkey}, count(*) as total
              FROM (
                   select segid, {pkey} FROM _tmp_master
                   union all
                   select gp_segment_id as segid, {pkey} FROM gp_dist_random('{catalog}')
              ) all_segments
              GROUP BY segid, {pkey}
              HAVING count(*) > 1
          ) rowresult
          GROUP BY {pkey}, total
          """.format(catalog = catname,
                     pkey = ','.join(pkey))

    return qry


#-------------------------------------------------------------------------------
def checkDuplicatePersistentEntry():

    """
    MPP-18178: check duplicate entries in gp_persistent_relation_node
    	have the same: tablespace_oid, database_oid, relfilenode_oid, segment_file_num
    	except mirror_existence_state != 6 (MIRROR DROP PENDING)
    """

    catname = 'gp_persistent_relation_node'
    fields = ['tablespace_oid', 'database_oid', 'relfilenode_oid', 'segment_file_num']
    excol = 'mirror_existence_state'
    state = 6 

    qry = duplicatePersistentEntryQuery(catname, fields, excol, state)

    try:
        db = connect2(GV.cfg[1], utilityMode=False)
        curs  = db.query(qry)
        nrows = curs.ntuples()

        if nrows == 0:
            logger.info('[OK] Checking for duplicate persistent entries for ' + catname)
        else:
            GV.testStatus = False
            setError(ERROR_NOREPAIR)
            logger.error('[FAIL] Checking for duplicate persistent entries for ' + catname)
            logger.error('  %s has %d issue(s)' % (catname, nrows))

            fields = curs.listfields()
            log_literal(logger, logging.ERROR, "    " + " | ".join(fields))
            for row in curs.getresult():
                log_literal(logger, logging.ERROR, "    " + " | ".join(map(str, row)))
            results = curs.getresult()
            processMissingDuplicateEntryResult(catname, fields, results, "duplicate")
            if catname == 'pg_type':
            	generateVerifyFile(catname, fields, results, 'duplicate_persistent')
    except Exception, e:
        setError(ERROR_NOREPAIR)
        myprint('[ERROR] Executing: duplicate persistent entries check for ' + catname)
        myprint('  Execution error: ' + str(e))
        myprint(qry)


def duplicatePersistentEntryQuery(catname, pkey, excol, state):
    
    """
    Check for duplicate persistent table entries:
    	the query is similar to the duplicate catalog entries query, except an extra condition 
    	and the check is limited to the connected database for reporting purposes
    """
    
    qry = """
          SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
          
          -- distribute catalog table from master, so that we can avoid to gather
          CREATE TEMPORARY TABLE _tmp_master ON COMMIT DROP AS
              SELECT gp_segment_id segid, {pkey}, {excol} FROM {catalog};
          SELECT {pkey}, total, array_agg(segid order by segid) as segids
          FROM (
              SELECT segid, {pkey}, count(*) as total
              FROM (
                   select segid, {pkey} from _tmp_master
                   where {excol} != {state}
                   union all
                   select gp_segment_id as segid, {pkey} from gp_dist_random('{catalog}') 
                   where {excol} != {state}
              ) all_segments 
                LEFT OUTER JOIN pg_database d ON (all_segments.database_oid = d.oid)
              WHERE d.datname = '{dbname}'
              GROUP BY segid, {pkey}
              HAVING count(*) > 1
          ) rowresult 
          GROUP BY {pkey}, total
          """.format(catalog=catname, pkey=','.join(pkey), excol=excol, state=state, dbname=GV.dbname)
    return qry

############################################################################
# Help populating repair part for all tested types
# All functions dependent on results stored in global variable GV
############################################################################
name_repair = {
    "segment":
    {
         "description": "Check if needs repairing segment",
         "fn": lambda maybeRemove, catmod_guc, seg: checkSegmentRepair(maybeRemove, catmod_guc, seg)
    },
    "reindex":
    {
         "description": "Check if needs repair file for reindex",
         "fn": lambda: checkReindexRepair()
    },
    "constraints":
    {
         "description": "Check if needs repair file to fix constraints",
         "fn": lambda: checkConstraintsRepair()
    },
    "owners":
    {
         "description": "Check if needs repair file to fix messed up ownership",
         "fn": lambda: checkOwnersRepair()
    },
    "schemas":
    {
         "description": "Check if needs repair file to fix schema related issues",
         "fn": lambda: checkSchemaRepair()
    },
    "policies":
    {
         "description": "Check if needs repair file to fix distribution policy",
         "fn": lambda: checkPoliciesRepair()
    }
}

############################################################################
# version = X.X : run this test as part of running all tests on gpdb <= X.X  
#                 individually, any test should be ok run on any version
#  online = True: okie to run gpcheckcat online
#   order = X   : the order test should be run when running all tests
############################################################################

name_test = {
    "duplicate":
    {
         "description": "Check for duplicate entries",
         "fn": lambda: checkDuplicateEntry(),
         "version": 'main',
         "order": 1,
         "online": True
    },
    "missing_extraneous":
    {
         "description": "Cross consistency check for missing or extraneous entries",
         "fn": lambda: checkMissingEntry(),
         "version": 'main',
         "order": 2,
         "online": True
    },
    "inconsistent":
    {
         "description": "Cross consistency check for master segment inconsistency",
         "fn": lambda: checkInconsistentEntry(),
         "version": 'main',
         "order": 3,
         "online": True
    },
    "foreign_key":
    {
         "description": "Check foreign keys",
         "fn": lambda: checkForeignKey(),
         "version": 'main',
         "order": 4,
         "online": True
    },
    "acl":
    {
         "description": "Cross consistency check for access control privileges",
         "fn": lambda: checkACL(),
         "version": 'main',
         "order": 5,
         "online": True
    },
    "persistent":
    {
         "description": "Check persistent tables",
         "fn": lambda: checkPersistentTables(),
         "version": 'main',
         "order": 6,
         "online": False
    },
    "pgclass":
    {
         "description": "Check pg_class entry that does not have any correspond pg_attribute entry",
         "fn": lambda: checkPGClass(),
         "version": 'main',
         "order": 7,
         "online": False
    },
    "namespace":
    {
         "description": "Check for leaked temporary schema and missing schema definition",
         "fn": lambda: checkPGNamespace(),
         "version": 'main',
         "order": 8,
         "online": False
    },
    "distribution_policy":
    {
         "description": "Check constraints on randomly distributed tables",
         "fn": lambda: checkDistribPolicy(),
         "version": 'main',
         "order": 9,
         "online": False
    },
    "dependency":
    {
         "description": "Check for dependency on non-existent objects",
         "fn": lambda: checkDepend(),
         "version": 'main',
         "order": 10,
         "online": False
    },
    "owner":
    {
         "description": "Check table ownership that is inconsistent with the master database",
         "fn": lambda: checkOwners(),
         "version": 'main',
         "order": 11,
         "online": True
    },
    "part_integrity":
    {
         "description": "Check pg_partition branch integrity, partition with oids, partition distribution policy",
         "fn": lambda: checkPartitionIntegrity(),
         "version": 'main',
         "order": 13,
         "online": True
    },
    "part_constraint":
    {
         "description": "Check constraints on partitioned tables",
         "fn": lambda: checkPartitionRegularity(),
         "version": 'main',
         "order": 14,
         "online": True
    },
    "duplicate_persistent":
    {
        "description": "Check for duplicate gp_persistent_relation_node entries",
        "fn": lambda: checkDuplicatePersistentEntry(),
        "version": 'main',
        "order": 16,
        "online": True
    }
}


#-------------------------------------------------------------------------------
def listAllTests():

    myprint('\nList of gpcheckcat tests:\n')
    for name in sorted(name_test, key=lambda x: name_test[x]["order"]):
        myprint(" %24s: %s" % \
              (name, name_test[name]["description"]))
    myprint('')


#-------------------------------------------------------------------------------
def runTestCatname(cat):

    tests = {'missing_extraneous': lambda: checkTableMissingEntry(cat),
             'inconsistent': lambda: checkTableInconsistentEntry(cat),
             'foreign_key': lambda: checkTableForeignKey(cat),
             'duplicate': lambda: checkTableDuplicateEntry(cat),
             'acl': lambda: checkTableACL(cat)}

    for t in sorted(tests):
        myprint("Performing test '%s' for %s" % (t,cat.getTableName()))
        stime = time.time()
        tests[t]()
        etime = time.time()
        elapsed = etime - stime
        GV.elapsedTime += elapsed
        elapsed = str(datetime.timedelta(seconds=elapsed))[:-4]
        GV.totalTestRun += 1
        myprint('Total runtime for this test: %s' % (elapsed))


#-------------------------------------------------------------------------------
def runOneTest(name):

    if not name_test.has_key(name):
        logger.info("'%s' is not a valid test" % (name))
        raise LookupError
    if GV.opt['-O'] and not name_test[name]["online"]:
        logger.info("%s: Skip this test in online mode" % (name))
        return
    else:
        myprint("Performing test '%s'" % name)
        GV.totalTestRun += 1
        GV.testStatus = True
        stime = time.time()
        name_test[name]["fn"]()
        etime = time.time()
        elapsed = etime - stime
        GV.elapsedTime += elapsed
        elapsed = str(datetime.timedelta(seconds=elapsed))[:-4]
        myprint('Total runtime for this test: %s' % (elapsed))
        if GV.testStatus == False:
            GV.failedTest.append(name)



#-------------------------------------------------------------------------------
def runAllTests():
    '''
    perform catalog check for specified database
    '''
    for name in sorted(name_test, key=lambda x: name_test[x]["order"]):
        if name_test[name]["version"] >= GV.version:
            runOneTest(name)

    closeDbs()
    logger.info("------------------------------------")
    fixes = (len(GV.Remove) > 0 or 
             len(GV.AdjustConname) > 0 or
             len(GV.DemoteConstraint) > 0 or
             len(GV.ReSync) > 0 or 
             len(GV.Reindex) > 0 or 
             len(GV.Constraints) > 0 or
             len(GV.Owners) > 0 or 
             len(GV.Schemas) > 0 or
             len(GV.Policies) > 0)
    if GV.opt['-g'] != None and fixes:
        try:
            if not os.path.exists(GV.opt['-g']):
                os.mkdir(GV.opt['-g'])
        except Exception, e:
            logger.fatal('Unable to create directory "%s": %s' % (GV.opt['-g'], str(e)))
            sys.exit(1)
                   
        logger.debug('Building catalog repair scripts')
        # build a script to run these files
        script = ''
        # if repair script already exist, do not have to add extra script type to head
        if not os.path.isfile(os.path.join(GV.opt['-g'], REPAIR_SCRIPT)):
            script = '#!/bin/bash\ncd $(dirname $0)\n'
        # set allow_system_table_mods GUC for gpdb >= 4.2
        catmod_guc = ""
        if GV.version >= "4.2":
            catmod_guc = "-c allow_system_table_mods=dml"

        # don't remove anything if ReSync possible --
        # comment out the delete statements from the repair scripts
        maybeRemove = "";
        if len(GV.ReSync):
            maybeRemove="# "
        
        # use the per-dbid loop for removal and for contraint
        # name adjustments
        
        dbids = set(GV.Remove.keys())
        dbids = dbids.union(GV.AdjustConname.keys())
        dbids = dbids.union(GV.DemoteConstraint.keys())

        for seg in dbids:
            script += '\n%secho "Repairing segment %i"\n' % (maybeRemove, seg)
            segment_repair_script = name_repair["segment"]["fn"](maybeRemove, catmod_guc, seg)
            script += segment_repair_script

        c = GV.cfg[1]
        for name in name_repair:
            # skip checking on the segment repeatedly
            if name in ['segment']:
                continue
            description, repair_filename = name_repair[name]["fn"]()
            if repair_filename != None:
                    script += description
                    script += 'psql -X -a -h %s -p %i -f %s "%s" > %s.out 2>&1\n' % \
                              (c['hostname'], c['port'], repair_filename, GV.dbname, repair_filename)

        generate_repair_script(script)

    if GV.retcode >= ERROR_NOREPAIR:
        logger.warn('[WARN]: unable to generate repairs for some issues')
    logger.info("Check complete")

def generate_repair_script(script):
    try:
        path = '%s/%s' % (GV.opt['-g'], REPAIR_SCRIPT)
        file = open(path, 'a')
        file.write(script)
        file.close()
        os.chmod(path, stat.S_IXUSR | stat.S_IRUSR | stat.S_IWUSR)
    except Exception, e:
        logger.fatal('Could not write script: %s' % str(e))
        sys.exit(1)

    myprint('')
    myprint('[INFO]: repair scripts generated: %s' % path)

def checkReindexRepair():
    if len(GV.Reindex) > 0:
        # dbname.type.timestamp.sql
        filename = '%s.%s.%s.sql' % (GV.dbname, "reindex", TIMESTAMP)
        fullpath = '%s/%s' % (GV.opt['-g'], filename)
        try:
            file = open(fullpath, 'w')
        except Exception, e:
            logger.fatal('Unable to create file "%s": %s' % (fullpath, str(e)))
            sys.exit(1)

        description = '\necho "Reindexing potentially damaged bitmap indexes"\n'
        for r in GV.Reindex:
            file.write('REINDEX INDEX %s;\n' % r)
        file.close()
        return description, filename
    else:
        return None, None

def checkConstraintsRepair():
    if len(GV.Constraints) > 0:
        # dbname.type.timestamp.sql
        filename = '%s.%s.%s.sql' % (GV.dbname, "removeconstraints", TIMESTAMP)
        fullpath = '%s/%s' % (GV.opt['-g'], filename)
        try:
            file = open(fullpath, 'w')
        except Exception, e:
            logger.fatal('Unable to create file "%s": %s' % (fullpath, str(e)))
            sys.exit(1)

        description = '\necho "Dropping invalid unique constraints"\n'
        GV.Constraints = list(set(GV.Constraints))
        for r in GV.Constraints:
            file.write('%s\n' % r)
        file.close()
        return description, filename
    else:
        return None, None

def checkOwnersRepair():
    if len(GV.Owners) > 0:
        # Previously we removed duplicate statements from the "Owners" list
        # by casting it through a "list(set(...))", however this does not work
        # since the order of items in the list is important for correct results.

        # dbname.type.timestamp.sql
        filename = '%s.%s.%s.sql' % (GV.dbname, "fixowners", TIMESTAMP)
        fullpath = '%s/%s' % (GV.opt['-g'], filename)
        try:
            file = open(fullpath, 'w')
        except Exception, e:
            logger.fatal('Unable to create file "%s": %s' % (fullpath, str(e)))
            sys.exit(1)

        description = '\necho "Correcting table ownership"\n'
        for r in GV.Owners:
            file.write('%s\n' % r)
        file.close()
        return description, filename
    else:
        return None, None

def checkSchemaRepair():
    # Remove leaked temporary schemas
    if len(GV.Schemas) > 0:
        # dbname.type.timestamp.sql
        filename = '%s.%s.%s.sql' % (GV.dbname, "fixnamespace", TIMESTAMP)
        fullpath = '%s/%s' % (GV.opt['-g'], filename)
        try:
            file = open(fullpath, 'w')
        except Exception, e:
            logger.fatal('Unable to create file "%s": %s' % (fullpath, str(e)))
            sys.exit(1)

        description = '\necho "Dropping temporary schemas"\n'
        for s in GV.Schemas:
            file.write('DROP SCHEMA IF EXISTS "%s" CASCADE;\n' % s)
        file.close()
        return description, filename
    else:
        return None, None

def checkPoliciesRepair():
    # changes to distribution policies
    if len(GV.Policies) > 0:
        # dbname.type.timestamp.sql
        filename = '%s.%s.%s.sql' % (GV.dbname, "fixdistribution", TIMESTAMP)
        fullpath = '%s/%s' % (GV.opt['-g'], filename)
        try:
            file = open(fullpath, 'w')
        except Exception, e:
            logger.fatal('Unable to create file "%s": %s' % (fullpath, str(e)))
            sys.exit(1)

        description = '\necho "Fixing distribution policies"\n'
        for r in GV.Policies:
            file.write('%s\n' % r)
        file.close()
        return description, filename
    else:
        return None, None

def checkSegmentRepair(maybeRemove, catmod_guc, seg):
    # dbid.host.port.dbname.timestamp.sql
    c = GV.cfg[seg]
    filename = '%i.%s.%i.%s.%s.sql' % (seg, c['hostname'], c['port'], GV.dbname, TIMESTAMP)
    filename = filename.replace(' ', '_')
    fullpath = '%s/%s' % (GV.opt['-g'], filename)
    try:
        file = open(fullpath, 'w')
    except Exception, e:
        logger.fatal('Unable to create file "%s": %s' % (fullpath, str(e)))
        sys.exit(1)

    #unique
    lines = set()
    if GV.Remove.has_key(seg):
        lines = lines.union(GV.Remove[seg])
    if GV.AdjustConname.has_key(seg):
        lines = lines.union(GV.AdjustConname[seg])
    if GV.DemoteConstraint.has_key(seg):
        lines = lines.union(GV.DemoteConstraint[seg])

    # make sure it is sorted
    li = list(lines)
    li.sort()
    file.write('BEGIN;\n');
    for line in li:
        file.write(line + '\n')
    file.write('COMMIT;\n');
    file.close()

    run_psql_script= '''{maybe}env PGOPTIONS="-c gp_session_role=utility {guc}" psql -X -a -h {hostname} -p {port} -f {fname} "{dbname}" > {fname}.out'''.format(
                        maybe = maybeRemove, guc = catmod_guc,
                        hostname = c['hostname'],
                        port = c['port'],
                        fname = filename,
                        dbname = GV.dbname)

    return run_psql_script
#-------------------------------------------------------------------------------
def getCatalog():
    # Establish a connection to the master & looks up info in the catalog
    db = connect2(GV.cfg[1], utilityMode=False)
    return GPCatalog(db)


#-------------------------------------------------------------------------------
def getReportConfiguration():
    cfg = {}
    for dbid, each in GV.cfg.iteritems():
        if each['content'] == -1: 
            segname = 'master'
        else: 
            segname = 'seg'+str(each['content']+1)
        cfg[each['content']] = {'segname': segname, 
                                'hostname': each['hostname'], 
                                'port': each['port']}
    return cfg

#===============================================================================
# GPCHECKCAT REPORT
#===============================================================================

GPObjects = {}     # key = (catname, oid), value = GPObject
GPObjectGraph = {} # key = GPObject, value=[GPObject]
#-------------------------------------------------------------------------------


# TableMainColumn[catname] = [colname, catname2]
#    - report this catname's issues as part of catname2
#    - catname.colname references catname2.oid
#-------------------------------------------------------------------------------
TableMainColumn = {}
# Table with no OID
TableMainColumn['gp_verification_history']      = ['vertoken','gp_verification_history']
TableMainColumn['gp_version_at_initdb']         = ['schemaversion', 'gp_version_at_initdb']
TableMainColumn['pg_aggregate'] 				= ['aggfnoid','pg_proc']
TableMainColumn['pg_amop'] 						= ['amopclaid','pg_opclass']
TableMainColumn['pg_amproc']      				= ['amopclaid','pg_opclass']
TableMainColumn['pg_appendonly']  				= ['relid','pg_class']
TableMainColumn['pg_attribute']   				= ['attrelid','pg_class']
TableMainColumn['pg_attribute_encoding']        = ['attrelid', 'pg_class']
TableMainColumn['pg_auth_member'] 				= ['roleid','pg_authid']
TableMainColumn['pg_autovacuum']      		    = ['vacrelid','pg_class']
TableMainColumn['pg_exttable']                  = ['reloid','pg_class']
TableMainColumn['pg_foreign_table']    		    = ['reloid','pg_class']
TableMainColumn['pg_index']                     = ['indexrelid','pg_class']
TableMainColumn['pg_inherits']    				= ['inhrelid','pg_class']
TableMainColumn['pg_largeobject']      		    = ['loid','pg_largeobject']
TableMainColumn['pg_pltemplate']                = ['tmplname', 'pg_pltemplate']
TableMainColumn['pg_proc_callback']             = ['profnoid', 'pg_proc']
TableMainColumn['pg_type_encoding']             = ['typid', 'pg_type']
TableMainColumn['pg_window']      				= ['winfnoid','pg_proc']

# Table with OID (special case), these OIDs are known to be inconsistent
TableMainColumn['pg_attrdef']     = ['adrelid','pg_class']
TableMainColumn['pg_constraint']  = ['conrelid','pg_class']
TableMainColumn['pg_trigger']     = ['tgrelid','pg_class']
TableMainColumn['pg_rewrite']     = ['ev_class','pg_class']

# Persistent table
TableMainColumn['gp_persistent_relation_node'] = ['relfilenode_oid', 'pg_class']

# Cast OID alias type to OID since our graph of objects is based on OID
# int2vector is also casted to int2[] due to the lack of an <(int2vector, int2vector) operator
autoCast = {
  'regproc':      '::oid',
  'regprocedure': '::oid',
  'regoper':      '::oid',
  'regoperator':  '::oid',
  'regclass':     '::oid',
  'regtype':      '::oid',
  'int2vector':   '::int2[]'
}

#-------------------------------------------------------------------------------
class QueryException(Exception): pass
    

#-------------------------------------------------------------------------------
# Get gpObj from GPObjects, instantiate a new one & add to GPObjects if not found
def getGPObject(oid, catname):

    gpObj = GPObjects.get((oid, catname),None)
    if gpObj is None:
        if catname == 'pg_class':
            gpObj = RelationObject(oid, catname)
        else:
            gpObj = GPObject(oid, catname)
        GPObjects[(oid,catname)] = gpObj
    return gpObj



#-------------------------------------------------------------------------------
def getOidFromPK(catname, pkeys):

    # pkeys: name-value pair
    pkeystrList = ["%s='%s'" % (key,value) for key, value in pkeys.iteritems()]
    pkeystr     = ' and '.join(pkeystrList)

    qry = """
          SELECT oid 
          FROM (
                SELECT oid FROM {catname} 
                WHERE {pkeystr}
                UNION ALL
                SELECT oid FROM gp_dist_random('{catname}')
                WHERE {pkeystr}
          ) alloids
          GROUP BY oid
          ORDER BY count(*) desc, oid
          """ .format(catname = catname,
                      pkeystr = pkeystr)

    try:
        db = connect2(GV.cfg[1], utilityMode=False)
        curs = db.query(qry)
        if (len(curs.dictresult()) == 0):
            raise QueryException("No such entry '%s' in %s" % (pkeystr,catname))

        return curs.dictresult().pop()['oid']

    except Exception, e:
        setError(ERROR_NOREPAIR)
        myprint('  Execution error: ' + str(e))
        myprint(qry)


#-------------------------------------------------------------------------------
def getClassOidForRelfilenode(relfilenode):
    qry = "SELECT oid FROM pg_class WHERE relfilenode = %d;" % (relfilenode)
    try:
        dburl = dbconn.DbURL(hostname=GV.opt['-h'], port=GV.opt['-p'], dbname=GV.dbname)
        conn = dbconn.connect(dburl)
        oid = dbconn.execSQLForSingletonRow(conn, qry)[0]
        return oid
    except Exception, e:
        setError(ERROR_NOREPAIR)
        myprint('  Execution error: ' + str(e))


#-------------------------------------------------------------------------------
def getResourceTypeOid(oid):
    qry = """ 
          SELECT oid
          FROM ( 
               SELECT oid FROM pg_resourcetype WHERE restypid = %d
               UNION ALL
               SELECT oid FROM gp_dist_random('pg_resourcetype')
                WHERE restypid = %d
          ) alloids
          GROUP BY oid ORDER BY count(*) desc LIMIT 1
          """ % (oid, oid)

    try:
        db = connect()
        curs = db.query(qry)
        if len(curs.dictresult()) == 0: return 0
        return curs.dictresult().pop()['oid']
    except Exception, e:
        setError(ERROR_NOREPAIR)
        myprint('  Execution error: ' + str(e))

  
#-------------------------------------------------------------------------------
# Process results of tests (CC and FK) for a particular catalog:
#   - Categorize entry into GPObject
#   - Instantiate GPObject if needed
#-------------------------------------------------------------------------------
def processMissingDuplicateEntryResult(catname, colname, allValues, type):

    # type = {"missing" | "duplicate"}
    '''
    colname:       proname | pronamespace | proargtypes | exists | segids
    allValues:         add | 2200 | 23 23 | extra | {2,3}
                     scube | 2200 | 1700 | missing | {2}
               scube_accum | 2200 | 1700 1700 | missing | {2}

    colname:        oid | total | segids
    allValues:    18853 | 2 | {-1,1}
                  18853 | 3 | {0}
    '''
    gpObjName = catname
    gpColName = None
    pknames = [i for i in colname[:-2]] # Everything except the last two columns

    # This catname may not be a GPObject (e.g. pg_attribute)
    # If these catnames have oids, they are known to be inconsistent
    if catname in TableMainColumn:
        gpColName = TableMainColumn[catname][0]
        gpObjName = TableMainColumn[catname][1]
    elif 'oid' in pknames:
        gpColName = 'oid'

    # Process entries
    for row in allValues:
        rowObjName = gpObjName
        segids = row[-1]                    
        pkeys = dict((pk, row[colname.index(pk)]) for pk in pknames)

        if gpColName != None:
            oid = row[colname.index(gpColName)]
        else:
            oid = getOidFromPK(catname, pkeys)    
            pkeys = {'oid': oid}

        # Special case: constraint for domain, report pg_type.contypid
        if catname == 'pg_constraint' and oid == 0:
            oid = row[colname.index('contypid')]
            rowObjName = 'pg_type'
        # Special case: persistent table
        if catname == 'gp_persistent_relation_node':
            relfilenode = oid
            oid = getClassOidForRelfilenode(relfilenode) 

        gpObj = getGPObject(oid, rowObjName)

        if type == "missing":
            issue = CatMissingIssue(catname, pkeys, segids, row[-2])
            gpObj.setMissingIssue(issue)
        else:
            assert (type == "duplicate")
            issue = CatDuplicateIssue(catname, pkeys, segids, row[-2])
            gpObj.setDuplicateIssue(issue)



#-------------------------------------------------------------------------------
def processInconsistentEntryResult(catname, pknames, colname, allValues):
    # If tableHasInconsistentOid, columns does not have oid
    '''
    17365 | test10 | 2200 | 17366 | 0 | 0 | 17366 | 0 | 0 | 0 | f | r | h | 3 | 0 | 0 | 0 | 0 | 0 | f | f | f | f | None | {0}     -- row1
    17365 | test10 | 2200 | 17366 | 0 | 0 | 0     | 0 | 0 | 0 | f | r | h | 2 | 0 | 0 | 0 | 0 | 0 | f | f | f | f | None | {NULL}  -- row2

    176954 | test1 | 2200 | 176955 | 0 | 0 | 176956 | 0 | 0 | 0 | f | r | h | 4 | 0 | 0 | 0 | 0 | 0 | f | f | f | f | None | {-1}
    176954 | test1 | 2200 | 176955 | 0 | 0 | 176956 | 0 | 0 | 0 | f | r | h | 2 | 0 | 0 | 0 | 0 | 0 | f | f | f | f | None | {0,1}
    176954 | test1 | 2200 | 176955 | 0 | 0 | 176956 | 0 | 0 | 0 | f | r | h | 3 | 0 | 0 | 0 | 0 | 0 | f | f | f | f | None | {2,3}
    '''

    # Group allValues rows by its key (oid or primary key) into a dictionary:
    groupedValues = {}
    for row in allValues:
        if 'oid' in colname:
            keys = row[colname.index('oid')]
        else:
            keys = tuple((row[colname.index(n)]) for n in pknames)
        if keys in groupedValues:
            groupedValues[keys].append(row)
        else:
            groupedValues[keys] = [row]

    
    gpObjName = catname
    gpColName = None

    # This catname may not be a GPObject (e.g. pg_attribute)
    # If these catnames have oids, they are known to be inconsistent
    if catname in TableMainColumn:
        gpColName = TableMainColumn[catname][0]
        gpObjName = TableMainColumn[catname][1]
    elif 'oid' in colname:
         gpColName = 'oid'

    for keys,values in groupedValues.iteritems():
        rowObjName = gpObjName
        pkeys = dict((n,values[0][colname.index(n)]) for n in pknames)

        if gpColName != None:
            oid = values[0][colname.index(gpColName)]
        else:
            oid = getOidFromPK(catname, pkeys)
        issue = CatInconsistentIssue(catname, colname, list(values))

        # Special case: constraint for domain, report pg_type.contypid
        if catname == 'pg_constraint' and oid == 0:
            oid = values[0][colname.index('contypid')]
            rowObjName = 'pg_type'

        gpObj = getGPObject(oid, rowObjName)
        gpObj.setInconsistentIssue(issue)


#-------------------------------------------------------------------------------
def processForeignKeyResult(catname, pkcatname, colname, allValues):
    
    '''
    colname:    pg_class_relname | pg_class_relnamespace | pg_type_oid | segids
    allValues:            test11 | 2200 | 17389 | {-1,0,1,2,3}
                           test4 | 2200 | 17077 | {-1,0,1,2,3}
    '''

    gpObjName = pkcatname
    gpColName = colname[-2].rsplit('_',1)[1]
    fkeytab  = catname
    fkeylist = [name.rsplit('_',1)[1] for name in colname[:-2]]

    # This catname may not be a GPObject (e.g. pg_attribute)
    #    1. pg_attrdef(adrelid) referencing pg_attribute(attrelid)
    #    2. pg_rewrite(ev_class) referencing pg_attribute(attrelid)
    if pkcatname in TableMainColumn:
        if gpColName == TableMainColumn[catname][0]:
            gpObjName = TableMainColumn[catname][1]

    # Process each row
    for row in allValues:
        rowObjName = gpObjName
        segids = row[-1]
        oid = row[len(colname)-2]
        # Build fkeys dict: used to find oid of pg_class
        fkeys = dict((n,row[colname.index(fkeytab+'_'+n)]) for n in fkeylist)
        issue = CatForeignKeyIssue(pkcatname, {gpColName: oid}, segids, catname, fkeys)

        # Special cases:
        #    1. pg_class(oid) referencing pg_type(oid) - relation & composite type
        #    2. pg_resqueuecapability(restypid) referencing pg_resourcetype(restypid)
        if pkcatname == 'pg_type' and fkeytab == 'pg_class':
            rowObjName = 'pg_class'
            oid = getOidFromPK(rowObjName, fkeys)
        elif pkcatname == 'pg_resourcetype' and gpColName == 'restypid':
            oid = getResourceTypeOid(oid)
        gpObj = getGPObject(oid, rowObjName)
        gpObj.setForeignKeyIssue(issue)


#-------------------------------------------------------------------------------
def processACLResult(catname, colname, allValues):

    '''
    colname:	segid | datname | master_acl | segment_acl
    allValues:		2 | acldb | {=Tc/nmiller,nmiller=CTc/nmiller,person1=C/nmiller} | {=Tc/nmiller,nmiller=CTc/nmiller}
    				1 | gptest | None | {=Tc/nmiller,nmiller=CTc/nmiller,person2=CTc/nmiller}
    '''
 
    gpObjName = catname
    gpColName = None
    pknames = [i for i in colname[1:-2]]

    # We have to look up key to report (pg_pltemplate)
    if catname in TableMainColumn:
        gpColName = TableMainColumn[catname][0]
        gpObjName = TableMainColumn[catname][1]
    elif 'oid' in pknames:
        gpColName = 'oid'

    # Process entries
    for row in allValues:
        segid = row[0]                    
        pkeys = dict((pk, row[colname.index(pk)]) for pk in pknames)

        if gpColName != None:
            oid = row[colname.index(gpColName)]
        else:
            oid = getOidFromPK(catname, pkeys)    
            pkeys = {'oid': oid}

        macl = row[-2][1:-1].split(',') if row[-2] != None else []
        sacl = row[-1][1:-1].split(',') if row[-1] != None else []
        macl_only = list(set(macl).difference(sacl))
        sacl_only = list(set(sacl).difference(macl))
        
        issue = CatACLIssue(catname, pkeys, segid, macl_only, sacl_only)
        gpObj = getGPObject(oid, gpObjName)
        gpObj.setACLIssue(issue)


#-------------------------------------------------------------------------------
class CatInconsistentIssue:

    def __init__(self, catname, columns, rows):

        self.catname = catname
        self.columns = columns
        self.rows = rows
   
    def report(self):

        def format_segids(segids):
            if segids == '{NULL}':
                idstr = 'all other segments'
            else:
                ids = [int(i) for i in segids[1:-1].split(',')]
                idstr = ''
                for i in ids:
                    idstr += '%s (%s:%d) ' % \
                       (GV.report_cfg[i]['segname'], GV.report_cfg[i]['hostname'],
                        GV.report_cfg[i]['port'])
            return idstr
            
        for i in range(0,len(self.columns)-1):
            colset = set(j[i] for j in self.rows)
            if len(colset) > 1:
                for row in self.rows:
                    myprint("%20s is '%s' on %s" % (self.columns[i],row[i],format_segids(row[-1])))


#-------------------------------------------------------------------------------
class CatForeignKeyIssue:

    def __init__(self, catname, pkeys, segids, fcatname, fkeys):

        self.catname  = catname
        self.pkeys    = pkeys     # string of pkey=xxxx or oid=xxxx 
        self.segids   = segids    # list of affected segids
        self.fcatname = fcatname  # checked object catname
        self.fkeys    = fkeys     # string of fkeys=xxxx

    def report(self):

        ids = [int(i) for i in self.segids[1:-1].split(',')]
        idstr = ''
        if len(ids) == len(GV.report_cfg):
            idstr = 'all segments'
        else:
            for i in ids:
                idstr += '%s (%s:%d) ' % \
                         (GV.report_cfg[i]['segname'], GV.report_cfg[i]['hostname'],
                          GV.report_cfg[i]['port'])

        if self.fcatname == 'pg_attribute':
            myprint("        No %s entry for %s column '%s' on %s" \
                     % (self.catname, self.fcatname,self.fkeys['attname'],idstr))
        else:
            myprint("        No %s entry for %s %s on %s" \
                     % (self.catname, self.fcatname,self.fkeys,idstr))

#-------------------------------------------------------------------------------
class CatMissingIssue:

    def __init__(self, catname, pkeys, segids, type ):

        self.catname = catname
        self.pkeys   = pkeys     # string of pkey=xxxx or oid=xxxx 
        self.segids  = segids    # list of affected segids
        self.type    = type      # missing or extra
        assert(self.type in ['missing','extra'])
       
    def report(self):

        ids = [int(i) for i in self.segids[1:-1].split(',')]
        idstr = ''
        if len(ids) == len(GV.report_cfg):
            idstr = 'all segments'
        else:
            for i in ids:
                idstr += '%s (%s:%d) ' % \
                         (GV.report_cfg[i]['segname'], GV.report_cfg[i]['hostname'],
                          GV.report_cfg[i]['port'])

        if self.catname == 'pg_attribute':
            myprint("        %s column '%s' on %s" \
                     % (self.type.capitalize(), self.pkeys['attname'],idstr))
        elif self.catname == 'pg_class':
            myprint('        %s relation metadata for %s on %s' \
                   % (self.type.capitalize(), str(self.pkeys), idstr))
        else:
            myprint('        %s %s metadata of %s on %s' \
                   % (self.type.capitalize(), self.catname[3:], str(self.pkeys), idstr))


#-------------------------------------------------------------------------------
class CatDuplicateIssue:

    def __init__(self, catname, pkeys, segids, enum ):

        self.catname = catname
        self.pkeys   = pkeys     # string of pkey=xxxx or oid=xxxx 
        self.segids  = segids    # list of affected segids
        self.enum    = enum      # number of entries

    def report(self):
        """ Found # catname entries of "oid=XXXXX" on segment {Y,Z} """
        myprint('       Found %d %s entries of %s on segment %s' \
                 % (self.enum, self.catname, str(self.pkeys), str(self.segids)))


#-------------------------------------------------------------------------------
class CatACLIssue:

    def __init__(self, catname, pkeys, segid, macl_only, sacl_only ):

        self.catname    = catname
        self.pkeys      = pkeys       # string of pkey=xxxx or oid=xxxx 
        self.segid      = segid       # the affected segid
        self.macl_only  = macl_only   # acl appears only on master
        self.sacl_only  = sacl_only   # acl appears only on segment

    def report(self):
        """ Master (host:port) and seg# (host:port) have different ACL:
                Exist(s) on master only: [...........]
                Exist(s) on   seg# only: [...........]
        """
        mstr = 'Master (%s:%s)' % (GV.report_cfg[-1]['hostname'],GV.report_cfg[-1]['port'])
        sstr = '%s (%s:%s)' % (GV.report_cfg[self.segid]['segname'],
                               GV.report_cfg[self.segid]['hostname'],
                               GV.report_cfg[self.segid]['port'])
        myprint('        %s and %s have different ACLs:' % (mstr, sstr))
        if len(self.macl_only) > 0:
            myprint('            Exist(s) on master only: %s' % (self.macl_only))
        if len(self.sacl_only) > 0:
            myprint('            Exist(s) on %s only: %s ' % \
                      (GV.report_cfg[self.segid]['segname'], self.sacl_only))
   

#-------------------------------------------------------------------------------
class GPObject:

    def __init__(self, oid, catname):
        self.oid          = oid
        self.catname      = catname
        self.missingIssues      = {} # key=issue.catname, value=list of catMissingIssue
        self.inconsistentIssues = {} # key=issue.catname, value=list of catInconsistentIssue
        self.duplicateIssues    = {} # key=issue.catname, value=list of catDuplicateIssue
        self.aclIssues          = {} # key=issue.catname, value=list of catACLIssue
        self.foreignkeyIssues   = {} # key=issue.catname, value=list of catForeignKeyIssue

    def setMissingIssue(self, issue):
        if issue.catname in self.missingIssues:
            self.missingIssues[issue.catname].append(issue)
        else:
            self.missingIssues[issue.catname] = [issue]

    def setInconsistentIssue(self, issue):
        if issue.catname in self.inconsistentIssues:
            self.inconsistentIssues[issue.catname].append(issue)
        else:
            self.inconsistentIssues[issue.catname] = [issue]

    def setDuplicateIssue(self, issue):
        if issue.catname in self.duplicateIssues:
            self.duplicateIssues[issue.catname].append(issue)
        else:
            self.duplicateIssues[issue.catname] = [issue]

    def setACLIssue(self, issue):
        if issue.catname in self.aclIssues:
            self.aclIssues[issue.catname].append(issue)
        else:
            self.aclIssues[issue.catname] = [issue]

    def setForeignKeyIssue(self, issue):
        if issue.catname in self.foreignkeyIssues:
            self.foreignkeyIssues[issue.catname].append(issue)
        else:
            self.foreignkeyIssues[issue.catname] = [issue]

    def isTopLevel(self):
        return True

    def reportAllIssues(self):
        """
        We want to prevent oids from certain catalog tables to appear on
        stdout. Hence we create a separate function for myprint which
        will log all the oid inconsistencies as WARNING instead of
        CRITICAL in order to log it in the log file.
        """
        def __myprint(string):
            if self.catname in ['pg_constraint']:
                _myprint(string, logging.WARNING)
            else:
                _myprint(string)

        global myprint
        myprint = __myprint

        if self.__class__ == GPObject:
            myprint('')
            myprint('----------------------------------------------------')
            myprint('Object oid: %s' % (self.oid))
            myprint('Table name: %s' % (self.catname))
            myprint('')

        # Report inconsistent issues
        if len(self.inconsistentIssues):
            for catname,issues in self.inconsistentIssues.iteritems():
                myprint('    Name of test which found this issue: inconsistent_%s' % catname)
                for each in issues:
                    each.report()
            myprint('')

        # Report missing issues
        if len(self.missingIssues):
            omitlist = ['pg_attribute','pg_attribute_encoding','pg_type','pg_appendonly','pg_index']
            if 'pg_class' in self.missingIssues:
                myprint('    Name of test which found this issue: missing_extraneous_pg_class')
                for name in omitlist:
                    if name in self.missingIssues:
                        myprint('    Name of test which found this issue: missing_extraneous_%s' % name)
                for each in self.missingIssues['pg_class']:
                    each.report()

                for catname, issues in self.missingIssues.iteritems():
                    if catname != 'pg_class' and catname not in omitlist:
                        myprint('    Name of test which found this issue: missing_extraneous_%s' % catname)
                        for each in issues:
                            each.report()
            else:
                for catname,issues in self.missingIssues.iteritems():
                    myprint('    Name of test which found this issue: missing_extraneous_%s' % catname)
                    for each in issues:
                        each.report()
            myprint('')

        # Report foreign key issues
        if len(self.foreignkeyIssues):
            for catname,issues in self.foreignkeyIssues.iteritems():
                myprint('    Name of test which found this issue: foreign_key_%s' % catname)
                for each in issues:
                    each.report()
            myprint('')

        if len(self.duplicateIssues):
            for catname,issues in self.duplicateIssues.iteritems():
                myprint('    Name of test which found this issue: duplicate_%s' % catname)
                for each in issues:
                    each.report()
            myprint('')

        # Report ACL issues
        if len(self.aclIssues):
            for catname,issues in self.aclIssues.iteritems():
                myprint('    Name of test which found this issue: acl_%s' % catname)
                for each in issues:
                    each.report()
            myprint('')

        myprint = _myprint

    def __cmp__(self, other):
        if isinstance(other, GPObject):
            return cmp((self.oid, self.catname), (other.oid, other.catname))
        else:
            return NotImplemented

    def __hash__(self):
        return hash((self.oid, self.catname))
   

#-------------------------------------------------------------------------------
class RelationObject(GPObject):

    def __init__(self, oid, catname):
        GPObject.__init__(self, oid, catname)
        self.relname = None
        self.nspname = None
        self.relkind = None
        self.paroid = None

    def reportAllIssues(self):
        if self.isTopLevel():
            myprint('')
            myprint('----------------------------------------------------')
            if self.relkind == 'c':
                myprint('Type oid: %d' % (self.oid))
                myprint('Type name: %s.%s' % (self.nspname, self.relname))
            else:
                myprint('Relation oid: %d' % (self.oid))
                myprint('Relation name: %s.%s' % (self.nspname, self.relname))
        else:
            myprint('    Sub-object: ')
            myprint('    ----------------------------------------------------')
            myprint('    Relation oid: %d' % (self.oid))
            myprint('    Relation name: %s.%s' % (self.nspname, self.relname))
        myprint('')
        GPObject.reportAllIssues(self)

    def setRelInfo(self, relname, nspname, relkind, paroid):
        self.relname = relname
        self.nspname = nspname
        self.relkind = relkind
        self.paroid  = paroid

    def isTopLevel(self):
        if self.relkind == 'i' or self.relkind == 't' or self.relkind == 'o':
            return False
        return True


#-------------------------------------------------------------------------------
def getRelInfo(objects):

    # Get relinfo: relname, relkind, par oid for all oids
    #   get relname, relkind
    #   left outer join with union of
    #    - get par oid for toast
    #    - get par oid for aoco
    #    - get par oid for index
    # for each query: if there is inconsistency, majority wins

    if objects == {}: return

    oids = [oid for (oid, catname) in objects if catname=='pg_class']
    if oids == []: return

    qry = """
          SELECT oid, relname, nspname, relkind, paroid
          FROM (
             SELECT oid, relname, nspname, relkind
             FROM (
               SELECT oid, relname, nspname, relkind, rank() over (partition by oid order by count(*) desc)
               FROM
               (
                 SELECT c.oid, c.relname, c.relkind, n.nspname
                 FROM   pg_class c
                        left outer join pg_namespace n
                        on (c.relnamespace = n.oid)
                 WHERE  c.oid in ({oids})
                 UNION ALL
                 SELECT c.oid, c.relname, c.relkind, n.nspname
                 FROM   gp_dist_random('pg_class') c
                        left outer join gp_dist_random('pg_namespace') n
                        on (c.relnamespace = n.oid and c.gp_segment_id = n.gp_segment_id)
                 WHERE  c.oid in ({oids})
               ) allrelinfo
               GROUP BY oid, relname, nspname, relkind
             ) relinfo
             WHERE rank=1
         ) relinfo

         LEFT OUTER JOIN

         (
            SELECT reltoastrelid as childoid, oid as paroid
            FROM (
              SELECT reltoastrelid, oid, rank() over (partition by reltoastrelid order by count(*) desc)
                FROM 
                  ( SELECT reltoastrelid, oid FROM pg_class
                    WHERE reltoastrelid in ({oids})
                    UNION ALL
                    SELECT reltoastrelid, oid FROM gp_dist_random('pg_class')
                    WHERE reltoastrelid in ({oids})
                  ) allpar_toast
               GROUP BY reltoastrelid, oid
            ) par_toast
            WHERE rank=1

            UNION ALL

            SELECT segrelid as childoid, relid as paroid
            FROM (
               SELECT segrelid, relid, rank() over (partition by segrelid order by count(*) desc)
                FROM 
                 ( SELECT segrelid, relid FROM pg_appendonly
                   WHERE segrelid in ({oids})
                   UNION ALL
                   SELECT segrelid, relid FROM gp_dist_random('pg_appendonly')
                   WHERE segrelid in ({oids})
                 ) allpar_aoco
               GROUP BY segrelid, relid
            ) par_aoco
            WHERE rank=1

            UNION ALL 

            SELECT indexrelid as childoid, indrelid as paroid
            FROM (
               SELECT indexrelid, indrelid, rank() over (partition by indexrelid order by count(*) desc)
               FROM 
                ( SELECT indexrelid, indrelid FROM pg_index
                   WHERE  indexrelid in ({oids})
                   UNION ALL
                  SELECT indexrelid, indrelid FROM gp_dist_random('pg_index')
                   WHERE  indexrelid in ({oids})
                ) allpar_index
               GROUP BY indexrelid, indrelid
            ) par_index
            WHERE rank=1
          ) par ON childoid = oid
          """.format( oids = ','.join(map(str,oids)))

    try:
        db = connect2(GV.cfg[1], utilityMode=False)
        curs = db.query(qry)
        for row in curs.getresult():
            (oid, relname, nspname, relkind, paroid) = row
            objects[oid,'pg_class'].setRelInfo(relname, nspname, relkind, paroid)
            
    except Exception, e:
        setError(ERROR_NOREPAIR)
        myprint('  Execution error: ' + str(e))
        myprint(qry)


#-------------------------------------------------------------------------------
def buildGraph():

    def buildGraphRecursive(objects, graph):
        if objects == {}: return
        getRelInfo (objects)
        localObjects = {}
        for (oid, catname),obj in objects.iteritems():
            # Top level object, add to graph
            if obj.isTopLevel():
                if obj not in graph:
                    graph[obj] = []
            # Not top level object, find parent, add to localObjects if needed
            else:
                parobj = objects.get((obj.paroid, catname), None)
                if parobj is None:
                    parobj = localObjects.get((obj.paroid, catname), None)
                    if parobj is None:
                        parobj = RelationObject(obj.paroid, catname)
                        localObjects[(obj.paroid, catname)] = parobj
                assert (parobj is not None)
                # Add obj and parobj to graph
                if parobj not in graph:
                    graph[parobj] = []
                if obj not in graph[parobj]:
                    graph[parobj].append(obj)
        buildGraphRecursive(localObjects, graph)

    buildGraphRecursive(GPObjects, GPObjectGraph)



#-------------------------------------------------------------------------------
def checkcatReport():

    def reportAllIssuesRecursive(par, graph):
        par.reportAllIssues()
        if par not in graph: 
            return
        for child in sorted(graph[par]):
            reportAllIssuesRecursive(child, graph)

    buildGraph()
    reportedTest = ['duplicate','missing_extraneous','inconsistent','foreign_key','acl', 'duplicate_persistent'] 
    myprint('')
    myprint('SUMMARY REPORT')
    myprint('===================================================================')
    elapsed = str(datetime.timedelta(seconds=GV.elapsedTime))[:-4]
    myprint('Total runtime for %d test(s): %s' % (GV.totalTestRun, elapsed))

    if len(GPObjectGraph) == 0 and len(GV.failedTest) == 0:
        myprint('Found no catalog issue\n')
        return
  
    if len(GPObjectGraph) > 0:
        total = 0
        for par in GPObjectGraph:
            if par.isTopLevel() and par.catname not in ['pg_constraint']: total += 1
        if total == 0:
            myprint('Found no catalog issue\n')
            if par.catname in ['pg_constraint']:
                myprint('Warnings were generated, see %s for detail\n' % get_logfile())
        else:
            myprint('Found a total of %d issue(s)' % total)
    
        for par in sorted(GPObjectGraph):
            if par.isTopLevel():
                reportAllIssuesRecursive(par, GPObjectGraph)
        myprint('')

    notReported = set(GV.failedTest).difference(reportedTest)
    if len(notReported) > 0:
        myprint('Failed test(s) that are not reported here: %s' % (', '.join(notReported)))
        myprint('See %s for detail\n' % get_logfile())

def _myprint(str, level=logging.CRITICAL):
    log_literal(logger,level,str)

myprint = _myprint

def generateVerifyFile(catname, fields, results, testname):
    in_clause = reduce(lambda x, y: x + ('' if not x else ',') + str(y[fields.index('oid')]), results, '')
    verify_sql = '''
          SELECT *
          FROM (
               SELECT relname, oid FROM pg_class WHERE reltype IN ({in_clause})
               UNION ALL
               SELECT relname, oid FROM gp_dist_random('pg_class') WHERE reltype IN ({in_clause})
          ) alltyprelids
          GROUP BY relname, oid ORDER BY count(*) desc
    '''.format(in_clause=in_clause)
    filename = 'gpcheckcat.verify.%s.%s.%s.%s.sql' % (GV.dbname, catname, testname, TIMESTAMP)
    try:
        with open(filename, 'w') as fp:
            fp.write(verify_sql + '\n')
    except Exception as e:
        logger.warning('Unable to generate verify file for %s (%s)' % (catname, str(e)))

#############
if __name__ == '__main__':

    parseCommandLine()
    if GV.opt['-l']:
        listAllTests()
        sys.exit(GV.retcode)

    GV.version = getversion()
    if GV.version < "4.0":
        myprint("Error: only Greenplum database version >= 4.0 are supported\n")
        sys.exit(GV.retcode)

    GV.cfg = getGPConfiguration()
    GV.report_cfg = getReportConfiguration()
    GV.max_content = max([GV.cfg[dbid]['content'] for dbid in GV.cfg])
    GV.catalog = getCatalog()

    for dbname in GV.alldb:

        # Reset global variables
        GV.reset_stmt_queues()
        GPObjects = {}
        GPObjectGraph = {} 
        GV.dbname  = dbname

        myprint('')
        myprint("Connected as user \'%s\' to database '%s', port '%d', gpdb version '%s'" \
                   % (GV.opt['-U'], GV.dbname, GV.report_cfg[-1]['port'], GV.version))
        myprint('-------------------------------------------------------------------')
           
        if GV.opt['-R']:
            name = GV.opt['-R']
            try:
                runOneTest(name)
            except LookupError, e:
                myprint("'%s' is not a valid test\n\n" % (name))
                setError(ERROR_NOREPAIR)
                sys.exit(GV.retcode)
        elif GV.opt['-C']:
            namestr = GV.opt['-C']
            try:
                cat = getCatObj(namestr)
                runTestCatname(cat)
            except Exception, e:
                setError(ERROR_NOREPAIR)
                sys.exit(GV.retcode)
        else:
            runAllTests()

        checkcatReport()

        # skip shared tables on subsequent passes
        if not GV.opt['-S']:
            GV.opt['-S'] = "none"

    sys.exit(GV.retcode)