use of liquibase.LabelExpression 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.LabelExpression in project liquibase by liquibase.
the class LiquibaseServletListener method executeUpdate.
/**
* Executes the Liquibase update.
*/
private void executeUpdate(ServletContext servletContext, InitialContext ic) throws NamingException, SQLException, LiquibaseException {
setDataSource((String) servletValueContainer.getValue(LIQUIBASE_DATASOURCE));
if (getDataSource() == null) {
throw new RuntimeException("Cannot run Liquibase, " + LIQUIBASE_DATASOURCE + " is not set");
}
setChangeLogFile((String) servletValueContainer.getValue(LIQUIBASE_CHANGELOG));
if (getChangeLogFile() == null) {
throw new RuntimeException("Cannot run Liquibase, " + LIQUIBASE_CHANGELOG + " is not set");
}
setContexts((String) servletValueContainer.getValue(LIQUIBASE_CONTEXTS));
setLabels((String) servletValueContainer.getValue(LIQUIBASE_LABELS));
this.defaultSchema = StringUtils.trimToNull((String) servletValueContainer.getValue(LIQUIBASE_SCHEMA_DEFAULT));
Connection connection = null;
Database database = null;
try {
DataSource dataSource = (DataSource) ic.lookup(this.dataSourceName);
connection = dataSource.getConnection();
Thread currentThread = Thread.currentThread();
ClassLoader contextClassLoader = currentThread.getContextClassLoader();
ResourceAccessor threadClFO = new ClassLoaderResourceAccessor(contextClassLoader);
ResourceAccessor clFO = new ClassLoaderResourceAccessor();
ResourceAccessor fsFO = new FileSystemResourceAccessor();
database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(new JdbcConnection(connection));
database.setDefaultSchemaName(getDefaultSchema());
Liquibase liquibase = new Liquibase(getChangeLogFile(), new CompositeResourceAccessor(clFO, fsFO, threadClFO), database);
@SuppressWarnings("unchecked") Enumeration<String> initParameters = servletContext.getInitParameterNames();
while (initParameters.hasMoreElements()) {
String name = initParameters.nextElement().trim();
if (name.startsWith(LIQUIBASE_PARAMETER + ".")) {
liquibase.setChangeLogParameter(name.substring(LIQUIBASE_PARAMETER.length() + 1), servletValueContainer.getValue(name));
}
}
liquibase.update(new Contexts(getContexts()), new LabelExpression(getLabels()));
} finally {
if (database != null) {
database.close();
} else if (connection != null) {
connection.close();
}
}
}
use of liquibase.LabelExpression in project liquibase by liquibase.
the class CDILiquibase method performUpdate.
private void performUpdate() throws LiquibaseException {
Connection c = null;
Liquibase liquibase = null;
try {
c = dataSource.getConnection();
liquibase = createLiquibase(c);
liquibase.getDatabase();
liquibase.update(new Contexts(config.getContexts()), new LabelExpression(config.getLabels()));
updateSuccessful = true;
} catch (SQLException e) {
throw new DatabaseException(e);
} catch (LiquibaseException ex) {
updateSuccessful = false;
throw ex;
} finally {
if (liquibase != null && liquibase.getDatabase() != null) {
liquibase.getDatabase().close();
} else if (c != null) {
try {
c.rollback();
c.close();
} catch (SQLException e) {
//nothing to do
}
}
}
}
use of liquibase.LabelExpression in project liquibase by liquibase.
the class AbstractIntegrationTest method testTagEmptyDatabase.
@Test
public void testTagEmptyDatabase() throws Exception {
if (database == null) {
return;
}
Liquibase liquibase = createLiquibase(completeChangeLog);
clearDatabase(liquibase);
liquibase = createLiquibase(completeChangeLog);
liquibase.checkLiquibaseTables(false, null, new Contexts(), new LabelExpression());
liquibase.tag("empty");
liquibase = createLiquibase(rollbackChangeLog);
liquibase.update(new Contexts());
liquibase.rollback("empty", new Contexts());
}
use of liquibase.LabelExpression in project liquibase by liquibase.
the class DropAllCommand method run.
@Override
protected CommandResult run() throws Exception {
try {
LockServiceFactory.getInstance().getLockService(database).waitForLock();
for (CatalogAndSchema schema : schemas) {
log.info("Dropping Database Objects in schema: " + schema);
checkLiquibaseTables(false, null, new Contexts(), new LabelExpression());
database.dropDatabaseObjects(schema);
}
} catch (DatabaseException e) {
throw e;
} catch (Exception e) {
throw new DatabaseException(e);
} finally {
LockServiceFactory.getInstance().getLockService(database).destroy();
resetServices();
}
return new CommandResult("All objects dropped from " + database.getConnection().getConnectionUserName() + "@" + database.getConnection().getURL());
}
Aggregations