/
AbstractDdlBuilder.java
2692 lines (2414 loc) · 101 KB
/
AbstractDdlBuilder.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 java.sql.Types;
import java.text.DateFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import org.apache.commons.collections.Closure;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.Predicate;
import org.apache.commons.lang.StringUtils;
import org.jumpmind.db.alter.AddColumnChange;
import org.jumpmind.db.alter.AddForeignKeyChange;
import org.jumpmind.db.alter.AddIndexChange;
import org.jumpmind.db.alter.AddPrimaryKeyChange;
import org.jumpmind.db.alter.AddTableChange;
import org.jumpmind.db.alter.ColumnAutoIncrementChange;
import org.jumpmind.db.alter.ColumnDataTypeChange;
import org.jumpmind.db.alter.ColumnDefaultValueChange;
import org.jumpmind.db.alter.ColumnRequiredChange;
import org.jumpmind.db.alter.ColumnSizeChange;
import org.jumpmind.db.alter.CopyColumnValueChange;
import org.jumpmind.db.alter.IModelChange;
import org.jumpmind.db.alter.ModelComparator;
import org.jumpmind.db.alter.PrimaryKeyChange;
import org.jumpmind.db.alter.RemoveColumnChange;
import org.jumpmind.db.alter.RemoveForeignKeyChange;
import org.jumpmind.db.alter.RemoveIndexChange;
import org.jumpmind.db.alter.RemovePrimaryKeyChange;
import org.jumpmind.db.alter.RemoveTableChange;
import org.jumpmind.db.alter.TableChange;
import org.jumpmind.db.model.Column;
import org.jumpmind.db.model.Database;
import org.jumpmind.db.model.ForeignKey;
import org.jumpmind.db.model.IIndex;
import org.jumpmind.db.model.IndexColumn;
import org.jumpmind.db.model.ModelException;
import org.jumpmind.db.model.PlatformColumn;
import org.jumpmind.db.model.Reference;
import org.jumpmind.db.model.Table;
import org.jumpmind.db.model.TypeMap;
import org.jumpmind.db.util.CallbackClosure;
import org.jumpmind.db.util.MultiInstanceofPredicate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This class is a collection of Strategy methods for creating the DDL required
* to create and drop databases and tables.
*
* It is hoped that just a single implementation of this class, for each
* database should make creating DDL for each physical database fairly
* straightforward.
*
* An implementation of this class can always delegate down to some templating
* technology such as Velocity if it requires. Though often that can be quite
* complex when attempting to reuse code across many databases. Hopefully only a
* small amount code needs to be changed on a per database basis.
*/
public abstract class AbstractDdlBuilder implements IDdlBuilder {
/** The line separator for in between sql commands. */
private static final String LINE_SEPARATOR = System.getProperty("line.separator", "\n");
/** The placeholder for the size value in the native type spec. */
protected static final String SIZE_PLACEHOLDER = "{0}";
/** The Log to which logging calls will be made. */
protected final Logger log = LoggerFactory.getLogger(getClass());
/** The indentation used to indent commands. */
private String indent = " ";
/** An optional locale specification for number and date formatting. */
private String valueLocale;
/** The date formatter. */
private DateFormat valueDateFormat;
/** The date time formatter. */
private DateFormat valueTimeFormat;
/** The number formatter. */
private NumberFormat valueNumberFormat;
/** Helper object for dealing with default values. */
private DefaultValueHelper defaultValueHelper = new DefaultValueHelper();
/** The character sequences that need escaping. */
private Map<String, String> charSequencesToEscape = new LinkedHashMap<String, String>();
protected DatabaseInfo databaseInfo = new DatabaseInfo();
protected boolean delimitedIdentifierModeOn = true;
protected boolean sqlCommentsOn = false;
protected boolean scriptModeOn = false;
protected String databaseName;
/**
* Creates a new sql builder.
*/
public AbstractDdlBuilder(String databaseName) {
this.databaseName = databaseName;
}
/**
* Returns the default value helper.
*
* @return The default value helper
*/
public DefaultValueHelper getDefaultValueHelper() {
return defaultValueHelper;
}
/**
* Returns the string used to indent the SQL.
*
* @return The indentation string
*/
public String getIndent() {
return indent;
}
/**
* Sets the string used to indent the SQL.
*
* @param indent
* The indentation string
*/
public void setIndent(String indent) {
this.indent = indent;
}
/**
* Returns the locale that is used for number and date formatting (when
* printing default values and in generates insert/update/delete
* statements).
*
* @return The locale or <code>null</code> if default formatting is used
*/
public String getValueLocale() {
return valueLocale;
}
/**
* Sets the locale that is used for number and date formatting (when
* printing default values and in generates insert/update/delete
* statements).
*
* @param localeStr
* The new locale or <code>null</code> if default formatting
* should be used; Format is "language[_country[_variant]]"
*/
public void setValueLocale(String localeStr) {
if (localeStr != null) {
int sepPos = localeStr.indexOf('_');
String language = null;
String country = null;
String variant = null;
if (sepPos > 0) {
language = localeStr.substring(0, sepPos);
country = localeStr.substring(sepPos + 1);
sepPos = country.indexOf('_');
if (sepPos > 0) {
variant = country.substring(sepPos + 1);
country = country.substring(0, sepPos);
}
} else {
language = localeStr;
}
if (language != null) {
Locale locale = null;
if (variant != null) {
locale = new Locale(language, country, variant);
} else if (country != null) {
locale = new Locale(language, country);
} else {
locale = new Locale(language);
}
valueLocale = localeStr;
setValueDateFormat(DateFormat.getDateInstance(DateFormat.SHORT, locale));
setValueTimeFormat(DateFormat.getTimeInstance(DateFormat.SHORT, locale));
setValueNumberFormat(NumberFormat.getNumberInstance(locale));
return;
}
}
valueLocale = null;
setValueDateFormat(null);
setValueTimeFormat(null);
setValueNumberFormat(null);
}
/**
* Returns the format object for formatting dates in the specified locale.
*
* @return The date format object or null if no locale is set
*/
protected DateFormat getValueDateFormat() {
return valueDateFormat;
}
/**
* Sets the format object for formatting dates in the specified locale.
*
* @param format
* The date format object
*/
protected void setValueDateFormat(DateFormat format) {
this.valueDateFormat = format;
}
/**
* Returns the format object for formatting times in the specified locale.
*
* @return The time format object or null if no locale is set
*/
protected DateFormat getValueTimeFormat() {
return valueTimeFormat;
}
/**
* Sets the date format object for formatting times in the specified locale.
*
* @param format
* The time format object
*/
protected void setValueTimeFormat(DateFormat format) {
this.valueTimeFormat = format;
}
/**
* Returns the format object for formatting numbers in the specified locale.
*
* @return The number format object or null if no locale is set
*/
protected NumberFormat getValueNumberFormat() {
return valueNumberFormat;
}
/**
* Returns a new date format object for formatting numbers in the specified
* locale. Platforms can override this if necessary.
*
* @param format
* The number format object
*/
protected void setValueNumberFormat(NumberFormat format) {
this.valueNumberFormat = format;
}
/**
* Adds a char sequence that needs escaping, and its escaped version.
*
* @param charSequence
* The char sequence
* @param escapedVersion
* The escaped version
*/
protected void addEscapedCharSequence(String charSequence, String escapedVersion) {
charSequencesToEscape.put(charSequence, escapedVersion);
}
public String createTables(Database database, boolean dropTables) {
StringBuilder ddl = new StringBuilder();
createTables(database, dropTables, ddl);
return ddl.toString();
}
/**
* Outputs the DDL required to drop (if requested) and (re)create all tables
* in the database model.
*/
public void createTables(Database database, boolean dropTables, StringBuilder ddl) {
if (dropTables) {
dropTables(database, ddl);
}
for (int idx = 0; idx < database.getTableCount(); idx++) {
Table table = database.getTable(idx);
writeTableComment(table, ddl);
createTable(table, ddl, false, false);
}
// we're writing the external foreignkeys last to ensure that all
// referenced tables are already defined
createExternalForeignKeys(database, ddl);
}
public String alterDatabase(Database currentModel, Database desiredModel, IAlterDatabaseInterceptor... alterDatabaseInterceptors) {
StringBuilder ddl = new StringBuilder();
alterDatabase(currentModel, desiredModel, ddl, alterDatabaseInterceptors);
return ddl.toString();
}
public String alterTable(Table currentTable, Table desiredTable, IAlterDatabaseInterceptor... alterDatabaseInterceptors) {
Database currentModel = new Database();
currentModel.addTable(currentTable);
Database desiredModel = new Database();
desiredModel.addTable(desiredTable);
return alterDatabase(currentModel, desiredModel, alterDatabaseInterceptors);
}
/**
* When the platform columns were added alters were not taken into
* consideration. Therefore, we copy the desiredPlatformColumn to the
* current platform column because the alter code ends up using the current
* column to come up with the alter statements. This is a hack that depends
* on the fact that none of the alter decision are based upon the current
* column's platform column.
*/
protected void mergeOrRemovePlatformTypes(Database currentModel, Database desiredModel) {
Table[] currentTables = currentModel.getTables();
for (Table currentTable : currentTables) {
/*
* Warning - we don't currently support altering tables across
* different catalogs and schemas, so we only need to look up by
* name
*/
Table desiredTable = desiredModel.findTable(currentTable.getName(), false);
if (desiredTable != null) {
Column[] currentColumns = currentTable.getColumns();
for (Column currentColumn : currentColumns) {
Column desiredColumn = desiredTable.getColumnWithName(currentColumn.getName());
if (desiredColumn != null) {
currentColumn.removePlatformColumn(databaseName);
PlatformColumn desiredPlatformColumn = desiredColumn
.findPlatformColumn(databaseName);
if (desiredPlatformColumn != null) {
currentColumn.addPlatformColumn(desiredPlatformColumn);
}
}
}
}
}
}
/**
* Generates the DDL to modify an existing database so the schema matches
* the specified database schema by using drops, modifications and
* additions. Database-specific implementations can change aspect of this
* algorithm by redefining the individual methods that compromise it.
*/
public void alterDatabase(Database currentModel, Database desiredModel, StringBuilder ddl, IAlterDatabaseInterceptor... alterDatabaseInterceptors) {
currentModel = currentModel.copy();
mergeOrRemovePlatformTypes(currentModel, desiredModel);
ModelComparator comparator = new ModelComparator(databaseName, databaseInfo, delimitedIdentifierModeOn);
List<IModelChange> detectedChanges = comparator.compare(currentModel, desiredModel);
if (alterDatabaseInterceptors != null) {
for (IAlterDatabaseInterceptor interceptor : alterDatabaseInterceptors) {
detectedChanges = interceptor.intercept(detectedChanges, currentModel, desiredModel);
}
}
processChanges(currentModel, desiredModel, detectedChanges, ddl);
}
public boolean isAlterDatabase(Database currentModel, Database desiredModel, IAlterDatabaseInterceptor... alterDatabaseInterceptors) {
ModelComparator comparator = new ModelComparator(databaseName, databaseInfo, delimitedIdentifierModeOn);
List<IModelChange> detectedChanges = comparator.compare(currentModel, desiredModel);
if (alterDatabaseInterceptors != null) {
for (IAlterDatabaseInterceptor interceptor : alterDatabaseInterceptors) {
detectedChanges = interceptor.intercept(detectedChanges, currentModel, desiredModel);
}
}
return detectedChanges.size() > 0;
}
/**
* Calls the given closure for all changes that are of one of the given
* types, and then removes them from the changes collection.
*
* @param changes
* The changes
* @param changeTypes
* The types to search for
* @param closure
* The closure to invoke
*/
protected void applyForSelectedChanges(Collection<IModelChange> changes,
Class<?>[] changeTypes, final Closure closure) {
final Predicate predicate = new MultiInstanceofPredicate(changeTypes);
// basically we filter the changes for all objects where the above
// predicate returns true, and for these filtered objects we invoke the
// given closure
CollectionUtils.filter(changes, new Predicate() {
public boolean evaluate(Object obj) {
if (predicate.evaluate(obj)) {
closure.execute(obj);
return false;
} else {
return true;
}
}
});
}
/**
* Processes the changes. The default argument performs several passes:
* <ol>
* <li>
* {@link org.jumpmind.db.alter.RemoveForeignKeyChange} and
* {@link org.jumpmind.db.alter.RemoveIndexChange} come first to allow for
* e.g. subsequent primary key changes or column removal.</li>
* <li>{@link org.jumpmind.db.alter.RemoveTableChange} comes after the
* removal of foreign keys and indices.</li>
* <li>These are all handled together:<br/>
* {@link org.jumpmind.db.alter.RemovePrimaryKeyChange}<br/>
* {@link org.jumpmind.db.alter.AddPrimaryKeyChange}<br/>
* {@link org.jumpmind.db.alter.PrimaryKeyChange}<br/>
* {@link org.jumpmind.db.alter.RemoveColumnChange}<br/>
* {@link org.jumpmind.db.alter.AddColumnChange}<br/>
* {@link org.jumpmind.db.alter.ColumnAutoIncrementChange} <br/>
* {@link org.jumpmind.db.alter.ColumnDefaultValueChange} <br/>
* {@link org.jumpmind.db.alter.ColumnRequiredChange}<br/>
* {@link org.jumpmind.db.alter.ColumnDataTypeChange}<br/>
* {@link org.jumpmind.db.alter.ColumnSizeChange}<br/>
* The reason for this is that the default algorithm rebuilds the table for
* these changes and thus their order is irrelevant.</li>
* <li>{@link org.jumpmind.db.alter.AddTableChange}<br/>
* needs to come after the table removal (so that tables of the same name
* are removed) and before the addition of foreign keys etc.</li>
* <li>{@link org.jumpmind.db.alter.AddForeignKeyChange} and
* {@link org.jumpmind.db.alter.AddIndexChange} come last after
* table/column/primary key additions or changes.</li>
* </ol>
*/
@SuppressWarnings("unchecked")
protected void processChanges(Database currentModel, Database desiredModel,
List<IModelChange> changes, StringBuilder ddl) {
CallbackClosure callbackClosure = new CallbackClosure(this, "processChange", new Class[] {
Database.class, Database.class, null, StringBuilder.class }, new Object[] {
currentModel, desiredModel, null, ddl });
// 1st pass: removing external constraints and indices
applyForSelectedChanges(changes, new Class[] { RemoveForeignKeyChange.class,
RemoveIndexChange.class }, callbackClosure);
// 2nd pass: removing tables
applyForSelectedChanges(changes, new Class[] { RemoveTableChange.class }, callbackClosure);
// 3rd pass: changing the structure of tables
Predicate predicate = new MultiInstanceofPredicate(new Class[] {
RemovePrimaryKeyChange.class, AddPrimaryKeyChange.class, PrimaryKeyChange.class,
RemoveColumnChange.class, AddColumnChange.class, ColumnAutoIncrementChange.class,
ColumnDefaultValueChange.class, ColumnRequiredChange.class,
ColumnDataTypeChange.class, ColumnSizeChange.class, CopyColumnValueChange.class });
processTableStructureChanges(currentModel, desiredModel,
CollectionUtils.select(changes, predicate), ddl);
// 4th pass: adding tables
applyForSelectedChanges(changes, new Class[] { AddTableChange.class }, callbackClosure);
// 5th pass: adding external constraints and indices
applyForSelectedChanges(changes, new Class[] { AddForeignKeyChange.class,
AddIndexChange.class }, callbackClosure);
}
/**
* This is a fall-through callback which generates a warning because a
* specific change type wasn't handled.
*/
protected void processChange(Database currentModel, Database desiredModel, IModelChange change,
StringBuilder ddl) {
log.warn("Change of type " + change.getClass() + " was not handled");
}
/**
* Processes the change representing the removal of a foreign key.
*/
protected void processChange(Database currentModel, Database desiredModel,
RemoveForeignKeyChange change, StringBuilder ddl) {
writeExternalForeignKeyDropStmt(change.getChangedTable(), change.getForeignKey(), ddl);
change.apply(currentModel, delimitedIdentifierModeOn);
}
/**
* Processes the change representing the removal of an index.
*
* @param currentModel
* The current database schema
* @param desiredModel
* The desired database schema
* @param change
* The change object
*/
protected void processChange(Database currentModel, Database desiredModel,
RemoveIndexChange change, StringBuilder ddl) {
writeExternalIndexDropStmt(change.getChangedTable(), change.getIndex(), ddl);
change.apply(currentModel, delimitedIdentifierModeOn);
}
/**
* Processes the change representing the removal of a table.
*
* @param currentModel
* The current database schema
* @param desiredModel
* The desired database schema
* @param change
* The change object
*/
protected void processChange(Database currentModel, Database desiredModel,
RemoveTableChange change, StringBuilder ddl) {
dropTable(change.getChangedTable(), ddl, false, false);
change.apply(currentModel, delimitedIdentifierModeOn);
}
/**
* Processes the change representing the addition of a table.
*
* @param currentModel
* The current database schema
* @param desiredModel
* The desired database schema
* @param change
* The change object
*/
protected void processChange(Database currentModel, Database desiredModel,
AddTableChange change, StringBuilder ddl) {
createTable(change.getNewTable(), ddl, false, false);
change.apply(currentModel, delimitedIdentifierModeOn);
}
/**
* Processes the change representing the addition of a foreign key.
*
* @param currentModel
* The current database schema
* @param desiredModel
* The desired database schema
* @param change
* The change object
*/
protected void processChange(Database currentModel, Database desiredModel,
AddForeignKeyChange change, StringBuilder ddl) {
writeExternalForeignKeyCreateStmt(desiredModel, change.getChangedTable(),
change.getNewForeignKey(), ddl);
change.apply(currentModel, delimitedIdentifierModeOn);
}
/**
* Processes the change representing the addition of an index.
*
* @param currentModel
* The current database schema
* @param desiredModel
* The desired database schema
* @param change
* The change object
*/
protected void processChange(Database currentModel, Database desiredModel,
AddIndexChange change, StringBuilder ddl) {
writeExternalIndexCreateStmt(change.getChangedTable(), change.getNewIndex(), ddl);
change.apply(currentModel, delimitedIdentifierModeOn);
}
protected void filterChanges(Collection<TableChange> changes) {
}
/**
* Processes the changes to the structure of tables.
*
* @param currentModel
* The current database schema
* @param desiredModel
* The desired database schema
* @param changes
* The change objects
*/
protected void processTableStructureChanges(Database currentModel, Database desiredModel,
Collection<TableChange> changes, StringBuilder ddl) {
filterChanges(changes);
LinkedHashMap<String, List<TableChange>> changesPerTable = new LinkedHashMap<String, List<TableChange>>();
LinkedHashMap<String, List<ForeignKey>> unchangedFKs = new LinkedHashMap<String, List<ForeignKey>>();
boolean caseSensitive = delimitedIdentifierModeOn;
// we first sort the changes for the tables
// however since the changes might contain source or target tables
// we use the names rather than the table objects
for (Iterator<TableChange> changeIt = changes.iterator(); changeIt.hasNext();) {
TableChange change = changeIt.next();
String name = change.getChangedTable().getName();
if (!caseSensitive) {
name = name.toUpperCase();
}
List<TableChange> changesForTable = (List<TableChange>) changesPerTable.get(name);
if (changesForTable == null) {
changesForTable = new ArrayList<TableChange>();
changesPerTable.put(name, changesForTable);
unchangedFKs.put(name, getUnchangedForeignKeys(currentModel, desiredModel, name));
}
changesForTable.add(change);
}
// we also need to drop the foreign keys of the unchanged tables
// referencing the changed tables
addRelevantFKsFromUnchangedTables(currentModel, desiredModel, changesPerTable.keySet(),
unchangedFKs);
// we're dropping the unchanged foreign keys
for (Iterator<Map.Entry<String, List<ForeignKey>>> tableFKIt = unchangedFKs.entrySet()
.iterator(); tableFKIt.hasNext();) {
Map.Entry<String, List<ForeignKey>> entry = tableFKIt.next();
Table targetTable = desiredModel.findTable((String) entry.getKey(), caseSensitive);
for (Iterator<ForeignKey> fkIt = entry.getValue().iterator(); fkIt.hasNext();) {
writeExternalForeignKeyDropStmt(targetTable, fkIt.next(), ddl);
}
}
// We're using a copy of the current model so that the table structure
// changes can modify it
Database copyOfCurrentModel = copy(currentModel);
for (Iterator<Map.Entry<String, List<TableChange>>> tableChangeIt = changesPerTable
.entrySet().iterator(); tableChangeIt.hasNext();) {
Map.Entry<String, List<TableChange>> entry = tableChangeIt.next();
processTableStructureChanges(copyOfCurrentModel, desiredModel, entry.getKey(),
entry.getValue(), ddl);
}
// and finally we're re-creating the unchanged foreign keys
for (Iterator<Map.Entry<String, List<ForeignKey>>> tableFKIt = unchangedFKs.entrySet()
.iterator(); tableFKIt.hasNext();) {
Map.Entry<String, List<ForeignKey>> entry = tableFKIt.next();
Table targetTable = desiredModel.findTable((String) entry.getKey(), caseSensitive);
for (Iterator<ForeignKey> fkIt = entry.getValue().iterator(); fkIt.hasNext();) {
writeExternalForeignKeyCreateStmt(desiredModel, targetTable, fkIt.next(), ddl);
}
}
}
/**
* Determines the unchanged foreign keys of the indicated table.
*
* @param currentModel
* The current model
* @param desiredModel
* The desired model
* @param tableName
* The name of the table
* @return The list of unchanged foreign keys
*/
private List<ForeignKey> getUnchangedForeignKeys(Database currentModel, Database desiredModel,
String tableName) {
ArrayList<ForeignKey> unchangedFKs = new ArrayList<ForeignKey>();
boolean caseSensitive = delimitedIdentifierModeOn;
Table sourceTable = currentModel.findTable(tableName, caseSensitive);
Table targetTable = desiredModel.findTable(tableName, caseSensitive);
for (int idx = 0; idx < targetTable.getForeignKeyCount(); idx++) {
ForeignKey targetFK = targetTable.getForeignKey(idx);
ForeignKey sourceFK = sourceTable.findForeignKey(targetFK, caseSensitive);
if (sourceFK != null) {
unchangedFKs.add(targetFK);
}
}
return unchangedFKs;
}
/**
* Adds the foreign keys of the unchanged tables that reference changed
* tables to the given map.
*
* @param currentModel
* The current model
* @param desiredModel
* The desired model
* @param namesOfKnownChangedTables
* The known names of changed tables
* @param fksPerTable
* The map table name -> foreign keys to which found foreign keys
* will be added to
*/
private void addRelevantFKsFromUnchangedTables(Database currentModel, Database desiredModel,
Set<String> namesOfKnownChangedTables, Map<String, List<ForeignKey>> fksPerTable) {
boolean caseSensitive = delimitedIdentifierModeOn;
for (int tableIdx = 0; tableIdx < desiredModel.getTableCount(); tableIdx++) {
Table targetTable = desiredModel.getTable(tableIdx);
String name = targetTable.getName();
Table sourceTable = currentModel.findTable(name, caseSensitive);
List<ForeignKey> relevantFks = null;
if (!caseSensitive) {
name = name.toUpperCase();
}
if ((sourceTable != null) && !namesOfKnownChangedTables.contains(name)) {
for (int fkIdx = 0; fkIdx < targetTable.getForeignKeyCount(); fkIdx++) {
ForeignKey targetFk = targetTable.getForeignKey(fkIdx);
ForeignKey sourceFk = sourceTable.findForeignKey(targetFk, caseSensitive);
String refName = targetFk.getForeignTableName();
if (!caseSensitive) {
refName = refName.toUpperCase();
}
if ((sourceFk != null) && namesOfKnownChangedTables.contains(refName)) {
if (relevantFks == null) {
relevantFks = new ArrayList<ForeignKey>();
fksPerTable.put(name, relevantFks);
}
relevantFks.add(targetFk);
}
}
}
}
}
/**
* Processes the changes to the structure of a single table.
* Database-specific implementations might redefine this method, but it is
* usually sufficient to redefine the
* {@link #processTableStructureChanges(Database, Database, Table, Table, Map, List)}
* method instead.
*/
protected void processTableStructureChanges(Database currentModel, Database desiredModel,
String tableName, List<TableChange> changes, StringBuilder ddl) {
StringBuilder tableDdl = new StringBuilder();
Database originalModel = copy(currentModel);
Table sourceTable = originalModel.findTable(tableName, delimitedIdentifierModeOn);
Table targetTable = desiredModel.findTable(tableName, delimitedIdentifierModeOn);
// we're enforcing a full rebuild in case of the addition of a required
// column without a default value that is not autoincrement
boolean requiresFullRebuild = false;
for (Iterator<TableChange> changeIt = changes.iterator(); !requiresFullRebuild
&& changeIt.hasNext();) {
TableChange change = changeIt.next();
if (change instanceof AddColumnChange) {
AddColumnChange addColumnChange = (AddColumnChange) change;
if (addColumnChange.getNewColumn().isRequired()
&& (addColumnChange.getNewColumn().getDefaultValue() == null)
&& !addColumnChange.getNewColumn().isAutoIncrement()) {
requiresFullRebuild = true;
}
}
}
if (!requiresFullRebuild) {
processTableStructureChanges(currentModel, desiredModel, sourceTable, targetTable,
changes, tableDdl);
}
if (!changes.isEmpty()) {
// we can only copy the data if no required columns without default
// value and non-autoincrement have been added
boolean canMigrateData = true;
for (Iterator<TableChange> it = changes.iterator(); canMigrateData && it.hasNext();) {
TableChange change = it.next();
if (change instanceof AddColumnChange) {
AddColumnChange addColumnChange = (AddColumnChange) change;
if (addColumnChange.getNewColumn().isRequired()
&& !addColumnChange.getNewColumn().isAutoIncrement()
&& (addColumnChange.getNewColumn().getDefaultValue() == null)) {
log.warn("Data cannot be retained in table "
+ change.getChangedTable().getName()
+ " because of the addition of the required column "
+ addColumnChange.getNewColumn().getName());
canMigrateData = false;
}
}
}
Table realTargetTable = getRealTargetTableFor(desiredModel, sourceTable, targetTable);
if (canMigrateData) {
Table tempTable = getTemporaryTableFor(sourceTable);
dropTemporaryTable(tempTable, ddl);
createTemporaryTable(tempTable, ddl);
writeCopyDataStatement(sourceTable, tempTable, ddl);
/*
* Note that we don't drop the indices here because the DROP
* TABLE will take care of that Likewise, foreign keys have
* already been dropped as necessary
*/
dropTable(sourceTable, ddl, false, true);
createTable(realTargetTable, ddl, false, true);
writeCopyDataStatement(tempTable, targetTable, ddl);
dropTemporaryTable(tempTable, ddl);
writeFixLastIdentityValues(targetTable, ddl);
} else {
dropTable(sourceTable, ddl, false, false);
createTable(realTargetTable, ddl, false, false);
}
} else {
ddl.append(tableDdl);
}
}
protected Database copy(Database currentModel) {
try {
return (Database) currentModel.clone();
} catch (CloneNotSupportedException ex) {
throw new DdlException(ex);
}
}
/**
* Allows database-specific implementations to handle changes in a database
* specific manner. Any handled change should be applied to the given
* current model (which is a copy of the real original model) and be removed
* from the list of changes.<br/>
* In the default implementation, all {@link AddPrimaryKeyChange} changes
* are applied via an <code>ALTER TABLE ADD CONSTRAINT</code> statement.
*
* @param currentModel
* The current database schema
* @param desiredModel
* The desired database schema
* @param sourceTable
* The original table
* @param targetTable
* The desired table
* @param changes
* The change objects for the target table
*/
protected void processTableStructureChanges(Database currentModel, Database desiredModel,
Table sourceTable, Table targetTable, List<TableChange> changes, StringBuilder ddl) {
if (changes.size() == 1) {
TableChange change = changes.get(0);
if (change instanceof AddPrimaryKeyChange) {
processChange(currentModel, desiredModel, (AddPrimaryKeyChange) change, ddl);
changes.clear();
}
}
Iterator<TableChange> it = changes.iterator();
while (it.hasNext()) {
TableChange change = (TableChange) it.next();
// Check to see if we can generate alters for type changes
if (change instanceof ColumnDataTypeChange) {
ColumnDataTypeChange typeChange = (ColumnDataTypeChange)change;
if (typeChange.getNewTypeCode() == Types.BIGINT) {
if (writeAlterColumnDataTypeToBigInt(typeChange, ddl)) {
it.remove();
}
}
}
}
}
protected void processChange(Database currentModel, Database desiredModel,
CopyColumnValueChange change, StringBuilder ddl) {
ddl.append("UPDATE ");
ddl.append(getFullyQualifiedTableNameShorten(change.getChangedTable()));
ddl.append(" SET ");
printIdentifier(getColumnName(change.getTargetColumn()), ddl);
ddl.append("=");
printIdentifier(getColumnName(change.getSourceColumn()), ddl);
printEndOfStatement(ddl);
change.apply(currentModel, delimitedIdentifierModeOn);
}
protected boolean writeAlterColumnDataTypeToBigInt(ColumnDataTypeChange change, StringBuilder ddl) {
return false;
}
/**
* The fully qualified table name shorten
*/
protected String getFullyQualifiedTableNameShorten(Table table) {
String result="";
if (StringUtils.isNotBlank(table.getCatalog())) {
result+=getDelimitedIdentifier(table.getCatalog()).concat(databaseInfo.getCatalogSeparator());
}
if (StringUtils.isNotBlank(table.getSchema())) {
result+=getDelimitedIdentifier(table.getSchema()).concat(databaseInfo.getSchemaSeparator());
}
result+=getDelimitedIdentifier(getTableName(table.getName()));
return result;
}
/**
* Creates a temporary table object that corresponds to the given table.
* Database-specific implementations may redefine this method if e.g. the
* database directly supports temporary tables. The default implementation
* simply appends an underscore to the table name and uses that as the table
* name.
* @param targetTable
* The target table
*
* @return The temporary table
*/
protected Table getTemporaryTableFor(Table targetTable) {
return getTemporaryTableFor(targetTable, "_");
}
public Table getBackupTableFor(Table sourceTable) {
return getTemporaryTableFor(sourceTable, "x");
}
public Table createBackupTableFor(Database model, Table sourceTable, StringBuilder ddl) {
Table backupTable = getBackupTableFor(sourceTable);
writeTableCreationStmt(backupTable, ddl);
printEndOfStatement(ddl);
writeCopyDataStatement(sourceTable, backupTable, ddl);
return backupTable;
}
public void restoreTableFromBackup(Table backupTable, Table targetTable,
LinkedHashMap<Column, Column> columnMap, StringBuilder ddl) {
ddl.append("DELETE FROM ");
ddl.append(getFullyQualifiedTableNameShorten(targetTable));
printEndOfStatement(ddl);
writeCopyDataStatement(backupTable, targetTable, columnMap, ddl);
}
protected Table getTemporaryTableFor(Table targetTable, String suffix) {
Table table = new Table();
table.setCatalog(targetTable.getCatalog());
table.setSchema(targetTable.getSchema());
table.setName(targetTable.getName() + suffix);
table.setType(targetTable.getType());
for (int idx = 0; idx < targetTable.getColumnCount(); idx++) {
try {
table.addColumn((Column) targetTable.getColumn(idx).clone());
} catch (CloneNotSupportedException ex) {
throw new DdlException(ex);
}
}
return table;
}
/**
* Outputs the DDL to create the given temporary table. Per default this is
* simply a call to {@link #createTable(Table, Map)}.
* @param table
* The table
*/
protected void createTemporaryTable(Table table, StringBuilder ddl) {
createTable(table, ddl, true, false);
}
/**
* Outputs the DDL to drop the given temporary table. Per default this is
* simply a call to {@link #dropTable(Table)}.
* @param table
* The table
*/
protected void dropTemporaryTable(Table table, StringBuilder ddl) {
dropTable(table, ddl, true, false);
}