Search in sources :

Example 21 with CustomChangeException

use of liquibase.exception.CustomChangeException in project NativeCriteria by pnowy.

the class ImportPicture method generateStatements.

@Override
public SqlStatement[] generateStatements(Database database) throws CustomChangeException {
    JdbcConnection connection = (JdbcConnection) database.getConnection();
    final String sql = "INSERT INTO IMAGE(NAME, CONTENT) VALUES (?, ?)";
    try (PreparedStatement ps = connection.prepareStatement(sql)) {
        ps.setString(1, "pn.png");
        ps.setBlob(2, png);
        ps.executeUpdate();
    } catch (Exception e) {
        log.error("", e);
        throw new CustomChangeException("Cannot insert image data!", e);
    } finally {
        try {
            png.close();
        } catch (Exception ignore) {
        }
    }
    return new SqlStatement[0];
}
Also used : SqlStatement(liquibase.statement.SqlStatement) CustomChangeException(liquibase.exception.CustomChangeException) JdbcConnection(liquibase.database.jvm.JdbcConnection) PreparedStatement(java.sql.PreparedStatement) CustomChangeException(liquibase.exception.CustomChangeException) SetupException(liquibase.exception.SetupException)

Example 22 with CustomChangeException

use of liquibase.exception.CustomChangeException in project openmrs-module-mirebalais by PIH.

the class PrintingIDCardStatusChangeSet method executeUpdate.

/**
 * Executes a SQL update
 * @throws CustomChangeException
 */
protected void executeUpdate(StringBuilder sql, Database database) throws CustomChangeException {
    PreparedStatement s = null;
    try {
        JdbcConnection connection = (JdbcConnection) database.getConnection();
        s = connection.prepareStatement(sql.toString());
        s.executeUpdate();
    } catch (Exception e) {
        throw new CustomChangeException("Failed to execute sql: " + sql.toString());
    } finally {
        try {
            if (s != null) {
                s.close();
            }
        } catch (Exception e) {
        }
    }
}
Also used : CustomChangeException(liquibase.exception.CustomChangeException) PreparedStatement(java.sql.PreparedStatement) JdbcConnection(liquibase.database.jvm.JdbcConnection) CustomChangeException(liquibase.exception.CustomChangeException) SetupException(liquibase.exception.SetupException)

Example 23 with CustomChangeException

use of liquibase.exception.CustomChangeException 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 24 with CustomChangeException

use of liquibase.exception.CustomChangeException 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 25 with CustomChangeException

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

the class ConvertOrderersToProviders method execute.

@Override
public void execute(Database database) throws CustomChangeException {
    JdbcConnection connection = (JdbcConnection) database.getConnection();
    try {
        List<List<Object>> usersAndProviders = getUsersAndProviders(connection);
        convertOrdererToProvider(connection, usersAndProviders);
    } catch (Exception e) {
        throw new CustomChangeException(e);
    }
}
Also used : CustomChangeException(liquibase.exception.CustomChangeException) JdbcConnection(liquibase.database.jvm.JdbcConnection) List(java.util.List) 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