Search in sources :

Example 21 with LockService

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

the class Liquibase method rollback.

/**
 * Rollback count
 *
 * @param changesToRollback
 * @param rollbackScript
 * @param contexts
 * @param labelExpression
 * @throws LiquibaseException
 */
public void rollback(int changesToRollback, 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
                // 
                ChangeLogIterator listLogIterator = new ChangeLogIterator(database.getRanChangeSetList(), changeLog, new AlreadyRanChangeSetFilter(database.getRanChangeSetList()), new ContextChangeSetFilter(contexts), new LabelChangeSetFilter(labelExpression), new DbmsChangeSetFilter(database), new IgnoreChangeSetFilter(), new CountChangeSetFilter(changesToRollback));
                // 
                // 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-count", connection, changeLogFile, contexts, labelExpression, listLogIterator);
                }
                // 
                if (connection != null) {
                    changeExecListener = new HubChangeExecListener(rollbackOperation, changeExecListener);
                }
                // 
                // Create another iterator to run
                // 
                ChangeLogIterator logIterator = new ChangeLogIterator(database.getRanChangeSetList(), changeLog, new AlreadyRanChangeSetFilter(database.getRanChangeSetList()), new ContextChangeSetFilter(contexts), new LabelChangeSetFilter(labelExpression), new DbmsChangeSetFilter(database), new IgnoreChangeSetFilter(), new CountChangeSetFilter(changesToRollback));
                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("Error releasing 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 22 with LockService

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

the class Liquibase method update.

/**
 * Update to tag
 *
 * @param   tag                             Tag to update for
 * @param   contexts
 * @param   labelExpression
 * @throws  LiquibaseException
 */
public void update(String tag, Contexts contexts, LabelExpression labelExpression) throws LiquibaseException {
    if (tag == null) {
        update(contexts, labelExpression);
        return;
    }
    changeLogParameters.setContexts(contexts);
    changeLogParameters.setLabels(labelExpression);
    runInScope(new Scope.ScopedRunner() {

        @Override
        public void run() throws Exception {
            LockService lockService = LockServiceFactory.getInstance().getLockService(database);
            lockService.waitForLock();
            HubUpdater hubUpdater = null;
            Operation updateOperation = null;
            BufferedLogService bufferLog = new BufferedLogService();
            DatabaseChangeLog changeLog = 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
                // 
                List<RanChangeSet> ranChangeSetList = database.getRanChangeSetList();
                ChangeLogIterator listLogIterator = new ChangeLogIterator(changeLog, new ShouldRunChangeSetFilter(database), new ContextChangeSetFilter(contexts), new LabelChangeSetFilter(labelExpression), new DbmsChangeSetFilter(database), new IgnoreChangeSetFilter(), new UpToTagChangeSetFilter(tag, ranChangeSetList));
                // 
                // 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-to-tag", 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 UpToTagChangeSetFilter(tag, ranChangeSetList));
                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) InputStreamList(liquibase.resource.InputStreamList)

Example 23 with LockService

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

the class Liquibase method changeLogSync.

/**
 * Changelogsync or changelogsync to tag
 *
 * @param tag
 * @param contexts
 * @param labelExpression
 * @throws LiquibaseException
 */
public void changeLogSync(String tag, 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 changeLogSyncOperation = 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 = buildChangeLogIterator(tag, changeLog, contexts, labelExpression);
                // 
                // Create or retrieve the Connection
                // Make sure the Hub is available here by checking the return
                // 
                Connection connection = getConnection(changeLog);
                if (connection != null) {
                    String operationCommand = (tag == null ? "changelog-sync" : "changelog-sync-to-tag");
                    changeLogSyncOperation = hubUpdater.preUpdateHub("CHANGELOGSYNC", operationCommand, connection, changeLogFile, contexts, labelExpression, listLogIterator);
                }
                // 
                if (connection != null) {
                    changeLogSyncListener = new HubChangeExecListener(changeLogSyncOperation, changeExecListener);
                }
                ChangeLogIterator runChangeLogIterator = buildChangeLogIterator(tag, changeLog, contexts, labelExpression);
                CompositeLogService compositeLogService = new CompositeLogService(true, bufferLog);
                Scope.child(Scope.Attr.logService.name(), compositeLogService, () -> {
                    runChangeLogIterator.run(new ChangeLogSyncVisitor(database, changeLogSyncListener), new RuntimeEnvironment(database, contexts, labelExpression));
                });
                hubUpdater.postUpdateHub(changeLogSyncOperation, bufferLog);
            } catch (Exception e) {
                if (changeLogSyncOperation != null) {
                    hubUpdater.postUpdateHubExceptionHandling(changeLogSyncOperation, bufferLog, e.getMessage());
                }
                throw e;
            } finally {
                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 24 with LockService

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

the class Liquibase method clearCheckSums.

/**
 * Sets checksums to null so they will be repopulated next run
 */
public void clearCheckSums() throws LiquibaseException {
    LOG.info("Clearing database change log checksums");
    runInScope(new Scope.ScopedRunner() {

        @Override
        public void run() throws Exception {
            LockService lockService = LockServiceFactory.getInstance().getLockService(database);
            lockService.waitForLock();
            try {
                checkLiquibaseTables(false, null, new Contexts(), new LabelExpression());
                UpdateStatement updateStatement = new UpdateStatement(getDatabase().getLiquibaseCatalogName(), getDatabase().getLiquibaseSchemaName(), getDatabase().getDatabaseChangeLogTableName());
                updateStatement.addNewColumnValue("MD5SUM", null);
                Scope.getCurrentScope().getSingleton(ExecutorService.class).getExecutor("jdbc", database).execute(updateStatement);
                getDatabase().commit();
            } finally {
                try {
                    lockService.releaseLock();
                } catch (LockException e) {
                    LOG.severe(MSG_COULD_NOT_RELEASE_LOCK, e);
                }
            }
            resetServices();
        }
    });
}
Also used : UpdateStatement(liquibase.statement.core.UpdateStatement) CommandScope(liquibase.command.CommandScope) LockService(liquibase.lockservice.LockService) ExecutorService(liquibase.executor.ExecutorService) InvalidExampleException(liquibase.snapshot.InvalidExampleException) IOException(java.io.IOException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException)

Example 25 with LockService

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

the class AbstractIntegrationTest method wipeDatabase.

/**
 * Wipes all Liquibase schemas in the database before testing starts. This includes the DATABASECHANGELOG/LOCK
 * tables.
 */
protected void wipeDatabase() {
    emptySchemas.clear();
    try {
        // TODO the cleaner solution would be to have a noCachingHasObject() Method in SnapshotGeneratorFactory
        try {
            if (database.getConnection() != null) {
                String sql = "DROP TABLE " + database.getDatabaseChangeLogLockTableName();
                for (SqlListener listener : Scope.getCurrentScope().getListeners(SqlListener.class)) {
                    listener.writeSqlWillRun(sql);
                }
                ((JdbcConnection) database.getConnection()).getUnderlyingConnection().createStatement().executeUpdate(sql);
                database.commit();
            }
        } catch (SQLException e) {
            if (database instanceof PostgresDatabase) {
                // throws "current transaction is aborted" unless we roll back the connection
                database.rollback();
            }
        }
        SnapshotGeneratorFactory.resetAll();
        LockService lockService = LockServiceFactory.getInstance().getLockService(database);
        emptyTestSchema(CatalogAndSchema.DEFAULT.getCatalogName(), CatalogAndSchema.DEFAULT.getSchemaName(), database);
        SnapshotGeneratorFactory factory = SnapshotGeneratorFactory.getInstance();
        if (database.supportsSchemas()) {
            emptyTestSchema(null, ALT_SCHEMA, database);
        }
        if (supportsAltCatalogTests()) {
            if (database.supportsSchemas() && database.supportsCatalogs()) {
                emptyTestSchema(ALT_CATALOG, ALT_SCHEMA, database);
            }
        }
        /*
             * There is a special treatment for identifiers in the case when (a) the RDBMS does NOT support
             * schemas AND (b) the RDBMS DOES support catalogs AND (c) someone uses "schemaName=..." in a
             * Liquibase ChangeSet. In this case, AbstractJdbcDatabase.escapeObjectName assumes the author
             * was intending to write "catalog=..." and transparently rewrites the expression.
             * For us, this means that we have to wipe both ALT_SCHEMA and ALT_CATALOG to be sure we
             * are doing a thorough cleanup.
             */
        CatalogAndSchema[] alternativeLocations = new CatalogAndSchema[] { new CatalogAndSchema(ALT_CATALOG, null), new CatalogAndSchema(null, ALT_SCHEMA), new CatalogAndSchema("LBCAT2", database.getDefaultSchemaName()), new CatalogAndSchema(null, "LBCAT2"), new CatalogAndSchema("lbcat2", database.getDefaultSchemaName()), new CatalogAndSchema(null, "lbcat2") };
        for (CatalogAndSchema location : alternativeLocations) {
            emptyTestSchema(location.getCatalogName(), location.getSchemaName(), database);
        }
        database.commit();
        SnapshotGeneratorFactory.resetAll();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Also used : PostgresDatabase(liquibase.database.core.PostgresDatabase) SqlListener(liquibase.listener.SqlListener) LockService(liquibase.lockservice.LockService) SQLException(java.sql.SQLException) JdbcConnection(liquibase.database.jvm.JdbcConnection) SnapshotGeneratorFactory(liquibase.snapshot.SnapshotGeneratorFactory) ValidationFailedException(liquibase.exception.ValidationFailedException) ChangeLogParseException(liquibase.exception.ChangeLogParseException) SQLException(java.sql.SQLException) DatabaseException(liquibase.exception.DatabaseException) LiquibaseException(liquibase.exception.LiquibaseException)

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