Search in sources :

Example 11 with LockService

use of liquibase.lockservice.LockService in project liquibase by liquibase.

the class Liquibase method futureRollbackSQL.

protected void futureRollbackSQL(Integer count, String tag, Contexts contexts, LabelExpression labelExpression, Writer output, boolean checkLiquibaseTables) throws LiquibaseException {
    changeLogParameters.setContexts(contexts);
    changeLogParameters.setLabels(labelExpression);
    runInScope(new Scope.ScopedRunner() {

        @Override
        public void run() throws Exception {
            LoggingExecutor outputTemplate = new LoggingExecutor(Scope.getCurrentScope().getSingleton(ExecutorService.class).getExecutor(database), output, database);
            Executor oldTemplate = getAndReplaceJdbcExecutor(output);
            Scope.getCurrentScope().getSingleton(ExecutorService.class).setExecutor(database, outputTemplate);
            outputHeader("SQL to roll back currently unexecuted changes");
            LockService lockService = LockServiceFactory.getInstance().getLockService(database);
            lockService.waitForLock();
            try {
                DatabaseChangeLog changeLog = getDatabaseChangeLog();
                if (checkLiquibaseTables) {
                    checkLiquibaseTables(false, changeLog, contexts, labelExpression);
                }
                ChangeLogHistoryServiceFactory.getInstance().getChangeLogService(database).generateDeploymentId();
                changeLog.validate(database, contexts, labelExpression);
                ChangeLogIterator logIterator;
                if ((count == null) && (tag == null)) {
                    logIterator = new ChangeLogIterator(changeLog, new NotRanChangeSetFilter(database.getRanChangeSetList()), new ContextChangeSetFilter(contexts), new LabelChangeSetFilter(labelExpression), new IgnoreChangeSetFilter(), new DbmsChangeSetFilter(database));
                } else if (count != null) {
                    ChangeLogIterator forwardIterator = new ChangeLogIterator(changeLog, new NotRanChangeSetFilter(database.getRanChangeSetList()), new ContextChangeSetFilter(contexts), new LabelChangeSetFilter(labelExpression), new DbmsChangeSetFilter(database), new IgnoreChangeSetFilter(), new CountChangeSetFilter(count));
                    final ListVisitor listVisitor = new ListVisitor();
                    forwardIterator.run(listVisitor, new RuntimeEnvironment(database, contexts, labelExpression));
                    logIterator = new ChangeLogIterator(changeLog, new NotRanChangeSetFilter(database.getRanChangeSetList()), new ContextChangeSetFilter(contexts), new LabelChangeSetFilter(labelExpression), new DbmsChangeSetFilter(database), new IgnoreChangeSetFilter(), new ChangeSetFilter() {

                        @Override
                        public ChangeSetFilterResult accepts(ChangeSet changeSet) {
                            return new ChangeSetFilterResult(listVisitor.getSeenChangeSets().contains(changeSet), null, null);
                        }
                    });
                } else {
                    List<RanChangeSet> ranChangeSetList = database.getRanChangeSetList();
                    UpToTagChangeSetFilter upToTagChangeSetFilter = new UpToTagChangeSetFilter(tag, ranChangeSetList);
                    ChangeLogIterator forwardIterator = new ChangeLogIterator(changeLog, new NotRanChangeSetFilter(ranChangeSetList), new ContextChangeSetFilter(contexts), new LabelChangeSetFilter(labelExpression), new DbmsChangeSetFilter(database), new IgnoreChangeSetFilter(), upToTagChangeSetFilter);
                    final ListVisitor listVisitor = new ListVisitor();
                    forwardIterator.run(listVisitor, new RuntimeEnvironment(database, contexts, labelExpression));
                    // 
                    if (!upToTagChangeSetFilter.isSeenTag()) {
                        String message = "No tag matching '" + tag + "' found";
                        Scope.getCurrentScope().getUI().sendMessage("ERROR: " + message);
                        Scope.getCurrentScope().getLog(Liquibase.class).severe(message);
                        throw new LiquibaseException(new IllegalArgumentException(message));
                    }
                    logIterator = new ChangeLogIterator(changeLog, new NotRanChangeSetFilter(ranChangeSetList), new ContextChangeSetFilter(contexts), new LabelChangeSetFilter(labelExpression), new DbmsChangeSetFilter(database), new IgnoreChangeSetFilter(), new ChangeSetFilter() {

                        @Override
                        public ChangeSetFilterResult accepts(ChangeSet changeSet) {
                            return new ChangeSetFilterResult(listVisitor.getSeenChangeSets().contains(changeSet), null, null);
                        }
                    });
                }
                logIterator.run(createRollbackVisitor(), new RuntimeEnvironment(database, contexts, labelExpression));
            } finally {
                try {
                    lockService.releaseLock();
                } catch (LockException e) {
                    LOG.severe(MSG_COULD_NOT_RELEASE_LOCK, e);
                }
                Scope.getCurrentScope().getSingleton(ExecutorService.class).setExecutor("jdbc", database, oldTemplate);
                resetServices();
            }
            flushOutputWriter(output);
        }
    });
}
Also used : Executor(liquibase.executor.Executor) LoggingExecutor(liquibase.executor.LoggingExecutor) LockService(liquibase.lockservice.LockService) InvalidExampleException(liquibase.snapshot.InvalidExampleException) IOException(java.io.IOException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) CommandScope(liquibase.command.CommandScope) LoggingExecutor(liquibase.executor.LoggingExecutor) ExecutorService(liquibase.executor.ExecutorService)

Example 12 with LockService

use of liquibase.lockservice.LockService in project liquibase by liquibase.

the class Liquibase method update.

/**
 * Update to count
 *
 * @param  changesToApply
 * @param  contexts
 * @param  labelExpression
 * @throws LiquibaseException
 */
public void update(int changesToApply, Contexts contexts, LabelExpression labelExpression) throws LiquibaseException {
    changeLogParameters.setContexts(contexts);
    changeLogParameters.setLabels(labelExpression);
    runInScope(new Scope.ScopedRunner() {

        @Override
        public void run() throws Exception {
            LockService lockService = LockServiceFactory.getInstance().getLockService(database);
            lockService.waitForLock();
            Operation updateOperation = null;
            BufferedLogService bufferLog = new BufferedLogService();
            DatabaseChangeLog changeLog = null;
            HubUpdater hubUpdater = null;
            try {
                changeLog = getDatabaseChangeLog();
                checkLiquibaseTables(true, changeLog, contexts, labelExpression);
                ChangeLogHistoryServiceFactory.getInstance().getChangeLogService(database).generateDeploymentId();
                changeLog.validate(database, contexts, labelExpression);
                // 
                // Let the user know that they can register for Hub
                // 
                hubUpdater = new HubUpdater(new Date(), changeLog, database);
                hubUpdater.register(changeLogFile);
                // 
                // Create an iterator which will be used with a ListVisitor
                // to grab the list of change sets for the update
                // 
                ChangeLogIterator listLogIterator = new ChangeLogIterator(changeLog, new ShouldRunChangeSetFilter(database), new ContextChangeSetFilter(contexts), new LabelChangeSetFilter(labelExpression), new DbmsChangeSetFilter(database), new IgnoreChangeSetFilter(), new CountChangeSetFilter(changesToApply));
                // 
                // Create or retrieve the Connection
                // Make sure the Hub is available here by checking the return
                // 
                Connection connection = getConnection(changeLog);
                if (connection != null) {
                    updateOperation = hubUpdater.preUpdateHub("UPDATE", "update-count", connection, changeLogFile, contexts, labelExpression, listLogIterator);
                }
                // 
                if (connection != null) {
                    changeExecListener = new HubChangeExecListener(updateOperation, changeExecListener);
                }
                // 
                // Create another iterator to run
                // 
                ChangeLogIterator runChangeLogIterator = new ChangeLogIterator(changeLog, new ShouldRunChangeSetFilter(database), new ContextChangeSetFilter(contexts), new LabelChangeSetFilter(labelExpression), new DbmsChangeSetFilter(database), new IgnoreChangeSetFilter(), new CountChangeSetFilter(changesToApply));
                CompositeLogService compositeLogService = new CompositeLogService(true, bufferLog);
                Scope.child(Scope.Attr.logService.name(), compositeLogService, () -> {
                    runChangeLogIterator.run(createUpdateVisitor(), new RuntimeEnvironment(database, contexts, labelExpression));
                });
                hubUpdater.postUpdateHub(updateOperation, bufferLog);
            } catch (Throwable e) {
                if (hubUpdater != null) {
                    hubUpdater.postUpdateHubExceptionHandling(updateOperation, bufferLog, e.getMessage());
                }
                throw e;
            } finally {
                database.setObjectQuotingStrategy(ObjectQuotingStrategy.LEGACY);
                try {
                    lockService.releaseLock();
                } catch (LockException e) {
                    LOG.severe(MSG_COULD_NOT_RELEASE_LOCK, e);
                }
                resetServices();
                setChangeExecListener(null);
            }
        }
    });
}
Also used : LockService(liquibase.lockservice.LockService) DatabaseConnection(liquibase.database.DatabaseConnection) Connection(liquibase.hub.model.Connection) Operation(liquibase.hub.model.Operation) InvalidExampleException(liquibase.snapshot.InvalidExampleException) IOException(java.io.IOException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) BufferedLogService(liquibase.logging.core.BufferedLogService) CompositeLogService(liquibase.logging.core.CompositeLogService) CommandScope(liquibase.command.CommandScope) HubChangeExecListener(liquibase.hub.listener.HubChangeExecListener)

Example 13 with LockService

use of liquibase.lockservice.LockService in project liquibase by liquibase.

the class Liquibase method rollback.

/**
 * Rollback to tag
 *
 * @param tagToRollBackTo
 * @param rollbackScript
 * @param contexts
 * @param labelExpression
 * @throws LiquibaseException
 */
public void rollback(String tagToRollBackTo, String rollbackScript, Contexts contexts, LabelExpression labelExpression) throws LiquibaseException {
    changeLogParameters.setContexts(contexts);
    changeLogParameters.setLabels(labelExpression);
    runInScope(new Scope.ScopedRunner() {

        @Override
        public void run() throws Exception {
            LockService lockService = LockServiceFactory.getInstance().getLockService(database);
            lockService.waitForLock();
            Operation rollbackOperation = null;
            BufferedLogService bufferLog = new BufferedLogService();
            DatabaseChangeLog changeLog = null;
            Date startTime = new Date();
            HubUpdater hubUpdater = null;
            try {
                changeLog = getDatabaseChangeLog();
                checkLiquibaseTables(false, changeLog, contexts, labelExpression);
                changeLog.validate(database, contexts, labelExpression);
                // 
                // Let the user know that they can register for Hub
                // 
                hubUpdater = new HubUpdater(startTime, changeLog, database);
                hubUpdater.register(changeLogFile);
                // 
                // Create an iterator which will be used with a ListVisitor
                // to grab the list of change sets for the update
                // 
                List<RanChangeSet> ranChangeSetList = database.getRanChangeSetList();
                ChangeLogIterator listLogIterator = new ChangeLogIterator(ranChangeSetList, changeLog, new AfterTagChangeSetFilter(tagToRollBackTo, ranChangeSetList), new AlreadyRanChangeSetFilter(ranChangeSetList), new ContextChangeSetFilter(contexts), new LabelChangeSetFilter(labelExpression), new IgnoreChangeSetFilter(), new DbmsChangeSetFilter(database));
                // 
                // Create or retrieve the Connection
                // Make sure the Hub is available here by checking the return
                // 
                Connection connection = getConnection(changeLog);
                if (connection != null) {
                    rollbackOperation = hubUpdater.preUpdateHub("ROLLBACK", "rollback", connection, changeLogFile, contexts, labelExpression, listLogIterator);
                }
                // 
                if (connection != null) {
                    changeExecListener = new HubChangeExecListener(rollbackOperation, changeExecListener);
                }
                // 
                // Create another iterator to run
                // 
                ChangeLogIterator logIterator = new ChangeLogIterator(ranChangeSetList, changeLog, new AfterTagChangeSetFilter(tagToRollBackTo, ranChangeSetList), new AlreadyRanChangeSetFilter(ranChangeSetList), new ContextChangeSetFilter(contexts), new LabelChangeSetFilter(labelExpression), new IgnoreChangeSetFilter(), new DbmsChangeSetFilter(database));
                CompositeLogService compositeLogService = new CompositeLogService(true, bufferLog);
                if (rollbackScript == null) {
                    Scope.child(Scope.Attr.logService.name(), compositeLogService, () -> {
                        logIterator.run(createRollbackVisitor(), new RuntimeEnvironment(database, contexts, labelExpression));
                    });
                } else {
                    List<ChangeSet> changeSets = determineRollbacks(logIterator, contexts, labelExpression);
                    Map<String, Object> values = new HashMap<>();
                    values.put(Scope.Attr.logService.name(), compositeLogService);
                    values.put(BufferedLogService.class.getName(), bufferLog);
                    Scope.child(values, () -> {
                        executeRollbackScript(rollbackScript, changeSets, contexts, labelExpression);
                    });
                    removeRunStatus(changeSets, contexts, labelExpression);
                }
                hubUpdater.postUpdateHub(rollbackOperation, bufferLog);
            } catch (Throwable t) {
                if (hubUpdater != null) {
                    hubUpdater.postUpdateHubExceptionHandling(rollbackOperation, bufferLog, t.getMessage());
                }
                throw t;
            } finally {
                try {
                    lockService.releaseLock();
                } catch (LockException e) {
                    LOG.severe(MSG_COULD_NOT_RELEASE_LOCK, e);
                }
            }
            resetServices();
            setChangeExecListener(null);
        }
    });
}
Also used : Operation(liquibase.hub.model.Operation) CompositeLogService(liquibase.logging.core.CompositeLogService) HubChangeExecListener(liquibase.hub.listener.HubChangeExecListener) InputStreamList(liquibase.resource.InputStreamList) LockService(liquibase.lockservice.LockService) DatabaseConnection(liquibase.database.DatabaseConnection) Connection(liquibase.hub.model.Connection) InvalidExampleException(liquibase.snapshot.InvalidExampleException) IOException(java.io.IOException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) BufferedLogService(liquibase.logging.core.BufferedLogService) CommandScope(liquibase.command.CommandScope)

Example 14 with LockService

use of liquibase.lockservice.LockService in project liquibase by liquibase.

the class DatabaseTestTemplate method test.

private void test(DatabaseTest test, Set<Database> databasesToTestOn) throws Exception {
    for (Database database : databasesToTestOn) {
        if (database instanceof SQLiteDatabase) {
            //todo: find how to get tests to run correctly on SQLite
            continue;
        }
        JdbcExecutor writeExecutor = new JdbcExecutor();
        writeExecutor.setDatabase(database);
        ExecutorService.getInstance().setExecutor(database, writeExecutor);
        LockService lockService = LockServiceFactory.getInstance().getLockService(database);
        lockService.reset();
        if (database.getConnection() != null) {
            lockService.forceReleaseLock();
        }
        try {
            test.performTest(database);
        } catch (ComparisonFailure e) {
            String newMessage = "Database Test Failure on " + database;
            if (e.getMessage() != null) {
                newMessage += ": " + e.getMessage();
            }
            ComparisonFailure newError = new ComparisonFailure(newMessage, e.getExpected(), e.getActual());
            newError.setStackTrace(e.getStackTrace());
            throw newError;
        } catch (AssertionError e) {
            e.printStackTrace();
            String newMessage = "Database Test Failure on " + database;
            if (e.getMessage() != null) {
                newMessage += ": " + e.getMessage();
            }
            AssertionError newError = new AssertionError(newMessage);
            newError.setStackTrace(e.getStackTrace());
            throw newError;
        } catch (MigrationFailedException e) {
            e.printStackTrace();
            String newMessage = "Database Test Failure on " + database;
            if (e.getMessage() != null) {
                newMessage += ": " + e.getMessage();
            }
            AssertionError newError = new AssertionError(newMessage);
            newError.setStackTrace(e.getStackTrace());
            throw newError;
        } catch (Exception e) {
            e.printStackTrace();
            String newMessage = "Database Test Exception on " + database;
            if (e.getMessage() != null) {
                newMessage += ": " + e.getMessage();
            }
            Exception newError = e.getClass().getConstructor(String.class).newInstance(newMessage);
            if (e.getCause() == null) {
                newError.setStackTrace(e.getStackTrace());
            } else {
                newError.setStackTrace(e.getCause().getStackTrace());
            }
            throw newError;
        } finally {
            if (database.getConnection() != null && !database.getAutoCommitMode()) {
                database.rollback();
            }
        }
    }
}
Also used : LockService(liquibase.lockservice.LockService) MigrationFailedException(liquibase.exception.MigrationFailedException) SQLiteDatabase(liquibase.database.core.SQLiteDatabase) ComparisonFailure(org.junit.ComparisonFailure) SQLiteDatabase(liquibase.database.core.SQLiteDatabase) Database(liquibase.database.Database) JdbcExecutor(liquibase.executor.jvm.JdbcExecutor) MigrationFailedException(liquibase.exception.MigrationFailedException)

Example 15 with LockService

use of liquibase.lockservice.LockService in project liquibase by liquibase.

the class AbstractIntegrationTest method setUp.

@Before
public void setUp() throws Exception {
    openConnection(url);
    if (database != null) {
        if (!database.getConnection().getAutoCommit()) {
            database.rollback();
        }
        SnapshotGeneratorFactory.resetAll();
        ExecutorService.getInstance().reset();
        LockServiceFactory.getInstance().resetAll();
        LockServiceFactory.getInstance().getLockService(database).init();
        ChangeLogHistoryServiceFactory.getInstance().resetAll();
        if (database.getConnection() != null) {
            ((JdbcConnection) database.getConnection()).getUnderlyingConnection().createStatement().executeUpdate("drop table " + database.getDatabaseChangeLogLockTableName());
            database.commit();
        }
        SnapshotGeneratorFactory.resetAll();
        LockService lockService = LockServiceFactory.getInstance().getLockService(database);
        database.dropDatabaseObjects(CatalogAndSchema.DEFAULT);
        if (database.supportsSchemas()) {
            database.dropDatabaseObjects(new CatalogAndSchema((String) null, DatabaseTestContext.ALT_SCHEMA));
        }
        if (supportsAltCatalogTests()) {
            if (database.supportsSchemas() && database.supportsCatalogs()) {
                database.dropDatabaseObjects(new CatalogAndSchema(DatabaseTestContext.ALT_CATALOG, DatabaseTestContext.ALT_SCHEMA));
            } else if (database.supportsCatalogs()) {
                database.dropDatabaseObjects(new CatalogAndSchema(DatabaseTestContext.ALT_SCHEMA, null));
            }
        }
        database.commit();
        SnapshotGeneratorFactory.resetAll();
    }
}
Also used : LockService(liquibase.lockservice.LockService) JdbcConnection(liquibase.database.jvm.JdbcConnection) CatalogAndSchema(liquibase.CatalogAndSchema) Before(org.junit.Before)

Aggregations

LockService (liquibase.lockservice.LockService)27 IOException (java.io.IOException)10 CommandScope (liquibase.command.CommandScope)9 DatabaseConnection (liquibase.database.DatabaseConnection)9 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)8 BufferedLogService (liquibase.logging.core.BufferedLogService)8 InvalidExampleException (liquibase.snapshot.InvalidExampleException)8 LockException (liquibase.exception.LockException)7 HubChangeExecListener (liquibase.hub.listener.HubChangeExecListener)7 Connection (liquibase.hub.model.Connection)7 Operation (liquibase.hub.model.Operation)7 CompositeLogService (liquibase.logging.core.CompositeLogService)7 LiquibaseException (liquibase.exception.LiquibaseException)6 Database (liquibase.database.Database)4 ExecutorService (liquibase.executor.ExecutorService)4 InputStreamList (liquibase.resource.InputStreamList)4 Liquibase (liquibase.Liquibase)3 DatabaseChangeLog (liquibase.changelog.DatabaseChangeLog)3 JdbcConnection (liquibase.database.jvm.JdbcConnection)3 ChangeLogParseException (liquibase.exception.ChangeLogParseException)3