Search in sources :

Example 31 with CustomChangeException

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

the class CreateCodedOrderFrequencyForDrugOrderFrequencyChangeset method insertUniqueFrequencies.

private void insertUniqueFrequencies(JdbcConnection connection, Set<String> uniqueFrequencies) throws CustomChangeException, SQLException, DatabaseException {
    PreparedStatement insertOrderFrequencyStatement = null;
    Boolean autoCommit = null;
    try {
        autoCommit = connection.getAutoCommit();
        connection.setAutoCommit(false);
        insertOrderFrequencyStatement = connection.prepareStatement("insert into order_frequency " + "(concept_id, creator, date_created, retired, uuid) values (?, ?, ?, ?, ?)");
        Date date = new Date(new java.util.Date().getTime());
        for (String frequency : uniqueFrequencies) {
            if (StringUtils.isBlank(frequency)) {
                continue;
            }
            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) {
                // a single concept is mapped to more than one text or there is an order frequency already
                continue;
            }
            // Generating UUID for order frequency. Generated UUIDs will be the same if concepts UUIDs are the same.
            String uuid = UpgradeUtil.getConceptUuid(connection.getUnderlyingConnection(), conceptIdForFrequency);
            // Adding random value for order frequency
            uuid += "-6925ebb0-7c69-11e3-baa7-0800200c9a66";
            uuid = UUID.nameUUIDFromBytes(uuid.getBytes(StandardCharsets.UTF_8)).toString();
            insertOrderFrequencyStatement.setInt(1, conceptIdForFrequency);
            insertOrderFrequencyStatement.setInt(2, 1);
            insertOrderFrequencyStatement.setDate(3, date);
            insertOrderFrequencyStatement.setBoolean(4, false);
            insertOrderFrequencyStatement.setString(5, uuid);
            insertOrderFrequencyStatement.executeUpdate();
            insertOrderFrequencyStatement.clearParameters();
        }
        connection.commit();
    } catch (DatabaseException | SQLException e) {
        handleError(connection, e);
    } finally {
        if (autoCommit != null) {
            connection.setAutoCommit(autoCommit);
        }
        if (insertOrderFrequencyStatement != null) {
            insertOrderFrequencyStatement.close();
        }
    }
}
Also used : SQLException(java.sql.SQLException) CustomChangeException(liquibase.exception.CustomChangeException) PreparedStatement(java.sql.PreparedStatement) DatabaseException(liquibase.exception.DatabaseException) Date(java.sql.Date)

Example 32 with CustomChangeException

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

the class DisableTriggersChangeSet method execute.

@Override
public void execute(Database database) throws CustomChangeException {
    JdbcConnection connection = (JdbcConnection) database.getConnection();
    DatabaseMetaData metadata;
    try {
        metadata = connection.getMetaData();
        String[] types = { "TABLE" };
        ResultSet rs = metadata.getTables(null, null, "%", types);
        while (rs.next()) {
            String tableName = rs.getString(3);
            connection.prepareStatement("ALTER TABLE " + tableName + " DISABLE TRIGGER ALL").execute();
        }
    } catch (DatabaseException | SQLException ex) {
        throw new CustomChangeException("Error disabling trigger: " + ex);
    }
}
Also used : SQLException(java.sql.SQLException) ResultSet(java.sql.ResultSet) CustomChangeException(liquibase.exception.CustomChangeException) JdbcConnection(liquibase.database.jvm.JdbcConnection) DatabaseMetaData(java.sql.DatabaseMetaData) DatabaseException(liquibase.exception.DatabaseException)

Example 33 with CustomChangeException

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

the class EnableTriggersChangeSet method execute.

@Override
public void execute(Database database) throws CustomChangeException {
    JdbcConnection connection = (JdbcConnection) database.getConnection();
    DatabaseMetaData metadata;
    try {
        metadata = connection.getMetaData();
        String[] types = { "TABLE" };
        ResultSet rs = metadata.getTables(null, null, "%", types);
        while (rs.next()) {
            String tableName = rs.getString(3);
            connection.prepareStatement("ALTER TABLE " + tableName + " ENABLE TRIGGER ALL").execute();
        }
    } catch (DatabaseException | SQLException ex) {
        throw new CustomChangeException("Error enabling trigger: " + ex);
    }
}
Also used : SQLException(java.sql.SQLException) ResultSet(java.sql.ResultSet) CustomChangeException(liquibase.exception.CustomChangeException) JdbcConnection(liquibase.database.jvm.JdbcConnection) DatabaseMetaData(java.sql.DatabaseMetaData) DatabaseException(liquibase.exception.DatabaseException)

Example 34 with CustomChangeException

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

the class MigrateConceptReferenceTermChangeSet method execute.

/**
 * @see liquibase.change.custom.CustomTaskChange#execute(liquibase.database.Database)
 */
@Override
public void execute(Database database) throws CustomChangeException {
    final JdbcConnection connection = (JdbcConnection) database.getConnection();
    Boolean prevAutoCommit = null;
    PreparedStatement selectTypes = null;
    PreparedStatement batchUpdateMap = null;
    PreparedStatement selectMap = null;
    PreparedStatement updateMapTerm = null;
    PreparedStatement insertTerm = null;
    PreparedStatement updateMapType = null;
    try {
        prevAutoCommit = connection.getAutoCommit();
        connection.setAutoCommit(false);
        // Prepare a list of types and their ids.
        Map<String, Integer> typesToIds = new HashMap<>();
        selectTypes = connection.prepareStatement("select * from concept_map_type");
        selectTypes.execute();
        ResultSet selectTypeResult = selectTypes.getResultSet();
        while (selectTypeResult.next()) {
            typesToIds.put(selectTypeResult.getString("name").trim().toUpperCase(), selectTypeResult.getInt("concept_map_type_id"));
        }
        selectTypes.close();
        // The FK on concept_reference_term_id is not yet created so we are safe to copy over IDs.
        // The trims are done to be able to compare properly.
        batchUpdateMap = connection.prepareStatement("update concept_reference_map set" + " concept_reference_term_id = concept_map_id," + " source_code = trim(source_code), comment = trim(comment)");
        batchUpdateMap.execute();
        batchUpdateMap.close();
        // Preparing statements for use in the loop.
        updateMapTerm = connection.prepareStatement("update concept_reference_map set" + " concept_reference_term_id = ? where concept_map_id = ?");
        insertTerm = connection.prepareStatement("insert into concept_reference_term" + " (concept_reference_term_id, uuid, concept_source_id, code, creator, date_created, description)" + " values (?, ?, ?, ?, ?, ?, ?)");
        updateMapType = connection.prepareStatement("update concept_reference_map set" + " concept_map_type_id = ? where concept_map_id = ?");
        int prevSource = -1;
        String prevSourceCode = null;
        String prevComment = null;
        int prevInsertedTerm = -1;
        // In addition to source and source_code we order by UUID to always insert the same term if run on different systems.
        selectMap = connection.prepareStatement("select * from concept_reference_map" + " order by source, source_code, uuid");
        selectMap.execute();
        final ResultSet selectMapResult = selectMap.getResultSet();
        while (selectMapResult.next()) {
            final int conceptMapId = selectMapResult.getInt("concept_map_id");
            final int source = selectMapResult.getInt("source");
            final String sourceCode = selectMapResult.getString("source_code");
            final String comment = selectMapResult.getString("comment");
            final int creator = selectMapResult.getInt("creator");
            final Date dateCreated = selectMapResult.getDate("date_created");
            final String uuid = selectMapResult.getString("uuid");
            final Integer mapTypeId = determineMapTypeId(comment, typesToIds);
            final int updatedMapTypeId = (mapTypeId == null) ? typesToIds.get(DEFAULT_CONCEPT_MAP_TYPE) : mapTypeId;
            updateMapType.setInt(1, updatedMapTypeId);
            updateMapType.setInt(2, conceptMapId);
            updateMapType.execute();
            if (updateMapType.getUpdateCount() != 1) {
                throw new CustomChangeException("Failed to set map type: " + mapTypeId + " for map: " + conceptMapId + ", updated rows: " + updateMapType.getUpdateCount());
            }
            if (source == prevSource && (sourceCode == prevSourceCode || (sourceCode != null && sourceCode.equals(prevSourceCode)))) {
                if (mapTypeId == null && comment != null && !comment.equals(prevComment)) {
                    log.warn("Lost comment '" + comment + "' for map " + conceptMapId + ". Preserved comment " + prevComment);
                }
                // We need to use the last inserted term.
                updateMapTerm.setInt(1, prevInsertedTerm);
                updateMapTerm.setInt(2, conceptMapId);
                updateMapTerm.execute();
                if (updateMapTerm.getUpdateCount() != 1) {
                    throw new CustomChangeException("Failed to set reference term: " + prevInsertedTerm + " for map: " + conceptMapId + ", updated rows: " + updateMapTerm.getUpdateCount());
                }
            } else {
                insertTerm.setInt(1, conceptMapId);
                // We need to guaranty that UUIDs are always the same when run on different systems.
                insertTerm.setString(2, UUID.nameUUIDFromBytes(uuid.getBytes(StandardCharsets.UTF_8)).toString());
                insertTerm.setInt(3, source);
                insertTerm.setString(4, sourceCode);
                insertTerm.setInt(5, creator);
                insertTerm.setDate(6, dateCreated);
                if (mapTypeId == null) {
                    insertTerm.setString(7, comment);
                } else {
                    insertTerm.setString(7, null);
                }
                insertTerm.execute();
                prevInsertedTerm = conceptMapId;
            }
            prevSource = source;
            prevSourceCode = sourceCode;
            prevComment = comment;
        }
        selectMap.close();
        updateMapType.close();
        updateMapTerm.close();
        insertTerm.close();
        connection.commit();
    } catch (Exception e) {
        try {
            if (connection != null) {
                connection.rollback();
            }
        } catch (Exception ex) {
            log.error("Failed to rollback", ex);
        }
        throw new CustomChangeException(e);
    } finally {
        closeStatementQuietly(selectTypes);
        closeStatementQuietly(batchUpdateMap);
        closeStatementQuietly(selectMap);
        closeStatementQuietly(updateMapTerm);
        closeStatementQuietly(insertTerm);
        closeStatementQuietly(updateMapType);
        if (connection != null && prevAutoCommit != null) {
            try {
                connection.setAutoCommit(prevAutoCommit);
            } catch (DatabaseException e) {
                log.error("Failed to reset auto commit", e);
            }
        }
    }
}
Also used : HashMap(java.util.HashMap) CustomChangeException(liquibase.exception.CustomChangeException) JdbcConnection(liquibase.database.jvm.JdbcConnection) PreparedStatement(java.sql.PreparedStatement) Date(java.sql.Date) DatabaseException(liquibase.exception.DatabaseException) CustomChangeException(liquibase.exception.CustomChangeException) SetupException(liquibase.exception.SetupException) SQLException(java.sql.SQLException) ResultSet(java.sql.ResultSet) DatabaseException(liquibase.exception.DatabaseException)

Example 35 with CustomChangeException

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

the class MigrateDrugOrderUnitsToCodedDoseUnitsChangeset method execute.

@Override
public void execute(Database database) throws CustomChangeException {
    JdbcConnection connection = (JdbcConnection) database.getConnection();
    try {
        Set<String> uniqueUnits = DatabaseUtil.getUniqueNonNullColumnValues("units", "drug_order", String.class, connection.getUnderlyingConnection());
        migrateUnitsToCodedValue(connection, uniqueUnits);
    } catch (Exception e) {
        throw new CustomChangeException(e);
    }
}
Also used : CustomChangeException(liquibase.exception.CustomChangeException) JdbcConnection(liquibase.database.jvm.JdbcConnection) DatabaseException(liquibase.exception.DatabaseException) CustomChangeException(liquibase.exception.CustomChangeException) SetupException(liquibase.exception.SetupException) SQLException(java.sql.SQLException)

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