Search in sources :

Example 6 with DiffToChangeLog

use of liquibase.diff.output.changelog.DiffToChangeLog in project liquibase by liquibase.

the class H2IntegrationTest method diffToChangeLog.

// TODO: This test currently makes the whole VM exit with exit code -1, but does not generate a dump file
// (not a "genuine" VM crash). I need to disable this test until I can find out how to catch/debug this.
@Test
public void diffToChangeLog() throws Exception {
    if (getDatabase() == null) {
        return;
    }
    runCompleteChangeLog();
    DiffResult diffResult = DiffGeneratorFactory.getInstance().compare(getDatabase(), null, new CompareControl());
    File outputFile = new File("diffToChangeLog_" + getDatabase().getShortName() + ".log");
    if (outputFile.exists())
        outputFile.delete();
    PrintStream writer = new PrintStream(outputFile);
    new DiffToChangeLog(diffResult, new DiffOutputControl(true, true, true, null)).print(writer);
    writer.close();
}
Also used : PrintStream(java.io.PrintStream) CompareControl(liquibase.diff.compare.CompareControl) DiffOutputControl(liquibase.diff.output.DiffOutputControl) DiffToChangeLog(liquibase.diff.output.changelog.DiffToChangeLog) DiffResult(liquibase.diff.DiffResult) File(java.io.File) Test(org.junit.Test) AbstractIntegrationTest(liquibase.dbtest.AbstractIntegrationTest)

Example 7 with DiffToChangeLog

use of liquibase.diff.output.changelog.DiffToChangeLog in project liquibase by liquibase.

the class InternalGenerateChangelogCommandStep method run.

@Override
public void run(CommandResultsBuilder resultsBuilder) throws Exception {
    CommandScope commandScope = resultsBuilder.getCommandScope();
    outputBestPracticeMessage();
    String changeLogFile = StringUtil.trimToNull(commandScope.getArgumentValue(CHANGELOG_FILE_ARG));
    if (changeLogFile != null && changeLogFile.toLowerCase().endsWith(".sql")) {
        Scope.getCurrentScope().getUI().sendMessage("\n" + INFO_MESSAGE + "\n");
        Scope.getCurrentScope().getLog(getClass()).info("\n" + INFO_MESSAGE + "\n");
    }
    final Database referenceDatabase = commandScope.getArgumentValue(REFERENCE_DATABASE_ARG);
    InternalSnapshotCommandStep.logUnsupportedDatabase(referenceDatabase, this.getClass());
    DiffResult diffResult = createDiffResult(commandScope);
    DiffToChangeLog changeLogWriter = new DiffToChangeLog(diffResult, commandScope.getArgumentValue(DIFF_OUTPUT_CONTROL_ARG));
    changeLogWriter.setChangeSetAuthor(commandScope.getArgumentValue(AUTHOR_ARG));
    changeLogWriter.setChangeSetContext(commandScope.getArgumentValue(CONTEXT_ARG));
    changeLogWriter.setChangeSetPath(changeLogFile);
    ObjectQuotingStrategy originalStrategy = referenceDatabase.getObjectQuotingStrategy();
    try {
        referenceDatabase.setObjectQuotingStrategy(ObjectQuotingStrategy.QUOTE_ALL_OBJECTS);
        if (StringUtil.trimToNull(changeLogFile) != null) {
            changeLogWriter.print(changeLogFile);
        } else {
            PrintStream outputStream = new PrintStream(resultsBuilder.getOutputStream());
            try {
                changeLogWriter.print(outputStream);
            } finally {
                outputStream.flush();
            }
        }
        if (StringUtil.trimToNull(changeLogFile) != null) {
            Scope.getCurrentScope().getUI().sendMessage("Generated changelog written to " + new File(changeLogFile).getAbsolutePath());
        }
    } finally {
        referenceDatabase.setObjectQuotingStrategy(originalStrategy);
    }
}
Also used : PrintStream(java.io.PrintStream) Database(liquibase.database.Database) DiffToChangeLog(liquibase.diff.output.changelog.DiffToChangeLog) DiffResult(liquibase.diff.DiffResult) File(java.io.File) ObjectQuotingStrategy(liquibase.database.ObjectQuotingStrategy)

Example 8 with DiffToChangeLog

use of liquibase.diff.output.changelog.DiffToChangeLog in project liquibase by liquibase.

the class AbstractJdbcDatabase method dropDatabaseObjects.

@Override
public void dropDatabaseObjects(final CatalogAndSchema schemaToDrop) throws LiquibaseException {
    ObjectQuotingStrategy currentStrategy = this.getObjectQuotingStrategy();
    this.setObjectQuotingStrategy(ObjectQuotingStrategy.QUOTE_ALL_OBJECTS);
    try {
        DatabaseSnapshot snapshot;
        try {
            final SnapshotControl snapshotControl = new SnapshotControl(this);
            final Set<Class<? extends DatabaseObject>> typesToInclude = snapshotControl.getTypesToInclude();
            // We do not need to remove indexes and primary/unique keys explicitly. They should be removed
            // as part of tables.
            typesToInclude.remove(Index.class);
            typesToInclude.remove(PrimaryKey.class);
            typesToInclude.remove(UniqueConstraint.class);
            if (supportsForeignKeyDisable() || getShortName().equals("postgresql")) {
                // We do not remove ForeignKey because they will be disabled and removed as parts of tables.
                // Postgress is treated as if we can disable foreign keys because we can't drop
                // the foreign keys of a partitioned table, as discovered in
                // https://github.com/liquibase/liquibase/issues/1212
                typesToInclude.remove(ForeignKey.class);
            }
            final long createSnapshotStarted = System.currentTimeMillis();
            snapshot = SnapshotGeneratorFactory.getInstance().createSnapshot(schemaToDrop, this, snapshotControl);
            Scope.getCurrentScope().getLog(getClass()).fine(String.format("Database snapshot generated in %d ms. Snapshot includes: %s", System.currentTimeMillis() - createSnapshotStarted, typesToInclude));
        } catch (LiquibaseException e) {
            throw new UnexpectedLiquibaseException(e);
        }
        final long changeSetStarted = System.currentTimeMillis();
        CompareControl compareControl = new CompareControl(new CompareControl.SchemaComparison[] { new CompareControl.SchemaComparison(CatalogAndSchema.DEFAULT, schemaToDrop) }, snapshot.getSnapshotControl().getTypesToInclude());
        DiffResult diffResult = DiffGeneratorFactory.getInstance().compare(new EmptyDatabaseSnapshot(this), snapshot, compareControl);
        List<ChangeSet> changeSets = new DiffToChangeLog(diffResult, new DiffOutputControl(true, true, false, null).addIncludedSchema(schemaToDrop)).generateChangeSets();
        Scope.getCurrentScope().getLog(getClass()).fine(String.format("ChangeSet to Remove Database Objects generated in %d ms.", System.currentTimeMillis() - changeSetStarted));
        boolean previousAutoCommit = this.getAutoCommitMode();
        // clear out currently executed statements
        this.commit();
        // some DDL doesn't work in autocommit mode
        this.setAutoCommit(false);
        final boolean reEnableFK = supportsForeignKeyDisable() && disableForeignKeyChecks();
        try {
            for (ChangeSet changeSet : changeSets) {
                changeSet.setFailOnError(false);
                for (Change change : changeSet.getChanges()) {
                    if (change instanceof DropTableChange) {
                        ((DropTableChange) change).setCascadeConstraints(true);
                    }
                    SqlStatement[] sqlStatements = change.generateStatements(this);
                    for (SqlStatement statement : sqlStatements) {
                        Scope.getCurrentScope().getSingleton(ExecutorService.class).getExecutor("jdbc", this).execute(statement);
                    }
                }
                this.commit();
            }
        } finally {
            if (reEnableFK) {
                enableForeignKeyChecks();
            }
        }
        ChangeLogHistoryServiceFactory.getInstance().getChangeLogService(this).destroy();
        LockServiceFactory.getInstance().getLockService(this).destroy();
        this.setAutoCommit(previousAutoCommit);
        Scope.getCurrentScope().getLog(getClass()).info(String.format("Successfully deleted all supported object types in schema %s.", schemaToDrop.toString()));
    } finally {
        this.setObjectQuotingStrategy(currentStrategy);
        this.commit();
    }
}
Also used : DiffOutputControl(liquibase.diff.output.DiffOutputControl) DropTableChange(liquibase.change.core.DropTableChange) Change(liquibase.change.Change) SqlStatement(liquibase.statement.SqlStatement) EmptyDatabaseSnapshot(liquibase.snapshot.EmptyDatabaseSnapshot) DatabaseObject(liquibase.structure.DatabaseObject) CompareControl(liquibase.diff.compare.CompareControl) DiffToChangeLog(liquibase.diff.output.changelog.DiffToChangeLog) DropTableChange(liquibase.change.core.DropTableChange) UnexpectedLiquibaseException(liquibase.exception.UnexpectedLiquibaseException) LiquibaseException(liquibase.exception.LiquibaseException) DiffResult(liquibase.diff.DiffResult) DatabaseSnapshot(liquibase.snapshot.DatabaseSnapshot) EmptyDatabaseSnapshot(liquibase.snapshot.EmptyDatabaseSnapshot) SnapshotControl(liquibase.snapshot.SnapshotControl) UnexpectedLiquibaseException(liquibase.exception.UnexpectedLiquibaseException) RanChangeSet(liquibase.changelog.RanChangeSet) ChangeSet(liquibase.changelog.ChangeSet)

Example 9 with DiffToChangeLog

use of liquibase.diff.output.changelog.DiffToChangeLog in project liquibase by liquibase.

the class AbstractIntegrationTest method generateChangeLog_noChanges.

@Test
public void generateChangeLog_noChanges() throws Exception {
    if (database == null) {
        return;
    }
    runCompleteChangeLog();
    DiffResult diffResult = DiffGeneratorFactory.getInstance().compare(database, database, new CompareControl());
    DiffToChangeLog changeLogWriter = new DiffToChangeLog(diffResult, new DiffOutputControl(false, false, false, null));
    List<ChangeSet> changeSets = changeLogWriter.generateChangeSets();
    assertEquals(0, changeSets.size());
}
Also used : CompareControl(liquibase.diff.compare.CompareControl) DiffOutputControl(liquibase.diff.output.DiffOutputControl) DiffToChangeLog(liquibase.diff.output.changelog.DiffToChangeLog) DiffResult(liquibase.diff.DiffResult) ChangeSet(liquibase.changelog.ChangeSet) Test(org.junit.Test)

Example 10 with DiffToChangeLog

use of liquibase.diff.output.changelog.DiffToChangeLog in project liquibase by liquibase.

the class DiffDatabaseToChangeLogTask method executeWithLiquibaseClassloader.

@Override
protected void executeWithLiquibaseClassloader() throws BuildException {
    for (ChangeLogOutputFile changeLogOutputFile : changeLogOutputFiles) {
        PrintStream printStream = null;
        String encoding = getOutputEncoding(changeLogOutputFile);
        try {
            FileResource outputFile = changeLogOutputFile.getOutputFile();
            ChangeLogSerializer changeLogSerializer = changeLogOutputFile.getChangeLogSerializer();
            printStream = new PrintStream(outputFile.getOutputStream(), true, encoding);
            DiffResult diffResult = getDiffResult();
            DiffOutputControl diffOutputControl = getDiffOutputControl();
            DiffToChangeLog diffToChangeLog = new DiffToChangeLog(diffResult, diffOutputControl);
            diffToChangeLog.print(printStream, changeLogSerializer);
        } catch (UnsupportedEncodingException e) {
            throw new BuildException("Unable to diff databases to change log file. Encoding [" + encoding + "] is not supported.", e);
        } catch (IOException e) {
            throw new BuildException("Unable to diff databases to change log file. Error creating output stream.", e);
        } catch (ParserConfigurationException e) {
            throw new BuildException("Unable to diff databases to change log file. Error configuring parser.", e);
        } catch (DatabaseException e) {
            throw new BuildException("Unable to diff databases to change log file: " + e.getMessage(), e);
        } finally {
            FileUtils.close(printStream);
        }
    }
}
Also used : PrintStream(java.io.PrintStream) FileResource(org.apache.tools.ant.types.resources.FileResource) DiffOutputControl(liquibase.diff.output.DiffOutputControl) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ChangeLogSerializer(liquibase.serializer.ChangeLogSerializer) JsonChangeLogSerializer(liquibase.serializer.core.json.JsonChangeLogSerializer) StringChangeLogSerializer(liquibase.serializer.core.string.StringChangeLogSerializer) IOException(java.io.IOException) ChangeLogOutputFile(liquibase.integration.ant.type.ChangeLogOutputFile) DiffToChangeLog(liquibase.diff.output.changelog.DiffToChangeLog) DiffResult(liquibase.diff.DiffResult) BuildException(org.apache.tools.ant.BuildException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) DatabaseException(liquibase.exception.DatabaseException)

Aggregations

DiffToChangeLog (liquibase.diff.output.changelog.DiffToChangeLog)14 DiffOutputControl (liquibase.diff.output.DiffOutputControl)13 DiffResult (liquibase.diff.DiffResult)11 CompareControl (liquibase.diff.compare.CompareControl)9 ChangeSet (liquibase.changelog.ChangeSet)7 Test (org.junit.Test)7 PrintStream (java.io.PrintStream)6 Database (liquibase.database.Database)5 SnapshotControl (liquibase.snapshot.SnapshotControl)4 File (java.io.File)3 Liquibase (liquibase.Liquibase)3 AbstractIntegrationTest (liquibase.dbtest.AbstractIntegrationTest)3 DatabaseException (liquibase.exception.DatabaseException)3 ValidationFailedException (liquibase.exception.ValidationFailedException)3 DatabaseSnapshot (liquibase.snapshot.DatabaseSnapshot)3 IOException (java.io.IOException)2 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)2 CatalogAndSchema (liquibase.CatalogAndSchema)2 Contexts (liquibase.Contexts)2