Skip to content

Commit

Permalink
Implement a more complete changeset declaration
Browse files Browse the repository at this point in the history
  • Loading branch information
jhaber committed Aug 23, 2017
1 parent 49a952a commit fb688aa
Show file tree
Hide file tree
Showing 3 changed files with 75 additions and 41 deletions.
103 changes: 62 additions & 41 deletions src/main/java/com/refactify/Liquify.java
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
package com.refactify;

import java.io.FileOutputStream;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.lang.reflect.Field;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import com.refactify.arguments.ConversionArguments;
import com.refactify.arguments.ConversionArgumentsParser;
Expand All @@ -21,7 +24,6 @@
import liquibase.database.Database;
import liquibase.database.DatabaseFactory;
import liquibase.database.core.MySQLDatabase;
import liquibase.exception.LiquibaseException;
import liquibase.exception.MigrationFailedException;
import liquibase.exception.SetupException;
import liquibase.executor.Executor;
Expand All @@ -31,8 +33,6 @@
import liquibase.parser.ChangeLogParserFactory;
import liquibase.resource.FileSystemResourceAccessor;
import liquibase.resource.ResourceAccessor;
import liquibase.serializer.ChangeLogSerializer;
import liquibase.serializer.ChangeLogSerializerFactory;

public class Liquify {
private final static ConversionArgumentsParser parser = new ConversionArgumentsParser();
Expand All @@ -44,6 +44,11 @@ public static void main(final String[] args) {
if(conversionArguments.areValid()) {
String targetFileName = targetFileNameBuilder.buildFilename(conversionArguments);

if (!conversionArguments.getOverwrite() && new File(targetFileName).exists()) {
System.out.println("Target file " + targetFileName + " already exists, pass '--overwrite' to allow overwriting");
System.exit(1);
}

try (Writer writer = new FileWriter(targetFileName)) {
Executor realExecutor = ExecutorService.getInstance().getExecutor(mysql());
Executor loggingExecutor = new LoggingExecutor(realExecutor, new SqlFormattingWriter(writer), mysql());
Expand All @@ -68,11 +73,7 @@ private static void executeChangeLog(final ConversionArguments conversionArgumen
writer.write("--liquibase formatted sql\n\n");

for (ChangeSet changeSet : changeLog.getChangeSets()) {
String author = changeSet.getAuthor()
.replaceAll("\\s+", "_")
.replace("_(generated)","");

writer.write("--changeset " + author + ":" + changeSet.getId() + "\n");
writer.write(changeSetDeclaration(changeSet));
for (Change change : changeSet.getChanges()) {
try {
change.init();
Expand All @@ -87,31 +88,61 @@ private static void executeChangeLog(final ConversionArguments conversionArgumen
}
}

private static void convertDatabaseChangeLog(final ConversionArguments conversionArguments) {
String targetFileName = targetFileNameBuilder.buildFilename(conversionArguments);
try {
ResourceAccessor resourceAccessor = new FileSystemResourceAccessor(System.getProperty("user.dir"));
ChangeLogParser parser = ChangeLogParserFactory.getInstance().getParser(conversionArguments.getSource(), resourceAccessor);
DatabaseChangeLog changeLog = parser.parse(conversionArguments.getSource(), new ChangeLogParameters(), resourceAccessor);
ChangeLogSerializer serializer = ChangeLogSerializerFactory.getInstance().getSerializer(targetFileName);
for (ChangeSet set : changeLog.getChangeSets()) {
setFilePath(set, targetFileName);
}
serializer.write(changeLog.getChangeSets(), new FileOutputStream(targetFileName));
private static String changeSetDeclaration(ChangeSet changeSet) {
String author = changeSet.getAuthor()
.replaceAll("\\s+", "_")
.replace("_(generated)","");

List<String> parts = new ArrayList<>();
parts.add("--changeset");
parts.add(author + ":" + changeSet.getId());

if (changeSet.getContexts() != null && !changeSet.getContexts().isEmpty()) {
parts.add("context:" + join(changeSet.getContexts(), ","));
}

if (changeSet.getDbmsSet() != null && !changeSet.getDbmsSet().isEmpty()) {
parts.add("dbms:" + join(changeSet.getDbmsSet(), ","));
}

if (changeSet.isRunOnChange()) {
parts.add("runOnChange:true");
}

if (changeSet.isAlwaysRun()) {
parts.add("runAlways:true");
}

if (changeSet.getFailOnError() != null && !changeSet.getFailOnError()) {
parts.add("failOnError:false");
}

if (changeSet.getOnValidationFail() != ChangeSet.ValidationFailOption.HALT) {
parts.add("onValidationFail:" + changeSet.getOnValidationFail().name());
}
catch (LiquibaseException e) {
System.out.println("There was a problem parsing the source file.");
deleteTargetFile(targetFileName);

if (!changeSet.isRunInTransaction()) {
parts.add("runInTransaction:false");
}
catch (IOException e) {
System.out.println("There was a problem serializing the source file.");
deleteTargetFile(targetFileName);

return join(parts, " ") + "\n";
}

private static String join(Collection<String> strings, String separator) {
String joined = "";

Iterator<String> iterator = strings.iterator();
if (!iterator.hasNext()) {
return joined;
}
catch(IllegalStateException e) {
System.out.println(String.format("Database generator for type '%s' was not found.",
conversionArguments.getDatabase()));
deleteTargetFile(targetFileName);
joined += iterator.next();

while (iterator.hasNext()) {
joined += separator;
joined += iterator.next();
}

return joined;
}

private static void deleteTargetFile(final String targetFileName) {
Expand All @@ -123,16 +154,6 @@ private static void deleteTargetFile(final String targetFileName) {
}
}

private static void setFilePath(ChangeSet changeSet, String filePath) {
try {
Field f = ChangeSet.class.getDeclaredField("filePath");
f.setAccessible(true);
f.set(changeSet, filePath);
} catch (Exception e) {
throw new RuntimeException(e);
}
}

private static Database mysql() {
for (Database database : DatabaseFactory.getInstance().getImplementedDatabases()) {
if (database instanceof MySQLDatabase) {
Expand Down
10 changes: 10 additions & 0 deletions src/main/java/com/refactify/arguments/ConversionArguments.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ public class ConversionArguments {
private String source;
private ConversionType type;
private String database;
private boolean overwrite;
private static final String[] validFileExtensions = new String[] {".xml", ".yaml", ".json", ".sql"};
private static final String[] validDatabases =
new String[] {"db2", "derby", "firebird", "h2", "hsql", "informix", "mssql", "mariadb", "mysql", "oracle",
Expand Down Expand Up @@ -33,6 +34,14 @@ public void setDatabase(final String database) {
this.database = database;
}

public boolean getOverwrite() {
return overwrite;
}

public void setOverwrite(boolean overwrite) {
this.overwrite = overwrite;
}

public boolean areValid() {
return isValidPath(source) && hasValidType();
}
Expand Down Expand Up @@ -117,6 +126,7 @@ public String toString() {
sb.append("source='").append(source).append('\'');
sb.append(", type=").append(type);
sb.append(", database='").append(database).append('\'');
sb.append(", overwrite='").append(overwrite).append('\'');
sb.append('}');
return sb.toString();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@ else if (argument.equals("-db") || argument.equals("--database")) {
String value = arguments[++i];
conversionArguments.setDatabase(value);
}
else if (argument.equals("-overwrite") || argument.equals("--overwrite")) {
conversionArguments.setOverwrite(true);
}
}
}
catch (ArrayIndexOutOfBoundsException exc) {
Expand Down

0 comments on commit fb688aa

Please sign in to comment.