Skip to main content
summaryrefslogtreecommitdiffstats
blob: 10e9df6dd26cd533ff4e768d69962db17eae5007 (plain) (blame)
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
/*******************************************************************************
 * Copyright (c) 2006, 2008 Oracle. All rights reserved.
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v1.0, which accompanies this distribution
 * and is available at http://www.eclipse.org/legal/epl-v10.html.
 * 
 * Contributors:
 *     Oracle - initial API and implementation
 ******************************************************************************/
package org.eclipse.jpt.db.internal;

import java.text.Collator;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import org.eclipse.jpt.db.Column;
import org.eclipse.jpt.db.ForeignKey;
import org.eclipse.jpt.utility.internal.CollectionTools;
import org.eclipse.jpt.utility.internal.StringTools;
import org.eclipse.jpt.utility.internal.iterators.ArrayIterator;
import org.eclipse.jpt.utility.internal.iterators.FilteringIterator;
import org.eclipse.jpt.utility.internal.iterators.TransformationIterator;

/**
 *  Wrap a DTP ForeignKey
 */
final class DTPForeignKeyWrapper
	extends DTPDatabaseObjectWrapper
	implements ForeignKey
{
	// the wrapped DTP foreign key
	private final org.eclipse.datatools.modelbase.sql.constraints.ForeignKey dtpForeignKey;

	// lazy-initialized
	private DTPTableWrapper referencedTable;

	// lazy-initialized
	private LocalColumnPair[] columnPairs;

	// lazy-initialized - but it can be 'null' so we use a flag
	private String defaultAttributeName;
	private boolean defaultAttributeNameCalculated = false;


	// ********** constructor **********

	DTPForeignKeyWrapper(DTPTableWrapper baseTable, org.eclipse.datatools.modelbase.sql.constraints.ForeignKey dtpForeignKey) {
		super(baseTable, dtpForeignKey);
		this.dtpForeignKey = dtpForeignKey;
	}


	// ********** DTPWrapper implementation **********

	@Override
	synchronized void catalogObjectChanged() {
		super.catalogObjectChanged();
		this.getConnectionProfile().foreignKeyChanged(this);
	}

	@Override
	public String toString() {
		return StringTools.buildToStringFor(this, this.getName() + ": " + Arrays.asList(this.getColumnPairs()));  //$NON-NLS-1$
	}


	// ********** ForeignKey implementation **********

	public String getName() {
		return this.dtpForeignKey.getName();
	}

	public DTPTableWrapper getBaseTable() {
		return (DTPTableWrapper) this.getParent();
	}

	public synchronized DTPTableWrapper getReferencedTable() {
		if (this.referencedTable == null) {
			this.referencedTable = this.getBaseTable().getTable(this.dtpForeignKey.getUniqueConstraint().getBaseTable());
		}
		return this.referencedTable;
	}

	public boolean referencesSingleColumnPrimaryKey() {
		if (this.columnPairsSize() != 1) {
			return false;
		}
		if (this.getReferencedTable().primaryKeyColumnsSize() != 1) {
			return false;
		}
		return this.getColumnPair().getReferencedColumn() == this.getReferencedTable().getPrimaryKeyColumn();
	}

	// ***** column pairs

	public Iterator<ColumnPair> columnPairs() {
		return new ArrayIterator<ColumnPair>(this.getColumnPairs());
	}

	public LocalColumnPair getColumnPair() {
		LocalColumnPair[] pairs = this.getColumnPairs();
		if (pairs.length != 1) {
			throw new IllegalStateException("multiple column pairs: " + pairs.length);  //$NON-NLS-1$
		}
		return pairs[0];
	}

	private Iterator<LocalColumnPair> localColumnPairs() {
		return new ArrayIterator<LocalColumnPair>(this.getColumnPairs());
	}

	private synchronized LocalColumnPair[] getColumnPairs() {
		if (this.columnPairs == null) {
			this.columnPairs = this.buildColumnPairs();
		}
		return this.columnPairs;
	}

	private LocalColumnPair[] buildColumnPairs() {
		List<org.eclipse.datatools.modelbase.sql.tables.Column> baseColumns = this.getDTPBaseColumns();
		int size = baseColumns.size();
		List<org.eclipse.datatools.modelbase.sql.tables.Column> refColumns = this.getDTPReferenceColumns();
		if (refColumns.size() != size) {
			throw new IllegalStateException(this.getBaseTable().getName() + '.' + this.getName() +
								" - mismatched sizes: " + size + " vs. " + refColumns.size());  //$NON-NLS-1$  //$NON-NLS-2$
		}
		LocalColumnPair[] result = new LocalColumnPair[baseColumns.size()];
		for (int i = baseColumns.size(); i-- > 0; ) {
			result[i] = new LocalColumnPair(
								this.getBaseTable().getColumn(baseColumns.get(i)),
								this.getBaseTable().getColumn(refColumns.get(i))
						);
		}
		return result;
	}

	// minimize scope of suppressed warnings
	@SuppressWarnings("unchecked")
	private List<org.eclipse.datatools.modelbase.sql.tables.Column> getDTPBaseColumns() {
		return this.dtpForeignKey.getMembers();
	}

	// minimize scope of suppressed warnings
	@SuppressWarnings("unchecked")
	private List<org.eclipse.datatools.modelbase.sql.tables.Column> getDTPReferenceColumns() {
		return this.dtpForeignKey.getUniqueConstraint().getMembers();
	}

	public int columnPairsSize() {
		return this.getColumnPairs().length;
	}

	public Iterator<Column> baseColumns() {
		return new TransformationIterator<LocalColumnPair, Column>(this.localColumnPairs()) {
			@Override
			protected Column transform(LocalColumnPair pair) {
				return pair.getBaseColumn();
			}
		};
	}

	boolean baseColumnsContains(Column column) {
		return CollectionTools.contains(this.baseColumns(), column);
	}

	public Iterator<Column> nonPrimaryKeyBaseColumns() {
		return new FilteringIterator<Column, Column>(this.baseColumns()) {
			@Override
			protected boolean accept(Column column) {
				return ! column.isPartOfPrimaryKey();
			}
		};
	}

	public Iterator<Column> referencedColumns() {
		return new TransformationIterator<LocalColumnPair, Column>(this.localColumnPairs()) {
			@Override
			protected Column transform(LocalColumnPair columnPair) {
				return columnPair.getReferencedColumn();
			}
		};
	}

	// ***** attribute name

	public String getAttributeName() {
		String defaultName = this.getDefaultAttributeName();
		return (defaultName != null) ? defaultName : this.getNonDefaultAttributeName();
	}

	public synchronized String getDefaultAttributeName() {
		if ( ! this.defaultAttributeNameCalculated) {
			this.defaultAttributeNameCalculated = true;
			this.defaultAttributeName = this.buildDefaultAttributeName();
		}
		return this.defaultAttributeName;
	}

	private String buildDefaultAttributeName() {
		if ( ! this.referencesSingleColumnPrimaryKey()) {
			return null;
		}
		LocalColumnPair columnPair = this.getColumnPair();
		String baseColName = columnPair.getBaseColumn().getName();
		String refColName = columnPair.getReferencedColumn().getName();
		if (baseColName.length() <= (refColName.length() + 1)) {
			return null;
		}
		if ( ! baseColName.endsWith(refColName)) {
			return null;
		}
		int _index = baseColName.length() - refColName.length() - 1;
		if (baseColName.charAt(_index) != '_') {
			return null;
		}
		return baseColName.substring(0, _index);
	}

	/**
	 * If this is a simple (single-column) foreign key, use the name of the
	 * single base column to build a name. If this is a compound foreign key,
	 * return the name of the referenced table.
	 */
	// TODO if there is only one FK to a given table, use the table's name instead of the column's name?
	private String getNonDefaultAttributeName() {
		return (this.columnPairsSize() == 1) ?
						this.getNonDefaultAttributeNameFromBaseColumn()
					:
						this.getReferencedTable().getName();
	}

	/**
	 * The underscore check is helpful when the referenced column is NOT the
	 * primary key of the referenced table (i.e. it has only a UNIQUE constraint).
	 *     ForeignKey(EMP.CUBICLE_ID => CUBICLE.ID) => "CUBICLE"
	 *     ForeignKey(EMP.CUBICLEID => CUBICLE.ID) => "CUBICLE"
	 *     ForeignKey(EMP.CUBICLE_PK => CUBICLE.ID) => "CUBICLE_PK"
	 */
	private String getNonDefaultAttributeNameFromBaseColumn() {
		LocalColumnPair columnPair = this.getColumnPair();
		String baseColName = columnPair.getBaseColumn().getName();
		String refColName = columnPair.getReferencedColumn().getName();
		int len = baseColName.length();
		int refLen = refColName.length();
		if ((len > refLen) && baseColName.endsWith(refColName)) {
			len = len - refLen;
			if ((len > 1) && baseColName.charAt(len - 1) == '_') {
				len = len - 1;
			}
		}
		return baseColName.substring(0, len);
	}

	/**
	 * Examples:
	 * Oracle etc.
	 *     ForeignKey(FOO_ID => ID) vs. "foo" => null
	 *     ForeignKey(FOO_ID => FOO_ID) vs. "foo" => "FOO_ID"
	 *     ForeignKey(FOO => ID) vs. "foo" => "FOO"
	 *     ForeignKey(Foo_ID => ID) vs. "foo" => "\"Foo_ID\""
	 *     
	 * PostgreSQL etc.
	 *     ForeignKey(foo_id => id) vs. "foo" => null
	 *     ForeignKey(foo_id => foo_id) vs. "foo" => "foo_id"
	 *     ForeignKey(foo => id) vs. "foo" => "foo"
	 *     ForeignKey(Foo_ID => ID) vs. "foo" => "\"Foo_ID\""
	 *     
	 * SQL Server etc.
	 *     ForeignKey(foo_ID => ID) vs. "foo" => null
	 *     ForeignKey(FOO_ID => FOO_ID) vs. "foo" => "FOO_ID"
	 *     ForeignKey(FOO => ID) vs. "foo" => "FOO"
	 *     ForeignKey(Foo_ID => ID) vs. "foo" => "Foo_ID"
	 */
	public String getJoinColumnAnnotationIdentifier(String attributeName) {
		String baseColumnName = this.getColumnPair().getBaseColumn().getName();
		String defaultBaseColumnName = attributeName + '_' + this.getReferencedTable().getPrimaryKeyColumn().getName();
		return this.getDatabase().convertNameToIdentifier(baseColumnName, defaultBaseColumnName);
	}


	// ********** Comparable implementation **********

	public int compareTo(ForeignKey foreignKey) {
		return Collator.getInstance().compare(this.getName(), foreignKey.getName());
	}


	// ********** internal methods **********

	boolean wraps(org.eclipse.datatools.modelbase.sql.constraints.ForeignKey foreignKey) {
		return this.dtpForeignKey == foreignKey;
	}

	@Override
	void clear() {
		// the foreign key does not "contain" any other objects,
		// so we don't need to forward the #clear()
		this.defaultAttributeNameCalculated = false;
		this.defaultAttributeName = null;
		this.columnPairs =  null;
		this.referencedTable = null;
	}


	// ********** column pair implementation **********

	private static class LocalColumnPair implements ColumnPair {
		private final DTPColumnWrapper baseColumn;
		private final DTPColumnWrapper referencedColumn;

		LocalColumnPair(DTPColumnWrapper baseColumn, DTPColumnWrapper referencedColumn) {
			super();
			if ((baseColumn == null) || (referencedColumn == null)) {
				throw new NullPointerException();
			}
			this.baseColumn = baseColumn;
			this.referencedColumn = referencedColumn;
		}

		public DTPColumnWrapper getBaseColumn() {
			return this.baseColumn;
		}

		public DTPColumnWrapper getReferencedColumn() {
			return this.referencedColumn;
		}

		public int compareTo(ColumnPair columnPair) {
			return Collator.getInstance().compare(this.getBaseColumn().getName(), columnPair.getBaseColumn().getName());
		}

		@Override
		public String toString() {
			return StringTools.buildToStringFor(this, this.baseColumn.getName() + "=>" + this.referencedColumn.getName());  //$NON-NLS-1$
		}

	}

}

Back to the top