use of liquibase.diff.output.DiffOutputControl in project dropwizard by dropwizard.
the class DbDumpCommand method run.
@Override
@SuppressWarnings("UseOfSystemOutOrSystemErr")
public void run(Namespace namespace, Liquibase liquibase) throws Exception {
final Set<Class<? extends DatabaseObject>> compareTypes = new HashSet<>();
if (isTrue(namespace.getBoolean("columns"))) {
compareTypes.add(Column.class);
}
if (isTrue(namespace.getBoolean("data"))) {
compareTypes.add(Data.class);
}
if (isTrue(namespace.getBoolean("foreign-keys"))) {
compareTypes.add(ForeignKey.class);
}
if (isTrue(namespace.getBoolean("indexes"))) {
compareTypes.add(Index.class);
}
if (isTrue(namespace.getBoolean("primary-keys"))) {
compareTypes.add(PrimaryKey.class);
}
if (isTrue(namespace.getBoolean("sequences"))) {
compareTypes.add(Sequence.class);
}
if (isTrue(namespace.getBoolean("tables"))) {
compareTypes.add(Table.class);
}
if (isTrue(namespace.getBoolean("unique-constraints"))) {
compareTypes.add(UniqueConstraint.class);
}
if (isTrue(namespace.getBoolean("views"))) {
compareTypes.add(View.class);
}
final DiffToChangeLog diffToChangeLog = new DiffToChangeLog(new DiffOutputControl());
final Database database = liquibase.getDatabase();
final String filename = namespace.getString("output");
if (filename != null) {
try (PrintStream file = new PrintStream(filename, StandardCharsets.UTF_8.name())) {
generateChangeLog(database, database.getDefaultSchema(), diffToChangeLog, file, compareTypes);
}
} else {
generateChangeLog(database, database.getDefaultSchema(), diffToChangeLog, outputStream, compareTypes);
}
}
use of liquibase.diff.output.DiffOutputControl in project liquibase by liquibase.
the class AbstractJdbcDatabase method dropDatabaseObjects.
// ------- DATABASE OBJECT DROPPING METHODS ---- //
/**
* Drops all objects owned by the connected user.
*/
@Override
public void dropDatabaseObjects(final CatalogAndSchema schemaToDrop) throws LiquibaseException {
ObjectQuotingStrategy currentStrategy = this.getObjectQuotingStrategy();
this.setObjectQuotingStrategy(ObjectQuotingStrategy.QUOTE_ALL_OBJECTS);
try {
DatabaseSnapshot snapshot;
try {
final SnapshotControl snapshotControl = new SnapshotControl(this);
final Set<Class<? extends DatabaseObject>> typesToInclude = snapshotControl.getTypesToInclude();
//We do not need to remove indexes and primary/unique keys explicitly. They should be removed
//as part of tables.
typesToInclude.remove(Index.class);
typesToInclude.remove(PrimaryKey.class);
typesToInclude.remove(UniqueConstraint.class);
if (supportsForeignKeyDisable()) {
//We do not remove ForeignKey because they will be disabled and removed as parts of tables.
typesToInclude.remove(ForeignKey.class);
}
final long createSnapshotStarted = System.currentTimeMillis();
snapshot = SnapshotGeneratorFactory.getInstance().createSnapshot(schemaToDrop, this, snapshotControl);
LogFactory.getLogger().debug(String.format("Database snapshot generated in %d ms. Snapshot includes: %s", System.currentTimeMillis() - createSnapshotStarted, typesToInclude));
} catch (LiquibaseException e) {
throw new UnexpectedLiquibaseException(e);
}
final long changeSetStarted = System.currentTimeMillis();
DiffResult diffResult = DiffGeneratorFactory.getInstance().compare(new EmptyDatabaseSnapshot(this), snapshot, new CompareControl(snapshot.getSnapshotControl().getTypesToInclude()));
List<ChangeSet> changeSets = new DiffToChangeLog(diffResult, new DiffOutputControl(true, true, false, null).addIncludedSchema(schemaToDrop)).generateChangeSets();
LogFactory.getLogger().debug(String.format("ChangeSet to Remove Database Objects generated in %d ms.", System.currentTimeMillis() - changeSetStarted));
boolean previousAutoCommit = this.getAutoCommitMode();
//clear out currently executed statements
this.commit();
//some DDL doesn't work in autocommit mode
this.setAutoCommit(false);
final boolean reEnableFK = supportsForeignKeyDisable() && disableForeignKeyChecks();
try {
for (ChangeSet changeSet : changeSets) {
changeSet.setFailOnError(false);
for (Change change : changeSet.getChanges()) {
if (change instanceof DropTableChange) {
((DropTableChange) change).setCascadeConstraints(true);
}
SqlStatement[] sqlStatements = change.generateStatements(this);
for (SqlStatement statement : sqlStatements) {
ExecutorService.getInstance().getExecutor(this).execute(statement);
}
}
this.commit();
}
} finally {
if (reEnableFK) {
enableForeignKeyChecks();
}
}
ChangeLogHistoryServiceFactory.getInstance().getChangeLogService(this).destroy();
LockServiceFactory.getInstance().getLockService(this).destroy();
this.setAutoCommit(previousAutoCommit);
} finally {
this.setObjectQuotingStrategy(currentStrategy);
this.commit();
}
}
use of liquibase.diff.output.DiffOutputControl in project liquibase by liquibase.
the class Main method doMigration.
protected void doMigration() throws Exception {
if ("help".equalsIgnoreCase(command)) {
printHelp(System.err);
return;
}
try {
if (null != logFile) {
LogFactory.getInstance().getLog().setLogLevel(logLevel, logFile);
} else {
LogFactory.getInstance().getLog().setLogLevel(logLevel);
}
} catch (IllegalArgumentException e) {
throw new CommandLineParsingException(e.getMessage(), e);
}
FileSystemResourceAccessor fsOpener = new FileSystemResourceAccessor();
CommandLineResourceAccessor clOpener = new CommandLineResourceAccessor(classLoader);
CompositeResourceAccessor fileOpener = new CompositeResourceAccessor(fsOpener, clOpener);
Database 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);
try {
CompareControl.ComputedSchemas computedSchemas = CompareControl.computeSchemas(getCommandParam("schemas", null), getCommandParam("referenceSchemas", null), getCommandParam("outputSchemasAs", null), defaultCatalogName, defaultSchemaName, referenceDefaultCatalogName, referenceDefaultSchemaName, database);
CompareControl.SchemaComparison[] finalSchemaComparisons = computedSchemas.finalSchemaComparisons;
CatalogAndSchema[] finalTargetSchemas = computedSchemas.finalTargetSchemas;
boolean includeCatalog = Boolean.parseBoolean(getCommandParam("includeCatalog", "false"));
boolean includeSchema = Boolean.parseBoolean(getCommandParam("includeSchema", "false"));
boolean includeTablespace = Boolean.parseBoolean(getCommandParam("includeTablespace", "false"));
String excludeObjects = StringUtils.trimToNull(getCommandParam("excludeObjects", null));
String includeObjects = StringUtils.trimToNull(getCommandParam("includeObjects", null));
DiffOutputControl diffOutputControl = new DiffOutputControl(includeCatalog, includeSchema, includeTablespace, finalSchemaComparisons);
if (excludeObjects != null && includeObjects != null) {
throw new UnexpectedLiquibaseException("Cannot specify both excludeObjects and includeObjects");
}
if (excludeObjects != null) {
diffOutputControl.setObjectChangeFilter(new StandardObjectChangeFilter(StandardObjectChangeFilter.FilterType.EXCLUDE, excludeObjects));
}
if (includeObjects != null) {
diffOutputControl.setObjectChangeFilter(new StandardObjectChangeFilter(StandardObjectChangeFilter.FilterType.INCLUDE, includeObjects));
}
for (CompareControl.SchemaComparison schema : finalSchemaComparisons) {
diffOutputControl.addIncludedSchema(schema.getReferenceSchema());
diffOutputControl.addIncludedSchema(schema.getComparisonSchema());
}
if ("diff".equalsIgnoreCase(command)) {
CommandLineUtils.doDiff(createReferenceDatabaseFromCommandParams(commandParams, fileOpener), database, StringUtils.trimToNull(diffTypes), finalSchemaComparisons);
return;
} else if ("diffChangeLog".equalsIgnoreCase(command)) {
CommandLineUtils.doDiffToChangeLog(changeLogFile, createReferenceDatabaseFromCommandParams(commandParams, fileOpener), database, diffOutputControl, StringUtils.trimToNull(diffTypes), finalSchemaComparisons);
return;
} else if ("generateChangeLog".equalsIgnoreCase(command)) {
String changeLogFile = this.changeLogFile;
if (changeLogFile == null) {
//will output to stdout
changeLogFile = "";
}
// By default the generateChangeLog command is destructive, and
// Liquibase's attempt to append doesn't work properly. Just
// fail the build if the file already exists.
File file = new File(changeLogFile);
if (file.exists()) {
throw new LiquibaseException("ChangeLogFile " + changeLogFile + " already exists!");
}
CommandLineUtils.doGenerateChangeLog(changeLogFile, database, finalTargetSchemas, StringUtils.trimToNull(diffTypes), StringUtils.trimToNull(changeSetAuthor), StringUtils.trimToNull(changeSetContext), StringUtils.trimToNull(dataOutputDirectory), diffOutputControl);
return;
} else if ("snapshot".equalsIgnoreCase(command)) {
SnapshotCommand command = (SnapshotCommand) CommandFactory.getInstance().getCommand("snapshot");
command.setDatabase(database);
command.setSchemas(getCommandParam("schemas", database.getDefaultSchema().getSchemaName()));
command.setSerializerFormat(getCommandParam("snapshotFormat", null));
Writer outputWriter = getOutputWriter();
outputWriter.write(command.execute().print());
outputWriter.flush();
outputWriter.close();
return;
} else if ("executeSql".equalsIgnoreCase(command)) {
ExecuteSqlCommand command = (ExecuteSqlCommand) CommandFactory.getInstance().getCommand("execute");
command.setDatabase(database);
command.setSql(getCommandParam("sql", null));
command.setSqlFile(getCommandParam("sqlFile", null));
command.setDelimiter(getCommandParam("delimiter", ";"));
Writer outputWriter = getOutputWriter();
outputWriter.write(command.execute().print());
outputWriter.flush();
outputWriter.close();
return;
} else if ("snapshotReference".equalsIgnoreCase(command)) {
SnapshotCommand command = (SnapshotCommand) CommandFactory.getInstance().getCommand("snapshot");
Database referenceDatabase = createReferenceDatabaseFromCommandParams(commandParams, fileOpener);
command.setDatabase(referenceDatabase);
command.setSchemas(getCommandParam("schemas", referenceDatabase.getDefaultSchema().getSchemaName()));
Writer outputWriter = getOutputWriter();
outputWriter.write(command.execute().print());
outputWriter.flush();
outputWriter.close();
return;
}
Liquibase liquibase = new Liquibase(changeLogFile, fileOpener, database);
ChangeExecListener listener = ChangeExecListenerUtils.getChangeExecListener(liquibase.getDatabase(), liquibase.getResourceAccessor(), changeExecListenerClass, changeExecListenerPropertiesFile);
liquibase.setChangeExecListener(listener);
liquibase.setCurrentDateTimeFunction(currentDateTimeFunction);
for (Map.Entry<String, Object> entry : changeLogParameters.entrySet()) {
liquibase.setChangeLogParameter(entry.getKey(), entry.getValue());
}
if ("listLocks".equalsIgnoreCase(command)) {
liquibase.reportLocks(System.err);
return;
} else if ("releaseLocks".equalsIgnoreCase(command)) {
LockService lockService = LockServiceFactory.getInstance().getLockService(database);
lockService.forceReleaseLock();
System.err.println("Successfully released all database change log locks for " + liquibase.getDatabase().getConnection().getConnectionUserName() + "@" + liquibase.getDatabase().getConnection().getURL());
return;
} else if ("tag".equalsIgnoreCase(command)) {
liquibase.tag(getCommandArgument());
System.err.println("Successfully tagged " + liquibase.getDatabase().getConnection().getConnectionUserName() + "@" + liquibase.getDatabase().getConnection().getURL());
return;
} else if ("tagExists".equalsIgnoreCase(command)) {
String tag = commandParams.iterator().next();
boolean exists = liquibase.tagExists(tag);
if (exists) {
System.err.println("The tag " + tag + " already exists in " + liquibase.getDatabase().getConnection().getConnectionUserName() + "@" + liquibase.getDatabase().getConnection().getURL());
} else {
System.err.println("The tag " + tag + " does not exist in " + liquibase.getDatabase().getConnection().getConnectionUserName() + "@" + liquibase.getDatabase().getConnection().getURL());
}
return;
} else if ("dropAll".equals(command)) {
DropAllCommand command = (DropAllCommand) CommandFactory.getInstance().getCommand("dropAll");
command.setDatabase(liquibase.getDatabase());
command.setSchemas(getCommandParam("schemas", database.getDefaultSchema().getSchemaName()));
System.err.println(command.execute().print());
return;
} else if ("status".equalsIgnoreCase(command)) {
boolean runVerbose = false;
if (commandParams.contains("--verbose")) {
runVerbose = true;
}
liquibase.reportStatus(runVerbose, new Contexts(contexts), new LabelExpression(labels), getOutputWriter());
return;
} else if ("unexpectedChangeSets".equalsIgnoreCase(command)) {
boolean runVerbose = false;
if (commandParams.contains("--verbose")) {
runVerbose = true;
}
liquibase.reportUnexpectedChangeSets(runVerbose, contexts, getOutputWriter());
return;
} else if ("validate".equalsIgnoreCase(command)) {
try {
liquibase.validate();
} catch (ValidationFailedException e) {
e.printDescriptiveError(System.err);
return;
}
System.err.println("No validation errors found");
return;
} else if ("clearCheckSums".equalsIgnoreCase(command)) {
liquibase.clearCheckSums();
return;
} else if ("calculateCheckSum".equalsIgnoreCase(command)) {
CheckSum checkSum = null;
checkSum = liquibase.calculateCheckSum(commandParams.iterator().next());
System.out.println(checkSum);
return;
} else if ("dbdoc".equalsIgnoreCase(command)) {
if (commandParams.size() == 0) {
throw new CommandLineParsingException("dbdoc requires an output directory");
}
if (changeLogFile == null) {
throw new CommandLineParsingException("dbdoc requires a changeLog parameter");
}
liquibase.generateDocumentation(commandParams.iterator().next(), contexts);
return;
}
try {
if ("update".equalsIgnoreCase(command)) {
liquibase.update(new Contexts(contexts), new LabelExpression(labels));
} else if ("changelogSync".equalsIgnoreCase(command)) {
liquibase.changeLogSync(new Contexts(contexts), new LabelExpression(labels));
} else if ("changelogSyncSQL".equalsIgnoreCase(command)) {
liquibase.changeLogSync(new Contexts(contexts), new LabelExpression(labels), getOutputWriter());
} else if ("markNextChangeSetRan".equalsIgnoreCase(command)) {
liquibase.markNextChangeSetRan(new Contexts(contexts), new LabelExpression(labels));
} else if ("markNextChangeSetRanSQL".equalsIgnoreCase(command)) {
liquibase.markNextChangeSetRan(new Contexts(contexts), new LabelExpression(labels), getOutputWriter());
} else if ("updateCount".equalsIgnoreCase(command)) {
liquibase.update(Integer.parseInt(commandParams.iterator().next()), new Contexts(contexts), new LabelExpression(labels));
} else if ("updateCountSQL".equalsIgnoreCase(command)) {
liquibase.update(Integer.parseInt(commandParams.iterator().next()), new Contexts(contexts), new LabelExpression(labels), getOutputWriter());
} else if ("updateToTag".equalsIgnoreCase(command)) {
if (commandParams == null || commandParams.size() == 0) {
throw new CommandLineParsingException("updateToTag requires a tag");
}
liquibase.update(commandParams.iterator().next(), new Contexts(contexts), new LabelExpression(labels));
} else if ("updateToTagSQL".equalsIgnoreCase(command)) {
if (commandParams == null || commandParams.size() == 0) {
throw new CommandLineParsingException("updateToTagSQL requires a tag");
}
liquibase.update(commandParams.iterator().next(), new Contexts(contexts), new LabelExpression(labels), getOutputWriter());
} else if ("updateSQL".equalsIgnoreCase(command)) {
liquibase.update(new Contexts(contexts), new LabelExpression(labels), getOutputWriter());
} else if ("rollback".equalsIgnoreCase(command)) {
if (getCommandArgument() == null) {
throw new CommandLineParsingException("rollback requires a rollback tag");
}
liquibase.rollback(getCommandArgument(), getCommandParam("rollbackScript", null), new Contexts(contexts), new LabelExpression(labels));
} else if ("rollbackToDate".equalsIgnoreCase(command)) {
if (getCommandArgument() == null) {
throw new CommandLineParsingException("rollback requires a rollback date");
}
liquibase.rollback(new ISODateFormat().parse(getCommandArgument()), getCommandParam("rollbackScript", null), new Contexts(contexts), new LabelExpression(labels));
} else if ("rollbackCount".equalsIgnoreCase(command)) {
liquibase.rollback(Integer.parseInt(getCommandArgument()), getCommandParam("rollbackScript", null), new Contexts(contexts), new LabelExpression(labels));
} else if ("rollbackSQL".equalsIgnoreCase(command)) {
if (getCommandArgument() == null) {
throw new CommandLineParsingException("rollbackSQL requires a rollback tag");
}
liquibase.rollback(getCommandArgument(), getCommandParam("rollbackScript", null), new Contexts(contexts), new LabelExpression(labels), getOutputWriter());
} else if ("rollbackToDateSQL".equalsIgnoreCase(command)) {
if (getCommandArgument() == null) {
throw new CommandLineParsingException("rollbackToDateSQL requires a rollback date");
}
liquibase.rollback(new ISODateFormat().parse(getCommandArgument()), getCommandParam("rollbackScript", null), new Contexts(contexts), new LabelExpression(labels), getOutputWriter());
} else if ("rollbackCountSQL".equalsIgnoreCase(command)) {
if (getCommandArgument() == null) {
throw new CommandLineParsingException("rollbackCountSQL requires a rollback count");
}
liquibase.rollback(Integer.parseInt(getCommandArgument()), getCommandParam("rollbackScript", null), new Contexts(contexts), new LabelExpression(labels), getOutputWriter());
} else if ("futureRollbackSQL".equalsIgnoreCase(command)) {
liquibase.futureRollbackSQL(new Contexts(contexts), new LabelExpression(labels), getOutputWriter());
} else if ("futureRollbackCountSQL".equalsIgnoreCase(command)) {
if (getCommandArgument() == null) {
throw new CommandLineParsingException("futureRollbackCountSQL requires a rollback count");
}
liquibase.futureRollbackSQL(Integer.parseInt(getCommandArgument()), new Contexts(contexts), new LabelExpression(labels), getOutputWriter());
} else if ("futureRollbackFromTagSQL".equalsIgnoreCase(command)) {
if (getCommandArgument() == null) {
throw new CommandLineParsingException("futureRollbackFromTagSQL requires a tag");
}
liquibase.futureRollbackSQL(getCommandArgument(), new Contexts(contexts), new LabelExpression(labels), getOutputWriter());
} else if ("updateTestingRollback".equalsIgnoreCase(command)) {
liquibase.updateTestingRollback(new Contexts(contexts), new LabelExpression(labels));
} else {
throw new CommandLineParsingException("Unknown command: " + command);
}
} catch (ParseException e) {
throw new CommandLineParsingException("Unexpected date/time format. Use 'yyyy-MM-dd'T'HH:mm:ss'");
}
} finally {
try {
database.rollback();
database.close();
} catch (DatabaseException e) {
LogFactory.getInstance().getLog().warning("problem closing connection", e);
}
}
}
use of liquibase.diff.output.DiffOutputControl in project liquibase by liquibase.
the class H2IntegrationTest method diffToChangeLog.
@Test
public void diffToChangeLog() throws Exception {
if (getDatabase() == null) {
return;
}
runCompleteChangeLog();
DiffResult diffResult = DiffGeneratorFactory.getInstance().compare(getDatabase(), null, new CompareControl());
new DiffToChangeLog(diffResult, new DiffOutputControl(true, true, true, null)).print(System.out);
}
use of liquibase.diff.output.DiffOutputControl in project liquibase by liquibase.
the class LiquibaseDatabaseDiff method performLiquibaseTask.
@Override
protected void performLiquibaseTask(Liquibase liquibase) throws LiquibaseException {
ClassLoader cl = null;
ResourceAccessor fileOpener;
try {
cl = getClassLoaderIncludingProjectClasspath();
Thread.currentThread().setContextClassLoader(cl);
ClassLoader artifactClassLoader = getMavenArtifactClassLoader();
fileOpener = getFileOpener(artifactClassLoader);
} catch (MojoExecutionException e) {
throw new LiquibaseException("Could not create the class loader, " + e, e);
}
Database db = liquibase.getDatabase();
Database referenceDatabase = CommandLineUtils.createDatabaseObject(fileOpener, referenceUrl, referenceUsername, referencePassword, referenceDriver, referenceDefaultCatalogName, referenceDefaultSchemaName, outputDefaultCatalog, outputDefaultSchema, null, null, propertyProviderClass, null, null, databaseChangeLogTableName, databaseChangeLogLockTableName);
getLog().info("Performing Diff on database " + db.toString());
if (diffChangeLogFile != null) {
try {
DiffOutputControl diffOutputControl = new DiffOutputControl(diffIncludeCatalog, diffIncludeSchema, diffIncludeTablespace, null).addIncludedSchema(new CatalogAndSchema(referenceDefaultCatalogName, referenceDefaultSchemaName));
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));
}
CommandLineUtils.doDiffToChangeLog(diffChangeLogFile, referenceDatabase, db, diffOutputControl, StringUtils.trimToNull(diffTypes));
getLog().info("Differences written to Change Log File, " + diffChangeLogFile);
} catch (IOException e) {
throw new LiquibaseException(e);
} catch (ParserConfigurationException e) {
throw new LiquibaseException(e);
}
} else {
CommandLineUtils.doDiff(referenceDatabase, db, StringUtils.trimToNull(diffTypes));
}
}
Aggregations