File: ddTableFigure.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 (1798 lines) | stat: -rw-r--r-- 54,627 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
//////////////////////////////////////////////////////////////////////////
//
// pgAdmin III - PostgreSQL Tools
//
// Copyright (C) 2002 - 2014, The pgAdmin Development Team
// This software is released under the PostgreSQL Licence
//
// ddTableFigure.cpp - Draw table figure of a model
//
////////////////////////////////////////////////////////////////////////////


#include "pgAdmin3.h"

// wxWindows headers
#include <wx/wx.h>
#include <wx/dcbuffer.h>
#include <wx/pen.h>

// App headers
#include "dd/dditems/figures/ddTableFigure.h"
#include "dd/dditems/figures/ddTextTableItemFigure.h"
#include "dd/dditems/figures/ddColumnFigure.h"
#include "hotdraw/main/hdDrawingView.h"
#include "hotdraw/main/hdDrawingEditor.h"
#include "dd/dditems/utilities/ddDataType.h"
#include "dd/dditems/handles/ddAddColButtonHandle.h"
#include "dd/dditems/locators/ddAddColLocator.h"
#include "dd/dditems/handles/ddAddFkButtonHandle.h"
#include "dd/dditems/locators/ddAddFkLocator.h"
#include "dd/dditems/handles/ddRemoveTableButtonHandle.h"
#include "dd/dditems/locators/ddRemoveTableLocator.h"
#include "dd/dditems/handles/ddMinMaxTableButtonHandle.h"
#include "dd/dditems/locators/ddMinMaxTableLocator.h"
#include "dd/dditems/handles/ddScrollBarHandle.h"
#include "dd/dditems/locators/ddScrollBarTableLocator.h"
#include "dd/dditems/handles/ddSouthTableSizeHandle.h"
#include "dd/dditems/locators/ddTableBottomLocator.h"
#include "dd/ddmodel/ddDBReverseEngineering.h"
#include "hotdraw/utilities/hdGeometry.h"
#include "dd/dditems/figures/ddRelationshipFigure.h"
#include "hotdraw/connectors/hdLocatorConnector.h"
#include "hotdraw/main/hdDrawing.h"
#include "dd/ddmodel/ddDatabaseDesign.h"

//Images
#include "images/ddAddColumn.pngc"
#include "images/ddRemoveColumn.pngc"
#include "images/ddAddForeignKey.pngc"
#include "images/ddMaximizeTable.pngc"
#include "images/ddMinimizeTable.pngc"
#include "images/ddRemoveTable.pngc"

/*
All figures title, colums, indexes are store at same array to improve performance in the following order:
	[0] = table border rect
	[1] = table title
	[2] = first column index
	[maxColIndex] = last column index
	[minIdxIndex] = first index index
	[maxIdxIndex] = last index index
*/

void ddTableFigure::Init(wxString tableName, int x, int y)
{
	setKindId(DDTABLEFIGURE);
	internalPadding = 2;
	externalPadding = 4;
	selectingFkDestination = false;

	//Set Value default Attributes
	fontColorAttribute->fontColor = wxColour(49, 79, 79);
	//Set Value default selected Attributes
	lineSelAttribute->pen().SetColour(wxColour(204, 0, 0));
	lineSelAttribute->pen().SetStyle(wxSOLID);
	lineSelAttribute->pen().SetWidth(1);
	fillSelAttribute->brush().SetColour(wxColour(255, 250, 205));
	fillAttribute->brush().SetColour(wxColour(248, 248, 255));
	fontSelColorAttribute->fontColor = wxColour(49, 79, 79);

	//Set table size, width and position
	rectangleFigure = new hdRectangleFigure();
	rectangleFigure->moveTo(0, x, y);
	add(rectangleFigure);

	tableTitle = new ddTextTableItemFigure(tableName, dt_null, NULL);
	tableTitle->setOwnerTable(this);
	tableTitle->setEditable(true);
	tableTitle->moveTo(0, x, y);
	tableTitle->disablePopUp();
	tableTitle->setShowDataType(false);
	add(tableTitle);
	tableTitle->moveTo(0, rectangleFigure->getBasicDisplayBox().x[0] + internalPadding * 2, rectangleFigure->getBasicDisplayBox().y[0] + internalPadding / 2);

	//Intialize handles
	wxBitmap image = wxBitmap(*ddAddColumn_png_img);
	wxSize valueSize = wxSize(8, 8);
	figureHandles->addItem(new ddAddColButtonHandle((hdIFigure *)this, (hdILocator *)new ddAddColLocator(), image, valueSize));
	image = wxBitmap(*ddAddForeignKey_png_img);
	figureHandles->addItem(new ddAddFkButtonHandle((hdIFigure *)this, (hdILocator *)new ddAddFkLocator(), image, valueSize));
	image = wxBitmap(*ddRemoveTable_png_img);
	figureHandles->addItem(new ddRemoveTableButtonHandle((hdIFigure *)this, (hdILocator *)new ddRemoveTableLocator(), image, valueSize));
	image = wxBitmap(*ddMinimizeTable_png_img);
	wxBitmap image2 = wxBitmap(*ddMaximizeTable_png_img);
	figureHandles->addItem(new ddMinMaxTableButtonHandle((hdIFigure *)this, (hdILocator *)new ddMinMaxTableLocator(), image, image2, valueSize));
	figureHandles->addItem(new ddSouthTableSizeHandle(this, (hdILocator *)new ddTableBottomLocator()));

	//Intialize special handle
	valueSize = wxSize(10, colsRect.GetSize().GetHeight());
	scrollbar = new ddScrollBarHandle(this, (hdILocator *)new ddScrollBarTableLocator(), valueSize);

	//Intialize columns window (min is always 1 in both, with or without cols & indxs)
	colsRowsSize = 0;
	colsWindow = 0;
	idxsRowsSize = 0;
	idxsWindow = 0;

	//Initialize indexes (pointers to array segments)
	maxColIndex = 2;
	minIdxIndex = 2;
	maxIdxIndex = 2;

	//Initialize position where start to draw columns & indexes, this is the value to allow scrollbars
	beginDrawCols = 2;
	beginDrawIdxs = 2;

	//Initialize
	pkName = wxEmptyString;
	ukNames.clear();

	updateTableSize();

	basicDisplayBox.x[0] = x;
	basicDisplayBox.y[0] = y;
	belongsToSchema = false;
}

ddTableFigure::ddTableFigure(wxString tableName, int x, int y):
	hdCompositeFigure()
{
	Init(tableName, x, y);
}

ddTableFigure::ddTableFigure(wxString tableName, int posIdx, int x, int y):
	hdCompositeFigure()
{
	Init(tableName, 0, 0);
	//Check figure available positions for diagrams, add at least needed to allow initialization of the class
	int i, start;
	start = basicDisplayBox.CountPositions();
	for(i = start; i < (posIdx + 1); i++)
	{
		AddPosForNewDiagram();
	}
	syncInternalsPosAt(posIdx, x, y);
}

//Used by persistence classes
void ddTableFigure::InitTableValues(wxArrayString UniqueKeysName, wxString primaryKeyName, int bdc, int bdi, int maxcolsi, int minidxsi, int maxidxsi, int colsrs, int colsw, int idxsrs, int idxsw)
{
	ukNames = UniqueKeysName;
	pkName = primaryKeyName;
	beginDrawCols = bdc;
	beginDrawIdxs = bdi;
	maxColIndex = maxcolsi;
	minIdxIndex = minidxsi;
	maxIdxIndex = maxidxsi;
	colsRowsSize = colsrs;
	colsWindow = colsw;
	idxsRowsSize = idxsrs;
	idxsWindow = idxsw;
	updateTableSize();
}

ddTableFigure::~ddTableFigure()
{
	if(scrollbar)
	{
		if(figureHandles->existsObject(scrollbar))
			figureHandles->removeItem(scrollbar);
		delete scrollbar;
	}
}

void ddTableFigure::AddPosForNewDiagram()
{
	//Add new position to internal calculations figure
	fullSizeRect.addNewXYPosition();
	titleRect.addNewXYPosition();
	titleColsRect.addNewXYPosition();
	colsRect.addNewXYPosition();
	titleIndxsRect.addNewXYPosition();
	indxsRect.addNewXYPosition();
	unScrolledColsRect.addNewXYPosition();
	unScrolledFullSizeRect.addNewXYPosition();
	unScrolledTitleRect.addNewXYPosition();
	//Add to all figure figures
	hdCompositeFigure::AddPosForNewDiagram();
}

void ddTableFigure::RemovePosOfDiagram(int posIdx)
{
	//Remove position for internal calculations figure
	fullSizeRect.removeXYPosition(posIdx);
	titleRect.removeXYPosition(posIdx);
	titleColsRect.removeXYPosition(posIdx);
	colsRect.removeXYPosition(posIdx);
	titleIndxsRect.removeXYPosition(posIdx);
	indxsRect.removeXYPosition(posIdx);
	unScrolledColsRect.removeXYPosition(posIdx);
	unScrolledFullSizeRect.removeXYPosition(posIdx);
	unScrolledTitleRect.removeXYPosition(posIdx);
	//remove position at all figure figures
	hdCompositeFigure::RemovePosOfDiagram(posIdx);
}

ddColumnFigure *ddTableFigure::getColByName(wxString name)
{
	ddColumnFigure *out = NULL;
	ddColumnFigure *f;

	hdIteratorBase *iterator = figuresEnumerator();
	iterator->Next(); //First figure is main rect
	iterator->Next(); //Second figure is main title

	while(iterator->HasNext())
	{
		f = (ddColumnFigure *) iterator->Next();
		if(f->getColumnName(false).IsSameAs(name))
		{
			out = f;
			break;
		}
	}
	delete iterator;

	return out;
}

//WARNING: Columns SHOULD BE ADDED only using this function to avoid strange behaviors
void ddTableFigure::addColumn(int posIdx, ddColumnFigure *column)
{
	column->setOwnerTable(this);
	add(column);
	//Update Indexes
	if(maxColIndex == minIdxIndex) //maxColIndex == minIdxIndex means not indexes at this table, then update too
	{
		minIdxIndex++;
		maxIdxIndex++;
	}
	maxColIndex++;
	colsWindow++;  //by default add a column increase initial window
	colsRowsSize++;

	updateTableSize(true);

	//Fix column position at all available positions (Diagrams)
	int i;
	for(i = 0; i < basicDisplayBox.CountPositions(); i++)
	{
		syncInternalsPosAt(i, basicDisplayBox.x[i], basicDisplayBox.y[i]);
	}
}

//WARNING: Function should be called on a table generated from a storage or to sync values after a big change at model (not derived from hotdraw events)
void ddTableFigure::syncInternalsPosAt(int posIdx, int x, int y)
{
	basicDisplayBox.x[posIdx] = x;
	basicDisplayBox.y[posIdx] = y;
	rectangleFigure->moveTo(posIdx, x, y);
	tableTitle->moveTo(posIdx, rectangleFigure->getBasicDisplayBox().x[posIdx] + internalPadding * 2, rectangleFigure->getBasicDisplayBox().y[posIdx] + internalPadding / 2);
	calcInternalSubAreas(posIdx);
	recalculateColsPos(posIdx);
}

//WARNING: Function should be called on a table generated from a storage or to sync values after a big change at model (not derived from hotdraw events)
void ddTableFigure::syncInternalsPosAt(wxArrayInt &x, wxArrayInt &y)
{
	unsigned int posIdx, pointsCount = tableTitle->getBasicDisplayBox().CountPositions(), finalValue = x.Count();
	//I need to check that figures inside figure have all points too
	while(pointsCount < finalValue)
	{
		AddPosForNewDiagram();
		pointsCount = tableTitle->getBasicDisplayBox().CountPositions();
	}

	//optimize this, because this is hack right now to avoid some weird problem when recreating figure status
	basicDisplayBox.x = x;
	basicDisplayBox.y = y;

	for(posIdx = 0; posIdx < finalValue; posIdx++)
	{
		rectangleFigure->moveTo(posIdx, x[posIdx], y[posIdx]);
		tableTitle->moveTo(posIdx, rectangleFigure->getBasicDisplayBox().x[posIdx] + internalPadding * 2, rectangleFigure->getBasicDisplayBox().y[posIdx] + internalPadding / 2);
		calcInternalSubAreas(posIdx);
		recalculateColsPos(posIdx);
	}
}

//WARNING: Columns SHOULD BE ADDED only using this columns if was created as an image from storage one
void ddTableFigure::addColumnFromStorage(ddColumnFigure *column)
{
	add(column);
}

void ddTableFigure::removeColumn(int posIdx, ddColumnFigure *column)
{
	//Hack to allow to remove Fk before delete it.
	if(column->isPrimaryKey() || column->isUniqueKey())
	{
		column->setColumnKindToNone();
	}

	column->setOwnerTable(NULL);
	remove(column);

	if(column)
		delete column;
	//Update Indexes
	if(maxColIndex == minIdxIndex) //means not indexes at this table, then update too
	{
		minIdxIndex--;
		maxIdxIndex--;
	}
	maxColIndex--;
	if(colsRowsSize == colsWindow) //only decrease if size of window and columns is the same
		colsWindow--;
	colsRowsSize--;
	if(beginDrawCols > 2)
		beginDrawCols--;
	calcInternalSubAreas(posIdx);
	recalculateColsPos(posIdx);
	if(colsWindow == colsRowsSize) //if handle need to be removed, remove it
	{
		if(figureHandles->existsObject(scrollbar))
			figureHandles->removeItem(scrollbar);
	}
	//hack to update relationship position when table size change
	manuallyNotifyChange(posIdx);
	column = NULL;
}

void ddTableFigure::recalculateColsPos(int posIdx)
{
	wxFont font = fontAttribute->font();
	int defaultHeight = getColDefaultHeight(font);

	hdIFigure *f = (hdIFigure *) figureFigures->getItemAt(0); //first figure is always Rect
	int horizontalPos = f->displayBox().x[posIdx] + 2;
	int verticalPos = 0;

	for(int i = 2; i < maxColIndex ; i++)
	{
		f = (hdIFigure *) figureFigures->getItemAt(i); //table title
		if( (i >= beginDrawCols) && (i <= (colsWindow + beginDrawCols)) ) //Visible to draw
		{
			verticalPos = colsRect.y[posIdx] + (defaultHeight * (i - beginDrawCols) + ((i - beginDrawCols) * internalPadding));
			f->moveTo(posIdx, horizontalPos, verticalPos);
		}
		else
			f->moveTo(posIdx, -65000, -65000); //any figure outside canvas (x<0 || y<0) is not draw & not used to calculate displaybox
	}
}



void ddTableFigure::basicDraw(wxBufferedDC &context, hdDrawingView *view)
{
	int idx = view->getIdx();
	calcInternalSubAreas(idx);

	if(calcScrolled) //Hack to avoid pass view as parameter to calcInternalSubAreas() because is sometimes called outside a paint event
	{
		view->CalcScrolledPosition(fullSizeRect.x[idx], fullSizeRect.y[idx], &fullSizeRect.x[idx], &fullSizeRect.y[idx]);
		view->CalcScrolledPosition(titleRect.x[idx], titleRect.y[idx], &titleRect.x[idx], &titleRect.y[idx]);
		view->CalcScrolledPosition(titleColsRect.x[idx], titleColsRect.y[idx], &titleColsRect.x[idx], &titleColsRect.y[idx]);
		view->CalcScrolledPosition(colsRect.x[idx], colsRect.y[idx], &colsRect.x[idx], &colsRect.y[idx]);
		view->CalcScrolledPosition(titleIndxsRect.x[idx], titleIndxsRect.y[idx], &titleIndxsRect.x[idx], &titleIndxsRect.y[idx]);
		view->CalcScrolledPosition(indxsRect.x[idx], indxsRect.y[idx], &indxsRect.x[idx], &indxsRect.y[idx]);
		calcScrolled = false;
	}

	hdIFigure *f = (hdIFigure *) figureFigures->getItemAt(0); //table rectangle
	f->draw(context, view);
	f = (hdIFigure *) figureFigures->getItemAt(1); //table title
	f->draw(context, view);

	for(int i = beginDrawCols; i < (colsWindow + beginDrawCols); i++)
	{
		f = (hdIFigure *) figureFigures->getItemAt(i); //table title
		if(f->displayBox().GetPosition(view->getIdx()).x > 0 && f->displayBox().GetPosition(view->getIdx()).y > 0)
		{
			f->draw(context, view);
		}
	}

	reapplyAttributes(context, view); //reset attributes to default of figure because can be modified at Draw functions.

	//Set Font for title "Columns"
	wxFont font = fontAttribute->font();
	int newSize = font.GetPointSize() * 0.7;
	font.SetPointSize(newSize);
	context.SetFont(font);

	//Draw Columns Title Line 1
	context.DrawLine(titleColsRect.GetTopLeft(idx), titleColsRect.GetTopRight(idx));
	//Draw Columns Title
	context.DrawText(wxT("Columns"), titleColsRect.x[idx] + 3, titleColsRect.y[idx]);
	//Draw Columns Title Line 2
	context.DrawLine(titleColsRect.GetBottomLeft(idx), titleColsRect.GetBottomRight(idx));
	//DrawVertical Lines
	context.DrawLine(titleColsRect.GetBottomLeft(idx).x + 11, titleColsRect.GetBottomLeft(idx).y, titleColsRect.GetBottomLeft(idx).x + 11, titleIndxsRect.GetTopLeft(idx).y);
	context.DrawLine(titleColsRect.GetBottomLeft(idx).x + 22, titleColsRect.GetBottomLeft(idx).y, titleColsRect.GetBottomLeft(idx).x + 22, titleIndxsRect.GetTopLeft(idx).y);
	//Draw Indexes Title Line 1
	context.DrawLine(titleIndxsRect.GetTopLeft(idx), titleIndxsRect.GetTopRight(idx));
	//Draw Indexes Title
	//disable until implemented in a future: context.DrawText(wxT("Indexes"),titleIndxsRect.x+3,titleIndxsRect.y);
	//Draw Indexes Title Line 2
	context.DrawLine(titleIndxsRect.GetBottomLeft(idx), titleIndxsRect.GetBottomRight(idx));

	context.SetFont(fontAttribute->font()); 		//after change font return always to initial one

	//Draw scrollbar is needed
	if(scrollbar && figureHandles->existsObject(scrollbar))
		scrollbar->draw(context, view);

	//Use this in a future
	//Hack to show message to select fk destination table
	if(selectingFkDestination)
	{
		context.SetTextForeground(*wxWHITE);
		wxBrush old = context.GetBrush();
		context.SetBrush(*wxBLACK_BRUSH);

		int w, h, x, y;
		context.GetTextExtent(wxString(wxT("Select Destination table of foreign key")), &w, &h);
		x = fullSizeRect.GetTopLeft(idx).x + (((fullSizeRect.GetTopRight(idx).x - fullSizeRect.GetTopLeft(idx).x) - w) / 2);
		y = fullSizeRect.GetTopLeft(idx).y - h - 2;
		context.DrawRectangle(wxRect(x, y, w, h));
		context.DrawText(wxString(wxT("Select Destination table of foreign key")), x, y);

		context.SetBrush(old);
		context.SetTextForeground(*wxBLACK);
		context.SetBackground(*wxWHITE);

		//don't draw anything else then don't reapply default attributes
	}
}

void ddTableFigure::basicDrawSelected(wxBufferedDC &context, hdDrawingView *view)
{
	int idx = view->getIdx();
	calcInternalSubAreas(idx);

	if(calcScrolled) //Hack to avoid pass view as parameter to calcInternalSubAreas() because is sometimes called outside a paint event
	{
		view->CalcScrolledPosition(fullSizeRect.x[idx], fullSizeRect.y[idx], &fullSizeRect.x[idx], &fullSizeRect.y[idx]);
		view->CalcScrolledPosition(titleRect.x[idx], titleRect.y[idx], &titleRect.x[idx], &titleRect.y[idx]);
		view->CalcScrolledPosition(titleColsRect.x[idx], titleColsRect.y[idx], &titleColsRect.x[idx], &titleColsRect.y[idx]);
		view->CalcScrolledPosition(colsRect.x[idx], colsRect.y[idx], &colsRect.x[idx], &colsRect.y[idx]);
		view->CalcScrolledPosition(titleIndxsRect.x[idx], titleIndxsRect.y[idx], &titleIndxsRect.x[idx], &titleIndxsRect.y[idx]);
		view->CalcScrolledPosition(indxsRect.x[idx], indxsRect.y[idx], &indxsRect.x[idx], &indxsRect.y[idx]);
		calcScrolled = false;
	}

	hdIFigure *f = (hdIFigure *) figureFigures->getItemAt(0); //table rectangle
	f->drawSelected(context, view);
	f = (hdIFigure *) figureFigures->getItemAt(1); //table title
	f->drawSelected(context, view);

	for(int i = beginDrawCols; i < (colsWindow + beginDrawCols); i++)
	{
		f = (hdIFigure *) figureFigures->getItemAt(i); //table title
		if(f->displayBox().GetPosition(view->getIdx()).x > 0 && f->displayBox().GetPosition(view->getIdx()).y > 0)
		{
			f->drawSelected(context, view);
		}
	}

	reapplySelAttributes(context, view); //reset attributes to default of figure because can be modified at Draw functions.
	wxFont font = fontAttribute->font();
	float t = font.GetPointSize();
	int newSize = font.GetPointSize() * 0.7;
	font.SetPointSize(newSize);
	context.SetFont(font);

	//Draw Columns Title Line 1
	context.DrawLine(titleColsRect.GetTopLeft(idx), titleColsRect.GetTopRight(idx));
	//Draw Columns Title
	context.DrawText(wxT("Columns"), titleColsRect.x[idx] + 3, titleColsRect.y[idx]);
	//Draw Columns Title Line 2
	context.DrawLine(titleColsRect.GetBottomLeft(idx), titleColsRect.GetBottomRight(idx));
	//DrawVertical Lines
	context.DrawLine(titleColsRect.GetBottomLeft(idx).x + 11, titleColsRect.GetBottomLeft(idx).y, titleColsRect.GetBottomLeft(idx).x + 11, titleIndxsRect.GetTopLeft(idx).y);
	context.DrawLine(titleColsRect.GetBottomLeft(idx).x + 22, titleColsRect.GetBottomLeft(idx).y, titleColsRect.GetBottomLeft(idx).x + 22, titleIndxsRect.GetTopLeft(idx).y);
	//Draw Indexes Title Line 1
	context.DrawLine(titleIndxsRect.GetTopLeft(idx), titleIndxsRect.GetTopRight(idx));
	//Draw Indexes Title
	//disable until implemented in a future: context.DrawText(wxT("Indexes"),titleIndxsRect.x+3,titleIndxsRect.y);
	//Draw Indexes Title Line 2
	context.DrawLine(titleIndxsRect.GetBottomLeft(idx), titleIndxsRect.GetBottomRight(idx));
}

hdMultiPosRect &ddTableFigure::getBasicDisplayBox()
{
	return basicDisplayBox;
}

void ddTableFigure::setColsRowsWindow(int num)
{
	if(num > 0)
	{
		colsWindow = num;
		wxFont font = fontAttribute->font();
		colsRect.height = getColDefaultHeight(font) * colsWindow;
		colsRect.width = getFiguresMaxWidth();
	}
}

int ddTableFigure::getHeightFontMetric(wxString text, wxFont font)
{
	int width, height;
	wxBitmap emptyBitmap(*ddAddColumn_png_img);
	wxMemoryDC temp_dc;
	temp_dc.SelectObject(emptyBitmap);
	temp_dc.SetFont(font);
	temp_dc.GetTextExtent(text, &width, &height);
	return height;
}

int ddTableFigure::getColDefaultHeight(wxFont font)
{
	if(figureFigures->count() <= 0)
	{
		int width, height;
		wxBitmap emptyBitmap(*ddAddColumn_png_img);
		wxMemoryDC temp_dc;
		temp_dc.SelectObject(emptyBitmap);
		temp_dc.SetFont(font);
		temp_dc.GetTextExtent(wxT("NewColumn"), &width, &height);
		return height;
	}
	else
	{
		hdIFigure *f = (hdIFigure *) figureFigures->getItemAt(1); //table title
		return f->displayBox().height;
	}
}

//Show select fk destination Message Hack
void ddTableFigure::setSelectFkDestMode(bool value)
{
	selectingFkDestination = value;
}

int ddTableFigure::getFiguresMaxWidth()
{
	ddColumnFigure *cf;
	hdGeometry g;

	hdIteratorBase *iterator = figuresEnumerator();
	iterator->Next(); //First figure is main rect
	int maxWidth = 0;
	cf = (ddColumnFigure *) iterator->Next(); //Second figure is main title
	maxWidth = g.max(maxWidth, cf->displayBox().width + 20);
	while(iterator->HasNext())
	{
		cf = (ddColumnFigure *) iterator->Next();
		maxWidth = g.max(maxWidth, cf->displayBox().width);
	}
	delete iterator;
	if(figureHandles->existsObject(scrollbar))
		return maxWidth + 11;  //as defined at locator
	else
		return maxWidth;
}

void ddTableFigure::calcInternalSubAreas(int posIdx)
{
	calcScrolled = true;

	int maxWidth = getFiguresMaxWidth() + externalPadding;
	if(maxWidth < 100)
		maxWidth = 100;
	wxFont font = fontAttribute->font();
	int defaultHeight = getColDefaultHeight(font);

	hdRect db = basicDisplayBox.gethdRect(posIdx);

	//*** titleRect
	float t = font.GetPointSize();
	int newSize = font.GetPointSize() * 0.7;
	font.SetPointSize(newSize);
	int colsTitleHeight = getHeightFontMetric(wxT("Columns"), font);

	titleRect.x[posIdx] = db.x;
	titleRect.y[posIdx] = db.y;
	titleRect.width = maxWidth;
	titleRect.height = defaultHeight;

	titleColsRect.x[posIdx] = db.x;
	titleColsRect.y[posIdx] = titleRect.y[posIdx] + titleRect.height;
	titleColsRect.width = maxWidth;
	titleColsRect.height = colsTitleHeight;
	unScrolledTitleRect = titleColsRect;

	//*** colsRect
	colsRect.width = maxWidth;
	if(colsWindow > 0)
		colsRect.height = defaultHeight * colsWindow + (colsWindow * internalPadding);
	else
		colsRect.height = defaultHeight;
	colsRect.x[posIdx] = db.x;
	colsRect.y[posIdx] = titleRect.y[posIdx] + titleRect.height + titleColsRect.height;
	unScrolledColsRect = colsRect;

	//*** idxTitleRect
	titleIndxsRect.width = maxWidth;
	titleIndxsRect.height = colsTitleHeight;
	titleIndxsRect.x[posIdx] = db.x;
	titleIndxsRect.y[posIdx] = colsRect.y[posIdx] + colsRect.height;

	//*** indexesRect
	indxsRect.width = maxWidth;
	indxsRect.height = defaultHeight * idxsWindow + (idxsWindow * internalPadding);
	indxsRect.x[posIdx] = db.x;
	indxsRect.y[posIdx] = titleIndxsRect.y[posIdx] + titleIndxsRect.height;

	//*** FullTable Size
	fullSizeRect.width = maxWidth;
	fullSizeRect.height = titleRect.height + titleColsRect.height + colsRect.height + titleIndxsRect.height + indxsRect.height;
	fullSizeRect.x[posIdx] = db.x;
	fullSizeRect.y[posIdx] = titleRect.y[posIdx];
	unScrolledFullSizeRect = fullSizeRect;

	//Update size
	wxSize sizeValue = fullSizeRect.GetSize();
	rectangleFigure->setSize(sizeValue);
}

void ddTableFigure::updateTableSize(bool notifyChange)
{
	//Step 0: Recalculate displaybox size, in case of an external modification as change of datatype in a fk from a source (data is stored in original table)
	ddColumnFigure *cf;
	hdIteratorBase *iterator = figuresEnumerator();
	iterator->Next(); //First figure is main rect
	cf = (ddColumnFigure *) iterator->Next(); //Second figure is main title
	while(iterator->HasNext())
	{
		cf = (ddColumnFigure *) iterator->Next();
		cf->displayBoxUpdate();
	}
	delete iterator;

	//Step 1: Update table size
	calcInternalSubAreas(0);
	basicDisplayBox.SetSize(fullSizeRect.GetSize());
	if(notifyChange)
	{
		//hack to update relationship position when table size change, but need to be notified to all views only doing it right now for first view
		manuallyNotifyChange(0);
	}
}

hdMultiPosRect &ddTableFigure::getColsSpace()
{
	return unScrolledColsRect;
}

hdMultiPosRect &ddTableFigure::getFullSpace()
{
	return unScrolledFullSizeRect;
}

hdMultiPosRect &ddTableFigure::getTitleRect()
{
	return unScrolledTitleRect;
}


int ddTableFigure::getTotalColumns()
{
	return colsRowsSize;
}

int ddTableFigure::getColumnsWindow()
{
	return colsWindow;
}

void ddTableFigure::setColumnsWindow(int posIdx, int value, bool maximize)
{

	if(!maximize)
	{

		//if value >0 && <= max size table && table+offset < maxColIndex with window
		if( (value > 0) && (value <= colsRowsSize) && (maxColIndex >= ( beginDrawCols + value ) ) )
		{
			colsWindow = value;
			calcInternalSubAreas(posIdx);
			recalculateColsPos(posIdx);
		}

		//if special case of needing to modify beginDrawCols then do it
		if( (value > 0) && (value <= colsRowsSize) && (maxColIndex < ( beginDrawCols + value ) ) )
		{
			if( (beginDrawCols + colsWindow) == maxColIndex) //if index is at max
			{
				int diff = value - colsWindow; // value should be always higher tan colsWindows
				if(diff > 0 && (beginDrawCols - diff) >= 0 )
				{
					beginDrawCols -= diff;
					colsWindow = value;
					calcInternalSubAreas(posIdx);
					recalculateColsPos(posIdx);

				}
			}
		}
	}
	else
	{
		beginDrawCols = 2;
		colsWindow = value;
		calcInternalSubAreas(posIdx);
		recalculateColsPos(posIdx);
	}


	//Hide Scrollbar if needed
	if(colsWindow == colsRowsSize)
	{
		if(figureHandles->existsObject(scrollbar))
			figureHandles->removeItem(scrollbar);
	}
	else
	{
		if (!figureHandles->existsObject(scrollbar))
			figureHandles->addItem(scrollbar);
	}

}

void ddTableFigure::columnsWindowUp(int posIdx)  //move window from number to zero
{
	if( beginDrawCols > 2 )
	{
		beginDrawCols--;
		calcInternalSubAreas(posIdx);
		recalculateColsPos(posIdx);
	}
}

void ddTableFigure::columnsWindowDown(int posIdx)  //move window from number to maxcolumns
{
	if( (beginDrawCols + colsWindow) < maxColIndex)
	{
		beginDrawCols++;
		calcInternalSubAreas(posIdx);
		recalculateColsPos(posIdx);
	}
}

int ddTableFigure::getTopColWindowIndex()
{
	return (beginDrawCols - 2);
}

void ddTableFigure::setPkConstraintName(wxString name)
{
	pkName = name;
}

wxString ddTableFigure::getPkConstraintName()
{
	return pkName;
}

wxArrayString ddTableFigure::getAllColumnsNames()
{
	wxArrayString tmp;
	ddColumnFigure *f;
	tmp.Clear();
	hdIteratorBase *iterator = figuresEnumerator();
	iterator->Next(); //First figure is main rect
	iterator->Next(); //Second figure is main title

	while(iterator->HasNext())
	{
		f = (ddColumnFigure *) iterator->Next();
		tmp.Add(f->getColumnName(false));
	}
	delete iterator;
	return tmp;
}

wxArrayString ddTableFigure::getAllFkSourceColsNames(bool pk, int ukIndex)
{
	wxArrayString tmp;
	ddColumnFigure *f;
	tmp.Clear();
	hdIteratorBase *iterator = figuresEnumerator();
	iterator->Next(); //First figure is main rect
	iterator->Next(); //Second figure is main title

	while(iterator->HasNext())
	{
		f = (ddColumnFigure *) iterator->Next();
		if(pk)
		{
			if(f->isPrimaryKey())
				tmp.Add(f->getColumnName(false));
		}
		else
		{
			if(f->isUniqueKey(ukIndex))
				tmp.Add(f->getColumnName(false));
		}
	}
	delete iterator;
	return tmp;
}

ddColumnFigure *ddTableFigure::getColumnByName(wxString name)
{
	ddColumnFigure *f;
	hdIteratorBase *iterator = figuresEnumerator();
	iterator->Next(); //First figure is main rect
	iterator->Next(); //Second figure is main title

	while(iterator->HasNext())
	{
		f = (ddColumnFigure *) iterator->Next();
		if(f->getColumnName().IsSameAs(name))
		{
			return f;
		}
	}
	delete iterator;
	return NULL;
}

wxArrayString &ddTableFigure::getUkConstraintsNames()
{
	return ukNames;
}

wxString ddTableFigure::getTableName()
{
	ddTextTableItemFigure *c = (ddTextTableItemFigure *) figureFigures->getItemAt(1);
	c->setOneTimeNoAlias();
	return c->getText(false);
}

//set Null on all relationship items with a fk column to be delete or a pk to be removed (pk attribute)
void ddTableFigure::prepareForDeleteFkColumn(ddColumnFigure *column)
{
	hdIteratorBase *iterator = observersEnumerator();
	while(iterator->HasNext())
	{
		ddRelationshipFigure *r = (ddRelationshipFigure *) iterator->Next();
		if(r->getStartFigure() == this)	//Only update FK of connection with this table as source. source ---<| destination
			r->prepareFkForDelete(column);
	}
	delete iterator;

}

//	Note about observers:
//	A table is observed by several relationships at same time, where that observers
//	are just looking for changes that will affect relationship behavior.
//	Ex: if I delete a pk on observed table (source) all observers (destination)
//		should modify their columns to remove that fk created from that pk column.
// Warning: when a relationship is created an observer is added to both sides of relationship
// because this behavior (needed for update connection) to identify if is an observer
// of source table or destination table, should be check end figure, start!=end and end=this is end figure
// If start = and is recursive
void ddTableFigure::updateFkObservers()
{
	hdIteratorBase *iterator = observersEnumerator();
	while(iterator->HasNext())
	{
		ddRelationshipFigure *r = (ddRelationshipFigure *) iterator->Next();
		if(r->getStartFigure() == this)	//Only update FK of connection with this table as source. source ---<| destination
		{
			r->updateForeignKey();
		}
	}
	delete iterator;
}

//If a column change datatype, should alert all others table to adjust their size with new values
void ddTableFigure::updateSizeOfObservers()
{
	//For all tables that are observing this table, update their size
	hdIteratorBase *iterator = observersEnumerator();
	while(iterator->HasNext())
	{
		ddRelationshipFigure *r = (ddRelationshipFigure *) iterator->Next();
		ddTableFigure *destFkTable = (ddTableFigure *) r->getEndFigure();
		destFkTable->updateTableSize();
	}
	delete iterator;
}

//drop foreign keys with this table as origin or destination because table is going to be deleted
void ddTableFigure::processDeleteAlert(hdDrawing *drawing)
{
	hdIteratorBase *iterator = observersEnumerator();
	bool repeatFlag;
	do
	{
		repeatFlag = false;
		iterator->ResetIterator();
		while(iterator->HasNext())
		{
			ddRelationshipFigure *rel = (ddRelationshipFigure *) iterator->Next();
			rel->disconnectStart();
			rel->disconnectEnd();

			drawing->getOwnerEditor()->removeFromAllSelections(rel);
			drawing->getOwnerEditor()->deleteModelFigure(rel);
			repeatFlag = true;
			break;
		}
	}
	while(repeatFlag);

	delete iterator;
}

void ddTableFigure::basicMoveBy(int posIdx, int x, int y)
{

	hdIFigure *f = (hdIFigure *) figureFigures->getItemAt(0);
//Hack to avoid bug in if clause
	int width =  spaceForMovement.GetWidth();
	int height =  spaceForMovement.GetHeight();
	int bottom = f->displayBox().y[posIdx] + f->displayBox().height + y;
	int right = f->displayBox().x[posIdx] + f->displayBox().width + x;
	int left = f->displayBox().x[posIdx] + x;
	int top = f->displayBox().y[posIdx] + y;

//limit movemnt of table figures to canvas space
	if( (left > 0) && (top > 0) && (right < width) && (bottom < height) )
		hdCompositeFigure::basicMoveBy(posIdx, x, y);
}

//Validate status of table for SQL DDL generation
bool ddTableFigure::validateTable(wxString &errors)
{
	bool out = true;
	wxString tmp = wxEmptyString;
	ddColumnFigure *f;

	hdIteratorBase *iterator = figuresEnumerator();
	iterator->Next(); //First figure is main rect
	iterator->Next(); //Second figure is main title

	while(iterator->HasNext())
	{
		f = (ddColumnFigure *) iterator->Next();
		if(!f->validateColumn(tmp))
		{
			out = false;
		}
	}

	if(!out)
	{
		errors.Append(wxT("\n"));
		errors.Append(wxT("Errors detected at table") + this->getTableName() + wxT(" \n"));
		errors.Append(tmp);
		errors.Append(wxT("\n"));
	}

	delete iterator;

	return out;
}

//Using some options from http://www.postgresql.org/docs/8.1/static/sql-createtable.html, but new options can be added in a future.
wxString ddTableFigure::generateSQLCreate(wxString schemaName)
{
	//Columns and table
	wxString tmp(wxT("CREATE TABLE "));
	if(!schemaName.IsEmpty())
	{
		tmp += wxT("\"") + schemaName + wxT("\".\"") + getTableName() + wxT("\" (\n");
	}
	else
	{
		tmp += wxT("\"") + getTableName() + wxT("\" (\n");
	}
	hdIteratorBase *iterator = figuresEnumerator();
	iterator->Next(); //Fixed Position for table rectangle
	iterator->Next(); //Fixed Position for table name
	while(iterator->HasNext())
	{
		ddColumnFigure *column = (ddColumnFigure *) iterator->Next();
		tmp += column->generateSQL();
		if(column->isNotNull())
		{
			tmp += wxT(" NOT NULL");
		}
		if(iterator->HasNext())
		{
			tmp += wxT(" , \n");
		}
	}
	tmp += wxT("\n ); ");

	return tmp;
}

wxString ddTableFigure::generateSQLAlterPks(wxString schemaName)
{
	wxString tmp;
	hdIteratorBase *iterator = figuresEnumerator();
	//Pk, Uk Constraints
	iterator->Next(); //Fixed Position for table rectangle
	iterator->Next(); //Fixed Position for table name
	int contPk = 0;
	while(iterator->HasNext())
	{
		ddColumnFigure *column = (ddColumnFigure *) iterator->Next();
		if(column->isPrimaryKey())
			contPk++;
	}
	if(contPk > 0)
	{
		tmp += wxT("\nALTER TABLE ");
		if(!schemaName.IsEmpty())
		{
			tmp += wxT("\"") + schemaName + wxT("\".\"") + getTableName() + wxT("\"");
		}
		else
		{
			tmp += wxT("\"") + getTableName() + wxT("\"") ;
		}

		tmp += wxT(" ADD ");

		if(!pkName.IsEmpty())
		{
			tmp += wxT("CONSTRAINT \"") + pkName + wxT("\" ");
		}
		tmp += wxT("PRIMARY KEY ( ");
		iterator->ResetIterator();
		iterator->Next(); //Fixed Position for table rectangle
		iterator->Next(); //Fixed Position for table name

		while(iterator->HasNext())
		{
			ddColumnFigure *column = (ddColumnFigure *) iterator->Next();
			if(column->isPrimaryKey())
			{
				tmp += wxT("\"") + column->getColumnName() + wxT("\"");
				contPk--;
				if(contPk > 0)
				{
					tmp += wxT(" , ");
				}
				else
				{
					tmp += wxT(" ); ");
				}
			}
		}
	}
	delete iterator;

	return tmp;
}

wxString ddTableFigure::generateSQLAlterFks(wxString schemaName)
{
	wxString tmp;
	hdIteratorBase *iterator = figuresEnumerator();
	//Fk Constraint
	iterator = observersEnumerator();
	if(!iterator->HasNext())
	{
		tmp = wxEmptyString;
	}
	else
	{
		while(iterator->HasNext())
		{
			ddRelationshipFigure *rel = (ddRelationshipFigure *) iterator->Next();
			if(rel->getStartFigure() != this)
			{
				tmp += rel->generateSQL(schemaName);
			}
		}
	}
	delete iterator;
	return tmp;
}

wxString ddTableFigure::generateSQLAlterUks(wxString schemaName)
{
	hdIteratorBase *iterator = figuresEnumerator();

	//Pk, Uk Constraints
	iterator->Next(); //Fixed Position for table rectangle
	iterator->Next(); //Fixed Position for table name
	int MaxUk = -1;
	while(iterator->HasNext())
	{
		ddColumnFigure *column = (ddColumnFigure *) iterator->Next();
		if(column->isUniqueKey() && column->getUniqueConstraintIndex() > MaxUk)
			MaxUk = column->getUniqueConstraintIndex();
	}

	wxString tmp = wxEmptyString;
	if(MaxUk >= 0)
	{
		int i;
		for(i = 0; i <= MaxUk; i++)
		{
			tmp += wxT("\nALTER TABLE ");

			if(!schemaName.IsEmpty())
				tmp += wxT("\"") + schemaName + wxT("\".");
			tmp += wxT("\"") + getTableName() + wxT("\"") ;

			tmp += wxT(" ADD ");

			if(!getUkConstraintsNames()[i].IsEmpty())
			{
				tmp += wxT("CONSTRAINT \"") + getUkConstraintsNames()[i] + wxT("\" ") ;
			}
			tmp += wxT("UNIQUE ( ");

			int countUk = 0;
			iterator->ResetIterator();
			iterator->Next(); //Fixed Position for table rectangle
			iterator->Next(); //Fixed Position for table name
			while(iterator->HasNext())
			{
				ddColumnFigure *column = (ddColumnFigure *) iterator->Next();
				if(column->getUniqueConstraintIndex() == i)
					countUk++;
			}

			iterator->ResetIterator();
			iterator->Next(); //Fixed Position for table rectangle
			iterator->Next(); //Fixed Position for table name
			while(iterator->HasNext())
			{
				ddColumnFigure *column = (ddColumnFigure *) iterator->Next();
				if(column->isUniqueKey() && column->getUniqueConstraintIndex() == i)
				{
					tmp += wxT("\"") + column->getColumnName() + wxT("\"");
					countUk--;
					if(countUk > 0)
					{
						tmp += wxT(", ");
					}
				}
			}
			tmp += wxT(" ); ");
		}
	}
	delete iterator;
	return tmp;
}

wxString ddTableFigure::generateAltersTable(pgConn *connection, wxString schemaName, ddDatabaseDesign *design)
{
	wxString out;

	OID oidTable = ddImportDBUtils::getTableOID(connection, schemaName, getTableName());
	if(oidTable == -1)
	{
		wxMessageBox(wxString::Format(_("Cannot build an ALTER TABLE statement for a non existing table (%s.%s)."),
		                              schemaName.c_str(), getTableName().c_str()), _("Error when trying to get table OID"),  wxICON_ERROR);
		return wxEmptyString;
	}

	ddStubTable *dbTable = ddImportDBUtils::getTable(connection, getTableName(), oidTable);
	if(!dbTable)
	{
		wxMessageBox(wxString::Format(_("Cannot reverse engineering table %s.%s."),
		                              schemaName.c_str(), getTableName().c_str()), _("Error when trying to get stub table"),  wxICON_ERROR);
		return wxEmptyString;
	}

	//--------------- DETECT TABLE LEVEL CHANGES

	// Check if TABLE was renamed
	// **Not supported yet**

	// Check if PRIMARY KEY constraint was renamed
	// Some models don't set a name for the primary key, so we ignore those models
	if(this->getPkConstraintName().Len() > 0 && !dbTable->PrimaryKeyName.IsSameAs(this->getPkConstraintName()))
	{
		out += wxT("\n");
		out += wxT("ALTER INDEX \"") + dbTable->PrimaryKeyName + wxT("\" RENAME TO \"") + this->getPkConstraintName() + wxT("\";");
		out += wxT("\n");
	}

	// Check if a UNIQUE KEY constraint was renamed
	// **Not supported yet** (is it possible?)

	//--------------- DETECT COLUMN LEVEL CHANGES

	// Check if A COLUMN was renamed
	// **Not supported yet**

	// Look for columns that exist in the database but not in the model
	bool pkRemovedflag = false;
	bool ukRemoved = false;
	stubColsHashMap::iterator it;
	ddStubColumn *item;

	for (it = dbTable->cols.begin(); it != dbTable->cols.end(); ++it)
	{
		wxString key = it->first;
		item = it->second;
		ddColumnFigure *column = getColumnByName(key);

		// Check for changes at the column
		if(column)
		{
			// Generate ALTER COLUMN statement if needed
			// Datatype change, length, and precision are checked

			// Temporary conversion fix to datatype of designer should be improved in a future
			wxString dataType = item->typeColumn->Name();
			bool sameDatatype = true, sameScale = true, samePrecision = true;
			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)");
			}

			if(needps)
			{
				if(useScale)
				{
					samePrecision = column->getPrecision() == s;
				}
				else
				{
					samePrecision = column->getPrecision() == s;
					sameScale = column->getScale() == p;
				}
			}


			sameDatatype = column->getRawDataType().IsSameAs(dataType, false);

			if(!samePrecision || !sameScale || !sameDatatype)
			{
				out += wxT("\n");
				out += wxT("ALTER TABLE ");

				if(!schemaName.IsEmpty())
					out += wxT("\"") + schemaName + wxT("\".");
				out += wxT("\"") + getTableName() + wxT("\"") ;

				out	+= wxT(" ALTER COLUMN ") + column->generateSQL(true) + wxT(";");
				out += wxT("\n");
			}
		}
		else  // DROP COLUMN because it doesn't exist in the model anymore
		{
			out += wxT("\n");
			out += wxT("ALTER TABLE ");

			if(!schemaName.IsEmpty())
				out += wxT("\"") + schemaName + wxT("\".");
			out += wxT("\"") + getTableName() + wxT("\"") ;

			out += wxT(" DROP COLUMN \"") + key + wxT("\";");
			out += wxT("\n");
			if(item->isPrimaryKey)
			{
				pkRemovedflag = true;
			}
		}
	}

	// Look for columns that exist in the model but not in the database
	hdIteratorBase *iteratorPK = figuresEnumerator();
	iteratorPK->Next(); //Fixed Position for table rectangle
	iteratorPK->Next(); //Fixed Position for table name

	bool pkAddedflag = false;
	while(iteratorPK->HasNext())
	{
		ddColumnFigure *column = (ddColumnFigure *) iteratorPK->Next();
		if(dbTable->cols.find(column->getColumnName()) == dbTable->cols.end())  //Exist in model but not in db
		{
			out += wxT("\n");
			out += wxT("ALTER TABLE ");
			if(!schemaName.IsEmpty())
				out += wxT("\"") + schemaName + wxT("\".");
			out += wxT("\"") + getTableName() + wxT("\"") ;
			out += wxT(" ADD COLUMN ") + column->generateSQL() + wxT(";");
			out += wxT("\n");
			if(column->isPrimaryKey())
			{
				pkAddedflag = true;
			}
		}
	}

	// Look for all PRIMARY columns in the database's tables
	bool pkChanged = false;
	iteratorPK->ResetIterator();
	iteratorPK->Next(); //Fixed Position for table rectangle
	iteratorPK->Next(); //Fixed Position for table name
	while(iteratorPK->HasNext())
	{
		ddColumnFigure *column = (ddColumnFigure *) iteratorPK->Next();
		if(column->isPrimaryKey())
		{
			if(dbTable->cols.find(column->getColumnName()) == dbTable->cols.end())
			{
				pkChanged = true;
			}
			else
			{
				if(!dbTable->cols[column->getColumnName()]->isPrimaryKey)
				{
					pkChanged = true;
				}
			}
		}
	}
	delete iteratorPK;

	// Look for all PRIMARY columns in the model
	stubColsHashMap::iterator itCol;
	ddStubColumn *itemCol;
	for (itCol = dbTable->cols.begin(); itCol != dbTable->cols.end(); ++itCol)
	{
		wxString colStubName = itCol->first;
		itemCol = itCol->second;
		if(itemCol->isPrimaryKey)
		{
			ddColumnFigure *col = getColumnByName(colStubName);
			if(col != NULL)
			{
				if(!col->isPrimaryKey())
				{
					pkChanged = true;
				}
			}
			else
			{
				pkChanged = true;
			}
		}
	}


	// Handle the addition of a new column to the primary key
	if(pkAddedflag || pkRemovedflag || pkChanged)
	{
		// Drop existing primary key
		out += wxT("\n");
		out += wxT("ALTER TABLE ");
		if(!schemaName.IsEmpty())
			out += wxT("\"") + schemaName + wxT("\".");
		out += wxT("\"") + getTableName() + wxT("\"") ;
		out += wxT(" DROP CONSTRAINT \"") + this->getPkConstraintName() + wxT("\";");
		// Create the new one
		out += generateSQLAlterPks(schemaName);
	}

	// Handle changes from NOT NULL to NULL (always after dropping PK)
	for (it = dbTable->cols.begin(); it != dbTable->cols.end(); ++it)
	{
		wxString key = it->first;
		item = it->second;
		ddColumnFigure *column = getColumnByName(key);

		// Check for changes at the column level
		if(column)
		{
			// Generate ALTER COLUMN statement if needed
			// Datatype change, length and precision are handled.

			// Temporary conversion fix to datatype of designer should be improved in a future
			wxString dataType = item->typeColumn->Name();
			bool sameDatatype = true, sameScale = true, samePrecision = true;
			int s = -1, p = -1;

			// Model has now NULL constraint, so drop the NOT NULL constraint
			if(column->isNotNull())
			{
				if(!item->isNotNull)
				{
					out += wxT("\n");
					out += wxT("ALTER TABLE ");
					if(!schemaName.IsEmpty())
						out += wxT("\"") + schemaName + wxT("\".");
					out += wxT("\"") + getTableName() + wxT("\"") ;
					out += wxT(" ALTER COLUMN \"") + column->getColumnName() + _("\" SET NOT NULL;");
					out += wxT("\n");
				}
			}
			else if(!column->isNotNull())
			{
				if(item->isNotNull)
				{
					out += wxT("\n");
					out += wxT("ALTER TABLE \"");
					if(!schemaName.IsEmpty())
						out += wxT("\"") + schemaName + wxT("\".");
					out += wxT("\"") + getTableName() + wxT("\"") ;
					out += wxT("\" ALTER COLUMN \"") + column->getColumnName() + wxT("\" DROP NOT NULL;");
					out += wxT("\n");
				}
			}
		}
	}

	// Check UK conditions
	int i, maxUkn = this->getUkConstraintsNames().Count();
	for(i = 0; i < maxUkn; i++)
	{
		if(this->getUkConstraintsNames()[i].Len() == 0)
		{
			wxMessageBox(wxString::Format(_("Some UNIQUE keys on table %s have no name.\nYou should set a name for them, so that pgAdmin can check consistency with the already available database constraints."),
			                              getTableName().c_str()), _("Trying to build ALTER sentences"),  wxICON_ERROR);
			return wxEmptyString;
		}
	}

	// Search for UNIQUE key deleted from model, but available in the database
	// Two steps process: first drop then delete from wxarraystring
	int maxUkStub = dbTable->UniqueKeysNames.Count();
	for(i = 0; i < maxUkStub; i++)
	{
		// Drop UK [in db but not in model]
		if(this->getUkConstraintsNames().Index(dbTable->UniqueKeysNames[i]) == wxNOT_FOUND)
		{
			// Drop it
			out += wxT("\n");
			out += wxT("DROP INDEX \"") + dbTable->UniqueKeysNames[i] + wxT("\";");
			out += wxT("\n");

			// This index metadata is not useful anymore, so erase it at temporary stub table.
			stubColsHashMap::iterator itDelUkIdx;
			ddStubColumn *itemDelUkIdx;
			for (itDelUkIdx = dbTable->cols.begin(); itDelUkIdx != dbTable->cols.end(); ++itDelUkIdx)
			{
				wxString keyDelUkIdx = itDelUkIdx->first;
				itemDelUkIdx = itDelUkIdx->second;
				if(itemDelUkIdx->uniqueKeyIndex == i)
				{
					itemDelUkIdx->uniqueKeyIndex = -1;
				}
			}
		}
	}

	maxUkStub = dbTable->UniqueKeysNames.Count();
	for(i = 0; i < maxUkStub; i++)
	{
		// Drop UK [in db but not in model]
		if(this->getUkConstraintsNames().Index(dbTable->UniqueKeysNames[i]) == wxNOT_FOUND)
		{
			dbTable->UniqueKeysNames.RemoveAt(i);
			maxUkStub = dbTable->UniqueKeysNames.Count();
		}
	}

	// Search for new UK in model to add ADD CONSTRAINT clause
	int maxUkModel = this->getUkConstraintsNames().Count();
	for(i = 0; i < maxUkModel; i++)
	{
		// Add UK [in model but not in db]
		if(dbTable->UniqueKeysNames.Index(this->getUkConstraintsNames()[i]) == wxNOT_FOUND)
		{
			// Create it
			out += wxT("\nALTER TABLE ");
			if(!schemaName.IsEmpty())
				out += wxT("\"") + schemaName + wxT("\".");
			out += wxT("\"") + getTableName() + wxT("\"") ;
			out += wxT(" ADD ");
			if(!getUkConstraintsNames()[i].IsEmpty())
			{
				out += wxT(" CONSTRAINT \"") + getUkConstraintsNames()[i] + wxT("\" ");
			}
			out += wxT(" UNIQUE ( ");

			int countUk = 0;
			hdIteratorBase *iteratorUk = figuresEnumerator();
			iteratorUk->Next(); //Fixed Position for table rectangle
			iteratorUk->Next(); //Fixed Position for table name
			while(iteratorUk->HasNext())
			{
				ddColumnFigure *column = (ddColumnFigure *) iteratorUk->Next();
				if(column->getUniqueConstraintIndex() == i)
					countUk++;
			}

			iteratorUk->ResetIterator();
			iteratorUk->Next(); //Fixed Position for table rectangle
			iteratorUk->Next(); //Fixed Position for table name
			while(iteratorUk->HasNext())
			{
				ddColumnFigure *column = (ddColumnFigure *) iteratorUk->Next();
				if(column->isUniqueKey() && column->getUniqueConstraintIndex() == i)
				{
					out += wxT("\"") + column->getColumnName() + wxT("\"");
					countUk--;
					if(countUk > 0)
					{
						out += wxT(", ");
					}
					else
					{
						out += wxT(");");
					}
				}
			}
			delete iteratorUk;
		}
	}

	// After delete/create UK, look for changes at existing UK
	// Unified UK indexes at both dbtable and ddTableFigure [same index at dbtable that in tablefigure]
	// BUT in table figure exists indexes without an equivalent in dbtable
	maxUkStub = this->getUkConstraintsNames().Count();
	for(i = 0; i < maxUkStub; i++)
	{
		int oldIndex = dbTable->UniqueKeysNames.Index(this->getUkConstraintsNames()[i]);
		int newIndex = i;

		if(oldIndex != wxNOT_FOUND)
		{
			stubColsHashMap::iterator itDelUkIdx;
			ddStubColumn *itemDelUkIdx;
			for (itDelUkIdx = dbTable->cols.begin(); itDelUkIdx != dbTable->cols.end(); ++itDelUkIdx)
			{
				wxString keyDelUkIdx = itDelUkIdx->first;
				itemDelUkIdx = itDelUkIdx->second;
				if(item->uniqueKeyIndex == oldIndex)
				{
					item->uniqueKeyIndex = newIndex;
				}
			}
		}
	}

	// Generate again those UK that fill one of these conditions:
	// 1. UK at tablefigure have more columns that at stub
	// 2. Uk at stub have more column that at tablefigure
	// Right now, UK constraints have unified indexes (same index at tablefigure and stub)
	maxUkStub = this->getUkConstraintsNames().Count();

	// for each UK
	for(i = 0; i < maxUkStub; i++)
	{
		// Only for UKs with number unified that exists at both sides [db and tablefigure] [with boundaries check]
		int boundarie1 = getUkConstraintsNames().Count();
		int boundarie2 = dbTable->UniqueKeysNames.Count();
		if( (i < boundarie1) && (i < boundarie2) && getUkConstraintsNames().Index( dbTable->UniqueKeysNames[i]) != wxNOT_FOUND )
		{
			// Assumption
			bool createUkAgain = false;

			// CHECK FIRST CONDITION --->   1. UK at tablefigure have more columns that at stub?
			hdIteratorBase *iteratorUk = figuresEnumerator();
			iteratorUk->Next(); //Fixed Position for table rectangle
			iteratorUk->Next(); //Fixed Position for table name

			while(iteratorUk->HasNext())
			{
				ddColumnFigure *column = (ddColumnFigure *) iteratorUk->Next();
				// For each UK column of the constraint with same index (position i, constraint at getUkConstraintsNames()[] )
				if(column->getUniqueConstraintIndex() == i)
				{
					if(dbTable->cols.find(column->getColumnName()) == dbTable->cols.end())  //found at dbtable that uk column
					{
						createUkAgain = true;
					}
					else
					{
						ddStubColumn *stubCol = dbTable->cols[column->getColumnName()];
						if(!stubCol->isUniqueKey())
						{
							createUkAgain = true;
						}
					}
				}
			}
			delete iteratorUk;

			// CHECK SECOND CONDITION --->   UK at stub have more uk column of same index that at tablefigure?
			stubColsHashMap::iterator itCol;
			ddStubColumn *itemCol;
			for (itCol = dbTable->cols.begin(); itCol != dbTable->cols.end(); ++itCol)
			{
				bool isAtFigure = false;
				wxString colStubName = itCol->first;
				itemCol = itCol->second;
				if(itemCol->uniqueKeyIndex == i)
				{
					ddColumnFigure *colUk = getColumnByName(colStubName);
					if(colUk == NULL)
					{
						createUkAgain = true;
					}
					else
					{
						if(!colUk->isUniqueKey())
						{
							createUkAgain = true;
						}
					}
				}
			}

			if(createUkAgain)
			{
				// Drop it
				out += wxT("\n");
				out += wxT("DROP INDEX \"") + dbTable->UniqueKeysNames[i] + wxT("\";");
				out += wxT("\n");

				// Create it
				out += wxT("\nALTER TABLE ");
				if(!schemaName.IsEmpty())
					out += wxT("\"") + schemaName + wxT("\".");
				out += wxT("\"") + getTableName() + wxT("\"") ;
				out += wxT(" ADD ");
				if(!getUkConstraintsNames()[i].IsEmpty())
				{
					out += wxT(" CONSTRAINT \"") + getUkConstraintsNames()[i] + wxT("\" ");
				}
				out += wxT(" UNIQUE ( ");

				int countUk = 0;
				hdIteratorBase *iteratorUk = figuresEnumerator();
				iteratorUk->Next(); //Fixed Position for table rectangle
				iteratorUk->Next(); //Fixed Position for table name
				while(iteratorUk->HasNext())
				{
					ddColumnFigure *column = (ddColumnFigure *) iteratorUk->Next();
					if(column->getUniqueConstraintIndex() == i)
						countUk++;
				}

				iteratorUk->ResetIterator();
				iteratorUk->Next(); //Fixed Position for table rectangle
				iteratorUk->Next(); //Fixed Position for table name
				while(iteratorUk->HasNext())
				{
					ddColumnFigure *column = (ddColumnFigure *) iteratorUk->Next();
					if(column->isUniqueKey() && column->getUniqueConstraintIndex() == i)
					{
						out += wxT("\"") + column->getColumnName() + wxT("\"");
						countUk--;
						if(countUk > 0)
						{
							out += wxT(", ");
						}
						else
						{
							out += wxT(" );");
						}
					}
				}
				delete iteratorUk;
			}
		}
	}

	// Validate all FKs have a name defined at model
	hdIteratorBase *iteratorRelations = observersEnumerator();
	while(iteratorRelations->HasNext())
	{
		ddRelationshipFigure *r = (ddRelationshipFigure *) iteratorRelations->Next();
		if(r->getConstraintName().Len() == 0)	// Add to list, FKs with this table as destination. source ---<| destination
		{
			wxMessageBox(wxString::Format(_("Some foreign keys keys on table %s have no name.\nYou should set a name for them, so that pgAdmin can check consistency with the already available database constraints."),
			                              getTableName().c_str()), _("Trying to build ALTER sentences"),  wxICON_ERROR);
			return wxEmptyString;
		}
	}

	//Check Foreign Keys
	// FK at model are same (including attributes and columns) at db
	iteratorRelations->ResetIterator();
	while(iteratorRelations->HasNext())
	{
		ddRelationshipFigure *r = (ddRelationshipFigure *) iteratorRelations->Next();
		if(r->getEndFigure() == this)	// Only check FK this table as destination. source ---<| destination
		{
			// Check relationship from model exists a db?
			if(ddImportDBUtils::existsFk(connection, dbTable->OIDTable, schemaName, r->getConstraintName(), r->getStartTable()->getTableName()))
			{
				// Columns and other properties are exactly the same? if not, then drop and create again
				if(!ddImportDBUtils::isModelSameDbFk(connection, dbTable->OIDTable, schemaName, r->getConstraintName(), r->getStartTable()->getTableName(), r->getEndTable()->getTableName(), dbTable, r))
				{
					// Drop it first
					out += wxT("\n");
					out += wxT("ALTER TABLE ");
					if(!schemaName.IsEmpty())
						out += wxT("\"") + schemaName + wxT("\".");
					out += wxT("\"") + this->getTableName() + wxT("\"") ;
					out += wxT(" DROP CONSTRAINT \"") + r->getConstraintName() + wxT("\";");
					out += wxT("\n");

					// Then Add it again with changes
					out += r->generateSQL(schemaName);

				}
			}
			else //relationship only exists at model and not in db
			{
				//Create because it doesn't exists
				out += r->generateSQL(schemaName);
			}
		}
	}

	// Check foreign keys available in the database but not in the model
	// because we need to drop them
	// First, create a list of FKs at destination table in the model
	wxArrayString validFks;
	iteratorRelations->ResetIterator();
	while(iteratorRelations->HasNext())
	{
		ddRelationshipFigure *r = (ddRelationshipFigure *) iteratorRelations->Next();
		if(r->getEndFigure() == this)	// Add to list, FKs with this table as destination. source ---<| destination
		{
			validFks.Add(r->getConstraintName());
		}
	}
	delete iteratorRelations;

	wxArrayString fksToDelete = ddImportDBUtils::getFkAtDbNotInModel(connection, dbTable->OIDTable, schemaName, validFks , design);

	int max = fksToDelete.Count();
	for(i = 0; i < max; i++)
	{
		// Drop it
		out += wxT("\n");
		out += wxT("ALTER TABLE ");
		if(!schemaName.IsEmpty())
			out += wxT("\"") + schemaName + wxT("\".");
		out += wxT("\"") + this->getTableName() + wxT("\"") ;
		out += wxT(" DROP CONSTRAINT \"") + fksToDelete[i] + wxT("\";");
		out += wxT("\n");
	}

	if(dbTable)
		delete dbTable;
	return out;
}