liquibase.changelog.ChangeSet Java Examples

The following examples show how to use liquibase.changelog.ChangeSet. 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 File: ImpalaRemoveChangeSetRanStatusGenerator.java    From liquibase-impala with Apache License 2.0 6 votes vote down vote up
@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 #2
Source File: QuarkusJpaUpdaterProvider.java    From keycloak with 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 #3
Source File: QuarkusJpaUpdaterProvider.java    From keycloak with 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 #4
Source File: LiquibaseJpaUpdaterProvider.java    From keycloak with 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 #5
Source File: LiquibaseIT.java    From liquibase-spatial with 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 #6
Source File: LiquibaseIT.java    From liquibase-spatial with 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 File: LiquibaseFunctionalityResource.java    From quarkus with 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 #8
Source File: HiveStandardChangeLogHistoryService.java    From liquibase-impala with Apache License 2.0 6 votes vote down vote up
@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 #9
Source File: HiveRemoveChangeSetRanStatusGenerator.java    From liquibase-impala with Apache License 2.0 6 votes vote down vote up
@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 #10
Source File: LiquibaseExtensionCleanAtStartTest.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@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 #11
Source File: ChangeLogParserTest.java    From liquibase-percona with 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 #12
Source File: LiquibaseProcessor.java    From quarkus with 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 #13
Source File: LiquibaseJpaUpdaterProvider.java    From keycloak with 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 #14
Source File: LiquibaseImpl.java    From iaf with 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 #15
Source File: ChangeLogParserTest.java    From liquibase-percona with 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 #16
Source File: ChangeLogParserTest.java    From liquibase-percona with 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 #17
Source File: HiveMarkChangeSetRanGenerator.java    From liquibase-impala with Apache License 2.0 5 votes vote down vote up
@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 #18
Source File: HiveStandardChangeLogHistoryService.java    From liquibase-impala with Apache License 2.0 5 votes vote down vote up
@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 #19
Source File: HiveStandardChangeLogHistoryService.java    From liquibase-impala with Apache License 2.0 5 votes vote down vote up
@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 #20
Source File: HiveStandardChangeLogHistoryService.java    From liquibase-impala with Apache License 2.0 5 votes vote down vote up
@Override
protected void replaceChecksum(ChangeSet changeSet) throws DatabaseException {
    ExecutorService.getInstance().getExecutor(getDatabase()).execute(new UpdateChangeSetChecksumStatement(changeSet));

    getDatabase().commit();
    reset();
}
 
Example #21
Source File: HiveStandardChangeLogHistoryService.java    From liquibase-impala with Apache License 2.0 5 votes vote down vote up
@Override
public RanChangeSet getRanChangeSet(final ChangeSet changeSet) throws DatabaseException, DatabaseHistoryException {
    if (!hasDatabaseChangeLogTable()) {
        return null;
    }

    return super.getRanChangeSet(changeSet);
}
 
Example #22
Source File: AbstractJdbcDatabase.java    From jweb-cms with GNU Affero General Public License v3.0 4 votes vote down vote up
@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
Source File: AbstractJdbcDatabase.java    From jweb-cms with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public void markChangeSetExecStatus(final ChangeSet changeSet, final ChangeSet.ExecType execType) throws DatabaseException {
    ChangeLogHistoryServiceFactory.getInstance().getChangeLogService(this).setExecType(changeSet, execType);
}
 
Example #24
Source File: QuarkusJpaUpdaterProvider.java    From keycloak with Apache License 2.0 4 votes vote down vote up
protected void updateChangeSet(Liquibase liquibase, Writer exportWriter) throws LiquibaseException  {
    String changelog = liquibase.getChangeLogFile();
    Database database = liquibase.getDatabase();
    Table changelogTable = SnapshotGeneratorFactory.getInstance().getDatabaseChangeLogTable(new SnapshotControl(database, false, Table.class, Column.class), database);

    if (changelogTable != null) {
        boolean hasDeploymentIdColumn = changelogTable.getColumn(DEPLOYMENT_ID_COLUMN) != null;

        // create DEPLOYMENT_ID column if it doesn't exist
        if (!hasDeploymentIdColumn) {
            ChangeLogHistoryService changelogHistoryService = ChangeLogHistoryServiceFactory.getInstance().getChangeLogService(database);
            changelogHistoryService.generateDeploymentId();
            String deploymentId = changelogHistoryService.getDeploymentId();

            logger.debugv("Adding missing column {0}={1} to {2} table", DEPLOYMENT_ID_COLUMN, deploymentId,changelogTable.getName());

            List<SqlStatement> statementsToExecute = new ArrayList<>();
            statementsToExecute.add(new AddColumnStatement(database.getLiquibaseCatalogName(), database.getLiquibaseSchemaName(),
                    changelogTable.getName(), DEPLOYMENT_ID_COLUMN, "VARCHAR(10)", null));
            statementsToExecute.add(new UpdateStatement(database.getLiquibaseCatalogName(), database.getLiquibaseSchemaName(), changelogTable.getName())
                    .addNewColumnValue(DEPLOYMENT_ID_COLUMN, deploymentId));
            statementsToExecute.add(new SetNullableStatement(database.getLiquibaseCatalogName(), database.getLiquibaseSchemaName(),
                    changelogTable.getName(), DEPLOYMENT_ID_COLUMN, "VARCHAR(10)", false));

            ExecutorService executorService = ExecutorService.getInstance();
            Executor executor = executorService.getExecutor(liquibase.getDatabase());

            for (SqlStatement sql : statementsToExecute) {
                executor.execute(sql);
                database.commit();
            }
        }
    }

    List<ChangeSet> changeSets = getLiquibaseUnrunChangeSets(liquibase);
    if (!changeSets.isEmpty()) {
        List<RanChangeSet> ranChangeSets = liquibase.getDatabase().getRanChangeSetList();
        if (ranChangeSets.isEmpty()) {
            logger.infov("Initializing database schema. Using changelog {0}", changelog);
        } else {
            if (logger.isDebugEnabled()) {
                logger.debugv("Updating database from {0} to {1}. Using changelog {2}", ranChangeSets.get(ranChangeSets.size() - 1).getId(), changeSets.get(changeSets.size() - 1).getId(), changelog);
            } else {
                logger.infov("Updating database. Using changelog {0}", changelog);
            }
        }

        if (exportWriter != null) {
            if (ranChangeSets.isEmpty()) {
                outputChangeLogTableCreationScript(liquibase, exportWriter);
            }
            liquibase.update((Contexts) null, new LabelExpression(), exportWriter, false);
        } else {
            liquibase.update((Contexts) null);
        }

        logger.debugv("Completed database update for changelog {0}", changelog);
    } else {
        logger.debugv("Database is up to date for changelog {0}", changelog);
    }

    // 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);
}
 
Example #25
Source File: KeycloakLogger.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public void setChangeSet(ChangeSet changeSet) {
}
 
Example #26
Source File: DefaultLiquibaseConnectionProvider.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public void setChangeSet(ChangeSet changeSet) {
}
 
Example #27
Source File: LiquibaseJpaUpdaterProvider.java    From keycloak with Apache License 2.0 4 votes vote down vote up
protected void updateChangeSet(Liquibase liquibase, Connection connection, Writer exportWriter) throws LiquibaseException, SQLException {
    String changelog = liquibase.getChangeLogFile();
    Database database = liquibase.getDatabase();
    Table changelogTable = SnapshotGeneratorFactory.getInstance().getDatabaseChangeLogTable(new SnapshotControl(database, false, Table.class, Column.class), database);

    if (changelogTable != null) {
        boolean hasDeploymentIdColumn = changelogTable.getColumn(DEPLOYMENT_ID_COLUMN) != null;

        // create DEPLOYMENT_ID column if it doesn't exist
        if (!hasDeploymentIdColumn) {
            ChangeLogHistoryService changelogHistoryService = ChangeLogHistoryServiceFactory.getInstance().getChangeLogService(database);
            changelogHistoryService.generateDeploymentId();
            String deploymentId = changelogHistoryService.getDeploymentId();

            logger.debugv("Adding missing column {0}={1} to {2} table", DEPLOYMENT_ID_COLUMN, deploymentId,changelogTable.getName());

            List<SqlStatement> statementsToExecute = new ArrayList<>();
            statementsToExecute.add(new AddColumnStatement(database.getLiquibaseCatalogName(), database.getLiquibaseSchemaName(),
                    changelogTable.getName(), DEPLOYMENT_ID_COLUMN, "VARCHAR(10)", null));
            statementsToExecute.add(new UpdateStatement(database.getLiquibaseCatalogName(), database.getLiquibaseSchemaName(), changelogTable.getName())
                    .addNewColumnValue(DEPLOYMENT_ID_COLUMN, deploymentId));
            statementsToExecute.add(new SetNullableStatement(database.getLiquibaseCatalogName(), database.getLiquibaseSchemaName(),
                    changelogTable.getName(), DEPLOYMENT_ID_COLUMN, "VARCHAR(10)", false));

            ExecutorService executorService = ExecutorService.getInstance();
            Executor executor = executorService.getExecutor(liquibase.getDatabase());

            for (SqlStatement sql : statementsToExecute) {
                executor.execute(sql);
                database.commit();
            }
        }
    }

    List<ChangeSet> changeSets = getLiquibaseUnrunChangeSets(liquibase);
    if (!changeSets.isEmpty()) {
        List<RanChangeSet> ranChangeSets = liquibase.getDatabase().getRanChangeSetList();
        if (ranChangeSets.isEmpty()) {
            logger.infov("Initializing database schema. Using changelog {0}", changelog);
        } else {
            if (logger.isDebugEnabled()) {
                logger.debugv("Updating database from {0} to {1}. Using changelog {2}", ranChangeSets.get(ranChangeSets.size() - 1).getId(), changeSets.get(changeSets.size() - 1).getId(), changelog);
            } else {
                logger.infov("Updating database. Using changelog {0}", changelog);
            }
        }

        if (exportWriter != null) {
            if (ranChangeSets.isEmpty()) {
                outputChangeLogTableCreationScript(liquibase, exportWriter);
            }
            liquibase.update((Contexts) null, new LabelExpression(), exportWriter, false);
        } else {
            liquibase.update((Contexts) null);
        }

        logger.debugv("Completed database update for changelog {0}", changelog);
    } else {
        logger.debugv("Database is up to date for changelog {0}", changelog);
    }

    // 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);
}
 
Example #28
Source File: AbstractJdbcDatabase.java    From jweb-cms with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public Date getRanDate(final ChangeSet changeSet) throws DatabaseException, DatabaseHistoryException {
    return ChangeLogHistoryServiceFactory.getInstance().getChangeLogService(this).getRanDate(changeSet);
}
 
Example #29
Source File: AbstractJdbcDatabase.java    From jweb-cms with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public ChangeSet.RunStatus getRunStatus(final ChangeSet changeSet) throws DatabaseException, DatabaseHistoryException {
    return ChangeLogHistoryServiceFactory.getInstance().getChangeLogService(this).getRunStatus(changeSet);
}
 
Example #30
Source File: AbstractJdbcDatabase.java    From jweb-cms with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public void removeRanStatus(final ChangeSet changeSet) throws DatabaseException {
    ChangeLogHistoryServiceFactory.getInstance().getChangeLogService(this).removeFromHistory(changeSet);
}