Java Code Examples for liquibase.changelog.ChangeSet

The following examples show how to use liquibase.changelog.ChangeSet. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: quarkus   Source File: LiquibaseFunctionalityResource.java    License: Apache License 2.0 6 votes vote down vote up
@GET
@Path("update")
public String doUpdateAuto() {
    assertCommandFactoryResolvesProperly();

    try (Liquibase liquibase = liquibaseFactory.createLiquibase()) {
        liquibase.update(liquibaseFactory.createContexts(), liquibaseFactory.createLabels());
        List<ChangeSetStatus> status = liquibase.getChangeSetStatuses(liquibaseFactory.createContexts(),
                liquibaseFactory.createLabels());
        List<ChangeSetStatus> changeSets = Objects.requireNonNull(status,
                "ChangeSetStatus is null! Database update was not applied");
        return changeSets.stream()
                .filter(ChangeSetStatus::getPreviouslyRan)
                .map(ChangeSetStatus::getChangeSet)
                .map(ChangeSet::getId)
                .collect(Collectors.joining(","));
    } catch (Exception ex) {
        throw new WebApplicationException(ex.getMessage(), ex);
    }
}
 
Example 2
@Test
@DisplayName("Clean at start correctly")
public void testLiquibaseConfigInjection() throws Exception {
    try (Connection connection = defaultDataSource.getConnection(); Statement stat = connection.createStatement()) {
        try (ResultSet executeQuery = stat
                .executeQuery("select * from fake_existing_tbl")) {
            fail("fake_existing_tbl should not exist");
        } catch (JdbcSQLException e) {
            // expected fake_existing_tbl does not exist
        }
    }

    try (Liquibase liquibase = liquibaseFactory.createLiquibase()) {
        List<ChangeSetStatus> status = liquibase.getChangeSetStatuses(liquibaseFactory.createContexts(),
                liquibaseFactory.createLabels());
        assertNotNull(status, "Status is null");
        assertEquals(1, status.size(), "The set of changes is not null");
        assertTrue(status.get(0).getWillRun());

        List<ChangeSet> unrun = liquibase.listUnrunChangeSets(liquibaseFactory.createContexts(),
                liquibaseFactory.createLabels());
        assertNotNull(unrun, "Unrun is null");
        assertEquals(1, status.size(), "The set of unrun changes is not null");
    }
}
 
Example 3
@Override
public Sql[] generateSql(RemoveChangeSetRanStatusStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) {
    ChangeSet changeSet = statement.getChangeSet();
    String tmpTable = UUID.randomUUID().toString().replaceAll("-", "");
    String catalogName = database.getLiquibaseCatalogName();
    String schemaName = database.getDefaultSchemaName();
    String tableName = database.getDatabaseChangeLogTableName();
    CreateTableAsSelectStatement createTableAsSelectStatement = new CreateTableAsSelectStatement(catalogName, schemaName, tableName, tmpTable)
            .addColumnNames("ID", "AUTHOR", "FILENAME", "DATEEXECUTED", "ORDEREXECUTED", "EXECTYPE", "MD5SUM", "DESCRIPTION", "COMMENTS", "TAG", "LIQUIBASE", "CONTEXTS", "LABELS", "DEPLOYMENT_ID")
            .setWhereCondition(database.escapeObjectName("ID", Column.class) + " != ? " +
                    "AND " + database.escapeObjectName("FILENAME", Column.class) + " != ?")
            .addWhereParameters(changeSet.getId(), changeSet.getFilePath());

    return CustomSqlGenerator.generateSql(database,
            createTableAsSelectStatement,
            new DropTableStatement(catalogName, schemaName, tableName, false),
            new RenameTableStatement(catalogName, schemaName, tmpTable, tableName));
}
 
Example 4
@Override
    public void tag(final String tagString) throws DatabaseException {
        Database database = getDatabase();
        Executor executor = ExecutorService.getInstance().getExecutor(database);
        try {
            int totalRows = ExecutorService.getInstance().getExecutor(database).queryForInt(new SelectFromDatabaseChangeLogStatement(new ColumnConfig().setName("COUNT(*)", true)));
            if (totalRows == 0) {
                ChangeSet emptyChangeSet = new ChangeSet(String.valueOf(new Date().getTime()), "liquibase", false, false, "liquibase-internal", null, null, getDatabase().getObjectQuotingStrategy(), null);
                this.setExecType(emptyChangeSet, ChangeSet.ExecType.EXECUTED);
            }

//            Timestamp lastExecutedDate = (Timestamp) this.getExecutor().queryForObject(createChangeToTagSQL(), Timestamp.class);
            executor.execute(new TagDatabaseStatement(tagString));
            getDatabase().commit();

            if (this.ranChangeSetList != null) {
                ranChangeSetList.get(ranChangeSetList.size() - 1).setTag(tagString);
            }
        } catch (Exception e) {
            throw new DatabaseException(e);
        }
    }
 
Example 5
@Override
public Sql[] generateSql(RemoveChangeSetRanStatusStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) {
    ChangeSet changeSet = statement.getChangeSet();
    String tmpTable = UUID.randomUUID().toString().replaceAll("-", "");
    String catalogName = database.getLiquibaseCatalogName();
    String schemaName = database.getDefaultSchemaName();
    String tableName = database.getDatabaseChangeLogTableName();
    CreateTableAsSelectStatement createTableAsSelectStatement = new CreateTableAsSelectStatement(catalogName, schemaName, tableName, tmpTable)
            .addColumnNames("ID", "AUTHOR", "FILENAME", "DATEEXECUTED", "ORDEREXECUTED", "EXECTYPE", "MD5SUM", "DESCRIPTION", "COMMENTS", "TAG", "LIQUIBASE", "CONTEXTS", "LABELS", "DEPLOYMENT_ID")
            .setWhereCondition(" NOT (" + database.escapeObjectName("ID", Column.class) + " = ? " +
                    "AND " + database.escapeObjectName("FILENAME", Column.class) + " = ?)")
            .addWhereParameters(changeSet.getId(), changeSet.getFilePath());

    return CustomSqlGenerator.generateSql(database,
            UserSessionSettings.syncDdlStart(),
            createTableAsSelectStatement,
            new DropTableStatement(catalogName, schemaName, tableName, false),
            new RenameTableStatement(catalogName, schemaName, tmpTable, tableName),
            UserSessionSettings.syncDdlStop());
}
 
Example 6
Source Project: liquibase-spatial   Source File: LiquibaseIT.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Tests Liquibase updating and rolling back the database.
 *
 * @param changeLogFile
 *           the database change log to use in the {@link Liquibase#update(Contexts) update}.
 * @throws LiquibaseException
 *            if Liquibase fails to initialize or run the update.
 * @throws SQLException
 *            if unable to get the database connection.
 */
@Test(dataProvider = "databaseUrlProvider", enabled = false)
public void testLiquibaseUpdateTestingRollback(final String changeLogFile)
      throws LiquibaseException, SQLException {
   final Connection connection = getConnection();
   final JdbcConnection jdbcConnection = new JdbcConnection(connection);
   try {
      final ResourceAccessor resourceAccessor = new ClassLoaderResourceAccessor();
      final Liquibase liquibase = createLiquibase(changeLogFile, resourceAccessor,
            jdbcConnection);
      final Contexts contexts = null;
      final LabelExpression labels = new LabelExpression();
      liquibase.updateTestingRollback(contexts, labels);
      final List<ChangeSet> unrunChangeSets = liquibase.listUnrunChangeSets(contexts, labels);
      assertTrue(unrunChangeSets.isEmpty(), "All change sets should have run");
   } finally {
      jdbcConnection.rollback();
      jdbcConnection.close();
   }
}
 
Example 7
Source Project: liquibase-spatial   Source File: LiquibaseIT.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Tests Liquibase updating the database.
 *
 * @param changeLogFile
 *           the database change log to use in the {@link Liquibase#update(Contexts) update}.
 * @throws LiquibaseException
 *            if Liquibase fails to initialize or run the update.
 * @throws SQLException
 *            if unable to get the database connection.
 */
@Test(dataProvider = "databaseUrlProvider")
public void testLiquibaseUpdate(final String changeLogFile) throws LiquibaseException,
SQLException {
   final Connection connection = getConnection();
   final JdbcConnection jdbcConnection = new JdbcConnection(connection);
   try {
      final ResourceAccessor resourceAccessor = new ClassLoaderResourceAccessor();
      final Liquibase liquibase = createLiquibase(changeLogFile, resourceAccessor,
            jdbcConnection);
      final Contexts contexts = null;
      liquibase.update(contexts);
      final List<ChangeSet> unrunChangeSets = liquibase.listUnrunChangeSets(contexts);
      assertTrue(unrunChangeSets.isEmpty(), "All change sets should have run");
   } finally {
      jdbcConnection.rollback();
      jdbcConnection.close();
   }
}
 
Example 8
Source Project: keycloak   Source File: LiquibaseJpaUpdaterProvider.java    License: Apache License 2.0 6 votes vote down vote up
protected Status validateChangeSet(Liquibase liquibase, String changelog) throws LiquibaseException {
    final Status result;
    List<ChangeSet> changeSets = getLiquibaseUnrunChangeSets(liquibase);

    if (!changeSets.isEmpty()) {
        if (changeSets.size() == liquibase.getDatabaseChangeLog().getChangeSets().size()) {
            result = Status.EMPTY;
        } else {
            logger.debugf("Validation failed. Database is not up-to-date for changelog %s", changelog);
            result = Status.OUTDATED;
        }
    } else {
        logger.debugf("Validation passed. Database is up-to-date for changelog %s", changelog);
        result = Status.VALID;
    }

    // Needs to restart liquibase services to clear ChangeLogHistoryServiceFactory.getInstance().
    // See https://issues.jboss.org/browse/KEYCLOAK-3769 for discussion relevant to why reset needs to be here
    resetLiquibaseServices(liquibase);

    return result;
}
 
Example 9
Source Project: keycloak   Source File: QuarkusJpaUpdaterProvider.java    License: Apache License 2.0 6 votes vote down vote up
protected Status validateChangeSet(Liquibase liquibase, String changelog) throws LiquibaseException {
    final Status result;
    List<ChangeSet> changeSets = getLiquibaseUnrunChangeSets(liquibase);

    if (!changeSets.isEmpty()) {
        if (changeSets.size() == liquibase.getDatabaseChangeLog().getChangeSets().size()) {
            result = Status.EMPTY;
        } else {
            logger.debugf("Validation failed. Database is not up-to-date for changelog %s", changelog);
            result = Status.OUTDATED;
        }
    } else {
        logger.debugf("Validation passed. Database is up-to-date for changelog %s", changelog);
        result = Status.VALID;
    }

    // Needs to restart liquibase services to clear ChangeLogHistoryServiceFactory.getInstance().
    // See https://issues.jboss.org/browse/KEYCLOAK-3769 for discussion relevant to why reset needs to be here
    resetLiquibaseServices(liquibase);

    return result;
}
 
Example 10
Source Project: keycloak   Source File: QuarkusJpaUpdaterProvider.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private List<ChangeSet> getLiquibaseUnrunChangeSets(Liquibase liquibase) {
    // we don't need to fetch change sets if they were previously obtained
    return changeSets.computeIfAbsent(liquibase.getChangeLogFile(), new Function<String, List<ChangeSet>>() {
        @Override
        public List<ChangeSet> apply(String s) {
            // TODO tracked as: https://issues.jboss.org/browse/KEYCLOAK-3730
            // TODO: When https://liquibase.jira.com/browse/CORE-2919 is resolved, replace the following two lines with:
            // List<ChangeSet> changeSets = liquibase.listUnrunChangeSets((Contexts) null, new LabelExpression(), false);
            Method listUnrunChangeSets = Reflections.findDeclaredMethod(Liquibase.class, "listUnrunChangeSets", Contexts.class, LabelExpression.class, boolean.class);

            return Reflections
                    .invokeMethod(true, listUnrunChangeSets, List.class, liquibase, (Contexts) null, new LabelExpression(), false);
        }
    });
}
 
Example 11
Source Project: quarkus   Source File: LiquibaseProcessor.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Finds all resource files for the given change log file
 */
private Set<String> findAllChangeLogs(String file, ChangeLogParserFactory changeLogParserFactory,
        ClassLoaderResourceAccessor classLoaderResourceAccessor,
        ChangeLogParameters changeLogParameters) {
    try {
        ChangeLogParser parser = changeLogParserFactory.getParser(file, classLoaderResourceAccessor);
        DatabaseChangeLog changelog = parser.parse(file, changeLogParameters, classLoaderResourceAccessor);

        if (changelog != null) {
            Set<String> result = new LinkedHashSet<>();
            // get all changeSet files
            for (ChangeSet changeSet : changelog.getChangeSets()) {
                result.add(changeSet.getFilePath());

                // get all parents of the changeSet
                DatabaseChangeLog parent = changeSet.getChangeLog();
                while (parent != null) {
                    result.add(parent.getFilePath());
                    parent = parent.getParentChangeLog();
                }
            }
            result.add(changelog.getFilePath());
            return result;
        }
    } catch (LiquibaseException ex) {
        throw new IllegalStateException(ex);
    }
    return Collections.emptySet();
}
 
Example 12
@Override
public Sql[] generateSql(MarkChangeSetRanStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) {
    ChangeSet changeSet = statement.getChangeSet();

    SqlStatement runStatement;
    try {
        if (statement.getExecType().equals(ChangeSet.ExecType.FAILED) || statement.getExecType().equals(ChangeSet.ExecType.SKIPPED)) {
            return new Sql[0]; //don't mark
        }

        String tag = null;
        for (Change change : changeSet.getChanges()) {
            if (change instanceof TagDatabaseChange) {
                TagDatabaseChange tagChange = (TagDatabaseChange) change;
                tag = tagChange.getTag();
            }
        }

        runStatement = new HiveInsertStatement(database.getLiquibaseCatalogName(), database.getLiquibaseSchemaName(), database.getDatabaseChangeLogTableName())
                .addColumnValue(changeSet.getId())
                .addColumnValue(changeSet.getAuthor())
                .addColumnValue(changeSet.getFilePath())
                .addColumnValue(DateTimeUtils.getCurrentTS("yyyy-MM-dd HH:mm:ss"))
                .addColumnValue(ChangeLogHistoryServiceFactory.getInstance().getChangeLogService(database).getNextSequenceValue())
                .addColumnValue(statement.getExecType().value)
                .addColumnValue(changeSet.generateCheckSum().toString())
                .addColumnValue(changeSet.getDescription())
                .addColumnValue(StringUtils.trimToEmpty(changeSet.getComments()))
                .addColumnValue(tag == null ? "NULL" : tag)
                .addColumnValue(ChangeLogHistoryServiceFactory.getInstance().getChangeLogService(database).getDeploymentId())
                .addColumnValue(changeSet.getContexts() == null || changeSet.getContexts().isEmpty() ? null : changeSet.getContexts().toString())
                .addColumnValue(changeSet.getLabels() == null || changeSet.getLabels().isEmpty() ? null : changeSet.getLabels().toString())
                .addColumnValue(LiquibaseUtil.getBuildVersion());
    } catch (LiquibaseException e) {
        throw new UnexpectedLiquibaseException(e);
    }

    return SqlGeneratorFactory.getInstance().generateSql(runStatement, database);
}
 
Example 13
@Override
protected void replaceChecksum(ChangeSet changeSet) throws DatabaseException {
    ExecutorService.getInstance().getExecutor(getDatabase()).execute(new UpdateChangeSetChecksumStatement(changeSet));

    getDatabase().commit();
    reset();
}
 
Example 14
@Override
public RanChangeSet getRanChangeSet(final ChangeSet changeSet) throws DatabaseException, DatabaseHistoryException {
    if (!hasDatabaseChangeLogTable()) {
        return null;
    }

    return super.getRanChangeSet(changeSet);
}
 
Example 15
@Override
public void setExecType(ChangeSet changeSet, ChangeSet.ExecType execType) throws DatabaseException {
    Database database = getDatabase();

    ExecutorService.getInstance().getExecutor(database).execute(new MarkChangeSetRanStatement(changeSet, execType));
    getDatabase().commit();
    if (this.ranChangeSetList != null) {
        this.ranChangeSetList.add(new RanChangeSet(changeSet, execType, null, null));
    }

}
 
Example 16
@Override
public void removeFromHistory(final ChangeSet changeSet) throws DatabaseException {
    Database database = getDatabase();
    ExecutorService.getInstance().getExecutor(database).execute(new RemoveChangeSetRanStatusStatement(changeSet));
    getDatabase().commit();

    if (this.ranChangeSetList != null) {
        this.ranChangeSetList.remove(new RanChangeSet(changeSet));
    }
}
 
Example 17
Source Project: liquibase-percona   Source File: ChangeLogParserTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testReadLiquibaseUsePerconaFlagYAML() throws Exception {
    DatabaseChangeLog changelog = loadChangeLog("test-changelog.yaml");
    Assertions.assertEquals(2, changelog.getChangeSets().size());
    ChangeSet addColumnChangeset = changelog.getChangeSets().get(1);
    Change change = addColumnChangeset.getChanges().get(0);
    Assertions.assertEquals(PerconaAddColumnChange.class, change.getClass());
    Assertions.assertNotNull(((PerconaAddColumnChange)change).getUsePercona());
    Assertions.assertFalse(((PerconaAddColumnChange)change).getUsePercona());
}
 
Example 18
Source Project: liquibase-percona   Source File: ChangeLogParserTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testReadLiquibaseUsePerconaFlagXML() throws Exception {
    DatabaseChangeLog changelog = loadChangeLog("test-changelog.xml");
    Assertions.assertEquals(2, changelog.getChangeSets().size());
    ChangeSet addColumnChangeset = changelog.getChangeSets().get(1);
    Change change = addColumnChangeset.getChanges().get(0);
    Assertions.assertEquals(PerconaAddColumnChange.class, change.getClass());
    Assertions.assertNotNull(((PerconaAddColumnChange)change).getUsePercona());
    Assertions.assertFalse(((PerconaAddColumnChange)change).getUsePercona());
}
 
Example 19
Source Project: liquibase-percona   Source File: ChangeLogParserTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testReadLiquibaseUsePerconaFlagXMLPercona() throws Exception {
    DatabaseChangeLog changelog = loadChangeLog("test-changelog-percona.xml");
    Assertions.assertEquals(2, changelog.getChangeSets().size());
    ChangeSet addColumnChangeset = changelog.getChangeSets().get(1);
    Change change = addColumnChangeset.getChanges().get(0);
    Assertions.assertEquals(PerconaAddColumnChange.class, change.getClass());
    Assertions.assertNotNull(((PerconaAddColumnChange)change).getUsePercona());
    Assertions.assertFalse(((PerconaAddColumnChange)change).getUsePercona());
}
 
Example 20
Source Project: iaf   Source File: LiquibaseImpl.java    License: Apache License 2.0 5 votes vote down vote up
public void update() {
	List<String> changes = new ArrayList<String>();
	try {
		List<ChangeSet> changeSets = liquibase.listUnrunChangeSets(contexts, labelExpression);
		for (ChangeSet changeSet : changeSets) {
			changes.add("LiquiBase applying change ["+changeSet.getId()+":"+changeSet.getAuthor()+"] description ["+changeSet.getDescription()+"]");
		}

		if(changeSets.size() > 0) {
			liquibase.update(contexts);

			ChangeSet lastChange = changeSets.get(changeSets.size()-1);
			String tag = lastChange.getId() + ":" + lastChange.getAuthor();
			tag(tag);

			if(changes.size() > 1) {
				log("LiquiBase applied ["+changes.size()+"] change(s) and added tag ["+tag+"]");
			}
			else {
				for (String change : changes) {
					log(change + " tag ["+tag+"]");
				}
			}
		}
	}
	catch (Exception e) {
		String errorMsg = "Error running LiquiBase update for configuration ["+configurationName+"]. Failed to execute ["+changes.size()+"] change(s): ";
		errorMsg += e.getMessage();
		ConfigurationWarnings.add(log, errorMsg, e);
	}
}
 
Example 21
Source Project: keycloak   Source File: LiquibaseJpaUpdaterProvider.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private List<ChangeSet> getLiquibaseUnrunChangeSets(Liquibase liquibase) {
    // TODO tracked as: https://issues.jboss.org/browse/KEYCLOAK-3730
    // TODO: When https://liquibase.jira.com/browse/CORE-2919 is resolved, replace the following two lines with:
    // List<ChangeSet> changeSets = liquibase.listUnrunChangeSets((Contexts) null, new LabelExpression(), false);
    Method listUnrunChangeSets = Reflections.findDeclaredMethod(Liquibase.class, "listUnrunChangeSets", Contexts.class, LabelExpression.class, boolean.class);
    return Reflections.invokeMethod(true, listUnrunChangeSets, List.class, liquibase, (Contexts) null, new LabelExpression(), false);
}
 
Example 22
@Override
public void dropDatabaseObjects(final CatalogAndSchema schemaToDrop) throws LiquibaseException {
    ObjectQuotingStrategy currentStrategy = this.getObjectQuotingStrategy();
    this.setObjectQuotingStrategy(ObjectQuotingStrategy.QUOTE_ALL_OBJECTS);
    try {
        DatabaseSnapshot snapshot;
        try {
            final SnapshotControl snapshotControl = new SnapshotControl(this);
            final Set<Class<? extends DatabaseObject>> typesToInclude = snapshotControl.getTypesToInclude();

            //We do not need to remove indexes and primary/unique keys explicitly. They should be removed
            //as part of tables.
            typesToInclude.remove(Index.class);
            typesToInclude.remove(PrimaryKey.class);
            typesToInclude.remove(UniqueConstraint.class);

            if (supportsForeignKeyDisable()) {
                //We do not remove ForeignKey because they will be disabled and removed as parts of tables.
                typesToInclude.remove(ForeignKey.class);
            }

            final long createSnapshotStarted = System.currentTimeMillis();
            snapshot = SnapshotGeneratorFactory.getInstance().createSnapshot(schemaToDrop, this, snapshotControl);
            LogService.getLog(getClass()).debug(LogType.LOG, String.format("Database snapshot generated in %d ms. Snapshot includes: %s", System.currentTimeMillis() - createSnapshotStarted, typesToInclude));
        } catch (LiquibaseException e) {
            throw new UnexpectedLiquibaseException(e);
        }

        final long changeSetStarted = System.currentTimeMillis();
        CompareControl compareControl = new CompareControl(
            new CompareControl.SchemaComparison[]{
                new CompareControl.SchemaComparison(
                    CatalogAndSchema.DEFAULT,
                    schemaToDrop)},
            snapshot.getSnapshotControl().getTypesToInclude());
        DiffResult diffResult = DiffGeneratorFactory.getInstance().compare(
            new EmptyDatabaseSnapshot(this),
            snapshot,
            compareControl);

        List<ChangeSet> changeSets = new DiffToChangeLog(diffResult, new DiffOutputControl(true, true, false, null).addIncludedSchema(schemaToDrop)).generateChangeSets();
        LogService.getLog(getClass()).debug(LogType.LOG, String.format("ChangeSet to Remove Database Objects generated in %d ms.", System.currentTimeMillis() - changeSetStarted));

        boolean previousAutoCommit = this.getAutoCommitMode();
        this.commit(); //clear out currently executed statements
        this.setAutoCommit(false); //some DDL doesn't work in autocommit mode
        final boolean reEnableFK = supportsForeignKeyDisable() && disableForeignKeyChecks();
        try {
            for (ChangeSet changeSet : changeSets) {
                changeSet.setFailOnError(false);
                for (Change change : changeSet.getChanges()) {
                    if (change instanceof DropTableChange) {
                        ((DropTableChange) change).setCascadeConstraints(true);
                    }
                    SqlStatement[] sqlStatements = change.generateStatements(this);
                    for (SqlStatement statement : sqlStatements) {
                        ExecutorService.getInstance().getExecutor(this).execute(statement);
                    }

                }
                this.commit();
            }
        } finally {
            if (reEnableFK) {
                enableForeignKeyChecks();
            }
        }

        ChangeLogHistoryServiceFactory.getInstance().getChangeLogService(this).destroy();
        LockServiceFactory.getInstance().getLockService(this).destroy();

        this.setAutoCommit(previousAutoCommit);
        LogService.getLog(getClass()).info(LogType.LOG, String.format("Successfully deleted all supported object types in schema %s.", schemaToDrop.toString()));
    } finally {
        this.setObjectQuotingStrategy(currentStrategy);
        this.commit();
    }
}
 
Example 23
@Override
public ChangeSet.RunStatus getRunStatus(final ChangeSet changeSet) throws DatabaseException, DatabaseHistoryException {
    return ChangeLogHistoryServiceFactory.getInstance().getChangeLogService(this).getRunStatus(changeSet);
}
 
Example 24
@Override
public RanChangeSet getRanChangeSet(final ChangeSet changeSet) throws DatabaseException, DatabaseHistoryException {
    return ChangeLogHistoryServiceFactory.getInstance().getChangeLogService(this).getRanChangeSet(changeSet);
}
 
Example 25
@Override
public Date getRanDate(final ChangeSet changeSet) throws DatabaseException, DatabaseHistoryException {
    return ChangeLogHistoryServiceFactory.getInstance().getChangeLogService(this).getRanDate(changeSet);
}
 
Example 26
@Override
public void markChangeSetExecStatus(final ChangeSet changeSet, final ChangeSet.ExecType execType) throws DatabaseException {
    ChangeLogHistoryServiceFactory.getInstance().getChangeLogService(this).setExecType(changeSet, execType);
}
 
Example 27
@Override
public void removeRanStatus(final ChangeSet changeSet) throws DatabaseException {
    ChangeLogHistoryServiceFactory.getInstance().getChangeLogService(this).removeFromHistory(changeSet);
}
 
Example 28
@Override
public void setChangeSet (ChangeSet changeSet)
{
}
 
Example 29
Source Project: telekom-workflow-engine   Source File: Slf4jLogger.java    License: MIT License 4 votes vote down vote up
@Override
public void setChangeSet( ChangeSet changeSet ){
    changeSetName = (changeSet == null) ? null : changeSet.toString( false );
}
 
Example 30
Source Project: liquibase-percona   Source File: PerconaChangeUtil.java    License: Apache License 2.0 4 votes vote down vote up
public static SqlStatement[] generateStatements(PerconaChange change,
        Database database, SqlStatement[] originalStatements) {

    String changeSetId = "unknown changeset id";
    if (change instanceof Change) {
        ChangeSet changeSet = ((Change)change).getChangeSet();
        if (changeSet != null) {
            changeSetId = changeSet.getId() + ":" + changeSet.getAuthor();
        }
    }

    if (change.getUsePercona() == null && !Configuration.getDefaultOn()) {
        log.debug("Not using percona toolkit, because property " + Configuration.DEFAULT_ON + " is false. " + changeSetId + ":" + change.getChangeName());
        return originalStatements;
    }
    if (change.getUsePercona() != null && !change.getUsePercona()) {
        log.debug("Not using percona toolkit, because usePercona flag is false for " + changeSetId + ":" + change.getChangeName());
        return originalStatements;
    }
    if (Configuration.skipChange(change.getChangeName())) {
        maybeLog("Not using percona toolkit, because skipChange for "
                + change.getChangeName() + " is active (property: " + Configuration.SKIP_CHANGES + ")!");
        return originalStatements;
    }

    List<SqlStatement> statements = new ArrayList<SqlStatement>(Arrays.asList(originalStatements));

    if (database instanceof MySQLDatabase) {
        if (PTOnlineSchemaChangeStatement.isAvailable()) {
            PTOnlineSchemaChangeStatement statement = new PTOnlineSchemaChangeStatement(
                    change.getTargetDatabaseName(),
                    change.getTargetTableName(),
                    change.generateAlterStatement(database));

            if (isDryRun(database)) {
                CommentStatement commentStatement = new CommentStatement(statement.printCommand(database));

                if (Configuration.noAlterSqlDryMode()) {
                    statements.clear();
                    statements.add(0, commentStatement);
                } else {
                    statements.add(0, commentStatement);
                    statements.add(1, new CommentStatement("Instead of the following statements, pt-online-schema-change will be used"));
                }
            } else {
                statements.clear();
                statements.add(statement);
            }
        } else {
            if (Configuration.failIfNoPT()) {
                throw new RuntimeException("No percona toolkit found!");
            }
            maybeLog("Not using percona toolkit, because it is not available!");
        }
    }

    return statements.toArray(new SqlStatement[statements.size()]);
}