Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[DAT-6608] Refactors DropAll command as CommandStep #4171

Merged
merged 6 commits into from
May 12, 2023
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,16 +1,15 @@
package liquibase.command.util;
package liquibase.command.util

import liquibase.Scope
import liquibase.UpdateSummaryEnum;
import liquibase.command.CommandResultsBuilder;
import liquibase.command.CommandScope;
import liquibase.command.core.DropAllCommandStep;
import liquibase.command.core.GenerateChangelogCommandStep;
import liquibase.command.core.UpdateCommandStep;
import liquibase.UpdateSummaryEnum
import liquibase.command.CommandScope
import liquibase.command.core.DropAllCommandStep
import liquibase.command.core.GenerateChangelogCommandStep
import liquibase.command.core.UpdateCommandStep
import liquibase.command.core.helpers.DbUrlConnectionCommandStep
import liquibase.command.core.helpers.ShowSummaryArgument;
import liquibase.exception.CommandExecutionException;
import liquibase.extension.testing.testsystem.DatabaseTestSystem;
import liquibase.command.core.helpers.ShowSummaryArgument
import liquibase.exception.CommandExecutionException
import liquibase.extension.testing.testsystem.DatabaseTestSystem
import liquibase.resource.SearchPathResourceAccessor
import liquibase.sdk.resource.MockResourceAccessor

Expand Down Expand Up @@ -66,14 +65,12 @@ class CommandUtil {
}

static void runDropAll(DatabaseTestSystem db) throws Exception {
DropAllCommandStep step = new DropAllCommandStep()
CommandScope commandScope = new CommandScope(DropAllCommandStep.COMMAND_NAME)
commandScope.addArgumentValue(DbUrlConnectionCommandStep.URL_ARG, db.getConnectionUrl())
commandScope.addArgumentValue(DbUrlConnectionCommandStep.USERNAME_ARG, db.getUsername())
commandScope.addArgumentValue(DbUrlConnectionCommandStep.PASSWORD_ARG, db.getPassword())
OutputStream outputStream = new ByteArrayOutputStream()
CommandResultsBuilder commandResultsBuilder = new CommandResultsBuilder(commandScope, outputStream)
step.run(commandResultsBuilder)
commandScope.setOutput(new ByteArrayOutputStream())
commandScope.execute()
}

private static void execUpdateCommandInScope(SearchPathResourceAccessor resourceAccessor, DatabaseTestSystem db, String changelogFile,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,6 @@ Required Args:
url (String) The JDBC database connection URL
OBFUSCATED
Optional Args:
changelogFile (String) The root changelog
Default: null
defaultCatalogName (String) The default catalog name to use for the database connection
Default: null
defaultSchemaName (String) The default schema name to use for the database connection
Expand Down Expand Up @@ -80,50 +78,6 @@ Optional Args:
]
}

run "Happy path with an unregistered changelog file does not show Hub messaging", {
arguments = [
url : { it.url },
username : { it.username },
password : { it.password },
changelogFile: "changelogs/h2/complete/simple.changelog.xml"
]
setup {
database = [
new CreateTableChange(
tableName: "FirstTable",
columns: [
ColumnConfig.fromName("FirstColumn")
.setType("VARCHAR(255)")
]
),
new CreateTableChange(
tableName: "SecondTable",
columns: [
ColumnConfig.fromName("SecondColumn")
.setType("VARCHAR(255)")
]
),
new TagDatabaseChange(
tag: "version_2.0"
),
new CreateTableChange(
tableName: "liquibaseRunInfo",
columns: [
ColumnConfig.fromName("timesRan")
.setType("INT")
]
),
]
}

expectedUI = [
CommandTests.assertNotContains("WARNING: The changelog file specified is not registered with any Liquibase Hub project")
]
expectedResults = [
statusCode : 0,
]
}

run "Run without a URL should throw an exception", {
arguments = [
url : "",
Expand Down
12 changes: 3 additions & 9 deletions liquibase-standard/src/main/java/liquibase/Liquibase.java
Original file line number Diff line number Diff line change
Expand Up @@ -1136,17 +1136,11 @@ public final void dropAll() throws DatabaseException {
*/
public final void dropAll(CatalogAndSchema... schemas) throws DatabaseException {

if ((schemas == null) || (schemas.length == 0)) {
schemas = new CatalogAndSchema[]{
new CatalogAndSchema(getDatabase().getDefaultCatalogName(), getDatabase().getDefaultSchemaName())
};
}

CatalogAndSchema[] finalSchemas = schemas;
try {
CommandScope dropAll = new CommandScope("internalDropAll")
.addArgumentValue(InternalDropAllCommandStep.DATABASE_ARG, Liquibase.this.getDatabase())
.addArgumentValue(InternalDropAllCommandStep.SCHEMAS_ARG, finalSchemas);
CommandScope dropAll = new CommandScope("dropAll")
.addArgumentValue(DbUrlConnectionCommandStep.DATABASE_ARG, Liquibase.this.getDatabase())
.addArgumentValue(DropAllCommandStep.CATALOG_AND_SCHEMAS_ARG, finalSchemas);

try {
dropAll.execute();
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,49 +1,37 @@
package liquibase.command.core;

import liquibase.CatalogAndSchema;
import liquibase.Scope;
import liquibase.command.*;
import liquibase.configuration.ConfigurationValueObfuscator;
import liquibase.exception.CommandExecutionException;
import liquibase.database.Database;
import liquibase.exception.DatabaseException;
import liquibase.exception.LiquibaseException;
import liquibase.lockservice.LockService;
import liquibase.logging.Logger;
import liquibase.util.StringUtil;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

public class DropAllCommandStep extends AbstractCliWrapperCommandStep {
public class DropAllCommandStep extends AbstractCommandStep {

public static final String[] COMMAND_NAME = {"dropAll"};

public static final CommandArgumentDefinition<String> USERNAME_ARG;
public static final CommandArgumentDefinition<String> PASSWORD_ARG;
public static final CommandArgumentDefinition<String> URL_ARG;
public static final CommandArgumentDefinition<String> DEFAULT_CATALOG_NAME_ARG;
public static final CommandArgumentDefinition<String> DEFAULT_SCHEMA_NAME_ARG;
private final Logger log = Scope.getCurrentScope().getLog(DropAllCommandStep.class);

public static final CommandArgumentDefinition<String> SCHEMAS_ARG;
public static final CommandArgumentDefinition<String> CHANGELOG_FILE_ARG;
public static final CommandArgumentDefinition<CatalogAndSchema[]> CATALOG_AND_SCHEMAS_ARG;
public static final CommandArgumentDefinition<UUID> HUB_CONNECTION_ID_ARG;
public static final CommandArgumentDefinition<UUID> HUB_PROJECT_ID_ARG;
public static final CommandArgumentDefinition<String> DRIVER_ARG;
public static final CommandArgumentDefinition<String> DRIVER_PROPERTIES_FILE_ARG;

static {
CommandBuilder builder = new CommandBuilder(COMMAND_NAME);
URL_ARG = builder.argument(CommonArgumentNames.URL, String.class).required()
.description("The JDBC database connection URL").build();
USERNAME_ARG = builder.argument(CommonArgumentNames.USERNAME, String.class)
.description("Username to use to connect to the database").build();
SCHEMAS_ARG = builder.argument("schemas", String.class)
.description("Schemas to include in drop").build();
DEFAULT_SCHEMA_NAME_ARG = builder.argument("defaultSchemaName", String.class)
.description("The default schema name to use for the database connection").build();
DEFAULT_CATALOG_NAME_ARG = builder.argument("defaultCatalogName", String.class)
.description("The default catalog name to use for the database connection").build();
DRIVER_ARG = builder.argument("driver", String.class)
.description("The JDBC driver class").build();
DRIVER_PROPERTIES_FILE_ARG = builder.argument("driverPropertiesFile", String.class)
.description("The JDBC driver properties file").build();
PASSWORD_ARG = builder.argument(CommonArgumentNames.PASSWORD, String.class)
.description("Password to use to connect to the database")
.setValueObfuscator(ConfigurationValueObfuscator.STANDARD)
.build();
CHANGELOG_FILE_ARG = builder.argument(CommonArgumentNames.CHANGELOG_FILE, String.class)
.description("The root changelog").build();
SCHEMAS_ARG = builder.argument("schemas", String.class).description("Schemas to include in drop").build();
CATALOG_AND_SCHEMAS_ARG = builder.argument("catalogAndSchemas", CatalogAndSchema[].class)
.description("Catalog and schemas to include in drop. It has precedence over SCHEMAS_ARG").supersededBy(SCHEMAS_ARG).hidden().build();
SCHEMAS_ARG.setSupersededBy(CATALOG_AND_SCHEMAS_ARG);
HUB_CONNECTION_ID_ARG = builder.argument("hubConnectionId", UUID.class)
.description("Used to identify the specific Connection in which to record or extract data at Liquibase Hub. Available in your Liquibase Hub Project at https://hub.liquibase.com.").build();
HUB_PROJECT_ID_ARG = builder.argument("hubProjectId", UUID.class)
Expand All @@ -54,13 +42,60 @@ public class DropAllCommandStep extends AbstractCliWrapperCommandStep {
public String[][] defineCommandNames() {
return new String[][] { COMMAND_NAME };
}

@Override
public void adjustCommandDefinition(CommandDefinition commandDefinition) {
commandDefinition.setShortDescription("Drop all database objects owned by the user");
}

@Override
protected String[] collectArguments(CommandScope commandScope) throws CommandExecutionException {
return collectArguments(commandScope, null, null);
public List<Class<?>> requiredDependencies() {
return Arrays.asList(Database.class, LockService.class);
}

@Override
public void run(CommandResultsBuilder resultsBuilder) throws Exception {
CommandScope commandScope = resultsBuilder.getCommandScope();
Database database = (Database) commandScope.getDependency(Database.class);

List<CatalogAndSchema> catalogAndSchemas = getCatalogAndSchemas(database, commandScope);

try {
for (CatalogAndSchema catalogAndSchema : catalogAndSchemas) {
log.info("Dropping Database Objects in schema: " + catalogAndSchema);
database.dropDatabaseObjects(catalogAndSchema);
}
} catch (LiquibaseException liquibaseException) {
String message =
String.format("Error occurred during dropAll: %s%nIt is possible that not all objects were dropped.%n",
liquibaseException.getMessage());

Scope.getCurrentScope().getUI().sendMessage(message);
log.severe(message, liquibaseException);
} catch (Exception e) {
throw new DatabaseException(e);
}

Scope.getCurrentScope().getUI().sendMessage("All objects dropped from " + database.getConnection().getConnectionUserName() + "@" + database.getConnection().getURL());
resultsBuilder.addResult("statusCode", 0);
}

private List<CatalogAndSchema> getCatalogAndSchemas(Database database, CommandScope commandScope) {
String schemas = commandScope.getArgumentValue(SCHEMAS_ARG);
CatalogAndSchema[] catalogAndSchemas = commandScope.getArgumentValue(CATALOG_AND_SCHEMAS_ARG);

if (catalogAndSchemas != null && catalogAndSchemas.length > 0) {
return Arrays.asList(catalogAndSchemas);
}

List<CatalogAndSchema> computedCatalogAndSchemas = new ArrayList<>();
if (schemas == null || schemas.isEmpty()) {
computedCatalogAndSchemas.add(new CatalogAndSchema(database.getDefaultCatalogName(), database.getDefaultSchemaName()));
} else {
StringUtil.splitAndTrim(schemas, ",").forEach(s ->
computedCatalogAndSchemas.add(new CatalogAndSchema(null, s).customize(database))
);
} return computedCatalogAndSchemas;
}

}