Search in sources :

Example 26 with DatabaseSnapshot

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

the class DiffToChangeLog method print.

public void print(String changeLogFile, ChangeLogSerializer changeLogSerializer) throws ParserConfigurationException, IOException, DatabaseException {
    this.changeSetPath = changeLogFile;
    File file = new File(changeLogFile);
    final Map<String, Object> newScopeObjects = new HashMap<>();
    File objectsDir = null;
    if (changeLogFile.toLowerCase().endsWith("sql")) {
        DeprecatedConfigurationValueProvider.setData("liquibase.pro.sql.inline", "true");
    } else if (this.diffResult.getComparisonSnapshot() instanceof EmptyDatabaseSnapshot) {
        objectsDir = new File(file.getParentFile(), "objects");
    } else {
        objectsDir = new File(file.getParentFile(), "objects-" + new Date().getTime());
    }
    if (objectsDir != null) {
        if (objectsDir.exists()) {
            throw new UnexpectedLiquibaseException("The generatechangelog command would overwrite your existing stored logic files. To run this command please remove or rename the '" + objectsDir.getCanonicalPath() + "' dir in your local project directory");
        }
        newScopeObjects.put(EXTERNAL_FILE_DIR_SCOPE_KEY, objectsDir);
    }
    newScopeObjects.put(DIFF_OUTPUT_CONTROL_SCOPE_KEY, diffOutputControl);
    try {
        // 
        // Get a Database instance and save it in the scope for later use
        // 
        DatabaseSnapshot snapshot = diffResult.getReferenceSnapshot();
        Database database = determineDatabase(diffResult.getReferenceSnapshot());
        if (database == null) {
            database = determineDatabase(diffResult.getComparisonSnapshot());
        }
        newScopeObjects.put(DIFF_SNAPSHOT_DATABASE, database);
        Scope.child(newScopeObjects, new Scope.ScopedRunner() {

            @Override
            public void run() {
                try {
                    if (!file.exists()) {
                        // print changeLog only if there are available changeSets to print instead of printing it always
                        printNew(changeLogSerializer, file);
                    } else {
                        Scope.getCurrentScope().getLog(getClass()).info(file + " exists, appending");
                        ByteArrayOutputStream out = new ByteArrayOutputStream();
                        print(new PrintStream(out, true, GlobalConfiguration.OUTPUT_FILE_ENCODING.getCurrentValue()), changeLogSerializer);
                        String xml = new String(out.toByteArray(), GlobalConfiguration.OUTPUT_FILE_ENCODING.getCurrentValue());
                        String innerXml = xml.replaceFirst("(?ms).*<databaseChangeLog[^>]*>", "");
                        innerXml = innerXml.replaceFirst(DATABASE_CHANGE_LOG_CLOSING_XML_TAG, "");
                        innerXml = innerXml.trim();
                        if ("".equals(innerXml)) {
                            Scope.getCurrentScope().getLog(getClass()).info("No changes found, nothing to do");
                            return;
                        }
                        try (RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw")) {
                            String line;
                            long offset = 0;
                            boolean foundEndTag = false;
                            while ((line = randomAccessFile.readLine()) != null) {
                                int index = line.indexOf(DATABASE_CHANGE_LOG_CLOSING_XML_TAG);
                                if (index >= 0) {
                                    foundEndTag = true;
                                    break;
                                } else {
                                    offset = randomAccessFile.getFilePointer();
                                }
                            }
                            String lineSeparator = GlobalConfiguration.OUTPUT_LINE_SEPARATOR.getCurrentValue();
                            if (foundEndTag) {
                                randomAccessFile.seek(offset);
                                randomAccessFile.writeBytes("    ");
                                randomAccessFile.write(innerXml.getBytes(GlobalConfiguration.OUTPUT_FILE_ENCODING.getCurrentValue()));
                                randomAccessFile.writeBytes(lineSeparator);
                                randomAccessFile.writeBytes(DATABASE_CHANGE_LOG_CLOSING_XML_TAG + lineSeparator);
                            } else {
                                randomAccessFile.seek(0);
                                long length = randomAccessFile.length();
                                randomAccessFile.seek(length);
                                randomAccessFile.write(xml.getBytes(GlobalConfiguration.OUTPUT_FILE_ENCODING.getCurrentValue()));
                            }
                        }
                    }
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        });
    } catch (Exception e) {
        // rethrow known exceptions. TODO: Fix this up with final Scope API
        final Throwable cause = e.getCause();
        if (cause instanceof ParserConfigurationException) {
            throw (ParserConfigurationException) cause;
        }
        if (cause instanceof IOException) {
            throw (IOException) cause;
        }
        if (cause instanceof DatabaseException) {
            throw (DatabaseException) cause;
        }
        throw new RuntimeException(e);
    }
}
Also used : UnexpectedLiquibaseException(liquibase.exception.UnexpectedLiquibaseException) DatabaseException(liquibase.exception.DatabaseException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) Scope(liquibase.Scope) EmptyDatabaseSnapshot(liquibase.snapshot.EmptyDatabaseSnapshot) DatabaseObject(liquibase.structure.DatabaseObject) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) UnexpectedLiquibaseException(liquibase.exception.UnexpectedLiquibaseException) DatabaseSnapshot(liquibase.snapshot.DatabaseSnapshot) EmptyDatabaseSnapshot(liquibase.snapshot.EmptyDatabaseSnapshot) DatabaseException(liquibase.exception.DatabaseException)

Example 27 with DatabaseSnapshot

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

the class LiquibaseRelationalSchemaCreator method createRelationalSchema.

@Override
public void createRelationalSchema(RelationalSchema schema, Connection targetConn) throws CollectRdbException {
    PrintStream ps = null;
    try {
        LiquidbaseDatabaseSnapshotBuilder snapshotGen = new LiquidbaseDatabaseSnapshotBuilder();
        Database rdb = getDatabaseImplementation(targetConn);
        boolean dbSupportsFKs = rdb instanceof SQLiteDatabase ? false : true;
        DatabaseSnapshot generatedSnapshot = snapshotGen.createSnapshot(schema, dbSupportsFKs);
        String targetSchema = schema.getName();
        rdb.setDefaultSchemaName(targetSchema);
        DatabaseSnapshot emptyDbSnapshot = new DatabaseSnapshot(rdb, targetSchema);
        // Generate change set
        Diff diff = new Diff(generatedSnapshot, emptyDbSnapshot);
        DiffResult diffResult = diff.compare();
        File tmpFile = File.createTempFile("collect-schemagen", ".xml");
        ps = new PrintStream(new FileOutputStream(tmpFile));
        diffResult.setChangeSetAuthor("collect3");
        diffResult.setChangeSetContext("schemagen");
        System.out.println("Writing change log to " + tmpFile.getAbsolutePath());
        diffResult.printChangeLog(ps, rdb);
        ps.flush();
        // Execute change set
        Liquibase liq = new Liquibase(tmpFile.getName(), new FileSystemResourceAccessor(tmpFile.getParent()), rdb);
        liq.update("schemagen");
    } catch (LiquibaseException e) {
        throw new CollectRdbException("Failed to update schema", e);
    } catch (IOException e) {
        throw new CollectRdbException("Failed to create temp db changelog file", e);
    } catch (ParserConfigurationException e) {
        throw new CollectRdbException("Failed to write temp db changelog file", e);
    } finally {
        if (ps != null) {
            ps.close();
        }
    }
}
Also used : PrintStream(java.io.PrintStream) Diff(liquibase.diff.Diff) IOException(java.io.IOException) Liquibase(liquibase.Liquibase) SQLiteDatabase(liquibase.database.core.SQLiteDatabase) CollectRdbException(org.openforis.collect.relational.CollectRdbException) FileOutputStream(java.io.FileOutputStream) SQLiteDatabase(liquibase.database.core.SQLiteDatabase) PostgresDatabase(liquibase.database.core.PostgresDatabase) Database(liquibase.database.Database) DiffResult(liquibase.diff.DiffResult) FileSystemResourceAccessor(liquibase.resource.FileSystemResourceAccessor) LiquibaseException(liquibase.exception.LiquibaseException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) DatabaseSnapshot(liquibase.snapshot.DatabaseSnapshot) File(java.io.File)

Example 28 with DatabaseSnapshot

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

the class IdmDatabaseSnapshotBuilder method toSnapshot.

public DatabaseSnapshot toSnapshot() throws DatabaseException {
    this.snapshot = new DatabaseSnapshot(database, surveyUri);
    this.tables = snapshot.getTables();
    createDataTables();
    createCodeListTables();
    return snapshot;
}
Also used : DatabaseSnapshot(liquibase.snapshot.DatabaseSnapshot)

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