1 package org.liquibase.maven.plugins;
2
3 import java.io.File;
4 import java.io.FileWriter;
5 import java.io.IOException;
6 import java.io.Writer;
7 import java.text.DateFormat;
8 import java.text.ParseException;
9 import java.text.SimpleDateFormat;
10
11 import liquibase.Liquibase;
12 import liquibase.database.Database;
13 import liquibase.exception.LiquibaseException;
14 import liquibase.resource.ResourceAccessor;
15
16 import org.apache.maven.plugin.MojoExecutionException;
17
18
19
20
21
22
23
24
25
26 public class LiquibaseRollbackSQL extends LiquibaseRollback {
27
28
29
30
31
32
33
34 protected File migrationSqlOutputFile;
35
36
37 private Writer outputWriter;
38
39 @Override
40 protected boolean isPromptOnNonLocalDatabase() {
41
42
43 return false;
44 }
45
46 @Override
47 protected Liquibase createLiquibase(ResourceAccessor fo, Database db) throws MojoExecutionException {
48 Liquibase liquibase = super.createLiquibase(fo, db);
49
50
51 try {
52 if (!migrationSqlOutputFile.exists()) {
53
54 migrationSqlOutputFile.getParentFile().mkdirs();
55
56 if (!migrationSqlOutputFile.createNewFile()) {
57 throw new MojoExecutionException("Cannot create the migration SQL file; "
58 + migrationSqlOutputFile.getAbsolutePath());
59 }
60 }
61 outputWriter = new FileWriter(migrationSqlOutputFile);
62 } catch (IOException e) {
63 getLog().error(e);
64 throw new MojoExecutionException("Failed to create SQL output writer", e);
65 }
66 getLog().info("Output SQL Migration File: " + migrationSqlOutputFile.getAbsolutePath());
67 return liquibase;
68 }
69
70 @Override
71 protected void printSettings(String indent) {
72 super.printSettings(indent);
73 getLog().info(indent + "migrationSQLOutputFile: " + migrationSqlOutputFile);
74 }
75
76 @Override
77 protected void cleanup(Database db) {
78 super.cleanup(db);
79 if (outputWriter != null) {
80 try {
81 outputWriter.close();
82 } catch (IOException e) {
83 getLog().error(e);
84 }
85 }
86 }
87
88 @Override
89 protected void performLiquibaseTask(Liquibase liquibase) throws LiquibaseException {
90 switch (type) {
91 case COUNT: {
92 liquibase.rollback(rollbackCount, contexts, outputWriter);
93 break;
94 }
95 case DATE: {
96 DateFormat format = DateFormat.getDateInstance();
97 try {
98 liquibase.rollback(format.parse(rollbackDate), contexts, outputWriter);
99 } catch (ParseException e) {
100 String message = "Error parsing rollbackDate: " + e.getMessage();
101 if (format instanceof SimpleDateFormat) {
102 message += "\nDate must match pattern: " + ((SimpleDateFormat) format).toPattern();
103 }
104 throw new LiquibaseException(message, e);
105 }
106 break;
107 }
108 case TAG: {
109 liquibase.rollback(rollbackTag, contexts, outputWriter);
110 break;
111 }
112 default: {
113 throw new IllegalStateException("Unexpected rollback type, " + type);
114 }
115 }
116 }
117 }