Search in sources :

Example 21 with DatabaseConnection

use of liquibase.database.DatabaseConnection 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 22 with DatabaseConnection

use of liquibase.database.DatabaseConnection in project liquibase by liquibase.

the class Scope method describe.

public String describe() {
    String databaseName = null;
    Database database = getDatabase();
    if (database != null) {
        databaseName = database.getShortName();
        DatabaseConnection connection = database.getConnection();
        if (connection == null) {
            databaseName = "unconnected " + databaseName;
        } else if (connection instanceof OfflineConnection) {
            databaseName = "offline " + databaseName;
        } else if (connection instanceof JdbcConnection) {
            databaseName = "jdbc " + databaseName;
        }
    }
    return "scope(database=" + databaseName + ")";
}
Also used : Database(liquibase.database.Database) DatabaseConnection(liquibase.database.DatabaseConnection) JdbcConnection(liquibase.database.jvm.JdbcConnection) OfflineConnection(liquibase.database.OfflineConnection)

Example 23 with DatabaseConnection

use of liquibase.database.DatabaseConnection in project liquibase by liquibase.

the class HubUpdater method loadDatabaseMetadata.

// 
// Put database/driver version information in the details map
// 
private void loadDatabaseMetadata() throws DatabaseException, SQLException {
    if (database.getConnection() == null) {
        return;
    }
    final IntegrationDetails integrationDetails = Scope.getCurrentScope().get("integrationDetails", IntegrationDetails.class);
    if (integrationDetails == null) {
        return;
    }
    String databaseProductName = database.getDatabaseProductName();
    String databaseProductVersion = database.getDatabaseProductVersion();
    Scope.getCurrentScope().getLog(getClass()).fine("Database product name         " + databaseProductName);
    Scope.getCurrentScope().getLog(getClass()).fine("Database product version      " + databaseProductVersion);
    DatabaseConnection connection = database.getConnection();
    if (connection instanceof JdbcConnection) {
        JdbcConnection jdbcConnection = (JdbcConnection) connection;
        java.sql.Connection conn = jdbcConnection.getUnderlyingConnection();
        int driverMajorVersion = conn.getMetaData().getDriverMajorVersion();
        int driverMinorVersion = conn.getMetaData().getDriverMinorVersion();
        Scope.getCurrentScope().getLog(getClass()).fine("Database driver version       " + driverMajorVersion + "." + driverMinorVersion);
        integrationDetails.setParameter("db__driverVersion", driverMajorVersion + "." + driverMinorVersion);
    } else {
        integrationDetails.setParameter("db__driverVersion", "Unable to determine");
    }
    integrationDetails.setParameter("db__databaseProduct", databaseProductName);
    integrationDetails.setParameter("db__databaseVersion", databaseProductVersion);
}
Also used : IntegrationDetails(liquibase.integration.IntegrationDetails) DatabaseConnection(liquibase.database.DatabaseConnection) JdbcConnection(liquibase.database.jvm.JdbcConnection)

Example 24 with DatabaseConnection

use of liquibase.database.DatabaseConnection in project liquibase by liquibase.

the class JdbcExecutor method executeDb2ZosComplexStatement.

private void executeDb2ZosComplexStatement(SqlStatement sqlStatement) throws DatabaseException {
    DatabaseConnection con = database.getConnection();
    if (con instanceof OfflineConnection) {
        throw new DatabaseException("Cannot execute commands against an offline database");
    }
    Sql[] sqls = SqlGeneratorFactory.getInstance().generateSql(sqlStatement, database);
    for (Sql sql : sqls) {
        try {
            if (sql instanceof CallableSql) {
                CallableStatement call = null;
                ResultSet resultSet = null;
                try {
                    call = ((JdbcConnection) con).getUnderlyingConnection().prepareCall(sql.toSql());
                    resultSet = call.executeQuery();
                    checkCallStatus(resultSet, ((CallableSql) sql).getExpectedStatus());
                } finally {
                    JdbcUtil.close(resultSet, call);
                }
            } else {
                Statement stmt = null;
                try {
                    stmt = ((JdbcConnection) con).getUnderlyingConnection().createStatement();
                    stmt.execute(sql.toSql());
                    con.commit();
                } finally {
                    JdbcUtil.closeStatement(stmt);
                }
            }
        } catch (Exception e) {
            throw new DatabaseException(e.getMessage() + " [Failed SQL: " + getErrorCode(e) + sql.toSql() + "]", e);
        }
    }
}
Also used : CallableSql(liquibase.sql.CallableSql) CallableStatement(java.sql.CallableStatement) CompoundStatement(liquibase.statement.CompoundStatement) ExecutablePreparedStatement(liquibase.statement.ExecutablePreparedStatement) SqlStatement(liquibase.statement.SqlStatement) CallableSqlStatement(liquibase.statement.CallableSqlStatement) Statement(java.sql.Statement) CallableStatement(java.sql.CallableStatement) ResultSet(java.sql.ResultSet) DatabaseConnection(liquibase.database.DatabaseConnection) JdbcConnection(liquibase.database.jvm.JdbcConnection) OfflineConnection(liquibase.database.OfflineConnection) DatabaseException(liquibase.exception.DatabaseException) SQLException(java.sql.SQLException) DatabaseException(liquibase.exception.DatabaseException) Sql(liquibase.sql.Sql) CallableSql(liquibase.sql.CallableSql)

Example 25 with DatabaseConnection

use of liquibase.database.DatabaseConnection in project liquibase by liquibase.

the class JdbcExecutor method execute.

// Incorrect warning, at least at this point. The situation here is not that we inject some unsanitised parameter
// into a query. Instead, we process a whole query. The check should be performed at the places where
// the query is composed.
@SuppressWarnings("squid:S2077")
public Object execute(CallableStatementCallback action, List<SqlVisitor> sqlVisitors) throws DatabaseException {
    DatabaseConnection con = database.getConnection();
    if (con instanceof OfflineConnection) {
        throw new DatabaseException("Cannot execute commands against an offline database");
    }
    CallableStatement stmt = null;
    try {
        String sql = applyVisitors(action.getStatement(), sqlVisitors)[0];
        stmt = ((JdbcConnection) con).getUnderlyingConnection().prepareCall(sql);
        return action.doInCallableStatement(stmt);
    } catch (SQLException ex) {
        // Release Connection early, to avoid potential connection pool deadlock
        // in the case when the exception translator hasn't been initialized yet.
        JdbcUtil.closeStatement(stmt);
        stmt = null;
        throw new DatabaseException("Error executing SQL " + StringUtil.join(applyVisitors(action.getStatement(), sqlVisitors), "; on " + con.getURL()) + ": " + ex.getMessage(), ex);
    } finally {
        JdbcUtil.closeStatement(stmt);
    }
}
Also used : SQLException(java.sql.SQLException) CallableStatement(java.sql.CallableStatement) DatabaseConnection(liquibase.database.DatabaseConnection) JdbcConnection(liquibase.database.jvm.JdbcConnection) OfflineConnection(liquibase.database.OfflineConnection) DatabaseException(liquibase.exception.DatabaseException)

Aggregations

DatabaseConnection (liquibase.database.DatabaseConnection)36 JdbcConnection (liquibase.database.jvm.JdbcConnection)20 DatabaseException (liquibase.exception.DatabaseException)15 OfflineConnection (liquibase.database.OfflineConnection)12 Database (liquibase.database.Database)11 SQLException (java.sql.SQLException)10 UnexpectedLiquibaseException (liquibase.exception.UnexpectedLiquibaseException)5 RawSqlStatement (liquibase.statement.core.RawSqlStatement)5 Test (org.junit.Test)5 Statement (java.sql.Statement)4 DatabaseFactory (liquibase.database.DatabaseFactory)4 MSSQLDatabase (liquibase.database.core.MSSQLDatabase)4 CallableStatement (java.sql.CallableStatement)3 Connection (java.sql.Connection)3 Liquibase (liquibase.Liquibase)3 PostgresDatabase (liquibase.database.core.PostgresDatabase)3 SqlStatement (liquibase.statement.SqlStatement)3 Method (java.lang.reflect.Method)2 BigInteger (java.math.BigInteger)2 DatabaseMetaData (java.sql.DatabaseMetaData)2