-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
SpringLiquibase.java
678 lines (584 loc) · 23.3 KB
/
SpringLiquibase.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
package liquibase.integration.spring;
import liquibase.Contexts;
import liquibase.LabelExpression;
import liquibase.Liquibase;
import liquibase.configuration.ConfigurationProperty;
import liquibase.configuration.GlobalConfiguration;
import liquibase.configuration.LiquibaseConfiguration;
import liquibase.database.Database;
import liquibase.database.DatabaseConnection;
import liquibase.database.DatabaseFactory;
import liquibase.database.OfflineConnection;
import liquibase.database.jvm.JdbcConnection;
import liquibase.exception.DatabaseException;
import liquibase.exception.LiquibaseException;
import liquibase.logging.LogService;
import liquibase.logging.LogType;
import liquibase.logging.Logger;
import liquibase.resource.ClassLoaderResourceAccessor;
import liquibase.resource.ResourceAccessor;
import liquibase.util.StringUtils;
import liquibase.util.file.FilenameUtils;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.ResourcePatternUtils;
import javax.sql.DataSource;
import java.io.*;
import java.net.URLConnection;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.jar.Attributes;
import java.util.jar.Manifest;
/**
* A Spring-ified wrapper for Liquibase.
* <p/>
* Example Configuration:
* <p/>
* <p/>
* This Spring configuration example will cause liquibase to run automatically when the Spring context is
* initialized. It will load <code>db-changelog.xml</code> from the classpath and apply it against
* <code>myDataSource</code>.
* <p/>
* <p/>
*
* <pre>
* <bean id="myLiquibase"
* class="liquibase.spring.SpringLiquibase"
* >
*
* <property name="dataSource" ref="myDataSource" />
*
* <property name="changeLog" value="classpath:db-changelog.xml" />
*
* </bean>
*
* </pre>
*
* @author Rob Schoening
*/
public class SpringLiquibase implements InitializingBean, BeanNameAware, ResourceLoaderAware {
protected final Logger log = LogService.getLog(SpringLiquibase.class);
protected String beanName;
protected ResourceLoader resourceLoader;
protected DataSource dataSource;
protected String changeLog;
protected String contexts;
protected String labels;
protected String tag;
protected Map<String, String> parameters;
protected String defaultSchema;
protected String liquibaseSchema;
protected String databaseChangeLogTable;
protected String databaseChangeLogLockTable;
protected String liquibaseTablespace;
protected boolean dropFirst;
protected boolean clearCheckSums;
protected boolean shouldRun = true;
protected File rollbackFile;
/**
* Ignores classpath prefix during changeset comparison.
* This is particularly useful if Liquibase is run in different ways.
*
* For instance, if Maven plugin is used to run changesets, as in:
* <code>
* <configuration>
* ...
* <changeLogFile>path/to/changelog</changeLogFile>
* </configuration>
* </code>
*
* And {@link SpringLiquibase} is configured like:
* <code>
* SpringLiquibase springLiquibase = new SpringLiquibase();
* springLiquibase.setChangeLog("classpath:path/to/changelog");
* </code>
*
* or, in equivalent XML configuration:
* <code>
* <bean id="springLiquibase" class="liquibase.integration.spring.SpringLiquibase">
* <property name="changeLog" value="path/to/changelog" />
* </bean>
* </code>
*
* {@link Liquibase#listUnrunChangeSets(Contexts, )} will
* always, by default, return changesets, regardless of their
* execution by Maven.
* Maven-executed changeset path name are not be prepended by
* "classpath:" whereas the ones parsed via SpringLiquibase are.
*
* To avoid this issue, just set ignoreClasspathPrefix to true.
*/
private boolean ignoreClasspathPrefix = true;
protected boolean testRollbackOnUpdate = false;
public SpringLiquibase() {
super();
}
public boolean isDropFirst() {
return dropFirst;
}
public void setDropFirst(boolean dropFirst) {
this.dropFirst = dropFirst;
}
public boolean isClearCheckSums() {
return clearCheckSums;
}
public void setClearCheckSums(boolean clearCheckSums) {
this.clearCheckSums = clearCheckSums;
}
public void setShouldRun(boolean shouldRun) {
this.shouldRun = shouldRun;
}
public String getDatabaseProductName() throws DatabaseException {
Connection connection = null;
Database database = null;
String name = "unknown";
try {
connection = getDataSource().getConnection();
database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(new JdbcConnection(connection));
name = database.getDatabaseProductName();
} catch (SQLException e) {
throw new DatabaseException(e);
} finally {
if (database != null) {
database.close();
} else if (connection != null) {
try {
if (!connection.getAutoCommit()) {
connection.rollback();
}
connection.close();
} catch (SQLException e) {
log.warning(LogType.LOG, "problem closing connection", e);
}
}
}
return name;
}
/**
* The DataSource that liquibase will use to perform the migration.
*/
public DataSource getDataSource() {
return dataSource;
}
/**
* The DataSource that liquibase will use to perform the migration.
*/
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
/**
* Returns a Resource that is able to resolve to a file or classpath resource.
*/
public String getChangeLog() {
return changeLog;
}
/**
* Sets a Spring Resource that is able to resolve to a file or classpath resource.
* An example might be <code>classpath:db-changelog.xml</code>.
*/
public void setChangeLog(String dataModel) {
this.changeLog = dataModel;
}
public String getContexts() {
return contexts;
}
public void setContexts(String contexts) {
this.contexts = contexts;
}
public String getLabels() {
return labels;
}
public void setLabels(String labels) {
this.labels = labels;
}
public String getTag() {
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
public String getDefaultSchema() {
return defaultSchema;
}
public void setDefaultSchema(String defaultSchema) {
this.defaultSchema = defaultSchema;
}
public String getLiquibaseTablespace() {
return liquibaseTablespace;
}
public void setLiquibaseTablespace(String liquibaseTablespace) {
this.liquibaseTablespace = liquibaseTablespace;
}
public String getLiquibaseSchema() {
return liquibaseSchema;
}
public void setLiquibaseSchema(String liquibaseSchema) {
this.liquibaseSchema = liquibaseSchema;
}
public String getDatabaseChangeLogTable() {
return databaseChangeLogTable;
}
public void setDatabaseChangeLogTable(String databaseChangeLogTable) {
this.databaseChangeLogTable = databaseChangeLogTable;
}
public String getDatabaseChangeLogLockTable() {
return databaseChangeLogLockTable;
}
public void setDatabaseChangeLogLockTable(String databaseChangeLogLockTable) {
this.databaseChangeLogLockTable = databaseChangeLogLockTable;
}
/**
* Returns whether a rollback should be tested at update time or not.
*/
public boolean isTestRollbackOnUpdate() {
return testRollbackOnUpdate;
}
/**
* If testRollbackOnUpdate is set to true a rollback will be tested at tupdate time.
* For doing so when the update is performed
* @param testRollbackOnUpdate
*/
public void setTestRollbackOnUpdate(boolean testRollbackOnUpdate) {
this.testRollbackOnUpdate = testRollbackOnUpdate;
}
/**
* Executed automatically when the bean is initialized.
*/
@Override
public void afterPropertiesSet() throws LiquibaseException {
ConfigurationProperty shouldRunProperty = LiquibaseConfiguration.getInstance()
.getProperty(GlobalConfiguration.class, GlobalConfiguration.SHOULD_RUN);
if (!shouldRunProperty.getValue(Boolean.class)) {
LogService.getLog(getClass()).info(LogType.LOG, "Liquibase did not run because " + LiquibaseConfiguration
.getInstance().describeValueLookupLogic(shouldRunProperty) + " was set to false");
return;
}
if (!shouldRun) {
LogService.getLog(getClass()).info(LogType.LOG, "Liquibase did not run because 'shouldRun' " + "property was set " +
"to false on " + getBeanName() + " Liquibase Spring bean.");
return;
}
Connection c = null;
Liquibase liquibase = null;
try {
c = getDataSource().getConnection();
liquibase = createLiquibase(c);
generateRollbackFile(liquibase);
performUpdate(liquibase);
} catch (SQLException e) {
throw new DatabaseException(e);
} finally {
Database database = null;
if (liquibase != null) {
database = liquibase.getDatabase();
}
if (database != null) {
database.close();
}
}
}
private void generateRollbackFile(Liquibase liquibase) throws LiquibaseException {
if (rollbackFile != null) {
try (
FileOutputStream fileOutputStream = new FileOutputStream(rollbackFile);
Writer output = new OutputStreamWriter(fileOutputStream, LiquibaseConfiguration.getInstance()
.getConfiguration(GlobalConfiguration.class).getOutputEncoding())
) {
if (tag != null) {
liquibase.futureRollbackSQL(tag, new Contexts(getContexts()),
new LabelExpression(getLabels()), output);
} else {
liquibase.futureRollbackSQL(new Contexts(getContexts()), new LabelExpression(getLabels()), output);
}
} catch (IOException e) {
throw new LiquibaseException("Unable to generate rollback file.", e);
}
}
}
protected void performUpdate(Liquibase liquibase) throws LiquibaseException {
if (isClearCheckSums()) {
liquibase.clearCheckSums();
}
if (isTestRollbackOnUpdate()) {
if (tag != null) {
liquibase.updateTestingRollback(tag, new Contexts(getContexts()), new LabelExpression(getLabels()));
} else {
liquibase.updateTestingRollback(new Contexts(getContexts()), new LabelExpression(getLabels()));
}
} else {
if (tag != null) {
liquibase.update(tag, new Contexts(getContexts()), new LabelExpression(getLabels()));
} else {
liquibase.update(new Contexts(getContexts()), new LabelExpression(getLabels()));
}
}
}
protected Liquibase createLiquibase(Connection c) throws LiquibaseException {
ResourceAccessor resourceAccessor = createResourceOpener();
Liquibase liquibase = new Liquibase(getChangeLog(), resourceAccessor, createDatabase(c, resourceAccessor));
liquibase.setIgnoreClasspathPrefix(isIgnoreClasspathPrefix());
if (parameters != null) {
for (Map.Entry<String, String> entry : parameters.entrySet()) {
liquibase.setChangeLogParameter(entry.getKey(), entry.getValue());
}
}
if (isDropFirst()) {
liquibase.dropAll();
}
return liquibase;
}
/**
* Subclasses may override this method add change some database settings such as
* default schema before returning the database object.
*
* @param c
* @return a Database implementation retrieved from the {@link DatabaseFactory}.
* @throws DatabaseException
*/
protected Database createDatabase(Connection c, ResourceAccessor resourceAccessor) throws DatabaseException {
DatabaseConnection liquibaseConnection;
if (c == null) {
log.warning(LogType.LOG,
"Null connection returned by liquibase datasource. Using offline unknown database");
liquibaseConnection = new OfflineConnection("offline:unknown", resourceAccessor);
} else {
liquibaseConnection = new JdbcConnection(c);
}
Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(liquibaseConnection);
if (StringUtils.trimToNull(this.defaultSchema) != null) {
if (database.supportsSchemas()) {
database.setDefaultSchemaName(this.defaultSchema);
} else if (database.supportsCatalogs()) {
database.setDefaultCatalogName(this.defaultSchema);
}
}
if (StringUtils.trimToNull(this.liquibaseSchema) != null) {
if (database.supportsSchemas()) {
database.setLiquibaseSchemaName(this.liquibaseSchema);
} else if (database.supportsCatalogs()) {
database.setLiquibaseCatalogName(this.liquibaseSchema);
}
}
if (StringUtils.trimToNull(this.liquibaseTablespace) != null && database.supportsTablespaces()) {
database.setLiquibaseTablespaceName(this.liquibaseTablespace);
}
if (StringUtils.trimToNull(this.databaseChangeLogTable) != null) {
database.setDatabaseChangeLogTableName(this.databaseChangeLogTable);
}
if (StringUtils.trimToNull(this.databaseChangeLogLockTable) != null) {
database.setDatabaseChangeLogLockTableName(this.databaseChangeLogLockTable);
}
return database;
}
public void setChangeLogParameters(Map<String, String> parameters) {
this.parameters = parameters;
}
/**
* Create a new resourceOpener.
*/
protected ResourceAccessor createResourceOpener() {
return new SpringResourceOpener(getChangeLog());
}
/**
* Gets the Spring-name of this instance.
*
* @return
*/
public String getBeanName() {
return beanName;
}
/**
* Spring sets this automatically to the instance's configured bean name.
*/
@Override
public void setBeanName(String name) {
this.beanName = name;
}
public ResourceLoader getResourceLoader() {
return resourceLoader;
}
@Override
public void setResourceLoader(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
}
public void setRollbackFile(File rollbackFile) {
this.rollbackFile = rollbackFile;
}
public boolean isIgnoreClasspathPrefix() {
return ignoreClasspathPrefix;
}
public void setIgnoreClasspathPrefix(boolean ignoreClasspathPrefix) {
this.ignoreClasspathPrefix = ignoreClasspathPrefix;
}
@Override
public String toString() {
return getClass().getName() + "(" + this.getResourceLoader().toString() + ")";
}
public class SpringResourceOpener extends ClassLoaderResourceAccessor {
private String parentFile;
public SpringResourceOpener(String parentFile) {
this.parentFile = parentFile;
}
@Override
protected void init() {
super.init();
try {
Resource[] resources = getResources("");
if ((resources.length != 0) && ((resources.length != 1) || resources[0].exists())) {
for (Resource res : resources) {
addRootPath(res.getURL());
}
return;
}
//sometimes not able to look up by empty string, try all the liquibase packages
Set<String> liquibasePackages = new HashSet<>();
for (Resource manifest : getResources("META-INF/MANIFEST.MF")) {
liquibasePackages.addAll(getPackagesFromManifest(manifest));
}
if (liquibasePackages.isEmpty()) {
LogService.getLog(getClass()).warning(LogType.LOG,
"No Liquibase-Packages entry found in MANIFEST.MF. " +
"Using fallback of entire 'liquibase' package");
liquibasePackages.add("liquibase");
}
for (String foundPackage : liquibasePackages) {
for (Resource res : getResources(foundPackage)) {
if (res.exists()) {
addRootPath(res.getURL());
} else {
LogService.getLog(getClass()).warning(LogType.LOG,
"Resource does not exist: " +
res.getDescription());
}
}
}
} catch (IOException e) {
LogService.getLog(getClass()).warning(LogType.LOG, "Error initializing SpringLiquibase", e);
}
}
@Override
public Set<String> list(String relativeTo, String path, boolean includeFiles, boolean includeDirectories,
boolean recursive) throws IOException {
if (path == null) {
return null;
}
//
// Possible Resources Types
//
// Standalone Jar
// Root Path: jar:file:/Projects/my-project/second-module/target/second-module-1.0.0-SNAPSHOT-exec.jar!/BOOT-INF/lib/first-module-1.0.0-SNAPSHOT.jar!/
// +Resource: jar:file:/Projects/my-project/second-module/target/second-module-1.0.0-SNAPSHOT-exec.jar!/BOOT-INF/lib/first-module-1.0.0-SNAPSHOT.jar!/db/changelog/0-initial-schema.xml
// Standalone War
// Root Path: jar:file:/Projects/my-project/second-module/target/second-module-1.0.0-SNAPSHOT-exec.war!/WEB-INF/lib/first-module-1.0.0-SNAPSHOT.jar!/
// +Resource: jar:file:/Projects/my-project/second-module/target/second-module-1.0.0-SNAPSHOT-exec.war!/WEB-INF/lib/first-module-1.0.0-SNAPSHOT.jar!/-db/changelog/0-initial-schema.xml
// Openned Jar Dependency
// Root Path: file:/Projects/my-project/first-module/target/classes/
// +Resource: file:/Projects/my-project/first-module/target/classes/db/changelog/0-initial-schema.xml
// War Wild-Fly Exploded
// Root Path: vfs:/Projects/my-project/second-module/target/second-module-1.0.0-SNAPSHOT/WEB-INF/lib/first-module-1.0.0-SNAPSHOT.jar/
// +Resource: vfs:/Projects/my-project/second-module/target/second-module-1.0.0-SNAPSHOT/WEB-INF/lib/first-module-1.0.0-SNAPSHOT.jar/db/changelog/0-initial-schema.xml
// War Wild-Fly Artifact
// Root Path: vfs:/content/second-module-1.0.0-SNAPSHOT.war/WEB-INF/lib/first-module-1.0.0-SNAPSHOT.jar/
// +Resource: vfs:/content/second-module-1.0.0-SNAPSHOT.war/WEB-INF/lib/first-module-1.0.0-SNAPSHOT.jar/db/changelog/0-initial-schema.xml
Set<String> returnSet = new HashSet<>();
path = path + (recursive ? "**" : '*'); // All files inside!
String tempFile = FilenameUtils.concat(FilenameUtils.getFullPath(relativeTo), path);
Resource[] resources = getResources(adjustClasspath(tempFile));
for (Resource resource : resources) {
String resourceStr = resource.getURL().toExternalForm();
String resourcePath = convertToPath(resourceStr);
if (resourceStr.endsWith(resourcePath) && !resourceStr.equals(resourcePath)) {
returnSet.add(resourcePath);
} else {
// Closed Jar Dependency
// Root Path: file:/.m2/repository/org/liquibase/test/first-module/1.0.0-SNAPSHOT/first-module-1.0.0-SNAPSHOT.jar/
// +Resource: jar:file:/.m2/repository/org/liquibase/test/first-module/1.0.0-SNAPSHOT/first-module-1.0.0-SNAPSHOT.jar!/db/changelog/0-initial-schema.xml
String newResourceStr = resource.getURL().getFile(); // Remove "jar:" from begining.
newResourceStr = newResourceStr.replaceAll("!", "");
String newResourcePath = convertToPath(newResourceStr);
if (newResourceStr.endsWith(newResourcePath) && !newResourceStr.equals(newResourcePath)) {
returnSet.add(newResourcePath);
} else {
LogService.getLog(getClass()).warning(
LogType.LOG, "Not a valid resource entry: " + resourceStr);
}
}
}
return returnSet;
}
@Override
public Set<InputStream> getResourcesAsStream(String path) throws IOException {
if (path == null) {
return null;
}
Resource[] resources = getResources(adjustClasspath(path));
if ((resources == null) || (resources.length == 0)) {
return null;
}
Set<InputStream> returnSet = new HashSet<>();
for (Resource resource : resources) {
LogService.getLog(getClass()).debug(LogType.LOG, "Opening "
+ resource.getURL().toExternalForm() + " as " + path);
URLConnection connection = resource.getURL().openConnection();
connection.setUseCaches(false);
returnSet.add(connection.getInputStream());
}
return returnSet;
}
public Resource getResource(String file) {
return getResourceLoader().getResource(adjustClasspath(file));
}
private String adjustClasspath(String file) {
if (file == null) {
return null;
}
return (isPrefixPresent(parentFile) && !isPrefixPresent(file)) ? (ResourceLoader.CLASSPATH_URL_PREFIX +
file) : file;
}
private Resource[] getResources(String foundPackage) throws IOException {
return ResourcePatternUtils.getResourcePatternResolver(getResourceLoader()).getResources(foundPackage);
}
private Set<String> getPackagesFromManifest(Resource manifest) throws IOException {
Set<String> manifestPackages = new HashSet<>();
if (!manifest.exists()) {
return manifestPackages;
}
InputStream inputStream = null;
try {
inputStream = manifest.getInputStream();
Manifest manifestObj = new Manifest(inputStream);
Attributes attributes = manifestObj.getAttributes("Liquibase-Package");
if (attributes == null) {
return manifestPackages;
}
for (Object attr : attributes.values()) {
String packages = "\\s*,\\s*";
for (String fullPackage : attr.toString().split(packages)) {
manifestPackages.add(fullPackage.split("\\.")[0]);
}
}
} finally {
if (inputStream != null) {
inputStream.close();
}
}
return manifestPackages;
}
public boolean isPrefixPresent(String file) {
if (file == null) {
return false;
}
return file.startsWith("classpath") || file.startsWith("file:") || file.startsWith("url:");
}
@Override
public ClassLoader toClassLoader() {
return getResourceLoader().getClassLoader();
}
}
}