Search in sources :

Example 76 with DatabaseException

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

the class CreateDiscontinueOrders method getDiscontinuedOrders.

private List<DiscontinuedOrder> getDiscontinuedOrders(JdbcConnection connection) throws CustomChangeException, SQLException {
    List<DiscontinuedOrder> dcOrders = new ArrayList<>();
    PreparedStatement statement = null;
    try {
        statement = connection.prepareStatement("select order_id, concept_id, patient_id, encounter_id, date_stopped, " + "discontinued_by, discontinued_reason, discontinued_reason_non_coded, order_type_id " + "from orders where discontinued = ?");
        statement.setBoolean(1, true);
        ResultSet rs = statement.executeQuery();
        while (rs.next()) {
            dcOrders.add(new DiscontinuedOrder(rs.getInt("order_id"), rs.getInt("concept_id"), rs.getInt("patient_id"), rs.getInt("encounter_id"), rs.getInt("discontinued_by"), rs.getInt("discontinued_reason"), rs.getString("discontinued_reason_non_coded"), rs.getDate("date_stopped"), rs.getInt("order_type_id")));
        }
    } catch (SQLException | DatabaseException e) {
        throw new CustomChangeException(e);
    } finally {
        if (statement != null) {
            statement.close();
        }
    }
    return dcOrders;
}
Also used : SQLException(java.sql.SQLException) ArrayList(java.util.ArrayList) ResultSet(java.sql.ResultSet) CustomChangeException(liquibase.exception.CustomChangeException) PreparedStatement(java.sql.PreparedStatement) DatabaseException(liquibase.exception.DatabaseException)

Example 77 with DatabaseException

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

the class CreateDiscontinueOrders method createDiscontinueOrders.

private void createDiscontinueOrders(JdbcConnection connection, List<DiscontinuedOrder> discontinuedOrders) throws CustomChangeException, SQLException, DatabaseException {
    final int batchSize = 1000;
    int index = 0;
    PreparedStatement insertStatement = null;
    Boolean autoCommit = null;
    try {
        autoCommit = connection.getAutoCommit();
        connection.setAutoCommit(false);
        insertStatement = connection.prepareStatement("Insert into orders(previous_order_id, concept_id, patient_id, encounter_id, " + "creator, date_created, discontinued_reason, discontinued_reason_non_coded, " + "uuid, order_action, orderer, order_number, order_type_id, start_date, auto_expire_date) " + "values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        for (DiscontinuedOrder discontinuedOrder : discontinuedOrders) {
            insertStatement.setInt(1, discontinuedOrder.previousOrderId);
            insertStatement.setInt(2, discontinuedOrder.conceptId);
            insertStatement.setInt(3, discontinuedOrder.patientId);
            setIntOrNull(insertStatement, 4, discontinuedOrder.encounterId);
            insertStatement.setInt(5, discontinuedOrder.discontinuedById);
            insertStatement.setDate(6, new Date(System.currentTimeMillis()));
            setIntOrNull(insertStatement, 7, discontinuedOrder.discontinuedReasonId);
            insertStatement.setString(8, discontinuedOrder.discontinuedReasonNonCoded);
            insertStatement.setString(9, UUID.randomUUID().toString());
            insertStatement.setString(10, Order.Action.DISCONTINUE.name());
            setIntOrNull(insertStatement, 11, discontinuedOrder.discontinuedById);
            insertStatement.setString(12, discontinuedOrder.orderNumber);
            insertStatement.setInt(13, discontinuedOrder.orderTypeId);
            insertStatement.setDate(14, discontinuedOrder.dateActivated);
            insertStatement.setDate(15, discontinuedOrder.dateActivated);
            insertStatement.addBatch();
            if (index % batchSize == 0) {
                insertStatement.executeBatch();
            }
            index++;
        }
        insertStatement.executeBatch();
        connection.commit();
    } catch (DatabaseException | SQLException e) {
        handleError(connection, e);
    } finally {
        if (autoCommit != null) {
            connection.setAutoCommit(autoCommit);
        }
        if (insertStatement != null) {
            insertStatement.close();
        }
    }
}
Also used : SQLException(java.sql.SQLException) PreparedStatement(java.sql.PreparedStatement) DatabaseException(liquibase.exception.DatabaseException) Date(java.sql.Date)

Example 78 with DatabaseException

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

the class DuplicateLocationAttributeTypeNameChangeSet method execute.

/**
 * Method to perform validation and resolution of duplicate LocationAttributeType names
 */
@Override
public void execute(Database database) throws CustomChangeException {
    JdbcConnection connection = (JdbcConnection) database.getConnection();
    Map<String, HashSet<Integer>> duplicates = new HashMap<>();
    Statement stmt = null;
    PreparedStatement pStmt = null;
    ResultSet rs = null;
    boolean autoCommit = true;
    try {
        // set auto commit mode to false for UPDATE action
        autoCommit = connection.getAutoCommit();
        connection.setAutoCommit(false);
        stmt = connection.createStatement();
        rs = stmt.executeQuery("SELECT * FROM location_attribute_type " + "INNER JOIN (SELECT name FROM location_attribute_type GROUP BY name HAVING count(name) > 1) " + "dup ON location_attribute_type.name = dup.name");
        Integer id;
        String name;
        while (rs.next()) {
            id = rs.getInt("location_attribute_type_id");
            name = rs.getString("name");
            if (duplicates.get(name) == null) {
                HashSet<Integer> results = new HashSet<>();
                results.add(id);
                duplicates.put(name, results);
            } else {
                HashSet<Integer> results = duplicates.get(name);
                results.add(id);
            }
        }
        for (Object o : duplicates.entrySet()) {
            Map.Entry pairs = (Map.Entry) o;
            HashSet values = (HashSet) pairs.getValue();
            List<Integer> duplicateNames = new ArrayList<Integer>(values);
            int duplicateNameId = 1;
            for (int i = 1; i < duplicateNames.size(); i++) {
                String newName = pairs.getKey() + "_" + duplicateNameId;
                List<List<Object>> duplicateResult;
                boolean duplicateName;
                Connection con = DatabaseUpdater.getConnection();
                do {
                    String sqlValidatorString = "select * from location_attribute_type where name = '" + newName + "'";
                    duplicateResult = DatabaseUtil.executeSQL(con, sqlValidatorString, true);
                    if (!duplicateResult.isEmpty()) {
                        duplicateNameId += 1;
                        newName = pairs.getKey() + "_" + duplicateNameId;
                        duplicateName = true;
                    } else {
                        duplicateName = false;
                    }
                } while (duplicateName);
                pStmt = connection.prepareStatement("update location_attribute_type set name = ?, changed_by = ?, date_changed = ? where location_attribute_type_id = ?");
                if (!duplicateResult.isEmpty()) {
                    pStmt.setString(1, newName);
                }
                pStmt.setString(1, newName);
                pStmt.setInt(2, DatabaseUpdater.getAuthenticatedUserId());
                Calendar cal = Calendar.getInstance();
                Date date = new Date(cal.getTimeInMillis());
                pStmt.setDate(3, date);
                pStmt.setInt(4, duplicateNames.get(i));
                duplicateNameId += 1;
                pStmt.executeUpdate();
            }
        }
    } catch (BatchUpdateException e) {
        log.warn("Error generated while processsing batch insert", e);
        try {
            log.debug("Rolling back batch", e);
            connection.rollback();
        } catch (Exception rbe) {
            log.warn("Error generated while rolling back batch insert", e);
        }
        // marks the changeset as a failed one
        throw new CustomChangeException("Failed to update one or more duplicate LocationAttributeType names", e);
    } catch (Exception e) {
        throw new CustomChangeException("Error while updating duplicate LocationAttributeType object names", e);
    } finally {
        // reset to auto commit mode
        try {
            connection.commit();
            connection.setAutoCommit(autoCommit);
        } catch (DatabaseException e) {
            log.warn("Failed to reset auto commit back to true", e);
        }
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                log.warn("Failed to close the resultset object");
            }
        }
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                log.warn("Failed to close the select statement used to identify duplicate LocationAttributeType object names");
            }
        }
        if (pStmt != null) {
            try {
                pStmt.close();
            } catch (SQLException e) {
                log.warn("Failed to close the prepared statement used to update duplicate LocationAttributeType object names");
            }
        }
    }
}
Also used : HashMap(java.util.HashMap) SQLException(java.sql.SQLException) ArrayList(java.util.ArrayList) CustomChangeException(liquibase.exception.CustomChangeException) JdbcConnection(liquibase.database.jvm.JdbcConnection) ResultSet(java.sql.ResultSet) ArrayList(java.util.ArrayList) List(java.util.List) HashSet(java.util.HashSet) BatchUpdateException(java.sql.BatchUpdateException) PreparedStatement(java.sql.PreparedStatement) Statement(java.sql.Statement) Calendar(java.util.Calendar) Connection(java.sql.Connection) JdbcConnection(liquibase.database.jvm.JdbcConnection) PreparedStatement(java.sql.PreparedStatement) Date(java.sql.Date) BatchUpdateException(java.sql.BatchUpdateException) CustomChangeException(liquibase.exception.CustomChangeException) SetupException(liquibase.exception.SetupException) SQLException(java.sql.SQLException) DatabaseException(liquibase.exception.DatabaseException) HashMap(java.util.HashMap) Map(java.util.Map) DatabaseException(liquibase.exception.DatabaseException)

Example 79 with DatabaseException

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

the class BooleanConceptChangeSet method createConcept.

/**
 * creates a concept
 *
 * @param connection a DatabaseConnection
 * @param names a Map from locale to names in that locale, which will be added to the new
 *            concept
 * @throws CustomChangeException
 */
private Integer createConcept(JdbcConnection connection, Map<String, String[]> names) throws CustomChangeException {
    PreparedStatement updateStatement = null;
    try {
        int conceptId = getInt(connection, "SELECT MAX(concept_id) FROM concept");
        conceptId++;
        updateStatement = connection.prepareStatement("INSERT INTO concept (concept_id, short_name, description, datatype_id, class_id, retired, is_set, creator, date_created, uuid) VALUES (?, '', '', 4, 11, FALSE, FALSE, 1, NOW(), ?)");
        updateStatement.setInt(1, conceptId);
        updateStatement.setString(2, UUID.randomUUID().toString());
        updateStatement.executeUpdate();
        // only tag one name as preferred
        boolean preferredDoneAlready = false;
        int conceptNameId = getInt(connection, "SELECT MAX(concept_name_id) FROM concept_name");
        for (Map.Entry<String, String[]> e : names.entrySet()) {
            String locale = e.getKey();
            for (String name : e.getValue()) {
                conceptNameId++;
                updateStatement = connection.prepareStatement("INSERT INTO concept_name (concept_name_id, concept_id, locale, name, creator, date_created, uuid) VALUES (?, ?, ?, ?, 1, NOW(), ?)");
                updateStatement.setInt(1, conceptNameId);
                updateStatement.setInt(2, conceptId);
                updateStatement.setString(3, locale);
                updateStatement.setString(4, name);
                updateStatement.setString(5, UUID.randomUUID().toString());
                updateStatement.executeUpdate();
                updateStatement.close();
                // fix this before refactoring concept_name_tags.
                if (!preferredDoneAlready && "en".equals(locale)) {
                    updateStatement = connection.prepareStatement("INSERT INTO concept_name_tag_map (concept_name_id, concept_name_tag_id) VALUES (?, 4)");
                    updateStatement.setInt(1, conceptNameId);
                    updateStatement.executeUpdate();
                    updateStatement.close();
                    preferredDoneAlready = true;
                }
                updateStatement = connection.prepareStatement("INSERT INTO concept_word (concept_id, word, locale, concept_name_id) VALUES (?, ?, ?, ?)");
                updateStatement.setInt(1, conceptId);
                updateStatement.setString(2, name);
                updateStatement.setString(3, locale);
                updateStatement.setInt(4, conceptNameId);
                updateStatement.executeUpdate();
            }
        }
        return conceptId;
    } catch (DatabaseException | SQLException e) {
        throw new CustomChangeException("Unable to create concept with names " + names, e);
    } finally {
        if (updateStatement != null) {
            try {
                updateStatement.close();
            } catch (SQLException e) {
            }
        }
    }
}
Also used : SQLException(java.sql.SQLException) CustomChangeException(liquibase.exception.CustomChangeException) PreparedStatement(java.sql.PreparedStatement) HashMap(java.util.HashMap) Map(java.util.Map) DatabaseException(liquibase.exception.DatabaseException)

Example 80 with DatabaseException

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

the class BooleanConceptChangeSet method createGlobalProperties.

/**
 * Inserts global properties 'Concept.true' and 'Concept.false' into the global_property table
 *
 * @param connection a DatabaseConnection
 * @param trueConceptId the concept id for true boolean concept
 * @param falseConceptId the concept id for false boolean concept
 * @throws CustomChangeException
 */
private void createGlobalProperties(JdbcConnection connection, Integer trueConceptId, Integer falseConceptId) throws CustomChangeException {
    if (trueConceptId == null || trueConceptId < 1 || falseConceptId == null || falseConceptId < 1) {
        throw new CustomChangeException("Can't create global properties for true/false concepts with invalid conceptIds");
    }
    PreparedStatement updateStatement = null;
    try {
        updateStatement = connection.prepareStatement("INSERT INTO global_property (property, property_value, description, uuid) VALUES (?, ?, ?, ?)");
        updateStatement.setString(1, OpenmrsConstants.GLOBAL_PROPERTY_TRUE_CONCEPT);
        updateStatement.setInt(2, trueConceptId);
        updateStatement.setString(3, "Concept id of the concept defining the TRUE boolean concept");
        updateStatement.setString(4, UUID.randomUUID().toString());
        updateStatement.executeUpdate();
        updateStatement.setString(1, OpenmrsConstants.GLOBAL_PROPERTY_FALSE_CONCEPT);
        updateStatement.setInt(2, falseConceptId);
        updateStatement.setString(3, "Concept id of the concept defining the FALSE boolean concept");
        updateStatement.setString(4, UUID.randomUUID().toString());
        updateStatement.executeUpdate();
    } catch (DatabaseException | SQLException e) {
        throw new CustomChangeException("Unable to create global properties for concept ids defining boolean concepts", e);
    } finally {
        if (updateStatement != null) {
            try {
                updateStatement.close();
            } catch (SQLException e) {
            }
        }
    }
}
Also used : SQLException(java.sql.SQLException) CustomChangeException(liquibase.exception.CustomChangeException) PreparedStatement(java.sql.PreparedStatement) DatabaseException(liquibase.exception.DatabaseException)

Aggregations

DatabaseException (liquibase.exception.DatabaseException)139 SQLException (java.sql.SQLException)65 JdbcConnection (liquibase.database.jvm.JdbcConnection)34 PreparedStatement (java.sql.PreparedStatement)33 ResultSet (java.sql.ResultSet)28 Statement (java.sql.Statement)24 Database (liquibase.database.Database)24 UnexpectedLiquibaseException (liquibase.exception.UnexpectedLiquibaseException)24 CustomChangeException (liquibase.exception.CustomChangeException)22 CatalogAndSchema (liquibase.CatalogAndSchema)17 LiquibaseException (liquibase.exception.LiquibaseException)16 AbstractJdbcDatabase (liquibase.database.AbstractJdbcDatabase)14 InvalidExampleException (liquibase.snapshot.InvalidExampleException)14 RawSqlStatement (liquibase.statement.core.RawSqlStatement)14 MSSQLDatabase (liquibase.database.core.MSSQLDatabase)13 CachedRow (liquibase.snapshot.CachedRow)13 SqlStatement (liquibase.statement.SqlStatement)13 DatabaseConnection (liquibase.database.DatabaseConnection)12 JdbcDatabaseSnapshot (liquibase.snapshot.JdbcDatabaseSnapshot)12 ArrayList (java.util.ArrayList)11