Search in sources :

Example 1 with CommandResults

use of liquibase.command.CommandResults in project liquibase by liquibase.

the class Main method doMigration.

/**
 * Do the actual database migration, i.e. apply the ChangeSets.
 *
 * @throws Exception
 */
protected void doMigration() throws Exception {
    if (COMMANDS.HELP.equalsIgnoreCase(command)) {
        printHelp(System.err);
        return;
    }
    // 
    if (StringUtil.isNotEmpty(HubConfiguration.LIQUIBASE_HUB_API_KEY.getCurrentValue())) {
        LOG.fine("Liquibase Hub API Key:  " + HubConfiguration.LIQUIBASE_HUB_API_KEY.getCurrentValueObfuscated());
    }
    if (StringUtil.isNotEmpty(HubConfiguration.LIQUIBASE_HUB_URL.getCurrentValue())) {
        LOG.fine("Liquibase Hub URL:      " + HubConfiguration.LIQUIBASE_HUB_URL.getCurrentValue());
    }
    LOG.fine("Liquibase Hub Mode:     " + HubConfiguration.LIQUIBASE_HUB_MODE.getCurrentValue());
    // 
    // Check for a valid license to run PRO commands
    // 
    String formatValue = getCommandParam(OPTIONS.FORMAT, null);
    if (isLicenseableCommand(formatValue)) {
        if (isFormattedDiff()) {
            if (formatValue != null && !formatValue.equalsIgnoreCase("json")) {
                String messageString = "\nWARNING: The diff command optional Pro parameter '--format' " + "currently supports only 'TXT' or 'JSON' as values.  (Blank defaults to 'TXT')";
                throw new LiquibaseException(String.format(messageString));
            }
        }
        if (!commandParams.contains("--help") && !liquibaseProLicenseValid) {
            String warningAboutCommand = command;
            if (command.equalsIgnoreCase(COMMANDS.DIFF) && formatValue != null && !formatValue.isEmpty()) {
                warningAboutCommand = "diff --format=" + formatValue;
            }
            String messageString = String.format(coreBundle.getString("no.pro.license.found"), warningAboutCommand);
            throw new LiquibaseException(messageString);
        }
    }
    try {
    // if (null != logFile) {
    // Scope.getCurrentScope().getLog(getClass()).setLogLevel(logLevel, logFile);
    // } else {
    // Scope.getCurrentScope().getLog(getClass()).setLogLevel(logLevel);
    // }
    } catch (IllegalArgumentException e) {
        throw new CommandLineParsingException(e.getMessage(), e);
    }
    final ResourceAccessor fileOpener;
    if (Main.runningFromNewCli) {
        fileOpener = Scope.getCurrentScope().getResourceAccessor();
    } else {
        fileOpener = new CompositeResourceAccessor(new FileSystemResourceAccessor(Paths.get(".").toAbsolutePath().toFile()), new CommandLineResourceAccessor(classLoader));
    }
    Database database = null;
    if (dbConnectionNeeded(command) && this.url != null) {
        database = CommandLineUtils.createDatabaseObject(fileOpener, this.url, this.username, this.password, this.driver, this.defaultCatalogName, this.defaultSchemaName, Boolean.parseBoolean(outputDefaultCatalog), Boolean.parseBoolean(outputDefaultSchema), this.databaseClass, this.driverPropertiesFile, this.propertyProviderClass, this.liquibaseCatalogName, this.liquibaseSchemaName, this.databaseChangeLogTableName, this.databaseChangeLogLockTableName);
        if (this.databaseChangeLogTablespaceName != null) {
            database.setLiquibaseTablespaceName(this.databaseChangeLogTablespaceName);
        } else {
            database.setLiquibaseTablespaceName(GlobalConfiguration.LIQUIBASE_TABLESPACE_NAME.getCurrentConfiguredValue().getValue());
        }
    }
    try {
        if ((excludeObjects != null) && (includeObjects != null)) {
            throw new UnexpectedLiquibaseException(String.format(coreBundle.getString("cannot.specify.both"), OPTIONS.EXCLUDE_OBJECTS, OPTIONS.INCLUDE_OBJECTS));
        }
        if (GlobalConfiguration.SHOULD_SNAPSHOT_DATA.getCurrentValue().equals(false) && dataOutputDirectory != null) {
            // If we are not otherwise going to snapshot data, still snapshot data if dataOutputDirectory is set
            DeprecatedConfigurationValueProvider.setData(GlobalConfiguration.SHOULD_SNAPSHOT_DATA, true);
        }
        ObjectChangeFilter objectChangeFilter = null;
        CompareControl.ComputedSchemas computedSchemas = CompareControl.computeSchemas(schemas, referenceSchemas, outputSchemasAs, defaultCatalogName, defaultSchemaName, referenceDefaultCatalogName, referenceDefaultSchemaName, database);
        CompareControl.SchemaComparison[] finalSchemaComparisons = computedSchemas.finalSchemaComparisons;
        DiffOutputControl diffOutputControl = new DiffOutputControl(includeCatalog, includeSchema, includeTablespace, finalSchemaComparisons);
        if (excludeObjects != null) {
            objectChangeFilter = new StandardObjectChangeFilter(StandardObjectChangeFilter.FilterType.EXCLUDE, excludeObjects);
            diffOutputControl.setObjectChangeFilter(objectChangeFilter);
        }
        if (includeObjects != null) {
            objectChangeFilter = new StandardObjectChangeFilter(StandardObjectChangeFilter.FilterType.INCLUDE, includeObjects);
            diffOutputControl.setObjectChangeFilter(objectChangeFilter);
        }
        for (CompareControl.SchemaComparison schema : finalSchemaComparisons) {
            diffOutputControl.addIncludedSchema(schema.getReferenceSchema());
            diffOutputControl.addIncludedSchema(schema.getComparisonSchema());
        }
        if (COMMANDS.DIFF.equalsIgnoreCase(command)) {
            if (commandParams.contains("--help")) {
                outputStream.println("liquibase diff" + "\n" + "          Outputs a description of differences.  If you have a Liquibase Pro key, you can output the differences as JSON using the --format=JSON option\n");
                System.exit(0);
            }
            if (isFormattedDiff()) {
                CommandScope liquibaseCommand = new CommandScope("internalFormattedDiff");
                CommandScope diffCommand = CommandLineUtils.createDiffCommand(createReferenceDatabaseFromCommandParams(commandParams, fileOpener), database, StringUtil.trimToNull(diffTypes), finalSchemaComparisons, objectChangeFilter, new PrintStream(getOutputStream()));
                liquibaseCommand.addArgumentValue("format", getCommandParam(OPTIONS.FORMAT, "JSON").toUpperCase());
                liquibaseCommand.addArgumentValue("diffCommand", diffCommand);
                liquibaseCommand.setOutput(getOutputStream());
                liquibaseCommand.execute();
            } else {
                CommandLineUtils.doDiff(createReferenceDatabaseFromCommandParams(commandParams, fileOpener), database, StringUtil.trimToNull(diffTypes), finalSchemaComparisons, objectChangeFilter, new PrintStream(getOutputStream()));
            }
            return;
        } else if (COMMANDS.DIFF_CHANGELOG.equalsIgnoreCase(command)) {
            CommandLineUtils.doDiffToChangeLog(changeLogFile, createReferenceDatabaseFromCommandParams(commandParams, fileOpener), database, diffOutputControl, objectChangeFilter, StringUtil.trimToNull(diffTypes), finalSchemaComparisons);
            return;
        } else if (COMMANDS.GENERATE_CHANGELOG.equalsIgnoreCase(command)) {
            String currentChangeLogFile = this.changeLogFile;
            if (currentChangeLogFile == null) {
                // will output to stdout:
                currentChangeLogFile = "";
            }
            File file = new File(currentChangeLogFile);
            if (file.exists() && (!Boolean.parseBoolean(overwriteOutputFile))) {
                throw new LiquibaseException(String.format(coreBundle.getString("changelogfile.already.exists"), currentChangeLogFile));
            } else {
                try {
                    if (!file.delete()) {
                    // Nothing needs to be done
                    }
                } catch (SecurityException e) {
                    throw new LiquibaseException(String.format(coreBundle.getString("attempt.to.delete.the.file.failed.cannot.continue"), currentChangeLogFile), e);
                }
            }
            CatalogAndSchema[] finalTargetSchemas = computedSchemas.finalTargetSchemas;
            CommandLineUtils.doGenerateChangeLog(currentChangeLogFile, database, finalTargetSchemas, StringUtil.trimToNull(diffTypes), StringUtil.trimToNull(changeSetAuthor), StringUtil.trimToNull(changeSetContext), StringUtil.trimToNull(dataOutputDirectory), diffOutputControl);
            return;
        } else if (COMMANDS.SNAPSHOT.equalsIgnoreCase(command)) {
            CommandScope snapshotCommand = new CommandScope("internalSnapshot");
            snapshotCommand.addArgumentValue(InternalSnapshotCommandStep.DATABASE_ARG, database).addArgumentValue(InternalSnapshotCommandStep.SCHEMAS_ARG, InternalSnapshotCommandStep.parseSchemas(database, getSchemaParams(database))).addArgumentValue(InternalSnapshotCommandStep.SERIALIZER_FORMAT_ARG, getCommandParam(OPTIONS.SNAPSHOT_FORMAT, null));
            Writer outputWriter = getOutputWriter();
            String result = InternalSnapshotCommandStep.printSnapshot(snapshotCommand, snapshotCommand.execute());
            outputWriter.write(result);
            outputWriter.flush();
            return;
        } else if (COMMANDS.EXECUTE_SQL.equalsIgnoreCase(command)) {
            CommandScope executeSqlCommand = new CommandScope("internalExecuteSql").addArgumentValue(InternalExecuteSqlCommandStep.DATABASE_ARG, database).addArgumentValue(InternalExecuteSqlCommandStep.SQL_ARG, getCommandParam("sql", null)).addArgumentValue(InternalExecuteSqlCommandStep.SQLFILE_ARG, getCommandParam("sqlFile", null)).addArgumentValue(InternalExecuteSqlCommandStep.DELIMITER_ARG, getCommandParam("delimiter", ";"));
            CommandResults results = executeSqlCommand.execute();
            Writer outputWriter = getOutputWriter();
            String output = (String) results.getResult("output");
            outputWriter.write(output);
            outputWriter.flush();
            return;
        } else if (COMMANDS.SNAPSHOT_REFERENCE.equalsIgnoreCase(command)) {
            CommandScope snapshotCommand = new CommandScope("internalSnapshot");
            Database referenceDatabase = createReferenceDatabaseFromCommandParams(commandParams, fileOpener);
            snapshotCommand.addArgumentValue(InternalSnapshotCommandStep.DATABASE_ARG, referenceDatabase).addArgumentValue(InternalSnapshotCommandStep.SCHEMAS_ARG, InternalSnapshotCommandStep.parseSchemas(referenceDatabase, getSchemaParams(referenceDatabase))).addArgumentValue(InternalSnapshotCommandStep.SERIALIZER_FORMAT_ARG, getCommandParam(OPTIONS.SNAPSHOT_FORMAT, null));
            Writer outputWriter = getOutputWriter();
            outputWriter.write(InternalSnapshotCommandStep.printSnapshot(snapshotCommand, snapshotCommand.execute()));
            outputWriter.flush();
            return;
        }
        Liquibase liquibase = new Liquibase(changeLogFile, fileOpener, database);
        if (Main.newCliChangelogParameters != null) {
            for (Map.Entry<String, String> param : Main.newCliChangelogParameters.entrySet()) {
                liquibase.setChangeLogParameter(param.getKey(), param.getValue());
            }
        }
        try {
            if (hubConnectionId != null) {
                try {
                    liquibase.setHubConnectionId(UUID.fromString(hubConnectionId));
                } catch (IllegalArgumentException e) {
                    throw new LiquibaseException("The command '" + command + "' failed because parameter 'hubConnectionId' has invalid value '" + hubConnectionId + "' Learn more at https://hub.liquibase.com");
                }
            }
        } catch (IllegalArgumentException e) {
            throw new LiquibaseException("Unexpected hubConnectionId format: " + hubConnectionId, e);
        }
        ChangeExecListener listener = ChangeExecListenerUtils.getChangeExecListener(liquibase.getDatabase(), liquibase.getResourceAccessor(), changeExecListenerClass, changeExecListenerPropertiesFile);
        liquibase.setChangeExecListener(listener);
        if (database != null) {
            database.setCurrentDateTimeFunction(currentDateTimeFunction);
        }
        for (Map.Entry<String, Object> entry : changeLogParameters.entrySet()) {
            liquibase.setChangeLogParameter(entry.getKey(), entry.getValue());
        }
        if (COMMANDS.LIST_LOCKS.equalsIgnoreCase(command)) {
            liquibase.reportLocks(System.err);
            return;
        } else if (COMMANDS.RELEASE_LOCKS.equalsIgnoreCase(command)) {
            LockService lockService = LockServiceFactory.getInstance().getLockService(database);
            lockService.forceReleaseLock();
            Scope.getCurrentScope().getUI().sendMessage(String.format(coreBundle.getString("successfully.released.database.change.log.locks"), liquibase.getDatabase().getConnection().getConnectionUserName() + "@" + liquibase.getDatabase().getConnection().getURL()));
            return;
        } else if (COMMANDS.TAG.equalsIgnoreCase(command)) {
            liquibase.tag(getCommandArgument());
            Scope.getCurrentScope().getUI().sendMessage(String.format(coreBundle.getString("successfully.tagged"), liquibase.getDatabase().getConnection().getConnectionUserName() + "@" + liquibase.getDatabase().getConnection().getURL()));
            return;
        } else if (COMMANDS.TAG_EXISTS.equalsIgnoreCase(command)) {
            String tag = commandParams.iterator().next();
            boolean exists = liquibase.tagExists(tag);
            if (exists) {
                Scope.getCurrentScope().getUI().sendMessage(String.format(coreBundle.getString("tag.exists"), tag, liquibase.getDatabase().getConnection().getConnectionUserName() + "@" + liquibase.getDatabase().getConnection().getURL()));
            } else {
                Scope.getCurrentScope().getUI().sendMessage(String.format(coreBundle.getString("tag.does.not.exist"), tag, liquibase.getDatabase().getConnection().getConnectionUserName() + "@" + liquibase.getDatabase().getConnection().getURL()));
            }
            return;
        } else if (COMMANDS.ROLLBACK_ONE_CHANGE_SET.equalsIgnoreCase(command)) {
            Map<String, Object> argsMap = new HashMap<>();
            loadChangeSetInfoToMap(argsMap);
            argsMap.put("changeLogFile", changeLogFile);
            CommandScope liquibaseCommand = createLiquibaseCommand(database, liquibase, "internalRollbackOneChangeSet", argsMap);
            liquibaseCommand.execute();
            return;
        } else if (COMMANDS.ROLLBACK_ONE_CHANGE_SET_SQL.equalsIgnoreCase(command)) {
            Writer outputWriter = getOutputWriter();
            Map<String, Object> argsMap = new HashMap<>();
            loadChangeSetInfoToMap(argsMap);
            argsMap.put("changeLogFile", changeLogFile);
            argsMap.put("outputWriter", outputWriter);
            argsMap.put("force", Boolean.TRUE);
            CommandScope liquibaseCommand = createLiquibaseCommand(database, liquibase, "internalRollbackOneChangeSetSQL", argsMap);
            liquibaseCommand.execute();
            return;
        } else if (COMMANDS.ROLLBACK_ONE_UPDATE.equalsIgnoreCase(command)) {
            Map<String, Object> argsMap = new HashMap<>();
            argsMap.put("changeLogFile", changeLogFile);
            argsMap.put("deploymentId", getCommandParam(OPTIONS.DEPLOYMENT_ID, null));
            CommandScope liquibaseCommand = createLiquibaseCommand(database, liquibase, "internalRollbackOneUpdate", argsMap);
            liquibaseCommand.execute();
            return;
        } else if (COMMANDS.ROLLBACK_ONE_UPDATE_SQL.equalsIgnoreCase(command)) {
            Writer outputWriter = getOutputWriter();
            Map<String, Object> argsMap = new HashMap<>();
            argsMap.put("deploymentId", getCommandParam(OPTIONS.DEPLOYMENT_ID, null));
            argsMap.put("force", Boolean.TRUE);
            argsMap.put("outputWriter", outputWriter);
            CommandScope liquibaseCommand = createLiquibaseCommand(database, liquibase, "internalRollbackOneUpdateSQL", argsMap);
            liquibaseCommand.execute();
            return;
        } else if (COMMANDS.DEACTIVATE_CHANGELOG.equalsIgnoreCase(command)) {
            Map<String, Object> argsMap = new HashMap<>();
            CommandScope liquibaseCommand = createLiquibaseCommand(database, liquibase, COMMANDS.DEACTIVATE_CHANGELOG, argsMap);
            liquibaseCommand.addArgumentValue(DeactivateChangelogCommandStep.CHANGELOG_FILE_ARG, changeLogFile);
            liquibaseCommand.execute();
            return;
        } else if (COMMANDS.REGISTER_CHANGELOG.equalsIgnoreCase(command)) {
            Map<String, Object> argsMap = new HashMap<>();
            CommandScope liquibaseCommand = createLiquibaseCommand(database, liquibase, COMMANDS.REGISTER_CHANGELOG, argsMap);
            if (hubProjectId != null && hubProjectName != null) {
                throw new LiquibaseException("\nThe 'registerchangelog' command failed because too many parameters were provided. Command expects a Hub project ID or new Hub project name, but not both.\n");
            }
            try {
                if (hubProjectId != null) {
                    try {
                        liquibaseCommand.addArgumentValue(RegisterChangelogCommandStep.HUB_PROJECT_ID_ARG, UUID.fromString(hubProjectId));
                    } catch (IllegalArgumentException e) {
                        throw new LiquibaseException("The command '" + command + "' failed because parameter 'hubProjectId' has invalid value '" + hubProjectId + "'. Learn more at https://hub.liquibase.com");
                    }
                }
            } catch (IllegalArgumentException e) {
                throw new LiquibaseException("Unexpected hubProjectId format: " + hubProjectId, e);
            }
            if (hubProjectName != null) {
                liquibaseCommand.addArgumentValue(RegisterChangelogCommandStep.HUB_PROJECT_NAME_ARG.getName(), hubProjectName);
            }
            liquibaseCommand.execute();
            return;
        } else if (COMMANDS.SYNC_HUB.equalsIgnoreCase(command)) {
            executeSyncHub(database, liquibase);
            return;
        } else if (COMMANDS.DROP_ALL.equalsIgnoreCase(command)) {
            CommandScope dropAllCommand = new CommandScope("internalDropAll");
            if (hubConnectionId != null) {
                dropAllCommand.addArgumentValue(InternalDropAllCommandStep.HUB_CONNECTION_ID_ARG, UUID.fromString(hubConnectionId));
            }
            if (hubProjectId != null) {
                dropAllCommand.addArgumentValue(InternalDropAllCommandStep.HUB_PROJECT_ID_ARG, UUID.fromString(hubProjectId));
            }
            dropAllCommand.addArgumentValue(InternalDropAllCommandStep.DATABASE_ARG, liquibase.getDatabase()).addArgumentValue(InternalDropAllCommandStep.SCHEMAS_ARG, InternalSnapshotCommandStep.parseSchemas(database, getSchemaParams(database))).addArgumentValue(InternalDropAllCommandStep.CHANGELOG_FILE_ARG, changeLogFile);
            dropAllCommand.execute();
            return;
        } else if (COMMANDS.STATUS.equalsIgnoreCase(command)) {
            boolean runVerbose = false;
            if (commandParams.contains("--" + OPTIONS.VERBOSE)) {
                runVerbose = true;
            }
            liquibase.reportStatus(runVerbose, new Contexts(contexts), new LabelExpression(labels), getOutputWriter());
            return;
        } else if (COMMANDS.UNEXPECTED_CHANGESETS.equalsIgnoreCase(command)) {
            boolean runVerbose = false;
            if (commandParams.contains("--" + OPTIONS.VERBOSE)) {
                runVerbose = true;
            }
            liquibase.reportUnexpectedChangeSets(runVerbose, contexts, getOutputWriter());
            return;
        } else if (COMMANDS.VALIDATE.equalsIgnoreCase(command)) {
            liquibase.validate();
            Scope.getCurrentScope().getUI().sendMessage(coreBundle.getString("no.validation.errors.found"));
            return;
        } else if (COMMANDS.CLEAR_CHECKSUMS.equalsIgnoreCase(command)) {
            liquibase.clearCheckSums();
            return;
        } else if (COMMANDS.CALCULATE_CHECKSUM.equalsIgnoreCase(command)) {
            CheckSum checkSum = null;
            checkSum = liquibase.calculateCheckSum(commandParams.iterator().next());
            Scope.getCurrentScope().getUI().sendMessage(checkSum.toString());
            return;
        } else if (COMMANDS.DB_DOC.equalsIgnoreCase(command)) {
            if (commandParams.isEmpty()) {
                throw new CommandLineParsingException(coreBundle.getString("dbdoc.requires.output.directory"));
            }
            if (changeLogFile == null) {
                throw new CommandLineParsingException(coreBundle.getString("dbdoc.requires.changelog.parameter"));
            }
            liquibase.generateDocumentation(commandParams.iterator().next(), contexts);
            return;
        }
        try {
            if (COMMANDS.UPDATE.equalsIgnoreCase(command)) {
                liquibase.update(new Contexts(contexts), new LabelExpression(labels));
            } else if (COMMANDS.CHANGELOG_SYNC.equalsIgnoreCase(command)) {
                liquibase.changeLogSync(new Contexts(contexts), new LabelExpression(labels));
            } else if (COMMANDS.CHANGELOG_SYNC_SQL.equalsIgnoreCase(command)) {
                liquibase.changeLogSync(new Contexts(contexts), new LabelExpression(labels), getOutputWriter());
            } else if (COMMANDS.CHANGELOG_SYNC_TO_TAG.equalsIgnoreCase(command)) {
                if ((commandParams == null) || commandParams.isEmpty()) {
                    throw new CommandLineParsingException(String.format(coreBundle.getString("command.requires.tag"), COMMANDS.CHANGELOG_SYNC_TO_TAG));
                }
                liquibase.changeLogSync(commandParams.iterator().next(), new Contexts(contexts), new LabelExpression(labels));
            } else if (COMMANDS.CHANGELOG_SYNC_TO_TAG_SQL.equalsIgnoreCase(command)) {
                if ((commandParams == null) || commandParams.isEmpty()) {
                    throw new CommandLineParsingException(String.format(coreBundle.getString("command.requires.tag"), COMMANDS.CHANGELOG_SYNC_TO_TAG_SQL));
                }
                liquibase.changeLogSync(commandParams.iterator().next(), new Contexts(contexts), new LabelExpression(labels), getOutputWriter());
            } else if (COMMANDS.MARK_NEXT_CHANGESET_RAN.equalsIgnoreCase(command)) {
                liquibase.markNextChangeSetRan(new Contexts(contexts), new LabelExpression(labels));
            } else if (COMMANDS.MARK_NEXT_CHANGESET_RAN_SQL.equalsIgnoreCase(command)) {
                liquibase.markNextChangeSetRan(new Contexts(contexts), new LabelExpression(labels), getOutputWriter());
            } else if (COMMANDS.UPDATE_COUNT.equalsIgnoreCase(command)) {
                liquibase.update(Integer.parseInt(commandParams.iterator().next()), new Contexts(contexts), new LabelExpression(labels));
            } else if (COMMANDS.UPDATE_COUNT_SQL.equalsIgnoreCase(command)) {
                liquibase.update(Integer.parseInt(commandParams.iterator().next()), new Contexts(contexts), new LabelExpression(labels), getOutputWriter());
            } else if (COMMANDS.UPDATE_TO_TAG.equalsIgnoreCase(command)) {
                if ((commandParams == null) || commandParams.isEmpty()) {
                    throw new CommandLineParsingException(String.format(coreBundle.getString("command.requires.tag"), COMMANDS.UPDATE_TO_TAG));
                }
                liquibase.update(commandParams.iterator().next(), new Contexts(contexts), new LabelExpression(labels));
            } else if (COMMANDS.UPDATE_TO_TAG_SQL.equalsIgnoreCase(command)) {
                if ((commandParams == null) || commandParams.isEmpty()) {
                    throw new CommandLineParsingException(String.format(coreBundle.getString("command.requires.tag"), COMMANDS.UPDATE_TO_TAG_SQL));
                }
                liquibase.update(commandParams.iterator().next(), new Contexts(contexts), new LabelExpression(labels), getOutputWriter());
            } else if (COMMANDS.UPDATE_SQL.equalsIgnoreCase(command)) {
                liquibase.update(new Contexts(contexts), new LabelExpression(labels), getOutputWriter());
            } else if (COMMANDS.ROLLBACK.equalsIgnoreCase(command)) {
                if (getCommandArgument() == null) {
                    throw new CommandLineParsingException(String.format(coreBundle.getString("command.requires.tag"), COMMANDS.ROLLBACK));
                }
                liquibase.rollback(getCommandArgument(), getCommandParam(COMMANDS.ROLLBACK_SCRIPT, null), new Contexts(contexts), new LabelExpression(labels));
            } else if (COMMANDS.ROLLBACK_TO_DATE.equalsIgnoreCase(command)) {
                if (getCommandArgument() == null) {
                    throw new CommandLineParsingException(String.format(coreBundle.getString("command.requires.timestamp"), COMMANDS.ROLLBACK_TO_DATE));
                }
                liquibase.rollback(new ISODateFormat().parse(getCommandArgument()), getCommandParam(COMMANDS.ROLLBACK_SCRIPT, null), new Contexts(contexts), new LabelExpression(labels));
            } else if (COMMANDS.ROLLBACK_COUNT.equalsIgnoreCase(command)) {
                liquibase.rollback(Integer.parseInt(getCommandArgument()), getCommandParam(COMMANDS.ROLLBACK_SCRIPT, null), new Contexts(contexts), new LabelExpression(labels));
            } else if (COMMANDS.ROLLBACK_SQL.equalsIgnoreCase(command)) {
                if (getCommandArgument() == null) {
                    throw new CommandLineParsingException(String.format(coreBundle.getString("command.requires.tag"), COMMANDS.ROLLBACK_SQL));
                }
                liquibase.rollback(getCommandArgument(), getCommandParam(COMMANDS.ROLLBACK_SCRIPT, null), new Contexts(contexts), new LabelExpression(labels), getOutputWriter());
            } else if (COMMANDS.ROLLBACK_TO_DATE_SQL.equalsIgnoreCase(command)) {
                if (getCommandArgument() == null) {
                    throw new CommandLineParsingException(String.format(coreBundle.getString("command.requires.timestamp"), COMMANDS.ROLLBACK_TO_DATE_SQL));
                }
                liquibase.rollback(new ISODateFormat().parse(getCommandArgument()), getCommandParam(COMMANDS.ROLLBACK_SCRIPT, null), new Contexts(contexts), new LabelExpression(labels), getOutputWriter());
            } else if (COMMANDS.ROLLBACK_COUNT_SQL.equalsIgnoreCase(command)) {
                if (getCommandArgument() == null) {
                    throw new CommandLineParsingException(String.format(coreBundle.getString("command.requires.count"), COMMANDS.ROLLBACK_COUNT_SQL));
                }
                liquibase.rollback(Integer.parseInt(getCommandArgument()), getCommandParam(COMMANDS.ROLLBACK_SCRIPT, null), new Contexts(contexts), new LabelExpression(labels), getOutputWriter());
            } else if (COMMANDS.FUTURE_ROLLBACK_SQL.equalsIgnoreCase(command)) {
                liquibase.futureRollbackSQL(new Contexts(contexts), new LabelExpression(labels), getOutputWriter());
            } else if (COMMANDS.FUTURE_ROLLBACK_COUNT_SQL.equalsIgnoreCase(command)) {
                if (getCommandArgument() == null) {
                    throw new CommandLineParsingException(String.format(coreBundle.getString("command.requires.count"), COMMANDS.FUTURE_ROLLBACK_COUNT_SQL));
                }
                liquibase.futureRollbackSQL(Integer.valueOf(getCommandArgument()), new Contexts(contexts), new LabelExpression(labels), getOutputWriter());
            } else if (COMMANDS.FUTURE_ROLLBACK_FROM_TAG_SQL.equalsIgnoreCase(command)) {
                if (getCommandArgument() == null) {
                    throw new CommandLineParsingException(String.format(coreBundle.getString("command.requires.tag"), COMMANDS.FUTURE_ROLLBACK_FROM_TAG_SQL));
                }
                liquibase.futureRollbackSQL(getCommandArgument(), new Contexts(contexts), new LabelExpression(labels), getOutputWriter());
            } else if (COMMANDS.UPDATE_TESTING_ROLLBACK.equalsIgnoreCase(command)) {
                liquibase.updateTestingRollback(new Contexts(contexts), new LabelExpression(labels));
            } else if (COMMANDS.HISTORY.equalsIgnoreCase(command)) {
                CommandScope historyCommand = new CommandScope("internalHistory");
                historyCommand.addArgumentValue(InternalHistoryCommandStep.DATABASE_ARG, database);
                historyCommand.setOutput(getOutputStream());
                historyCommand.execute();
            } else {
                throw new CommandLineParsingException(String.format(coreBundle.getString("command.unknown"), command));
            }
        } catch (ParseException ignored) {
            throw new CommandLineParsingException(coreBundle.getString("timeformat.invalid"));
        }
    } finally {
        try {
            if (database != null) {
                database.rollback();
                database.close();
            }
        } catch (DatabaseException e) {
            Scope.getCurrentScope().getLog(getClass()).warning(coreBundle.getString("problem.closing.connection"), e);
        }
    }
}
Also used : ResourceAccessor(liquibase.resource.ResourceAccessor) CompositeResourceAccessor(liquibase.resource.CompositeResourceAccessor) FileSystemResourceAccessor(liquibase.resource.FileSystemResourceAccessor) ClassLoaderResourceAccessor(liquibase.resource.ClassLoaderResourceAccessor) ISODateFormat(liquibase.util.ISODateFormat) StandardObjectChangeFilter(liquibase.diff.output.StandardObjectChangeFilter) ChangeExecListener(liquibase.changelog.visitor.ChangeExecListener) Database(liquibase.database.Database) CommandScope(liquibase.command.CommandScope) ObjectChangeFilter(liquibase.diff.output.ObjectChangeFilter) StandardObjectChangeFilter(liquibase.diff.output.StandardObjectChangeFilter) LockService(liquibase.lockservice.LockService) DiffOutputControl(liquibase.diff.output.DiffOutputControl) CompositeResourceAccessor(liquibase.resource.CompositeResourceAccessor) CheckSum(liquibase.change.CheckSum) CompareControl(liquibase.diff.compare.CompareControl) FileSystemResourceAccessor(liquibase.resource.FileSystemResourceAccessor) ParseException(java.text.ParseException) JarFile(java.util.jar.JarFile) CommandResults(liquibase.command.CommandResults)

Example 2 with CommandResults

use of liquibase.command.CommandResults in project liquibase by liquibase.

the class HubUpdater method registerChangeLog.

// 
// Register the specified changelog
// 
private void registerChangeLog(UUID hubProjectId, DatabaseChangeLog changeLog, String changeLogFile) throws LiquibaseException {
    String apiKey = StringUtil.trimToNull(HubConfiguration.LIQUIBASE_HUB_API_KEY.getCurrentValue());
    if (apiKey == null) {
        throw new LiquibaseException("The command 'RegisterChangeLog' " + " failed because the Liquibase API Key has not been set. Learn more at https://hub.liquibase.com");
    }
    CommandScope registerChangeLogCommand = new CommandScope("registerChangeLog");
    registerChangeLogCommand.addArgumentValue(RegisterChangelogCommandStep.CHANGELOG_FILE_ARG, changeLogFile);
    try {
        if (hubProjectId != null) {
            try {
                registerChangeLogCommand.addArgumentValue(RegisterChangelogCommandStep.HUB_PROJECT_ID_ARG, hubProjectId);
            } catch (IllegalArgumentException e) {
                throw new LiquibaseException("The command 'RegisterChangeLog' " + " failed because parameter 'hubProjectId' has invalid value '" + hubProjectId + "'. Learn more at https://hub.liquibase.com");
            }
        }
    } catch (IllegalArgumentException e) {
        throw new LiquibaseException("Unexpected hubProjectId format: " + hubProjectId, e);
    }
    // 
    // Execute registerChangeLog and reset the changeLog ID
    // 
    CommandResults results = registerChangeLogCommand.execute();
    String registerChangeLogId = results.getResult(RegisterChangelogCommandStep.REGISTERED_CHANGELOG_ID);
    if (registerChangeLogId != null) {
        changeLog.setChangeLogId(registerChangeLogId);
    }
}
Also used : LiquibaseException(liquibase.exception.LiquibaseException) CommandScope(liquibase.command.CommandScope) CommandResults(liquibase.command.CommandResults)

Aggregations

CommandResults (liquibase.command.CommandResults)2 CommandScope (liquibase.command.CommandScope)2 ParseException (java.text.ParseException)1 JarFile (java.util.jar.JarFile)1 CheckSum (liquibase.change.CheckSum)1 ChangeExecListener (liquibase.changelog.visitor.ChangeExecListener)1 Database (liquibase.database.Database)1 CompareControl (liquibase.diff.compare.CompareControl)1 DiffOutputControl (liquibase.diff.output.DiffOutputControl)1 ObjectChangeFilter (liquibase.diff.output.ObjectChangeFilter)1 StandardObjectChangeFilter (liquibase.diff.output.StandardObjectChangeFilter)1 LiquibaseException (liquibase.exception.LiquibaseException)1 LockService (liquibase.lockservice.LockService)1 ClassLoaderResourceAccessor (liquibase.resource.ClassLoaderResourceAccessor)1 CompositeResourceAccessor (liquibase.resource.CompositeResourceAccessor)1 FileSystemResourceAccessor (liquibase.resource.FileSystemResourceAccessor)1 ResourceAccessor (liquibase.resource.ResourceAccessor)1 ISODateFormat (liquibase.util.ISODateFormat)1