-
Notifications
You must be signed in to change notification settings - Fork 221
/
OracleDdlReader.java
528 lines (468 loc) · 21.9 KB
/
OracleDdlReader.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
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
package org.jumpmind.db.platform.oracle;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import static org.apache.commons.lang.StringUtils.isNotBlank;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Time;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang.StringUtils;
import org.jumpmind.db.model.Column;
import org.jumpmind.db.model.ColumnTypes;
import org.jumpmind.db.model.ForeignKey;
import org.jumpmind.db.model.ForeignKey.ForeignKeyAction;
import org.jumpmind.db.model.IIndex;
import org.jumpmind.db.model.Table;
import org.jumpmind.db.model.Trigger;
import org.jumpmind.db.model.Trigger.TriggerType;
import org.jumpmind.db.model.TypeMap;
import org.jumpmind.db.platform.AbstractJdbcDdlReader;
import org.jumpmind.db.platform.DatabaseMetaDataWrapper;
import org.jumpmind.db.platform.IDatabasePlatform;
import org.jumpmind.db.platform.IDdlBuilder;
import org.jumpmind.db.sql.ISqlRowMapper;
import org.jumpmind.db.sql.JdbcSqlTemplate;
import org.jumpmind.db.sql.Row;
import org.jumpmind.db.sql.SqlException;
/*
* Reads a database model from an Oracle 8 database.
*/
public class OracleDdlReader extends AbstractJdbcDdlReader {
/* The regular expression pattern for the Oracle conversion of ISO dates. */
private Pattern oracleIsoDatePattern;
/* The regular expression pattern for the Oracle conversion of ISO times. */
private Pattern oracleIsoTimePattern;
/*
* The regular expression pattern for the Oracle conversion of ISO
* timestamps.
*/
private Pattern oracleIsoTimestampPattern;
public OracleDdlReader(IDatabasePlatform platform) {
super(platform);
setDefaultCatalogPattern(null);
setDefaultSchemaPattern(null);
setDefaultTablePattern("%");
oracleIsoDatePattern = Pattern.compile("TO_DATE\\('([^']*)'\\, 'YYYY\\-MM\\-DD'\\)");
oracleIsoTimePattern = Pattern.compile("TO_DATE\\('([^']*)'\\, 'HH24:MI:SS'\\)");
oracleIsoTimestampPattern = Pattern
.compile("TO_DATE\\('([^']*)'\\, 'YYYY\\-MM\\-DD HH24:MI:SS'\\)");
}
@Override
protected Table readTable(Connection connection, DatabaseMetaDataWrapper metaData,
Map<String, Object> values) throws SQLException {
/*
* Oracle 10 added the recycle bin which contains dropped database
* objects not yet purged Since we don't want entries from the recycle
* bin, we filter them out
*/
boolean tableHasBeenDeleted = isTableInRecycleBin(connection, values);
/*
* System tables are in the system schema
*/
String schema = (String) values.get(getResultSetSchemaName());
if (!tableHasBeenDeleted && !"SYSTEM".equals(schema)) {
Table table = super.readTable(connection, metaData, values);
if (table != null) {
determineAutoIncrementColumns(connection, table);
}
return table;
} else {
return null;
}
}
protected boolean isTableInRecycleBin(Connection connection, Map<String, Object> values)
throws SQLException {
String tablename = (String)values.get("TABLE_NAME");
return StringUtils.isNotBlank(tablename) && tablename.toLowerCase().startsWith("bin$");
}
@Override
protected Integer mapUnknownJdbcTypeForColumn(Map<String, Object> values) {
String typeName = (String) values.get("TYPE_NAME");
if (typeName != null && typeName.startsWith("DATE")) {
return Types.DATE;
} else if (typeName != null && typeName.startsWith("TIMESTAMP")
&& !typeName.endsWith("TIME ZONE")) {
// This is for Oracle's TIMESTAMP(9)
return Types.TIMESTAMP;
} else if (typeName != null && typeName.startsWith("TIMESTAMP")
&& typeName.endsWith("WITH TIME ZONE")) {
return ColumnTypes.ORACLE_TIMESTAMPTZ;
} else if (typeName != null && typeName.startsWith("TIMESTAMP")
&& typeName.endsWith("WITH LOCAL TIME ZONE")) {
return ColumnTypes.ORACLE_TIMESTAMPLTZ;
} else if (typeName != null && typeName.startsWith("NVARCHAR")) {
// This is for Oracle's NVARCHAR type
return Types.VARCHAR;
} else if (typeName != null && typeName.startsWith("LONGNVARCHAR")) {
return Types.LONGVARCHAR;
} else if (typeName != null && typeName.startsWith("NCHAR")) {
return Types.CHAR;
} else if (typeName != null && typeName.startsWith("XML")) {
return Types.SQLXML;
} else if (typeName != null && typeName.endsWith("CLOB")) {
return Types.LONGVARCHAR;
} else if (typeName != null && typeName.startsWith("BINARY_FLOAT")) {
return Types.FLOAT;
} else if (typeName != null && typeName.startsWith("BINARY_DOUBLE")) {
return Types.DOUBLE;
} else if (typeName != null && typeName.startsWith("BFILE")) {
return Types.VARCHAR;
} else if (typeName != null && typeName.startsWith("INTERVAL")) {
return Types.VARCHAR;
} else if (typeName != null && typeName.startsWith("ROWID")) {
return Types.VARCHAR;
} else {
return super.mapUnknownJdbcTypeForColumn(values);
}
}
@Override
protected Column readColumn(DatabaseMetaDataWrapper metaData, Map<String, Object> values)
throws SQLException {
Column column = super.readColumn(metaData, values);
if (column.getMappedTypeCode() == Types.DECIMAL) {
// We're back-mapping the NUMBER columns returned by Oracle
// Note that the JDBC driver returns DECIMAL for these NUMBER
// columns
if (column.getScale() <= -127 || column.getScale() >= 127) {
if (column.getSizeAsInt() == 0) {
/*
* Latest oracle jdbc drivers for 11g return (0,-127) for
* types defined as integer resulting in bad mappings.
* NUMBER without scale or precision looks the same as
* INTEGER in the jdbc driver. We must check the Oracle
* meta data to see if type is an INTEGER.
*/
if (isColumnInteger((String)values.get("TABLE_NAME"),
(String)values.get("COLUMN_NAME"))) {
column.setMappedTypeCode(Types.BIGINT);
}
} else if (column.getSizeAsInt() <= 63) {
column.setMappedTypeCode(Types.REAL);
} else {
column.setMappedTypeCode(Types.DOUBLE);
}
}
} else if (column.getMappedTypeCode() == Types.FLOAT) {
// Same for REAL, FLOAT, DOUBLE PRECISION, which all back-map to
// FLOAT but with
// different sizes (63 for REAL, 126 for FLOAT/DOUBLE PRECISION)
switch (column.getSizeAsInt()) {
case 63:
column.setMappedTypeCode(Types.REAL);
break;
case 126:
column.setMappedTypeCode(Types.DOUBLE);
break;
}
} else if ((column.getMappedTypeCode() == Types.DATE)
|| (column.getMappedTypeCode() == Types.TIMESTAMP)) {
// we also reverse the ISO-format adaptation, and adjust the default
// value to timestamp
if (column.getDefaultValue() != null) {
Timestamp timestamp = null;
Matcher matcher = oracleIsoTimestampPattern.matcher(column.getDefaultValue());
if (matcher.matches()) {
String timestampVal = matcher.group(1);
timestamp = Timestamp.valueOf(timestampVal);
} else {
matcher = oracleIsoDatePattern.matcher(column.getDefaultValue());
if (matcher.matches()) {
String dateVal = matcher.group(1);
timestamp = new Timestamp(Date.valueOf(dateVal).getTime());
} else {
matcher = oracleIsoTimePattern.matcher(column.getDefaultValue());
if (matcher.matches()) {
String timeVal = matcher.group(1);
timestamp = new Timestamp(Time.valueOf(timeVal).getTime());
}
}
}
if (timestamp != null) {
column.setDefaultValue(timestamp.toString());
}
}
} else if (TypeMap.isTextType(column.getMappedTypeCode())) {
String defaultValue = column.getDefaultValue();
if (isNotBlank(defaultValue) && defaultValue.startsWith("('") && defaultValue.endsWith("')")) {
defaultValue = defaultValue.substring(2, defaultValue.length()-2);
}
column.setDefaultValue(unescape(defaultValue, "'", "''"));
}
return column;
}
private boolean isColumnInteger(String tableName, String columnName) {
return (platform.getSqlTemplate().queryForInt(
"select case when data_precision is null and data_scale=0 then 1 else 0 end " +
"from all_tab_columns where table_name=? and column_name=?", tableName, columnName) == 1);
}
/*
* Helper method that determines the auto increment status using Firebird's
* system tables.
*
* @param table The table
*/
protected void determineAutoIncrementColumns(Connection connection, Table table)
throws SQLException {
Column[] columns = table.getColumns();
for (int idx = 0; idx < columns.length; idx++) {
columns[idx].setAutoIncrement(isAutoIncrement(connection, table, columns[idx]));
}
}
/*
* Tries to determine whether the given column is an identity column.
*
* @param table The table
*
* @param column The column
*
* @return <code>true</code> if the column is an identity column
*/
protected boolean isAutoIncrement(Connection connection, Table table, Column column)
throws SQLException {
// TODO: For now, we only check whether there is a sequence & trigger as
// generated by DdlUtils
// But once sequence/trigger support is in place, it might be possible
// to 'parse' the
// trigger body (via SELECT trigger_name, trigger_body FROM
// user_triggers) in order to
// determine whether it fits our auto-increment definition
PreparedStatement prepStmt = null;
IDdlBuilder builder = getPlatform().getDdlBuilder();
String triggerName = builder.getConstraintName(OracleDdlBuilder.PREFIX_TRIGGER, table,
column.getName(), null);
String seqName = builder.getConstraintName(OracleDdlBuilder.PREFIX_SEQUENCE, table,
column.getName(), null);
if (!getPlatform().getDdlBuilder().isDelimitedIdentifierModeOn()) {
triggerName = triggerName.toUpperCase();
seqName = seqName.toUpperCase();
}
try {
prepStmt = connection
.prepareStatement("SELECT * FROM user_triggers WHERE trigger_name = ?");
prepStmt.setString(1, triggerName);
ResultSet resultSet = prepStmt.executeQuery();
if (!resultSet.next()) {
resultSet.close();
return false;
}
// we have a trigger, so lets check the sequence
prepStmt.close();
prepStmt = connection
.prepareStatement("SELECT * FROM user_sequences WHERE sequence_name = ?");
prepStmt.setString(1, seqName);
resultSet = prepStmt.executeQuery();
boolean resultFound = resultSet.next();
resultSet.close();
return resultFound;
} finally {
if (prepStmt != null) {
prepStmt.close();
}
}
}
@Override
protected Collection<IIndex> readIndices(Connection connection,
DatabaseMetaDataWrapper metaData, String tableName) throws SQLException {
// Oracle bug 4999817 causes a table analyze to execute in response to a
// call to
// DatabaseMetaData#getIndexInfo.
// The bug is fixed in driver version 10.2.0.4. The bug is present in at
// least
// driver versions 10.2.0.1.0, 10.1.0.2.0, and 9.2.0.5.
// To avoid this bug, we will access user_indexes view.
// This also allows us to filter system-generated indices which are
// identified by either
// having GENERATED='Y' in the query result, or by their index names
// being equal to the
// name of the primary key of the table
StringBuilder query = new StringBuilder();
query.append("SELECT a.INDEX_NAME, a.INDEX_TYPE, a.UNIQUENESS, b.COLUMN_NAME, b.COLUMN_POSITION FROM ALL_INDEXES a ");
query.append("JOIN ALL_IND_COLUMNS b ON a.table_name = b.table_name AND a.INDEX_NAME=b.INDEX_NAME AND a.TABLE_OWNER = b.TABLE_OWNER ");
query.append("WHERE ");
query.append("a.TABLE_NAME = ? ");
query.append("AND a.GENERATED='N' ");
query.append("AND a.TABLE_TYPE='TABLE' ");
if (metaData.getSchemaPattern() != null) {
query.append("AND a.TABLE_OWNER = ?");
}
Map<String, IIndex> indices = new LinkedHashMap<String, IIndex>();
PreparedStatement stmt = null;
try {
Set<String> pkIndecies = readPkIndecies(connection, metaData.getSchemaPattern(), tableName);
stmt = connection.prepareStatement(query.toString());
stmt.setString(
1,
getPlatform().getDdlBuilder().isDelimitedIdentifierModeOn() ? tableName : tableName
.toUpperCase());
if (metaData.getSchemaPattern() != null) {
stmt.setString(2, metaData.getSchemaPattern().toUpperCase());
}
ResultSet rs = stmt.executeQuery();
Map<String, Object> values = new HashMap<String, Object>();
while (rs.next()) {
String name = rs.getString(1);
if (pkIndecies.contains(name)) { // Filter PK indexes from these results.
continue;
}
String type = rs.getString(2);
// Only read in normal oracle indexes
if (type.startsWith("NORMAL")) {
values.put("INDEX_TYPE", new Short(DatabaseMetaData.tableIndexOther));
values.put("INDEX_NAME", name);
values.put("NON_UNIQUE",
"UNIQUE".equalsIgnoreCase(rs.getString(3)) ? Boolean.FALSE
: Boolean.TRUE);
values.put("COLUMN_NAME", rs.getString(4));
values.put("ORDINAL_POSITION", new Short(rs.getShort(5)));
readIndex(metaData, values, indices);
} else if (log.isDebugEnabled()) {
log.debug("Skipping index " + name + " of type " + type);
}
}
rs.close();
} finally {
if (stmt != null) {
stmt.close();
}
}
return indices.values();
}
@Override
protected String getTableNamePattern(String tableName) {
/*
* When looking up a table definition, Oracle treats underscore (_) in
* the table name as a wildcard, so it needs to be escaped, or you'll
* get back column names for more than one table. Example:
* DatabaseMetaData.metaData.getColumns(null, null, "SYM\\_NODE", null)
*/
return String.format("%s", tableName).replaceAll("\\_", "/_");
}
public List<String> getTableNames(final String catalog, final String schema,
final String[] tableTypes) {
List<String> tableNames = new ArrayList<String>();
JdbcSqlTemplate sqlTemplate = (JdbcSqlTemplate) platform.getSqlTemplate();
StringBuilder sql = new StringBuilder("select TABLE_NAME from ALL_TABLES");
Object[] params = null;
if (isNotBlank(schema)) {
sql.append(" where OWNER=?");
params = new Object[] { schema };
}
tableNames = sqlTemplate.query(sql.toString(), new ISqlRowMapper<String>() {
public String mapRow(Row row) {
return row.getString("TABLE_NAME");
}
}, params);
return tableNames;
}
public List<Trigger> getTriggers(final String catalog, final String schema,
final String tableName) throws SqlException {
List<Trigger> triggers = new ArrayList<Trigger>();
log.debug("Reading triggers for: {}", tableName);
JdbcSqlTemplate sqlTemplate = (JdbcSqlTemplate) platform.getSqlTemplate();
String sql = "SELECT TRIGGER_NAME, OWNER, TABLE_NAME, STATUS, TRIGGERING_EVENT FROM ALL_TRIGGERS WHERE TABLE_NAME=? and OWNER=?";
triggers = sqlTemplate.query(sql, new ISqlRowMapper<Trigger>() {
public Trigger mapRow(Row row) {
Trigger trigger = new Trigger();
trigger.setName(row.getString("TRIGGER_NAME"));
trigger.setSchemaName(row.getString("OWNER"));
trigger.setTableName(row.getString("TABLE_NAME"));
trigger.setEnabled(Boolean.valueOf(row.getString("STATUS")));
trigger.setSource("create ");
String triggerType = row.getString("TRIGGERING_EVENT");
if (triggerType.equals("DELETE")
|| triggerType.equals("INSERT")
|| triggerType.equals("UPDATE")) {
trigger.setTriggerType(TriggerType.valueOf(triggerType));
}
trigger.setMetaData(row);
return trigger;
}
}, tableName, schema);
for (final Trigger trigger : triggers) {
String name = trigger.getName();
String sourceSql = "select TEXT from all_source where OWNER=? AND NAME=? order by LINE";
final StringBuilder buff = new StringBuilder();
buff.append(trigger.getSource());
sqlTemplate.query(sourceSql, new ISqlRowMapper<Trigger>() {
public Trigger mapRow(Row row) {
String line = row.getString("TEXT");
if (!line.endsWith("\n")) {
buff.append("\n");
}
buff.append(line);
return trigger;
}
}, schema, name);
trigger.setSource(buff.toString());
}
return triggers;
}
protected Set<String> readPkIndecies(Connection connection, String schema, String tableName) throws SQLException {
String QUERY = "SELECT CONSTRAINT_NAME FROM ALL_CONSTRAINTS c WHERE c.TABLE_NAME = ? AND CONSTRAINT_TYPE = 'P'";
if (schema != null) {
QUERY += " AND c.OWNER = ?";
}
ResultSet rs = null;
PreparedStatement stmt = null;
Set<String> values = new LinkedHashSet<String>();
try {
stmt = connection.prepareStatement(QUERY);
stmt.setString(
1,
getPlatform().getDdlBuilder().isDelimitedIdentifierModeOn() ? tableName : tableName
.toUpperCase());
if (schema != null) {
stmt.setString(2, schema.toUpperCase());
}
rs = stmt.executeQuery();
while (rs.next()) {
String pkIndexName = rs.getString(1);
values.add(pkIndexName);
}
} finally {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
}
return values;
}
// Oracle does not support on update actions
@Override
protected void readForeignKeyUpdateRule(Map<String, Object> values, ForeignKey fk) {
fk.setOnUpdateAction(ForeignKeyAction.NOACTION);
}
}