This repository has been archived by the owner on Oct 28, 2022. It is now read-only.
/
DatabaseIntrospector.java
338 lines (298 loc) · 11.7 KB
/
DatabaseIntrospector.java
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
package org.springframework.roo.addon.dbre.addon.model;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
/**
* Creates a {@link Database database} model from a live database using JDBC.
*
* @author Alan Stewart
* @since 1.1
*/
public class DatabaseIntrospector extends AbstractIntrospector {
private final Set<String> excludeTables;
private final Set<String> includeTables;
private final Set<Schema> schemas;
private final boolean view;
public DatabaseIntrospector(final Connection connection,
final Set<Schema> schemas, final boolean view,
final Set<String> includeTables, final Set<String> excludeTables)
throws SQLException {
super(connection);
this.schemas = schemas;
this.view = view;
this.includeTables = includeTables;
this.excludeTables = excludeTables;
}
public Database createDatabase() throws SQLException {
final Set<Table> tables = new LinkedHashSet<Table>();
for (final Schema schema : schemas) {
tables.addAll(getTables(schema));
}
return new Database(tables);
}
private Index findIndex(final String name, final Set<Index> indices) {
for (final Index index : indices) {
if (index.getName().equalsIgnoreCase(name)) {
return index;
}
}
return null;
}
private String getArtifact(final String artifactName) throws SQLException {
if (databaseMetaData.storesLowerCaseIdentifiers()) {
return StringUtils.lowerCase(artifactName);
}
else if (databaseMetaData.storesUpperCaseIdentifiers()) {
return StringUtils.upperCase(artifactName);
}
else {
return artifactName;
}
}
private CascadeAction getCascadeAction(final Short actionValue) {
CascadeAction cascadeAction;
switch (actionValue.intValue()) {
case DatabaseMetaData.importedKeyCascade:
cascadeAction = CascadeAction.CASCADE;
break;
case DatabaseMetaData.importedKeySetNull:
cascadeAction = CascadeAction.SET_NULL;
break;
case DatabaseMetaData.importedKeySetDefault:
cascadeAction = CascadeAction.SET_DEFAULT;
break;
case DatabaseMetaData.importedKeyRestrict:
cascadeAction = CascadeAction.RESTRICT;
break;
case DatabaseMetaData.importedKeyNoAction:
cascadeAction = CascadeAction.NONE;
break;
default:
cascadeAction = CascadeAction.NONE;
}
return cascadeAction;
}
private Set<Table> getTables(final Schema schema) throws SQLException {
final Set<Table> tables = new LinkedHashSet<Table>();
final String[] types = view ? new String[] { TableType.TABLE.name(),
TableType.VIEW.name() }
: new String[] { TableType.TABLE.name() };
final ResultSet rs = databaseMetaData.getTables(null,
getArtifact(schema.getName()), null, types);
try {
while (rs.next()) {
final String tableName = rs.getString("TABLE_NAME");
// Check for certain tables such as Oracle recycle bin tables,
// and ignore
if (ignoreTables(tableName)) {
continue;
}
if (hasIncludedTable(tableName) && !hasExcludedTable(tableName)) {
final Table table = new Table(tableName, new Schema(
rs.getString("TABLE_SCHEM")));
table.setCatalog(rs.getString("TABLE_CAT"));
table.setDescription(rs.getString("REMARKS"));
readColumns(table);
readForeignKeys(table, false);
readForeignKeys(table, true);
readIndices(table);
for (final String columnName : readPrimaryKeyNames(table)) {
final Column column = table.findColumn(columnName);
if (column != null) {
column.setPrimaryKey(true);
}
}
tables.add(table);
}
}
}
finally {
rs.close();
}
return tables;
}
private boolean hasExcludedTable(final String tableName) {
if (excludeTables == null || excludeTables.isEmpty()) {
return false;
}
return hasTable(excludeTables, tableName);
}
private boolean hasIncludedTable(final String tableName) {
if (includeTables == null || includeTables.isEmpty()) {
return true;
}
return hasTable(includeTables, tableName);
}
private boolean hasTable(final Set<String> tables, final String tableName) {
for (final String table : tables) {
final String regex = table.replaceAll("\\*", ".*").replaceAll(
"\\?", ".?");
final Pattern pattern = Pattern.compile(regex);
if (pattern.matcher(tableName).matches()) {
return true;
}
}
return false;
}
private boolean ignoreTables(final String tableName) {
boolean ignore = false;
try {
if ("Oracle".equalsIgnoreCase(databaseMetaData
.getDatabaseProductName()) && tableName.startsWith("BIN$")) {
ignore = true;
}
if ("MySQL".equalsIgnoreCase(databaseMetaData
.getDatabaseProductName()) && tableName.equals("SEQUENCE")) {
ignore = true;
}
}
catch (final SQLException ignored) {
}
return ignore;
}
private void readColumns(final Table table) throws SQLException {
final ResultSet rs = databaseMetaData.getColumns(table.getCatalog(),
table.getSchema().getName(), table.getName(), null);
try {
while (rs.next()) {
final Column column = new Column(rs.getString("COLUMN_NAME"),
rs.getInt("DATA_TYPE"), rs.getString("TYPE_NAME"),
rs.getInt("COLUMN_SIZE"), rs.getInt("DECIMAL_DIGITS"));
column.setDescription(rs.getString("REMARKS"));
column.setDefaultValue(rs.getString("COLUMN_DEF"));
column.setRequired("NO".equalsIgnoreCase(rs
.getString("IS_NULLABLE")));
table.addColumn(column);
}
}
finally {
rs.close();
}
}
private void readForeignKeys(final Table table, final boolean exported)
throws SQLException {
final Map<String, ForeignKey> foreignKeys = new LinkedHashMap<String, ForeignKey>();
ResultSet rs;
if (exported) {
rs = databaseMetaData.getExportedKeys(table.getCatalog(), table
.getSchema().getName(), table.getName());
}
else {
rs = databaseMetaData.getImportedKeys(table.getCatalog(), table
.getSchema().getName(), table.getName());
}
try {
while (rs.next()) {
final String name = rs.getString("FK_NAME");
final String foreignTableName = rs
.getString(exported ? "FKTABLE_NAME" : "PKTABLE_NAME");
final String key = name + "_" + foreignTableName;
if (!hasExcludedTable(foreignTableName)) {
final ForeignKey foreignKey = new ForeignKey(name,
foreignTableName);
foreignKey.setForeignSchemaName(StringUtils.defaultIfEmpty(
rs.getString(exported ? "FKTABLE_SCHEM"
: "PKTABLE_SCHEM"),
DbreModelService.NO_SCHEMA_REQUIRED));
foreignKey.setOnUpdate(getCascadeAction(rs
.getShort("UPDATE_RULE")));
foreignKey.setOnDelete(getCascadeAction(rs
.getShort("DELETE_RULE")));
foreignKey.setExported(exported);
final String localColumnName = rs
.getString(exported ? "PKCOLUMN_NAME"
: "FKCOLUMN_NAME");
final String foreignColumnName = rs
.getString(exported ? "FKCOLUMN_NAME"
: "PKCOLUMN_NAME");
final Reference reference = new Reference(localColumnName,
foreignColumnName);
if (foreignKeys.containsKey(key)) {
foreignKeys.get(key).addReference(reference);
}
else {
foreignKey.addReference(reference);
foreignKeys.put(key, foreignKey);
}
}
}
}
finally {
rs.close();
}
for (final ForeignKey foreignKey : foreignKeys.values()) {
if (exported) {
table.addExportedKey(foreignKey);
}
else {
table.addImportedKey(foreignKey);
}
}
}
private void readIndices(final Table table) throws SQLException {
final Set<Index> indices = new LinkedHashSet<Index>();
ResultSet rs;
try {
// Catching SQLException here due to Oracle throwing exception when
// attempting to retrieve indices for deleted tables that exist in
// Oracle's recycle bin
rs = databaseMetaData.getIndexInfo(table.getCatalog(), table
.getSchema().getName(), table.getName(), false, false);
}
catch (final SQLException e) {
return;
}
if (rs != null) {
try {
while (rs.next()) {
final Short type = rs.getShort("TYPE");
if (type == DatabaseMetaData.tableIndexStatistic) {
continue;
}
final String indexName = rs.getString("INDEX_NAME");
Index index = findIndex(indexName, indices);
if (index == null) {
index = new Index(indexName);
}
else {
indices.remove(index);
}
index.setUnique(!rs.getBoolean("NON_UNIQUE"));
final IndexColumn indexColumn = new IndexColumn(
rs.getString("COLUMN_NAME"));
index.addColumn(indexColumn);
indices.add(index);
}
}
finally {
rs.close();
}
}
for (final Index index : indices) {
table.addIndex(index);
}
}
private Set<String> readPrimaryKeyNames(final Table table)
throws SQLException {
final Set<String> columnNames = new LinkedHashSet<String>();
final ResultSet rs = databaseMetaData.getPrimaryKeys(
table.getCatalog(), table.getSchema().getName(),
table.getName());
try {
while (rs.next()) {
columnNames.add(rs.getString("COLUMN_NAME"));
}
}
finally {
rs.close();
}
return columnNames;
}
}