Search in sources :

Example 6 with DatabaseSnapshot

use of liquibase.snapshot.DatabaseSnapshot 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)

Example 7 with DatabaseSnapshot

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

the class DbDumpCommand method generateChangeLog.

private void generateChangeLog(final Database database, final CatalogAndSchema catalogAndSchema, final DiffToChangeLog changeLogWriter, PrintStream outputStream, final Set<Class<? extends DatabaseObject>> compareTypes) throws DatabaseException, IOException, ParserConfigurationException {
    @SuppressWarnings({ "unchecked", "rawtypes" }) final SnapshotControl snapshotControl = new SnapshotControl(database, compareTypes.toArray(new Class[compareTypes.size()]));
    final CompareControl compareControl = new CompareControl(new CompareControl.SchemaComparison[] { new CompareControl.SchemaComparison(catalogAndSchema, catalogAndSchema) }, compareTypes);
    final CatalogAndSchema[] compareControlSchemas = compareControl.getSchemas(CompareControl.DatabaseRole.REFERENCE);
    try {
        final DatabaseSnapshot referenceSnapshot = SnapshotGeneratorFactory.getInstance().createSnapshot(compareControlSchemas, database, snapshotControl);
        final DatabaseSnapshot comparisonSnapshot = SnapshotGeneratorFactory.getInstance().createSnapshot(compareControlSchemas, null, snapshotControl);
        final DiffResult diffResult = DiffGeneratorFactory.getInstance().compare(referenceSnapshot, comparisonSnapshot, compareControl);
        changeLogWriter.setDiffResult(diffResult);
        changeLogWriter.print(outputStream);
    } catch (InvalidExampleException e) {
        throw new UnexpectedLiquibaseException(e);
    }
}
Also used : InvalidExampleException(liquibase.snapshot.InvalidExampleException) CompareControl(liquibase.diff.compare.CompareControl) DiffResult(liquibase.diff.DiffResult) CatalogAndSchema(liquibase.CatalogAndSchema) SnapshotControl(liquibase.snapshot.SnapshotControl) DatabaseSnapshot(liquibase.snapshot.DatabaseSnapshot) UnexpectedLiquibaseException(liquibase.exception.UnexpectedLiquibaseException)

Example 8 with DatabaseSnapshot

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

the class DBDocVisitor method writeHTML.

public void writeHTML(File rootOutputDir, ResourceAccessor resourceAccessor) throws IOException, LiquibaseException, DatabaseHistoryException {
    ChangeLogWriter changeLogWriter = new ChangeLogWriter(resourceAccessor, rootOutputDir);
    HTMLWriter authorWriter = new AuthorWriter(rootOutputDir, database);
    HTMLWriter tableWriter = new TableWriter(rootOutputDir, database);
    HTMLWriter columnWriter = new ColumnWriter(rootOutputDir, database);
    HTMLWriter pendingChangesWriter = new PendingChangesWriter(rootOutputDir, database);
    HTMLWriter recentChangesWriter = new RecentChangesWriter(rootOutputDir, database);
    HTMLWriter pendingSQLWriter = new PendingSQLWriter(rootOutputDir, database, rootChangeLog);
    copyFile("liquibase/dbdoc/stylesheet.css", rootOutputDir);
    copyFile("liquibase/dbdoc/index.html", rootOutputDir);
    copyFile("liquibase/dbdoc/globalnav.html", rootOutputDir);
    copyFile("liquibase/dbdoc/overview-summary.html", rootOutputDir);
    DatabaseSnapshot snapshot = SnapshotGeneratorFactory.getInstance().createSnapshot(database.getDefaultSchema(), database, new SnapshotControl(database));
    new ChangeLogListWriter(rootOutputDir).writeHTML(changeLogs);
    SortedSet<Table> tables = new TreeSet<Table>(snapshot.get(Table.class));
    Iterator<Table> tableIterator = tables.iterator();
    while (tableIterator.hasNext()) {
        if (database.isLiquibaseObject(tableIterator.next())) {
            tableIterator.remove();
        }
    }
    new TableListWriter(rootOutputDir).writeHTML(tables);
    new AuthorListWriter(rootOutputDir).writeHTML(new TreeSet<Object>(changesByAuthor.keySet()));
    for (String author : changesByAuthor.keySet()) {
        authorWriter.writeHTML(author, changesByAuthor.get(author), changesToRunByAuthor.get(author), rootChangeLogName);
    }
    for (Table table : tables) {
        if (database.isLiquibaseObject(table)) {
            continue;
        }
        tableWriter.writeHTML(table, changesByObject.get(table), changesToRunByObject.get(table), rootChangeLogName);
    }
    for (Column column : snapshot.get(Column.class)) {
        if (database.isLiquibaseObject(column.getRelation())) {
            continue;
        }
        columnWriter.writeHTML(column, changesByObject.get(column), changesToRunByObject.get(column), rootChangeLogName);
    }
    for (ChangeLogInfo changeLog : changeLogs) {
        changeLogWriter.writeChangeLog(changeLog.logicalPath, changeLog.physicalPath);
    }
    pendingChangesWriter.writeHTML("index", null, changesToRun, rootChangeLogName);
    pendingSQLWriter.writeHTML("sql", null, changesToRun, rootChangeLogName);
    if (recentChanges.size() > MAX_RECENT_CHANGE) {
        recentChanges = recentChanges.subList(0, MAX_RECENT_CHANGE);
    }
    recentChangesWriter.writeHTML("index", recentChanges, null, rootChangeLogName);
}
Also used : Table(liquibase.structure.core.Table) Column(liquibase.structure.core.Column) DatabaseObject(liquibase.structure.DatabaseObject) DatabaseSnapshot(liquibase.snapshot.DatabaseSnapshot) SnapshotControl(liquibase.snapshot.SnapshotControl)

Example 9 with DatabaseSnapshot

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

the class StringSnapshotSerializerReadable method serialize.

@Override
public String serialize(LiquibaseSerializable object, boolean pretty) {
    try {
        StringBuilder buffer = new StringBuilder();
        DatabaseSnapshot snapshot = ((DatabaseSnapshot) object);
        Database database = snapshot.getDatabase();
        buffer.append("Database snapshot for ").append(database.getConnection().getURL()).append("\n");
        addDivider(buffer);
        buffer.append("Database type: ").append(database.getDatabaseProductName()).append("\n");
        buffer.append("Database version: ").append(database.getDatabaseProductVersion()).append("\n");
        buffer.append("Database user: ").append(database.getConnection().getConnectionUserName()).append("\n");
        SnapshotControl snapshotControl = snapshot.getSnapshotControl();
        List<Class> includedTypes = sort(snapshotControl.getTypesToInclude());
        buffer.append("Included types:\n").append(StringUtils.indent(StringUtils.join(includedTypes, "\n", new StringUtils.StringUtilsFormatter<Class>() {

            @Override
            public String toString(Class obj) {
                return obj.getName();
            }
        }))).append("\n");
        List<Schema> schemas = sort(snapshot.get(Schema.class), new Comparator<Schema>() {

            @Override
            public int compare(Schema o1, Schema o2) {
                return o1.toString().compareTo(o2.toString());
            }
        });
        for (Schema schema : schemas) {
            if (database.supportsSchemas()) {
                buffer.append("\nCatalog & Schema: ").append(schema.getCatalogName()).append(" / ").append(schema.getName()).append("\n");
            } else {
                buffer.append("\nCatalog: ").append(schema.getCatalogName()).append("\n");
            }
            StringBuilder catalogBuffer = new StringBuilder();
            for (Class type : includedTypes) {
                if (type.equals(Schema.class) || type.equals(Catalog.class) || type.equals(Column.class)) {
                    continue;
                }
                List<DatabaseObject> objects = new ArrayList<DatabaseObject>(snapshot.get(type));
                ListIterator<DatabaseObject> iterator = objects.listIterator();
                while (iterator.hasNext()) {
                    DatabaseObject next = iterator.next();
                    if (next instanceof DatabaseLevelObject) {
                        continue;
                    }
                    Schema objectSchema = next.getSchema();
                    if (objectSchema == null) {
                        if (!(next instanceof CatalogLevelObject) || !((CatalogLevelObject) next).getCatalog().equals(schema.getCatalog())) {
                            iterator.remove();
                        }
                    } else if (!objectSchema.equals(schema)) {
                        iterator.remove();
                    }
                }
                outputObjects(objects, type, catalogBuffer);
            }
            buffer.append(StringUtils.indent(catalogBuffer.toString(), INDENT_LENGTH));
        }
        //standardize all newline chars
        return buffer.toString().replace("\r\n", "\n").replace("\r", "\n");
    } catch (Exception e) {
        throw new UnexpectedLiquibaseException(e);
    }
}
Also used : CatalogLevelObject(liquibase.structure.CatalogLevelObject) UnexpectedLiquibaseException(liquibase.exception.UnexpectedLiquibaseException) DatabaseLevelObject(liquibase.structure.DatabaseLevelObject) Database(liquibase.database.Database) DatabaseObject(liquibase.structure.DatabaseObject) DatabaseSnapshot(liquibase.snapshot.DatabaseSnapshot) SnapshotControl(liquibase.snapshot.SnapshotControl) UnexpectedLiquibaseException(liquibase.exception.UnexpectedLiquibaseException)

Example 10 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();
    try {
        InputStream stream = StreamUtil.singleInputStream(path, resourceAccessor);
        if (stream == null) {
            throw new LiquibaseParseException(path + " does not exist");
        }
        Map parsedYaml;
        try {
            parsedYaml = yaml.loadAs(new InputStreamReader(stream, LiquibaseConfiguration.getInstance().getConfiguration(GlobalConfiguration.class).getOutputEncoding()), Map.class);
        } catch (Exception e) {
            throw new LiquibaseParseException("Syntax error in " + getSupportedFileExtensions()[0] + ": " + e.getMessage(), e);
        } finally {
            try {
                stream.close();
            } catch (IOException ioe) {
            }
        }
        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().newInstance();
        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 (Throwable e) {
        if (e instanceof LiquibaseParseException) {
            throw (LiquibaseParseException) e;
        }
        throw new LiquibaseParseException(e);
    }
}
Also used : ParsedNode(liquibase.parser.core.ParsedNode) InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) IOException(java.io.IOException) Yaml(org.yaml.snakeyaml.Yaml) IOException(java.io.IOException) LiquibaseParseException(liquibase.exception.LiquibaseParseException) LiquibaseParseException(liquibase.exception.LiquibaseParseException) Database(liquibase.database.Database) Map(java.util.Map) EmptyDatabaseSnapshot(liquibase.snapshot.EmptyDatabaseSnapshot) RestoredDatabaseSnapshot(liquibase.snapshot.RestoredDatabaseSnapshot) DatabaseSnapshot(liquibase.snapshot.DatabaseSnapshot) RestoredDatabaseSnapshot(liquibase.snapshot.RestoredDatabaseSnapshot)

Aggregations

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