Search in sources :

Example 1 with SnapshotControl

use of liquibase.snapshot.SnapshotControl in project liquibase by liquibase.

the class AbstractJdbcDatabase method dropDatabaseObjects.

// ------- DATABASE OBJECT DROPPING METHODS ---- //
/**
     * Drops all objects owned by the connected user.
     */
@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()) {
                //We do not remove ForeignKey because they will be disabled and removed as parts of tables.
                typesToInclude.remove(ForeignKey.class);
            }
            final long createSnapshotStarted = System.currentTimeMillis();
            snapshot = SnapshotGeneratorFactory.getInstance().createSnapshot(schemaToDrop, this, snapshotControl);
            LogFactory.getLogger().debug(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();
        DiffResult diffResult = DiffGeneratorFactory.getInstance().compare(new EmptyDatabaseSnapshot(this), snapshot, new CompareControl(snapshot.getSnapshotControl().getTypesToInclude()));
        List<ChangeSet> changeSets = new DiffToChangeLog(diffResult, new DiffOutputControl(true, true, false, null).addIncludedSchema(schemaToDrop)).generateChangeSets();
        LogFactory.getLogger().debug(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) {
                        ExecutorService.getInstance().getExecutor(this).execute(statement);
                    }
                }
                this.commit();
            }
        } finally {
            if (reEnableFK) {
                enableForeignKeyChecks();
            }
        }
        ChangeLogHistoryServiceFactory.getInstance().getChangeLogService(this).destroy();
        LockServiceFactory.getInstance().getLockService(this).destroy();
        this.setAutoCommit(previousAutoCommit);
    } finally {
        this.setObjectQuotingStrategy(currentStrategy);
        this.commit();
    }
}
Also used : DiffOutputControl(liquibase.diff.output.DiffOutputControl) Change(liquibase.change.Change) DropTableChange(liquibase.change.core.DropTableChange) 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) DiffResult(liquibase.diff.DiffResult) DatabaseSnapshot(liquibase.snapshot.DatabaseSnapshot) EmptyDatabaseSnapshot(liquibase.snapshot.EmptyDatabaseSnapshot) SnapshotControl(liquibase.snapshot.SnapshotControl)

Example 2 with SnapshotControl

use of liquibase.snapshot.SnapshotControl in project liquibase by liquibase.

the class AbstractDatabaseDiffTask method getDiffResult.

protected DiffResult getDiffResult() {
    Liquibase liquibase = getLiquibase();
    Database targetDatabase = liquibase.getDatabase();
    Database referenceDatabase = createDatabaseFromType(referenceDatabaseType);
    CatalogAndSchema targetCatalogAndSchema = buildCatalogAndSchema(targetDatabase);
    CatalogAndSchema referenceCatalogAndSchema = buildCatalogAndSchema(referenceDatabase);
    CompareControl.SchemaComparison[] schemaComparisons = { new CompareControl.SchemaComparison(referenceCatalogAndSchema, targetCatalogAndSchema) };
    SnapshotGeneratorFactory snapshotGeneratorFactory = SnapshotGeneratorFactory.getInstance();
    DatabaseSnapshot referenceSnapshot;
    try {
        referenceSnapshot = snapshotGeneratorFactory.createSnapshot(referenceDatabase.getDefaultSchema(), referenceDatabase, new SnapshotControl(referenceDatabase, diffTypes));
    } catch (LiquibaseException e) {
        throw new BuildException("Unable to create a DatabaseSnapshot. " + e.toString(), e);
    }
    CompareControl compareControl = new CompareControl(schemaComparisons, referenceSnapshot.getSnapshotControl().getTypesToInclude());
    try {
        return liquibase.diff(referenceDatabase, targetDatabase, compareControl);
    } catch (LiquibaseException e) {
        throw new BuildException("Unable to diff databases. " + e.toString(), e);
    }
}
Also used : Liquibase(liquibase.Liquibase) Database(liquibase.database.Database) CompareControl(liquibase.diff.compare.CompareControl) SnapshotGeneratorFactory(liquibase.snapshot.SnapshotGeneratorFactory) LiquibaseException(liquibase.exception.LiquibaseException) BuildException(org.apache.tools.ant.BuildException) CatalogAndSchema(liquibase.CatalogAndSchema) DatabaseSnapshot(liquibase.snapshot.DatabaseSnapshot) SnapshotControl(liquibase.snapshot.SnapshotControl)

Example 3 with SnapshotControl

use of liquibase.snapshot.SnapshotControl in project liquibase by liquibase.

the class Liquibase method generateChangeLog.

public void generateChangeLog(CatalogAndSchema catalogAndSchema, DiffToChangeLog changeLogWriter, PrintStream outputStream, ChangeLogSerializer changeLogSerializer, Class<? extends DatabaseObject>... snapshotTypes) throws DatabaseException, IOException, ParserConfigurationException {
    Set<Class<? extends DatabaseObject>> finalCompareTypes = null;
    if (snapshotTypes != null && snapshotTypes.length > 0) {
        finalCompareTypes = new HashSet<Class<? extends DatabaseObject>>(Arrays.asList(snapshotTypes));
    }
    SnapshotControl snapshotControl = new SnapshotControl(this.getDatabase(), snapshotTypes);
    CompareControl compareControl = new CompareControl(new CompareControl.SchemaComparison[] { new CompareControl.SchemaComparison(catalogAndSchema, catalogAndSchema) }, finalCompareTypes);
    //        compareControl.addStatusListener(new OutDiffStatusListener());
    DatabaseSnapshot originalDatabaseSnapshot = null;
    try {
        originalDatabaseSnapshot = SnapshotGeneratorFactory.getInstance().createSnapshot(compareControl.getSchemas(CompareControl.DatabaseRole.REFERENCE), getDatabase(), snapshotControl);
        DiffResult diffResult = DiffGeneratorFactory.getInstance().compare(originalDatabaseSnapshot, SnapshotGeneratorFactory.getInstance().createSnapshot(compareControl.getSchemas(CompareControl.DatabaseRole.REFERENCE), null, snapshotControl), compareControl);
        changeLogWriter.setDiffResult(diffResult);
        if (changeLogSerializer != null) {
            changeLogWriter.print(outputStream, changeLogSerializer);
        } else {
            changeLogWriter.print(outputStream);
        }
    } catch (InvalidExampleException e) {
        throw new UnexpectedLiquibaseException(e);
    }
}
Also used : InvalidExampleException(liquibase.snapshot.InvalidExampleException) DatabaseObject(liquibase.structure.DatabaseObject) CompareControl(liquibase.diff.compare.CompareControl) DiffResult(liquibase.diff.DiffResult) SnapshotControl(liquibase.snapshot.SnapshotControl) DatabaseSnapshot(liquibase.snapshot.DatabaseSnapshot) UnexpectedLiquibaseException(liquibase.exception.UnexpectedLiquibaseException)

Example 4 with SnapshotControl

use of liquibase.snapshot.SnapshotControl in project liquibase by liquibase.

the class MssqlIntegrationTest method dataTypesTest.

@Test
public void dataTypesTest() throws Exception {
    if (this.getDatabase() == null) {
        return;
    }
    Liquibase liquibase = createLiquibase("changelogs/mssql/issues/data.types.xml");
    liquibase.update((String) null);
    DatabaseSnapshot snapshot = SnapshotGeneratorFactory.getInstance().createSnapshot(CatalogAndSchema.DEFAULT, this.getDatabase(), new SnapshotControl(getDatabase()));
    for (Table table : snapshot.get(Table.class)) {
        if (getDatabase().isLiquibaseObject(table)) {
            continue;
        }
        for (Column column : table.getColumns()) {
            String expectedType = column.getName().split("_")[0];
            if (expectedType.equalsIgnoreCase("text")) {
                expectedType = "nvarchar";
            }
            String foundTypeDefinition = DataTypeFactory.getInstance().from(column.getType(), new MSSQLDatabase()).toDatabaseDataType(getDatabase()).toString();
            String foundType = foundTypeDefinition.replaceFirst("\\(.*", "");
            assertEquals("Wrong data type for " + table.getName() + "." + column.getName(), expectedType.toLowerCase(), foundType.toLowerCase());
            if (expectedType.equalsIgnoreCase("varbinary")) {
                if (column.getName().endsWith("_MAX")) {
                    assertEquals("VARBINARY(MAX)", foundTypeDefinition);
                } else {
                    assertEquals("VARBINARY(1)", foundTypeDefinition);
                }
            }
        }
    }
}
Also used : Liquibase(liquibase.Liquibase) Table(liquibase.structure.core.Table) Column(liquibase.structure.core.Column) MSSQLDatabase(liquibase.database.core.MSSQLDatabase) DatabaseSnapshot(liquibase.snapshot.DatabaseSnapshot) EmptyDatabaseSnapshot(liquibase.snapshot.EmptyDatabaseSnapshot) SnapshotControl(liquibase.snapshot.SnapshotControl) Test(org.junit.Test)

Example 5 with SnapshotControl

use of liquibase.snapshot.SnapshotControl in project liquibase by liquibase.

the class AbstractIntegrationTest method testOutputChangeLog.

@Test
public void testOutputChangeLog() throws Exception {
    if (database == null) {
        return;
    }
    StringWriter output = new StringWriter();
    Liquibase liquibase = createLiquibase(completeChangeLog);
    clearDatabase(liquibase);
    liquibase = createLiquibase(completeChangeLog);
    liquibase.update(this.contexts, output);
    String outputResult = output.getBuffer().toString();
    assertNotNull(outputResult);
    //should be pretty big
    assertTrue(outputResult.length() > 100);
    System.out.println(outputResult);
    assertTrue("create databasechangelog command not found in: \n" + outputResult, outputResult.contains("CREATE TABLE " + database.escapeTableName(database.getLiquibaseCatalogName(), database.getLiquibaseSchemaName(), database.getDatabaseChangeLogTableName())));
    assertTrue("create databasechangeloglock command not found in: \n" + outputResult, outputResult.contains("CREATE TABLE " + database.escapeTableName(database.getLiquibaseCatalogName(), database.getLiquibaseSchemaName(), database.getDatabaseChangeLogLockTableName())));
    assertTrue(outputResult.contains("€"));
    assertTrue(outputResult.contains("€"));
    DatabaseSnapshot snapshot = SnapshotGeneratorFactory.getInstance().createSnapshot(database.getDefaultSchema(), database, new SnapshotControl(database));
    assertEquals(0, snapshot.get(Schema.class).iterator().next().getDatabaseObjects(Table.class).size());
}
Also used : Liquibase(liquibase.Liquibase) CatalogAndSchema(liquibase.CatalogAndSchema) DatabaseSnapshot(liquibase.snapshot.DatabaseSnapshot) SnapshotControl(liquibase.snapshot.SnapshotControl) Test(org.junit.Test)

Aggregations

SnapshotControl (liquibase.snapshot.SnapshotControl)14 DatabaseSnapshot (liquibase.snapshot.DatabaseSnapshot)12 Liquibase (liquibase.Liquibase)7 CompareControl (liquibase.diff.compare.CompareControl)6 Test (org.junit.Test)6 CatalogAndSchema (liquibase.CatalogAndSchema)5 DiffResult (liquibase.diff.DiffResult)5 UnexpectedLiquibaseException (liquibase.exception.UnexpectedLiquibaseException)5 Table (liquibase.structure.core.Table)5 EmptyDatabaseSnapshot (liquibase.snapshot.EmptyDatabaseSnapshot)4 DatabaseObject (liquibase.structure.DatabaseObject)4 Column (liquibase.structure.core.Column)4 Database (liquibase.database.Database)3 MSSQLDatabase (liquibase.database.core.MSSQLDatabase)3 DiffOutputControl (liquibase.diff.output.DiffOutputControl)3 DiffToChangeLog (liquibase.diff.output.changelog.DiffToChangeLog)3 LiquibaseException (liquibase.exception.LiquibaseException)3 InvalidExampleException (liquibase.snapshot.InvalidExampleException)3 SqlStatement (liquibase.statement.SqlStatement)3 ColumnConfig (liquibase.change.ColumnConfig)2