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
|
//////////////////////////////////////////////////////////////////////////
//
// pgAdmin III - PostgreSQL Tools
//
// Copyright (C) 2002 - 2014, The pgAdmin Development Team
// This software is released under the PostgreSQL Licence
//
// ddDBReverseEnginering.cpp - Reverse engineering database functions for database designer.
//
//////////////////////////////////////////////////////////////////////////
#include "pgAdmin3.h"
// wxWindows headers
#include <wx/wx.h>
#include <wx/regex.h>
// App headers
#include "schema/pgSchema.h"
#include "schema/pgDatatype.h"
#include "dd/ddmodel/ddDBReverseEngineering.h"
#include "dd/dditems/figures/ddTableFigure.h"
#include "dd/ddmodel/ddDatabaseDesign.h"
#include "dd/dditems/figures/ddRelationshipFigure.h"
#include "dd/dditems/figures/ddRelationshipItem.h"
#include "dd/dditems/figures/ddRelationshipTerminal.h"
#include "images/namespaces.pngc"
#include "images/namespace-sm.pngc"
#include "images/gqbOrderAddAll.pngc"
#include "images/gqbOrderRemoveAll.pngc"
#include "images/gqbOrderRemove.pngc"
#include "images/gqbOrderAdd.pngc"
BEGIN_EVENT_TABLE(ddDBReverseEngineering, wxWizard)
EVT_WIZARD_FINISHED(wxID_ANY, ddDBReverseEngineering::OnFinishPressed)
END_EVENT_TABLE()
BEGIN_EVENT_TABLE(SelSchemaPage, wxWizardPage)
EVT_WIZARD_PAGE_CHANGING(wxID_ANY, SelSchemaPage::OnWizardPageChanging)
END_EVENT_TABLE()
BEGIN_EVENT_TABLE(SelTablesPage, wxWizardPage)
EVT_BUTTON(DDREMOVE, SelTablesPage::OnButtonRemove)
EVT_BUTTON(DDREMOVEALL, SelTablesPage::OnButtonRemoveAll)
EVT_BUTTON(DDADD, SelTablesPage::OnButtonAdd)
EVT_BUTTON(DDADDALL, SelTablesPage::OnButtonAddAll)
EVT_WIZARD_PAGE_CHANGING(wxID_ANY, SelTablesPage::OnWizardPageChanging)
END_EVENT_TABLE()
BEGIN_EVENT_TABLE(ReportPage, wxWizardPage)
EVT_WIZARD_PAGE_CHANGING(wxID_ANY, ReportPage::OnWizardPageChanging)
END_EVENT_TABLE()
//
//
//
// ----- Stub & reverse engineering classes Implementation
//
//
//
wxArrayString ddImportDBUtils::getTablesNames(pgConn *connection, wxString schemaName)
{
wxArrayString out;
wxString query;
OID schemaOID = ddImportDBUtils::getSchemaOID(connection, schemaName);
// Get the child objects.
query = wxT("SELECT oid, relname, relkind\n")
wxT(" FROM pg_class\n")
wxT(" WHERE relkind IN ('r') AND relnamespace = ") + NumToStr(schemaOID) + wxT(";");
pgSet *tables = connection->ExecuteSet(query);
if (tables)
{
while (!tables->Eof())
{
wxString tmpname = tables->GetVal(wxT("relname"));
wxString relkind = tables->GetVal(wxT("relkind"));
if (relkind == wxT("r")) // Table
{
out.Add(tables->GetVal(wxT("relname")));
}
tables->MoveNext();
}
delete tables;
}
return out;
}
OID ddImportDBUtils::getSchemaOID(pgConn *connection, wxString schemaName)
{
// Search Schemas and insert it
wxString restr = wxT(" WHERE ");
restr += wxT("NOT ");
restr += wxT("((nspname = 'pg_catalog' AND EXISTS (SELECT 1 FROM pg_class WHERE relname = 'pg_class' AND relnamespace = nsp.oid LIMIT 1)) OR\n");
restr += wxT("(nspname = 'pgagent' AND EXISTS (SELECT 1 FROM pg_class WHERE relname = 'pga_job' AND relnamespace = nsp.oid LIMIT 1)) OR\n");
restr += wxT("(nspname = 'information_schema' AND EXISTS (SELECT 1 FROM pg_class WHERE relname = 'tables' AND relnamespace = nsp.oid LIMIT 1)) OR\n");
restr += wxT("(nspname LIKE '_%' AND EXISTS (SELECT 1 FROM pg_proc WHERE proname='slonyversion' AND pronamespace = nsp.oid LIMIT 1)) OR\n");
restr += wxT("(nspname = 'dbo' AND EXISTS (SELECT 1 FROM pg_class WHERE relname = 'systables' AND relnamespace = nsp.oid LIMIT 1)) OR\n");
restr += wxT("(nspname = 'sys' AND EXISTS (SELECT 1 FROM pg_class WHERE relname = 'all_tables' AND relnamespace = nsp.oid LIMIT 1)))\n");
if (connection->EdbMinimumVersion(8, 2))
{
restr += wxT(" AND nsp.nspparent = 0\n");
// Do not show dbms_job_procedure in schemas
if (!settings->GetShowSystemObjects())
restr += wxT("AND NOT (nspname = 'dbms_job_procedure' AND EXISTS(SELECT 1 FROM pg_proc WHERE pronamespace = nsp.oid and proname = 'run_job' LIMIT 1))\n");
}
wxString sql;
if (connection->BackendMinimumVersion(8, 1))
{
sql = wxT("SELECT CASE WHEN nspname LIKE E'pg\\\\_temp\\\\_%' THEN 1\n")
wxT(" WHEN (nspname LIKE E'pg\\\\_%') THEN 0\n");
}
else
{
sql = wxT("SELECT CASE WHEN nspname LIKE 'pg\\\\_temp\\\\_%' THEN 1\n")
wxT(" WHEN (nspname LIKE 'pg\\\\_%') THEN 0\n");
}
sql += wxT(" ELSE 3 END AS nsptyp, nspname, nsp.oid\n")
wxT(" FROM pg_namespace nsp\n")
+ restr + wxT(" AND nspname = '") + schemaName + wxT("' ") +
wxT(" ORDER BY 1, nspname");
pgSet *schemas = connection->ExecuteSet(sql);
int times = 0;
OID schemaOID = -1;
if (schemas)
{
while (!schemas->Eof())
{
wxString name = schemas->GetVal(wxT("nspname"));
long nsptyp = schemas->GetLong(wxT("nsptyp"));
wxStringTokenizer tokens(settings->GetSystemSchemas(), wxT(","));
while (tokens.HasMoreTokens())
{
wxRegEx regex(tokens.GetNextToken());
if (regex.Matches(name))
{
nsptyp = SCHEMATYP_USERSYS;
break;
}
}
if (nsptyp <= SCHEMATYP_USERSYS && !settings->GetShowSystemObjects())
{
schemas->MoveNext();
continue;
}
schemaOID = schemas->GetOid(wxT("oid"));
times++;
schemas->MoveNext();
}
delete schemas;
}
if(times > 1 || schemaOID == -1)
{
wxMessageBox(_("Schema not found"), _("getting table OID"), wxICON_ERROR | wxOK);
return -1;
}
return schemaOID;
}
OID ddImportDBUtils::getTableOID(pgConn *connection, wxString schemaName, wxString tableName)
{
OID schemaOID = ddImportDBUtils::getSchemaOID(connection, schemaName);
wxString query;
OID tableOID = -1;
// Get the child objects.
query = wxT("SELECT oid, relname, relkind\n")
wxT(" FROM pg_class\n")
wxT(" WHERE relkind IN ('r') AND relnamespace = ") + NumToStr(schemaOID) +
wxT(" AND relname = '") + tableName + wxT("';");
pgSet *tables = connection->ExecuteSet(query);
int times;
if (tables)
{
times = 0;
while (!tables->Eof())
{
wxString relkind = tables->GetVal(wxT("relkind"));
if (relkind == wxT("r")) // Table
{
tableOID = tables->GetOid(wxT("oid"));
times++;
}
tables->MoveNext();
}
delete tables;
}
if(times > 1 || tableOID == -1)
{
wxMessageBox(_("Table not found"), _("getting table OID"), wxICON_ERROR | wxOK);
return -1;
}
return tableOID;
}
// Don't support inherited tables right now, or tables where a column is part of more than one Unique Key.
ddStubTable *ddImportDBUtils::getTable(pgConn *connection, wxString tableName, OID tableOid)
{
wxString sql;
int currentcol;
ddStubTable *table = NULL;
ddStubColumn *column = NULL;
// grab inherited tables [if found don't allow table import because this feature isn't supported right now]
sql = wxT("SELECT inhparent::regclass AS inhrelname,\n")
wxT(" (SELECT count(*) FROM pg_attribute WHERE attrelid=inhparent AND attnum>0) AS colscount\n")
wxT(" FROM pg_inherits\n")
wxT(" WHERE inhrelid = ") + NumToStr(tableOid) + wxT("::oid\n")
wxT(" ORDER BY inhseqno");
pgSet *inhtables = connection->ExecuteSet(sql);
if(inhtables && inhtables->Eof())
{
wxString systemRestriction;
systemRestriction = wxT("\n AND att.attnum > 0");
sql =
wxT("SELECT att.*, def.*, pg_catalog.pg_get_expr(def.adbin, def.adrelid) AS defval, CASE WHEN att.attndims > 0 THEN 1 ELSE 0 END AS isarray, format_type(ty.oid,NULL) AS typname, format_type(ty.oid,att.atttypmod) AS displaytypname, tn.nspname as typnspname, et.typname as elemtypname,\n")
wxT(" ty.typstorage AS defaultstorage, cl.relname, na.nspname, att.attstattarget, description, cs.relname AS sername, ns.nspname AS serschema,\n")
wxT(" (SELECT count(1) FROM pg_type t2 WHERE t2.typname=ty.typname) > 1 AS isdup, indkey");
if (connection->BackendMinimumVersion(9, 1))
sql += wxT(",\n coll.collname, nspc.nspname as collnspname");
if (connection->BackendMinimumVersion(8, 5))
sql += wxT(",\n attoptions");
if (connection->BackendMinimumVersion(7, 4))
sql +=
wxT(",\n")
wxT(" EXISTS(SELECT 1 FROM pg_constraint WHERE conrelid=att.attrelid AND contype='f'")
wxT(" AND att.attnum=ANY(conkey)) As isfk");
if (connection->BackendMinimumVersion(9, 1))
{
sql += wxT(",\n(SELECT array_agg(label) FROM pg_seclabels sl1 WHERE sl1.objoid=att.attrelid AND sl1.objsubid=att.attnum) AS labels");
sql += wxT(",\n(SELECT array_agg(provider) FROM pg_seclabels sl2 WHERE sl2.objoid=att.attrelid AND sl2.objsubid=att.attnum) AS providers");
}
sql += wxT("\n")
wxT(" FROM pg_attribute att\n")
wxT(" JOIN pg_type ty ON ty.oid=atttypid\n")
wxT(" JOIN pg_namespace tn ON tn.oid=ty.typnamespace\n")
wxT(" JOIN pg_class cl ON cl.oid=att.attrelid\n")
wxT(" JOIN pg_namespace na ON na.oid=cl.relnamespace\n")
wxT(" LEFT OUTER JOIN pg_type et ON et.oid=ty.typelem\n")
wxT(" LEFT OUTER JOIN pg_attrdef def ON adrelid=att.attrelid AND adnum=att.attnum\n")
wxT(" LEFT OUTER JOIN pg_description des ON des.objoid=att.attrelid AND des.objsubid=att.attnum\n")
wxT(" LEFT OUTER JOIN (pg_depend JOIN pg_class cs ON objid=cs.oid AND cs.relkind='S') ON refobjid=att.attrelid AND refobjsubid=att.attnum\n")
wxT(" LEFT OUTER JOIN pg_namespace ns ON ns.oid=cs.relnamespace\n")
wxT(" LEFT OUTER JOIN pg_index pi ON pi.indrelid=att.attrelid AND indisprimary\n");
if (connection->BackendMinimumVersion(9, 1))
sql += wxT(" LEFT OUTER JOIN pg_collation coll ON att.attcollation=coll.oid\n")
wxT(" LEFT OUTER JOIN pg_namespace nspc ON coll.collnamespace=nspc.oid\n");
sql += wxT(" WHERE att.attrelid = ") + NumToStr(tableOid)
+ systemRestriction + wxT("\n")
wxT(" AND att.attisdropped IS FALSE\n")
wxT(" ORDER BY att.attnum");
table = new ddStubTable(tableName, tableOid);
pgSet *columns = connection->ExecuteSet(sql);
if (columns)
{
currentcol = 0;
while (!columns->Eof())
{
currentcol++;
column = new ddStubColumn(columns->GetVal(wxT("attname")), tableOid);
column->pgColNumber = columns->GetLong(wxT("attnum"));
wxString pkCols = columns->GetVal(wxT("indkey"));
bool isPK = false;
wxStringTokenizer indkey(pkCols);
while (indkey.HasMoreTokens())
{
wxString str = indkey.GetNextToken();
if (StrToLong(str) == column->pgColNumber)
{
isPK = true;
break;
}
}
column->isPrimaryKey = isPK;
long typmod = columns->GetLong(wxT("atttypmod"));
pgDatatype *dt = new pgDatatype(columns->GetVal(wxT("typnspname")), columns->GetVal(wxT("typname")),
columns->GetBool(wxT("isdup")),
columns->GetLong(wxT("attndims")), typmod);
column->typeColumn = dt;
column->isNotNull = columns->GetBool(wxT("attnotnull"));
wxString colName = column->columnName;
table->cols[colName] = column;
columns->MoveNext();
}
delete columns;
}
setUniqueConstraints(connection, table);
setPkName(connection, table);
return table;
}
return table;
}
//true on everything fine, false when some error is found
bool ddImportDBUtils::setUniqueConstraints(pgConn *connection, ddStubTable *table)
{
bool out = true;
//temporary fix, this should be adapted to pgadmin way of working
// check for extended ruleutils with pretty-print option
wxString prettyOption;
wxString exprname = connection->ExecuteScalar(wxT("SELECT proname FROM pg_proc WHERE proname='pg_get_viewdef' AND proargtypes[1]=16"));
if (!exprname.IsEmpty())
prettyOption = wxT(", true");
wxString query;
wxString proname, projoin;
if (connection->BackendMinimumVersion(7, 4))
{
proname = wxT("indnatts, ");
if (connection->BackendMinimumVersion(7, 5))
{
proname += wxT("cls.reltablespace AS spcoid, spcname, ");
projoin = wxT(" LEFT OUTER JOIN pg_tablespace ta on ta.oid=cls.reltablespace\n");
}
}
else
{
proname = wxT("proname, pn.nspname as pronspname, proargtypes, ");
projoin = wxT(" LEFT OUTER JOIN pg_proc pr ON pr.oid=indproc\n")
wxT(" LEFT OUTER JOIN pg_namespace pn ON pn.oid=pr.pronamespace\n");
}
query = wxT("SELECT DISTINCT ON(cls.relname) cls.oid, cls.relname as idxname, indrelid, indkey, indisclustered, indisunique, indisprimary, n.nspname,\n")
wxT(" ") + proname + wxT("tab.relname as tabname, indclass, con.oid AS conoid, CASE contype WHEN 'p' THEN desp.description WHEN 'u' THEN desp.description WHEN 'x' THEN desp.description ELSE des.description END AS description,\n")
wxT(" pg_get_expr(indpred, indrelid") + prettyOption + wxT(") as indconstraint, contype, condeferrable, condeferred, amname\n");
if (connection->BackendMinimumVersion(8, 2))
query += wxT(", substring(array_to_string(cls.reloptions, ',') from 'fillfactor=([0-9]*)') AS fillfactor \n");
query += wxT(" FROM pg_index idx\n")
wxT(" JOIN pg_class cls ON cls.oid=indexrelid\n")
wxT(" JOIN pg_class tab ON tab.oid=indrelid\n")
+ projoin +
wxT(" JOIN pg_namespace n ON n.oid=tab.relnamespace\n")
wxT(" JOIN pg_am am ON am.oid=cls.relam\n")
wxT(" LEFT JOIN pg_depend dep ON (dep.classid = cls.tableoid AND dep.objid = cls.oid AND dep.refobjsubid = '0' AND dep.refclassid=(SELECT oid FROM pg_class WHERE relname='pg_constraint') AND dep.deptype='i')\n")
wxT(" LEFT OUTER JOIN pg_constraint con ON (con.tableoid = dep.refclassid AND con.oid = dep.refobjid)\n")
wxT(" LEFT OUTER JOIN pg_description des ON des.objoid=cls.oid\n")
wxT(" LEFT OUTER JOIN pg_description desp ON (desp.objoid=con.oid AND desp.objsubid = 0)\n")
wxT(" WHERE indrelid = ") + NumToStr(table->OIDTable) + wxT("::oid")
+ wxT(" AND contype='u' ")
+ wxT("\n")
wxT(" ORDER BY cls.relname");
pgSet *indexes = connection->ExecuteSet(query);
int ukIndex = -1;
wxArrayString UniqueKeysNames;
if (indexes)
{
while (!indexes->Eof())
{
ukIndex++;
wxString uniqueKeys = indexes->GetVal(wxT("indkey"));
UniqueKeysNames.Add(indexes->GetVal(wxT("idxname")));
wxStringTokenizer indkey(uniqueKeys);
while (indkey.HasMoreTokens())
{
//Get column number in unique key
wxString str = indkey.GetNextToken();
//look at all columns [change for hashmap in a future if that option is more optimized]
stubColsHashMap::iterator it;
ddStubColumn *item;
for (it = table->cols.begin(); it != table->cols.end(); ++it)
{
wxString key = it->first;
item = it->second;
//If column belong to unique constraint mark it
if (StrToLong(str) == item->pgColNumber)
{
item->uniqueKeyIndex = ukIndex;
}
}
}
indexes->MoveNext();
}
table->UniqueKeysNames = UniqueKeysNames;
delete indexes;
}
return out; //false in a future when detect a column in more than one unique key because this is not supported by database designer right now
}
//true on everything fine, false when some error is found
bool ddImportDBUtils::setPkName(pgConn *connection, ddStubTable *table)
{
bool out = true;
wxString pkName = wxEmptyString;
//temporary fix, this should be adapted to pgadmin way of working
// check for extended ruleutils with pretty-print option
wxString prettyOption;
wxString exprname = connection->ExecuteScalar(wxT("SELECT proname FROM pg_proc WHERE proname='pg_get_viewdef' AND proargtypes[1]=16"));
if (!exprname.IsEmpty())
prettyOption = wxT(", true");
wxString query;
wxString proname, projoin;
if (connection->BackendMinimumVersion(7, 4))
{
proname = wxT("indnatts, ");
if (connection->BackendMinimumVersion(7, 5))
{
proname += wxT("cls.reltablespace AS spcoid, spcname, ");
projoin = wxT(" LEFT OUTER JOIN pg_tablespace ta on ta.oid=cls.reltablespace\n");
}
}
else
{
proname = wxT("proname, pn.nspname as pronspname, proargtypes, ");
projoin = wxT(" LEFT OUTER JOIN pg_proc pr ON pr.oid=indproc\n")
wxT(" LEFT OUTER JOIN pg_namespace pn ON pn.oid=pr.pronamespace\n");
}
query = wxT("SELECT DISTINCT ON(cls.relname) cls.oid, cls.relname as idxname, indrelid, indkey, indisclustered, indisunique, indisprimary, n.nspname,\n")
wxT(" ") + proname + wxT("tab.relname as tabname, indclass, con.oid AS conoid, CASE contype WHEN 'p' THEN desp.description WHEN 'u' THEN desp.description WHEN 'x' THEN desp.description ELSE des.description END AS description,\n")
wxT(" pg_get_expr(indpred, indrelid") + prettyOption + wxT(") as indconstraint, contype, condeferrable, condeferred, amname\n");
if (connection->BackendMinimumVersion(8, 2))
query += wxT(", substring(array_to_string(cls.reloptions, ',') from 'fillfactor=([0-9]*)') AS fillfactor \n");
query += wxT(" FROM pg_index idx\n")
wxT(" JOIN pg_class cls ON cls.oid=indexrelid\n")
wxT(" JOIN pg_class tab ON tab.oid=indrelid\n")
+ projoin +
wxT(" JOIN pg_namespace n ON n.oid=tab.relnamespace\n")
wxT(" JOIN pg_am am ON am.oid=cls.relam\n")
wxT(" LEFT JOIN pg_depend dep ON (dep.classid = cls.tableoid AND dep.objid = cls.oid AND dep.refobjsubid = '0' AND dep.refclassid=(SELECT oid FROM pg_class WHERE relname='pg_constraint') AND dep.deptype='i')\n")
wxT(" LEFT OUTER JOIN pg_constraint con ON (con.tableoid = dep.refclassid AND con.oid = dep.refobjid)\n")
wxT(" LEFT OUTER JOIN pg_description des ON des.objoid=cls.oid\n")
wxT(" LEFT OUTER JOIN pg_description desp ON (desp.objoid=con.oid AND desp.objsubid = 0)\n")
wxT(" WHERE indrelid = ") + NumToStr(table->OIDTable) + wxT("::oid")
+ wxT(" AND contype='p' ")
+ wxT("\n")
wxT(" ORDER BY cls.relname");
pgSet *indexes = connection->ExecuteSet(query);
if (indexes)
{
while (!indexes->Eof())
{
pkName = indexes->GetVal(wxT("idxname"));
indexes->MoveNext();
}
delete indexes;
}
table->PrimaryKeyName = pkName;
return out; //false in a future when detect a column in more than one unique key because this is not supported by database designer right now
}
void ddImportDBUtils::getAllRelationships(pgConn *connection, stubTablesHashMap &tables, ddDatabaseDesign *design)
{
wxString sql;
ddRelationshipFigure *relation = NULL;
ddTableFigure *sourceTabFigure = NULL;
ddTableFigure *destTabFigure = NULL;
//Add Tables to the Model
stubTablesHashMap::iterator mainIt;
ddStubTable *destStubTable = NULL;
for (mainIt = tables.begin(); mainIt != tables.end(); ++mainIt)
{
wxString key = mainIt->first;
destStubTable = mainIt->second;
sql = wxT("SELECT ct.oid, conname, condeferrable, condeferred, confupdtype, confdeltype, confmatchtype, ")
wxT("conkey, confkey, confrelid, nl.nspname as fknsp, cl.relname as fktab, ")
wxT("nr.nspname as refnsp, cr.relname as reftab, description");
if (connection->BackendMinimumVersion(9, 1))
sql += wxT(", convalidated");
sql += wxT("\n FROM pg_constraint ct\n")
wxT(" JOIN pg_class cl ON cl.oid=conrelid\n")
wxT(" JOIN pg_namespace nl ON nl.oid=cl.relnamespace\n")
wxT(" JOIN pg_class cr ON cr.oid=confrelid\n")
wxT(" JOIN pg_namespace nr ON nr.oid=cr.relnamespace\n")
wxT(" LEFT OUTER JOIN pg_description des ON des.objoid=ct.oid\n")
wxT(" WHERE contype='f' AND conrelid = ") + NumToStr(destStubTable->OIDTable) + wxT("::oid")
//+ restriction +
+ wxT("\n")
wxT(" ORDER BY conname");
pgSet *foreignKeys = connection->ExecuteSet(sql);
if (foreignKeys && foreignKeys->NumRows() > 0)
{
while (!foreignKeys->Eof())
{
wxString sourceSchema, destSchema;
sourceSchema = foreignKeys->GetVal(wxT("refnsp"));
destSchema = foreignKeys->GetVal(wxT("fknsp"));
// Source Table ----------------------<| Destination Table
if(sourceSchema.IsSameAs(destSchema, false))
{
wxString sourceTableName = foreignKeys->GetVal(wxT("reftab"));
wxString destTableName = foreignKeys->GetVal(wxT("fktab"));
destTabFigure = design->getTable(destTableName);
sourceTabFigure = design->getTable(sourceTableName);
//Only if both tables were imported at same time
if(destTabFigure != NULL && sourceTabFigure != NULL)
{
int ukindex = -1; //Only Supporting foreign keys from PK right now when importing model
wxString RelationshipName = foreignKeys->GetVal(wxT("conname"));
wxString onUpd = foreignKeys->GetVal(wxT("confupdtype"));
actionKind onUpdate = onUpd.IsSameAs('a') ? FK_ACTION_NO :
onUpd.IsSameAs('r') ? FK_RESTRICT :
onUpd.IsSameAs('c') ? FK_CASCADE :
onUpd.IsSameAs('d') ? FK_SETDEFAULT :
onUpd.IsSameAs('n') ? FK_SETNULL : FK_ACTION_NO;
wxString onDel = foreignKeys->GetVal(wxT("confdeltype"));
actionKind onDelete = onUpd.IsSameAs('a') ? FK_ACTION_NO :
onUpd.IsSameAs('r') ? FK_RESTRICT :
onUpd.IsSameAs('c') ? FK_CASCADE :
onUpd.IsSameAs('d') ? FK_SETDEFAULT :
onUpd.IsSameAs('n') ? FK_SETNULL : FK_ACTION_NO;
wxString match = foreignKeys->GetVal(wxT("confmatchtype"));
bool matchSimple = match.IsSameAs('f') ? false :
match.IsSameAs('u') ? true : false;
//------ Preparing metada to allow discovery of some relationship attributes
//Source table columns
wxString fkColsSourceTable = foreignKeys->GetVal(wxT("confkey"));
//remove {} of string
fkColsSourceTable.Remove(0, 1);
fkColsSourceTable.RemoveLast();
wxString fkColsDestTable = foreignKeys->GetVal(wxT("conkey"));
//remove {} of string
fkColsDestTable.Remove(0, 1);
fkColsDestTable.RemoveLast();
wxSortedArrayInt sourceFkCols(sortFunc);
wxSortedArrayInt destFkCols(sortFunc);
wxSortedArrayInt sourcePKs(sortFunc);
wxSortedArrayInt destPKs(sortFunc);
//Split columns from sourceFk
wxStringTokenizer confkey(fkColsSourceTable);
while (confkey.HasMoreTokens())
{
wxString str = confkey.GetNextToken();
sourceFkCols.Add(StrToLong(str));
}
//Split columns from destFk
wxStringTokenizer conkey(fkColsDestTable);
while (conkey.HasMoreTokens())
{
wxString str = conkey.GetNextToken();
destFkCols.Add(StrToLong(str));
}
//Get Stub of source table
ddStubTable *sourceStubTable = tables[sourceTableName];
//Get PK columns of source
stubColsHashMap::iterator it;
ddStubColumn *column;
for (it = sourceStubTable->cols.begin(); it != sourceStubTable->cols.end(); ++it)
{
wxString key = it->first;
column = it->second;
if(column->isPrimaryKey)
sourcePKs.Add(column->pgColNumber);
}
//Get PK columns of dest
for (it = destStubTable->cols.begin(); it != destStubTable->cols.end(); ++it)
{
wxString key = it->first;
column = it->second;
if(column->isPrimaryKey)
destPKs.Add(column->pgColNumber);
}
// Source Table ----------------------<| Destination Table
//Default assumption is the source of this fk is a Primary Key.
bool fkFromPk = true;
//first check: number of columns used as fk at Source is the same of the pk at Source
if(sourceFkCols.Count() == sourcePKs.Count())
{
int i;
//Because postgres columns numbers are stored in an ordered array,
//their index should be the same at all positions
int srcFkCount = sourceFkCols.Count();
for(i = 0; i < srcFkCount; i++)
{
if( sourceFkCols[i] != sourcePKs[i] )
{
fkFromPk = false;
break;
}
}
}
else
{
fkFromPk = true;
}
//------ Finding fk from uk or pk?
int ukIndex = -1;
//if fkFromPk = false then is fkfromUK?, check that
//all source fk columns should belong to one Uk at source table.
if( fkFromPk == false )
{
bool error = false;
int baseColNumber = sourceFkCols[sourceFkCols.Count() - 1];
int baseUkIdxSourceCol = sourceStubTable->getColumnByNumber(baseColNumber)->uniqueKeyIndex;
int nextColNumber, nextUkIdxSourceCol;
int countSrcFkCols = sourceFkCols.Count() - 2;
while(countSrcFkCols >= 0)
{
nextColNumber = sourceFkCols[countSrcFkCols];
nextUkIdxSourceCol = sourceStubTable->getColumnByNumber(nextColNumber)->uniqueKeyIndex;
countSrcFkCols--;
if(baseUkIdxSourceCol != nextUkIdxSourceCol)
{
error = true;
wxMessageBox(_("Error detecting kind of foreign key source: from Pk or from Uk"), _("Error importing relationship"), wxICON_ERROR | wxOK);
return;
}
}
if(!error)
{
ukIndex = baseUkIdxSourceCol;
}
}
//Last check of consistency
if(fkFromPk == false && ukIndex < 0)
{
wxMessageBox(_("Error detecting kind of foreign key source: from Pk or from Uk"), _("Error importing relationship"), wxICON_ERROR | wxOK);
return;
}
//------ identifying relationship or not -----|-<|?
//Default assumption is relationship is identifying
bool identifying = true;
//first check: number of columns used as fk at Source is the same of the pk at Source
if(destFkCols.Count() == destPKs.Count())
{
int i;
//Because postgres columns numbers are stored in an ordered array,
//their index should be the same at all positions
int destFkCount = destFkCols.Count();
for(i = 0; i < destFkCount; i++)
{
if( destFkCols[i] != destPKs[i] )
{
identifying = false;
break;
}
}
}
else
{
identifying = false;
}
//------ 1:1 or 1:M ? as a fact 1:1 have a fk,uk at destination table.
// A foreign key have an one to many relationship when there is an UK for same column(s)
// inside the foreign key. Assumption, a column on belong to one Uk (no more than one).
bool oneToMany = true;
int baseColNumber = destFkCols[destFkCols.Count() - 1];
int baseUkIdxDestCol = destStubTable->getColumnByNumber(baseColNumber)->uniqueKeyIndex;
if(baseUkIdxDestCol != -1)
{
oneToMany = false;
int nextUkIdxDestCol, nextColNumber;
int countDestFkCols = destFkCols.Count() - 2;
while(countDestFkCols >= 0)
{
nextColNumber = destFkCols[countDestFkCols];
nextUkIdxDestCol = destStubTable->getColumnByNumber(nextColNumber)->uniqueKeyIndex;
countDestFkCols--;
//if a dest fk column is not in the same Uk index of first one
if(nextUkIdxDestCol != baseUkIdxDestCol)
{
oneToMany = true;
break;
}
}
}
//Step two check all column of fk are inside a unique key (all and not more)
if(oneToMany == false) //assumption is 1:1 relationship until now
{
int numberColsInUk = 0, nextUkIdxDestCol, nextColNumber;
ddStubColumn *item;
for (it = destStubTable->cols.begin(); it != destStubTable->cols.end(); ++it)
{
wxString key = it->first;
item = it->second;
//at each column with same uk index that base comparison column, count it
nextColNumber = item->pgColNumber;
nextUkIdxDestCol = destStubTable->getColumnByNumber(nextColNumber)->uniqueKeyIndex;
if( nextUkIdxDestCol == baseUkIdxDestCol)
{
numberColsInUk++;
}
}
//number of columns in uk used by relationship is bigger or lesser than number of columns
//in destination table used by relationship as fk dest(dest fk columnn), then is not 1:1
if(numberColsInUk != destFkCols.Count())
oneToMany = true;
}
//Optional or Mandatory consistency
bool mandatoryRelationship;
int countDestFkCols = destFkCols.Count() - 1;
bool isNotNull;
int nnCols = 0, nullCols = 0, nextColNumber;
while(countDestFkCols >= 0)
{
nextColNumber = destFkCols[countDestFkCols];
isNotNull = destStubTable->getColumnByNumber(nextColNumber)->isNotNull;
countDestFkCols--;
if(isNotNull)
nnCols++;
else
nullCols++;
}
if(nnCols == 0 && nullCols > 0)
{
mandatoryRelationship = false;
}
else if(nnCols > 0 && nullCols == 0)
{
mandatoryRelationship = true;
}
else
{
wxMessageBox(_("Error detecting kind of foreign key: null or not null"), _("Error importing relationship"), wxICON_ERROR | wxOK);
return;
}
relation = new ddRelationshipFigure();
relation->setStartTerminal(new ddRelationshipTerminal(relation, false));
relation->setEndTerminal(new ddRelationshipTerminal(relation, true));
relation->clearPoints(0);
relation->initRelationValues(sourceTabFigure, destTabFigure, ukIndex, RelationshipName, onUpdate, onDelete, matchSimple, identifying, oneToMany, mandatoryRelationship, fkFromPk);
relation->updateConnection(0);
design->addTableToModel(relation);
//Add items to relationship
wxString srcColName, destColName;
ddColumnFigure *sourceCol = NULL, *destinationCol = NULL;
bool autoGenFk = false;
wxString initialColName;
ddRelationshipItem *item = NULL;
int i, srcFkCount = sourceFkCols.Count();
for(i = 0; i < srcFkCount ; i++)
{
srcColName = sourceStubTable->getColumnByNumber(sourceFkCols[i])->columnName;
destColName = destStubTable->getColumnByNumber(destFkCols[i])->columnName;
sourceCol = sourceTabFigure->getColByName(srcColName);
destinationCol = destTabFigure->getColByName(destColName);
initialColName = srcColName;
item = new ddRelationshipItem();
item->initRelationshipItemValues(relation, destTabFigure, autoGenFk, destinationCol, sourceCol, initialColName);
relation->getItemsHashMap()[item->original->getColumnName()] = item;
}
}
}
foreignKeys->MoveNext();
}
delete foreignKeys;
}
}
}
bool ddImportDBUtils::existsFk(pgConn *connection, OID destTableOid, wxString schemaName, wxString fkName, wxString sourceTableName)
{
wxString sql;
OID sourceOID = getTableOID(connection, schemaName, sourceTableName);
if(sourceOID == -1 )
{
return false;
}
sql = wxT("SELECT ct.oid, conname, condeferrable, condeferred, confupdtype, confdeltype, confmatchtype, ")
wxT("conkey, confkey, confrelid, nl.nspname as fknsp, cl.relname as fktab, ")
wxT("nr.nspname as refnsp, cr.relname as reftab, description");
if (connection->BackendMinimumVersion(9, 1))
sql += wxT(", convalidated");
sql += wxT("\n FROM pg_constraint ct\n")
wxT(" JOIN pg_class cl ON cl.oid=conrelid\n")
wxT(" JOIN pg_namespace nl ON nl.oid=cl.relnamespace\n")
wxT(" JOIN pg_class cr ON cr.oid=confrelid\n")
wxT(" JOIN pg_namespace nr ON nr.oid=cr.relnamespace\n")
wxT(" LEFT OUTER JOIN pg_description des ON des.objoid=ct.oid\n")
wxT(" WHERE contype='f' AND conrelid = ") + NumToStr(destTableOid) + wxT("::oid")
wxT(" AND conname ='") + fkName + wxT("' ")
wxT(" AND confrelid = ") + NumToStr(sourceOID) + wxT("::oid")
wxT("\n")
wxT(" ORDER BY conname");
pgSet *foreignKeys = connection->ExecuteSet(sql);
//relation don't exists then
if(foreignKeys->NumRows() == 0)
{
return false;
}
delete foreignKeys;
return true;
}
int ddImportDBUtils::getPgColumnNum(pgConn *connection, wxString schemaName, wxString tableName, wxString columnName)
{
int out = -1;
wxString sql;
OID tableOid = getTableOID(connection, schemaName, tableName);
wxString systemRestriction;
systemRestriction = wxT("\n AND att.attnum > 0");
sql = wxT("SELECT att.attrelid,att.attname, att.attnum ")
wxT("\n")
wxT(" FROM pg_attribute att\n")
wxT(" JOIN pg_type ty ON ty.oid=atttypid\n")
wxT(" JOIN pg_namespace tn ON tn.oid=ty.typnamespace\n")
wxT(" JOIN pg_class cl ON cl.oid=att.attrelid\n")
wxT(" JOIN pg_namespace na ON na.oid=cl.relnamespace\n")
wxT(" LEFT OUTER JOIN pg_type et ON et.oid=ty.typelem\n")
wxT(" LEFT OUTER JOIN pg_attrdef def ON adrelid=att.attrelid AND adnum=att.attnum\n")
wxT(" LEFT OUTER JOIN pg_description des ON des.objoid=att.attrelid AND des.objsubid=att.attnum\n")
wxT(" LEFT OUTER JOIN (pg_depend JOIN pg_class cs ON objid=cs.oid AND cs.relkind='S') ON refobjid=att.attrelid AND refobjsubid=att.attnum\n")
wxT(" LEFT OUTER JOIN pg_namespace ns ON ns.oid=cs.relnamespace\n")
wxT(" LEFT OUTER JOIN pg_index pi ON pi.indrelid=att.attrelid AND indisprimary\n");
if (connection->BackendMinimumVersion(9, 1))
sql += wxT(" LEFT OUTER JOIN pg_collation coll ON att.attcollation=coll.oid\n")
wxT(" LEFT OUTER JOIN pg_namespace nspc ON coll.collnamespace=nspc.oid\n");
sql += wxT(" WHERE att.attrelid = ") + NumToStr(tableOid)
+ systemRestriction + wxT("\n")
wxT(" AND att.attisdropped IS FALSE\n")
wxT(" ORDER BY att.attnum");
pgSet *columns = connection->ExecuteSet(sql);
if (columns)
{
while (!columns->Eof())
{
wxString colName = columns->GetVal(wxT("attname"));
if(colName.IsSameAs(columnName, false))
{
out = columns->GetLong(wxT("attnum"));
break;
}
columns->MoveNext();
}
delete columns;
}
return out;
}
wxArrayString ddImportDBUtils::getFkAtDbNotInModel(pgConn *connection, OID destTableOid, wxString schemaName, wxArrayString existingFkList, ddDatabaseDesign *design)
{
wxArrayString out;
wxString sql;
sql = wxT("SELECT ct.oid, conname, condeferrable, condeferred, confupdtype, confdeltype, confmatchtype, ")
wxT("conkey, confkey, confrelid, nl.nspname as fknsp, cl.relname as fktab, ")
wxT("nr.nspname as refnsp, cr.relname as reftab, description");
if (connection->BackendMinimumVersion(9, 1))
sql += wxT(", convalidated");
sql += wxT("\n FROM pg_constraint ct\n")
wxT(" JOIN pg_class cl ON cl.oid=conrelid\n")
wxT(" JOIN pg_namespace nl ON nl.oid=cl.relnamespace\n")
wxT(" JOIN pg_class cr ON cr.oid=confrelid\n")
wxT(" JOIN pg_namespace nr ON nr.oid=cr.relnamespace\n")
wxT(" LEFT OUTER JOIN pg_description des ON des.objoid=ct.oid\n")
wxT(" WHERE contype='f' AND conrelid = ") + NumToStr(destTableOid) + wxT("::oid");
//Add Fk names in model
int i, max = existingFkList.Count();
if(max > 0)
{
sql += wxT(" AND conname NOT IN( ");
for(i = 0; i < max - 1; i++)
{
sql += wxT("'") + existingFkList[i] + wxT("',");
}
if(max >= 1)
{
sql += wxT("'") + existingFkList[max - 1] + wxT("'");
}
sql += wxT(" ) ");
}
//Add valid tables sources names to search (others outside a model shouldn't be modified)
sql += wxT("\n ORDER BY conname");
pgSet *foreignKeys = connection->ExecuteSet(sql);
if (foreignKeys && foreignKeys->NumRows() > 0)
{
while (!foreignKeys->Eof())
{
//Create a list will all relationships in db but not in model [but only for tables IN MODEL because tables not in model SHOULDN'T BE modified]
wxString sourceTableName = foreignKeys->GetVal(wxT("reftab"));
if(design->getTable(sourceTableName))
{
wxString RelationshipName = foreignKeys->GetVal(wxT("conname"));
out.Add(RelationshipName);
}
foreignKeys->MoveNext();
}
delete foreignKeys;
}
//return a list with Fks to delete from db because don't exists at model.
return out;
}
//Assumption Fk exists, and this should be checked before with existsFk function
bool ddImportDBUtils::isModelSameDbFk(pgConn *connection, OID destTableOid, wxString schemaName, wxString fkName, wxString sourceTableName, wxString destTableName, ddStubTable *destStubTable, ddRelationshipFigure *relation)
{
bool equalFk = true;
wxString sql;
OID sourceOID = getTableOID(connection, schemaName, sourceTableName);
sql = wxT("SELECT ct.oid, conname, condeferrable, condeferred, confupdtype, confdeltype, confmatchtype, ")
wxT("conkey, confkey, confrelid, nl.nspname as fknsp, cl.relname as fktab, ")
wxT("nr.nspname as refnsp, cr.relname as reftab, description");
if (connection->BackendMinimumVersion(9, 1))
sql += wxT(", convalidated");
sql += wxT("\n FROM pg_constraint ct\n")
wxT(" JOIN pg_class cl ON cl.oid=conrelid\n")
wxT(" JOIN pg_namespace nl ON nl.oid=cl.relnamespace\n")
wxT(" JOIN pg_class cr ON cr.oid=confrelid\n")
wxT(" JOIN pg_namespace nr ON nr.oid=cr.relnamespace\n")
wxT(" LEFT OUTER JOIN pg_description des ON des.objoid=ct.oid\n")
wxT(" WHERE contype='f' AND conrelid = ") + NumToStr(destTableOid) + wxT("::oid")
wxT(" AND conname ='") + fkName + wxT("' ")
wxT(" AND confrelid = ") + NumToStr(sourceOID) + wxT("::oid")
wxT("\n")
wxT(" ORDER BY conname");
pgSet *foreignKeys = connection->ExecuteSet(sql);
//First Step create array with columns from pgCol numbers from destTable (MODEL) in relationship;
//Second Step create array with columns from pgCol numbers from srcTable (MODEL) in relationship;
wxSortedArrayInt destPgs(sortFunc);
wxSortedArrayInt srcPgs(sortFunc);
columnsHashMap::iterator it;
ddRelationshipItem *item;
for (it = relation->getItemsHashMap().begin(); it != relation->getItemsHashMap().end(); ++it)
{
wxString key = it->first;
item = it->second;
int pgColDest = getPgColumnNum(connection, schemaName, destTableName, item->fkColumn->getColumnName());
destPgs.Add(pgColDest);
int pgColSrc = getPgColumnNum(connection, schemaName, sourceTableName, item->original->getColumnName());
srcPgs.Add(pgColSrc);
}
//Extracting relationship metadata information from DB relationship
int ukindex = -1; //Only Supporting foreign keys from PK right now when importing model
wxString RelationshipName;
actionKind onUpdate;
actionKind onDelete;
bool matchSimple;
bool identifying = true; //Default assumption is relationship is identifying
bool oneToMany = true;
bool mandatoryRelationship;
bool fkFromPk = true; //Default assumption is the source of this fk is a Primary Key.
wxSortedArrayInt sourceFkCols(sortFunc);
wxSortedArrayInt destFkCols(sortFunc);
if (foreignKeys && foreignKeys->NumRows() == 1)
{
while (!foreignKeys->Eof())
{
//------ Preparing metada to allow discovery of some relationship attributes
RelationshipName = foreignKeys->GetVal(wxT("conname"));
wxString onUpd = foreignKeys->GetVal(wxT("confupdtype"));
onUpdate = onUpd.IsSameAs('a') ? FK_ACTION_NO :
onUpd.IsSameAs('r') ? FK_RESTRICT :
onUpd.IsSameAs('c') ? FK_CASCADE :
onUpd.IsSameAs('d') ? FK_SETDEFAULT :
onUpd.IsSameAs('n') ? FK_SETNULL : FK_ACTION_NO;
wxString onDel = foreignKeys->GetVal(wxT("confdeltype"));
onDelete = onUpd.IsSameAs('a') ? FK_ACTION_NO :
onUpd.IsSameAs('r') ? FK_RESTRICT :
onUpd.IsSameAs('c') ? FK_CASCADE :
onUpd.IsSameAs('d') ? FK_SETDEFAULT :
onUpd.IsSameAs('n') ? FK_SETNULL : FK_ACTION_NO;
wxString match = foreignKeys->GetVal(wxT("confmatchtype"));
matchSimple = match.IsSameAs('f') ? false :
match.IsSameAs('u') ? true : false;
//------ Preparing metada to allow discovery of some relationship attributes
//Source table columns
wxString fkColsSourceTable = foreignKeys->GetVal(wxT("confkey"));
wxSortedArrayInt sourcePKs(sortFunc);
wxSortedArrayInt destPKs(sortFunc);
//remove {} of string
fkColsSourceTable.Remove(0, 1);
fkColsSourceTable.RemoveLast();
wxString fkColsDestTable = foreignKeys->GetVal(wxT("conkey"));
//remove {} of string
fkColsDestTable.Remove(0, 1);
fkColsDestTable.RemoveLast();
//Separe columns from sourceFk
wxStringTokenizer confkey(fkColsSourceTable);
while (confkey.HasMoreTokens())
{
wxString str = confkey.GetNextToken();
sourceFkCols.Add(StrToLong(str));
}
//Separe columns from destFk
wxStringTokenizer conkey(fkColsDestTable);
while (conkey.HasMoreTokens())
{
wxString str = conkey.GetNextToken();
destFkCols.Add(StrToLong(str));
}
//Get Stub of source table
ddStubTable *sourceStubTable = ddImportDBUtils::getTable(connection, sourceTableName, sourceOID);
//Get PK columns of source
stubColsHashMap::iterator it;
ddStubColumn *column;
for (it = sourceStubTable->cols.begin(); it != sourceStubTable->cols.end(); ++it)
{
wxString key = it->first;
column = it->second;
if(column->isPrimaryKey)
sourcePKs.Add(column->pgColNumber);
}
//Get PK columns of dest
for (it = destStubTable->cols.begin(); it != destStubTable->cols.end(); ++it)
{
wxString key = it->first;
column = it->second;
if(column->isPrimaryKey)
destPKs.Add(column->pgColNumber);
}
// Source Table ----------------------<| Destination Table
//first check: number of columns used as fk at Source is the same of the pk at Source
if(sourceFkCols.Count() == sourcePKs.Count())
{
int i;
//Because postgres columns numbers are stored in an ordered array,
//their index should be the same at all positions
int srcFkCount = sourceFkCols.Count();
for(i = 0; i < srcFkCount; i++)
{
if( sourceFkCols[i] != sourcePKs[i] )
{
fkFromPk = false;
break;
}
}
}
else
{
fkFromPk = true;
}
//------ Finding fk from uk or pk?
int ukIndex = -1;
//if fkFromPk = false then is fkfromUK?, check that
//all source fk columns should belong to one Uk at source table.
if( fkFromPk == false )
{
bool error = false;
int baseColNumber = sourceFkCols[sourceFkCols.Count() - 1];
int baseUkIdxSourceCol = sourceStubTable->getColumnByNumber(baseColNumber)->uniqueKeyIndex;
int nextColNumber, nextUkIdxSourceCol;
int countSrcFkCols = sourceFkCols.Count() - 2;
while(countSrcFkCols >= 0)
{
nextColNumber = sourceFkCols[countSrcFkCols];
nextUkIdxSourceCol = sourceStubTable->getColumnByNumber(nextColNumber)->uniqueKeyIndex;
countSrcFkCols--;
if(baseUkIdxSourceCol != nextUkIdxSourceCol)
{
error = true;
wxMessageBox(_("Error detecting kind of foreign key source: from Pk or from Uk"), _("Error importing relationship"), wxICON_ERROR | wxOK);
return false;
}
}
if(!error)
{
ukIndex = baseUkIdxSourceCol;
}
}
//Last check of consistency
if(fkFromPk == false && ukIndex < 0)
{
wxMessageBox(_("Error detecting kind of foreign key source: from Pk or from Uk"), _("Error importing relationship"), wxICON_ERROR | wxOK);
return false;
}
//------ identifying relationship or not -----|-<|?
//first check: number of columns used as fk at Source is the same of the pk at Source
if(destFkCols.Count() == destPKs.Count())
{
int i;
//Because postgres columns numbers are stored in an ordered array,
//their index should be the same at all positions
int destFkCount = destFkCols.Count();
for(i = 0; i < destFkCount; i++)
{
if( destFkCols[i] != destPKs[i] )
{
identifying = false;
break;
}
}
}
else
{
identifying = false;
}
//------ 1:1 or 1:M ? as a fact 1:1 have a fk,uk at destination table.
// A foreign key have an one to many relationship when there is an UK for same column(s)
// inside the foreign key. Assumption, a column on belong to one Uk (no more than one).
int baseColNumber = destFkCols[destFkCols.Count() - 1];
int baseUkIdxDestCol = destStubTable->getColumnByNumber(baseColNumber)->uniqueKeyIndex;
if(baseUkIdxDestCol != -1)
{
oneToMany = false;
int nextUkIdxDestCol, nextColNumber;
int countDestFkCols = destFkCols.Count() - 2;
while(countDestFkCols >= 0)
{
nextColNumber = destFkCols[countDestFkCols];
nextUkIdxDestCol = destStubTable->getColumnByNumber(nextColNumber)->uniqueKeyIndex;
countDestFkCols--;
//if a dest fk column is not in the same Uk index of first one
if(nextUkIdxDestCol != baseUkIdxDestCol)
{
oneToMany = true;
break;
}
}
}
//Step two check all column of fk are inside a unique key (all and not more)
if(oneToMany == false) //assumption is 1:1 relationship until now
{
int numberColsInUk = 0, nextUkIdxDestCol, nextColNumber;
ddStubColumn *item;
for (it = destStubTable->cols.begin(); it != destStubTable->cols.end(); ++it)
{
wxString key = it->first;
item = it->second;
//at each column with same uk index that base comparison column, count it
nextColNumber = item->pgColNumber;
nextUkIdxDestCol = destStubTable->getColumnByNumber(nextColNumber)->uniqueKeyIndex;
if( nextUkIdxDestCol == baseUkIdxDestCol)
{
numberColsInUk++;
}
}
//number of columns in uk used by relationship is bigger or lesser than number of columns
//in destination table used by relationship as fk dest(dest fk columnn), then is not 1:1
if(numberColsInUk != destFkCols.Count())
oneToMany = true;
}
//Optional or Mandatory consistency
int countDestFkCols = destFkCols.Count() - 1;
bool isNotNull;
int nnCols = 0, nullCols = 0, nextColNumber;
while(countDestFkCols >= 0)
{
nextColNumber = destFkCols[countDestFkCols];
isNotNull = destStubTable->getColumnByNumber(nextColNumber)->isNotNull;
countDestFkCols--;
if(isNotNull)
nnCols++;
else
nullCols++;
}
if(nnCols == 0 && nullCols > 0)
{
mandatoryRelationship = false;
}
else if(nnCols > 0 && nullCols == 0)
{
mandatoryRelationship = true;
}
else
{
wxMessageBox(_("Error detecting kind of foreign key: null or not null"), _("Error importing relationship"), wxICON_ERROR | wxOK);
return false;
}
delete sourceStubTable;
foreignKeys->MoveNext();
}
//After collection db info compare with model info
//Is safe to check if this UKindex is the same Ukindex of relationship because both aren't equal.
//Before should by unified by same uk index like in comparing uk at table figure class
//Todo in a future
//relation is fromPk in model and db?
if(fkFromPk && !relation->isForeignKeyFromPk())
equalFk = false;
//OnUpdateAction is the same kind?
if(onUpdate != relation->getOnUpdateAction())
equalFk = false;
//OnDeleteAction is the same kind?
if(onDelete != relation->getOnDeleteAction())
equalFk = false;
//Are same match kind
if(matchSimple != relation->getMatchSimple())
equalFk = false;
//are both identifying?
if(identifying != relation->getIdentifying())
equalFk = false;
//are both 1:1 or 1:M
if(oneToMany != relation->getOneToMany())
equalFk = false;
//Mandatory value is the same?
if(mandatoryRelationship != relation->getMandatory())
equalFk = false;
//Columns at both arrays: created from model and created from db are supposed to have same number of item
//if not fk has changed.
//Number of source fk columns at DB is the same number of source fk columns at model
if(sourceFkCols.Count() != srcPgs.Count())
equalFk = false;
//Number of destination fk columns at DB is the same number of destination fk columns at model
if(destFkCols.Count() != destPgs.Count())
equalFk = false;
//Now because arrays are sorted they numbers should match exactly (same pg column number)
int i, max = sourceFkCols.Count();
for(i = 0; i < max; i++)
{
if(sourceFkCols[i] != srcPgs[i])
equalFk = false;
}
max = destFkCols.Count();
for(i = 0; i < max; i++)
{
if(destFkCols[i] != destPgs[i])
equalFk = false;
}
return equalFk;
}
else
{
wxMessageBox(_("Error fk is repeated"), _("Error comparing relationships"), wxICON_ERROR | wxOK);
}
delete foreignKeys;
return equalFk;
}
ddTableFigure *ddImportDBUtils::getTableFigure(ddStubTable *table)
{
wxString name = table->tableName;
ddTableFigure *tableFigure = new ddTableFigure(name, -1, -1);
if(tableFigure != NULL)
{
//Default Values
int colsRowsSize = 0;
int colsWindow = 0;
int idxsRowsSize = 0;
int idxsWindow = 0;
int maxColIndex = 2;
int minIdxIndex = 2;
int maxIdxIndex = 2;
int beginDrawCols = 2;
int beginDrawIdxs = 2;
tableFigure->InitTableValues(table->UniqueKeysNames, table->PrimaryKeyName, beginDrawCols, beginDrawIdxs, maxColIndex, minIdxIndex, maxIdxIndex, colsRowsSize, colsWindow, idxsRowsSize, idxsWindow);
//Add Columns to Table
stubColsHashMap::iterator it;
ddStubColumn *item;
for (it = table->cols.begin(); it != table->cols.end(); ++it)
{
wxString key = it->first;
item = it->second;
ddColumnOptionType option = item->isNotNull ? notnull : null;
bool generateFkName = false; //Not automatic names will be used by default at user imported tables.
wxString dataType = item->typeColumn->Name();
//temporary conversion fix to datatype of designer should be improved in a future
int s = -1, p = -1;
bool useScale = true, needps = false;
s = item->typeColumn->Length();
p = item->typeColumn->Precision();
if(dataType.IsSameAs(wxT("character varying"), false))
{
needps = true;
dataType = wxT("varchar(n)");
}
else if(dataType.IsSameAs(wxT("numeric"), false))
{
needps = true;
useScale = false;
dataType = wxT("numeric(p,s)");
}
else if(dataType.IsSameAs(wxT("interval"), false))
{
needps = true;
dataType = wxT("interval(n)");
}
else if(dataType.IsSameAs(wxT("bit"), false))
{
needps = true;
dataType = wxT("bit(n)");
}
else if(dataType.IsSameAs(wxT("char"), false))
{
needps = true;
dataType = wxT("char(n)");
}
else if(dataType.IsSameAs(wxT("varbit"), false))
{
needps = true;
dataType = wxT("varbit(n)");
}
else if(dataType.IsSameAs(wxT("character"), false))
{
needps = true;
dataType = wxT("char(n)");
}
int precision = -1;
int scale = -1;
wxString colName = item->columnName;
int ukindex = -1; //By default no ukindex is set
ddColumnFigure *columnFigure = new ddColumnFigure(colName, tableFigure, option, generateFkName, item->isPrimaryKey, dataType, precision, scale, ukindex, NULL, NULL);
//a conversion problem I called precision to length of types, pgadmin called scale.
//this should be fixed, at the same time the datatype subsystem of the database designer will be redesigned.
/*
Disable right now, it can be useful at the future when db designer will be improved again
columnFigure->setPgAttNumCol(item->pgColNumber);
*/
if(needps)
{
if(useScale)
{
columnFigure->setPrecision(s);
columnFigure->setScale(-1);
}
else
{
columnFigure->setPrecision(p);
columnFigure->setScale(s);
}
}
if(item->isUniqueKey())
{
columnFigure->setUniqueConstraintIndex(item->uniqueKeyIndex);
}
tableFigure->addColumn(-1, columnFigure);
columnFigure->setRightIconForColumn();
}
return tableFigure;
}
else
{
return NULL;
}
}
ddStubTable::ddStubTable()
{
tableName = wxEmptyString;
}
ddStubTable::ddStubTable(wxString name, OID tableOID)
{
tableName = name;
OIDTable = tableOID;
}
ddStubTable::~ddStubTable()
{
}
ddStubColumn *ddStubTable::getColumnByNumber(int pgColNumber)
{
stubColsHashMap::iterator it;
ddStubColumn *item, *out = NULL;
for (it = cols.begin(); it != cols.end(); ++it)
{
wxString key = it->first;
item = it->second;
//If found pgColNumber at table columns
if (item->pgColNumber == pgColNumber)
{
out = item;
break;
}
}
return out;
}
ddStubColumn::ddStubColumn(wxString name, OID oidSource, bool notNull, bool pk, pgDatatype *type, int ukIndex)
{
columnName = name;
OIDTable = oidSource;
isNotNull = notNull;
isPrimaryKey = pk;
typeColumn = type;
uniqueKeyIndex = ukIndex;
}
ddStubColumn::ddStubColumn(const ddStubColumn ©)
{
columnName = copy.columnName;
OIDTable = copy.OIDTable;
isNotNull = copy.isNotNull;
isPrimaryKey = copy.isPrimaryKey;
typeColumn = copy.typeColumn;
uniqueKeyIndex = copy.uniqueKeyIndex;
}
ddStubColumn::ddStubColumn(wxString name, OID oidSource)
{
columnName = name;
OIDTable = oidSource;
uniqueKeyIndex = -1;
OIDTable = -1;
typeColumn = NULL;
}
ddStubColumn::ddStubColumn()
{
uniqueKeyIndex = -1;
OIDTable = -1;
typeColumn = NULL;
}
ddStubColumn::~ddStubColumn()
{
if(typeColumn)
delete typeColumn;
}
bool ddStubColumn::isUniqueKey()
{
return uniqueKeyIndex > -1;
};
//
//
//
// ----- ddDBReverseEngineering Implementation
//
//
//
ddDBReverseEngineering::ddDBReverseEngineering(wxFrame *frame, ddDatabaseDesign *design, pgConn *connection, bool useSizer)
: wxWizard(frame, wxID_ANY, wxT("Import tables from schema wizard"),
wxBitmap(*namespaces_png_bmp), wxDefaultPosition,
wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER)
{
conn = connection;
OIDSelectedSchema = 0;
figuresDesign = design;
// a wizard page may be either an object of predefined class
initialPage = new wxWizardPageSimple(this);
frontText = new wxStaticText(initialPage, wxID_ANY,
wxT("Import database tables to model tables wizard.\n")
wxT("\n")
wxT("The next pages will allow you to import database tables inside a database model.")
wxT("\n\n")
wxT("\nSome restrictions apply:\n\n")
wxT("1. Columns that belong to more than one unique constraint aren't supported.\n\n")
wxT("2. Relationships are imported only if both tables (source and destination) are imported.\n\n")
wxT("3. User defined datatypes aren't supported.\n\n")
wxT("4. No indexes, views, sequences and others objects different from tables/relationships can be imported.\n\n")
wxT("5. Tables with same name cannot be imported.\n\n")
wxT("6. Inherited tables cannot be imported.\n\n")
, wxPoint(5, 5)
);
page2 = new SelSchemaPage(this, initialPage);
initialPage->SetNext(page2);
page3 = new SelTablesPage(this, page2);
page2->SetNext(page3);
page4 = new ReportPage(this, page3);
page3->SetNext(page4);
page4->SetNext(NULL);
if ( useSizer )
{
// allow the wizard to size itself around the pages
GetPageAreaSizer()->Add(initialPage);
}
}
// Destructor
ddDBReverseEngineering::~ddDBReverseEngineering()
{
if(frontText)
delete frontText;
}
wxArrayString ddDBReverseEngineering::getTables()
{
wxArrayString out;
wxString query;
tablesOIDHM.clear();
// Get the child objects.
query = wxT("SELECT oid, relname, relkind\n")
wxT(" FROM pg_class\n")
wxT(" WHERE relkind IN ('r') AND relnamespace = ") + NumToStr(OIDSelectedSchema) + wxT(";");
pgSet *tables = conn->ExecuteSet(query);
if (tables)
{
while (!tables->Eof())
{
wxString tmpname = tables->GetVal(wxT("relname"));
wxString relkind = tables->GetVal(wxT("relkind"));
if (relkind == wxT("r")) // Table
{
out.Add(tables->GetVal(wxT("relname")));
tablesOIDHM[tables->GetVal(wxT("relname"))] = tables->GetOid(wxT("oid"));
}
tables->MoveNext();
}
delete tables;
}
return out;
}
void ddDBReverseEngineering::OnFinishPressed(wxWizardEvent &event)
{
//Add Tables to the Model
stubTablesHashMap::iterator it;
ddStubTable *item;
for (it = stubsHM.begin(); it != stubsHM.end(); ++it)
{
wxString key = it->first;
item = it->second;
figuresDesign->addTableToModel(ddImportDBUtils::getTableFigure(item));
}
//Add All relationships to the Model
ddImportDBUtils::getAllRelationships(getConnection(), stubsHM, getDesign());
}
//
//
//
// ----- SelSchemaPage Implementation
//
//
//
SelSchemaPage::SelSchemaPage(wxWizard *parent, wxWizardPage *prev)
: wxWizardPage(parent)
{
wparent = (ddDBReverseEngineering *) parent;
m_prev = prev;
m_next = NULL;
// A top-level sizer
wxBoxSizer *topSizer = new wxBoxSizer(wxVERTICAL );
this->SetSizer(topSizer);
//Add a message
message = new wxStaticText(this, wxID_STATIC, _("Please, select a schema to use at import tables process:"), wxDefaultPosition, wxDefaultSize, wxALIGN_CENTER);
topSizer->Add(message);
topSizer->AddSpacer(10);
//Get Schemas info
if(wparent && wparent->getConnection())
refreshSchemas(wparent->getConnection());
//Add a listbox with schemas
m_allSchemas = new wxListBox(this, DDALLSCHEMAS, wxDefaultPosition, wxDefaultSize, schemasNames, wxLB_SORT | wxLB_ALWAYS_SB | wxLB_SINGLE);
topSizer->Add(m_allSchemas, 1, wxEXPAND);
}
SelSchemaPage::~SelSchemaPage()
{
if(m_allSchemas)
delete m_allSchemas;
if(message)
delete message;
}
void SelSchemaPage::OnWizardPageChanging(wxWizardEvent &event)
{
if(event.GetDirection() && m_allSchemas->GetSelection() == wxNOT_FOUND)
{
wxMessageBox(_("Please, select a Schema to continue to next step."), _("Select a Schema..."), wxICON_WARNING | wxOK, this);
event.Veto();
}
else if(event.GetDirection())
{
wparent->OIDSelectedSchema = schemasHM[schemasNames[m_allSchemas->GetSelection()]];
wparent->schemaName = schemasNames[m_allSchemas->GetSelection()];
wparent->page3->RefreshTablesList();
}
}
void SelSchemaPage::refreshSchemas(pgConn *connection)
{
schemasHM.clear();
schemasNames.Clear();
// Search Schemas and insert it
wxString restr = wxT(" WHERE ");
restr += wxT("NOT ");
restr += wxT("((nspname = 'pg_catalog' AND EXISTS (SELECT 1 FROM pg_class WHERE relname = 'pg_class' AND relnamespace = nsp.oid LIMIT 1)) OR\n");
restr += wxT("(nspname = 'pgagent' AND EXISTS (SELECT 1 FROM pg_class WHERE relname = 'pga_job' AND relnamespace = nsp.oid LIMIT 1)) OR\n");
restr += wxT("(nspname = 'information_schema' AND EXISTS (SELECT 1 FROM pg_class WHERE relname = 'tables' AND relnamespace = nsp.oid LIMIT 1)) OR\n");
restr += wxT("(nspname LIKE '_%' AND EXISTS (SELECT 1 FROM pg_proc WHERE proname='slonyversion' AND pronamespace = nsp.oid LIMIT 1)) OR\n");
restr += wxT("(nspname = 'dbo' AND EXISTS (SELECT 1 FROM pg_class WHERE relname = 'systables' AND relnamespace = nsp.oid LIMIT 1)) OR\n");
restr += wxT("(nspname = 'sys' AND EXISTS (SELECT 1 FROM pg_class WHERE relname = 'all_tables' AND relnamespace = nsp.oid LIMIT 1)))\n");
if (connection->EdbMinimumVersion(8, 2))
{
restr += wxT(" AND nsp.nspparent = 0\n");
// Do not show dbms_job_procedure in schemas
if (!settings->GetShowSystemObjects())
restr += wxT("AND NOT (nspname = 'dbms_job_procedure' AND EXISTS(SELECT 1 FROM pg_proc WHERE pronamespace = nsp.oid and proname = 'run_job' LIMIT 1))\n");
}
wxString sql;
if (connection->BackendMinimumVersion(8, 1))
{
sql = wxT("SELECT CASE WHEN nspname LIKE E'pg\\\\_temp\\\\_%' THEN 1\n")
wxT(" WHEN (nspname LIKE E'pg\\\\_%') THEN 0\n");
}
else
{
sql = wxT("SELECT CASE WHEN nspname LIKE 'pg\\\\_temp\\\\_%' THEN 1\n")
wxT(" WHEN (nspname LIKE 'pg\\\\_%') THEN 0\n");
}
sql += wxT(" ELSE 3 END AS nsptyp, nspname, nsp.oid\n")
wxT(" FROM pg_namespace nsp\n")
+ restr +
wxT(" ORDER BY 1, nspname");
pgSet *schemas = connection->ExecuteSet(sql);
if (schemas)
{
while (!schemas->Eof())
{
wxString name = schemas->GetVal(wxT("nspname"));
long nsptyp = schemas->GetLong(wxT("nsptyp"));
wxStringTokenizer tokens(settings->GetSystemSchemas(), wxT(","));
while (tokens.HasMoreTokens())
{
wxRegEx regex(tokens.GetNextToken());
if (regex.Matches(name))
{
nsptyp = SCHEMATYP_USERSYS;
break;
}
}
if (nsptyp <= SCHEMATYP_USERSYS && !settings->GetShowSystemObjects())
{
schemas->MoveNext();
continue;
}
//Build Schema Tree item
//this->AppendItem(rootNode, name , DD_IMG_FIG_SCHEMA, DD_IMG_FIG_SCHEMA, NULL);
schemasNames.Add(name);
schemasHM[name] = schemas->GetOid(wxT("oid"));
schemas->MoveNext();
}
delete schemas;
}
}
//
//
//
// ----- SelTablesPage Implementation
//
//
//
SelTablesPage::SelTablesPage(wxWizard *parent, wxWizardPage *prev)
: wxWizardPage(parent)
{
wparent = (ddDBReverseEngineering *) parent;
m_prev = prev;
m_next = NULL;
wxFlexGridSizer *mainSizer = new wxFlexGridSizer(2, 3, 0, 0);
this->SetSizer(mainSizer);
leftText = new wxStaticText(this, wxID_STATIC, _("Table(s) from selected schema"), wxDefaultPosition, wxDefaultSize, wxALIGN_CENTER);
mainSizer->Add(leftText);
centerText = new wxStaticText(this, wxID_STATIC, wxT(" "), wxDefaultPosition, wxDefaultSize, wxALIGN_CENTER);
mainSizer->Add(centerText);
rightText = new wxStaticText(this, wxID_STATIC, _("Tables(s) to be imported"), wxDefaultPosition, wxDefaultSize, wxALIGN_CENTER);
mainSizer->Add(rightText, wxALIGN_LEFT);
//left listbox with all tables from selected schema
m_allTables = new wxListBox( this, DDALLTABS, wxDefaultPosition, wxDefaultSize, 0, NULL, wxLB_EXTENDED | wxLB_ALWAYS_SB | wxLB_SORT);
mainSizer->AddGrowableRow(1);
mainSizer->AddGrowableCol(0);
mainSizer->Add(m_allTables , 1, wxEXPAND);
addBitmap = *gqbOrderAdd_png_bmp;
addAllBitmap = *gqbOrderAddAll_png_bmp;
removeBitmap = *gqbOrderRemove_png_bmp;
removeAllBitmap = *gqbOrderRemoveAll_png_bmp;
buttonAdd = new wxBitmapButton( this, DDADD, addBitmap, wxDefaultPosition, wxDefaultSize, wxBU_AUTODRAW, wxDefaultValidator, wxT("Add Column") );
buttonAdd->SetToolTip(_("Add the selected table(s)"));
buttonAddAll = new wxBitmapButton( this, DDADDALL, addAllBitmap, wxDefaultPosition, wxDefaultSize, wxBU_AUTODRAW, wxDefaultValidator, wxT("Add All Columns") );
buttonAddAll->SetToolTip(_("Add all tables"));
buttonRemove = new wxBitmapButton( this, DDREMOVE, removeBitmap, wxDefaultPosition, wxDefaultSize, wxBU_AUTODRAW, wxDefaultValidator, wxT("Remove Column") );
buttonRemove->SetToolTip(_("Remove the selected table(s)"));
buttonRemoveAll = new wxBitmapButton( this, DDREMOVEALL, removeAllBitmap, wxDefaultPosition, wxDefaultSize, wxBU_AUTODRAW, wxDefaultValidator, wxT("Remove All Columns") );
buttonRemoveAll->SetToolTip(_("Remove all tables"));
wxBoxSizer *buttonsSizer = new wxBoxSizer( wxVERTICAL );
buttonsSizer->Add(
this->buttonAdd,
0, // make horizontally unstretchable
wxALL, // make border all around (implicit top alignment)
3 ); // set border width to 3
buttonsSizer->Add(
this->buttonAddAll,
0, // make horizontally unstretchable
wxALL, // make border all around (implicit top alignment)
3 ); // set border width to 3
buttonsSizer->Add(
this->buttonRemove,
0, // make horizontally unstretchable
wxALL, // make border all around (implicit top alignment)
3 ); // set border width to 3
buttonsSizer->Add(
this->buttonRemoveAll,
0, // make horizontally unstretchable
wxALL, // make border all around (implicit top alignment)
3 ); // set border width to 3
mainSizer->Add(
buttonsSizer,
0, // make vertically unstretchable
wxALIGN_CENTER ); // no border and centre horizontally
//right listbox with selected tables from schema to be imported.
m_selTables = new wxListBox( this, DDSELTABS, wxDefaultPosition, wxDefaultSize, 0, NULL, wxLB_EXTENDED | wxLB_ALWAYS_SB | wxLB_SORT);
mainSizer->AddGrowableCol(2);
mainSizer->Add(m_selTables , 1, wxEXPAND);
mainSizer->Fit(this);
}
SelTablesPage::~SelTablesPage()
{
if(rightText)
delete rightText;
if(centerText)
delete centerText;
if(leftText)
delete leftText;
if(m_allTables)
delete m_allTables;
if(m_selTables)
delete m_selTables;
if(buttonAdd)
delete buttonAdd;
if(buttonAddAll)
delete buttonAddAll;
if(buttonRemove)
delete buttonRemove;
if(buttonRemoveAll)
delete buttonRemoveAll;
}
void SelTablesPage::RefreshTablesList()
{
m_allTables->Set(wparent->getTables(), (void **)NULL);
}
void SelTablesPage::OnButtonAdd(wxCommandEvent &)
{
wxArrayInt positions;
if(m_allTables->GetSelections(positions) > 0)
{
int i;
int size = positions.Count();
for(i = 0; i < size; i++)
{
m_selTables->Append(m_allTables->GetString(positions[i]));
m_allTables->Deselect(positions[i]);
}
for(i = (size - 1); i >= 0 ; i--)
{
m_allTables->Delete(positions[i]);
}
if(m_allTables->GetCount() > 0)
m_allTables->Select(0);
}
}
void SelTablesPage::OnButtonAddAll(wxCommandEvent &)
{
int itemsCount = m_allTables->GetCount();
if( itemsCount > 0)
{
do
{
m_allTables->Deselect(0);
m_selTables->Append(m_allTables->GetString(0));
m_allTables->Delete(0);
itemsCount--;
}
while(itemsCount > 0);
}
}
void SelTablesPage::OnButtonRemove(wxCommandEvent &)
{
wxArrayInt positions;
if(m_selTables->GetSelections(positions) > 0)
{
int i;
int size = positions.Count(); //warning about conversion should be ignored
for(i = 0; i < size; i++)
{
m_allTables->Append(m_selTables->GetString(positions[i]));
m_selTables->Deselect(positions[i]);
}
for(i = (size - 1); i >= 0 ; i--)
{
m_selTables->Delete(positions[i]);
}
if(m_selTables->GetCount() > 0)
m_selTables->Select(0);
}
}
void SelTablesPage::OnButtonRemoveAll(wxCommandEvent &)
{
int itemsCount = m_selTables->GetCount();
if( itemsCount > 0)
{
do
{
m_selTables->Deselect(0);
m_allTables->Append(m_selTables->GetString(0));
m_selTables->Delete(0);
itemsCount--;
}
while(itemsCount > 0);
}
}
void SelTablesPage::OnWizardPageChanging(wxWizardEvent &event)
{
if(event.GetDirection() && m_selTables->GetCount() <= 0)
{
wxMessageBox(_("Please, select at least a table to continue to next step."), _("Select some Tables..."), wxICON_WARNING | wxOK, this);
event.Veto();
}
else if(event.GetDirection())
{
int itemsCount = m_selTables->GetCount();
if( itemsCount > 0)
{
int item = 0;
do
{
ddStubTable *table = ddImportDBUtils::getTable(wparent->getConnection(), m_selTables->GetString(item), wparent->tablesOIDHM[m_selTables->GetString(item)]);
if(table == NULL)
{
ReportPage *tmp = (ReportPage *) m_next;
tmp->results->AppendText(_("Error when preparing to import table: ") + m_selTables->GetString(item) + _(", this table have inherited columns and this feature is not supported at this moment.\n\n"));
}
else if(wparent->getDesign()->getTable(m_selTables->GetString(item)) != NULL)
{
ReportPage *tmp = (ReportPage *) m_next;
tmp->results->AppendText(_("Error when preparing to import table: ") + m_selTables->GetString(item) + _(", this table already exists in the model and updating table at a model is not supported at this moment.\n\n"));
}
else if(table->tableName.Length() > 0)
{
if(m_next)
{
ReportPage *tmp = (ReportPage *) m_next;
tmp->results->AppendText(_("Prepared to import table: ") + table->tableName + _("\n"));
wparent->stubsHM[table->tableName] = table;
}
}
else
{
if(m_next)
{
ReportPage *tmp = (ReportPage *) m_next;
tmp->results->AppendText(_("Error when preparing to import table: ") + m_selTables->GetString(item) + _("\n"));
}
}
item++;
}
while(item < itemsCount);
}
}
else if(!event.GetDirection())
{
//Reset tables after a warning
int answer = wxMessageBox(_("Returning to previous dialog will remove all selected tables, do you like to continue?"), _("Confirm"), wxYES_NO | wxCANCEL, this);
if (answer == wxYES)
{
m_selTables->Clear();
m_allTables->Clear();
wparent->tablesOIDHM.clear();
}
else
event.Veto();
}
}
//
//
//
// ----- ReportPage Implementation
//
//
//
ReportPage::ReportPage(wxWizard *parent, wxWizardPage *prev)
: wxWizardPage(parent)
{
wparent = (ddDBReverseEngineering *) parent;
m_prev = prev;
m_next = NULL;
// A top-level sizer
wxBoxSizer *topSizer = new wxBoxSizer(wxVERTICAL );
this->SetSizer(topSizer);
//Add a message
results = new wxTextCtrl(this, wxID_ANY , wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_MULTILINE | wxTE_READONLY | wxTE_LEFT
);
topSizer->Add(results, 1, wxEXPAND);
topSizer->Fit(this);
}
ReportPage::~ReportPage()
{
if(results)
delete results;
}
void ReportPage::OnWizardPageChanging(wxWizardEvent &event)
{
if(!event.GetDirection())
{
int answer = wxMessageBox(_("Returning to previous dialog will delete imported tables before adding it to the model?"), _("Confirm"), wxYES_NO | wxCANCEL, this);
if (answer == wxYES)
{
results->Clear();
wparent->stubsHM.clear();
}
else
event.Veto();
}
}
|