Search in sources :

Example 1 with Executor

use of liquibase.executor.Executor in project liquibase by liquibase.

the class PreconditionContainer method check.

@Override
public void check(Database database, DatabaseChangeLog changeLog, ChangeSet changeSet) throws PreconditionFailedException, PreconditionErrorException {
    String ranOn = String.valueOf(changeLog);
    if (changeSet != null) {
        ranOn = String.valueOf(changeSet);
    }
    Executor executor = ExecutorService.getInstance().getExecutor(database);
    try {
        // Three cases for preConditions onUpdateSQL:
        // 1. TEST: preConditions should be run, as in regular update mode
        // 2. FAIL: the preConditions should fail if there are any
        // 3. IGNORE: act as if preConditions don't exist
        boolean testPrecondition = false;
        if (executor.updatesDatabase()) {
            testPrecondition = true;
        } else {
            if (this.getOnSqlOutput().equals(PreconditionContainer.OnSqlOutputOption.TEST)) {
                testPrecondition = true;
            } else if (this.getOnSqlOutput().equals(PreconditionContainer.OnSqlOutputOption.FAIL)) {
                throw new PreconditionFailedException("Unexpected precondition in updateSQL mode with onUpdateSQL value: " + this.getOnSqlOutput(), changeLog, this);
            } else if (this.getOnSqlOutput().equals(PreconditionContainer.OnSqlOutputOption.IGNORE)) {
                testPrecondition = false;
            }
        }
        if (testPrecondition) {
            super.check(database, changeLog, changeSet);
        }
    } catch (PreconditionFailedException e) {
        StringBuffer message = new StringBuffer();
        message.append("     ").append(e.getFailedPreconditions().size()).append(" preconditions failed").append(StreamUtil.getLineSeparator());
        for (FailedPrecondition invalid : e.getFailedPreconditions()) {
            message.append("     ").append(invalid.toString());
            message.append(StreamUtil.getLineSeparator());
        }
        if (getOnFailMessage() != null) {
            message = new StringBuffer(getOnFailMessage());
        }
        if (this.getOnFail().equals(PreconditionContainer.FailOption.WARN)) {
            LogFactory.getLogger().info("Executing: " + ranOn + " despite precondition failure due to onFail='WARN':\n " + message);
        } else {
            if (getOnFailMessage() == null) {
                throw e;
            } else {
                throw new PreconditionFailedException(getOnFailMessage(), changeLog, this);
            }
        }
    } catch (PreconditionErrorException e) {
        StringBuffer message = new StringBuffer();
        message.append("     ").append(e.getErrorPreconditions().size()).append(" preconditions failed").append(StreamUtil.getLineSeparator());
        for (ErrorPrecondition invalid : e.getErrorPreconditions()) {
            message.append("     ").append(invalid.toString());
            message.append(StreamUtil.getLineSeparator());
        }
        if (this.getOnError().equals(PreconditionContainer.ErrorOption.CONTINUE)) {
            LogFactory.getLogger().info("Continuing past: " + toString() + " despite precondition error:\n " + message);
            throw e;
        } else if (this.getOnError().equals(PreconditionContainer.ErrorOption.WARN)) {
            LogFactory.getLogger().warning("Continuing past: " + toString() + " despite precondition error:\n " + message);
        } else {
            if (getOnErrorMessage() == null) {
                throw e;
            } else {
                throw new PreconditionErrorException(getOnErrorMessage(), e.getErrorPreconditions());
            }
        }
    }
}
Also used : Executor(liquibase.executor.Executor) ErrorPrecondition(liquibase.precondition.ErrorPrecondition) FailedPrecondition(liquibase.precondition.FailedPrecondition)

Example 2 with Executor

use of liquibase.executor.Executor in project liquibase by liquibase.

the class ChangeSet method rollback.

public void rollback(Database database) throws RollbackFailedException {
    try {
        Executor executor = ExecutorService.getInstance().getExecutor(database);
        executor.comment("Rolling Back ChangeSet: " + toString());
        database.setObjectQuotingStrategy(objectQuotingStrategy);
        // set auto-commit based on runInTransaction if database supports DDL in transactions
        if (database.supportsDDLInTransaction()) {
            database.setAutoCommit(!runInTransaction);
        }
        RanChangeSet ranChangeSet = database.getRanChangeSet(this);
        if (hasCustomRollbackChanges()) {
            final List<SqlStatement> statements = new LinkedList<SqlStatement>();
            for (Change change : rollback.getChanges()) {
                if (((change instanceof DbmsTargetedChange)) && !DatabaseList.definitionMatches(((DbmsTargetedChange) change).getDbms(), database, true)) {
                    continue;
                }
                ValidationErrors errors = change.validate(database);
                if (errors.hasErrors()) {
                    throw new RollbackFailedException("Rollback statement failed validation: " + errors.toString());
                }
                SqlStatement[] changeStatements = change.generateStatements(database);
                if (changeStatements != null) {
                    statements.addAll(Arrays.asList(changeStatements));
                }
            }
            if (!statements.isEmpty()) {
                database.executeRollbackStatements(statements.toArray(new SqlStatement[] {}), sqlVisitors);
            }
        } else {
            List<Change> changes = getChanges();
            for (int i = changes.size() - 1; i >= 0; i--) {
                Change change = changes.get(i);
                database.executeRollbackStatements(change, sqlVisitors);
            }
        }
        if (runInTransaction) {
            database.commit();
        }
        log.debug("ChangeSet " + toString() + " has been successfully rolled back.");
    } catch (Exception e) {
        try {
            database.rollback();
        } catch (DatabaseException e1) {
        //ok
        }
        throw new RollbackFailedException(e);
    } finally {
        // but only if the database supports DDL in transactions
        if (!runInTransaction && database.supportsDDLInTransaction()) {
            try {
                database.setAutoCommit(false);
            } catch (DatabaseException e) {
                throw new RollbackFailedException("Could not resetInternalState autocommit", e);
            }
        }
    }
}
Also used : Change(liquibase.change.Change) EmptyChange(liquibase.change.core.EmptyChange) RawSQLChange(liquibase.change.core.RawSQLChange) DbmsTargetedChange(liquibase.change.DbmsTargetedChange) ParsedNodeException(liquibase.parser.core.ParsedNodeException) SqlStatement(liquibase.statement.SqlStatement) Executor(liquibase.executor.Executor) DbmsTargetedChange(liquibase.change.DbmsTargetedChange)

Example 3 with Executor

use of liquibase.executor.Executor in project liquibase by liquibase.

the class Liquibase method update.

public void update(String tag, Contexts contexts, LabelExpression labelExpression, Writer output) throws LiquibaseException {
    if (tag == null) {
        update(contexts, labelExpression, output);
        return;
    }
    changeLogParameters.setContexts(contexts);
    changeLogParameters.setLabels(labelExpression);
    Executor oldTemplate = ExecutorService.getInstance().getExecutor(database);
    LoggingExecutor loggingExecutor = new LoggingExecutor(ExecutorService.getInstance().getExecutor(database), output, database);
    ExecutorService.getInstance().setExecutor(database, loggingExecutor);
    outputHeader("Update to '" + tag + "' Database Script");
    update(tag, contexts, labelExpression);
    try {
        output.flush();
    } catch (IOException e) {
        throw new LiquibaseException(e);
    }
    resetServices();
    ExecutorService.getInstance().setExecutor(database, oldTemplate);
}
Also used : Executor(liquibase.executor.Executor) LoggingExecutor(liquibase.executor.LoggingExecutor) LoggingExecutor(liquibase.executor.LoggingExecutor) UnexpectedLiquibaseException(liquibase.exception.UnexpectedLiquibaseException) LiquibaseException(liquibase.exception.LiquibaseException)

Example 4 with Executor

use of liquibase.executor.Executor in project liquibase by liquibase.

the class Liquibase method markNextChangeSetRan.

public void markNextChangeSetRan(Contexts contexts, LabelExpression labelExpression, Writer output) throws LiquibaseException {
    changeLogParameters.setContexts(contexts);
    changeLogParameters.setLabels(labelExpression);
    LoggingExecutor outputTemplate = new LoggingExecutor(ExecutorService.getInstance().getExecutor(database), output, database);
    Executor oldTemplate = ExecutorService.getInstance().getExecutor(database);
    ExecutorService.getInstance().setExecutor(database, outputTemplate);
    outputHeader("SQL to add all changesets to database history table");
    markNextChangeSetRan(contexts, labelExpression);
    try {
        output.flush();
    } catch (IOException e) {
        throw new LiquibaseException(e);
    }
    ExecutorService.getInstance().setExecutor(database, oldTemplate);
    resetServices();
}
Also used : Executor(liquibase.executor.Executor) LoggingExecutor(liquibase.executor.LoggingExecutor) LoggingExecutor(liquibase.executor.LoggingExecutor) UnexpectedLiquibaseException(liquibase.exception.UnexpectedLiquibaseException) LiquibaseException(liquibase.exception.LiquibaseException)

Example 5 with Executor

use of liquibase.executor.Executor in project liquibase by liquibase.

the class DiffToChangeLog method addDependencies.

/**
     * Adds dependencies to the graph as schema.object_name.
     */
protected void addDependencies(DependencyUtil.DependencyGraph<String> graph, List<String> schemas, Collection<DatabaseObject> missingObjects, Database database) throws DatabaseException {
    if (database instanceof DB2Database) {
        Executor executor = ExecutorService.getInstance().getExecutor(database);
        List<Map<String, ?>> rs = executor.queryForList(new RawSqlStatement("select TABSCHEMA, TABNAME, BSCHEMA, BNAME from syscat.tabdep where (" + StringUtils.join(schemas, " OR ", new StringUtils.StringUtilsFormatter<String>() {

            @Override
            public String toString(String obj) {
                return "TABSCHEMA='" + obj + "'";
            }
        }) + ")"));
        for (Map<String, ?> row : rs) {
            String tabName = StringUtils.trimToNull((String) row.get("TABSCHEMA")) + "." + StringUtils.trimToNull((String) row.get("TABNAME"));
            String bName = StringUtils.trimToNull((String) row.get("BSCHEMA")) + "." + StringUtils.trimToNull((String) row.get("BNAME"));
            graph.add(bName, tabName);
        }
    } else if (database instanceof OracleDatabase) {
        Executor executor = ExecutorService.getInstance().getExecutor(database);
        List<Map<String, ?>> rs = executor.queryForList(new RawSqlStatement("select OWNER, NAME, REFERENCED_OWNER, REFERENCED_NAME from DBA_DEPENDENCIES where REFERENCED_OWNER != 'SYS' AND NOT(NAME LIKE 'BIN$%') AND NOT(OWNER = REFERENCED_OWNER AND NAME = REFERENCED_NAME) AND (" + StringUtils.join(schemas, " OR ", new StringUtils.StringUtilsFormatter<String>() {

            @Override
            public String toString(String obj) {
                return "OWNER='" + obj + "'";
            }
        }) + ")"));
        for (Map<String, ?> row : rs) {
            String tabName = StringUtils.trimToNull((String) row.get("OWNER")) + "." + StringUtils.trimToNull((String) row.get("NAME"));
            String bName = StringUtils.trimToNull((String) row.get("REFERENCED_OWNER")) + "." + StringUtils.trimToNull((String) row.get("REFERENCED_NAME"));
            graph.add(bName, tabName);
        }
    } else if (database instanceof MSSQLDatabase && database.getDatabaseMajorVersion() >= 9) {
        Executor executor = ExecutorService.getInstance().getExecutor(database);
        String sql = "select object_schema_name(referencing_id) as referencing_schema_name, object_name(referencing_id) as referencing_name, object_name(referenced_id) as referenced_name, object_schema_name(referenced_id) as referenced_schema_name  from sys.sql_expression_dependencies depz where (" + StringUtils.join(schemas, " OR ", new StringUtils.StringUtilsFormatter<String>() {

            @Override
            public String toString(String obj) {
                return "object_schema_name(referenced_id)='" + obj + "'";
            }
        }) + ")";
        sql += " UNION select object_schema_name(object_id) as referencing_schema_name, object_name(object_id) as referencing_name, object_name(parent_object_id) as referenced_name, object_schema_name(parent_object_id) as referenced_schema_name " + "from sys.objects " + "where parent_object_id > 0 " + "and is_ms_shipped=0 " + "and (" + StringUtils.join(schemas, " OR ", new StringUtils.StringUtilsFormatter<String>() {

            @Override
            public String toString(String obj) {
                return "object_schema_name(object_id)='" + obj + "'";
            }
        }) + ")";
        sql += " UNION select object_schema_name(fk.object_id) as referencing_schema_name, fk.name as referencing_name, i.name as referenced_name, object_schema_name(i.object_id) as referenced_schema_name " + "from sys.foreign_keys fk " + "join sys.indexes i on fk.referenced_object_id=i.object_id and fk.key_index_id=i.index_id " + "where fk.is_ms_shipped=0 " + "and (" + StringUtils.join(schemas, " OR ", new StringUtils.StringUtilsFormatter<String>() {

            @Override
            public String toString(String obj) {
                return "object_schema_name(fk.object_id)='" + obj + "'";
            }
        }) + ")";
        sql += " UNION select object_schema_name(i.object_id) as referencing_schema_name, object_name(i.object_id) as referencing_name, s.name as referenced_name, null as referenced_schema_name " + "from sys.indexes i " + "join sys.partition_schemes s on i.data_space_id = s.data_space_id";
        sql += " UNION select null as referencing_schema_name, s.name as referencing_name, f.name as referenced_name, null as referenced_schema_name from sys.partition_functions f " + "join sys.partition_schemes s on s.function_id=f.function_id";
        sql += " UNION select null as referencing_schema_name, s.name as referencing_name, fg.name as referenced_name, null as referenced_schema_name from sys.partition_schemes s " + "join sys.destination_data_spaces ds on s.data_space_id=ds.partition_scheme_id " + "join sys.filegroups fg on ds.data_space_id=fg.data_space_id";
        //get data file -> filegroup dependencies
        sql += " UNION select distinct null as referencing_schema_name, f.name as referencing_name, ds.name as referenced_name, null as referenced_schema_name from sys.database_files f " + "join sys.data_spaces ds on f.data_space_id=ds.data_space_id " + "where f.data_space_id > 1";
        //get table -> filestream dependencies
        sql += " UNION select object_schema_name(t.object_id) as referencing_schema_name, t.name as referencing_name, ds.name as referenced_name, null as referenced_schema_name from sys.tables t " + "join sys.data_spaces ds on t.filestream_data_space_id=ds.data_space_id " + "where t.filestream_data_space_id > 1";
        //get table -> filestream dependencies
        sql += " UNION select object_schema_name(t.object_id) as referencing_schema_name, t.name as referencing_name, ds.name as referenced_name, null as referenced_schema_name from sys.tables t " + "join sys.data_spaces ds on t.lob_data_space_id=ds.data_space_id " + "where t.lob_data_space_id > 1";
        //get index -> filegroup dependencies
        sql += " UNION select object_schema_name(i.object_id) as referencing_schema_name, i.name as referencing_name, ds.name as referenced_name, null as referenced_schema_name from sys.indexes i " + "join sys.data_spaces ds on i.data_space_id=ds.data_space_id " + "where i.data_space_id > 1";
        //get index -> table dependencies
        sql += " UNION select object_schema_name(i.object_id) as referencing_schema_name, i.name as referencing_name, object_name(i.object_id) as referenced_name, object_schema_name(i.object_id) as referenced_schema_name from sys.indexes i " + "where " + StringUtils.join(schemas, " OR ", new StringUtils.StringUtilsFormatter<String>() {

            @Override
            public String toString(String obj) {
                return "object_schema_name(i.object_id)='" + obj + "'";
            }
        });
        //get schema -> base object dependencies
        sql += " UNION SELECT SCHEMA_NAME(SCHEMA_ID) as referencing_schema_name, name as referencing_name, PARSENAME(BASE_OBJECT_NAME,1) AS referenced_name, (CASE WHEN PARSENAME(BASE_OBJECT_NAME,2) IS NULL THEN schema_name(schema_id) else PARSENAME(BASE_OBJECT_NAME,2) END) AS referenced_schema_name FROM SYS.SYNONYMS WHERE is_ms_shipped='false' AND " + StringUtils.join(schemas, " OR ", new StringUtils.StringUtilsFormatter<String>() {

            @Override
            public String toString(String obj) {
                return "SCHEMA_NAME(SCHEMA_ID)='" + obj + "'";
            }
        });
        List<Map<String, ?>> rs = executor.queryForList(new RawSqlStatement(sql));
        if (rs.size() > 0) {
            for (Map<String, ?> row : rs) {
                String bName = StringUtils.trimToNull((String) row.get("REFERENCED_SCHEMA_NAME")) + "." + StringUtils.trimToNull((String) row.get("REFERENCED_NAME"));
                String tabName = StringUtils.trimToNull((String) row.get("REFERENCING_SCHEMA_NAME")) + "." + StringUtils.trimToNull((String) row.get("REFERENCING_NAME"));
                if (!bName.equals(tabName)) {
                    graph.add(bName, tabName);
                }
            }
        }
    }
}
Also used : DB2Database(liquibase.database.core.DB2Database) RawSqlStatement(liquibase.statement.core.RawSqlStatement) OracleDatabase(liquibase.database.core.OracleDatabase) Executor(liquibase.executor.Executor) StringUtils(liquibase.util.StringUtils) MSSQLDatabase(liquibase.database.core.MSSQLDatabase)

Aggregations

Executor (liquibase.executor.Executor)52 ExecutorService (liquibase.executor.ExecutorService)40 LoggingExecutor (liquibase.executor.LoggingExecutor)32 LiquibaseException (liquibase.exception.LiquibaseException)18 UnexpectedLiquibaseException (liquibase.exception.UnexpectedLiquibaseException)14 DatabaseException (liquibase.exception.DatabaseException)11 RawSqlStatement (liquibase.statement.core.RawSqlStatement)11 Database (liquibase.database.Database)8 SqlStatement (liquibase.statement.SqlStatement)7 RawSQLChange (liquibase.change.core.RawSQLChange)6 MSSQLDatabase (liquibase.database.core.MSSQLDatabase)6 Map (java.util.Map)4 EmptyChange (liquibase.change.core.EmptyChange)4 ChangeSet (liquibase.changelog.ChangeSet)4 SnapshotControl (liquibase.snapshot.SnapshotControl)4 SQLException (java.sql.SQLException)3 DB2Database (liquibase.database.core.DB2Database)3 ParsedNodeException (liquibase.parser.core.ParsedNodeException)3 ErrorPrecondition (liquibase.precondition.ErrorPrecondition)3 FailedPrecondition (liquibase.precondition.FailedPrecondition)3