Search in sources :

Example 1 with StandardObjectChangeFilter

use of liquibase.diff.output.StandardObjectChangeFilter 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 StandardObjectChangeFilter

use of liquibase.diff.output.StandardObjectChangeFilter in project liquibase by liquibase.

the class LiquibaseDatabaseDiff method performLiquibaseTask.

@Override
protected void performLiquibaseTask(Liquibase liquibase) throws LiquibaseException {
    // 
    if (isFormattedDiff()) {
        if (format != null && !format.equalsIgnoreCase("json")) {
            String messageString = "\nWARNING: The diff command 'diff --format=" + format + "' optional Pro parameter '--format' " + "currently supports only 'TXT' or 'JSON' as values.  (Blank defaults to 'TXT')";
            throw new LiquibaseException(String.format(messageString));
        }
        boolean hasProLicense = MavenUtils.checkProLicense(liquibaseProLicenseKey, commandName, getLog());
        if (!hasProLicense) {
            throw new LiquibaseException("The command 'diff --format=" + format + "' requires a Liquibase Pro License, available at https://www.liquibase.org/download or sales@liquibase.com." + " Options include the liquibase.pro.licenseKey in the defaults file, adding a flag in the CLI, and more. Learn more at https://docs.liquibase.com");
        }
    }
    ClassLoader cl = null;
    ResourceAccessor resourceAccessor;
    try {
        cl = getClassLoaderIncludingProjectClasspath();
        Thread.currentThread().setContextClassLoader(cl);
        ClassLoader artifactClassLoader = getMavenArtifactClassLoader();
        resourceAccessor = getResourceAccessor(artifactClassLoader);
    } catch (MojoExecutionException e) {
        throw new LiquibaseException("Could not create the class loader, " + e, e);
    }
    Database db = liquibase.getDatabase();
    Database referenceDatabase = CommandLineUtils.createDatabaseObject(resourceAccessor, referenceUrl, referenceUsername, referencePassword, referenceDriver, referenceDefaultCatalogName, referenceDefaultSchemaName, outputDefaultCatalog, outputDefaultSchema, null, null, propertyProviderClass, null, null, databaseChangeLogTableName, databaseChangeLogLockTableName);
    getLog().info("Performing Diff on database " + db.toString());
    if ((diffExcludeObjects != null) && (diffIncludeObjects != null)) {
        throw new UnexpectedLiquibaseException("Cannot specify both excludeObjects and includeObjects");
    }
    ObjectChangeFilter objectChangeFilter = null;
    if (diffExcludeObjects != null) {
        objectChangeFilter = new StandardObjectChangeFilter(StandardObjectChangeFilter.FilterType.EXCLUDE, diffExcludeObjects);
    }
    if (diffIncludeObjects != null) {
        objectChangeFilter = new StandardObjectChangeFilter(StandardObjectChangeFilter.FilterType.INCLUDE, diffIncludeObjects);
    }
    CompareControl.SchemaComparison[] schemaComparisons = createSchemaComparisons(db);
    if (diffChangeLogFile != null) {
        try {
            DiffOutputControl diffOutputControl = new DiffOutputControl(diffIncludeCatalog, diffIncludeSchema, diffIncludeTablespace, null).addIncludedSchema(new CatalogAndSchema(referenceDefaultCatalogName, referenceDefaultSchemaName));
            diffOutputControl.setObjectChangeFilter(objectChangeFilter);
            CommandLineUtils.doDiffToChangeLog(diffChangeLogFile, referenceDatabase, db, diffOutputControl, objectChangeFilter, StringUtil.trimToNull(diffTypes), schemaComparisons);
            if (new File(diffChangeLogFile).exists()) {
                getLog().info("Differences written to Change Log File, " + diffChangeLogFile);
            }
        } catch (IOException | ParserConfigurationException e) {
            throw new LiquibaseException(e);
        }
    } else {
        PrintStream printStream = createPrintStream();
        if (isFormattedDiff()) {
            CommandScope liquibaseCommand = new CommandScope("internalDiff");
            CommandScope diffCommand = CommandLineUtils.createDiffCommand(referenceDatabase, db, StringUtil.trimToNull(diffTypes), schemaComparisons, objectChangeFilter, printStream);
            CompareControl compareControl = new CompareControl(schemaComparisons, diffTypes);
            liquibaseCommand.addArgumentValue("format", format);
            liquibaseCommand.addArgumentValue("diffCommand", diffCommand);
            liquibaseCommand.addArgumentValue("targetDatabase", db);
            liquibaseCommand.addArgumentValue("referenceDatabase", referenceDatabase);
            liquibaseCommand.addArgumentValue("compareControl", compareControl);
            liquibaseCommand.addArgumentValue("objectChangeFilter", objectChangeFilter);
            if (StringUtil.isEmpty(diffTypes)) {
                liquibaseCommand.addArgumentValue("snapshotTypes", new Class[0]);
            } else {
                liquibaseCommand.addArgumentValue("snapshotTypes", diffTypes);
            }
            CommandScope formattedDiffCommand = new CommandScope("internalFormattedDiff");
            formattedDiffCommand.addArgumentValue("format", format);
            formattedDiffCommand.addArgumentValue("diffCommand", liquibaseCommand);
            formattedDiffCommand.execute();
        } else {
            CommandLineUtils.doDiff(referenceDatabase, db, StringUtil.trimToNull(diffTypes), schemaComparisons, objectChangeFilter, printStream);
        }
    }
}
Also used : ResourceAccessor(liquibase.resource.ResourceAccessor) PrintStream(java.io.PrintStream) StandardObjectChangeFilter(liquibase.diff.output.StandardObjectChangeFilter) ObjectChangeFilter(liquibase.diff.output.ObjectChangeFilter) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) DiffOutputControl(liquibase.diff.output.DiffOutputControl) IOException(java.io.IOException) CatalogAndSchema(liquibase.CatalogAndSchema) StandardObjectChangeFilter(liquibase.diff.output.StandardObjectChangeFilter) Database(liquibase.database.Database) CompareControl(liquibase.diff.compare.CompareControl) LiquibaseException(liquibase.exception.LiquibaseException) UnexpectedLiquibaseException(liquibase.exception.UnexpectedLiquibaseException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) UnexpectedLiquibaseException(liquibase.exception.UnexpectedLiquibaseException) File(java.io.File)

Example 3 with StandardObjectChangeFilter

use of liquibase.diff.output.StandardObjectChangeFilter in project liquibase by liquibase.

the class LiquibaseGenerateChangeLogMojo method performLiquibaseTask.

@Override
protected void performLiquibaseTask(Liquibase liquibase) throws LiquibaseException {
    ClassLoader cl = null;
    try {
        cl = getClassLoaderIncludingProjectClasspath();
        Thread.currentThread().setContextClassLoader(cl);
    } catch (MojoExecutionException e) {
        throw new LiquibaseException("Could not create the class loader, " + e, e);
    }
    Database database = liquibase.getDatabase();
    getLog().info("Generating Change Log from database " + database.toString());
    try {
        DiffOutputControl diffOutputControl = new DiffOutputControl(outputDefaultCatalog, outputDefaultSchema, true, null);
        if ((diffExcludeObjects != null) && (diffIncludeObjects != null)) {
            throw new UnexpectedLiquibaseException("Cannot specify both excludeObjects and includeObjects");
        }
        if (diffExcludeObjects != null) {
            diffOutputControl.setObjectChangeFilter(new StandardObjectChangeFilter(StandardObjectChangeFilter.FilterType.EXCLUDE, diffExcludeObjects));
        }
        if (diffIncludeObjects != null) {
            diffOutputControl.setObjectChangeFilter(new StandardObjectChangeFilter(StandardObjectChangeFilter.FilterType.INCLUDE, diffIncludeObjects));
        }
        // 
        // Set the global configuration option based on presence of the dataOutputDirectory
        // 
        boolean b = dataDir != null;
        Scope.child(GlobalConfiguration.SHOULD_SNAPSHOT_DATA.getKey(), b, () -> {
            CommandLineUtils.doGenerateChangeLog(outputChangeLogFile, database, defaultCatalogName, defaultSchemaName, StringUtil.trimToNull(diffTypes), StringUtil.trimToNull(changeSetAuthor), StringUtil.trimToNull(changeSetContext), StringUtil.trimToNull(dataDir), diffOutputControl);
            getLog().info("Output written to Change Log file, " + outputChangeLogFile);
        });
    } catch (Exception e) {
        throw new LiquibaseException(e);
    }
}
Also used : StandardObjectChangeFilter(liquibase.diff.output.StandardObjectChangeFilter) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) Database(liquibase.database.Database) DiffOutputControl(liquibase.diff.output.DiffOutputControl) LiquibaseException(liquibase.exception.LiquibaseException) UnexpectedLiquibaseException(liquibase.exception.UnexpectedLiquibaseException) UnexpectedLiquibaseException(liquibase.exception.UnexpectedLiquibaseException) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) MojoFailureException(org.apache.maven.plugin.MojoFailureException) LiquibaseException(liquibase.exception.LiquibaseException) UnexpectedLiquibaseException(liquibase.exception.UnexpectedLiquibaseException)

Aggregations

Database (liquibase.database.Database)3 DiffOutputControl (liquibase.diff.output.DiffOutputControl)3 StandardObjectChangeFilter (liquibase.diff.output.StandardObjectChangeFilter)3 CompareControl (liquibase.diff.compare.CompareControl)2 ObjectChangeFilter (liquibase.diff.output.ObjectChangeFilter)2 LiquibaseException (liquibase.exception.LiquibaseException)2 UnexpectedLiquibaseException (liquibase.exception.UnexpectedLiquibaseException)2 ResourceAccessor (liquibase.resource.ResourceAccessor)2 MojoExecutionException (org.apache.maven.plugin.MojoExecutionException)2 File (java.io.File)1 IOException (java.io.IOException)1 PrintStream (java.io.PrintStream)1 ParseException (java.text.ParseException)1 JarFile (java.util.jar.JarFile)1 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)1 CatalogAndSchema (liquibase.CatalogAndSchema)1 CheckSum (liquibase.change.CheckSum)1 ChangeExecListener (liquibase.changelog.visitor.ChangeExecListener)1 CommandResults (liquibase.command.CommandResults)1 CommandScope (liquibase.command.CommandScope)1