liquibase.executor.Executor Java Examples

The following examples show how to use liquibase.executor.Executor. 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: 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 #2
Source File: CustomLockService.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private Set<Integer> currentIdsInDatabaseChangeLogLockTable() throws DatabaseException {
    try {
        Executor executor = ExecutorService.getInstance().getExecutor(database);
        String idColumnName = database.escapeColumnName(database.getLiquibaseCatalogName(),
                database.getLiquibaseSchemaName(),
                database.getDatabaseChangeLogLockTableName(),
                "ID");
        String lockTableName = database.escapeTableName(database.getLiquibaseCatalogName(),
                database.getLiquibaseSchemaName(),
                database.getDatabaseChangeLogLockTableName());
        SqlStatement sqlStatement = new RawSqlStatement("SELECT " + idColumnName + " FROM " + lockTableName);
        List<Map<String, ?>> rows = executor.queryForList(sqlStatement);
        Set<Integer> ids = rows.stream().map(columnMap -> ((Number) columnMap.get("ID")).intValue()).collect(Collectors.toSet());
        database.commit();
        return ids;
    } catch (UnexpectedLiquibaseException ulie) {
        // It can happen with MariaDB Galera 10.1 that UnexpectedLiquibaseException is rethrown due the DB lock.
        // It is sufficient to just rollback transaction and retry in that case.
        if (ulie.getCause() != null && ulie.getCause() instanceof DatabaseException) {
            throw (DatabaseException) ulie.getCause();
        } else {
            throw ulie;
        }
    }
}
 
Example #3
Source File: LiquibaseJpaUpdaterProvider.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private void outputChangeLogTableCreationScript(Liquibase liquibase, final Writer exportWriter) throws DatabaseException {
    Database database = liquibase.getDatabase();

    Executor oldTemplate = ExecutorService.getInstance().getExecutor(database);
    LoggingExecutor executor = new LoggingExecutor(ExecutorService.getInstance().getExecutor(database), exportWriter, database);
    ExecutorService.getInstance().setExecutor(database, executor);

    executor.comment("*********************************************************************");
    executor.comment("* Keycloak database creation script - apply this script to empty DB *");
    executor.comment("*********************************************************************" + StreamUtil.getLineSeparator());

    executor.execute(new CreateDatabaseChangeLogTableStatement());
    // DatabaseChangeLogLockTable is created before this code is executed and recreated if it does not exist automatically
    // in org.keycloak.connections.jpa.updater.liquibase.lock.CustomLockService.init() called indirectly from
    // KeycloakApplication constructor (search for waitForLock() call). Hence it is not included in the creation script.

    executor.comment("*********************************************************************" + StreamUtil.getLineSeparator());

    ExecutorService.getInstance().setExecutor(database, oldTemplate);
}
 
Example #4
Source File: QuarkusJpaUpdaterProvider.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private void outputChangeLogTableCreationScript(Liquibase liquibase, final Writer exportWriter) throws DatabaseException {
    Database database = liquibase.getDatabase();

    Executor oldTemplate = ExecutorService.getInstance().getExecutor(database);
    LoggingExecutor executor = new LoggingExecutor(ExecutorService.getInstance().getExecutor(database), exportWriter, database);
    ExecutorService.getInstance().setExecutor(database, executor);

    executor.comment("*********************************************************************");
    executor.comment("* Keycloak database creation script - apply this script to empty DB *");
    executor.comment("*********************************************************************" + StreamUtil.getLineSeparator());

    executor.execute(new CreateDatabaseChangeLogTableStatement());
    // DatabaseChangeLogLockTable is created before this code is executed and recreated if it does not exist automatically
    // in org.keycloak.connections.jpa.updater.liquibase.lock.CustomLockService.init() called indirectly from
    // KeycloakApplication constructor (search for waitForLock() call). Hence it is not included in the creation script.

    executor.comment("*********************************************************************" + StreamUtil.getLineSeparator());

    ExecutorService.getInstance().setExecutor(database, oldTemplate);
}
 
Example #5
Source File: PerconaChangeUtil.java    From liquibase-percona with Apache License 2.0 5 votes vote down vote up
/**
 * Determines whether *SQL (updateSQL/rollbackSQL) is executed or whether
 * the statements should be executed directly.
 * @param database the database
 * @return <code>true</code> if dry-run is enabled and the statements should *not* be executed.
 */
public static boolean isDryRun(Database database) {
    Executor executor = ExecutorService.getInstance().getExecutor(database);
    if (executor instanceof LoggingExecutor) {
        return true;
    }
    return false;
}
 
Example #6
Source File: HiveStandardChangeLogHistoryService.java    From liquibase-impala with Apache License 2.0 4 votes vote down vote up
@Override
public void init() throws DatabaseException {
    if (serviceInitialized) {
        return;
    }
    Database database = getDatabase();
    Executor executor = ExecutorService.getInstance().getExecutor(database);

    Table changeLogTable = null;
    try {
        changeLogTable = SnapshotGeneratorFactory.getInstance().getDatabaseChangeLogTable(new SnapshotControl(database, false, Table.class, Column.class), database);
    } catch (LiquibaseException e) {
        throw new UnexpectedLiquibaseException(e);
    }

    List<SqlStatement> statementsToExecute = new ArrayList<SqlStatement>();

    if (changeLogTable != null) {
        boolean hasDescription = changeLogTable.getColumn("DESCRIPTION") != null;
        boolean hasComments = changeLogTable.getColumn("COMMENTS") != null;
        boolean hasTag = changeLogTable.getColumn("TAG") != null;
        boolean hasLiquibase = changeLogTable.getColumn("LIQUIBASE") != null;
        boolean hasContexts = changeLogTable.getColumn("CONTEXTS") != null;
        boolean hasLabels = changeLogTable.getColumn("LABELS") != null;
        boolean hasOrderExecuted = changeLogTable.getColumn("ORDEREXECUTED") != null;
        boolean hasExecTypeColumn = changeLogTable.getColumn("EXECTYPE") != null;
        String charTypeName = getCharTypeName();
        boolean hasDeploymentIdColumn = changeLogTable.getColumn("DEPLOYMENT_ID") != null;

        if (!hasDescription) {
            executor.comment("Adding missing databasechangelog.description column");
            statementsToExecute.add(new AddColumnStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "DESCRIPTION", charTypeName, null));
        }
        if (!hasTag) {
            executor.comment("Adding missing databasechangelog.tag column");
            statementsToExecute.add(new AddColumnStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "TAG", charTypeName, null));
        }
        if (!hasComments) {
            executor.comment("Adding missing databasechangelog.comments column");
            statementsToExecute.add(new AddColumnStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "COMMENTS", charTypeName, null));
        }
        if (!hasLiquibase) {
            executor.comment("Adding missing databasechangelog.liquibase column");
            statementsToExecute.add(new AddColumnStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "LIQUIBASE", charTypeName, null));
        }
        if (!hasOrderExecuted) {
            executor.comment("Adding missing databasechangelog.orderexecuted column");
            statementsToExecute.add(new AddColumnStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "ORDEREXECUTED", "int", null));
        }
        if (!hasExecTypeColumn) {
            executor.comment("Adding missing databasechangelog.exectype column");
            statementsToExecute.add(new AddColumnStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "EXECTYPE", charTypeName, null));
        }

        if (!hasContexts) {
            executor.comment("Adding missing databasechangelog.contexts column");
            statementsToExecute.add(new AddColumnStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "CONTEXTS", charTypeName, null));
        }

        if (!hasLabels) {
            executor.comment("Adding missing databasechangelog.labels column");
            statementsToExecute.add(new AddColumnStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "LABELS", charTypeName, null));
        }

        if (!hasDeploymentIdColumn) {
            executor.comment("Adding missing databasechangelog.deployment_id column");
            statementsToExecute.add(new AddColumnStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "DEPLOYMENT_ID", charTypeName, null));
        }
    } else {
        executor.comment("Create Database Change Log Table");
        SqlStatement createTableStatement = new CreateDatabaseChangeLogTableStatement();
        if (!canCreateChangeLogTable()) {
            throw new DatabaseException("Cannot create " + getDatabase().escapeTableName(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName()) + " table for your getDatabase().\n\n" +
                    "Please construct it manually using the following SQL as a base and re-run Liquibase:\n\n" +
                    createTableStatement);
        }
        // If there is no table in the database for recording change history create one.
        statementsToExecute.add(createTableStatement);
        LOG.info("Creating database history table with name: " + getDatabase().escapeTableName(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName()));
    }

    for (SqlStatement sql : statementsToExecute) {
        if (SqlGeneratorFactory.getInstance().supports(sql, database)) {
            executor.execute(sql);
            getDatabase().commit();
        } else {
            LOG.info("Cannot run " + sql.getClass().getSimpleName() + " on " + getDatabase().getShortName() + " when checking databasechangelog table");
        }
    }
    serviceInitialized = true;
}
 
Example #7
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 #8
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);
}