/
AbstractDbDialect.java
1438 lines (1250 loc) · 56.1 KB
/
AbstractDbDialect.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
/*
* SymmetricDS is an open source database synchronization solution.
*
* Copyright (C) Chris Henson <chenson42@users.sourceforge.net>,
* Eric Long <erilong@users.sourceforge.net>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, see
* <http://www.gnu.org/licenses/>.
*/
package org.jumpmind.symmetric.db;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.io.StringWriter;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Time;
import java.sql.Timestamp;
import java.sql.Types;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.collections.map.ListOrderedMap;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.apache.commons.lang.time.FastDateFormat;
import org.jumpmind.symmetric.common.ParameterConstants;
import org.jumpmind.symmetric.common.logging.ILog;
import org.jumpmind.symmetric.common.logging.LogFactory;
import org.jumpmind.symmetric.db.informix.InformixDbDialect;
import org.jumpmind.symmetric.db.mssql.MsSqlDbDialect;
import org.jumpmind.symmetric.ddl.Platform;
import org.jumpmind.symmetric.ddl.io.DatabaseIO;
import org.jumpmind.symmetric.ddl.model.Column;
import org.jumpmind.symmetric.ddl.model.Database;
import org.jumpmind.symmetric.ddl.model.ForeignKey;
import org.jumpmind.symmetric.ddl.model.Index;
import org.jumpmind.symmetric.ddl.model.IndexColumn;
import org.jumpmind.symmetric.ddl.model.NonUniqueIndex;
import org.jumpmind.symmetric.ddl.model.Table;
import org.jumpmind.symmetric.ddl.model.UniqueIndex;
import org.jumpmind.symmetric.ddl.platform.DatabaseMetaDataWrapper;
import org.jumpmind.symmetric.ddl.platform.MetaDataColumnDescriptor;
import org.jumpmind.symmetric.ddl.platform.SqlBuilder;
import org.jumpmind.symmetric.ddl.platform.informix.InformixModelReader;
import org.jumpmind.symmetric.ddlutils.JdbcModelReaderSupport;
import org.jumpmind.symmetric.load.IColumnFilter;
import org.jumpmind.symmetric.model.DataEventType;
import org.jumpmind.symmetric.model.Node;
import org.jumpmind.symmetric.model.Trigger;
import org.jumpmind.symmetric.model.TriggerHistory;
import org.jumpmind.symmetric.model.TriggerRouter;
import org.jumpmind.symmetric.service.IParameterService;
import org.jumpmind.symmetric.util.AppUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.ConnectionCallback;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCallback;
import org.springframework.jdbc.support.JdbcUtils;
import org.springframework.jdbc.support.lob.LobHandler;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;
abstract public class AbstractDbDialect implements IDbDialect {
final ILog logger = LogFactory.getLog(getClass());
public static final String REQUIRED_FIELD_NULL_SUBSTITUTE = " ";
public static final String[] TIMESTAMP_PATTERNS = { "yyyy-MM-dd HH:mm:ss.S",
"yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM-dd" };
public static final String[] TIME_PATTERNS = { "HH:mm:ss.S", "HH:mm:ss",
"yyyy-MM-dd HH:mm:ss.S", "yyyy-MM-dd HH:mm:ss" };
public static final FastDateFormat JDBC_TIMESTAMP_FORMATTER = FastDateFormat
.getInstance("yyyy-MM-dd hh:mm:ss.SSS");
protected final ILog log = LogFactory.getLog(getClass());
public static final int MAX_SYMMETRIC_SUPPORTED_TRIGGER_SIZE = 50;
protected JdbcTemplate jdbcTemplate;
protected Platform platform;
protected DatabaseModel cachedModel = new DatabaseModel();
protected SqlTemplate sqlTemplate;
private Map<Integer, String> _defaultSizes;
protected IParameterService parameterService;
protected String tablePrefix;
protected int streamingResultsFetchSize;
protected Boolean supportsGetGeneratedKeys;
protected TransactionTemplate transactionTemplate;
protected String databaseName;
protected int databaseMajorVersion;
protected int databaseMinorVersion;
protected String databaseProductVersion;
protected String identifierQuoteString;
protected Set<String> sqlKeywords;
protected String defaultSchema;
protected LobHandler lobHandler;
protected boolean supportsTransactionViews = false;
protected AbstractDbDialect() {
_defaultSizes = new HashMap<Integer, String>();
_defaultSizes.put(new Integer(1), "254");
_defaultSizes.put(new Integer(12), "254");
_defaultSizes.put(new Integer(-1), "254");
_defaultSizes.put(new Integer(-2), "254");
_defaultSizes.put(new Integer(-3), "254");
_defaultSizes.put(new Integer(-4), "254");
_defaultSizes.put(new Integer(4), "32");
_defaultSizes.put(new Integer(-5), "64");
_defaultSizes.put(new Integer(7), "7,0");
_defaultSizes.put(new Integer(6), "15,0");
_defaultSizes.put(new Integer(8), "15,0");
_defaultSizes.put(new Integer(3), "15,15");
_defaultSizes.put(new Integer(2), "15,15");
}
public String toFormattedTimestamp(java.util.Date time) {
StringBuilder ts = new StringBuilder("{ts '");
ts.append(JDBC_TIMESTAMP_FORMATTER.format(time));
ts.append("'}");
return ts.toString();
}
public IColumnFilter newDatabaseColumnFilter() {
return null;
}
public void prepareTableForDataLoad(Table table) {
}
public void cleanupAfterDataLoad(Table table) {
}
protected boolean allowsNullForIdentityColumn() {
return true;
}
public void resetCachedTableModel() {
synchronized (this.getClass()) {
this.cachedModel.resetTableIndexCache();
Table[] tables = this.cachedModel.getTables();
if (tables != null) {
for (Table table : tables) {
this.cachedModel.removeTable(table);
}
}
}
}
/**
* Provide a default implementation of this method using DDLUtils,
* getMaxColumnNameLength()
*/
public int getMaxTriggerNameLength() {
int max = getPlatform().getPlatformInfo().getMaxColumnNameLength();
return max < MAX_SYMMETRIC_SUPPORTED_TRIGGER_SIZE && max > 0 ? max
: MAX_SYMMETRIC_SUPPORTED_TRIGGER_SIZE;
}
public void init(Platform pf, int queryTimeout, JdbcTemplate jdbcTemplate) {
log.info("DbDialectInUse", this.getClass().getName());
this.jdbcTemplate = jdbcTemplate;
this.jdbcTemplate.setQueryTimeout(queryTimeout);
this.platform = pf;
this.identifierQuoteString = "\"";
jdbcTemplate.execute(new ConnectionCallback<Object>() {
public Object doInConnection(Connection c) throws SQLException, DataAccessException {
DatabaseMetaData meta = c.getMetaData();
databaseName = meta.getDatabaseProductName();
databaseMajorVersion = meta.getDatabaseMajorVersion();
databaseMinorVersion = meta.getDatabaseMinorVersion();
databaseProductVersion = meta.getDatabaseProductVersion();
return null;
}
});
}
abstract protected void initTablesAndFunctionsForSpecificDialect();
public void initTablesAndFunctions() {
initTablesAndFunctionsForSpecificDialect();
createTablesIfNecessary();
createRequiredFunctions();
resetCachedTableModel();
}
final public boolean doesTriggerExist(String catalogName, String schema, String tableName,
String triggerName) {
try {
return doesTriggerExistOnPlatform(catalogName, schema, tableName, triggerName);
} catch (Exception ex) {
log.warn("TriggerMayExist", ex);
return false;
}
}
protected void createRequiredFunctions() {
String[] functions = sqlTemplate.getFunctionsToInstall();
for (int i = 0; i < functions.length; i++) {
String funcName = tablePrefix + "_" + functions[i];
if (jdbcTemplate.queryForInt(sqlTemplate.getFunctionInstalledSql(funcName,
defaultSchema)) == 0) {
jdbcTemplate.update(sqlTemplate.getFunctionSql(functions[i], funcName,
defaultSchema));
log.info("FunctionInstalled", funcName);
}
}
}
public BinaryEncoding getBinaryEncoding() {
return BinaryEncoding.NONE;
}
public boolean isDateOverrideToTimestamp() {
return false;
}
abstract protected boolean doesTriggerExistOnPlatform(String catalogName, String schema,
String tableName, String triggerName);
public String getTransactionTriggerExpression(String defaultCatalog, String defaultSchema,
Trigger trigger) {
return "null";
}
public String createInitialLoadSqlFor(Node node, TriggerRouter trigger, Table table, TriggerHistory triggerHistory) {
return sqlTemplate.createInitalLoadSql(node, this, trigger, table, triggerHistory).trim();
}
public String createPurgeSqlFor(Node node, TriggerRouter triggerRouter) {
return sqlTemplate.createPurgeSql(node, this, triggerRouter);
}
public String createCsvDataSql(Trigger trigger, String whereClause) {
return sqlTemplate.createCsvDataSql(
this,
trigger,
getTable(trigger.getSourceCatalogName(), trigger.getSourceSchemaName(), trigger
.getSourceTableName(), true), whereClause).trim();
}
public String createCsvPrimaryKeySql(Trigger trigger, String whereClause) {
return sqlTemplate.createCsvPrimaryKeySql(
this,
trigger,
getTable(trigger.getSourceCatalogName(), trigger.getSourceSchemaName(), trigger
.getSourceTableName(), true), whereClause).trim();
}
public Table getTable(Trigger trigger, boolean useCache) {
return getTable(trigger.getSourceCatalogName(), trigger.getSourceSchemaName(), trigger
.getSourceTableName(), useCache);
}
/**
* This method uses the ddlutil's model reader which uses the jdbc metadata
* to lookup up table metadata.
* <p/>
* Dialect may optionally override this method to more efficiently lookup up
* table metadata directly against information schemas.
*/
public Table getTable(String catalogName, String schemaName, String tableName, boolean useCache) {
Table retTable = cachedModel.findTable(catalogName, schemaName, tableName);
if (retTable == null || !useCache) {
synchronized (this.getClass()) {
try {
Table table = getTable(catalogName, schemaName, tableName);
if (retTable != null) {
cachedModel.removeTable(retTable);
}
if (table != null) {
cachedModel.addTable(table);
}
retTable = table;
} catch (RuntimeException ex) {
throw ex;
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
}
return retTable;
}
public Set<String> getSqlKeywords() {
if (sqlKeywords == null) {
jdbcTemplate.execute(new ConnectionCallback<Object>() {
public Object doInConnection(Connection con) throws SQLException,
DataAccessException {
DatabaseMetaData metaData = con.getMetaData();
sqlKeywords = new HashSet<String>(Arrays.asList(metaData.getSQLKeywords()
.split(",")));
return null;
}
});
}
return sqlKeywords;
}
/**
* Returns a new {@link Table} object.
*/
protected Table getTable(String catalogName, String schemaName, String tblName) {
if (parameterService.is(ParameterConstants.DB_METADATA_IGNORE_CASE)) {
Table table = getTableCaseSensitive(StringUtils.upperCase(catalogName), StringUtils
.upperCase(schemaName), StringUtils.upperCase(tblName));
if (table == null) {
table = getTableCaseSensitive(StringUtils.lowerCase(catalogName), StringUtils
.lowerCase(schemaName), StringUtils.lowerCase(tblName));
if (table == null) {
table = getTableCaseSensitive(catalogName, schemaName, StringUtils
.upperCase(tblName));
if (table == null) {
table = getTableCaseSensitive(catalogName, schemaName, StringUtils
.lowerCase(tblName));
if (table == null) {
table = getTableCaseSensitive(catalogName, schemaName,
getPlatformTableName(catalogName, schemaName, tblName));
}
}
}
}
return table;
} else {
return getTableCaseSensitive(catalogName, schemaName, tblName);
}
}
protected String getPlatformTableName(String catalogName, String schemaName, String tblName) {
return tblName;
}
protected Table getTableCaseSensitive(String catalogName, String schemaName,
final String tblName) {
// If we don't provide a default schema or catalog, then on some
// databases multiple results will be found in the metadata from
// multiple schemas/catalogs
final String schema = StringUtils.isBlank(schemaName) ? getDefaultSchema() : schemaName;
final String catalog = StringUtils.isBlank(catalogName) ? getDefaultCatalog() : catalogName;
return (Table) jdbcTemplate.execute(new ConnectionCallback<Table>() {
public Table doInConnection(Connection c) throws SQLException, DataAccessException {
Table table = null;
DatabaseMetaDataWrapper metaData = new DatabaseMetaDataWrapper();
metaData.setMetaData(c.getMetaData());
metaData.setCatalog(catalog);
metaData.setSchemaPattern(schema);
metaData.setTableTypes(null);
String tableName = tblName;
if (storesUpperCaseNamesInCatalog()) {
tableName = tblName.toUpperCase();
} else if (storesLowerCaseNamesInCatalog()) {
tableName = tblName.toLowerCase();
}
ResultSet tableData = null;
try {
tableData = metaData.getTables(getTableNamePattern(tableName));
while (tableData != null && tableData.next()) {
Map<String, Object> values = readColumns(tableData, initColumnsForTable());
table = readTable(metaData, values);
}
} finally {
JdbcUtils.closeResultSet(tableData);
}
makeAllColumnsPrimaryKeysIfNoPrimaryKeysFound(table);
return table;
}
});
}
protected String getTableNamePattern(String tableName) {
return tableName;
}
/**
* Treat tables with no primary keys as a table with all primary keys.
*/
protected void makeAllColumnsPrimaryKeysIfNoPrimaryKeysFound(Table table) {
if (table != null && table.getPrimaryKeyColumns() != null
&& table.getPrimaryKeyColumns().length == 0) {
Column[] allCoumns = table.getColumns();
for (Column column : allCoumns) {
if (!column.isOfBinaryType()) {
column.setPrimaryKey(true);
}
}
}
}
@SuppressWarnings("unchecked")
protected Table readTable(DatabaseMetaDataWrapper metaData, Map values) throws SQLException {
String tableName = (String) values.get("TABLE_NAME");
Table table = null;
if (tableName != null && tableName.length() > 0) {
table = new Table();
table.setName(tableName);
table.setType((String) values.get("TABLE_TYPE"));
table.setCatalog((String) values.get("TABLE_CAT"));
table.setSchema((String) values.get("TABLE_SCHEM"));
table.setDescription((String) values.get("REMARKS"));
table.addColumns(readColumns(metaData, tableName));
if (parameterService.is(ParameterConstants.INITIAL_LOAD_CREATE_SCHEMA_BEFORE_RELOAD)) {
table.addIndices(readIndices(metaData, tableName));
}
Collection primaryKeys = readPrimaryKeyNames(metaData, tableName);
for (Iterator it = primaryKeys.iterator(); it.hasNext(); table.findColumn(
(String) it.next(), true).setPrimaryKey(true))
;
if (this instanceof InformixDbDialect) {
InformixModelReader reader = (InformixModelReader) platform.getModelReader();
reader.removeSystemIndices(metaData, table);
}
if (this instanceof MsSqlDbDialect || this instanceof InformixDbDialect) {
determineAutoIncrementFromResultSetMetaData(table, table.getColumns());
}
}
return table;
}
protected List<MetaDataColumnDescriptor> initColumnsForTable() {
List<MetaDataColumnDescriptor> result = new ArrayList<MetaDataColumnDescriptor>();
result.add(new MetaDataColumnDescriptor("TABLE_NAME", 12));
result.add(new MetaDataColumnDescriptor("TABLE_TYPE", 12, "UNKNOWN"));
result.add(new MetaDataColumnDescriptor("TABLE_CAT", 12));
result.add(new MetaDataColumnDescriptor("TABLE_SCHEM", 12));
result.add(new MetaDataColumnDescriptor("REMARKS", 12));
return result;
}
protected List<MetaDataColumnDescriptor> initColumnsForColumn() {
List<MetaDataColumnDescriptor> result = new ArrayList<MetaDataColumnDescriptor>();
result.add(new MetaDataColumnDescriptor("COLUMN_DEF", 12));
result.add(new MetaDataColumnDescriptor("TABLE_NAME", 12));
result.add(new MetaDataColumnDescriptor("COLUMN_NAME", 12));
result.add(new MetaDataColumnDescriptor("TYPE_NAME", 12));
result.add(new MetaDataColumnDescriptor("DATA_TYPE", 4, new Integer(1111)));
result.add(new MetaDataColumnDescriptor("NUM_PREC_RADIX", 4, new Integer(10)));
result.add(new MetaDataColumnDescriptor("DECIMAL_DIGITS", 4, new Integer(0)));
result.add(new MetaDataColumnDescriptor("COLUMN_SIZE", 12));
result.add(new MetaDataColumnDescriptor("IS_NULLABLE", 12, "YES"));
result.add(new MetaDataColumnDescriptor("REMARKS", 12));
return result;
}
protected List<MetaDataColumnDescriptor> initColumnsForPK() {
List<MetaDataColumnDescriptor> result = new ArrayList<MetaDataColumnDescriptor>();
result.add(new MetaDataColumnDescriptor("COLUMN_NAME", 12));
result.add(new MetaDataColumnDescriptor("TABLE_NAME", 12));
result.add(new MetaDataColumnDescriptor("PK_NAME", 12));
return result;
}
@SuppressWarnings("unchecked")
protected Collection<Column> readColumns(DatabaseMetaDataWrapper metaData, String tableName)
throws SQLException {
ResultSet columnData = null;
try {
columnData = metaData.getColumns(getTableNamePattern(tableName), null);
List<Column> columns = new ArrayList<Column>();
Map values = null;
for (; columnData.next(); columns.add(readColumn(metaData, values))) {
values = readColumns(columnData, initColumnsForColumn());
}
return columns;
} finally {
JdbcUtils.closeResultSet(columnData);
}
}
protected Integer overrideJdbcTypeForColumn(Map<Object,Object> values) {
return null;
}
@SuppressWarnings("unchecked")
protected Column readColumn(DatabaseMetaDataWrapper metaData, Map values) throws SQLException {
Column column = new Column();
column.setName((String) values.get("COLUMN_NAME"));
column.setDefaultValue((String) values.get("COLUMN_DEF"));
Integer jdbcType = overrideJdbcTypeForColumn(values);
if (jdbcType != null) {
column.setTypeCode(jdbcType);
} else {
column.setTypeCode(((Integer) values.get("DATA_TYPE")).intValue());
}
column.setPrecisionRadix(((Integer) values.get("NUM_PREC_RADIX")).intValue());
String size = (String) values.get("COLUMN_SIZE");
int scale = ((Integer) values.get("DECIMAL_DIGITS")).intValue();
if (size == null)
size = (String) _defaultSizes.get(new Integer(column.getTypeCode()));
column.setSize(size);
if (scale != 0)
column.setScale(scale);
column.setRequired("NO".equalsIgnoreCase(((String) values.get("IS_NULLABLE")).trim()));
column.setDescription((String) values.get("REMARKS"));
return column;
}
protected void determineAutoIncrementFromResultSetMetaData(final Table table,
final Column columnsToCheck[]) throws SQLException {
final JdbcModelReaderSupport reader = new JdbcModelReaderSupport(platform);
final String catalogSeparator;
if (this instanceof InformixDbDialect) {
catalogSeparator = ":";
} else {
catalogSeparator = ".";
}
jdbcTemplate.execute(new ConnectionCallback<Object>() {
public Object doInConnection(Connection conn) throws SQLException, DataAccessException {
reader.determineAutoIncrementFromResultSetMetaData(conn, table, table.getColumns(),
catalogSeparator);
return null;
}
});
}
@SuppressWarnings("unchecked")
protected Map<String, Object> readColumns(ResultSet resultSet, List columnDescriptors)
throws SQLException {
HashMap<String, Object> values = new HashMap<String, Object>();
MetaDataColumnDescriptor descriptor;
for (Iterator it = columnDescriptors.iterator(); it.hasNext(); values.put(descriptor
.getName(), descriptor.readColumn(resultSet)))
descriptor = (MetaDataColumnDescriptor) it.next();
return values;
}
@SuppressWarnings("unchecked")
protected Collection<String> readPrimaryKeyNames(DatabaseMetaDataWrapper metaData,
String tableName) throws SQLException {
ResultSet pkData = null;
try {
List<String> pks = new ArrayList<String>();
Map values;
for (pkData = metaData.getPrimaryKeys(getTableNamePattern(tableName)); pkData.next(); pks
.add(readPrimaryKeyName(metaData, values))) {
values = readColumns(pkData, initColumnsForPK());
}
return pks;
} finally {
JdbcUtils.closeResultSet(pkData);
}
}
@SuppressWarnings("unchecked")
protected String readPrimaryKeyName(DatabaseMetaDataWrapper metaData, Map values)
throws SQLException {
return (String) values.get("COLUMN_NAME");
}
@SuppressWarnings("unchecked")
protected List initColumnsForIndex() {
List result = new ArrayList();
result.add(new MetaDataColumnDescriptor("INDEX_NAME", Types.VARCHAR));
// we're also reading the table name so that a model reader impl can
// filter manually
result.add(new MetaDataColumnDescriptor("TABLE_NAME", Types.VARCHAR));
result.add(new MetaDataColumnDescriptor("NON_UNIQUE", Types.BIT, Boolean.TRUE));
result.add(new MetaDataColumnDescriptor("ORDINAL_POSITION", Types.TINYINT, new Short(
(short) 0)));
result.add(new MetaDataColumnDescriptor("COLUMN_NAME", Types.VARCHAR));
result.add(new MetaDataColumnDescriptor("TYPE", Types.TINYINT));
return result;
}
@SuppressWarnings("unchecked")
protected Collection readIndices(DatabaseMetaDataWrapper metaData, String tableName)
throws SQLException {
if (this instanceof InformixDbDialect) {
InformixModelReader reader = (InformixModelReader) platform.getModelReader();
return reader.readIndices(metaData, tableName);
}
Map indices = new ListOrderedMap();
ResultSet indexData = null;
try {
indexData = metaData.getIndices(getTableNamePattern(tableName), false, false);
while (indexData.next()) {
Map values = readColumns(indexData, initColumnsForIndex());
readIndex(metaData, values, indices);
}
} finally {
if (indexData != null) {
indexData.close();
}
}
return indices.values();
}
@SuppressWarnings("unchecked")
protected void readIndex(DatabaseMetaDataWrapper metaData, Map values, Map knownIndices)
throws SQLException {
Short indexType = (Short) values.get("TYPE");
// we're ignoring statistic indices
if ((indexType != null) && (indexType.shortValue() == DatabaseMetaData.tableIndexStatistic)) {
return;
}
String indexName = (String) values.get("INDEX_NAME");
if (indexName != null) {
Index index = (Index) knownIndices.get(indexName);
if (index == null) {
if (((Boolean) values.get("NON_UNIQUE")).booleanValue()) {
index = new NonUniqueIndex();
} else {
index = new UniqueIndex();
}
index.setName(indexName);
knownIndices.put(indexName, index);
}
IndexColumn indexColumn = new IndexColumn();
indexColumn.setName((String) values.get("COLUMN_NAME"));
if (values.containsKey("ORDINAL_POSITION")) {
indexColumn.setOrdinalPosition(((Short) values.get("ORDINAL_POSITION")).intValue());
}
index.addColumn(indexColumn);
}
}
public void removeTrigger(StringBuilder sqlBuffer, String catalogName, String schemaName,
String triggerName, String tableName, TriggerHistory oldHistory) {
schemaName = schemaName == null ? "" : (schemaName + ".");
final String sql = "drop trigger " + schemaName + triggerName;
logSql(sql, sqlBuffer);
if (parameterService.is(ParameterConstants.AUTO_SYNC_TRIGGERS)) {
try {
jdbcTemplate.update(sql);
} catch (Exception e) {
log.warn("TriggerDoesNotExist");
}
}
}
final protected void logSql(String sql, StringBuilder sqlBuffer) {
if (sqlBuffer != null) {
sqlBuffer.append(sql);
sqlBuffer.append(System.getProperty("line.separator"));
sqlBuffer.append(System.getProperty("line.separator"));
}
}
/**
* Create the configured trigger. The catalog will be changed to the source
* schema if the source schema is configured.
*/
public void createTrigger(final StringBuilder sqlBuffer, final DataEventType dml,
final Trigger trigger, final TriggerHistory hist, final String tablePrefix,
final Table table) {
jdbcTemplate.execute(new ConnectionCallback<Object>() {
public Object doInConnection(Connection con) throws SQLException, DataAccessException {
log.info("TriggerCreating", hist.getTriggerNameForDmlType(dml), trigger
.getSourceTableName());
String previousCatalog = null;
String sourceCatalogName = trigger.getSourceCatalogName();
String defaultCatalog = getDefaultCatalog();
String defaultSchema = getDefaultSchema();
try {
previousCatalog = switchCatalogForTriggerInstall(sourceCatalogName, con);
String triggerSql = sqlTemplate.createTriggerDDL(AbstractDbDialect.this, dml,
trigger, hist, tablePrefix, table, defaultCatalog, defaultSchema);
if (parameterService.is(ParameterConstants.AUTO_SYNC_TRIGGERS)) {
Statement stmt = con.createStatement();
stmt.setQueryTimeout(jdbcTemplate.getQueryTimeout());
try {
log.debug("Sql", triggerSql);
stmt.executeUpdate(triggerSql);
} catch (SQLException ex) {
log.error("TriggerCreateFailed", triggerSql);
throw ex;
}
String postTriggerDml = createPostTriggerDDL(dml, trigger, hist,
tablePrefix, table);
if (postTriggerDml != null) {
try {
stmt.executeUpdate(postTriggerDml);
} catch (SQLException ex) {
log.error("PostTriggerCreateFailed", postTriggerDml);
throw ex;
}
}
stmt.close();
}
logSql(triggerSql, sqlBuffer);
} finally {
if (sourceCatalogName != null
&& !sourceCatalogName.equalsIgnoreCase(previousCatalog)) {
switchCatalogForTriggerInstall(previousCatalog, con);
}
}
return null;
}
});
}
/**
* Provide the option switch a connection's schema for trigger installation.
*/
protected String switchCatalogForTriggerInstall(String catalog, Connection c)
throws SQLException {
return null;
}
public String createPostTriggerDDL(DataEventType dml, Trigger trigger, TriggerHistory hist,
String tablePrefix, Table table) {
return sqlTemplate.createPostTriggerDDL(this, dml, trigger, hist, tablePrefix, table,
getDefaultCatalog(), getDefaultSchema());
}
public String getCreateSymmetricDDL() {
Database db = readSymmetricSchemaFromXml();
prefixConfigDatabase(db);
return platform.getCreateTablesSql(db, true, true);
}
public String getCreateTableSQL(TriggerRouter trig) {
Table table = getTable(null, trig.getTrigger().getSourceSchemaName(), trig.getTrigger()
.getSourceTableName(), true);
String sql = null;
try {
StringWriter buffer = new StringWriter();
platform.getSqlBuilder().setWriter(buffer);
platform.getSqlBuilder().createTable(cachedModel, table);
sql = buffer.toString();
} catch (IOException e) {
}
return sql;
}
public String getCreateTableXML(TriggerRouter triggerRouter) {
Table table = getTable(null, triggerRouter.getTrigger().getSourceSchemaName(),
triggerRouter.getTrigger().getSourceTableName());
table.setName(triggerRouter.getTargetTable());
Database db = new Database();
db.setName(triggerRouter.getTargetSchema(getDefaultSchema()));
if (db.getName() == null) {
db.setName(getDefaultCatalog());
}
db.addTable(table);
StringWriter buffer = new StringWriter();
DatabaseIO xmlWriter = new DatabaseIO();
xmlWriter.write(db, buffer);
// TODO: remove when these bugs are fixed in DdlUtils
String xml = buffer.toString().replaceAll("'", "");
xml = xml.replaceAll("default=\"empty_blob\\(\\) *\"", "");
xml = xml.replaceAll("unique name=\"PRIMARY\"", "unique name=\"PRIMARYINDEX\"");
return xml;
}
public void createTables(String xml) {
StringReader reader = new StringReader(xml);
Database db = new DatabaseIO().read(reader);
platform.createTables(db, true, true);
}
public boolean doesDatabaseNeedConfigured() {
return prefixConfigDatabase(readSymmetricSchemaFromXml());
}
protected boolean prefixConfigDatabase(Database targetTables) {
try {
String tblPrefix = this.tablePrefix + "_";
Table[] tables = targetTables.getTables();
boolean createTables = false;
for (Table table : tables) {
table.setName(tblPrefix + table.getName());
fixForeignKeys(table, tblPrefix, false);
if (getTable(getDefaultCatalog(), getDefaultSchema(), table.getName(), false) == null) {
createTables = true;
}
}
return createTables;
} catch (CloneNotSupportedException e) {
throw new RuntimeException(e);
}
}
public Database readPlatformDatabase(boolean includeSymmetricTables) {
String schema = getDefaultSchema();
String catalog = getDefaultCatalog();
Database database = platform.readModelFromDatabase(!StringUtils.isBlank(schema) ? schema
: (!StringUtils.isBlank(catalog) ? catalog : "database"), catalog, schema, null);
if (!includeSymmetricTables) {
Database symmetricTables = readSymmetricSchemaFromXml();
Table[] tables = symmetricTables.getTables();
for (Table symTable : tables) {
for (Table table : database.getTables()) {
if (table.getName().equalsIgnoreCase(symTable.getName())) {
database.removeTable(table);
}
}
}
Table[] allTables = database.getTables();
for (Table table : allTables) {
// Remove SYM_ON_ trigger tables for embedded databases
if (table.getName().startsWith(tablePrefix.toUpperCase() + "_ON_")) {
database.removeTable(table);
}
}
}
return database;
}
/**
* @return true if SQL was executed.
*/
protected boolean createTablesIfNecessary() {
Database symmetricTables = readSymmetricSchemaFromXml();
try {
log.info("TablesAutoUpdatingStart");
String alterSql = getAlterSql(symmetricTables);
log.debug("TablesAutoUpdatingAlterSql", alterSql);
if (!StringUtils.isBlank(alterSql)) {
new SqlScript(alterSql, jdbcTemplate.getDataSource(), true, platform
.getPlatformInfo().getSqlCommandDelimiter(), null).execute();
return true;
} else {
return false;
}
} catch (RuntimeException ex) {
throw ex;
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
protected String getAlterSql(Database desiredModel) throws IOException {
Database currentModel = new Database();
Table[] tables = desiredModel.getTables();
Database existingModel = readPlatformDatabase(true);
for (Table table : tables) {
Table currentVersion = existingModel.findTable(table.getName());
if (currentVersion != null) {
currentModel.addTable(currentVersion);
}
}
SqlBuilder builder = platform.getSqlBuilder();
StringWriter writer = new StringWriter();
builder.setWriter(writer);
builder.alterDatabase(currentModel, desiredModel, null);
return writer.toString();
}
protected Database readSymmetricSchemaFromXml() {
try {
Database database = new DatabaseIO().read(new InputStreamReader(AbstractDbDialect.class
.getResource("/symmetric-schema.xml").openStream()));
if (prefixConfigDatabase(database)) {
log.info("TablesMissing");
}
return database;
} catch (RuntimeException ex) {
throw ex;
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
protected void fixForeignKeys(Table table, String tablePrefix, boolean clone)
throws CloneNotSupportedException {
ForeignKey[] keys = table.getForeignKeys();
for (ForeignKey key : keys) {
if (clone) {
table.removeForeignKey(key);
key = (ForeignKey) key.clone();
table.addForeignKey(key);
}
String prefixedName = tablePrefix + key.getForeignTableName();
key.setForeignTableName(prefixedName);
key.setName(tablePrefix + key.getName());
}
}
public Platform getPlatform() {
return this.platform;
}
public String getName() {
return databaseName;
}
public String getVersion() {
return databaseMajorVersion + "." + databaseMinorVersion;
}
public int getMajorVersion() {
return databaseMajorVersion;
}
public int getMinorVersion() {
return databaseMinorVersion;
}
public String getProductVersion() {
return databaseProductVersion;
}
public String replaceTemplateVariables(DataEventType dml, Trigger trigger,
TriggerHistory history, String targetString) {
return sqlTemplate.replaceTemplateVariables(this, dml, trigger, history, tablePrefix,
getTable(trigger.getSourceCatalogName(), trigger.getSourceSchemaName(), trigger
.getSourceTableName(), true), getDefaultCatalog(), getDefaultSchema(),
targetString);
}
public boolean supportsGetGeneratedKeys() {
if (supportsGetGeneratedKeys == null) {
supportsGetGeneratedKeys = jdbcTemplate.execute(new ConnectionCallback<Boolean>() {
public Boolean doInConnection(Connection conn) throws SQLException,
DataAccessException {
return conn.getMetaData().supportsGetGeneratedKeys();
}
});
}
return supportsGetGeneratedKeys;
}
public boolean supportsTransactionViews() {
return supportsTransactionViews;
}