Search in sources :

Example 6 with LockService

use of liquibase.lockservice.LockService 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 7 with LockService

use of liquibase.lockservice.LockService in project liquibase by liquibase.

the class AbstractIntegrationTest method testInvalidIncludeDoesntBreakLiquibase.

@Test
public void testInvalidIncludeDoesntBreakLiquibase() throws Exception {
    assumeNotNull(this.getDatabase());
    Liquibase liquibase = createLiquibase(invalidReferenceChangeLog);
    try {
        liquibase.update(new Contexts());
        fail("Did not fail with invalid include");
    } catch (ChangeLogParseException ignored) {
    // expected
    }
    LockService lockService = LockServiceFactory.getInstance().getLockService(database);
    assertFalse(lockService.hasChangeLogLock());
}
Also used : LockService(liquibase.lockservice.LockService) ChangeLogParseException(liquibase.exception.ChangeLogParseException) Test(org.junit.Test)

Example 8 with LockService

use of liquibase.lockservice.LockService in project liquibase by liquibase.

the class InternalDropAllCommandStep method run.

@Override
public void run(CommandResultsBuilder resultsBuilder) throws Exception {
    CommandScope commandScope = resultsBuilder.getCommandScope();
    BufferedLogService bufferLog = new BufferedLogService();
    validateConnectionAndProjectIdsDependingOnApiKey(commandScope);
    Operation dropAllOperation;
    LockService lockService = LockServiceFactory.getInstance().getLockService(commandScope.getArgumentValue(DATABASE_ARG));
    HubUpdater hubUpdater;
    try {
        lockService.waitForLock();
        DatabaseChangeLog changeLog;
        HubRegisterResponse hubRegisterResponse = null;
        if (StringUtil.isNotEmpty(commandScope.getArgumentValue(CHANGELOG_FILE_ARG))) {
            // Let the user know they can register for Hub
            changeLog = parseChangeLogFile(commandScope.getArgumentValue(CHANGELOG_FILE_ARG));
            hubUpdater = new HubUpdater(new Date(), changeLog, commandScope.getArgumentValue(DATABASE_ARG));
            hubRegisterResponse = hubUpdater.register(commandScope.getArgumentValue(CHANGELOG_FILE_ARG));
            // Access the HubChangeLog and check to see if we should run syncHub
            HubChangeLog hubChangeLog = getHubChangeLog(changeLog);
            checkForRegisteredChangeLog(changeLog, hubChangeLog);
        } else {
            hubUpdater = new HubUpdater(new Date(), commandScope.getArgumentValue(DATABASE_ARG));
            hubRegisterResponse = hubUpdater.register(null);
        }
        Connection hubConnection = getHubConnection(commandScope);
        attachProjectToConnection(commandScope, hubConnection, hubRegisterResponse);
        dropAllOperation = hubUpdater.preUpdateHub("DROPALL", "drop-all", hubConnection);
        try {
            for (CatalogAndSchema schema : commandScope.getArgumentValue(SCHEMAS_ARG)) {
                log.info("Dropping Database Objects in schema: " + schema);
                checkLiquibaseTables(commandScope.getArgumentValue(DATABASE_ARG));
                commandScope.getArgumentValue(DATABASE_ARG).dropDatabaseObjects(schema);
            }
        } catch (LiquibaseException liquibaseException) {
            hubUpdater.postUpdateHubExceptionHandling(dropAllOperation, bufferLog, liquibaseException.getMessage());
            return;
        }
        final HubServiceFactory hubServiceFactory = Scope.getCurrentScope().getSingleton(HubServiceFactory.class);
        String apiKey = StringUtil.trimToNull(HubConfiguration.LIQUIBASE_HUB_API_KEY.getCurrentValue());
        if (apiKey != null && hubServiceFactory.isOnline()) {
            hubUpdater.syncHub(commandScope.getArgumentValue(CHANGELOG_FILE_ARG), hubConnection);
            hubUpdater.postUpdateHub(dropAllOperation, bufferLog);
        }
    } catch (DatabaseException e) {
        throw e;
    } catch (Exception e) {
        throw new DatabaseException(e);
    } finally {
        lockService.releaseLock();
        lockService.destroy();
        resetServices();
    }
    Scope.getCurrentScope().getUI().sendMessage("All objects dropped from " + commandScope.getArgumentValue(DATABASE_ARG).getConnection().getConnectionUserName() + "@" + commandScope.getArgumentValue(DATABASE_ARG).getConnection().getURL());
    resultsBuilder.addResult("statusCode", 0);
}
Also used : LockService(liquibase.lockservice.LockService) DatabaseConnection(liquibase.database.DatabaseConnection) CatalogAndSchema(liquibase.CatalogAndSchema) BufferedLogService(liquibase.logging.core.BufferedLogService) DatabaseChangeLog(liquibase.changelog.DatabaseChangeLog) Date(java.util.Date) DatabaseException(liquibase.exception.DatabaseException) CommandExecutionException(liquibase.exception.CommandExecutionException) LiquibaseException(liquibase.exception.LiquibaseException) LiquibaseException(liquibase.exception.LiquibaseException) DatabaseException(liquibase.exception.DatabaseException)

Example 9 with LockService

use of liquibase.lockservice.LockService in project liquibase by liquibase.

the class Liquibase method update.

/**
 * Liquibase update
 *
 * @param   contexts
 * @param   labelExpression
 * @param   checkLiquibaseTables
 * @throws  LiquibaseException
 */
public void update(Contexts contexts, LabelExpression labelExpression, boolean checkLiquibaseTables) throws LiquibaseException {
    runInScope(() -> {
        LockService lockService = LockServiceFactory.getInstance().getLockService(database);
        lockService.waitForLock();
        changeLogParameters.setContexts(contexts);
        changeLogParameters.setLabels(labelExpression);
        Operation updateOperation = null;
        BufferedLogService bufferLog = new BufferedLogService();
        DatabaseChangeLog changeLog = null;
        HubUpdater hubUpdater = null;
        try {
            changeLog = getDatabaseChangeLog();
            if (checkLiquibaseTables) {
                checkLiquibaseTables(true, changeLog, contexts, labelExpression);
            }
            ChangeLogHistoryServiceFactory.getInstance().getChangeLogService(database).generateDeploymentId();
            changeLog.validate(database, contexts, labelExpression);
            // 
            // Let the user know that they can register for Hub
            // 
            hubUpdater = new HubUpdater(new Date(), changeLog, database);
            hubUpdater.register(changeLogFile);
            // 
            // Create or retrieve the Connection if this is not SQL generation
            // Make sure the Hub is available here by checking the return
            // We do not need a connection if we are using a LoggingExecutor
            // 
            ChangeLogIterator changeLogIterator = getStandardChangelogIterator(contexts, labelExpression, changeLog);
            Connection connection = getConnection(changeLog);
            if (connection != null) {
                updateOperation = hubUpdater.preUpdateHub("UPDATE", "update", connection, changeLogFile, contexts, labelExpression, changeLogIterator);
            }
            // 
            if (connection != null) {
                changeExecListener = new HubChangeExecListener(updateOperation, changeExecListener);
            }
            // 
            // Create another iterator to run
            // 
            ChangeLogIterator runChangeLogIterator = getStandardChangelogIterator(contexts, labelExpression, changeLog);
            CompositeLogService compositeLogService = new CompositeLogService(true, bufferLog);
            Scope.child(Scope.Attr.logService.name(), compositeLogService, () -> {
                runChangeLogIterator.run(createUpdateVisitor(), new RuntimeEnvironment(database, contexts, labelExpression));
            });
            // 
            // Update Hub with the operation information
            // 
            hubUpdater.postUpdateHub(updateOperation, bufferLog);
        } catch (Throwable e) {
            if (hubUpdater != null) {
                hubUpdater.postUpdateHubExceptionHandling(updateOperation, bufferLog, e.getMessage());
            }
            throw e;
        } finally {
            database.setObjectQuotingStrategy(ObjectQuotingStrategy.LEGACY);
            try {
                lockService.releaseLock();
            } catch (LockException e) {
                LOG.severe(MSG_COULD_NOT_RELEASE_LOCK, e);
            }
            resetServices();
            setChangeExecListener(null);
        }
    });
}
Also used : LockService(liquibase.lockservice.LockService) DatabaseConnection(liquibase.database.DatabaseConnection) Connection(liquibase.hub.model.Connection) Operation(liquibase.hub.model.Operation) BufferedLogService(liquibase.logging.core.BufferedLogService) CompositeLogService(liquibase.logging.core.CompositeLogService) HubChangeExecListener(liquibase.hub.listener.HubChangeExecListener)

Example 10 with LockService

use of liquibase.lockservice.LockService in project liquibase by liquibase.

the class Liquibase method rollback.

/**
 * Rollback to date
 *
 * @param dateToRollBackTo
 * @param rollbackScript
 * @param contexts
 * @param labelExpression
 * @throws LiquibaseException
 */
public void rollback(Date dateToRollBackTo, String rollbackScript, Contexts contexts, LabelExpression labelExpression) throws LiquibaseException {
    changeLogParameters.setContexts(contexts);
    changeLogParameters.setLabels(labelExpression);
    runInScope(new Scope.ScopedRunner() {

        @Override
        public void run() throws Exception {
            LockService lockService = LockServiceFactory.getInstance().getLockService(database);
            lockService.waitForLock();
            Operation rollbackOperation = null;
            BufferedLogService bufferLog = new BufferedLogService();
            DatabaseChangeLog changeLog = null;
            Date startTime = new Date();
            HubUpdater hubUpdater = null;
            try {
                changeLog = getDatabaseChangeLog();
                checkLiquibaseTables(false, changeLog, contexts, labelExpression);
                changeLog.validate(database, contexts, labelExpression);
                // 
                // Let the user know that they can register for Hub
                // 
                hubUpdater = new HubUpdater(startTime, changeLog, database);
                hubUpdater.register(changeLogFile);
                // 
                // Create an iterator which will be used with a ListVisitor
                // to grab the list of change sets for the update
                // 
                List<RanChangeSet> ranChangeSetList = database.getRanChangeSetList();
                ChangeLogIterator listLogIterator = new ChangeLogIterator(ranChangeSetList, changeLog, new ExecutedAfterChangeSetFilter(dateToRollBackTo, ranChangeSetList), new AlreadyRanChangeSetFilter(ranChangeSetList), new ContextChangeSetFilter(contexts), new LabelChangeSetFilter(labelExpression), new IgnoreChangeSetFilter(), new DbmsChangeSetFilter(database));
                // 
                // Create or retrieve the Connection
                // Make sure the Hub is available here by checking the return
                // 
                Connection connection = getConnection(changeLog);
                if (connection != null) {
                    rollbackOperation = hubUpdater.preUpdateHub("ROLLBACK", "rollback-to-date", connection, changeLogFile, contexts, labelExpression, listLogIterator);
                }
                // 
                if (connection != null) {
                    changeExecListener = new HubChangeExecListener(rollbackOperation, changeExecListener);
                }
                // 
                // Create another iterator to run
                // 
                ChangeLogIterator logIterator = new ChangeLogIterator(ranChangeSetList, changeLog, new ExecutedAfterChangeSetFilter(dateToRollBackTo, ranChangeSetList), new AlreadyRanChangeSetFilter(ranChangeSetList), new ContextChangeSetFilter(contexts), new LabelChangeSetFilter(labelExpression), new IgnoreChangeSetFilter(), new DbmsChangeSetFilter(database));
                CompositeLogService compositeLogService = new CompositeLogService(true, bufferLog);
                if (rollbackScript == null) {
                    Scope.child(Scope.Attr.logService.name(), compositeLogService, () -> {
                        logIterator.run(createRollbackVisitor(), new RuntimeEnvironment(database, contexts, labelExpression));
                    });
                } else {
                    List<ChangeSet> changeSets = determineRollbacks(logIterator, contexts, labelExpression);
                    Map<String, Object> values = new HashMap<>();
                    values.put(Scope.Attr.logService.name(), compositeLogService);
                    values.put(BufferedLogService.class.getName(), bufferLog);
                    Scope.child(values, () -> {
                        executeRollbackScript(rollbackScript, changeSets, contexts, labelExpression);
                    });
                    removeRunStatus(changeSets, contexts, labelExpression);
                }
                hubUpdater.postUpdateHub(rollbackOperation, bufferLog);
            } catch (Throwable t) {
                if (hubUpdater != null) {
                    hubUpdater.postUpdateHubExceptionHandling(rollbackOperation, bufferLog, t.getMessage());
                }
                throw t;
            } finally {
                try {
                    lockService.releaseLock();
                } catch (LockException e) {
                    LOG.severe(MSG_COULD_NOT_RELEASE_LOCK, e);
                }
                resetServices();
                setChangeExecListener(null);
            }
        }
    });
}
Also used : Operation(liquibase.hub.model.Operation) CompositeLogService(liquibase.logging.core.CompositeLogService) HubChangeExecListener(liquibase.hub.listener.HubChangeExecListener) InputStreamList(liquibase.resource.InputStreamList) LockService(liquibase.lockservice.LockService) DatabaseConnection(liquibase.database.DatabaseConnection) Connection(liquibase.hub.model.Connection) InvalidExampleException(liquibase.snapshot.InvalidExampleException) IOException(java.io.IOException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) BufferedLogService(liquibase.logging.core.BufferedLogService) CommandScope(liquibase.command.CommandScope)

Aggregations

LockService (liquibase.lockservice.LockService)27 IOException (java.io.IOException)10 CommandScope (liquibase.command.CommandScope)9 DatabaseConnection (liquibase.database.DatabaseConnection)9 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)8 BufferedLogService (liquibase.logging.core.BufferedLogService)8 InvalidExampleException (liquibase.snapshot.InvalidExampleException)8 LockException (liquibase.exception.LockException)7 HubChangeExecListener (liquibase.hub.listener.HubChangeExecListener)7 Connection (liquibase.hub.model.Connection)7 Operation (liquibase.hub.model.Operation)7 CompositeLogService (liquibase.logging.core.CompositeLogService)7 LiquibaseException (liquibase.exception.LiquibaseException)6 Database (liquibase.database.Database)4 ExecutorService (liquibase.executor.ExecutorService)4 InputStreamList (liquibase.resource.InputStreamList)4 Liquibase (liquibase.Liquibase)3 DatabaseChangeLog (liquibase.changelog.DatabaseChangeLog)3 JdbcConnection (liquibase.database.jvm.JdbcConnection)3 ChangeLogParseException (liquibase.exception.ChangeLogParseException)3