Search in sources :

Example 36 with Executor

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

the class Liquibase method rollback.

public void rollback(Date dateToRollBackTo, String rollbackScript, Contexts contexts, LabelExpression labelExpression, Writer output) throws LiquibaseException {
    changeLogParameters.setContexts(contexts);
    changeLogParameters.setLabels(labelExpression);
    @SuppressWarnings("squid:S1941") Executor oldTemplate = getAndReplaceJdbcExecutor(output);
    outputHeader("Rollback to " + dateToRollBackTo + " Script");
    rollback(dateToRollBackTo, contexts, labelExpression);
    flushOutputWriter(output);
    Scope.getCurrentScope().getSingleton(ExecutorService.class).setExecutor("jdbc", database, oldTemplate);
    resetServices();
}
Also used : Executor(liquibase.executor.Executor) LoggingExecutor(liquibase.executor.LoggingExecutor) ExecutorService(liquibase.executor.ExecutorService)

Example 37 with Executor

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

the class Liquibase method doChangeLogSyncSql.

private void doChangeLogSyncSql(String tag, Contexts contexts, LabelExpression labelExpression, Writer output, Supplier<String> header) throws LiquibaseException {
    changeLogParameters.setContexts(contexts);
    changeLogParameters.setLabels(labelExpression);
    runInScope(() -> {
        LoggingExecutor outputTemplate = new LoggingExecutor(Scope.getCurrentScope().getSingleton(ExecutorService.class).getExecutor(database), output, database);
        /* We have no other choice than to save the current Executer here. */
        @SuppressWarnings("squid:S1941") Executor oldTemplate = getAndReplaceJdbcExecutor(output);
        outputHeader("SQL to add all changesets to database history table");
        changeLogSync(tag, contexts, labelExpression);
        flushOutputWriter(output);
        Scope.getCurrentScope().getSingleton(ExecutorService.class).setExecutor("jdbc", database, oldTemplate);
        resetServices();
    });
}
Also used : Executor(liquibase.executor.Executor) LoggingExecutor(liquibase.executor.LoggingExecutor) LoggingExecutor(liquibase.executor.LoggingExecutor) ExecutorService(liquibase.executor.ExecutorService)

Example 38 with Executor

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

the class Liquibase method getConnection.

/**
 * Create or retrieve the Connection object
 *
 * @param   changeLog              Database changelog
 * @return  Connection
 * @throws  LiquibaseHubException  Thrown by HubService
 */
public Connection getConnection(DatabaseChangeLog changeLog) throws LiquibaseHubException {
    // 
    // If our current Executor is a LoggingExecutor then just return since we will not update Hub
    // 
    Executor executor = Scope.getCurrentScope().getSingleton(ExecutorService.class).getExecutor("jdbc", database);
    if (executor instanceof LoggingExecutor) {
        return null;
    }
    String changeLogId = changeLog.getChangeLogId();
    HubUpdater hubUpdater = new HubUpdater(new Date(), changeLog, database);
    if (hubUpdater.hubIsNotAvailable(changeLogId)) {
        if (StringUtil.isNotEmpty(HubConfiguration.LIQUIBASE_HUB_API_KEY.getCurrentValue()) && changeLogId == null) {
            String message = "The API key '" + HubConfiguration.LIQUIBASE_HUB_API_KEY.getCurrentValue() + "' was found, but no changelog ID exists.\n" + "No operations will be reported. Register this changelog with Liquibase Hub to generate free deployment reports.\n" + "Learn more at https://hub.liquibase.com.";
            Scope.getCurrentScope().getUI().sendMessage("WARNING: " + message);
            Scope.getCurrentScope().getLog(getClass()).warning(message);
        }
        return null;
    }
    // 
    if (StringUtil.isEmpty(HubConfiguration.LIQUIBASE_HUB_API_KEY.getCurrentValue()) && changeLogId != null) {
        String message = "The changelog ID '" + changeLogId + "' was found, but no API Key exists.\n" + "No operations will be reported. Simply add a liquibase.hub.apiKey setting to generate free deployment reports.\n" + "Learn more at https://hub.liquibase.com.";
        Scope.getCurrentScope().getUI().sendMessage("WARNING: " + message);
        Scope.getCurrentScope().getLog(getClass()).warning(message);
        return null;
    }
    Connection connection;
    final HubService hubService = Scope.getCurrentScope().getSingleton(HubServiceFactory.class).getService();
    if (getHubConnectionId() == null) {
        HubChangeLog hubChangeLog = hubService.getHubChangeLog(UUID.fromString(changeLogId), "*");
        if (hubChangeLog == null) {
            Scope.getCurrentScope().getLog(getClass()).warning("Retrieving Hub Change Log failed for Changelog ID: " + changeLogId);
            return null;
        }
        if (hubChangeLog.isDeleted()) {
            // 
            // Complain and stop the operation
            // 
            String message = "\n" + "The operation did not complete and will not be reported to Hub because the\n" + "" + "registered changelog has been deleted by someone in your organization.\n" + "Learn more at http://hub.liquibase.com.";
            throw new LiquibaseHubException(message);
        }
        Connection exampleConnection = new Connection();
        exampleConnection.setProject(hubChangeLog.getProject());
        exampleConnection.setJdbcUrl(Liquibase.this.database.getConnection().getURL());
        connection = hubService.getConnection(exampleConnection, true);
        setHubConnectionId(connection.getId());
    } else {
        connection = hubService.getConnection(new Connection().setId(getHubConnectionId()), true);
    }
    return connection;
}
Also used : Executor(liquibase.executor.Executor) LoggingExecutor(liquibase.executor.LoggingExecutor) LoggingExecutor(liquibase.executor.LoggingExecutor) HubChangeLog(liquibase.hub.model.HubChangeLog) ExecutorService(liquibase.executor.ExecutorService) DatabaseConnection(liquibase.database.DatabaseConnection) Connection(liquibase.hub.model.Connection)

Example 39 with Executor

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

the class HubUpdater method postUpdateHubExceptionHandling.

/**
 * Handle Hub exceptions thrown during the operation
 *
 * @param operation                Operation object
 * @param bufferLog                Log output
 * @param originalExceptionMessage Exception thrown by the operation
 */
public void postUpdateHubExceptionHandling(Operation operation, BufferedLogService bufferLog, String originalExceptionMessage) {
    try {
        // 
        // If our current Executor is a LoggingExecutor then just return since we will not update Hub
        // 
        Executor executor = Scope.getCurrentScope().getSingleton(ExecutorService.class).getExecutor("jdbc", database);
        if (executor instanceof LoggingExecutor) {
            return;
        }
        // 
        if (operation == null || hubIsNotAvailable(changeLog.getChangeLogId())) {
            return;
        }
        // 
        // Capture the current log level to use for filtering
        // 
        Level currentLevel = HubConfiguration.LIQUIBASE_HUB_LOGLEVEL.getCurrentValue();
        // 
        // Check to see if the changelog has been deactivated
        // 
        final HubService hubService = Scope.getCurrentScope().getSingleton(HubServiceFactory.class).getService();
        final HubChangeLog hubChangeLog = hubService.getHubChangeLog(UUID.fromString(changeLog.getChangeLogId()));
        if (hubChangeLog.isInactive()) {
            String message = "\n" + "The command completed and reported to Hub, but changelog '" + hubChangeLog.getName() + "' has been deactivated by someone in your organization.\n" + "To synchronize your changelog, checkout the latest from source control or run \"deactivatechangelog\".\n" + "After that, commands run against this changelog will not be reported to Hub until \"registerchangelog\" is run again.\n" + "Learn more at http://hub.liquibase.com";
            Scope.getCurrentScope().getLog(HubUpdater.class).warning(message);
            Scope.getCurrentScope().getUI().sendMessage("WARNING: " + message);
        }
        hubService.sendOperationEvent(operation, new OperationEvent().setEventType("COMPLETE").setStartDate(startTime).setEndDate(new Date()).setOperationEventStatus(new OperationEvent.OperationEventStatus().setOperationEventStatusType("FAIL").setStatusMessage(String.format("%s operation completed with errors", operation.getOperationStatus().getOperationStatusType()))).setOperationEventLog(new OperationEvent.OperationEventLog().setLogMessage(bufferLog.getLogAsString(currentLevel))));
        // 
        if (hubChangeLog.isActive()) {
            showOperationReportLink(operation, hubService);
        }
    } catch (LiquibaseException serviceException) {
        Scope.getCurrentScope().getLog(getClass()).warning(originalExceptionMessage, serviceException);
    }
}
Also used : Date(java.util.Date) Executor(liquibase.executor.Executor) LoggingExecutor(liquibase.executor.LoggingExecutor) LoggingExecutor(liquibase.executor.LoggingExecutor) ExecutorService(liquibase.executor.ExecutorService) Level(java.util.logging.Level) LiquibaseException(liquibase.exception.LiquibaseException)

Example 40 with Executor

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

the class InternalExecuteSqlCommandStep method run.

@Override
public void run(CommandResultsBuilder resultsBuilder) throws Exception {
    CommandScope commandScope = resultsBuilder.getCommandScope();
    Database database = commandScope.getArgumentValue(DATABASE_ARG);
    String sql = commandScope.getArgumentValue(SQL_ARG);
    String sqlFile = commandScope.getArgumentValue(SQLFILE_ARG);
    Executor executor = Scope.getCurrentScope().getSingleton(ExecutorService.class).getExecutor("jdbc", database);
    String sqlText;
    if (sqlFile == null) {
        sqlText = sql;
    } else {
        File file = new File(sqlFile);
        if (!file.exists()) {
            throw new LiquibaseException(String.format("The file '%s' does not exist", file.getCanonicalPath()));
        }
        sqlText = FileUtil.getContents(file);
    }
    String out = "";
    String[] sqlStrings = StringUtil.processMultiLineSQL(sqlText, true, true, commandScope.getArgumentValue(DELIMITER_ARG));
    for (String sqlString : sqlStrings) {
        if (sqlString.toLowerCase().matches("\\s*select .*")) {
            List<Map<String, ?>> rows = executor.queryForList(new RawSqlStatement(sqlString));
            out += "Output of " + sqlString + ":\n";
            if (rows.isEmpty()) {
                out += "-- Empty Resultset --\n";
            } else {
                SortedSet<String> keys = new TreeSet<>();
                for (Map<String, ?> row : rows) {
                    keys.addAll(row.keySet());
                }
                out += StringUtil.join(keys, " | ") + " |\n";
                for (Map<String, ?> row : rows) {
                    for (String key : keys) {
                        out += row.get(key) + " | ";
                    }
                    out += "\n";
                }
            }
        } else {
            executor.execute(new RawSqlStatement(sqlString));
            out += "Successfully Executed: " + sqlString + "\n";
        }
        out += "\n";
    }
    database.commit();
    resultsBuilder.addResult("output", out.trim());
// Scope.getCurrentScope().getUI().sendMessage(out.trim());
}
Also used : RawSqlStatement(liquibase.statement.core.RawSqlStatement) Executor(liquibase.executor.Executor) TreeSet(java.util.TreeSet) Database(liquibase.database.Database) ExecutorService(liquibase.executor.ExecutorService) LiquibaseException(liquibase.exception.LiquibaseException) File(java.io.File) Map(java.util.Map)

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