-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
ChangeSet.java
1559 lines (1330 loc) · 58.1 KB
/
ChangeSet.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 liquibase.changelog;
import liquibase.ContextExpression;
import liquibase.Labels;
import liquibase.Scope;
import liquibase.change.*;
import liquibase.change.core.EmptyChange;
import liquibase.change.core.RawSQLChange;
import liquibase.change.core.SQLFileChange;
import liquibase.changelog.visitor.ChangeExecListener;
import liquibase.configuration.LiquibaseConfiguration;
import liquibase.database.Database;
import liquibase.database.DatabaseList;
import liquibase.database.ObjectQuotingStrategy;
import liquibase.exception.*;
import liquibase.executor.Executor;
import liquibase.executor.ExecutorService;
import liquibase.executor.LoggingExecutor;
import liquibase.logging.Logger;
import liquibase.logging.mdc.MdcKey;
import liquibase.logging.mdc.customobjects.RollbackSqlFile;
import liquibase.parser.ChangeLogParserConfiguration;
import liquibase.parser.core.ParsedNode;
import liquibase.parser.core.ParsedNodeException;
import liquibase.precondition.Conditional;
import liquibase.precondition.ErrorPrecondition;
import liquibase.precondition.FailedPrecondition;
import liquibase.precondition.core.PreconditionContainer;
import liquibase.resource.ResourceAccessor;
import liquibase.sql.visitor.SqlVisitor;
import liquibase.sql.visitor.SqlVisitorFactory;
import liquibase.sqlgenerator.SqlGeneratorFactory;
import liquibase.statement.SqlStatement;
import liquibase.util.ISODateFormat;
import liquibase.util.SqlUtil;
import liquibase.util.StreamUtil;
import liquibase.util.StringUtil;
import java.time.Instant;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
/**
* Encapsulates a changeSet and all its associated changes.
*/
public class ChangeSet implements Conditional, ChangeLogChild {
protected CheckSum checkSum;
/**
* storedChecksum is used to make the checksum of a changeset that has already been run
* on a database available to liquibase extensions. This value might differ from the checkSum value that
* is calculated at run time when ValidatorVisitor is being called
*/
private CheckSum storedCheckSum;
private static final String AND = " AND ";
private static final String COMMA = ",";
private static final String WHITESPACE = " ";
private static final String OPEN_BRACKET = "(";
private static final String CLOSE_BRACKET = ")";
public enum RunStatus {
NOT_RAN, ALREADY_RAN, RUN_AGAIN, MARK_RAN, INVALID_MD5SUM
}
public enum ExecType {
EXECUTED("EXECUTED", false, true),
FAILED("FAILED", false, false),
SKIPPED("SKIPPED", false, false),
RERAN("RERAN", true, true),
MARK_RAN("MARK_RAN", false, true);
ExecType(String value, boolean ranBefore, boolean ran) {
this.value = value;
this.ranBefore = ranBefore;
this.ran = ran;
}
public final String value;
public final boolean ranBefore;
public final boolean ran;
}
public enum ValidationFailOption {
HALT("HALT"),
MARK_RAN("MARK_RAN");
final String key;
ValidationFailOption(String key) {
this.key = key;
}
@Override
public String toString() {
return key;
}
}
protected String key;
private ChangeLogParameters changeLogParameters;
/**
* List of change objects defined in this changeset
*/
private List<Change> changes;
/**
* "id" specified in changeLog file. Combination of id+author+filePath must be unique
*/
private String id;
/**
* "author" defined in changeLog file. Having each developer use a unique author tag allows duplicates of "id" attributes between developers.
*/
private String author;
/**
* File changeSet is defined in. May be a logical/non-physical string. It is included in the unique identifier to allow duplicate id+author combinations in different files
*/
private String filePath = "UNKNOWN CHANGE LOG";
/**
* A logicalFilePath if defined
*/
private String logicalFilePath;
/**
* File path stored in the databasechangelog table. It should be the same as filePath, but not always.
*/
private String storedFilePath;
/**
* If set to true, the changeSet will be executed on every update. Defaults to false
*/
private boolean alwaysRun;
/**
* If set to true, the changeSet will be executed when the checksum changes. Defaults to false.
*/
private boolean runOnChange;
/**
* Runtime contexts in which the changeSet will be executed. If null or empty, will execute regardless of contexts set
*/
private ContextExpression contextFilter;
/**
* "Labels" associated with this changeSet. If null or empty, will execute regardless of contexts set
*/
private Labels labels;
/**
* If set to true, the changeSet will be ignored (skipped)
*/
private boolean ignore;
/**
* Databases for which this changeset should run. The string values should match the value returned from Database.getShortName()
*/
private Set<String> dbmsSet;
/**
* If false, do not stop liquibase update execution if an error is thrown executing the changeSet. Defaults to true
*/
private Boolean failOnError;
/**
* List of checksums that are assumed to be valid besides the one stored in the database. Can include the string "any"
*/
private Set<CheckSum> validCheckSums = new HashSet<>();
/**
* If true, the changeSet will run in a database transaction. Defaults to true
*/
private boolean runInTransaction;
/**
* Behavior if the validation of any of the changeSet changes fails. Does not include checksum validation
*/
private ValidationFailOption onValidationFail = ValidationFailOption.HALT;
/**
* Stores if validation failed on this ChangeSet
*/
private boolean validationFailed;
/**
* Changes defined to roll back this changeSet
*/
private RollbackContainer rollback = new RollbackContainer();
/**
* ChangeSet comments defined in changeLog file
*/
private String comments;
/**
* ChangeSet level preconditions defined for this changeSet
*/
private PreconditionContainer preconditions;
/**
* ChangeSet level attribute to specify an Executor
*/
private String runWith;
/**
* ChangeSet level attribute to specify a spool file name
*/
private String runWithSpoolFile;
/**
* SqlVisitors defined for this changeset.
* SqlVisitors will modify the SQL generated by the changes before sending it to the database.
*/
private List<SqlVisitor> sqlVisitors = new ArrayList<>();
private ObjectQuotingStrategy objectQuotingStrategy;
private DatabaseChangeLog changeLog;
private String created;
/**
* Allow changeSet to be ran "first" or "last". Multiple changeSets with the same runOrder will preserve their order relative to each other.
*/
private String runOrder;
private Map<String, Object> attributes = new HashMap<>();
/**
* Deployment ID stored in the databasechangelog table.
*/
private String deploymentId;
public boolean shouldAlwaysRun() {
return alwaysRun;
}
public boolean shouldRunOnChange() {
return runOnChange;
}
public ChangeSet(DatabaseChangeLog databaseChangeLog) {
this.changes = new ArrayList<>();
this.changeLog = databaseChangeLog;
}
public ChangeSet(String id, String author, boolean alwaysRun, boolean runOnChange, String filePath, String contextFilter, String dbmsList, DatabaseChangeLog databaseChangeLog) {
this(id, author, alwaysRun, runOnChange, filePath, contextFilter, dbmsList, null, null, true, ObjectQuotingStrategy.LEGACY, databaseChangeLog);
}
public ChangeSet(String id, String author, boolean alwaysRun, boolean runOnChange, String filePath, String contextFilter, String dbmsList, boolean runInTransaction, DatabaseChangeLog databaseChangeLog) {
this(id, author, alwaysRun, runOnChange, filePath, contextFilter, dbmsList, null, null, runInTransaction, ObjectQuotingStrategy.LEGACY, databaseChangeLog);
}
public ChangeSet(String id, String author, boolean alwaysRun, boolean runOnChange, String filePath, String contextFilter, String dbmsList, ObjectQuotingStrategy quotingStrategy, DatabaseChangeLog databaseChangeLog) {
this(id, author, alwaysRun, runOnChange, filePath, contextFilter, dbmsList, null, null, true, quotingStrategy, databaseChangeLog);
}
public ChangeSet(String id, String author, boolean alwaysRun, boolean runOnChange, String filePath, String contextFilter, String dbmsList,
boolean runInTransaction, ObjectQuotingStrategy quotingStrategy, DatabaseChangeLog databaseChangeLog) {
this(id, author, alwaysRun, runOnChange, filePath, contextFilter, dbmsList, null, null, runInTransaction, quotingStrategy, databaseChangeLog);
}
public ChangeSet(String id, String author, boolean alwaysRun, boolean runOnChange, String filePath, String contextFilter, String dbmsList,
String runWith, String runWithSpoolFile, boolean runInTransaction, ObjectQuotingStrategy quotingStrategy, DatabaseChangeLog databaseChangeLog) {
this(databaseChangeLog);
this.id = id;
this.author = author;
this.filePath = filePath;
this.alwaysRun = alwaysRun;
this.runOnChange = runOnChange;
this.runInTransaction = runInTransaction;
this.objectQuotingStrategy = quotingStrategy;
this.contextFilter = new ContextExpression(contextFilter);
setDbms(dbmsList);
this.runWith = runWith;
this.runWithSpoolFile = runWithSpoolFile;
}
protected void setDbms(String dbmsList) {
this.dbmsSet = DatabaseList.toDbmsSet(dbmsList);
}
/**
* @return either this object's logicalFilePath or the changelog's filepath (logical or physical) if not.
*/
public String getFilePath() {
return filePath;
}
/**
* The logical file path defined directly on this node. Return null if not set.
*
* @return
*/
public String getLogicalFilePath() {
return logicalFilePath;
}
public void setLogicalFilePath(String logicalFilePath) {
this.logicalFilePath = logicalFilePath;
}
public String getStoredFilePath() {
if (storedFilePath == null) {
return getFilePath();
}
return storedFilePath;
}
public void setStoredFilePath(String storedFilePath) {
this.storedFilePath = storedFilePath;
}
public String getRunWith() {
return runWith;
}
public void setRunWith(String runWith) {
this.runWith = runWith;
}
public String getRunWithSpoolFile() {
return runWithSpoolFile;
}
public void setRunWithSpoolFile(String runWithSpoolFile) {
this.runWithSpoolFile = runWithSpoolFile;
}
public void clearCheckSum() {
this.checkSum = null;
}
public CheckSum generateCheckSum() {
if (checkSum == null) {
StringBuilder stringToMD5 = new StringBuilder();
for (Change change : getChanges()) {
stringToMD5.append(change.generateCheckSum()).append(":");
}
for (SqlVisitor visitor : this.getSqlVisitors()) {
stringToMD5.append(visitor.generateCheckSum()).append(";");
}
checkSum = CheckSum.compute(stringToMD5.toString());
}
return checkSum;
}
@Override
public void load(ParsedNode node, ResourceAccessor resourceAccessor) throws ParsedNodeException {
this.id = node.getChildValue(null, "id", String.class);
this.author = node.getChildValue(null, "author", String.class);
this.alwaysRun = node.getChildValue(null, "runAlways", node.getChildValue(null, "alwaysRun", false));
this.runOnChange = node.getChildValue(null, "runOnChange", false);
this.runWith = node.getChildValue(null, "runWith", String.class);
this.runWithSpoolFile = node.getChildValue(null, "runWithSpoolFile", String.class);
this.contextFilter = new ContextExpression(node.getChildValue(null, "contextFilter", String.class));
if (this.contextFilter.isEmpty()) {
contextFilter = new ContextExpression(node.getChildValue(null, "context", String.class));
}
this.labels = new Labels(StringUtil.trimToNull(node.getChildValue(null, "labels", String.class)));
setDbms(node.getChildValue(null, "dbms", String.class));
this.runInTransaction = node.getChildValue(null, "runInTransaction", true);
this.created = node.getChildValue(null, "created", String.class);
this.runOrder = node.getChildValue(null, "runOrder", String.class);
this.ignore = node.getChildValue(null, "ignore", false);
this.comments = StringUtil.join(node.getChildren(null, "comment"), "\n", obj -> {
if (((ParsedNode) obj).getValue() == null) {
return "";
} else {
return ((ParsedNode) obj).getValue().toString();
}
});
this.comments = StringUtil.trimToNull(this.comments);
String objectQuotingStrategyString = StringUtil.trimToNull(node.getChildValue(null, "objectQuotingStrategy", String.class));
if (changeLog != null) {
this.objectQuotingStrategy = changeLog.getObjectQuotingStrategy();
}
if (objectQuotingStrategyString != null) {
this.objectQuotingStrategy = ObjectQuotingStrategy.valueOf(objectQuotingStrategyString);
}
if (this.objectQuotingStrategy == null) {
this.objectQuotingStrategy = ObjectQuotingStrategy.LEGACY;
}
this.logicalFilePath = StringUtil.trimToNull(node.getChildValue(null, "logicalFilePath", String.class));
this.filePath = logicalFilePath;
if (filePath == null) {
if (changeLog != null) {
filePath = changeLog.getFilePath();
}
} else {
filePath = filePath.replaceAll("\\\\", "/")
.replaceFirst("^/", "");
}
this.setFailOnError(node.getChildValue(null, "failOnError", Boolean.class));
String onValidationFailString = node.getChildValue(null, "onValidationFail", "HALT");
this.setOnValidationFail(ValidationFailOption.valueOf(onValidationFailString));
for (ParsedNode child : node.getChildren()) {
handleChildNode(child, resourceAccessor);
}
}
protected void handleChildNode(ParsedNode child, ResourceAccessor resourceAccessor) throws ParsedNodeException {
switch (child.getName()) {
case "rollback":
handleRollbackNode(child, resourceAccessor);
break;
case "validCheckSum":
case "validCheckSums":
if (child.getValue() == null) {
return;
}
if (child.getValue() instanceof Collection) {
for (Object checksum : (Collection) child.getValue()) {
addValidCheckSum((String) checksum);
}
} else {
addValidCheckSum(child.getValue(String.class));
}
break;
case "modifySql":
String dbmsString = StringUtil.trimToNull(child.getChildValue(null, "dbms", String.class));
String contextFilterString = StringUtil.trimToNull(child.getChildValue(null, "contextFilter", String.class));
if (contextFilterString == null) {
contextFilterString = StringUtil.trimToNull(child.getChildValue(null, "context", String.class));
}
String labelsString = StringUtil.trimToNull(child.getChildValue(null, "labels", String.class));
boolean applyToRollback = child.getChildValue(null, "applyToRollback", false);
Set<String> dbms = new HashSet<>();
if (dbmsString != null) {
dbms.addAll(StringUtil.splitAndTrim(dbmsString, ","));
}
ContextExpression contextFilter = null;
if (contextFilterString != null) {
contextFilter = new ContextExpression(contextFilterString);
}
Labels labels = null;
if (labelsString != null) {
labels = new Labels(labelsString);
}
List<ParsedNode> potentialVisitors = child.getChildren();
for (ParsedNode node : potentialVisitors) {
SqlVisitor sqlVisitor = SqlVisitorFactory.getInstance().create(node.getName());
if (sqlVisitor != null) {
sqlVisitor.setApplyToRollback(applyToRollback);
if (!dbms.isEmpty()) {
sqlVisitor.setApplicableDbms(dbms);
}
sqlVisitor.setContextFilter(contextFilter);
sqlVisitor.setLabels(labels);
sqlVisitor.load(node, resourceAccessor);
addSqlVisitor(sqlVisitor);
}
}
break;
case "preConditions":
this.preconditions = new PreconditionContainer();
this.preconditions.load(child, resourceAccessor);
break;
case "changes":
for (ParsedNode changeNode : child.getChildren()) {
handleChildNode(changeNode, resourceAccessor);
}
break;
default:
Change change = toChange(child, resourceAccessor);
if ((change == null) && (child.getValue() instanceof String)) {
this.setAttribute(child.getName(), child.getValue());
} else {
addChange(change);
}
break;
}
}
protected void handleRollbackNode(ParsedNode rollbackNode, ResourceAccessor resourceAccessor) throws ParsedNodeException {
String changeSetId = rollbackNode.getChildValue(null, "changeSetId", String.class);
if (changeSetId != null) {
String changeSetAuthor = rollbackNode.getChildValue(null, "changeSetAuthor", String.class);
String changeSetPath = rollbackNode.getChildValue(null, "changeSetPath", getFilePath());
DatabaseChangeLog changeLog = this.getChangeLog();
List<ChangeSet> changeSets = changeLog.getChangeSets(changeSetPath, changeSetAuthor, changeSetId);
while (changeSets.isEmpty() && (changeLog != null)) {
changeLog = changeLog.getParentChangeLog();
if (changeLog != null) {
changeSets = changeLog.getChangeSets(changeSetPath, changeSetAuthor, changeSetId);
}
}
if (changeSets.isEmpty()) {
throw new ParsedNodeException("Change set " + new ChangeSet(changeSetId, changeSetAuthor, false, false, changeSetPath, null, null, null).toString(false) + " does not exist");
}
for (ChangeSet changeSet : changeSets) {
for (Change change : changeSet.getChanges()) {
rollback.getChanges().add(change);
}
}
return;
}
boolean foundValue = false;
for (ParsedNode childNode : rollbackNode.getChildren()) {
Change rollbackChange = toChange(childNode, resourceAccessor);
if (rollbackChange != null) {
addRollbackChange(rollbackChange);
foundValue = true;
}
}
Object value = rollbackNode.getValue();
if (value != null) {
if (value instanceof String) {
String finalValue = StringUtil.trimToNull((String) value);
if (finalValue != null) {
String[] strings = StringUtil.processMultiLineSQL(finalValue, true, true, ";");
for (String string : strings) {
addRollbackChange(new RawSQLChange(string));
foundValue = true;
}
}
} else {
throw new ParsedNodeException("Unexpected object: " + value.getClass().getName() + " '" + value + "'");
}
}
if (!foundValue) {
addRollbackChange(new EmptyChange());
}
}
protected Change toChange(ParsedNode value, ResourceAccessor resourceAccessor) throws ParsedNodeException {
Change change = Scope.getCurrentScope().getSingleton(ChangeFactory.class).create(value.getName());
if (change == null) {
if (value.getChildren().size() > 0 && ChangeLogParserConfiguration.CHANGELOG_PARSE_MODE.getCurrentValue().equals(ChangeLogParserConfiguration.ChangelogParseMode.STRICT)) {
String message = "";
if (this.getChangeLog() != null && this.getChangeLog().getPhysicalFilePath() != null) {
message = "Error parsing " + this.getChangeLog().getPhysicalFilePath() + ": ";
}
message += "Unknown change type '" + value.getName() + "'. Check for spelling or capitalization errors and missing extensions such as liquibase-commercial.";
throw new ParsedNodeException(message);
}
return null;
} else {
change.load(value, resourceAccessor);
return change;
}
}
@Override
public ParsedNode serialize() {
throw new RuntimeException("TODO");
}
public ExecType execute(DatabaseChangeLog databaseChangeLog, Database database) throws MigrationFailedException {
return execute(databaseChangeLog, null, database);
}
/**
* This method will actually execute each of the changes in the list against the
* specified database.
*
* @return should changeset be marked as ran
*/
public ExecType execute(DatabaseChangeLog databaseChangeLog, ChangeExecListener listener, Database database)
throws MigrationFailedException {
Logger log = Scope.getCurrentScope().getLog(getClass());
addChangeSetMdcProperties();
if (validationFailed) {
return ExecType.MARK_RAN;
}
long startTime = new Date().getTime();
Scope.getCurrentScope().addMdcValue(MdcKey.CHANGESET_OPERATION_START_TIME, Instant.ofEpochMilli(startTime).toString());
ExecType execType = null;
boolean skipChange = false;
Executor originalExecutor = setupCustomExecutorIfNecessary(database);
try {
Executor executor = Scope.getCurrentScope().getSingleton(ExecutorService.class).getExecutor("jdbc", database);
// set object quoting strategy
database.setObjectQuotingStrategy(objectQuotingStrategy);
if (database.supportsDDLInTransaction()) {
database.setAutoCommit(!runInTransaction);
}
executor.modifyChangeSet(this);
executor.comment("Changeset " + toString(false));
if (StringUtil.trimToNull(getComments()) != null) {
String comments = getComments();
String[] lines = comments.split("\\n");
for (int i = 0; i < lines.length; i++) {
if (i > 0) {
lines[i] = database.getLineComment() + " " + lines[i];
}
}
executor.comment(StringUtil.join(Arrays.asList(lines), "\n"));
}
try {
if (preconditions != null) {
preconditions.check(database, databaseChangeLog, this, listener);
}
} catch (PreconditionFailedException e) {
if (listener != null) {
listener.preconditionFailed(e, preconditions.getOnFail());
}
StringBuilder message = new StringBuilder();
message.append(StreamUtil.getLineSeparator());
for (FailedPrecondition invalid : e.getFailedPreconditions()) {
message.append(" ").append(invalid.toString());
message.append(StreamUtil.getLineSeparator());
}
if (preconditions.getOnFail().equals(PreconditionContainer.FailOption.HALT)) {
throw new MigrationFailedException(this, message.toString(), e);
} else if (preconditions.getOnFail().equals(PreconditionContainer.FailOption.CONTINUE)) {
skipChange = true;
execType = ExecType.SKIPPED;
Scope.getCurrentScope().getLog(getClass()).info("Continuing past: " + this + " despite precondition failure due to onFail='CONTINUE': " + message);
} else if (preconditions.getOnFail().equals(PreconditionContainer.FailOption.MARK_RAN)) {
execType = ExecType.MARK_RAN;
skipChange = true;
log.info("Marking ChangeSet: \"" + this + "\" as ran despite precondition failure due to onFail='MARK_RAN': " + message);
} else if (preconditions.getOnFail().equals(PreconditionContainer.FailOption.WARN)) {
execType = null; //already warned
} else {
throw new UnexpectedLiquibaseException("Unexpected precondition onFail attribute: " + preconditions.getOnFail(), e);
}
} catch (PreconditionErrorException e) {
if (listener != null) {
listener.preconditionErrored(e, preconditions.getOnError());
}
StringBuilder message = new StringBuilder();
message.append(StreamUtil.getLineSeparator());
for (ErrorPrecondition invalid : e.getErrorPreconditions()) {
message.append(" ").append(invalid.toString());
message.append(StreamUtil.getLineSeparator());
}
if (preconditions.getOnError().equals(PreconditionContainer.ErrorOption.HALT)) {
throw new MigrationFailedException(this, message.toString(), e);
} else if (preconditions.getOnError().equals(PreconditionContainer.ErrorOption.CONTINUE)) {
skipChange = true;
execType = ExecType.SKIPPED;
} else if (preconditions.getOnError().equals(PreconditionContainer.ErrorOption.MARK_RAN)) {
execType = ExecType.MARK_RAN;
skipChange = true;
log.info("Marking ChangeSet: " + this + " ran despite precondition error: " + message);
} else if (preconditions.getOnError().equals(PreconditionContainer.ErrorOption.WARN)) {
execType = null; //already logged
} else {
throw new UnexpectedLiquibaseException("Unexpected precondition onError attribute: " + preconditions.getOnError(), e);
}
database.rollback();
} finally {
database.rollback();
}
if (!skipChange) {
for (Change change : changes) {
try {
change.finishInitialization();
} catch (SetupException se) {
throw new MigrationFailedException(this, se);
}
}
log.fine("Reading ChangeSet: " + this);
for (Change change : getChanges()) {
if ((!(change instanceof DbmsTargetedChange)) || DatabaseList.definitionMatches(((DbmsTargetedChange) change).getDbms(), database, true)) {
if (listener != null) {
listener.willRun(change, this, changeLog, database);
}
if (change.generateStatementsVolatile(database)) {
executor.comment("WARNING The following SQL may change each run and therefore is possibly incorrect and/or invalid:");
}
addSqlMdc(change, database, false);
database.executeStatements(change, databaseChangeLog, sqlVisitors);
log.info(change.getConfirmationMessage());
if (listener != null) {
listener.ran(change, this, changeLog, database);
}
} else {
log.fine("Change " + change.getSerializedObjectName() + " not included for database " + database.getShortName());
}
}
if (runInTransaction) {
database.commit();
}
if (execType == null) {
execType = ExecType.EXECUTED;
}
long stopTime = new Date().getTime();
Scope.getCurrentScope().addMdcValue(MdcKey.CHANGESET_OPERATION_STOP_TIME, Instant.ofEpochMilli(stopTime).toString());
Scope.getCurrentScope().addMdcValue(MdcKey.CHANGESET_OUTCOME, execType.value.toLowerCase());
log.info("ChangeSet " + toString(false) + " ran successfully in " + (stopTime - startTime) + "ms");
} else {
log.fine("Skipping ChangeSet: " + this);
}
} catch (Exception e) {
Scope.getCurrentScope().addMdcValue(MdcKey.CHANGESET_OPERATION_STOP_TIME, Instant.ofEpochMilli(new Date().getTime()).toString());
if (getFailOnError() == null || getFailOnError()) {
Scope.getCurrentScope().addMdcValue(MdcKey.CHANGESET_OUTCOME, ExecType.FAILED.value.toLowerCase());
}
log.severe(String.format("ChangeSet %s encountered an exception.", toString(false)));
try {
database.rollback();
} catch (Exception e1) {
throw new MigrationFailedException(this, e);
}
if ((getFailOnError() != null) && !getFailOnError()) {
log.info("Changeset " + toString(false) + " failed, but failOnError was false. Error: " + e.getMessage());
log.fine("Failure Stacktrace", e);
execType = ExecType.FAILED;
} else {
if (e instanceof MigrationFailedException) {
throw ((MigrationFailedException) e);
} else {
throw new MigrationFailedException(this, e);
}
}
} finally {
Scope.getCurrentScope().getSingleton(ExecutorService.class).setExecutor("jdbc", database, originalExecutor);
// restore auto-commit to false if this ChangeSet was not run in a transaction,
// but only if the database supports DDL in transactions
if (!runInTransaction && database.supportsDDLInTransaction()) {
try {
database.setAutoCommit(false);
} catch (DatabaseException e) {
Scope.getCurrentScope().getLog(getClass()).warning("Could not resetInternalState autocommit", e);
}
}
}
return execType;
}
//
// Get the custom Executor ready if necessary
// We do not do anything if we have a LoggingExecutor.
//
private Executor setupCustomExecutorIfNecessary(Database database) {
Executor originalExecutor = Scope.getCurrentScope().getSingleton(ExecutorService.class).getExecutor("jdbc", database);
if (getRunWith() == null || originalExecutor instanceof LoggingExecutor) {
return originalExecutor;
}
Scope.getCurrentScope().addMdcValue(MdcKey.RUN_WITH, getRunWith());
String executorName = ChangeSet.lookupExecutor(getRunWith());
Executor customExecutor = Scope.getCurrentScope().getSingleton(ExecutorService.class).getExecutor(executorName, database);
Scope.getCurrentScope().getSingleton(ExecutorService.class).setExecutor("jdbc", database, customExecutor);
List<Change> changes = getChanges();
for (Change change : changes) {
if (!(change instanceof AbstractChange)) {
continue;
}
final ResourceAccessor resourceAccessor = ((AbstractChange) change).getResourceAccessor();
if (resourceAccessor != null) {
customExecutor.setResourceAccessor(resourceAccessor);
break;
}
}
return originalExecutor;
}
/**
* Look for a configuration property that matches liquibase.<executor name>.executor
* and if found, return its value as the executor name
*
* @param executorName The value from the input changeset runWith attribute
* @return String The mapped value
*/
public static String lookupExecutor(String executorName) {
if (StringUtil.isEmpty(executorName)) {
return null;
}
String key = "liquibase." + executorName.toLowerCase() + ".executor";
if (executorName.equalsIgnoreCase("psql") || executorName.equalsIgnoreCase("sqlcmd") || executorName.equalsIgnoreCase("sqlplus")) {
return executorName;
}
String replacementExecutorName = (String) Scope.getCurrentScope().getSingleton(LiquibaseConfiguration.class)
.getCurrentConfiguredValue(null, null, key)
.getValue();
if (replacementExecutorName != null) {
Scope.getCurrentScope().getLog(ChangeSet.class).info("Mapped '" + executorName + "' to executor '" + replacementExecutorName + "'");
return replacementExecutorName;
} else if (executorName.equalsIgnoreCase("native")) {
String message = "Unable to locate an executor for 'runWith=" + executorName + "'. You must specify a valid executor name.";
Scope.getCurrentScope().getLog(ChangeSet.class).warning(message);
Scope.getCurrentScope().getUI().sendErrorMessage("WARNING: " + message);
}
return executorName;
}
public void rollback(Database database) throws RollbackFailedException {
rollback(database, null);
}
public void rollback(Database database, ChangeExecListener listener) throws RollbackFailedException {
Scope.getCurrentScope().addMdcValue(MdcKey.CHANGESET_OPERATION_START_TIME, Instant.ofEpochMilli(new Date().getTime()).toString());
addChangeSetMdcProperties();
Scope.getCurrentScope().addMdcValue(MdcKey.DEPLOYMENT_ID, getDeploymentId());
Executor originalExecutor = setupCustomExecutorIfNecessary(database);
try {
Executor executor = Scope.getCurrentScope().getSingleton(ExecutorService.class).getExecutor("jdbc", database);
executor.comment("Rolling Back ChangeSet: " + this);
database.setObjectQuotingStrategy(objectQuotingStrategy);
// set auto-commit based on runInTransaction if database supports DDL in transactions
if (database.supportsDDLInTransaction()) {
database.setAutoCommit(!runInTransaction);
}
executor.modifyChangeSet(this);
if (hasCustomRollbackChanges()) {
final List<SqlStatement> statements = new LinkedList<>();
for (Change change : rollback.getChanges()) {
if (this.ignoreSpecificChangeTypes(change, database)) {
continue;
}
if (listener != null) {
listener.willRun(change, this, changeLog, database);
}
ValidationErrors errors = change.validate(database);
if (errors.hasErrors()) {
throw new RollbackFailedException("Rollback statement failed validation: " + errors);
}
//
SqlStatement[] changeStatements = change.generateStatements(database);
addSqlMdc(change, database, false);
if (change instanceof SQLFileChange) {
addSqlFileMdc((SQLFileChange) change);
}
if (changeStatements != null) {
statements.addAll(Arrays.asList(changeStatements));
}
if (listener != null) {
listener.ran(change, this, changeLog, database);
}
}
if (!statements.isEmpty()) {
database.executeRollbackStatements(statements.toArray(SqlStatement.EMPTY_SQL_STATEMENT), sqlVisitors);
}
} else {
List<Change> changes = getChanges();
for (int i = changes.size() - 1; i >= 0; i--) {
Change change = changes.get(i);
if (change instanceof RawSQLChange && this.getFilePath().toLowerCase().endsWith(".sql")) {
throw new RollbackFailedException("Liquibase does not support automatic rollback generation for raw " +
"sql changes (did you mean to specify keyword \"empty\" to ignore rolling back this change?)");
}
addSqlMdc(change, database, true);
database.executeRollbackStatements(change, sqlVisitors);
}
}
if (runInTransaction) {
database.commit();
}
Scope.getCurrentScope().addMdcValue(MdcKey.CHANGESET_OUTCOME, ExecType.EXECUTED.value.toLowerCase());
Scope.getCurrentScope().addMdcValue(MdcKey.CHANGESET_OPERATION_STOP_TIME, Instant.ofEpochMilli(new Date().getTime()).toString());
Scope.getCurrentScope().getLog(getClass()).fine("ChangeSet " + toString() + " has been successfully rolled back.");
} catch (Exception e) {
Scope.getCurrentScope().addMdcValue(MdcKey.CHANGESET_OPERATION_STOP_TIME, Instant.ofEpochMilli(new Date().getTime()).toString());
try {
Scope.getCurrentScope().addMdcValue(MdcKey.CHANGESET_OUTCOME, ExecType.FAILED.value.toLowerCase());
Scope.getCurrentScope().getLog(getClass()).fine("ChangeSet " + this + " rollback failed.");
database.rollback();
} catch (DatabaseException e1) {
//ok
}
throw new RollbackFailedException(e);
} finally {
// restore auto-commit to false if this ChangeSet was not run in a transaction,
// but only if the database supports DDL in transactions
Scope.getCurrentScope().getSingleton(ExecutorService.class).setExecutor("jdbc", database, originalExecutor);
if (!runInTransaction && database.supportsDDLInTransaction()) {
try {
database.setAutoCommit(false);
} catch (DatabaseException e) {
Scope.getCurrentScope().getLog(getClass()).warning("Could not resetInternalState autocommit", e);
}
}
}
}
private void addSqlFileMdc(SQLFileChange change) {
RollbackSqlFile rollbackSqlFile = new RollbackSqlFile(change);
Scope.getCurrentScope().addMdcValue(MdcKey.ROLLBACK_SQL_FILE, rollbackSqlFile);
}
private boolean ignoreSpecificChangeTypes(Change change, Database database) {
return ((change instanceof DbmsTargetedChange) && !DatabaseList.definitionMatches(((DbmsTargetedChange) change).getDbms(), database, true))
|| ((change instanceof RawSQLChange) && "empty".equalsIgnoreCase(((RawSQLChange)change).getSql()));
}
/**
* Returns whether custom rollback steps are specified for this changeSet, or whether auto-generated ones should be used
*/
public boolean hasCustomRollbackChanges() {
return (rollback != null) && (rollback.getChanges() != null) && !rollback.getChanges().isEmpty();
}
/**
* Returns an unmodifiable list of changes. To add one, use the addRefactoring method.
*/
public List<Change> getChanges() {
return Collections.unmodifiableList(changes);
}
public void addChange(Change change) {
if (change == null) {
return;
}
changes.add(change);
change.setChangeSet(this);
}
public String getId() {
return id;
}
public String getAuthor() {
return author;
}
/**
* @deprecated use {@link #getContextFilter()}
*/
public ContextExpression getContexts() {
return getContextFilter();
}
/**
* @deprecated use {@link #setContextFilter(ContextExpression)}
*/
public ChangeSet setContexts(ContextExpression contexts) {
return setContextFilter(contexts);
}
public ContextExpression getContextFilter() {
return contextFilter;
}
public ChangeSet setContextFilter(ContextExpression contextFilter) {
this.contextFilter = contextFilter;
return this;
}
public Labels getLabels() {
return labels;
}
public void setLabels(Labels labels) {
this.labels = labels;
}