Search in sources :

Example 71 with DatabaseException

use of liquibase.exception.DatabaseException in project libresonic by Libresonic.

the class DbmsVersionPrecondition method check.

@Override
public void check(Database database) throws CustomPreconditionFailedException, CustomPreconditionErrorException {
    try {
        int dbMajor = database.getDatabaseMajorVersion();
        int dbMinor = database.getDatabaseMinorVersion();
        if (major != null && !major.equals(dbMajor)) {
            throw new CustomPreconditionFailedException("DBMS Major Version Precondition failed: expected " + major + ", got " + dbMajor);
        }
        if (minor != null && !minor.equals(dbMinor)) {
            throw new CustomPreconditionFailedException("DBMS Minor Version Precondition failed: expected " + minor + ", got " + dbMinor);
        }
    } catch (DatabaseException e) {
        throw new CustomPreconditionErrorException(e.getMessage());
    }
}
Also used : DatabaseException(liquibase.exception.DatabaseException) CustomPreconditionFailedException(liquibase.exception.CustomPreconditionFailedException) CustomPreconditionErrorException(liquibase.exception.CustomPreconditionErrorException)

Example 72 with DatabaseException

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

the class SourceMySqldiffFile method execute.

/**
 * Does the work of executing the file on mysql
 *
 * @see liquibase.change.custom.CustomTaskChange#execute(liquibase.database.Database)
 */
@Override
public void execute(Database database) throws CustomChangeException {
    Properties runtimeProperties = Context.getRuntimeProperties();
    String username = runtimeProperties.getProperty(CONNECTION_USERNAME);
    String password = runtimeProperties.getProperty(CONNECTION_PASSWORD);
    if (username == null) {
        username = System.getProperty(CONNECTION_USERNAME);
    }
    if (password == null) {
        password = System.getProperty(CONNECTION_PASSWORD);
    }
    // if we're in a "generate sql file" mode, quit early
    if (username == null || password == null) {
        return;
    }
    DatabaseConnection connection = database.getConnection();
    // copy the file from the classpath to a real file
    File tmpOutputFile = null;
    try {
        tmpOutputFile = File.createTempFile(sqlFile, "tmp");
        InputStream sqlFileInputStream = fileOpener.getResourceAsStream(sqlFile);
        OutputStream outputStream = new FileOutputStream(tmpOutputFile);
        OpenmrsUtil.copyFile(sqlFileInputStream, outputStream);
    } catch (IOException e) {
        if (tmpOutputFile != null) {
            throw new CustomChangeException("Unable to copy " + sqlFile + " to file: " + tmpOutputFile.getAbsolutePath(), e);
        } else {
            throw new CustomChangeException("Unable to copy " + sqlFile, e);
        }
    }
    // build the mysql command line string
    List<String> commands = new ArrayList<>();
    String databaseName;
    try {
        commands.add("mysql");
        commands.add("-u" + username);
        commands.add("-p" + password);
        String path = tmpOutputFile.getAbsolutePath();
        if (!OpenmrsConstants.UNIX_BASED_OPERATING_SYSTEM) {
            // windows hacks
            path = fixWindowsPathHack(path);
        }
        commands.add("-esource " + path);
        databaseName = connection.getCatalog();
        commands.add(databaseName);
    } catch (DatabaseException e) {
        throw new CustomChangeException("Unable to generate command string for file: " + sqlFile, e);
    }
    // to be used in error messages if this fails
    String errorCommand = "\"mysql -u" + username + " -p -e\"source " + tmpOutputFile.getAbsolutePath() + "\"" + databaseName;
    // run the command line string
    StringBuilder output = new StringBuilder();
    // default to a non-zero exit value in case of exceptions
    Integer exitValue = -1;
    try {
        exitValue = execCmd(tmpOutputFile.getParentFile(), commands.toArray(new String[] {}), output);
    } catch (IOException io) {
        if (io.getMessage().endsWith("not found")) {
            throw new CustomChangeException("Unable to run command: " + commands.get(0) + ".  Make sure that it is on the PATH and then restart your server and try again. " + " Or run " + errorCommand + " at the command line with the appropriate full mysql path", io);
        }
    } catch (Exception e) {
        throw new CustomChangeException("Error while executing command: '" + commands.get(0) + "'", e);
    }
    log.debug("Exec called: " + Collections.singletonList(commands));
    if (exitValue != 0) {
        log.error("There was an error while running the " + commands.get(0) + " command.  Command output: " + output.toString());
        throw new CustomChangeException("There was an error while running the " + commands.get(0) + " command. See your server's error log for the full error output. As an alternative, you" + " can run this command manually on your database to skip over this error.  Run this at the command line " + errorCommand + "  ");
    } else {
        // a normal exit value
        log.debug("Output of exec: " + output);
    }
}
Also used : InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) ArrayList(java.util.ArrayList) CustomChangeException(liquibase.exception.CustomChangeException) IOException(java.io.IOException) Properties(java.util.Properties) CustomChangeException(liquibase.exception.CustomChangeException) SetupException(liquibase.exception.SetupException) IOException(java.io.IOException) DatabaseException(liquibase.exception.DatabaseException) FileOutputStream(java.io.FileOutputStream) DatabaseConnection(liquibase.database.DatabaseConnection) File(java.io.File) DatabaseException(liquibase.exception.DatabaseException)

Example 73 with DatabaseException

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

the class AddConceptMapTypesChangeset method getInt.

/**
 * returns an integer resulting from the execution of an sql statement
 *
 * @param connection a DatabaseConnection
 * @param sql the sql statement to execute
 * @return integer resulting from the execution of the sql statement
 */
private int getInt(JdbcConnection connection, String sql) {
    Statement stmt = null;
    int result = 0;
    try {
        stmt = connection.createStatement();
        ResultSet rs = stmt.executeQuery(sql);
        if (rs.next()) {
            result = rs.getInt(1);
        } else {
            log.warn("No row returned by getInt() method");
        }
        if (rs.next()) {
            log.warn("Multiple rows returned by getInt() method");
        }
        return result;
    } catch (DatabaseException | SQLException e) {
        log.warn("Error generated", e);
    } finally {
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                log.warn("Failed to close the statement object");
            }
        }
    }
    return result;
}
Also used : SQLException(java.sql.SQLException) PreparedStatement(java.sql.PreparedStatement) Statement(java.sql.Statement) ResultSet(java.sql.ResultSet) DatabaseException(liquibase.exception.DatabaseException)

Example 74 with DatabaseException

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

the class AddConceptMapTypesChangeset method runBatchInsert.

/**
 * Executes all the changes to the concept names as a batch update.
 *
 * @param connection The database connection
 */
private void runBatchInsert(JdbcConnection connection) throws CustomChangeException {
    PreparedStatement pStmt = null;
    try {
        connection.setAutoCommit(false);
        Integer userId = DatabaseUpdater.getAuthenticatedUserId();
        // if we have no authenticated user(for API users), set as Daemon
        if (userId == null || userId < 1) {
            userId = getInt(connection, "SELECT min(user_id) FROM users");
            // leave it as null rather than setting it to 0
            if (userId < 1) {
                userId = null;
            }
        }
        // userId is not a param, because it's easier this way if it's null
        pStmt = connection.prepareStatement("INSERT INTO concept_map_type " + "(concept_map_type_id, name, is_hidden, retired, creator, date_created, uuid) VALUES(?,?,?,?," + userId + ",?,?)");
        int mapTypeId = 1;
        for (String map : visibleConceptMapTypeArray) {
            String[] mapTypeAndUuid = map.trim().split("\\|");
            String mapType = mapTypeAndUuid[0];
            String mapUuid = mapTypeAndUuid[1];
            pStmt.setInt(1, mapTypeId);
            pStmt.setString(2, mapType);
            pStmt.setBoolean(3, false);
            pStmt.setBoolean(4, false);
            pStmt.setDate(5, new Date(Calendar.getInstance().getTimeInMillis()));
            pStmt.setString(6, mapUuid);
            pStmt.addBatch();
            mapTypeId++;
        }
        for (String map : hiddenConceptMapTypeArray) {
            String[] mapTypeAndUuid = map.trim().split("\\|");
            String mapType = mapTypeAndUuid[0];
            String mapUuid = mapTypeAndUuid[1];
            pStmt.setInt(1, mapTypeId);
            pStmt.setString(2, mapType);
            pStmt.setBoolean(3, true);
            pStmt.setBoolean(4, false);
            pStmt.setDate(5, new Date(Calendar.getInstance().getTimeInMillis()));
            pStmt.setString(6, mapUuid);
            pStmt.addBatch();
            mapTypeId++;
        }
        try {
            int[] updateCounts = pStmt.executeBatch();
            for (int updateCount : updateCounts) {
                if (updateCount > -1) {
                    log.debug("Successfully executed: updateCount=" + updateCount);
                } else if (updateCount == Statement.SUCCESS_NO_INFO) {
                    log.debug("Successfully executed; No Success info");
                } else if (updateCount == Statement.EXECUTE_FAILED) {
                    log.warn("Failed to execute insert");
                }
            }
            log.debug("Committing inserts...");
            connection.commit();
        } catch (BatchUpdateException be) {
            log.warn("Error generated while processsing batch insert", be);
            int[] updateCounts = be.getUpdateCounts();
            for (int updateCount : updateCounts) {
                if (updateCount > -1) {
                    log.warn("Executed with exception: insertCount=" + updateCount);
                } else if (updateCount == Statement.SUCCESS_NO_INFO) {
                    log.warn("Executed with exception; No Success info");
                } else if (updateCount == Statement.EXECUTE_FAILED) {
                    log.warn("Failed to execute insert with exception");
                }
            }
            try {
                log.debug("Rolling back batch", be);
                connection.rollback();
            } catch (Exception rbe) {
                log.warn("Error generated while rolling back batch insert", be);
            }
            // marks the changeset as a failed one
            throw new CustomChangeException("Failed to insert one or more concept map types", be);
        }
    } catch (DatabaseException | SQLException e) {
        throw new CustomChangeException("Failed to insert one or more concept map types:", e);
    } finally {
        // reset to auto commit mode
        try {
            connection.setAutoCommit(true);
        } catch (DatabaseException e) {
            log.warn("Failed to reset auto commit back to true", e);
        }
        if (pStmt != null) {
            try {
                pStmt.close();
            } catch (SQLException e) {
                log.warn("Failed to close the prepared statement object");
            }
        }
    }
}
Also used : SQLException(java.sql.SQLException) CustomChangeException(liquibase.exception.CustomChangeException) PreparedStatement(java.sql.PreparedStatement) Date(java.sql.Date) BatchUpdateException(java.sql.BatchUpdateException) DatabaseException(liquibase.exception.DatabaseException) CustomChangeException(liquibase.exception.CustomChangeException) SetupException(liquibase.exception.SetupException) SQLException(java.sql.SQLException) DatabaseException(liquibase.exception.DatabaseException) BatchUpdateException(java.sql.BatchUpdateException)

Example 75 with DatabaseException

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

the class ConvertOrderersToProviders method convertOrdererToProvider.

private void convertOrdererToProvider(JdbcConnection connection, List<List<Object>> usersAndProviders) throws CustomChangeException, SQLException, DatabaseException {
    final int batchSize = 1000;
    int index = 0;
    PreparedStatement updateStatement = null;
    Statement statement = connection.createStatement();
    Boolean autoCommit = null;
    try {
        autoCommit = connection.getAutoCommit();
        connection.setAutoCommit(false);
        updateStatement = connection.prepareStatement("UPDATE orders SET orderer = ? WHERE orderer = ?");
        boolean supportsBatchUpdate = connection.getMetaData().supportsBatchUpdates();
        for (List<Object> row : usersAndProviders) {
            updateStatement.setInt(1, (Integer) row.get(1));
            updateStatement.setInt(2, (Integer) row.get(0));
            if (supportsBatchUpdate) {
                updateStatement.addBatch();
                index++;
                if (index % batchSize == 0) {
                    updateStatement.executeBatch();
                }
            } else {
                updateStatement.executeUpdate();
            }
        }
        if (supportsBatchUpdate) {
            updateStatement.executeBatch();
        }
        // Set the orderer for orders with null orderer to Unknown Provider
        statement.execute("UPDATE orders SET orderer = " + "(SELECT provider_id FROM provider WHERE uuid =" + "(SELECT property_value FROM global_property WHERE property = '" + "" + OpenmrsConstants.GP_UNKNOWN_PROVIDER_UUID + "')) " + "WHERE orderer IS NULL");
        connection.commit();
    } catch (DatabaseException | SQLException e) {
        handleError(connection, e);
    } finally {
        if (autoCommit != null) {
            connection.setAutoCommit(autoCommit);
        }
        if (updateStatement != null) {
            updateStatement.close();
        }
        if (statement != null) {
            statement.close();
        }
    }
}
Also used : SQLException(java.sql.SQLException) PreparedStatement(java.sql.PreparedStatement) Statement(java.sql.Statement) 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