liquibase.statement.core.UpdateStatement Java Examples

The following examples show how to use liquibase.statement.core.UpdateStatement. 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: JpaUpdate4_7_0_OfflineSessionsTimestamps.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
protected void generateStatementsImpl() throws CustomChangeException {
    String offlineUserSessionsTableName = database.correctObjectName("OFFLINE_USER_SESSION", Table.class);

    try {
        int currentTime = Time.currentTime();

        UpdateStatement updateStatement = new UpdateStatement(null, null, offlineUserSessionsTableName)
                .addNewColumnValue("LAST_SESSION_REFRESH", currentTime);

        statements.add(updateStatement);

        confirmationMessage.append("Updated column LAST_SESSION_REFRESH in OFFLINE_USER_SESSION table with time " + currentTime);
    } catch (Exception e) {
        throw new CustomChangeException(getTaskId() + ": Exception when updating data from previous version", e);
    }
}
 
Example #2
Source File: HiveStandardChangeLogHistoryService.java    From liquibase-impala with Apache License 2.0 5 votes vote down vote up
@Override
public void clearAllCheckSums() throws LiquibaseException {
    Database database = getDatabase();
    UpdateStatement updateStatement = new UpdateStatement(database.getLiquibaseCatalogName(), database.getLiquibaseSchemaName(), database.getDatabaseChangeLogTableName());
    updateStatement.addNewColumnValue("MD5SUM", null);
    ExecutorService.getInstance().getExecutor(database).execute(updateStatement);
    database.commit();
}
 
Example #3
Source File: AbstractSpatialUpdateGenerator.java    From liquibase-spatial with Apache License 2.0 5 votes vote down vote up
/**
 * Find any fields that look like WKT or EWKT and replace them with the database-specific value.
 */
@Override
public Sql[] generateSql(final UpdateStatement statement, final Database database,
      final SqlGeneratorChain sqlGeneratorChain) {
   for (final Entry<String, Object> entry : statement.getNewColumnValues().entrySet()) {
      entry.setValue(handleColumnValue(entry.getValue(), database));
   }
   return super.generateSql(statement, database, sqlGeneratorChain);
}
 
Example #4
Source File: CertificateBlobToBase64.java    From aerogear-unifiedpush-server with Apache License 2.0 5 votes vote down vote up
@Override
public SqlStatement[] generateStatements(Database database) throws CustomChangeException {
    List<SqlStatement> statements = new ArrayList<>();

    Connection conn = ((JdbcConnection) (database.getConnection())).getWrappedConnection();

    try {
        conn.setAutoCommit(false);
        ResultSet resultSet = conn.createStatement().executeQuery("SELECT id, certificate from ios_variant");
        while (resultSet.next()) {
            String id = resultSet.getString("id");
            Blob blob = resultSet.getBlob("certificate");
            InputStream certificate = blob.getBinaryStream();
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            int bytesRead = -1;
            byte[] buffer = new byte[1024];
            while ((bytesRead = certificate.read(buffer)) != -1) {
                stream.write(buffer, 0, bytesRead);
            }
            final String certificateData = Base64.getEncoder().encodeToString(stream.toByteArray());

            UpdateStatement updateStatement = new UpdateStatement(null, null, "ios_variant")
                    .addNewColumnValue("cert_data", certificateData)
                    .setWhereClause("id='" + id + "'");
            statements.add(updateStatement);

        }
        conn.commit();

        if (!statements.isEmpty()) {
            confirmationMessage = "updated certificate data successfully";
        }

        return statements.toArray(new SqlStatement[statements.size()]);
    } catch (Exception e) {
        throw new CustomChangeException("Failed to migrate certificate data");
    }

}
 
Example #5
Source File: JpaUpdate1_4_0_Final.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
protected void generateStatementsImpl() throws CustomChangeException {
    String userAttributeTableName = database.correctObjectName("USER_ATTRIBUTE", Table.class);

    try {
        PreparedStatement statement = jdbcConnection.prepareStatement("select NAME, USER_ID from " + getTableName("USER_ATTRIBUTE"));

        try {
            ResultSet resultSet = statement.executeQuery();
            try {
                while (resultSet.next()) {
                    String name = resultSet.getString(1);
                    String userId = resultSet.getString(2);

                    UpdateStatement updateStatement = new UpdateStatement(null, null, userAttributeTableName)
                            .addNewColumnValue("ID", KeycloakModelUtils.generateId())
                            .setWhereClause("NAME='" + name + "' AND USER_ID='" + userId + "'");
                    statements.add(updateStatement);
                }
            } finally {
                resultSet.close();
            }
        } finally {
            statement.close();
        }

        confirmationMessage.append("Updated " + statements.size() + " attributes in USER_ATTRIBUTE table");
    } catch (Exception e) {
        throw new CustomChangeException(getTaskId() + ": Exception when updating data from previous version", e);
    }
}
 
Example #6
Source File: JpaUpdate1_9_0_Final.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
protected void generateStatementsImpl() throws CustomChangeException {
    String userFederationProviderTableName = database.correctObjectName("USER_FEDERATION_PROVIDER", Table.class);

    try {
        PreparedStatement statement = jdbcConnection.prepareStatement("select REALM_ID, USERFEDERATIONPROVIDERS_ID from " + getTableName("FED_PROVIDERS"));

        try {
            ResultSet resultSet = statement.executeQuery();
            try {
                while (resultSet.next()) {
                    String realmId = resultSet.getString(1);
                    String userFederationProviderId = resultSet.getString(2);

                    UpdateStatement updateStatement = new UpdateStatement(null, null, userFederationProviderTableName)
                            .addNewColumnValue("REALM_ID", realmId)
                            .setWhereClause("ID='" + userFederationProviderId + "'");
                    statements.add(updateStatement);
                }
            } finally {
                resultSet.close();
            }
        } finally {
            statement.close();
        }

        confirmationMessage.append("Updated " + statements.size() + " records in USER_FEDERATION_PROVIDER table");
    } catch (Exception e) {
        throw new CustomChangeException(getTaskId() + ": Exception when updating data from previous version", e);
    }
}
 
Example #7
Source File: JpaUpdate1_2_0_Beta1.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected void addAccessCodeLoginTimeout() {
    UpdateStatement statement = new UpdateStatement(null, null, realmTableName)
            .addNewColumnValue("LOGIN_LIFESPAN", 1800)
            .setWhereClause("LOGIN_LIFESPAN IS NULL");
    statements.add(statement);

    confirmationMessage.append("Updated LOGIN_LIFESPAN of all realms to 1800 seconds. ");
}
 
Example #8
Source File: AddRealmCodeSecret.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public SqlStatement[] generateStatements(Database database) throws CustomChangeException {
    try {
        StringBuilder sb = new StringBuilder();
        sb.append("Generated codeSecret for realms: ");

        Connection connection = ((JdbcConnection) (database.getConnection())).getWrappedConnection();
        ArrayList<SqlStatement> statements = new ArrayList<SqlStatement>();

        String correctedTableName = database.correctObjectName("REALM", Table.class);
        String correctedSchemaName = database.escapeObjectName(database.getDefaultSchemaName(), Schema.class);

        if (SnapshotGeneratorFactory.getInstance().has(new Table().setName(correctedTableName), database)) {
            try (Statement st = connection.createStatement(); ResultSet resultSet = st.executeQuery("SELECT ID FROM " + LiquibaseJpaUpdaterProvider.getTable(correctedTableName, correctedSchemaName) + " WHERE CODE_SECRET IS NULL")) {
                while (resultSet.next()) {
                    String id = resultSet.getString(1);
                    
                    UpdateStatement statement = new UpdateStatement(null, null, correctedTableName)
                            .addNewColumnValue("CODE_SECRET", KeycloakModelUtils.generateCodeSecret())
                            .setWhereClause("ID=?").addWhereParameters(id);
                    statements.add(statement);
                    
                    if (!resultSet.isFirst()) {
                        sb.append(", ");
                    }
                    sb.append(id);
                }

                if (!statements.isEmpty()) {
                    confirmationMessage = sb.toString();
                }
            }
        }

        return statements.toArray(new SqlStatement[statements.size()]);
    } catch (Exception e) {
        throw new CustomChangeException("Failed to add realm code secret", e);
    }
}
 
Example #9
Source File: AbstractSpatialUpdateGenerator.java    From liquibase-spatial with Apache License 2.0 4 votes vote down vote up
@Override
public ValidationErrors validate(final UpdateStatement statement, final Database database,
      final SqlGeneratorChain sqlGeneratorChain) {
   return sqlGeneratorChain.validate(statement, database);
}
 
Example #10
Source File: SpatialUpdateGeneratorOracle.java    From liquibase-spatial with Apache License 2.0 4 votes vote down vote up
/**
 * Verifies that the <code>UpdateStatement</code> has WKT or EWKT.
 */
@Override
public boolean supports(final UpdateStatement statement, final Database database) {
   return database instanceof OracleDatabase;
}
 
Example #11
Source File: SpatialUpdateGeneratorMySQL.java    From liquibase-spatial with Apache License 2.0 4 votes vote down vote up
@Override
public boolean supports(final UpdateStatement statement, final Database database) {
   return database instanceof MySQLDatabase;
}
 
Example #12
Source File: SpatialUpdateGeneratorGeoDB.java    From liquibase-spatial with Apache License 2.0 4 votes vote down vote up
@Override
public boolean supports(final UpdateStatement statement, final Database database) {
   return database instanceof DerbyDatabase || database instanceof H2Database;
}
 
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);
}