001package org.kualigan.tools.ant.tasks;
002
003import liquibase.integration.ant.*;
004import liquibase.Liquibase;
005import liquibase.util.ui.UIFactory;
006import org.apache.tools.ant.BuildException;
007
008import java.io.Writer;
009
010/**
011 * Ant task for migrating a database forward.
012 */
013public class DatabaseUpdateTask extends BaseLiquibaseTask {
014    private boolean dropFirst = false;
015
016    public boolean isDropFirst() {
017        return dropFirst;
018    }
019
020    public void setDropFirst(boolean dropFirst) {
021        this.dropFirst = dropFirst;
022    }
023
024    @Override
025    public void execute() throws BuildException {
026        if (!shouldRun()) {
027            return;
028        }
029
030        super.execute();
031
032        Liquibase liquibase = null;
033        try {
034            liquibase = createLiquibase();
035
036            if (isPromptOnNonLocalDatabase()
037                    && !liquibase.isSafeToRunMigration()
038                    && UIFactory.getInstance().getFacade().promptForNonLocalDatabase(liquibase.getDatabase())) {
039                throw new BuildException("Chose not to run against non-production database");
040            }
041
042            Writer writer = createOutputWriter();
043            if (writer == null) {
044                if (isDropFirst()) {
045                    liquibase.dropAll();
046                }
047
048                liquibase.update(getContexts());
049            } else {
050                if (isDropFirst()) {
051                    throw new BuildException("Cannot dropFirst when outputting update SQL");
052                }
053                liquibase.update(getContexts(), writer);
054                writer.flush();
055                writer.close();
056            }
057
058        } catch (Exception e) {
059            throw new BuildException(e);
060        } finally {
061            closeDatabase(liquibase);
062        }
063    }
064}