liquibase.changelog.ChangeLogHistoryServiceFactory Java Examples

The following examples show how to use liquibase.changelog.ChangeLogHistoryServiceFactory. 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: 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 #2
Source File: AbstractJdbcDatabase.java    From jweb-cms with GNU Affero General Public License v3.0 4 votes vote down vote up
protected boolean canCreateChangeLogTable() throws DatabaseException {
    return ((StandardChangeLogHistoryService) ChangeLogHistoryServiceFactory.getInstance().getChangeLogService(this)).canCreateChangeLogTable();
}
 
Example #3
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 #4
Source File: AbstractJdbcDatabase.java    From jweb-cms with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public void tag(final String tagString) throws DatabaseException {
    ChangeLogHistoryServiceFactory.getInstance().getChangeLogService(this).tag(tagString);
}
 
Example #5
Source File: AbstractJdbcDatabase.java    From jweb-cms with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public boolean doesTagExist(final String tag) throws DatabaseException {
    return ChangeLogHistoryServiceFactory.getInstance().getChangeLogService(this).tagExists(tag);
}
 
Example #6
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 #7
Source File: AbstractJdbcDatabase.java    From jweb-cms with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public RanChangeSet getRanChangeSet(final ChangeSet changeSet) throws DatabaseException, DatabaseHistoryException {
    return ChangeLogHistoryServiceFactory.getInstance().getChangeLogService(this).getRanChangeSet(changeSet);
}
 
Example #8
Source File: AbstractJdbcDatabase.java    From jweb-cms with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public List<RanChangeSet> getRanChangeSetList() throws DatabaseException {
    return ChangeLogHistoryServiceFactory.getInstance().getChangeLogService(this).getRanChangeSets();
}
 
Example #9
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 #10
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 #11
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);
}
 
Example #12
Source File: AbstractJdbcDatabase.java    From jweb-cms with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public void resetInternalState() {
    ChangeLogHistoryServiceFactory.getInstance().getChangeLogService(this).reset();
    LockServiceFactory.getInstance().getLockService(this).reset();
}
 
Example #13
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 #14
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);
}