use of liquibase.database.Database in project liquibase by liquibase.
the class StandardChangeLogHistoryService method getRanChangeSets.
/**
* Returns the ChangeSets that have been run against the current getDatabase().
*/
public List<RanChangeSet> getRanChangeSets() throws DatabaseException {
if (this.ranChangeSetList == null) {
Database database = getDatabase();
String databaseChangeLogTableName = getDatabase().escapeTableName(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName());
List<RanChangeSet> ranChangeSetList = new ArrayList<RanChangeSet>();
if (hasDatabaseChangeLogTable()) {
LogFactory.getLogger().info("Reading from " + databaseChangeLogTableName);
List<Map<String, ?>> results = queryDatabaseChangeLogTable(database);
for (Map rs : results) {
String fileName = rs.get("FILENAME").toString();
String author = rs.get("AUTHOR").toString();
String id = rs.get("ID").toString();
String md5sum = rs.get("MD5SUM") == null || !databaseChecksumsCompatible ? null : rs.get("MD5SUM").toString();
String description = rs.get("DESCRIPTION") == null ? null : rs.get("DESCRIPTION").toString();
String comments = rs.get("COMMENTS") == null ? null : rs.get("COMMENTS").toString();
Object tmpDateExecuted = rs.get("DATEEXECUTED");
Date dateExecuted = null;
if (tmpDateExecuted instanceof Date) {
dateExecuted = (Date) tmpDateExecuted;
} else {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
dateExecuted = df.parse((String) tmpDateExecuted);
} catch (ParseException e) {
}
}
String tmpOrderExecuted = rs.get("ORDEREXECUTED").toString();
Integer orderExecuted = (tmpOrderExecuted == null ? null : Integer.valueOf(tmpOrderExecuted));
String tag = rs.get("TAG") == null ? null : rs.get("TAG").toString();
String execType = rs.get("EXECTYPE") == null ? null : rs.get("EXECTYPE").toString();
ContextExpression contexts = new ContextExpression((String) rs.get("CONTEXTS"));
Labels labels = new Labels((String) rs.get("LABELS"));
String deploymentId = (String) rs.get("DEPLOYMENT_ID");
try {
RanChangeSet ranChangeSet = new RanChangeSet(fileName, id, author, CheckSum.parse(md5sum), dateExecuted, tag, ChangeSet.ExecType.valueOf(execType), description, comments, contexts, labels, deploymentId);
ranChangeSet.setOrderExecuted(orderExecuted);
ranChangeSetList.add(ranChangeSet);
} catch (IllegalArgumentException e) {
LogFactory.getLogger().severe("Unknown EXECTYPE from database: " + execType);
throw e;
}
}
}
this.ranChangeSetList = ranChangeSetList;
}
return Collections.unmodifiableList(ranChangeSetList);
}
use of liquibase.database.Database in project liquibase by liquibase.
the class StandardChangeLogHistoryService method setExecType.
@Override
public void setExecType(ChangeSet changeSet, ChangeSet.ExecType execType) throws DatabaseException {
Database database = getDatabase();
ExecutorService.getInstance().getExecutor(database).execute(new MarkChangeSetRanStatement(changeSet, execType));
getDatabase().commit();
if (this.ranChangeSetList != null) {
this.ranChangeSetList.add(new RanChangeSet(changeSet, execType, null, null));
}
}
use of liquibase.database.Database in project liquibase by liquibase.
the class ExecuteShellCommandChange method generateStatements.
@Override
public SqlStatement[] generateStatements(final Database database) {
boolean shouldRun = true;
if (os != null && os.size() > 0) {
String currentOS = System.getProperty("os.name");
if (!os.contains(currentOS)) {
shouldRun = false;
LogFactory.getLogger().info("Not executing on os " + currentOS + " when " + os + " was specified");
}
}
// check if running under not-executed mode (logging output)
boolean nonExecutedMode = false;
Executor executor = ExecutorService.getInstance().getExecutor(database);
if (executor instanceof LoggingExecutor) {
nonExecutedMode = true;
}
this.finalCommandArray = createFinalCommandArray(database);
if (shouldRun && !nonExecutedMode) {
return new SqlStatement[] { new RuntimeStatement() {
@Override
public Sql[] generate(Database database) {
try {
executeCommand(database);
} catch (Exception e) {
throw new UnexpectedLiquibaseException("Error executing command: " + e.getLocalizedMessage(), e);
}
return null;
}
} };
}
if (nonExecutedMode) {
try {
return new SqlStatement[] { new CommentStatement(getCommandString()) };
} finally {
nonExecutedCleanup();
}
}
return new SqlStatement[0];
}
use of liquibase.database.Database 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.database.Database 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();
}
}
}
Aggregations