/
OfflineChangeLogHistoryService.java
408 lines (353 loc) · 15.9 KB
/
OfflineChangeLogHistoryService.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
package liquibase.changelog;
import liquibase.ContextExpression;
import liquibase.Labels;
import liquibase.Scope;
import liquibase.change.Change;
import liquibase.change.CheckSum;
import liquibase.change.core.TagDatabaseChange;
import liquibase.changelog.ChangeSet.ExecType;
import liquibase.GlobalConfiguration;
import liquibase.database.Database;
import liquibase.database.OfflineConnection;
import liquibase.exception.DatabaseException;
import liquibase.exception.LiquibaseException;
import liquibase.exception.UnexpectedLiquibaseException;
import liquibase.executor.ExecutorService;
import liquibase.servicelocator.LiquibaseService;
import liquibase.statement.core.CreateDatabaseChangeLogTableStatement;
import liquibase.statement.core.MarkChangeSetRanStatement;
import liquibase.statement.core.RemoveChangeSetRanStatusStatement;
import liquibase.statement.core.UpdateChangeSetChecksumStatement;
import liquibase.util.ISODateFormat;
import liquibase.util.LiquibaseUtil;
import liquibase.util.csv.CSVReader;
import liquibase.util.csv.CSVWriter;
import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@LiquibaseService(skip = true)
@SuppressWarnings("java:S899")
public class OfflineChangeLogHistoryService extends AbstractChangeLogHistoryService {
private final File changeLogFile;
private boolean executeDmlAgainstDatabase = true;
/**
* Output CREATE TABLE LIQUIBASECHANGELOG or not
*/
private boolean executeDdlAgainstDatabase = true;
private Integer lastChangeSetSequenceValue;
private enum Columns {
ID,
AUTHOR,
FILENAME,
DATEEXECUTED,
ORDEREXECUTED,
EXECTYPE,
MD5SUM,
DESCRIPTION,
COMMENTS,
TAG,
LIQUIBASE,
CONTEXTS,
LABELS,
DEPLOYMENT_ID,
}
public OfflineChangeLogHistoryService(Database database, File changeLogFile, boolean executeDmlAgainstDatabase, boolean executeDdlAgainstDatabase) {
setDatabase(database);
this.executeDmlAgainstDatabase = executeDmlAgainstDatabase;
this.executeDdlAgainstDatabase = executeDdlAgainstDatabase;
changeLogFile = changeLogFile.getAbsoluteFile();
this.changeLogFile = changeLogFile;
}
@Override
public int getPriority() {
return 500;
}
@Override
public boolean supports(Database database) {
return (database.getConnection() != null) && (database.getConnection() instanceof OfflineConnection);
}
public boolean isExecuteDmlAgainstDatabase() {
return executeDmlAgainstDatabase;
}
public void setExecuteDmlAgainstDatabase(boolean executeDmlAgainstDatabase) {
this.executeDmlAgainstDatabase = executeDmlAgainstDatabase;
}
public boolean isExecuteDdlAgainstDatabase() {
return executeDdlAgainstDatabase;
}
public void setExecuteDdlAgainstDatabase(boolean executeDdlAgainstDatabase) {
this.executeDdlAgainstDatabase = executeDdlAgainstDatabase;
}
@Override
public void reset() {
// nothing to do.
}
@Override
public void init() throws DatabaseException {
if (!changeLogFile.exists()) {
changeLogFile.getParentFile().mkdirs();
try {
changeLogFile.createNewFile();
writeHeader(changeLogFile);
if (isExecuteDdlAgainstDatabase()) {
Scope.getCurrentScope().getSingleton(ExecutorService.class).getExecutor("jdbc", getDatabase()).execute(new CreateDatabaseChangeLogTableStatement());
}
} catch (Exception e) {
throw new UnexpectedLiquibaseException(e);
}
}
}
protected void writeHeader(File file) throws IOException {
try (FileOutputStream outputStream = new FileOutputStream(file);
Writer writer = new OutputStreamWriter(outputStream,
GlobalConfiguration.OUTPUT_FILE_ENCODING.getCurrentValue())
) {
CSVWriter csvWriter = new CSVWriter(writer);
String[] columns = new String[Columns.values().length];
int i = 0;
for (Columns column : Columns.values()) {
columns[i++] = column.toString();
}
csvWriter.writeNext(columns);
}
}
@Override
protected void replaceChecksum(final ChangeSet changeSet) throws DatabaseException {
if (isExecuteDmlAgainstDatabase()) {
Scope.getCurrentScope().getSingleton(ExecutorService.class).getExecutor("jdbc", getDatabase()).execute(new UpdateChangeSetChecksumStatement(changeSet));
}
replaceChangeSet(changeSet, new ReplaceChangeSetLogic() {
@Override
public String[] execute(String[] line) {
line[Columns.MD5SUM.ordinal()] = changeSet.generateCheckSum().toString();
return line;
}
});
}
@Override
public List<RanChangeSet> getRanChangeSets() throws DatabaseException {
try (
Reader reader = new InputStreamReader(new FileInputStream(this.changeLogFile), GlobalConfiguration.OUTPUT_FILE_ENCODING.getCurrentValue())
)
{
CSVReader csvReader = new CSVReader(reader);
String[] line = csvReader.readNext();
if (line == null) { //empty file
writeHeader(this.changeLogFile);
return new ArrayList<>();
}
if (!"ID".equals(line[Columns.ID.ordinal()])) {
throw new DatabaseException("Missing header in file "+this.changeLogFile.getAbsolutePath());
}
List<RanChangeSet> returnList = new ArrayList<>();
while ((line = csvReader.readNext()) != null) {
ContextExpression contexts = new ContextExpression();
if (line.length > Columns.CONTEXTS.ordinal()) {
contexts = new ContextExpression(line[Columns.CONTEXTS.ordinal()]);
}
Labels labels = new Labels();
if (line.length > Columns.LABELS.ordinal()) {
labels = new Labels(line[Columns.LABELS.ordinal()]);
}
String deploymentId = null;
if (line.length > Columns.DEPLOYMENT_ID.ordinal()) {
deploymentId = line[Columns.DEPLOYMENT_ID.ordinal()];
}
returnList.add(new RanChangeSet(
line[Columns.FILENAME.ordinal()],
line[Columns.ID.ordinal()],
line[Columns.AUTHOR.ordinal()],
CheckSum.parse(line[Columns.MD5SUM.ordinal()]),
new ISODateFormat().parse(line[Columns.DATEEXECUTED.ordinal()]),
line[Columns.TAG.ordinal()],
ChangeSet.ExecType.valueOf(line[Columns.EXECTYPE.ordinal()]),
line[Columns.DESCRIPTION.ordinal()],
line[Columns.COMMENTS.ordinal()],
contexts,
labels,
deploymentId));
}
return returnList;
} catch (Exception e) {
throw new DatabaseException(e);
}
}
protected void replaceChangeSet(ChangeSet changeSet, ReplaceChangeSetLogic replaceLogic) throws DatabaseException {
File oldFile = this.changeLogFile;
File newFile = new File(oldFile.getParentFile(), oldFile.getName()+".new");
try (
Reader reader = new InputStreamReader(new FileInputStream(oldFile), GlobalConfiguration.OUTPUT_FILE_ENCODING.getCurrentValue());
Writer writer = new OutputStreamWriter(new FileOutputStream(newFile), GlobalConfiguration.OUTPUT_FILE_ENCODING.getCurrentValue());
CSVReader csvReader = new CSVReader(reader);
CSVWriter csvWriter = new CSVWriter(writer)
)
{
String[] line;
while ((line = csvReader.readNext()) != null) {
if ((changeSet == null) || (line[Columns.ID.ordinal()].equals(changeSet.getId()) && line[Columns.AUTHOR.ordinal()].equals
(changeSet.getAuthor()) && line[Columns.FILENAME.ordinal()].equals(changeSet.getFilePath()))) {
line = replaceLogic.execute(line);
}
if (line != null) {
csvWriter.writeNext(line);
}
}
} catch (Exception e) {
throw new DatabaseException(e);
}
oldFile.delete();
newFile.renameTo(oldFile);
}
protected void appendChangeSet(ChangeSet changeSet, ChangeSet.ExecType execType) throws DatabaseException {
File oldFile = this.changeLogFile;
File newFile = new File(oldFile.getParentFile(), oldFile.getName()+".new");
try (
Reader reader = new InputStreamReader(new FileInputStream(oldFile), GlobalConfiguration.OUTPUT_FILE_ENCODING.getCurrentValue());
Writer writer = new OutputStreamWriter(new FileOutputStream(newFile), GlobalConfiguration.OUTPUT_FILE_ENCODING.getCurrentValue());
CSVReader csvReader = new CSVReader(reader);
CSVWriter csvWriter = new CSVWriter(writer)
)
{
String[] line;
while ((line = csvReader.readNext()) != null) {
csvWriter.writeNext(line);
}
String tag = "";
for (Change change : changeSet.getChanges()) {
if (change instanceof TagDatabaseChange) {
TagDatabaseChange tagChange = (TagDatabaseChange) change;
tag = tagChange.getTag();
}
}
String[] newLine = new String[Columns.values().length];
newLine[Columns.ID.ordinal()] = changeSet.getId();
newLine[Columns.AUTHOR.ordinal()] = changeSet.getAuthor();
newLine[Columns.FILENAME.ordinal()] = changeSet.getFilePath();
newLine[Columns.DATEEXECUTED.ordinal()] = new ISODateFormat().format(new java.sql.Timestamp(new Date().getTime()));
newLine[Columns.ORDEREXECUTED.ordinal()] = String.valueOf(getNextSequenceValue());
newLine[Columns.EXECTYPE.ordinal()] = execType.value;
newLine[Columns.MD5SUM.ordinal()] = changeSet.generateCheckSum().toString();
newLine[Columns.DESCRIPTION.ordinal()] = changeSet.getDescription();
newLine[Columns.COMMENTS.ordinal()] = changeSet.getComments();
newLine[Columns.TAG.ordinal()] = tag;
newLine[Columns.LIQUIBASE.ordinal()] = LiquibaseUtil.getBuildVersion();
newLine[Columns.CONTEXTS.ordinal()] = (changeSet.getContextFilter() == null) ? null : changeSet.getContextFilter().toString();
newLine[Columns.LABELS.ordinal()] = (changeSet.getLabels() == null) ? null : changeSet.getLabels().toString();
newLine[Columns.DEPLOYMENT_ID.ordinal()] = getDeploymentId();
csvWriter.writeNext(newLine);
} catch (Exception e) {
throw new DatabaseException(e);
}
oldFile.delete();
newFile.renameTo(oldFile);
}
@Override
public void setExecType(final ChangeSet changeSet, final ChangeSet.ExecType execType) throws DatabaseException {
if (isExecuteDmlAgainstDatabase()) {
Scope.getCurrentScope().getSingleton(ExecutorService.class).getExecutor("jdbc", getDatabase()).execute(new MarkChangeSetRanStatement(changeSet, execType));
getDatabase().commit();
}
if (execType.equals(ChangeSet.ExecType.FAILED) || execType.equals(ChangeSet.ExecType.SKIPPED)) {
return; //do nothing
} else if (execType.ranBefore) {
replaceChangeSet(changeSet, new ReplaceChangeSetLogic() {
@Override
public String[] execute(String[] line) {
line[Columns.DATEEXECUTED.ordinal()] = new ISODateFormat().format(new java.sql.Timestamp(new Date().getTime()));
line[Columns.MD5SUM.ordinal()] = changeSet.generateCheckSum().toString();
line[Columns.EXECTYPE.ordinal()] = execType.value;
return line;
}
});
} else {
appendChangeSet(changeSet, execType);
}
}
@Override
public void removeFromHistory(ChangeSet changeSet) throws DatabaseException {
if (isExecuteDmlAgainstDatabase()) {
Scope.getCurrentScope().getSingleton(ExecutorService.class).getExecutor("jdbc", getDatabase()).execute(new RemoveChangeSetRanStatusStatement(changeSet));
getDatabase().commit();
}
replaceChangeSet(changeSet, new ReplaceChangeSetLogic() {
@Override
public String[] execute(String[] line) {
return null;
}
});
}
@Override
public int getNextSequenceValue() throws LiquibaseException {
if (lastChangeSetSequenceValue == null) {
lastChangeSetSequenceValue = 0;
try (
Reader reader = new InputStreamReader(new FileInputStream(this.changeLogFile), GlobalConfiguration.OUTPUT_FILE_ENCODING.getCurrentValue())
)
{
CSVReader csvReader = new CSVReader(reader);
String[] line = csvReader.readNext(); //skip header line
List<RanChangeSet> returnList = new ArrayList<>();
while ((line = csvReader.readNext()) != null) {
try {
lastChangeSetSequenceValue = Integer.valueOf(line[Columns.ORDEREXECUTED.ordinal()]);
} catch (NumberFormatException ignore) {
// ignore.
}
}
} catch (Exception ignore) {
// ignore
}
}
return ++lastChangeSetSequenceValue;
}
@Override
public void tag(final String tagString) throws DatabaseException {
RanChangeSet last = null;
List<RanChangeSet> ranChangeSets = getRanChangeSets();
if (ranChangeSets.isEmpty()) {
ChangeSet emptyChangeSet = new ChangeSet(String.valueOf(new Date().getTime()), "liquibase", false, false, "liquibase-internal", null, null, getDatabase().getObjectQuotingStrategy(), null);
appendChangeSet(emptyChangeSet, ExecType.EXECUTED);
last = new RanChangeSet(emptyChangeSet);
} else {
last = ranChangeSets.get(ranChangeSets.size() - 1);
}
ChangeSet lastChangeSet = new ChangeSet(last.getId(), last.getAuthor(), false, false, last.getChangeLog(), null, null, true, null, null);
replaceChangeSet(lastChangeSet, new ReplaceChangeSetLogic() {
@Override
public String[] execute(String[] line) {
line[Columns.TAG.ordinal()] = tagString;
return line;
}
});
}
@Override
public boolean tagExists(String tag) throws DatabaseException {
List<RanChangeSet> ranChangeSets = getRanChangeSets();
for (RanChangeSet changeset : ranChangeSets) {
if (tag.equals(changeset.getTag())) {
return true;
}
}
return false;
}
private interface ReplaceChangeSetLogic {
public String[] execute(String[] line);
}
@Override
public void clearAllCheckSums() throws LiquibaseException {
replaceChangeSet(null, new ReplaceChangeSetLogic() {
@Override
public String[] execute(String[] line) {
line[Columns.MD5SUM.ordinal()] = null;
return line;
}
});
}
@Override
public void destroy() throws DatabaseException {
if (changeLogFile.exists() && !changeLogFile.delete()) {
throw new DatabaseException("Could not delete changelog history file "+changeLogFile.getAbsolutePath());
}
}
}