File: dlgProperty.cpp

package info (click to toggle)
pgadmin3 1.20.0~beta2-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 73,704 kB
  • ctags: 18,591
  • sloc: cpp: 193,786; ansic: 18,736; sh: 5,154; pascal: 1,120; yacc: 927; makefile: 516; lex: 421; xml: 126; perl: 40
file content (2364 lines) | stat: -rw-r--r-- 57,460 bytes parent folder | download
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
//////////////////////////////////////////////////////////////////////////
//
// pgAdmin III - PostgreSQL Tools
//
// Copyright (C) 2002 - 2014, The pgAdmin Development Team
// This software is released under the PostgreSQL Licence
//
// dlgQuery.cpp - Property Dialog
//
//////////////////////////////////////////////////////////////////////////

// wxWindows headers
#include <wx/wx.h>
#include <wx/button.h>

// App headers
#include "pgAdmin3.h"
#include "ctl/ctlMenuToolbar.h"
#include "ctl/ctlSQLBox.h"
#include "schema/pgCollection.h"
#include "schema/pgDatatype.h"
#include "utils/misc.h"
#include "utils/pgDefs.h"
#include "ctl/ctlSecurityPanel.h"
#include "ctl/ctlDefaultSecurityPanel.h"

// Images
#include "images/properties.pngc"

#include "frm/frmMain.h"
#include "frm/frmHint.h"

// Property dialogs
#include "dlg/dlgProperty.h"
#include "dlg/dlgServer.h"
#include "dlg/dlgAggregate.h"
#include "dlg/dlgColumn.h"
#include "dlg/dlgIndex.h"
#include "dlg/dlgIndexConstraint.h"
#include "dlg/dlgForeignKey.h"
#include "dlg/dlgCheck.h"
#include "dlg/dlgRule.h"
#include "dlg/dlgTrigger.h"
#include "dlg/dlgEventTrigger.h"
#include "agent/dlgJob.h"
#include "agent/dlgStep.h"
#include "agent/dlgSchedule.h"

#include "slony/dlgRepCluster.h"
#include "slony/dlgRepNode.h"
#include "slony/dlgRepPath.h"
#include "slony/dlgRepListen.h"
#include "slony/dlgRepSet.h"
#include "slony/dlgRepSequence.h"
#include "slony/dlgRepTable.h"
#include "slony/dlgRepSubscription.h"
#include "schema/pgTable.h"
#include "schema/pgColumn.h"
#include "schema/pgTrigger.h"
#include "schema/pgGroup.h"
#include "schema/pgUser.h"
#include "schema/pgEventTrigger.h"

void dataType::SetOid(OID id)
{
	oid = id;
}

void dataType::SetTypename(wxString name)
{
	typeName = name;
}

OID dataType::GetOid()
{
	return oid;
}

wxString dataType::GetTypename()
{
	return typeName;
}

#define CTRLID_CHKSQLTEXTFIELD 1000


BEGIN_EVENT_TABLE(dlgProperty, DialogWithHelp)
	EVT_NOTEBOOK_PAGE_CHANGED(XRCID("nbNotebook"),  dlgProperty::OnPageSelect)

	EVT_TEXT(XRCID("txtName"),                      dlgProperty::OnChange)
	EVT_TEXT(XRCID("cbOwner"),                      dlgProperty::OnChangeOwner)
	EVT_COMBOBOX(XRCID("cbOwner"),                  dlgProperty::OnChange)
	EVT_TEXT(XRCID("cbSchema"),                     dlgProperty::OnChange)
	EVT_COMBOBOX(XRCID("cbSchema"),                 dlgProperty::OnChange)
	EVT_TEXT(XRCID("txtComment"),                   dlgProperty::OnChange)

	EVT_CHECKBOX(CTRLID_CHKSQLTEXTFIELD,            dlgProperty::OnChangeReadOnly)

	EVT_BUTTON(wxID_HELP,                           dlgProperty::OnHelp)
	EVT_BUTTON(wxID_OK,                             dlgProperty::OnOK)
END_EVENT_TABLE();


dlgProperty::dlgProperty(pgaFactory *f, frmMain *frame, const wxString &resName) : DialogWithHelp(frame)
{
	readOnly = false;
	sqlPane = 0;
	sqlTextField1 = 0;
	sqlTextField2 = 0;
	processing = false;
	mainForm = frame;
	database = 0;
	connection = 0;
	factory = f;
	item = (void *)NULL;
	owneritem = (void *)NULL;
	chkReadOnly = (wxCheckBox *)NULL;
	SetFont(settings->GetSystemFont());
	LoadResource(frame, resName);

#ifdef __WXMSW__
	SetWindowStyleFlag(GetWindowStyleFlag() & ~wxMAXIMIZE_BOX);
#endif

	nbNotebook = CTRL_NOTEBOOK("nbNotebook");
	if (!nbNotebook)
	{
		wxMessageBox(wxString::Format(_("Problem with resource %s: Notebook not found.\nPrepare to crash!"), resName.c_str()));
		return;
	}

	// Set the icon
	wxBitmap bm(factory->GetImage());
	wxIcon ico;
	ico.CopyFromBitmap(bm);
	SetIcon(ico);

	txtName = CTRL_TEXT("txtName");
	txtOid = CTRL_TEXT("txtOID");
	txtComment = CTRL_TEXT("txtComment");
	cbOwner = CTRL_COMBOBOX2("cbOwner");
	cbSchema = CTRL_COMBOBOX2("cbSchema");
	cbClusterSet = CTRL_COMBOBOX1("cbClusterSet");

	wxString db = wxT("Database");
	wxString ts = wxT("Tablespace");
	enableSQL2 = db.Cmp(factory->GetTypeName()) == 0
	             || ts.Cmp(factory->GetTypeName()) == 0;

	wxNotebookPage *page = nbNotebook->GetPage(0);
	wxASSERT(page != NULL);
	page->GetClientSize(&width, &height);

	numericValidator.SetStyle(wxFILTER_NUMERIC);
	btnOK->Disable();

	statusBar = XRCCTRL(*this, "unkStatusBar", wxStatusBar);
}


dlgProperty::~dlgProperty()
{
	wxString prop = wxT("Properties/") + wxString(factory->GetTypeName());
	settings->WritePoint(prop, GetPosition());

	if (GetWindowStyle() & wxRESIZE_BORDER)
		settings->WriteSize(prop, GetSize());

	if (obj)
		obj->SetWindowPtr(NULL);
}


wxString dlgProperty::GetHelpPage() const
{
	wxString page;

	pgObject *obj = ((dlgProperty *)this)->GetObject();
	if (obj)
		page = obj->GetHelpPage(false);
	else
	{
		// Attempt to get he page from the dialogue, otherwise, take a shot at it!
		page = this->GetHelpPage(true);
		if (page.Length() == 0)
		{
			page = wxT("pg/sql-create");
			page += wxString(factory->GetTypeName()).Lower();
		}
	}

	return page;
}


void dlgProperty::CheckValid(bool &enable, const bool condition, const wxString &msg)
{
	if (enable)
	{
		if (!condition)
		{
			if (statusBar)
				statusBar->SetStatusText(msg);
			enable = false;
		}
	}
}


void dlgProperty::SetDatabase(pgDatabase *db)
{
	database = db;
	if (db)
		connection = db->GetConnection();
}

void dlgProperty::SetDatatypeCache(dataTypeCache cache)
{
	dtCache = cache;
}

void dlgProperty::EnableOK(bool enable)
{
	btnOK->Enable(enable);
	if (enable)
	{
		if (statusBar)
			statusBar->SetStatusText(wxEmptyString);
	}
}


void dlgProperty::SetSqlReadOnly(bool readonly)
{
	if (chkReadOnly)
		chkReadOnly->Enable(!readonly);
}


int dlgProperty::Go(bool modal)
{
	wxASSERT(factory != 0);

	if(GetObject())
		obj = GetObject();
	else
		obj = mainForm->GetBrowser()->GetObject(mainForm->GetBrowser()->GetSelection());

	// restore previous position and size, if applicable
	wxString prop = wxT("Properties/") + wxString(factory->GetTypeName());

	wxSize origSize = GetSize();

	if (GetWindowStyle() & wxRESIZE_BORDER)
		SetSize(settings->Read(prop, GetSize()));

	wxPoint pos = settings->Read(prop, GetPosition());
	if (pos.x >= 0 && pos.y >= 0)
		Move(pos);

	wxSize size = GetSize();
	CheckOnScreen(this, pos, size, origSize.GetWidth(), origSize.GetHeight());
	Move(pos);

	ctlComboBoxFix *cbowner = (ctlComboBoxFix *)cbOwner;
	ctlComboBoxFix *cbschema = (ctlComboBoxFix *)cbSchema;

	if (cbClusterSet)
	{
		cbClusterSet->Append(wxEmptyString);
		cbClusterSet->SetSelection(0);

		if (mainForm && database)
		{
			wxArrayString clusters = database->GetSlonyClusters(mainForm->GetBrowser());

			size_t i;
			for (i = 0 ; i < clusters.GetCount() ; i++)
			{
				wxString cluster = wxT("_") + clusters.Item(i);
				pgSetIterator sets(connection,
				                   wxT("SELECT set_id, ") + qtIdent(cluster) + wxT(".slonyversionmajor(), ") + qtIdent(cluster) + wxT(".slonyversionminor()\n")
				                   wxT("  FROM ") + qtIdent(cluster) + wxT(".sl_set\n")
				                   wxT(" WHERE set_origin = ") + qtIdent(cluster) +
				                   wxT(".getlocalnodeid(") + qtDbString(cluster) + wxT(");"));

				while (sets.RowsLeft())
				{
					wxString str;
					long setId = sets.GetLong(wxT("set_id"));
					long majorVer = sets.GetLong(wxT("slonyversionmajor"));
					long minorVer = sets.GetLong(wxT("slonyversionminor"));
					str.Printf(_("Cluster \"%s\", set %ld"), clusters.Item(i).c_str(), setId);
					cbClusterSet->Append(str, static_cast<void *>(new replClientData(cluster, setId, majorVer, minorVer)));
				}
			}
		}
		if (cbClusterSet->GetCount() < 2)
			cbClusterSet->Disable();
	}

	if (cbowner && !cbowner->GetCount())
	{
		if (!GetObject())
			cbOwner->Append(wxEmptyString);
		AddGroups(cbowner);
		AddUsers(cbowner);
	}
	if (txtOid)
		txtOid->Disable();

	if (cbschema && !cbschema->GetCount())
		AddSchemas(cbschema);

	if (GetObject())
	{
		if (txtName)
			txtName->SetValue(GetObject()->GetName());
		if (txtOid)
			txtOid->SetValue(NumToStr((unsigned long)GetObject()->GetOid()));
		if (cbOwner)
			cbOwner->SetValue(GetObject()->GetOwner());
		if (cbSchema)
			cbSchema->SetValue(GetObject()->GetSchema()->GetName());
		if (txtComment)
			txtComment->SetValue(GetObject()->GetComment());


		if (!readOnly && !GetObject()->CanCreate())
		{
			// users who can't create will usually not be allowed to change either.
			readOnly = false;
		}

		wxString typeName = factory->GetTypeName();
		SetTitle(wxString(wxGetTranslation(typeName)) + wxT(" ") + GetObject()->GetFullIdentifier());
	}
	else
	{
		if (factory)
			SetTitle(wxGetTranslation(factory->GetNewString()));
		if (cbSchema)
		{
			if (obj->GetMetaType() == PGM_SCHEMA)
				cbSchema->SetValue(obj->GetName());
			else
				cbSchema->SetValue(obj->GetSchema()->GetName());
		}
	}
	if (statusBar)
		statusBar->SetStatusText(wxEmptyString);

	if (nbNotebook)
	{
		wxNotebookPage *pg = nbNotebook->GetPage(0);
		if (pg)
			pg->SetFocus();
	}

	// This fixes a UI glitch on MacOS X and Windows
	// Because of the new layout code, the Privileges pane don't size itself properly
	SetSize(GetSize().GetWidth() + 1, GetSize().GetHeight());
	SetSize(GetSize().GetWidth() - 1, GetSize().GetHeight());

	if (modal)
		return ShowModal();
	else
		Show(true);

	return 0;
}


void dlgProperty::CreateAdditionalPages()
{
	if (wxString(factory->GetTypeName()).Cmp(wxT("Server")))
	{
		// create a panel
		sqlPane = new wxPanel(nbNotebook);

		// add panel to the notebook
		nbNotebook->AddPage(sqlPane, wxT("SQL"));

		// create a flex grid sizer
		wxFlexGridSizer *fgsizer = new wxFlexGridSizer(1, 5, 5);

		// add checkbox to the panel
		chkReadOnly = new wxCheckBox(sqlPane, CTRLID_CHKSQLTEXTFIELD, _("Read only"));
		chkReadOnly->SetValue(true);
		fgsizer->Add(chkReadOnly, 1, wxALL | wxALIGN_LEFT, 5);

		// text entry box
		sqlTextField1 = new ctlSQLBox(sqlPane, CTL_PROPSQL,
		                              wxDefaultPosition, wxDefaultSize,
		                              wxTE_MULTILINE | wxSUNKEN_BORDER | wxTE_RICH2);
		fgsizer->Add(sqlTextField1, 1, wxALL | wxEXPAND, 5);

		// text entry box
		if (enableSQL2)
		{
			sqlTextField2 = new ctlSQLBox(sqlPane, CTL_PROPSQL,
			                              wxDefaultPosition, wxDefaultSize,
			                              wxTE_MULTILINE | wxSUNKEN_BORDER | wxTE_RICH2);
			fgsizer->Add(sqlTextField2, 1, wxALL | wxEXPAND, 5);
		}

		fgsizer->AddGrowableCol(0);
		fgsizer->AddGrowableRow(1);
		if (fgsizer->GetRows() > 1)
		{
			fgsizer->AddGrowableRow(2);
		}

		sqlPane->SetAutoLayout(true);
		sqlPane->SetSizer(fgsizer);
	}
}


wxString dlgProperty::GetName()
{
	if (txtName)
	{
		if (GetObject())
		{
			// If there is an existing object name with a leading or trailing
			// space, don't try to remove it.
			if (GetObject()->GetName() == txtName->GetValue())
				return txtName->GetValue();
			else
				return txtName->GetValue().Strip(wxString::both);
		}
		else
			return txtName->GetValue().Strip(wxString::both);
	}
	return wxEmptyString;
}


void dlgProperty::AppendNameChange(wxString &sql, const wxString &objName)
{
	if (GetObject()->GetName() != GetName())
	{
		if (objName.Length() > 0)
		{
			sql += wxT("ALTER ") + objName
			       +  wxT("\n  RENAME TO ") + qtIdent(GetName())
			       +  wxT(";\n");
		}
		else
		{
			sql += wxT("ALTER ") + GetObject()->GetTypeName().MakeUpper()
			       +  wxT(" ") + GetObject()->GetQuotedFullIdentifier()
			       +  wxT("\n  RENAME TO ") + qtIdent(GetName())
			       +  wxT(";\n");
		}
	}
}


void dlgProperty::AppendOwnerChange(wxString &sql, const wxString &objName)
{
	if (!GetObject() || GetObject()->GetOwner() != cbOwner->GetValue())
	{
		sql += wxT("ALTER ") + objName
		       +  wxT("\n  OWNER TO ") + qtIdent(cbOwner->GetValue())
		       +  wxT(";\n");
	}
}


void dlgProperty::AppendOwnerNew(wxString &sql, const wxString &objName)
{
	if (cbOwner->GetGuessedSelection() > 0)
		sql += wxT("ALTER ") + objName
		       +  wxT("\n  OWNER TO ") + qtIdent(cbOwner->GetValue())
		       +  wxT(";\n");
}


void dlgProperty::AppendSchemaChange(wxString &sql, const wxString &objName)
{
	wxString currentschema;

	if (GetObject()->GetMetaType() == PGM_SCHEMA)
	{
		currentschema = GetObject()->GetName();
	}
	else
	{
		currentschema = GetObject()->GetSchema()->GetName();
	}

	if (currentschema != cbSchema->GetValue())
	{
		sql += wxT("ALTER ") + objName
		       +  wxT("\n  SET SCHEMA ") + qtIdent(cbSchema->GetValue())
		       +  wxT(";\n");
	}
}


void dlgProperty::AppendComment(wxString &sql, const wxString &objName, pgObject *obj)
{
	wxString comment = txtComment->GetValue();
	if ((!obj && !comment.IsEmpty()) || (obj && obj->GetComment() != comment))
	{
		sql += wxT("COMMENT ON ") + objName
		       + wxT("\n  IS ") + qtDbString(comment) + wxT(";\n");
	}
}


void dlgProperty::AppendComment(wxString &sql, const wxString &objType, pgSchema *schema, pgObject *obj)
{
	wxString comment = txtComment->GetValue();
	if ((!obj && !comment.IsEmpty()) || (obj && obj->GetComment() != comment))
	{
		sql += wxT("COMMENT ON ") + objType + wxT(" ");
		if (schema)
			sql += schema->GetQuotedPrefix();
		sql += qtIdent(GetName()) + wxT("\n  IS ") + qtDbString(comment) + wxT(";\n");
	}
}


void dlgProperty::AppendQuoted(wxString &sql, const wxString &name)
{
	// quick and quite dirty:
	// !!! this is unsafe if the name itself contains a dot which isn't meant as separator between schema and object
	if (name.First('.') >= 0)
	{
		sql += qtIdent(name.BeforeFirst('.')) + wxT(".") + qtIdent(name.AfterFirst('.'));
	}
	else
		sql += qtIdent(name);
}

void dlgProperty::AppendQuotedType(wxString &sql, const wxString &name)
{
	// see AppendQuoted()
	if (name.First('.') >= 0)
	{
		sql += qtIdent(name.BeforeFirst('.')) + wxT(".") + qtTypeIdent(name.AfterFirst('.'));
	}
	else
		sql += qtTypeIdent(name);
}


void dlgProperty::FillCombobox(const wxString &query, ctlComboBoxFix *cb1, ctlComboBoxFix *cb2)
{
	if (!cb1 && !cb2)
		return;

	pgSet *set = connection->ExecuteSet(query);
	if (set)
	{
		while (!set->Eof())
		{
			if (cb1)
				cb1->Append(set->GetVal(0));
			if (cb2)
				cb2->Append(set->GetVal(0));
			set->MoveNext();
		}
	}
}


void dlgProperty::AddDatabases(ctlComboBoxFix *cb)
{
	FillCombobox(wxT("SELECT datname FROM pg_database ORDER BY 1"), cb);
}


void dlgProperty::AddUsers(ctlComboBoxFix *cb1, ctlComboBoxFix *cb2)
{
	if (connection->BackendMinimumVersion(8, 1))
	{
		FillCombobox(wxT("SELECT rolname FROM pg_roles WHERE rolcanlogin ORDER BY 1"), cb1, cb2);
	}
	else
	{
		FillCombobox(wxT("SELECT usename FROM pg_user ORDER BY 1"), cb1, cb2);
	}
}


void dlgProperty::AddGroups(ctlComboBoxFix *combo)
{
	if (connection->BackendMinimumVersion(8, 1))
	{
		FillCombobox(wxT("SELECT rolname FROM pg_roles WHERE NOT rolcanlogin ORDER BY 1"), combo);
	}
	else
	{
		FillCombobox(wxT("SELECT groname FROM pg_group ORDER BY 1"), combo);
	}
}


void dlgProperty::AddSchemas(ctlComboBoxFix *combo)
{
	if (connection->BackendMinimumVersion(8, 1))
	{
		FillCombobox(wxT("SELECT nspname FROM pg_namespace WHERE nspname NOT LIKE E'pg\\\\_%' AND nspname != 'information_schema' ORDER BY nspname"),
		             combo);
	}
}


void dlgProperty::PrepareTablespace(ctlComboBoxFix *cb, const OID current)
{
	wxASSERT(cb != 0);

	if (connection->BackendMinimumVersion(8, 0))
	{
		// Populate the combo
		cb->FillOidKey(connection, wxT("SELECT oid, spcname FROM pg_tablespace WHERE spcname <> 'pg_global' ORDER BY spcname"));

		if (current)
			cb->SetKey(current);
		else
		{
			if (database)
				cb->SetValue(database->GetDefaultTablespace());
			else
			{
				wxString def = connection->ExecuteScalar(wxT("SELECT current_setting('default_tablespace');"));
				if (def == wxEmptyString || def == wxT("unset"))
					def = wxT("pg_default");
				cb->SetValue(def);
			}
		}
	}
	else
		cb->Disable();
}


void dlgProperty::OnChangeStc(wxStyledTextEvent &ev)
{
	CheckChange();
}


void dlgProperty::OnChange(wxCommandEvent &ev)
{
	CheckChange();
}


void dlgProperty::OnChangeOwner(wxCommandEvent &ev)
{
	ctlComboBox *cb = cbOwner;
	if (cb)
		cb->GuessSelection(ev);
	CheckChange();
}


void dlgProperty::OnChangeReadOnly(wxCommandEvent &ev)
{
	size_t pos;
	bool showmessage;

	showmessage = chkReadOnly->GetValue()
	              && ! (!enableSQL2 && GetSql().Length() == 0 && sqlTextField1->GetText().Cmp(_("-- nothing to change")) == 0)
	              && ! (!enableSQL2 && GetSql().Length() == 0 && sqlTextField1->GetText().Cmp(_("-- definition incomplete")) == 0)
	              && ! (enableSQL2 && GetSql().Length() == 0 && GetSql2().Length() == 0 && sqlTextField1->GetText().Cmp(_("-- nothing to change")) == 0 && sqlTextField2->GetText().Length() == 0)
	              && ! (enableSQL2 && GetSql().Length() == 0 && GetSql2().Length() == 0 && sqlTextField1->GetText().Cmp(_("-- definition incomplete")) == 0 && sqlTextField2->GetText().Length() == 0)
	              && (sqlTextField1->GetText().Cmp(GetSql()) != 0 || (enableSQL2 && sqlTextField2->GetText().Cmp(GetSql2()) != 0));

	if (showmessage)
	{
		if (wxMessageBox(_("Are you sure you wish to cancel your edit?"), _("SQL editor"), wxYES_NO | wxNO_DEFAULT) != wxYES)
		{
			chkReadOnly->SetValue(false);
			return;
		}
	}

	sqlTextField1->SetReadOnly(chkReadOnly->GetValue());
	if (enableSQL2)
	{
		sqlTextField2->SetReadOnly(chkReadOnly->GetValue());
	}
	for (pos = 0; pos < nbNotebook->GetPageCount() - 1; pos++)
	{
		nbNotebook->GetPage(pos)->Enable(chkReadOnly->GetValue());
	}

	if (chkReadOnly->GetValue())
	{
		FillSQLTextfield();
	}
}


void dlgProperty::FillSQLTextfield()
{
	// create a function because this is a duplicated code
	sqlTextField1->SetReadOnly(false);
	if (enableSQL2)
	{
		sqlTextField2->SetReadOnly(false);
	}
	if (btnOK->IsEnabled())
	{
		wxString tmp;
		if (cbClusterSet && cbClusterSet->GetSelection() > 0)
		{
			replClientData *data = (replClientData *)cbClusterSet->wxItemContainer::GetClientData(cbClusterSet->GetSelection());
			if(data)
				tmp.Printf(_("-- Execute replicated using cluster \"%s\", set %ld\n"), data->cluster.c_str(), data->setId);
		}
		sqlTextField1->SetText(tmp + GetSql());
		if (enableSQL2)
		{
			sqlTextField2->SetText(GetSql2());
		}
	}
	else
	{
		if (GetObject())
			sqlTextField1->SetText(_("-- nothing to change"));
		else
			sqlTextField1->SetText(_("-- definition incomplete"));
		if (enableSQL2)
		{
			sqlTextField2->SetText(wxT(""));
		}
	}
	sqlTextField1->SetReadOnly(true);
	if (enableSQL2)
	{
		sqlTextField2->SetReadOnly(true);
	}
}


bool dlgProperty::tryUpdate(wxTreeItemId collectionItem)
{
	ctlTree *browser = mainForm->GetBrowser();
	pgCollection *collection = (pgCollection *)browser->GetObject(collectionItem);
	if (collection && collection->IsCollection() && factory->GetCollectionFactory() == collection->GetFactory())
	{
		pgObject *data = CreateObject(collection);
		if (data)
		{

			wxString nodeName = this->GetDisplayName();
			if (nodeName.IsEmpty())
				nodeName = data->GetDisplayName();

			size_t pos = 0;
			wxTreeItemId newItem;

			if (!data->IsCreatedBy(columnFactory))
			{
				// columns should be appended, not inserted alphabetically

				wxCookieType cookie;
				newItem = browser->GetFirstChild(collectionItem, cookie);
				while (newItem)
				{
					if (browser->GetItemText(newItem) > nodeName)
						break;
					pos++;
					newItem = browser->GetNextChild(collectionItem, cookie);
				}
			}

			if (newItem)
				browser->InsertItem(collectionItem, pos, nodeName, data->GetIconId(), -1, data);
			else
				browser->AppendItem(collectionItem, nodeName, data->GetIconId(), -1, data);

			if (data->WantDummyChild())
				browser->AppendItem(data->GetId(), wxT("Dummy"));

			if (browser->GetSelection() == item)
				collection->ShowTreeDetail(browser, 0, mainForm->GetProperties());
			else
				collection->UpdateChildCount(browser);
		}
		else
		{
			// CreateObject didn't return a new pgObject; refresh the complete collection
			mainForm->Refresh(collection);
		}
		return true;
	}
	return false;
}



void dlgProperty::ShowObject()
{
	mainForm->ObjectBrowserRefreshing(true);
	pgObject *data = GetObject();

	// We might have a parent to refresh. If so, the children will
	// inherently get refreshed as well. Yay :-)
	if (owneritem)
	{
		// Get the object node in case we need it later
		wxTreeItemId objectnode = mainForm->GetBrowser()->GetItemParent(owneritem);

		// Stash the selected items path
		wxString currentPath = mainForm->GetCurrentNodePath();

		pgObject *tblobj = mainForm->GetBrowser()->GetObject(owneritem);

		if (tblobj)
		{
			dlgProperty *ownDialog = NULL;
			if (data)
			{
				ownDialog = data->GetWindowPtr();
				data->SetWindowPtr(NULL);
			}
			mainForm->Refresh(tblobj);
			if (data)
			{
				data->SetWindowPtr(ownDialog);
			}
		}

		// Restore the previous selection...
		mainForm->SetCurrentNode(mainForm->GetBrowser()->GetRootItem(), currentPath);
	}
	else if (data)
	{
		pgObject *newData = data->Refresh(mainForm->GetBrowser(), item);
		if (newData && newData != data)
		{
			mainForm->SetCurrentObject(newData);
			mainForm->GetBrowser()->SetItemData(item, newData);

			newData->SetId(item);
			delete data;
			SetObject(newData);

			newData->UpdateIcon(mainForm->GetBrowser());
		}
		if (newData)
		{
			mainForm->GetBrowser()->DeleteChildren(newData->GetId());

			if (item == mainForm->GetBrowser()->GetSelection())
				newData->ShowTree(mainForm, mainForm->GetBrowser(), mainForm->GetProperties(), 0);
			mainForm->GetBrowser()->SetItemText(item, newData->GetFullName());
			mainForm->GetSqlPane()->SetReadOnly(false);
			mainForm->GetSqlPane()->SetText(newData->GetSql(mainForm->GetBrowser()));
			mainForm->GetSqlPane()->SetReadOnly(true);
		}
	}
	else if (item && chkReadOnly->GetValue())
	{
		wxTreeItemId collectionItem = item;

		while (collectionItem)
		{
			// search up the tree for our collection
			if (tryUpdate(collectionItem))
				break;
			collectionItem = mainForm->GetBrowser()->GetItemParent(collectionItem);
		}
	}
	else // Brute force update the current item
	{
		pgObject *currobj = mainForm->GetBrowser()->GetObject(mainForm->GetBrowser()->GetSelection());

		if (currobj)
			mainForm->Refresh(currobj);
	}
	mainForm->ObjectBrowserRefreshing(false);
}


bool dlgProperty::apply(const wxString &sql, const wxString &sql2)
{
	wxString tmp;
	pgConn *myConn = connection;

	if (GetDisconnectFirst())
	{
		myConn = database->GetServer()->GetConnection();
		database->Disconnect();
	}

	if (!sql.IsEmpty())
	{
		wxArrayString queries;

		if (WannaSplitQueries())
			queries = SplitQueries(BuildSql(sql));
		else
			queries.Add(BuildSql(sql));

		for (size_t index = 0; index < queries.GetCount(); index++)
		{
			tmp = queries.Item(index);
			if (!myConn->ExecuteVoid(tmp))
			{
				// error message is displayed inside ExecuteVoid
				return false;
			}

			if (database)
				database->AppendSchemaChange(tmp);
		}
	}

	// Process the second SQL statement. This is primarily only used by
	// CREATE DATABASE which cannot be run in a multi-statement query in
	// PostgreSQL 8.3+
	if (!sql2.IsEmpty())
	{
		tmp = BuildSql(sql2);

		if (!myConn->ExecuteVoid(tmp))
		{
			// error message is displayed inside ExecuteVoid
			// Warn the user about partially applied changes, but don't bail out.
			// Carry on as if everything was successful (because the most important
			// change was!!
			wxMessageBox(_("An error occured executing the second stage SQL statement.\n\nChanges may have been partially applied."), _("Warning"), wxICON_EXCLAMATION | wxOK, this);
		}
		else // Only apend schema changes if there was no error.
		{
			if (database)
				database->AppendSchemaChange(tmp);
		}
	}

	ShowObject();

	return true;
}


wxString dlgProperty::BuildSql(const wxString &sql)
{
	wxString tmp;

	if (cbClusterSet && cbClusterSet->GetSelection() > 0)
	{
		replClientData *data = (replClientData *)cbClusterSet->wxItemContainer::GetClientData(cbClusterSet->GetSelection());
		if (data)
		{
			if (data->majorVer > 1 || (data->majorVer == 1 && data->minorVer >= 2))
			{
				// From slony version 2.2.0 onwards ddlscript_prepare() method is removed and
				// ddlscript_complete() method arguments got changed so we have to use ddlcapture() method
				// instead of ddlscript_prepare() and changed the argument of ddlscript_complete() method
				if ((data->majorVer == 2 && data->minorVer >= 2) || (data->majorVer > 2))
				{
					tmp = wxT("SELECT ") + qtIdent(data->cluster)
					      + wxT(".ddlcapture(") + qtDbString(sql) + wxT(", ") + wxT("NULL::text") + wxT(" );\n")
					      + wxT("SELECT ") + qtIdent(data->cluster)
					      + wxT(".ddlscript_complete(") + wxT("NULL::text") + wxT(" );\n");
				}
				else
				{
					tmp = wxT("SELECT ") + qtIdent(data->cluster)
					      + wxT(".ddlscript_prepare(") + NumToStr(data->setId) + wxT(", -1);\n")
					      + sql + wxT(";\n")
					      + wxT("SELECT ") + qtIdent(data->cluster)
					      + wxT(".ddlscript_complete(") + NumToStr(data->setId) + wxT(", ")
					      + qtDbString(sql) + wxT(", -1);\n");
				}
			}
			else
			{
				tmp = wxT("SELECT ") + qtIdent(data->cluster)
				      + wxT(".ddlscript(") + NumToStr(data->setId) + wxT(", ")
				      + qtDbString(sql) + wxT(", 0);\n");
			}
		}
	}
	else
		tmp = sql;

	return tmp;
}


wxArrayString dlgProperty::SplitQueries(const wxString &sql)
{
	wxArrayString queries;
	wxString query;
	wxString c;

	bool antislash = false;
	bool quote_string = false;
	bool doublequote_string = false;

	for (size_t item = 0; item < sql.Length(); item++)
	{
		c = sql.GetChar(item);

		if (c == wxT("\\"))
			antislash = true;

		if (c == wxT("'"))
		{
			if (antislash)
				antislash = false;
			else if (quote_string)
				quote_string = false;
			else if (!doublequote_string)
				quote_string = true;
		}

		if (c == wxT("\""))
		{
			if (antislash)
				antislash = false;
			else if (doublequote_string)
				doublequote_string = false;
			else if (!quote_string)
				doublequote_string = true;
		}

		query = query + c;

		if (c == wxT(";") && !antislash && !quote_string && !doublequote_string)
		{
			queries.Add(query);
			query = wxEmptyString;
		}
	}

	return queries;
}


void dlgProperty::OnOK(wxCommandEvent &ev)
{
#ifdef __WXGTK__
	if (!btnOK->IsEnabled())
		return;
#endif
	if (!IsUpToDate())
	{
		if (wxMessageBox(wxT("The object has been changed by another user. Do you wish to continue to try to update it?"), wxT("Overwrite changes?"), wxYES_NO) != wxYES)
			return;
	}

	EnableOK(false);

	if (IsModal())
	{
		EndModal(0);
		return;
	}

	wxString sql;
	wxString sql2;
	if (chkReadOnly->GetValue())
	{
		sql = GetSql();
		sql2 = GetSql2();
	}
	else
	{
		sql = sqlTextField1->GetText();
		if (enableSQL2)
		{
			sql2 = sqlTextField2->GetText();
		}
		else
		{
			sql2 = wxT("");
		}
	}

	if (!apply(sql, sql2))
	{
		EnableOK(true);
		return;
	}

	Destroy();
}


void dlgProperty::OnPageSelect(wxNotebookEvent &event)
{
	if (sqlTextField1 && chkReadOnly->GetValue() &&
	        event.GetSelection() == (int)nbNotebook->GetPageCount() - 1)
	{
		FillSQLTextfield();
	}
}



void dlgProperty::InitDialog(frmMain *frame, pgObject *node)
{
	CenterOnParent();
	if (!connection)
		connection = node->GetConnection();
	database = node->GetDatabase();

	if (factory != node->GetFactory() && !node->IsCollection())
	{
		wxCookieType cookie;
		wxTreeItemId collectionItem = frame->GetBrowser()->GetFirstChild(node->GetId(), cookie);
		while (collectionItem)
		{
			pgCollection *collection = (pgCollection *)frame->GetBrowser()->GetObject(collectionItem);
			if (collection && collection->IsCollection() && collection->IsCollectionFor(node))
				break;

			collectionItem = frame->GetBrowser()->GetNextChild(node->GetId(), cookie);
		}
		item = collectionItem;
	}
	else
		item = node->GetId();

	// Additional hacks to get the table to refresh when modifying sub-objects
	if (!item && (node->GetMetaType() == PGM_TABLE || node->GetMetaType() == PGM_VIEW
	              || node->GetMetaType() == GP_PARTITION || node->GetMetaType() == PGM_DOMAIN))
		owneritem = node->GetId();

	int metatype = node->GetMetaType();

	switch (metatype)
	{
		case PGM_COLUMN:
			owneritem = node->GetTable()->GetId();
			break;

		case PGM_CHECK:
		case PGM_FOREIGNKEY:
		case PGM_CONSTRAINT:
		case PGM_EXCLUDE:
		case PGM_INDEX:
		case PGM_PRIMARYKEY:
		case PGM_UNIQUE:
		case PGM_TRIGGER:
		case PGM_RULE: // Rules are technically table objects! Yeuch
		case EDB_PACKAGEFUNCTION:
		case EDB_PACKAGEVARIABLE:
		case PGM_SCHEDULE:
		case PGM_STEP:
			if (node->IsCollection())
				owneritem = frame->GetBrowser()->GetParentObject(node->GetId())->GetId();
			else
				owneritem = frame->GetBrowser()->GetParentObject(frame->GetBrowser()->GetParentObject(node->GetId())->GetId())->GetId();
			break;

		default:
			// we want to do this as objects can change schema
			owneritem = node->GetId();
			break;
	}
}


dlgProperty *dlgProperty::CreateDlg(frmMain *frame, pgObject *node, bool asNew, pgaFactory *factory)
{
	if (!factory)
	{
		factory = node->GetFactory();
		if (node->IsCollection())
			factory = ((pgaCollectionFactory *)factory)->GetItemFactory();
	}

	pgObject *currentNode, *parentNode;
	if (asNew)
		currentNode = 0;
	else
		currentNode = node;

	if (factory != node->GetFactory())
		parentNode = node;
	else
		parentNode = frame->GetBrowser()->GetObject(
		                 frame->GetBrowser()->GetItemParent(node->GetId()));

	if (parentNode && parentNode->IsCollection() && parentNode->GetMetaType() != PGM_SERVER)
		parentNode = frame->GetBrowser()->GetObject(
		                 frame->GetBrowser()->GetItemParent(parentNode->GetId()));

	dlgProperty *dlg = 0;

	if (factory)
	{
		dlg = factory->CreateDialog(frame, currentNode, parentNode);
		if (dlg)
		{
			if (factory->IsCollection())
				factory = ((pgaCollectionFactory *)factory)->GetItemFactory();
			wxASSERT(factory);

			dlg->InitDialog(frame, node);

			if (currentNode)
				currentNode->SetWindowPtr(dlg);
		}
	}
	return dlg;
}


bool dlgProperty::CreateObjectDialog(frmMain *frame, pgObject *node, pgaFactory *factory)
{
	if (node->GetMetaType() != PGM_SERVER)
	{
		pgConn *conn = node->GetConnection();
		if (!conn || conn->GetStatus() != PGCONN_OK || !conn->IsAlive())
			return false;
	}

	dlgProperty *dlg = NULL;

	if (node)
		dlg = node->GetWindowPtr();

	if (dlg)
		dlg->Raise();
	else
	{
		dlg = CreateDlg(frame, node, true, factory);

		if (dlg)
		{
			dlg->SetTitle(wxGetTranslation(dlg->factory->GetNewString()));

			dlg->CreateAdditionalPages();
			dlg->Go();
			dlg->CheckChange();
		}
		else
			wxMessageBox(_("Not implemented."));
	}

	return true;
}


bool dlgProperty::EditObjectDialog(frmMain *frame, ctlSQLBox *sqlbox, pgObject *node)
{
	if (node->GetMetaType() != PGM_SERVER)
	{
		pgConn *conn = node->GetConnection();
		if (!conn || conn->GetStatus() != PGCONN_OK || !conn->IsAlive())
			return false;
	}

	// If this is a function or view, hint that the user might want to edit the object in
	// the query tool.
	if (node->GetMetaType() == PGM_FUNCTION || node->GetMetaType() == PGM_VIEW)
	{
		if (frmHint::ShowHint(frame, HINT_OBJECT_EDITING) == wxID_CANCEL)
			return false;
	}

	dlgProperty *dlg = NULL;

	if (node)
		dlg = node->GetWindowPtr();

	if (dlg)
		dlg->Raise();
	else
	{
		dlg = CreateDlg(frame, node, false);

		if (dlg)
		{
			wxString typeName = dlg->factory->GetTypeName();
			dlg->SetTitle(wxString(wxGetTranslation(typeName)) + wxT(" ") + node->GetFullIdentifier());

			dlg->CreateAdditionalPages();
			dlg->Go();

			dlg->CheckChange();
		}
		else
			wxMessageBox(_("Not implemented."));
	}

	return true;
}

wxString dlgProperty::qtDbString(const wxString &str)
{
	// Use the server aware version if possible
	if (connection)
		return connection->qtDbString(str);
	else if (database)
		return database->GetConnection()->qtDbString(str);
	else
	{
		wxString ret = str;
		ret.Replace(wxT("\\"), wxT("\\\\"));
		ret.Replace(wxT("'"), wxT("''"));
		ret.Append(wxT("'"));
		ret.Prepend(wxT("'"));
		return ret;
	}
}

void dlgProperty::OnHelp(wxCommandEvent &ev)
{
	wxString page = GetHelpPage();

	if (!page.IsEmpty())
	{
		if (page.StartsWith(wxT("pg/")))
		{
			if (connection)
			{
				if (connection->GetIsEdb())
					DisplayHelp(page.Mid(3), HELP_ENTERPRISEDB);
				else if (connection->GetIsGreenplum())
					DisplayHelp(page.Mid(3), HELP_GREENPLUM);
				else
					DisplayHelp(page.Mid(3), HELP_POSTGRESQL);
			}
			else
				DisplayHelp(page.Mid(3), HELP_POSTGRESQL);
		}
		else if (page.StartsWith(wxT("slony/")))
			DisplayHelp(page.Mid(6), HELP_SLONY);
		else
			DisplayHelp(page, HELP_PGADMIN);
	}
}

/////////////////////////////////////////////////////////////////////////////


dlgTypeProperty::dlgTypeProperty(pgaFactory *f, frmMain *frame, const wxString &resName)
	: dlgProperty(f, frame, resName)
{
	isVarLen = false;
	isVarPrec = false;
	if (wxWindow::FindWindow(XRCID("txtLength")))
	{
		txtLength = CTRL_TEXT("txtLength");
		txtLength->SetValidator(numericValidator);
		txtLength->Disable();
	}
	else
		txtLength = 0;
	if (wxWindow::FindWindow(XRCID("txtPrecision")))
	{
		txtPrecision = CTRL_TEXT("txtPrecision");
		txtPrecision->SetValidator(numericValidator);
		txtPrecision->Disable();
	}
	else
		txtPrecision = 0;
}


void dlgTypeProperty::FillDatatype(ctlComboBox *cb, bool withDomains, bool addSerials)
{
	FillDatatype(cb, 0, withDomains, addSerials);
}

void dlgTypeProperty::FillDatatype(ctlComboBox *cb, ctlComboBox *cb2, bool withDomains, bool addSerials)
{

	if (dtCache.IsEmpty())
	{
		// A column dialog is directly called, no datatype caching is done.
		// Fetching datatypes from server.
		DatatypeReader tr(database, withDomains, addSerials);
		while (tr.HasMore())
		{
			pgDatatype dt = tr.GetDatatype();

			AddType(wxT("?"), tr.GetOid(), dt.GetQuotedSchemaPrefix(database) + dt.QuotedFullName());
			cb->Append(dt.GetQuotedSchemaPrefix(database) + dt.QuotedFullName());
			if (cb2)
				cb2->Append(dt.GetQuotedSchemaPrefix(database) + dt.QuotedFullName());
			tr.MoveNext();
		}
	}
	else
	{
		// A column dialog is called from a table dialog where we have already cached the datatypes.
		// Using cached datatypes.
		size_t i;
		for (i = 0; i < dtCache.GetCount(); i++)
		{
			AddType(wxT("?"), dtCache.Item(i)->GetOid(), dtCache.Item(i)->GetTypename());
			cb->Append(dtCache.Item(i)->GetTypename());
			if (cb2)
				cb2->Append(dtCache.Item(i)->GetTypename());
		}
	}

}


int dlgTypeProperty::Go(bool modal)
{
	if (GetObject())
	{
		if (txtLength)
			txtLength->SetValidator(numericValidator);
		if (txtPrecision)
			txtPrecision->SetValidator(numericValidator);
	}
	return dlgProperty::Go(modal);
}



void dlgTypeProperty::AddType(const wxString &typ, const OID oid, const wxString quotedName)
{
	wxString vartyp;
	if (typ == wxT("?"))
	{
		switch ((long)oid)
		{
			case PGOID_TYPE_BIT:
			case PGOID_TYPE_BIT_ARRAY:
			case PGOID_TYPE_VARBIT:
			case PGOID_TYPE_VARBIT_ARRAY:
			case PGOID_TYPE_BPCHAR:
			case PGOID_TYPE_BPCHAR_ARRAY:
			case PGOID_TYPE_VARCHAR:
			case PGOID_TYPE_VARCHAR_ARRAY:
				vartyp = wxT("L");
				break;
			case PGOID_TYPE_TIME:
			case PGOID_TYPE_TIME_ARRAY:
			case PGOID_TYPE_TIMETZ:
			case PGOID_TYPE_TIMETZ_ARRAY:
			case PGOID_TYPE_TIMESTAMP:
			case PGOID_TYPE_TIMESTAMP_ARRAY:
			case PGOID_TYPE_TIMESTAMPTZ:
			case PGOID_TYPE_TIMESTAMPTZ_ARRAY:
			case PGOID_TYPE_INTERVAL:
			case PGOID_TYPE_INTERVAL_ARRAY:
				vartyp = wxT("D");
				break;
			case PGOID_TYPE_NUMERIC:
			case PGOID_TYPE_NUMERIC_ARRAY:
				vartyp = wxT("P");
				break;
			default:
				vartyp = wxT(" ");
				break;
		}
	}
	else
		vartyp = typ;

	types.Add(vartyp + NumToStr(oid) + wxT(":") + quotedName);
}


wxString dlgTypeProperty::GetTypeInfo(int sel)
{
	wxString str;
	if (sel >= 0)
		str = types.Item(sel);

	return str;
}


wxString dlgTypeProperty::GetTypeOid(int sel)
{
	wxString str;
	if (sel >= 0)
		str = types.Item(sel).Mid(1).BeforeFirst(':');

	return str;
}


wxString dlgTypeProperty::GetQuotedTypename(int sel)
{
	wxString sql, suffix;
	bool isArray = false;

	if (sel >= 0)
	{
		sql = types.Item(sel).AfterFirst(':');

		// Deal with time/timestamp first as they're special cases
		if (sql.Left(19) == wxT("time with time zone"))
		{
			if (sql.Right(2) == wxT("[]"))
				isArray = true;
			sql = wxT("time");
			suffix = wxT("with time zone");
		}
		else if (sql.Left(21) == wxT("time without time zone"))
		{
			if (sql.Right(2) == wxT("[]"))
				isArray = true;
			sql = wxT("time");
			suffix = wxT("without time zone");
		}
		else if (sql.Left(24) == wxT("timestamp with time zone"))
		{
			if (sql.Right(2) == wxT("[]"))
				isArray = true;
			sql = wxT("timestamp");
			suffix = wxT("with time zone");
		}
		else if (sql.Left(27) == wxT("timestamp without time zone"))
		{
			if (sql.Right(2) == wxT("[]"))
				isArray = true;
			sql = wxT("timestamp");
			suffix = wxT("without time zone");
		}
		else if (sql.Right(2) == wxT("[]"))
		{
			sql = sql.SubString(0, sql.Len() - 3);
			isArray = true;
		}
		else if (sql.Right(3) == wxT("[]\""))
		{
			sql = sql.SubString(1, sql.Len() - 4);
			isArray = true;
		}

		// Stick the length on
		if (isVarLen && txtLength)
		{
			wxString varlen = txtLength->GetValue();
			if (!varlen.IsEmpty() && NumToStr(StrToLong(varlen)) == varlen && StrToLong(varlen) >= minVarLen)
			{
				sql += wxT("(") + varlen;
				if (isVarPrec && txtPrecision)
				{
					wxString varprec = txtPrecision->GetValue();
					if (!varprec.IsEmpty())
						sql += wxT(",") + varprec;
				}
				sql += wxT(")");
			}
		}
	}

	// Append any post-length suffix
	if (suffix.length())
		sql += wxT(" ") + suffix;

	// Append any array decoration
	if (isArray)
		sql += wxT("[]");

	return sql;
}


void dlgTypeProperty::CheckLenEnable()
{
	int sel = cbDatatype->GetGuessedSelection();
	if (sel >= 0)
	{
		wxString info = types.Item(sel);
		isVarPrec = info.StartsWith(wxT("P"));
		isVarLen =  isVarPrec || info.StartsWith(wxT("L")) || info.StartsWith(wxT("D"));
		minVarLen = (info.StartsWith(wxT("D")) ? 0 : 1);
		maxVarLen = isVarPrec ? 1000 :
		            minVarLen ? 0x7fffffff : 10;
	}
}


/////////////////////////////////////////////////////////////////////////////


dlgCollistProperty::dlgCollistProperty(pgaFactory *f, frmMain *frame, const wxString &resName, pgTable *parentNode)
	: dlgProperty(f, frame, resName)
{
	columns = 0;
	table = parentNode;
}


dlgCollistProperty::dlgCollistProperty(pgaFactory *f, frmMain *frame, const wxString &resName, ctlListView *colList)
	: dlgProperty(f, frame, resName)
{
	columns = colList;
	table = 0;
}


int dlgCollistProperty::Go(bool modal)
{
	if (columns)
	{
		int pos;
		// iterate cols
		for (pos = 0 ; pos < columns->GetItemCount() ; pos++)
		{
			wxString col = columns->GetItemText(pos);
			if (cbColumns->FindString(col) < 0)
			{
				cbColumns->Append(col, StrToOid(columns->GetText(pos, 7)));
			}
		}
	}
	if (table)
	{
		wxCookieType cookie;
		pgObject *data;
		wxTreeItemId columnsItem = mainForm->GetBrowser()->GetFirstChild(table->GetId(), cookie);
		while (columnsItem)
		{
			data = mainForm->GetBrowser()->GetObject(columnsItem);
			if (data->GetMetaType() == PGM_COLUMN && data->IsCollection())
				break;
			columnsItem = mainForm->GetBrowser()->GetNextChild(table->GetId(), cookie);
		}

		if (columnsItem)
		{
			wxCookieType cookie;
			pgColumn *column;
			wxTreeItemId item = mainForm->GetBrowser()->GetFirstChild(columnsItem, cookie);

			// check columns
			while (item)
			{
				column = (pgColumn *)mainForm->GetBrowser()->GetObject(item);
				if (column->IsCreatedBy(columnFactory))
				{
					if (column->GetColNumber() > 0)
					{
						cbColumns->Append(column->GetName(), column->GetAttTypId());
					}
				}

				item = mainForm->GetBrowser()->GetNextChild(columnsItem, cookie);
			}
		}
	}

	return dlgProperty::Go(modal);
}



/////////////////////////////////////////////////////////////////////////////


BEGIN_EVENT_TABLE(dlgSecurityProperty, dlgProperty)
	EVT_BUTTON(CTL_ADDPRIV,             dlgSecurityProperty::OnAddPriv)
	EVT_BUTTON(CTL_DELPRIV,             dlgSecurityProperty::OnDelPriv)
#ifdef __WXMAC__
	EVT_SIZE(                           dlgSecurityProperty::OnChangeSize)
#endif
END_EVENT_TABLE();

void dlgSecurityProperty::SetPrivilegesLayout()
{
	securityPage->lbPrivileges->GetParent()->Layout();
}

dlgSecurityProperty::dlgSecurityProperty(pgaFactory *f, frmMain *frame, pgObject *obj, const wxString &resName, const wxString &privList, const char *privChar)
	: dlgProperty(f, frame, resName)
{
	securityChanged = false;


	if (!privList.IsEmpty() && (!obj || obj->CanCreate()))
	{
		securityPage = new ctlSecurityPanel(nbNotebook, privList, privChar, frame->GetImageList());

		if (obj)
		{

			wxArrayString groups;
			// Fetch Groups Information
			pgSet *setGrp = obj->GetConnection()->ExecuteSet(wxT("SELECT groname FROM pg_group ORDER BY groname"));

			if (setGrp)
			{
				while (!setGrp->Eof())
				{
					groups.Add(setGrp->GetVal(0));
					setGrp->MoveNext();
				}
				delete setGrp;
			}

			wxString str = obj->GetAcl();
			if (!str.IsEmpty())
			{
				str = str.Mid(1, str.Length() - 2);
				wxStringTokenizer tokens(str, wxT(","));

				while (tokens.HasMoreTokens())
				{
					wxString str = tokens.GetNextToken();
					if (str[0U] == '"')
						str = str.Mid(1, str.Length() - 2);

					wxString name = str.BeforeLast('=');
					wxString value;

					connection = obj->GetConnection();
					if (connection->BackendMinimumVersion(7, 4))
						value = str.Mid(name.Length() + 1).BeforeLast('/');
					else
						value = str.Mid(name.Length() + 1);

					int icon = userFactory.GetIconId();

					if (name.Left(6).IsSameAs(wxT("group "), false))
					{
						icon = groupFactory.GetIconId();
						name = wxT("group ") + qtStrip(name.Mid(6));
					}
					else if (name.IsEmpty())
					{
						icon = PGICON_PUBLIC;
						name = wxT("public");
					}
					else
					{
						name = qtStrip(name);
						for (unsigned int index = 0; index < groups.Count(); index++)
							if (name == groups[index])
							{
								name = wxT("group ") + name;
								icon = groupFactory.GetIconId();
								break;
							}
					}

					securityPage->lbPrivileges->AppendItem(icon, name, value);
					currentAcl.Add(name + wxT("=") + value);
				}
			}
			else
			{
				int icon = PGICON_PUBLIC;
				wxString name = wxT("public");
				wxString value;
				if (obj->GetMetaType() == PGM_DATABASE)
					value = wxT("Tc");
				else if (obj->GetMetaType() == PGM_FUNCTION)
					value = wxT("X");
				else if (obj->GetMetaType() == PGM_LANGUAGE)
					value = wxT("U");

				if (value != wxEmptyString)
				{
					securityPage->lbPrivileges->AppendItem(icon, name, value);
					currentAcl.Add(name + wxT("=") + value);
				}
			}
		}
	}
	else
		securityPage = NULL;
}


dlgSecurityProperty::~dlgSecurityProperty()
{
}



#ifdef __WXMAC__
void dlgSecurityProperty::OnChangeSize(wxSizeEvent &ev)
{
	if (securityPage)
		securityPage->lbPrivileges->SetSize(wxDefaultCoord, wxDefaultCoord,
		                                    ev.GetSize().GetWidth(), ev.GetSize().GetHeight() - 550);
	if (GetAutoLayout())
	{
		Layout();
	}
}
#endif


int dlgSecurityProperty::Go(bool modal)
{
	if (securityPage)
	{
		if (cbOwner && !cbOwner->GetCount())
		{
			if (!GetObject())
				cbOwner->Append(wxEmptyString);
			AddGroups(cbOwner);
			AddUsers(cbOwner);
		}

		securityPage->SetConnection(connection);
		//securityPage->Layout();
	}

	return dlgProperty::Go(modal);
}


void dlgSecurityProperty::AddGroups(ctlComboBox *comboBox)
{
	if (!((securityPage && securityPage->cbGroups) || comboBox))
		return;

	pgSet *set = connection->ExecuteSet(wxT("SELECT groname FROM pg_group ORDER BY groname"));

	if (set)
	{
		while (!set->Eof())
		{
			if (securityPage && securityPage->cbGroups)
				securityPage->cbGroups->Append(wxT("group ") + set->GetVal(0));
			if (comboBox)
				comboBox->Append(set->GetVal(0));
			set->MoveNext();
		}
		delete set;
	}
}


void dlgSecurityProperty::AddUsers(ctlComboBox *combobox)
{
	if (securityPage && securityPage->cbGroups && settings->GetShowUsersForPrivileges())
	{
		securityPage->stGroup->SetLabel(_("Group/User"));
		dlgProperty::AddUsers(securityPage->cbGroups, combobox);
		Layout();
	}
	else
		dlgProperty::AddUsers(combobox);
}


void dlgSecurityProperty::OnAddPriv(wxCommandEvent &ev)
{
	securityChanged = true;
	EnableOK(btnOK->IsEnabled());
}


void dlgSecurityProperty::OnDelPriv(wxCommandEvent &ev)
{
	securityChanged = true;
	EnableOK(btnOK->IsEnabled());
}


wxString dlgSecurityProperty::GetHelpPage() const
{
	if (nbNotebook->GetSelection() == (int)nbNotebook->GetPageCount() - 2)
		return wxT("pg/sql-grant");
	else
		return dlgProperty::GetHelpPage();
}


void dlgSecurityProperty::EnableOK(bool enable, bool ignoreSql)
{
	// Don't enable the OK button if the object isn't yet created,
	// leave that to the object dialog.
	if (securityChanged && GetObject() && !ignoreSql)
	{
		wxString sql = GetSql();
		if (sql.IsEmpty())
		{
			enable = false;
			securityChanged = false;
		}
		else
			enable = true;
	}
	dlgProperty::EnableOK(enable);
}


wxString dlgSecurityProperty::GetGrant(const wxString &allPattern, const wxString &grantObject)
{
	if (securityPage)
		return securityPage->GetGrant(allPattern, grantObject, &currentAcl);
	else
		return wxString();
}

bool dlgSecurityProperty::DisablePrivilege(const wxString &priv)
{
	if (securityPage)
		return securityPage->DisablePrivilege(priv);
	else
		return true;
}

void dlgSecurityProperty::AppendCurrentAcl(const wxString &name, const wxString &value)
{
	if (!(name.IsEmpty() && value.IsEmpty()))
		currentAcl.Add(name + wxT("=") + value);
}


/////////////////////////////////////////////////////////////////////////////


BEGIN_EVENT_TABLE(dlgDefaultSecurityProperty, dlgSecurityProperty)
	EVT_BUTTON(CTL_DEFADDPRIV, dlgDefaultSecurityProperty::OnAddPriv)
	EVT_BUTTON(CTL_DEFDELPRIV, dlgDefaultSecurityProperty::OnDelPriv)
#ifdef __WXMAC__
	EVT_SIZE(                  dlgDefaultSecurityProperty::OnChangeSize)
#endif
END_EVENT_TABLE();


dlgDefaultSecurityProperty::dlgDefaultSecurityProperty(pgaFactory *f, frmMain *frame, pgObject *obj, const wxString &resName, const wxString &privList, const char *privChar, bool createDefPrivPanel)
	: dlgSecurityProperty(f, frame, obj, resName, privList, privChar), defaultSecurityChanged(false)
{
	pgConn *l_conn = obj ? obj->GetConnection() : connection;
	if ((!obj || obj->CanCreate()) && createDefPrivPanel)
		defaultSecurityPage = new ctlDefaultSecurityPanel(l_conn, nbNotebook, frame->GetImageList());
	else
		defaultSecurityPage = NULL;
}


void dlgDefaultSecurityProperty::AddGroups(ctlComboBox *comboBox)
{
	if (!((securityPage && securityPage->cbGroups) || comboBox || defaultSecurityPage))
		return;

	pgSet *set = connection->ExecuteSet(wxT("SELECT groname FROM pg_group ORDER BY groname"));

	if (set)
	{
		while (!set->Eof())
		{
			if (securityPage && securityPage->cbGroups)
				securityPage->cbGroups->Append(wxT("group ") + set->GetVal(0));

			if (comboBox)
				comboBox->Append(set->GetVal(0));

			if (defaultSecurityPage)
				defaultSecurityPage->m_groups.Add(wxT("group ") + set->GetVal(0));

			set->MoveNext();
		}
		delete set;
	}
}


void dlgDefaultSecurityProperty::AddUsers(ctlComboBox *combobox)
{
	if ((securityPage && securityPage->cbGroups) || defaultSecurityPage || combobox)
	{
		wxString strFetchUserQuery =
		    connection->BackendMinimumVersion(8, 1) ?
		    wxT("SELECT rolname FROM pg_roles WHERE rolcanlogin ORDER BY 1") :
		    wxT("SELECT usename FROM pg_user ORDER BY 1");

		pgSet *set = connection->ExecuteSet(strFetchUserQuery);
		if (set)
		{
			while (!set->Eof())
			{
				if (settings->GetShowUsersForPrivileges())
				{
					if (securityPage && securityPage->cbGroups)
						securityPage->cbGroups->Append(set->GetVal(0));

					if (defaultSecurityPage)
						defaultSecurityPage->m_groups.Add(set->GetVal(0));
				}

				if (combobox)
					combobox->Append(set->GetVal(0));

				set->MoveNext();
			}
		}
	}
}

#ifdef __WXMAC__
void dlgDefaultSecurityProperty::OnChangeSize(wxSizeEvent &ev)
{
	wxSize l_size = ev.GetSize();
	if (defaultSecurityPage && l_size.GetWidth() > 10 && l_size.GetWidth() > 25)
		defaultSecurityPage->SetSize(l_size.GetWidth() - 10, l_size.GetHeight() - 25);
	dlgSecurityProperty::OnChangeSize(ev);
}
#endif


void dlgDefaultSecurityProperty::EnableOK(bool enable, bool ignoreSql)
{
	// Don't enable the OK button if the object isn't yet created,
	// leave that to the object dialog.
	if (GetObject() && !ignoreSql)
	{
		wxString sql = GetSql();
		if (sql.IsEmpty())
		{
			enable = false;
		}
		else
			enable = true;
	}
	dlgSecurityProperty::EnableOK(enable, ignoreSql);
}


void dlgDefaultSecurityProperty::OnAddPriv(wxCommandEvent &ev)
{
	defaultSecurityChanged = true;
	EnableOK(btnOK->IsEnabled());
}


void dlgDefaultSecurityProperty::OnDelPriv(wxCommandEvent &ev)
{
	defaultSecurityChanged = true;
	EnableOK(btnOK->IsEnabled());
}

wxString dlgDefaultSecurityProperty::GetDefaultPrivileges(const wxString &schemaName)
{
	if (defaultSecurityChanged)
		return defaultSecurityPage->GetDefaultPrivileges(schemaName);
	return wxT("");
}

int dlgDefaultSecurityProperty::Go(bool modal, bool createDefPrivs, const wxString &defPrivsOnTables,
                                   const wxString &defPrivsOnSeqs, const wxString &defPrivsOnFuncs,
                                   const wxString &defPrivsOnTypes)
{
	if (securityPage)
	{
		if (cbOwner && !cbOwner->GetCount())
		{
			if (!GetObject())
				cbOwner->Append(wxEmptyString);
			AddGroups(cbOwner);
			AddUsers(cbOwner);
		}

		securityPage->SetConnection(connection);
		//securityPage->Layout();
	}

	int res = dlgSecurityProperty::Go(modal);

	if (defaultSecurityPage)
	{
		if (createDefPrivs && connection->BackendMinimumVersion(9, 0))
			defaultSecurityPage->UpdatePrivilegePages(createDefPrivs, defPrivsOnTables,
			        defPrivsOnSeqs, defPrivsOnFuncs, defPrivsOnTypes);
		else
			defaultSecurityPage->Enable(false);
	}

	return res;
}

wxString dlgDefaultSecurityProperty::GetHelpPage() const
{
	int nDiff      = nbNotebook->GetPageCount() - nbNotebook->GetSelection();

	switch (nDiff)
	{
		case 3:
			return wxT("pg/sql-grant");
		case 2:
			return wxT("pg/sql-alterdefaultprivileges");
		default:
			return dlgProperty::GetHelpPage();
	}
}

/////////////////////////////////////////////////////////////////////////////


BEGIN_EVENT_TABLE(dlgAgentProperty, dlgProperty)
	EVT_BUTTON (wxID_OK,                            dlgAgentProperty::OnOK)
END_EVENT_TABLE();

dlgAgentProperty::dlgAgentProperty(pgaFactory *f, frmMain *frame, const wxString &resName)
	: dlgProperty(f, frame, resName)
{
	recId = 0;
}


wxString dlgAgentProperty::GetSql()
{
	wxString str = GetInsertSql();
	if (!str.IsEmpty())
		str += wxT("\n\n");
	return str + GetUpdateSql();
}



bool dlgAgentProperty::executeSql()
{
	wxString sql;
	bool dataChanged = false;

	sql = GetInsertSql();
	if (!sql.IsEmpty())
	{
		int pos;
		long jobId = 0, schId = 0, stpId = 0;
		if (sql.Contains(wxT("<JobId>")))
		{
			recId = jobId = StrToLong(connection->ExecuteScalar(wxT("SELECT nextval('pgagent.pga_job_jobid_seq');")));
			while ((pos = sql.Find(wxT("<JobId>"))) >= 0)
				sql = sql.Left(pos) + NumToStr(jobId) + sql.Mid(pos + 7);
		}

		if (sql.Contains(wxT("<SchId>")))
		{
			// Each schedule ID should be unique. This'll need work if a schedule hits more than
			// one table or anything.
			recId = schId = StrToLong(connection->ExecuteScalar(wxT("SELECT nextval('pgagent.pga_schedule_jscid_seq');")));
			while ((pos = sql.Find(wxT("<SchId>"))) >= 0)
			{
				sql = sql.Left(pos) + NumToStr(schId) + sql.Mid(pos + 7);
				recId = schId = StrToLong(connection->ExecuteScalar(wxT("SELECT nextval('pgagent.pga_schedule_jscid_seq');")));
			}
		}

		if (sql.Contains(wxT("<StpId>")))
		{
			// Each step ID should be unique. This'll need work if a step hits more than
			// one table or anything.
			recId = stpId = StrToLong(connection->ExecuteScalar(wxT("SELECT nextval('pgagent.pga_jobstep_jstid_seq');")));
			while ((pos = sql.Find(wxT("<StpId>"))) >= 0)
			{
				sql = sql.Left(pos) + NumToStr(stpId) + sql.Mid(pos + 7);
				recId = stpId = StrToLong(connection->ExecuteScalar(wxT("SELECT nextval('pgagent.pga_jobstep_jstid_seq');")));
			}
		}

		pgSet *set = connection->ExecuteSet(sql);
		if (set)
		{
			delete set;
		}
		if (!set)
		{
			return false;
		}
		dataChanged = true;
	}

	sql = GetUpdateSql();
	if (!sql.IsEmpty())
	{
		int pos;
		while ((pos = sql.Find(wxT("<JobId>"))) >= 0)
			sql = sql.Left(pos) + NumToStr(recId) + sql.Mid(pos + 7);

		long newId;
		if (sql.Contains(wxT("<SchId>")))
		{
			// Each schedule ID should be unique. This'll need work if a schedule hits more than
			// one table or anything.
			newId = StrToLong(connection->ExecuteScalar(wxT("SELECT nextval('pgagent.pga_schedule_jscid_seq');")));
			while ((pos = sql.Find(wxT("<SchId>"))) >= 0)
			{
				sql = sql.Left(pos) + NumToStr(newId) + sql.Mid(pos + 7);
				newId = StrToLong(connection->ExecuteScalar(wxT("SELECT nextval('pgagent.pga_schedule_jscid_seq');")));
			}
		}

		if (sql.Contains(wxT("<StpId>")))
		{
			// Each step ID should be unique. This'll need work if a step hits more than
			// one table or anything.
			newId = StrToLong(connection->ExecuteScalar(wxT("SELECT nextval('pgagent.pga_jobstep_jstid_seq');")));
			while ((pos = sql.Find(wxT("<StpId>"))) >= 0)
			{
				sql = sql.Left(pos) + NumToStr(newId) + sql.Mid(pos + 7);
				newId = StrToLong(connection->ExecuteScalar(wxT("SELECT nextval('pgagent.pga_jobstep_jstid_seq');")));
			}
		}

		if (!connection->ExecuteVoid(sql))
		{
			// error message is displayed inside ExecuteVoid
			return false;
		}
		dataChanged = true;
	}

	return dataChanged;
}


void dlgAgentProperty::OnOK(wxCommandEvent &ev)
{
#ifdef __WXGTK__
	if (!btnOK->IsEnabled())
		return;
#endif
	if (!IsUpToDate())
	{
		if (wxMessageBox(wxT("The object has been changed by another user. Do you wish to continue to to try to update it?"), wxT("Overwrite changes?"), wxYES_NO) != wxYES)
			return;
	}

	if (IsModal())
	{
		EndModal(0);
		return;
	}

	connection->ExecuteVoid(wxT("BEGIN TRANSACTION"));

	if (executeSql())
	{
		connection->ExecuteVoid(wxT("COMMIT TRANSACTION"));
		ShowObject();
	}
	else
	{
		connection->ExecuteVoid(wxT("ROLLBACK TRANSACTION"));
	}

	Destroy();
}


propertyFactory::propertyFactory(menuFactoryList *list, wxMenu *mnu, ctlMenuToolbar *toolbar) : contextActionFactory(list)
{
	if (mnu)
		mnu->Append(id, _("&Properties...\tCtrl-Alt-Enter"), _("Display/edit the properties of the selected object."));
	else
		context = false;
	if (toolbar)
		toolbar->AddTool(id, wxEmptyString, *properties_png_bmp, _("Display/edit the properties of the selected object."), wxITEM_NORMAL);
}


wxWindow *propertyFactory::StartDialog(frmMain *form, pgObject *obj)
{
	if (!dlgProperty::EditObjectDialog(form, form->GetSqlPane(), obj))
		form->CheckAlive();

	return 0;
}


bool propertyFactory::CheckEnable(pgObject *obj)
{
	return obj && ((obj->GetMetaType() == PGM_DATABASE) ? (obj->GetConnection() != NULL) : true) && obj->CanEdit();
}


#include "images/create.pngc"
createFactory::createFactory(menuFactoryList *list, wxMenu *mnu, ctlMenuToolbar *toolbar) : actionFactory(list)
{
	mnu->Append(id, _("&Create..."),  _("Create a new object of the same type as the selected object."));
	toolbar->AddTool(id, wxEmptyString, *create_png_bmp, _("Create a new object of the same type as the selected object."), wxITEM_NORMAL);
}


wxWindow *createFactory::StartDialog(frmMain *form, pgObject *obj)
{
	if (!dlgProperty::CreateObjectDialog(form, obj, 0))
		form->CheckAlive();

	return 0;
}


bool createFactory::CheckEnable(pgObject *obj)
{
	return obj && obj->CanCreate();
}


#include "images/drop.pngc"
dropFactory::dropFactory(menuFactoryList *list, wxMenu *mnu, ctlMenuToolbar *toolbar) : contextActionFactory(list)
{
	mnu->Append(id, _("&Delete/Drop...\tDel"),  _("Delete/Drop the selected object."));
	toolbar->AddTool(id, wxEmptyString, *drop_png_bmp, _("Drop the currently selected object."), wxITEM_NORMAL);
}


wxWindow *dropFactory::StartDialog(frmMain *form, pgObject *obj)
{
	form->ExecDrop(false);
	return 0;
}


bool dropFactory::CheckEnable(pgObject *obj)
{
	return obj && obj->CanDrop();
}


dropCascadedFactory::dropCascadedFactory(menuFactoryList *list, wxMenu *mnu, ctlMenuToolbar *toolbar) : contextActionFactory(list)
{
	mnu->Append(id, _("Drop cascaded..."), _("Drop the selected object and all objects dependent on it."));
}


wxWindow *dropCascadedFactory::StartDialog(frmMain *form, pgObject *obj)
{
	form->ExecDrop(true);
	return 0;
}


bool dropCascadedFactory::CheckEnable(pgObject *obj)
{
	return obj && obj->CanDrop() && obj->CanDropCascaded();
}


#include "images/refresh.pngc"
refreshFactory::refreshFactory(menuFactoryList *list, wxMenu *mnu, ctlMenuToolbar *toolbar) : contextActionFactory(list)
{
	if (mnu)
		mnu->Append(id, _("Re&fresh\tF5"), _("Refresh the selected object."));
	else
		context = false;
	if (toolbar)
		toolbar->AddTool(id, wxEmptyString, *refresh_png_bmp, _("Refresh the selected object."), wxITEM_NORMAL);
}


wxWindow *refreshFactory::StartDialog(frmMain *form, pgObject *obj)
{
	if (form)
		obj = form->GetBrowser()->GetObject(form->GetBrowser()->GetSelection());

	if (obj)
		if (CheckEnable(obj))
			form->Refresh(obj);
	return 0;
}


bool refreshFactory::CheckEnable(pgObject *obj)
{
	// This isn't really clean... But we don't have a pgObject::CanRefresh() so far,
	// so it's Good Enough (tm) for now.
	return obj != 0 && !obj->IsCreatedBy(serverFactory.GetCollectionFactory());
}