Search in sources :

Example 16 with DatabaseSnapshot

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

the class SnapshotCommand method run.

@Override
public SnapshotCommandResult run() throws Exception {
    final CommandScope commandScope = new CommandScope("internalSnapshot");
    commandScope.addArgumentValue(InternalSnapshotCommandStep.DATABASE_ARG, this.getDatabase());
    commandScope.addArgumentValue(InternalSnapshotCommandStep.SCHEMAS_ARG, this.schemas);
    commandScope.addArgumentValue(InternalSnapshotCommandStep.SERIALIZER_FORMAT_ARG, this.getSerializerFormat());
    commandScope.addArgumentValue(InternalSnapshotCommandStep.SNAPSHOT_LISTENER_ARG, this.getSnapshotListener());
    final CommandResults results = commandScope.execute();
    DatabaseSnapshot snapshot = (DatabaseSnapshot) results.getResult("snapshot");
    return new SnapshotCommandResult(snapshot);
}
Also used : DatabaseSnapshot(liquibase.snapshot.DatabaseSnapshot)

Example 17 with DatabaseSnapshot

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

the class YamlSnapshotParser method parse.

@Override
public DatabaseSnapshot parse(String path, ResourceAccessor resourceAccessor) throws LiquibaseParseException {
    Yaml yaml = new Yaml(new SafeConstructor());
    try (InputStream stream = resourceAccessor.openStream(null, path)) {
        if (stream == null) {
            throw new LiquibaseParseException(path + " does not exist");
        }
        Map parsedYaml = getParsedYamlFromInputStream(yaml, stream);
        Map rootList = (Map) parsedYaml.get("snapshot");
        if (rootList == null) {
            throw new LiquibaseParseException("Could not find root snapshot node");
        }
        String shortName = (String) ((Map) rootList.get("database")).get("shortName");
        Database database = DatabaseFactory.getInstance().getDatabase(shortName).getClass().getConstructor().newInstance();
        database.setConnection(new OfflineConnection("offline:" + shortName, null));
        DatabaseSnapshot snapshot = new RestoredDatabaseSnapshot(database);
        ParsedNode snapshotNode = new ParsedNode(null, "snapshot");
        snapshotNode.setValue(rootList);
        Map metadata = (Map) rootList.get("metadata");
        if (metadata != null) {
            snapshot.getMetadata().putAll(metadata);
        }
        snapshot.load(snapshotNode, resourceAccessor);
        return snapshot;
    } catch (LiquibaseParseException e) {
        throw (LiquibaseParseException) e;
    } catch (Exception e) {
        throw new LiquibaseParseException(e);
    }
}
Also used : LiquibaseParseException(liquibase.exception.LiquibaseParseException) ParsedNode(liquibase.parser.core.ParsedNode) InputStream(java.io.InputStream) Database(liquibase.database.Database) SafeConstructor(org.yaml.snakeyaml.constructor.SafeConstructor) OfflineConnection(liquibase.database.OfflineConnection) Map(java.util.Map) RestoredDatabaseSnapshot(liquibase.snapshot.RestoredDatabaseSnapshot) DatabaseSnapshot(liquibase.snapshot.DatabaseSnapshot) Yaml(org.yaml.snakeyaml.Yaml) LiquibaseParseException(liquibase.exception.LiquibaseParseException) RestoredDatabaseSnapshot(liquibase.snapshot.RestoredDatabaseSnapshot)

Example 18 with DatabaseSnapshot

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

the class AbstractIntegrationTest method testRerunDiffChangeLog.

@Test
public void testRerunDiffChangeLog() throws Exception {
    assumeNotNull(this.getDatabase());
    for (int run = 0; run < 2; run++) {
        // run once outputting data as insert, once as csv
        boolean outputCsv = run == 1;
        runCompleteChangeLog();
        SnapshotControl snapshotControl = new SnapshotControl(database);
        DatabaseSnapshot originalSnapshot = SnapshotGeneratorFactory.getInstance().createSnapshot(database.getDefaultSchema(), database, snapshotControl);
        CompareControl compareControl = new CompareControl();
        // database returns different data even if the same
        compareControl.addSuppressedField(Column.class, "defaultValue");
        // database returns different data even if the same
        compareControl.addSuppressedField(Column.class, "autoIncrementInformation");
        if (database instanceof OracleDatabase) {
            // database returns different nvarchar2 info even though they are the same
            compareControl.addSuppressedField(Column.class, "type");
            // database returns different nullable on views, e.g. v_person.id
            compareControl.addSuppressedField(Column.class, "nullable");
        }
        if (database instanceof PostgresDatabase) {
            // database returns different nvarchar2 info even though they are the same
            compareControl.addSuppressedField(Column.class, "type");
        }
        DiffOutputControl diffOutputControl = new DiffOutputControl();
        File tempFile = tempDirectory.getRoot().createTempFile("liquibase-test", ".xml");
        if (outputCsv) {
            diffOutputControl.setDataDir(new File(tempFile.getParentFile(), "liquibase-data").getCanonicalPath().replaceFirst("\\w:", ""));
        }
        DiffResult diffResult = DiffGeneratorFactory.getInstance().compare(database, null, compareControl);
        FileOutputStream output = new FileOutputStream(tempFile);
        try {
            new DiffToChangeLog(diffResult, new DiffOutputControl()).print(new PrintStream(output));
            output.flush();
        } finally {
            output.close();
        }
        Liquibase liquibase = createLiquibase(tempFile.getName());
        clearDatabase();
        DatabaseSnapshot emptySnapshot = SnapshotGeneratorFactory.getInstance().createSnapshot(database.getDefaultSchema(), database, new SnapshotControl(database));
        // run again to test changelog testing logic
        liquibase = createLiquibase(tempFile.getName());
        try {
            liquibase.update(this.contexts);
        } catch (ValidationFailedException e) {
            e.printDescriptiveError(System.out);
            throw e;
        }
        DatabaseSnapshot migratedSnapshot = SnapshotGeneratorFactory.getInstance().createSnapshot(database.getDefaultSchema(), database, new SnapshotControl(database));
        DiffResult finalDiffResult = DiffGeneratorFactory.getInstance().compare(originalSnapshot, migratedSnapshot, compareControl);
        try {
            assertTrue("recreating the database from the generated change log should cause both 'before' and " + "'after' snapshots to be equal.", finalDiffResult.areEqual());
        } catch (AssertionError e) {
            new DiffToReport(finalDiffResult, System.err).print();
            throw e;
        }
        // diff to empty and drop all
        DiffResult emptyDiffResult = DiffGeneratorFactory.getInstance().compare(emptySnapshot, migratedSnapshot, compareControl);
        output = new FileOutputStream(tempFile);
        try {
            new DiffToChangeLog(emptyDiffResult, new DiffOutputControl(true, true, true, null)).print(new PrintStream(output));
            output.flush();
        } finally {
            output.close();
        }
        liquibase = createLiquibase(tempFile.getName());
        Scope.getCurrentScope().getLog(getClass()).info("updating from " + tempFile.getCanonicalPath());
        try {
            liquibase.update(this.contexts);
        } catch (LiquibaseException e) {
            throw e;
        }
        DatabaseSnapshot emptyAgainSnapshot = SnapshotGeneratorFactory.getInstance().createSnapshot(database.getDefaultSchema(), database, new SnapshotControl(database));
        assertEquals("a database that was 'updated' to an empty snapshot should only have 2 tables left: " + "the database change log table and the lock table.", 2, emptyAgainSnapshot.get(Table.class).size());
        assertEquals("a database that was 'updated' to an empty snapshot should not contain any views.", 0, emptyAgainSnapshot.get(View.class).size());
    }
}
Also used : DiffOutputControl(liquibase.diff.output.DiffOutputControl) OracleDatabase(liquibase.database.core.OracleDatabase) PostgresDatabase(liquibase.database.core.PostgresDatabase) ValidationFailedException(liquibase.exception.ValidationFailedException) DiffToReport(liquibase.diff.output.report.DiffToReport) CompareControl(liquibase.diff.compare.CompareControl) DiffToChangeLog(liquibase.diff.output.changelog.DiffToChangeLog) DiffResult(liquibase.diff.DiffResult) LiquibaseException(liquibase.exception.LiquibaseException) SnapshotControl(liquibase.snapshot.SnapshotControl) DatabaseSnapshot(liquibase.snapshot.DatabaseSnapshot) Test(org.junit.Test)

Example 19 with DatabaseSnapshot

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

the class AbstractIntegrationTest method testRerunDiffChangeLogAltSchema.

@Test
public void testRerunDiffChangeLogAltSchema() throws Exception {
    assumeNotNull(this.getDatabase());
    if (database.getShortName().equalsIgnoreCase("mssql")) {
        // not possible on MSSQL.
        return;
    }
    if (!database.supportsSchemas()) {
        return;
    }
    Liquibase liquibase = createLiquibase(includedChangeLog);
    database.setDefaultSchemaName("lbschem2");
    clearDatabase();
    LockService lockService = LockServiceFactory.getInstance().getLockService(database);
    lockService.forceReleaseLock();
    liquibase.update(includedChangeLog);
    DatabaseSnapshot originalSnapshot = SnapshotGeneratorFactory.getInstance().createSnapshot(database.getDefaultSchema(), database, new SnapshotControl(database));
    CompareControl compareControl = new CompareControl(new CompareControl.SchemaComparison[] { new CompareControl.SchemaComparison(CatalogAndSchema.DEFAULT, new CatalogAndSchema("lbcat2", null)) }, originalSnapshot.getSnapshotControl().getTypesToInclude());
    DiffResult diffResult = DiffGeneratorFactory.getInstance().compare(database, null, compareControl);
    File tempFile = File.createTempFile("liquibase-test", ".xml");
    FileOutputStream output = new FileOutputStream(tempFile);
    try {
        new DiffToChangeLog(diffResult, new DiffOutputControl()).print(new PrintStream(output));
        output.flush();
    } finally {
        output.close();
    }
    liquibase = createLiquibase(tempFile.getName());
    clearDatabase();
    // run again to test changelog testing logic
    Executor executor = Scope.getCurrentScope().getSingleton(ExecutorService.class).getExecutor("jdbc", database);
    try {
        executor.execute(new DropTableStatement("lbcat2", null, database.getDatabaseChangeLogTableName(), false));
    } catch (DatabaseException e) {
    // ok
    }
    try {
        executor.execute(new DropTableStatement("lbcat2", null, database.getDatabaseChangeLogLockTableName(), false));
    } catch (DatabaseException e) {
    // ok
    }
    database.commit();
    DatabaseConnection connection = new JdbcConnection(testSystem.getConnection());
    database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(connection);
    database.setDefaultSchemaName("lbschem2");
    liquibase = createLiquibase(tempFile.getName());
    try {
        liquibase.update(this.contexts);
    } catch (ValidationFailedException e) {
        e.printDescriptiveError(System.out);
        throw e;
    }
    tempFile.deleteOnExit();
    DatabaseSnapshot finalSnapshot = SnapshotGeneratorFactory.getInstance().createSnapshot(database.getDefaultSchema(), database, new SnapshotControl(database));
    CompareControl finalCompareControl = new CompareControl();
    finalCompareControl.addSuppressedField(Column.class, "autoIncrementInformation");
    DiffResult finalDiffResult = DiffGeneratorFactory.getInstance().compare(originalSnapshot, finalSnapshot, finalCompareControl);
    new DiffToReport(finalDiffResult, System.out).print();
    assertTrue("running the same change log two times against an alternative schema should produce " + "equal snapshots.", finalDiffResult.areEqual());
}
Also used : LockService(liquibase.lockservice.LockService) DiffOutputControl(liquibase.diff.output.DiffOutputControl) JdbcConnection(liquibase.database.jvm.JdbcConnection) Executor(liquibase.executor.Executor) ValidationFailedException(liquibase.exception.ValidationFailedException) ExecutorService(liquibase.executor.ExecutorService) DiffToReport(liquibase.diff.output.report.DiffToReport) CompareControl(liquibase.diff.compare.CompareControl) DiffToChangeLog(liquibase.diff.output.changelog.DiffToChangeLog) DatabaseConnection(liquibase.database.DatabaseConnection) DiffResult(liquibase.diff.DiffResult) DatabaseSnapshot(liquibase.snapshot.DatabaseSnapshot) SnapshotControl(liquibase.snapshot.SnapshotControl) DropTableStatement(liquibase.statement.core.DropTableStatement) DatabaseException(liquibase.exception.DatabaseException) Test(org.junit.Test)

Example 20 with DatabaseSnapshot

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

the class MySQLIntegrationTest method dateDefaultValue.

@Test
public void dateDefaultValue() throws Exception {
    if (getDatabase() == null) {
        return;
    }
    Scope.getCurrentScope().getSingleton(ExecutorService.class).getExecutor("jdbc", getDatabase()).execute(new RawSqlStatement("DROP TABLE IF " + "EXISTS ad"));
    try {
        Scope.getCurrentScope().getSingleton(ExecutorService.class).getExecutor("jdbc", getDatabase()).execute(new RawSqlStatement("CREATE TABLE ad (\n" + "ad_id int(10) unsigned NOT NULL AUTO_INCREMENT,\n" + "advertiser_id int(10) unsigned NOT NULL,\n" + "ad_type_id int(10) unsigned NOT NULL,\n" + "name varchar(155) NOT NULL DEFAULT '',\n" + "label varchar(155)NOT NULL DEFAULT '',\n" + "description text NOT NULL,\n" + "active tinyint(1) NOT NULL DEFAULT '0',\n" + "created datetime NOT NULL DEFAULT '0000-00-00 00:00:00',\n" + "updated datetime DEFAULT '0000-00-00 00:00:00',\n" + "PRIMARY KEY (ad_id),\n" + "KEY active (active)\n" + ")"));
    } catch (DatabaseException e) {
        if (e.getCause() instanceof SQLSyntaxErrorException) {
            Scope.getCurrentScope().getLog(getClass()).warning("MySQL returned DatabaseException", e);
            assumeTrue("MySQL seems to run in strict mode (no datetime literals with 0000-00-00 allowed). " + "Cannot run this test", false);
        } else {
            throw e;
        }
    }
    DatabaseSnapshot snapshot = SnapshotGeneratorFactory.getInstance().createSnapshot(CatalogAndSchema.DEFAULT, getDatabase(), new SnapshotControl(getDatabase()));
    Column createdColumn = snapshot.get(new Column().setRelation(new Table().setName("ad").setSchema(new Schema())).setName("created"));
    Object defaultValue = createdColumn.getDefaultValue();
    assertNotNull(defaultValue);
    assertEquals("0000-00-00 00:00:00", defaultValue);
}
Also used : RawSqlStatement(liquibase.statement.core.RawSqlStatement) Table(liquibase.structure.core.Table) Column(liquibase.structure.core.Column) Schema(liquibase.structure.core.Schema) CatalogAndSchema(liquibase.CatalogAndSchema) SQLSyntaxErrorException(java.sql.SQLSyntaxErrorException) DatabaseException(liquibase.exception.DatabaseException) DatabaseSnapshot(liquibase.snapshot.DatabaseSnapshot) SnapshotControl(liquibase.snapshot.SnapshotControl) Test(org.junit.Test) AbstractIntegrationTest(liquibase.dbtest.AbstractIntegrationTest)

Aggregations

DatabaseSnapshot (liquibase.snapshot.DatabaseSnapshot)28 SnapshotControl (liquibase.snapshot.SnapshotControl)20 Test (org.junit.Test)13 AbstractIntegrationTest (liquibase.dbtest.AbstractIntegrationTest)7 Column (liquibase.structure.core.Column)7 Table (liquibase.structure.core.Table)7 DiffResult (liquibase.diff.DiffResult)6 CompareControl (liquibase.diff.compare.CompareControl)6 CatalogAndSchema (liquibase.CatalogAndSchema)5 Liquibase (liquibase.Liquibase)5 Database (liquibase.database.Database)5 UnexpectedLiquibaseException (liquibase.exception.UnexpectedLiquibaseException)5 DatabaseObject (liquibase.structure.DatabaseObject)5 DatabaseException (liquibase.exception.DatabaseException)4 LiquibaseException (liquibase.exception.LiquibaseException)4 Schema (liquibase.structure.core.Schema)4 DiffOutputControl (liquibase.diff.output.DiffOutputControl)3 DiffToChangeLog (liquibase.diff.output.changelog.DiffToChangeLog)3 RawSqlStatement (liquibase.statement.core.RawSqlStatement)3 IOException (java.io.IOException)2