Search in sources :

Example 6 with CustomChangeException

use of liquibase.exception.CustomChangeException in project keycloak by keycloak.

the class JpaUpdate1_2_0_CR1 method generateStatementsImpl.

@Override
protected void generateStatementsImpl() throws CustomChangeException {
    String realmClientTableName = database.correctObjectName("REALM_CLIENT", Table.class);
    try {
        String trueValue = DataTypeFactory.getInstance().getTrueBooleanValue(database);
        PreparedStatement statement = jdbcConnection.prepareStatement("select CLIENT.REALM_ID, CLIENT.ID CLIENT_ID from " + getTableName("CLIENT") + " CLIENT where CLIENT.CONSENT_REQUIRED = " + trueValue);
        try {
            ResultSet resultSet = statement.executeQuery();
            try {
                while (resultSet.next()) {
                    String realmId = resultSet.getString("REALM_ID");
                    String oauthClientId = resultSet.getString("CLIENT_ID");
                    InsertStatement realmClientInsert = new InsertStatement(null, null, realmClientTableName).addColumnValue("REALM_ID", realmId).addColumnValue("CLIENT_ID", oauthClientId);
                    statements.add(realmClientInsert);
                }
            } finally {
                resultSet.close();
            }
        } finally {
            statement.close();
        }
        confirmationMessage.append("Inserted " + statements.size() + " OAuth Clients to REALM_CLIENT table");
    } catch (Exception e) {
        throw new CustomChangeException(getTaskId() + ": Exception when updating data from previous version", e);
    }
}
Also used : ResultSet(java.sql.ResultSet) CustomChangeException(liquibase.exception.CustomChangeException) PreparedStatement(java.sql.PreparedStatement) InsertStatement(liquibase.statement.core.InsertStatement) CustomChangeException(liquibase.exception.CustomChangeException)

Example 7 with CustomChangeException

use of liquibase.exception.CustomChangeException in project keycloak by keycloak.

the class JpaUpdate14_0_0_MigrateSamlArtifactAttribute method extractClientsData.

private void extractClientsData(String sql) throws CustomChangeException {
    try (PreparedStatement statement = jdbcConnection.prepareStatement(sql);
        ResultSet rs = statement.executeQuery()) {
        while (rs.next()) {
            String id = rs.getString(1);
            String clientId = rs.getString(2);
            if (id == null || id.trim().isEmpty() || clientId == null || clientId.trim().isEmpty()) {
                continue;
            }
            clientIds.put(id, clientId);
        }
    } catch (Exception e) {
        throw new CustomChangeException(getTaskId() + ": Exception when extracting data from previous version", e);
    }
}
Also used : ResultSet(java.sql.ResultSet) CustomChangeException(liquibase.exception.CustomChangeException) PreparedStatement(java.sql.PreparedStatement) ArtifactBindingUtils.computeArtifactBindingIdentifierString(org.keycloak.protocol.saml.util.ArtifactBindingUtils.computeArtifactBindingIdentifierString) CustomChangeException(liquibase.exception.CustomChangeException)

Example 8 with CustomChangeException

use of liquibase.exception.CustomChangeException in project keycloak by keycloak.

the class RemoveDuplicateOfflineSessions method generateStatementsImpl.

@Override
protected void generateStatementsImpl() throws CustomChangeException {
    Set<String> clientSessionIdsToDelete = new HashSet<>();
    String tableName = getTableName("OFFLINE_CLIENT_SESSION");
    String colClientSessionId = database.correctObjectName("CLIENT_SESSION_ID", Column.class);
    try (PreparedStatement ps = connection.prepareStatement(String.format("SELECT t.CLIENT_SESSION_ID, t.USER_SESSION_ID, t.CLIENT_ID, t.OFFLINE_FLAG" + "  FROM %1$s t," + "    (SELECT USER_SESSION_ID, CLIENT_ID, OFFLINE_FLAG" + "      FROM %1$s" + "    GROUP BY USER_SESSION_ID, CLIENT_ID, OFFLINE_FLAG" + "    HAVING COUNT(*) > 1) t1" + "  WHERE t.USER_SESSION_ID = t1.USER_SESSION_ID" + "    AND t.CLIENT_ID = t1.CLIENT_ID" + "    AND t.OFFLINE_FLAG = t1.OFFLINE_FLAG" + "  ORDER BY t.USER_SESSION_ID, t.CLIENT_ID, t.OFFLINE_FLAG", tableName));
        ResultSet resultSet = ps.executeQuery()) {
        // Find out all offending duplicates, keep first row only
        Key origKey = new Key(null, null, null);
        while (resultSet.next()) {
            String clientSessionId = resultSet.getString(1);
            Key key = new Key(resultSet.getString(2), resultSet.getString(3), resultSet.getString(4));
            if (key.equals(origKey)) {
                clientSessionIdsToDelete.add(clientSessionId);
            } else {
                origKey = key;
            }
        }
    } catch (Exception e) {
        throw new CustomChangeException(getTaskId() + ": Exception when updating data from previous version", e);
    }
    AtomicInteger ai = new AtomicInteger();
    clientSessionIdsToDelete.stream().collect(// Split into chunks of at most 20 items
    Collectors.groupingByConcurrent(id -> ai.getAndIncrement() / 20, Collectors.toList())).values().stream().map(ids -> new DeleteStatement(null, null, "OFFLINE_CLIENT_SESSION").setWhere(":name IN (" + ids.stream().map(id -> "?").collect(Collectors.joining(",")) + ")").addWhereColumnName(colClientSessionId).addWhereParameters(ids.toArray())).forEach(statements::add);
}
Also used : HashSet(java.util.HashSet) Objects(java.util.Objects) IntStream(java.util.stream.IntStream) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ResultSet(java.sql.ResultSet) Column(liquibase.structure.core.Column) DeleteStatement(liquibase.statement.core.DeleteStatement) Set(java.util.Set) CustomChangeException(liquibase.exception.CustomChangeException) PreparedStatement(java.sql.PreparedStatement) Collectors(java.util.stream.Collectors) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ResultSet(java.sql.ResultSet) CustomChangeException(liquibase.exception.CustomChangeException) PreparedStatement(java.sql.PreparedStatement) DeleteStatement(liquibase.statement.core.DeleteStatement) CustomChangeException(liquibase.exception.CustomChangeException) HashSet(java.util.HashSet)

Example 9 with CustomChangeException

use of liquibase.exception.CustomChangeException in project openmrs-core by openmrs.

the class MigrateAllergiesChangeSet method execute.

@Override
public void execute(Database database) throws CustomChangeException {
    try {
        loadSeverityConcepts(database);
        JdbcConnection connection = (JdbcConnection) database.getConnection();
        String sql = "select active_list_type_id from active_list_type where name = 'Allergy'";
        Statement selectStatement = connection.createStatement();
        ResultSet rs = selectStatement.executeQuery(sql);
        if (!rs.next()) {
            throw new CustomChangeException("Failed to find row with name 'Allergy' in the active_list_type");
        }
        int allergyTypeId = rs.getInt(1);
        sql = "insert into allergy (patient_id, coded_allergen, severity_concept_id, creator, date_created, uuid, comment, allergen_type) " + "values(?,?,?,?,?,?,?,?)";
        PreparedStatement allergyInsertStatement = connection.prepareStatement(sql);
        sql = "insert into allergy_reaction (allergy_id, reaction_concept_id, uuid) " + "values (?,?,?)";
        PreparedStatement reactionInsertStatement = connection.prepareStatement(sql);
        sql = "select allergy_id from allergy where uuid = ?";
        PreparedStatement allergySelectStatement = connection.prepareStatement(sql);
        sql = "select person_id, concept_id, comments, creator, date_created, uuid, reaction_concept_id, severity, allergy_type " + "from active_list al inner join active_list_allergy ala on al.active_list_id=ala.active_list_id " + "where voided = 0 and active_list_type_id = " + allergyTypeId;
        selectStatement = connection.createStatement();
        rs = selectStatement.executeQuery(sql);
        while (rs.next()) {
            String uuid = rs.getString("uuid");
            // insert allergy
            allergyInsertStatement.setInt(1, rs.getInt("person_id"));
            allergyInsertStatement.setInt(2, rs.getInt("concept_id"));
            Integer severityConcept = null;
            String severity = rs.getString("severity");
            if (AllergySeverity.MILD.name().equals(severity)) {
                severityConcept = mildConcept;
            } else if (AllergySeverity.MODERATE.name().equals(severity)) {
                severityConcept = moderateConcept;
            } else if (AllergySeverity.SEVERE.name().equals(severity)) {
                severityConcept = severeConcept;
            }
            if (severityConcept != null) {
                allergyInsertStatement.setInt(3, severityConcept);
            }
            allergyInsertStatement.setInt(4, rs.getInt("creator"));
            allergyInsertStatement.setDate(5, rs.getDate("date_created"));
            allergyInsertStatement.setString(6, uuid);
            allergyInsertStatement.setString(7, rs.getString("comments"));
            String allergyType = rs.getString("allergy_type");
            if (allergyType == null) {
                allergyType = "DRUG";
            } else if ("ENVIRONMENTAL".equals(allergyType)) {
                allergyType = "ENVIRONMENT";
            }
            allergyInsertStatement.setString(8, allergyType);
            allergyInsertStatement.execute();
            // get inserted allergy_id
            allergySelectStatement.setString(1, uuid);
            ResultSet rs2 = allergySelectStatement.executeQuery();
            rs2.next();
            // insert reaction
            reactionInsertStatement.setInt(1, rs2.getInt(1));
            reactionInsertStatement.setInt(2, rs.getInt("reaction_concept_id"));
            reactionInsertStatement.setString(3, UUID.randomUUID().toString());
            // some active lists do not have reactions recorded
            if (!rs.wasNull()) {
                reactionInsertStatement.execute();
            }
        }
    } catch (Exception ex) {
        throw new CustomChangeException(ex);
    }
}
Also used : Statement(java.sql.Statement) PreparedStatement(java.sql.PreparedStatement) ResultSet(java.sql.ResultSet) CustomChangeException(liquibase.exception.CustomChangeException) JdbcConnection(liquibase.database.jvm.JdbcConnection) PreparedStatement(java.sql.PreparedStatement) CustomChangeException(liquibase.exception.CustomChangeException) SetupException(liquibase.exception.SetupException)

Example 10 with CustomChangeException

use of liquibase.exception.CustomChangeException in project openmrs-core by openmrs.

the class MigrateDrugOrderFrequencyToCodedOrderFrequencyChangeset method migrateFrequenciesToCodedValue.

private void migrateFrequenciesToCodedValue(JdbcConnection connection, Set<String> uniqueFrequencies) throws CustomChangeException, SQLException, DatabaseException {
    PreparedStatement updateDrugOrderStatement = null;
    Boolean autoCommit = null;
    try {
        autoCommit = connection.getAutoCommit();
        connection.setAutoCommit(false);
        updateDrugOrderStatement = connection.prepareStatement("update drug_order set frequency = ? where frequency_text = ?");
        updateDrugOrderStatement.setNull(1, Types.INTEGER);
        updateDrugOrderStatement.setNull(2, Types.VARCHAR);
        updateDrugOrderStatement.executeUpdate();
        updateDrugOrderStatement.clearParameters();
        for (String frequency : uniqueFrequencies) {
            if (StringUtils.isBlank(frequency)) {
                updateDrugOrderStatement.setNull(1, Types.INTEGER);
            } else {
                Integer conceptIdForFrequency = UpgradeUtil.getConceptIdForUnits(frequency);
                if (conceptIdForFrequency == null) {
                    throw new CustomChangeException("No concept mapping found for frequency: " + frequency);
                }
                Integer orderFrequencyId = UpgradeUtil.getOrderFrequencyIdForConceptId(connection.getUnderlyingConnection(), conceptIdForFrequency);
                if (orderFrequencyId == null) {
                    throw new CustomChangeException("No order frequency found for concept " + conceptIdForFrequency);
                }
                updateDrugOrderStatement.setInt(1, orderFrequencyId);
            }
            updateDrugOrderStatement.setString(2, frequency);
            updateDrugOrderStatement.executeUpdate();
            updateDrugOrderStatement.clearParameters();
        }
        connection.commit();
    } catch (DatabaseException | SQLException e) {
        handleError(connection, e);
    } finally {
        if (autoCommit != null) {
            connection.setAutoCommit(autoCommit);
        }
        if (updateDrugOrderStatement != null) {
            updateDrugOrderStatement.close();
        }
    }
}
Also used : SQLException(java.sql.SQLException) CustomChangeException(liquibase.exception.CustomChangeException) PreparedStatement(java.sql.PreparedStatement) DatabaseException(liquibase.exception.DatabaseException)

Aggregations

CustomChangeException (liquibase.exception.CustomChangeException)46 PreparedStatement (java.sql.PreparedStatement)33 ResultSet (java.sql.ResultSet)26 DatabaseException (liquibase.exception.DatabaseException)26 SQLException (java.sql.SQLException)25 JdbcConnection (liquibase.database.jvm.JdbcConnection)21 SetupException (liquibase.exception.SetupException)16 Statement (java.sql.Statement)8 ArrayList (java.util.ArrayList)6 InsertStatement (liquibase.statement.core.InsertStatement)6 Table (liquibase.structure.core.Table)6 Date (java.sql.Date)5 HashMap (java.util.HashMap)5 Map (java.util.Map)5 BatchUpdateException (java.sql.BatchUpdateException)4 Connection (java.sql.Connection)4 HashSet (java.util.HashSet)4 List (java.util.List)4 UpdateStatement (liquibase.statement.core.UpdateStatement)4 SqlStatement (liquibase.statement.SqlStatement)3