/
AbstractJdbcDdlReader.java
1881 lines (1683 loc) · 75.2 KB
/
AbstractJdbcDdlReader.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
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
package org.jumpmind.db.platform;
/*
* 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.lang3.StringUtils.isBlank;
import static org.apache.commons.lang3.StringUtils.isNotBlank;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import org.apache.commons.lang3.StringUtils;
import org.jumpmind.db.model.Column;
import org.jumpmind.db.model.Database;
import org.jumpmind.db.model.ForeignKey;
import org.jumpmind.db.model.ForeignKey.ForeignKeyAction;
import org.jumpmind.db.model.IIndex;
import org.jumpmind.db.model.IndexColumn;
import org.jumpmind.db.model.NonUniqueIndex;
import org.jumpmind.db.model.PlatformColumn;
import org.jumpmind.db.model.Reference;
import org.jumpmind.db.model.Table;
import org.jumpmind.db.model.Trigger;
import org.jumpmind.db.model.TypeMap;
import org.jumpmind.db.model.UniqueIndex;
import org.jumpmind.db.sql.DmlStatement;
import org.jumpmind.db.sql.DmlStatement.DmlType;
import org.jumpmind.db.sql.IConnectionCallback;
import org.jumpmind.db.sql.IConnectionHandler;
import org.jumpmind.db.sql.ISqlTransaction;
import org.jumpmind.db.sql.JdbcSqlTemplate;
import org.jumpmind.db.sql.Row;
import org.jumpmind.db.sql.SqlException;
import org.jumpmind.db.sql.mapper.RowMapper;
import org.jumpmind.db.util.BinaryEncoding;
import org.jumpmind.db.util.TableRow;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/*
* An utility class to create a Database model from a live database.
*/
public abstract class AbstractJdbcDdlReader implements IDdlReader {
/* The Log to which logging calls will be made. */
protected Logger log = LoggerFactory.getLogger(getClass());
/* The descriptors for the relevant columns in the table meta data. */
private final List<MetaDataColumnDescriptor> _columnsForTable;
/* The descriptors for the relevant columns in the table column meta data. */
private final List<MetaDataColumnDescriptor> _columnsForColumn;
/* The descriptors for the relevant columns in the primary key meta data. */
private final List<MetaDataColumnDescriptor> _columnsForPK;
/* The descriptors for the relevant columns in the foreign key meta data. */
private final List<MetaDataColumnDescriptor> _columnsForFK;
/* The descriptors for the relevant columns in the index meta data. */
private final List<MetaDataColumnDescriptor> _columnsForIndex;
/* The platform that this model reader belongs to. */
protected IDatabasePlatform platform;
/*
* Contains default column sizes (minimum sizes that a JDBC-compliant db
* must support).
*/
private HashMap<Integer, String> _defaultSizes = new HashMap<Integer, String>();
/* The default database catalog to read. */
private String _defaultCatalogPattern = "%";
/* The default database schema(s) to read. */
private String _defaultSchemaPattern = "%";
/* The default pattern for reading all tables. */
private String _defaultTablePattern = "%";
/* The default pattern for reading all columns. */
private String _defaultColumnPattern;
/* The table types to recognize per default. */
private String[] _defaultTableTypes = { "TABLE" };
public AbstractJdbcDdlReader(IDatabasePlatform platform) {
this.platform = platform;
_defaultSizes.put(Integer.valueOf(Types.CHAR), "254");
_defaultSizes.put(Integer.valueOf(Types.VARCHAR), "254");
_defaultSizes.put(Integer.valueOf(Types.LONGVARCHAR), "254");
_defaultSizes.put(Integer.valueOf(Types.BINARY), "254");
_defaultSizes.put(Integer.valueOf(Types.VARBINARY), "254");
_defaultSizes.put(Integer.valueOf(Types.LONGVARBINARY), "254");
_defaultSizes.put(Integer.valueOf(Types.INTEGER), "32");
_defaultSizes.put(Integer.valueOf(Types.BIGINT), "64");
_defaultSizes.put(Integer.valueOf(Types.REAL), "7,0");
_defaultSizes.put(Integer.valueOf(Types.FLOAT), "15,0");
_defaultSizes.put(Integer.valueOf(Types.DOUBLE), "15,0");
_defaultSizes.put(Integer.valueOf(Types.DECIMAL), "15,15");
_defaultSizes.put(Integer.valueOf(Types.NUMERIC), "15,15");
_columnsForTable = initColumnsForTable();
_columnsForColumn = initColumnsForColumn();
_columnsForPK = initColumnsForPK();
_columnsForFK = initColumnsForFK();
_columnsForIndex = initColumnsForIndex();
}
@Override
public List<Trigger> getTriggers(String catalog, String schema,
String tableName) {
return Collections.emptyList();
}
/*
* Returns the platform that this model reader belongs to.
*
* @return The platform
*/
public IDatabasePlatform getPlatform() {
return platform;
}
/*
* Returns the platform specific settings.
*
* @return The platform settings
*/
public DatabaseInfo getPlatformInfo() {
return platform.getDatabaseInfo();
}
/*
* Returns descriptors for the columns that shall be read from the result
* set when reading the meta data for a table. Note that the columns are
* read in the order defined by this list.<br/> Redefine this method if you
* want more columns or a different order.
*
* @return The descriptors for the result set columns
*/
protected List<MetaDataColumnDescriptor> initColumnsForTable() {
List<MetaDataColumnDescriptor> result = new ArrayList<MetaDataColumnDescriptor>();
result.add(new MetaDataColumnDescriptor(getName("TABLE_NAME"), Types.VARCHAR));
result.add(new MetaDataColumnDescriptor(getName("TABLE_TYPE"), Types.VARCHAR, "UNKNOWN"));
result.add(new MetaDataColumnDescriptor(getResultSetCatalogName(), Types.VARCHAR));
result.add(new MetaDataColumnDescriptor(getResultSetSchemaName(), Types.VARCHAR));
result.add(new MetaDataColumnDescriptor(getName("REMARKS"), Types.VARCHAR));
return result;
}
/*
* Returns descriptors for the columns that shall be read from the result
* set when reading the meta data for table columns. Note that the columns
* are read in the order defined by this list.<br/> Redefine this method if
* you want more columns or a different order.
*
* @return The map column name -> descriptor for the result set columns
*/
protected List<MetaDataColumnDescriptor> initColumnsForColumn() {
List<MetaDataColumnDescriptor> result = new ArrayList<MetaDataColumnDescriptor>();
// As suggested by Alexandre Borgoltz, we're reading the COLUMN_DEF
// first because Oracle
// has problems otherwise (it seemingly requires a LONG column to be the
// first to be read)
// See also DDLUTILS-29
result.add(new MetaDataColumnDescriptor(getName("COLUMN_DEF"), Types.VARCHAR));
result.add(new MetaDataColumnDescriptor(getName("COLUMN_DEFAULT"), Types.VARCHAR));
// we're also reading the table name so that a model reader impl can
// filter manually
result.add(new MetaDataColumnDescriptor(getName("TABLE_NAME"), Types.VARCHAR));
result.add(new MetaDataColumnDescriptor(getName("COLUMN_NAME"), Types.VARCHAR));
result.add(new MetaDataColumnDescriptor(getName("TYPE_NAME"), Types.VARCHAR));
result.add(new MetaDataColumnDescriptor(getName("DATA_TYPE"), Types.INTEGER, Integer.valueOf(
java.sql.Types.OTHER)));
result.add(new MetaDataColumnDescriptor(getName("NUM_PREC_RADIX"), Types.INTEGER, Integer.valueOf(10)));
result.add(new MetaDataColumnDescriptor(getName("DECIMAL_DIGITS"), Types.INTEGER, Integer.valueOf(0)));
result.add(new MetaDataColumnDescriptor(getName("COLUMN_SIZE"), Types.VARCHAR));
result.add(new MetaDataColumnDescriptor(getName("CHAR_OCTET_LENGTH"), Types.VARCHAR));
result.add(new MetaDataColumnDescriptor(getName("IS_NULLABLE"), Types.VARCHAR, "YES"));
result.add(new MetaDataColumnDescriptor(getName("IS_AUTOINCREMENT"), Types.VARCHAR, "YES"));
result.add(new MetaDataColumnDescriptor(getName("REMARKS"), Types.VARCHAR));
return result;
}
/*
* Returns descriptors for the columns that shall be read from the result
* set when reading the meta data for primary keys. Note that the columns
* are read in the order defined by this list.<br/> Redefine this method if
* you want more columns or a different order.
*
* @return The map column name -> descriptor for the result set columns
*/
protected List<MetaDataColumnDescriptor> initColumnsForPK() {
List<MetaDataColumnDescriptor> result = new ArrayList<MetaDataColumnDescriptor>();
result.add(new MetaDataColumnDescriptor(getName("COLUMN_NAME"), Types.VARCHAR));
// we're also reading the table name so that a model reader impl can
// filter manually
result.add(new MetaDataColumnDescriptor(getName("TABLE_NAME"), Types.VARCHAR));
// the name of the primary key is currently only interesting to the pk
// index name resolution
result.add(new MetaDataColumnDescriptor(getName("PK_NAME"), Types.VARCHAR));
return result;
}
/*
* Returns descriptors for the columns that shall be read from the result
* set when reading the meta data for foreign keys originating from a table.
* Note that the columns are read in the order defined by this list.<br/>
* Redefine this method if you want more columns or a different order.
*
* @return The map column name -> descriptor for the result set columns
*/
protected List<MetaDataColumnDescriptor> initColumnsForFK() {
List<MetaDataColumnDescriptor> result = new ArrayList<MetaDataColumnDescriptor>();
result.add(new MetaDataColumnDescriptor(getName("PKTABLE_NAME"), Types.VARCHAR));
// we're also reading the table name so that a model reader impl can
// filter manually
result.add(new MetaDataColumnDescriptor(getName("FKTABLE_NAME"), Types.VARCHAR));
result.add(new MetaDataColumnDescriptor(getName("KEY_SEQ"), Types.TINYINT, Short.valueOf((short) 0)));
result.add(new MetaDataColumnDescriptor(getName("FK_NAME"), Types.VARCHAR));
result.add(new MetaDataColumnDescriptor(getName("FKTABLE_NAME"), Types.VARCHAR));
result.add(new MetaDataColumnDescriptor(getName("PKCOLUMN_NAME"), Types.VARCHAR));
result.add(new MetaDataColumnDescriptor(getName("FKCOLUMN_NAME"), Types.VARCHAR));
result.add(new MetaDataColumnDescriptor(getName("UPDATE_RULE"), Types.TINYINT));
result.add(new MetaDataColumnDescriptor(getName("DELETE_RULE"), Types.TINYINT));
return result;
}
/*
* Returns descriptors for the columns that shall be read from the result
* set when reading the meta data for indices. Note that the columns are
* read in the order defined by this list.<br/> Redefine this method if you
* want more columns or a different order.
*
* @return The map column name -> descriptor for the result set columns
*/
protected List<MetaDataColumnDescriptor> initColumnsForIndex() {
List<MetaDataColumnDescriptor> result = new ArrayList<MetaDataColumnDescriptor>();
result.add(new MetaDataColumnDescriptor(getName("INDEX_NAME"), Types.VARCHAR));
// we're also reading the table name so that a model reader impl can
// filter manually
result.add(new MetaDataColumnDescriptor(getName("TABLE_NAME"), Types.VARCHAR));
result.add(new MetaDataColumnDescriptor(getName("NON_UNIQUE"), Types.BIT, Boolean.TRUE));
result.add(new MetaDataColumnDescriptor(getName("ORDINAL_POSITION"), Types.TINYINT, Short.valueOf(
(short) 0)));
result.add(new MetaDataColumnDescriptor(getName("COLUMN_NAME"), Types.VARCHAR));
result.add(new MetaDataColumnDescriptor(getName("TYPE"), Types.TINYINT));
return result;
}
protected String getName(String defaultName){
return defaultName;
}
/*
* Returns the catalog(s) in the database to read per default.
*
* @return The default catalog(s)
*/
public String getDefaultCatalogPattern() {
return _defaultCatalogPattern;
}
/*
* Sets the catalog(s) in the database to read per default.
*
* @param catalogPattern The catalog(s)
*/
public void setDefaultCatalogPattern(String catalogPattern) {
_defaultCatalogPattern = catalogPattern;
}
/*
* Returns the schema(s) in the database to read per default.
*
* @return The default schema(s)
*/
public String getDefaultSchemaPattern() {
return _defaultSchemaPattern;
}
/*
* Sets the schema(s) in the database to read per default.
*
* @param schemaPattern The schema(s)
*/
public void setDefaultSchemaPattern(String schemaPattern) {
_defaultSchemaPattern = schemaPattern;
}
/*
* Returns the default pattern to read the relevant tables from the
* database.
*
* @return The table pattern
*/
public String getDefaultTablePattern() {
return _defaultTablePattern;
}
/*
* Sets the default pattern to read the relevant tables from the database.
*
* @param tablePattern The table pattern
*/
public void setDefaultTablePattern(String tablePattern) {
_defaultTablePattern = tablePattern;
}
/*
* Returns the default pattern to read the relevant columns from the
* database.
*
* @return The column pattern
*/
public String getDefaultColumnPattern() {
return _defaultColumnPattern;
}
/*
* Sets the default pattern to read the relevant columns from the database.
*
* @param columnPattern The column pattern
*/
public void setDefaultColumnPattern(String columnPattern) {
_defaultColumnPattern = columnPattern;
}
/*
* Returns the table types to recognize per default.
*
* @return The default table types
*/
public String[] getDefaultTableTypes() {
return _defaultTableTypes;
}
/*
* Sets the table types to recognize per default. Typical types are "TABLE",
* "VIEW", "SYSTEM TABLE", "GLOBAL TEMPORARY", "LOCAL TEMPORARY", "ALIAS",
* "SYNONYM".
*
* @param types The table types
*/
public void setDefaultTableTypes(String[] types) {
_defaultTableTypes = types;
}
/*
* Returns the descriptors for the columns to be read from the table meta
* data result set.
*
* @return The column descriptors
*/
protected List<MetaDataColumnDescriptor> getColumnsForTable() {
return _columnsForTable;
}
/*
* Returns the descriptors for the columns to be read from the column meta
* data result set.
*
* @return The column descriptors
*/
protected List<MetaDataColumnDescriptor> getColumnsForColumn() {
return _columnsForColumn;
}
/*
* Returns the descriptors for the columns to be read from the primary key
* meta data result set.
*
* @return The column descriptors
*/
protected List<MetaDataColumnDescriptor> getColumnsForPK() {
return _columnsForPK;
}
/*
* Returns the descriptors for the columns to be read from the foreign key
* meta data result set.
*
* @return The column descriptors
*/
protected List<MetaDataColumnDescriptor> getColumnsForFK() {
return _columnsForFK;
}
/*
* Returns the descriptors for the columns to be read from the index meta
* data result set.
*
* @return The column descriptors
*/
protected List<MetaDataColumnDescriptor> getColumnsForIndex() {
return _columnsForIndex;
}
/*
* Reads the database model from the given connection.
*
* @param connection The connection
*
* @param name The name of the resulting database; <code>null</code> when
* the default name (the catalog) is desired which might be
* <code>null</code> itself though
*
* @return The database model
*/
public Database getDatabase(Connection connection) throws SQLException {
return readTables(null, null, null);
}
protected String getResultSetSchemaName() {
return "TABLE_SCHEM";
}
protected String getResultSetCatalogName() {
return "TABLE_CAT";
}
/*
* Reads the database model from the given connection.
*
* @param catalog The catalog to access in the database; use
* <code>null</code> for the default value
*
* @param schema The schema to access in the database; use <code>null</code>
* for the default value
*
* @param tableTypes The table types to process; use <code>null</code> or an
* empty list for the default ones
*
* @return The database model
*/
public Database readTables(final String catalog, final String schema, final String[] tableTypes) {
JdbcSqlTemplate sqlTemplate = (JdbcSqlTemplate) platform.getSqlTemplateDirty();
return postprocessModelFromDatabase(sqlTemplate
.execute(new IConnectionCallback<Database>() {
public Database execute(Connection connection) throws SQLException {
Database db = new Database();
db.setName(Table.getFullyQualifiedTablePrefix(catalog, schema));
db.setCatalog(catalog);
db.setSchema(schema);
db.addTables(readTables(connection, catalog, schema, tableTypes));
db.initialize();
return db;
}
}));
}
/*
* Allows the platform to postprocess the model just read from the database.
*
* @param model The model
*/
protected Database postprocessModelFromDatabase(Database model) {
// Default values for CHAR/VARCHAR/LONGVARCHAR columns have quotation
// marks around them which we'll remove now
for (int tableIdx = 0; tableIdx < model.getTableCount(); tableIdx++) {
postprocessTableFromDatabase(model.getTable(tableIdx));
}
return model;
}
/*
* Reads the tables from the database metadata.
*
* @param catalog The catalog to acess in the database; use
* <code>null</code> for the default value
*
* @param schemaPattern The schema(s) to acess in the database; use
* <code>null</code> for the default value
*
* @param tableTypes The table types to process; use <code>null</code> or an
* empty list for the default ones
*
* @return The tables
*/
protected Collection<Table> readTables(Connection connection, String catalog,
String schemaPattern, String[] tableTypes) throws SQLException {
ResultSet tableData = null;
try {
DatabaseMetaDataWrapper metaData = new DatabaseMetaDataWrapper();
metaData.setMetaData(connection.getMetaData());
metaData.setCatalog(catalog == null ? getDefaultCatalogPattern() : catalog);
metaData.setSchemaPattern(schemaPattern == null ? getDefaultSchemaPattern()
: schemaPattern);
metaData.setTableTypes((tableTypes == null) || (tableTypes.length == 0) ? getDefaultTableTypes()
: tableTypes);
tableData = metaData.getTables(getDefaultTablePattern());
List<Table> tables = new ArrayList<Table>();
while (tableData.next()) {
Map<String, Object> values = readMetaData(tableData, getColumnsForTable());
Table table = readTable(connection, metaData, values);
if (table != null) {
tables.add(table);
}
}
final Collator collator = Collator.getInstance();
Collections.sort(tables, new Comparator<Table>() {
public int compare(Table obj1, Table obj2) {
return collator.compare(obj1.getName().toUpperCase(), obj2.getName()
.toUpperCase());
}
});
return tables;
} finally {
if (tableData != null) {
tableData.close();
}
}
}
@Override
public Table readTable(final String catalog, final String schema, final String table) {
try {
log.debug("reading table: " + table);
JdbcSqlTemplate sqlTemplate = (JdbcSqlTemplate) platform.getSqlTemplateDirty();
return postprocessTableFromDatabase(sqlTemplate.execute(new IConnectionCallback<Table>() {
public Table execute(Connection connection) throws SQLException {
DatabaseMetaDataWrapper metaData = new DatabaseMetaDataWrapper();
metaData.setMetaData(connection.getMetaData());
if (isNotBlank(catalog)) {
metaData.setCatalog(catalog);
}
if (isNotBlank(schema)) {
metaData.setSchemaPattern(schema);
}
metaData.setTableTypes(null);
ResultSet tableData = null;
try {
log.debug("getting table metadata for {}", table);
tableData = metaData.getTables(getTableNamePattern(table));
log.debug("done getting table metadata for {}", table);
if (tableData != null && tableData.next()) {
Map<String, Object> values = readMetaData(tableData, initColumnsForTable());
return readTable(connection, metaData, values);
} else {
log.debug("table {} not found", table);
return null;
}
} finally {
close(tableData);
}
}
}));
} catch (SqlException e) {
if (e.getMessage()!=null && StringUtils.containsIgnoreCase(e.getMessage(), "does not exist")) {
return null;
} else {
log.error("Failed to get metadata for {} because: {} {}", Table.getFullyQualifiedTableName(catalog, schema, table), e.getClass().getName(), e.getMessage());
throw e;
}
}
}
protected Table postprocessTableFromDatabase(Table table) {
if (table != null) {
for (int columnIdx = 0; columnIdx < table.getColumnCount(); columnIdx++) {
Column column = table.getColumn(columnIdx);
if (TypeMap.isTextType(column.getMappedTypeCode())
|| TypeMap.isDateTimeType(column.getMappedTypeCode())) {
String defaultValue = column.getDefaultValue();
if ((defaultValue != null) && (defaultValue.length() >= 2)
&& defaultValue.startsWith("'") && defaultValue.endsWith("'")) {
defaultValue = defaultValue.substring(1, defaultValue.length() - 1);
column.setDefaultValue(defaultValue);
}
}
}
}
return table;
}
protected void close(ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException ex) {
}
}
}
protected void close(Statement stmt) {
if (stmt != null) {
try {
stmt.close();
} catch (SQLException ex) {
}
}
}
protected String getTableNamePattern(String tableName) {
return tableName;
}
protected String getTableNamePatternForConstraints(String tableName) {
return tableName;
}
/*
* Reads the next table from the meta data.
*
* @param metaData The database meta data
*
* @param values The table metadata values as defined by {@link
* #getColumnsForTable()}
*
* @return The table or <code>null</code> if the result set row did not
* contain a valid table
*/
protected Table readTable(Connection connection, DatabaseMetaDataWrapper metaData,
Map<String, Object> values) throws SQLException {
String tableName = (String) values.get(getName("TABLE_NAME"));
if (tableName == null) {
tableName = (String) values.get("NAME");
}
try {
Table table = null;
if ((tableName != null) && (tableName.length() > 0)) {
String type = (String) values.get(getName("TABLE_TYPE"));
String[] unsupportedTableTypes = getUnsupportedTableTypes();
for (String unsupportedTableType : unsupportedTableTypes) {
if (StringUtils.isNotBlank(type) && type.equals(unsupportedTableType)) {
return null;
}
}
table = new Table();
table.setName(tableName);
table.setType(type);
String catalog = (String) values.get(getName(getResultSetCatalogName()));
table.setCatalog(catalog);
String schema = (String) values.get(getName(getResultSetSchemaName()));
table.setSchema(schema);
table.setDescription((String) values.get(getName("REMARKS")));
table.addColumns(readColumns(metaData, tableName));
if (table.getColumnCount() > 0) {
table.addForeignKeys(readForeignKeys(connection, metaData, tableName));
table.addIndices(readIndices(connection, metaData, tableName));
Collection<String> primaryKeys = readPrimaryKeyNames(metaData, tableName);
int primaryKeySequence = 1;
for (Iterator<String> it = primaryKeys.iterator(); it.hasNext();) {
Column column = table.findColumn(it.next(), true);
if (column != null) {
column.setPrimaryKey(true);
column.setPrimaryKeySequence(primaryKeySequence);
primaryKeySequence++;
}
}
if (getPlatformInfo().isSystemIndicesReturned()) {
removeSystemIndices(connection, metaData, table);
}
removeGeneratedColumns(connection, metaData, table);
} else {
table = null;
}
}
return table;
} catch (RuntimeException ex) {
log.error(String.format("Failed to read table: %s. Error: %s", tableName, ex.getMessage()));
throw ex;
} catch (SQLException ex) {
log.error(String.format("Failed to read table: %s. Error: %s", tableName, ex.getMessage()));
throw ex;
}
}
protected String[] getUnsupportedTableTypes() {
return new String[0];
}
/*
* Removes system indices (generated by the database for primary and foreign
* keys) from the table.
*
* @param metaData The database meta data
*
* @param table The table
*/
protected void removeSystemIndices(Connection connection, DatabaseMetaDataWrapper metaData,
Table table) throws SQLException {
removeInternalPrimaryKeyIndex(connection, metaData, table);
for (int fkIdx = 0; fkIdx < table.getForeignKeyCount(); fkIdx++) {
removeInternalForeignKeyIndex(connection, metaData, table, table.getForeignKey(fkIdx));
}
}
/*
* Removes any system generated columns that would be used during comparison
*
* @param connection
* @param metaData
* @param table
* @throws SQLException
*/
protected void removeGeneratedColumns(Connection connection, DatabaseMetaDataWrapper metaData,
Table table) throws SQLException {
}
/*
* Tries to remove the internal index for the table's primary key.
*
* @param metaData The database meta data
*
* @param table The table
*/
protected void removeInternalPrimaryKeyIndex(Connection connection,
DatabaseMetaDataWrapper metaData, Table table) throws SQLException {
Column[] pks = table.getPrimaryKeyColumns();
List<String> columnNames = new ArrayList<String>();
for (int columnIdx = 0; columnIdx < pks.length; columnIdx++) {
columnNames.add(pks[columnIdx].getName());
}
for (int indexIdx = 0; indexIdx < table.getIndexCount();) {
IIndex index = table.getIndex(indexIdx);
if (index.isUnique() && matches(index, columnNames)
&& isInternalPrimaryKeyIndex(connection, metaData, table, index)) {
table.removeIndex(indexIdx);
} else {
indexIdx++;
}
}
}
/*
* Tries to remove the internal index for the given foreign key.
*
* @param metaData The database meta data
*
* @param table The table where the table is defined
*
* @param fk The foreign key
*/
protected void removeInternalForeignKeyIndex(Connection connection,
DatabaseMetaDataWrapper metaData, Table table, ForeignKey fk) throws SQLException {
List<String> columnNames = new ArrayList<String>();
for (int columnIdx = 0; columnIdx < fk.getReferenceCount(); columnIdx++) {
columnNames.add(fk.getReference(columnIdx).getLocalColumnName());
}
for (int indexIdx = 0; indexIdx < table.getIndexCount();) {
IIndex index = table.getIndex(indexIdx);
if (matches(index, columnNames) && isInternalForeignKeyIndex(connection, metaData, table, fk, index)) {
fk.setAutoIndexPresent(true);
table.removeIndex(indexIdx);
} else {
indexIdx++;
}
}
}
/*
* Checks whether the given index matches the column list.
*
* @param index The index
*
* @param columnsToSearchFor The names of the columns that the index should
* be for
*
* @return <code>true</code> if the index matches the columns
*/
protected boolean matches(IIndex index, List<String> columnsToSearchFor) {
for (String column : columnsToSearchFor) {
boolean found = false;
for (int i = 0; i < index.getColumnCount(); i++) {
if (column != null && column.equals(index.getColumn(i).getName())) {
found = true;
}
}
if (!found) {
return false;
}
}
return true;
}
/*
* Tries to determine whether the index is the internal database-generated
* index for the given table's primary key. Note that only unique indices
* with the correct columns are fed to this method. Redefine this method for
* specific platforms if there are better ways to determine internal
* indices.
*
* @param metaData The database meta data
*
* @param table The table owning the index
*
* @param index The index to check
*
* @return <code>true</code> if the index seems to be an internal primary
* key one
*/
protected boolean isInternalPrimaryKeyIndex(Connection connection,
DatabaseMetaDataWrapper metaData, Table table, IIndex index) throws SQLException {
return false;
}
/*
* Tries to determine whether the index is the internal database-generated
* index for the given foreign key. Note that only non-unique indices with
* the correct columns are fed to this method. Redefine this method for
* specific platforms if there are better ways to determine internal
* indices.
*
* @param metaData The database meta data
*
* @param table The table owning the index and foreign key
*
* @param fk The foreign key
*
* @param index The index to check
*
* @return <code>true</code> if the index seems to be an internal primary
* key one
*/
protected boolean isInternalForeignKeyIndex(Connection connection,
DatabaseMetaDataWrapper metaData, Table table, ForeignKey fk, IIndex index)
throws SQLException {
return false;
}
/*
* Reads the column definitions for the indicated table.
*
* @param metaData The database meta data
*
* @param tableName The name of the table
*
* @return The columns
*/
protected Collection<Column> readColumns(DatabaseMetaDataWrapper metaData, String tableName)
throws SQLException {
ResultSet columnData = null;
try {
Set<String> columnNames = new HashSet<String>();
columnData = metaData.getColumns(getTableNamePattern(tableName),
getDefaultColumnPattern());
List<Column> columns = new ArrayList<Column>();
while (columnData.next()) {
Map<String, Object> values = readMetaData(columnData, getColumnsForColumn());
Column column = readColumn(metaData, values);
if (!columnNames.contains(column.getName())) {
columnNames.add(column.getName());
columns.add(column);
}
genericizeDefaultValuesAndUpdatePlatformColumn(column);
}
return columns;
} finally {
close(columnData);
}
}
protected void genericizeDefaultValuesAndUpdatePlatformColumn(Column column) {
PlatformColumn platformColumn = column.findPlatformColumn(platform.getName());
platformColumn.setDefaultValue(column.getDefaultValue());
/*
* Translate from platform specific functions to ansi sql functions
*/
if ("getdate()".equalsIgnoreCase(column.getDefaultValue())) {
column.setDefaultValue("CURRENT_TIMESTAMP");
}
}
protected Integer mapUnknownJdbcTypeForColumn(Map<String, Object> values) {
return null;
}
/*
* Extracts a column definition from the result set.
*
* @param metaData The database meta data
*
* @param values The column meta data values as defined by {@link
* #getColumnsForColumn()}
*
* @return The column
*/
protected Column readColumn(DatabaseMetaDataWrapper metaData, Map<String, Object> values)
throws SQLException {
Column column = new Column();
PlatformColumn platformColumn = new PlatformColumn();
platformColumn.setName(platform.getName());
column.setName((String) values.get(getName("COLUMN_NAME")));
String defaultValue = (String) values.get(getName("COLUMN_DEF"));
if (defaultValue == null) {
defaultValue = (String) values.get(getName("COLUMN_DEFAULT"));
}
if (defaultValue != null) {
defaultValue = defaultValue.trim();
column.setDefaultValue(defaultValue);
}
String typeName = (String) values.get(getName("TYPE_NAME"));
column.setJdbcTypeName(typeName);
Integer mappedType = mapUnknownJdbcTypeForColumn(values);
if (mappedType != null) {
column.setMappedTypeCode(mappedType);
} else {
column.setMappedTypeCode((Integer) values.get(getName("DATA_TYPE")));
}
column.setJdbcTypeCode((Integer) values.get(getName("DATA_TYPE")));
column.setPrecisionRadix(((Integer) values.get(getName("NUM_PREC_RADIX"))).intValue());
String columnSize = (String) values.get(getName("COLUMN_SIZE"));
int decimalDigits = ((Integer) values.get(getName("DECIMAL_DIGITS"))).intValue();
try {
platformColumn.setType(typeName);
if (isNotBlank(columnSize)) {
platformColumn.setSize(Integer.parseInt(columnSize));
}
platformColumn.setDecimalDigits(decimalDigits);
column.addPlatformColumn(platformColumn);
} catch (Exception ex) {
log.warn("", ex);