use of liquibase.exception.LiquibaseException in project liquibase by liquibase.
the class ValidatingVisitorPreConditionsTest method testPreconditionForOracleOnOracleWithChangeLog.
/**
* Test against oracle, but I don't know for sure if the precondition is really
* validated because oracle supports creating sequences.
*/
@Test
public void testPreconditionForOracleOnOracleWithChangeLog() {
// create the pre condition
PreconditionContainer preCondition = new PreconditionContainer();
preCondition.setOnFail(PreconditionContainer.FailOption.MARK_RAN.toString());
DBMSPrecondition dbmsPrecondition = new DBMSPrecondition();
dbmsPrecondition.setType("oracle");
preCondition.addNestedPrecondition(dbmsPrecondition);
changeSet1.setPreconditions(preCondition);
OracleDatabase oracleDb = new OracleDatabase() {
@Override
public List<RanChangeSet> getRanChangeSetList() throws DatabaseException {
return new ArrayList<RanChangeSet>();
}
@Override
public void rollback() throws DatabaseException {
//super.rollback();
}
};
String[] empty = {};
boolean exceptionThrown = false;
try {
changeLog.validate(oracleDb, empty);
} catch (LiquibaseException ex) {
exceptionThrown = true;
}
assertFalse(exceptionThrown);
}
use of liquibase.exception.LiquibaseException in project liquibase by liquibase.
the class AbstractLiquibaseMojo method execute.
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
getLog().info(MavenUtils.LOG_SEPARATOR);
if (server != null) {
AuthenticationInfo info = wagonManager.getAuthenticationInfo(server);
if (info != null) {
username = info.getUserName();
password = info.getPassword();
}
}
processSystemProperties();
LiquibaseConfiguration liquibaseConfiguration = LiquibaseConfiguration.getInstance();
if (!liquibaseConfiguration.getConfiguration(GlobalConfiguration.class).getShouldRun()) {
getLog().info("Liquibase did not run because " + liquibaseConfiguration.describeValueLookupLogic(GlobalConfiguration.class, GlobalConfiguration.SHOULD_RUN) + " was set to false");
return;
}
if (skip) {
getLog().warn("Liquibase skipped due to maven configuration");
return;
}
ClassLoader artifactClassLoader = getMavenArtifactClassLoader();
ResourceAccessor fileOpener = getFileOpener(artifactClassLoader);
configureFieldsAndValues(fileOpener);
LogFactory.getInstance().setDefaultLoggingLevel(logging);
// Displays the settings for the Mojo depending of verbosity mode.
displayMojoSettings();
// Check that all the parameters that must be specified have been by the user.
checkRequiredParametersAreSpecified();
Database database = null;
try {
String dbPassword = emptyPassword || password == null ? "" : password;
String driverPropsFile = (driverPropertiesFile == null) ? null : driverPropertiesFile.getAbsolutePath();
database = CommandLineUtils.createDatabaseObject(artifactClassLoader, url, username, dbPassword, driver, defaultCatalogName, defaultSchemaName, outputDefaultCatalog, outputDefaultSchema, databaseClass, driverPropsFile, propertyProviderClass, changelogCatalogName, changelogSchemaName, databaseChangeLogTableName, databaseChangeLogLockTableName);
liquibase = createLiquibase(fileOpener, database);
getLog().debug("expressionVars = " + String.valueOf(expressionVars));
if (expressionVars != null) {
for (Map.Entry<Object, Object> var : expressionVars.entrySet()) {
this.liquibase.setChangeLogParameter(var.getKey().toString(), var.getValue());
}
}
getLog().debug("expressionVariables = " + String.valueOf(expressionVariables));
if (expressionVariables != null) {
for (Map.Entry var : (Set<Map.Entry>) expressionVariables.entrySet()) {
if (var.getValue() != null) {
this.liquibase.setChangeLogParameter(var.getKey().toString(), var.getValue());
}
}
}
if (clearCheckSums) {
getLog().info("Clearing the Liquibase Checksums on the database");
liquibase.clearCheckSums();
}
getLog().info("Executing on Database: " + url);
if (isPromptOnNonLocalDatabase()) {
if (!liquibase.isSafeToRunUpdate()) {
if (UIFactory.getInstance().getFacade().promptForNonLocalDatabase(liquibase.getDatabase())) {
throw new LiquibaseException("User decided not to run against non-local database");
}
}
}
performLiquibaseTask(liquibase);
} catch (LiquibaseException e) {
cleanup(database);
throw new MojoExecutionException("Error setting up or running Liquibase: " + e.getMessage(), e);
}
cleanup(database);
getLog().info(MavenUtils.LOG_SEPARATOR);
getLog().info("");
}
use of liquibase.exception.LiquibaseException in project liquibase by liquibase.
the class MavenUtils method getDatabaseConnection.
public static Connection getDatabaseConnection(ClassLoader classLoader, String driver, String url, String username, String password) throws LiquibaseException {
Driver dbDriver = null;
try {
dbDriver = (Driver) Class.forName(driver, true, classLoader).newInstance();
} catch (InstantiationException e) {
throw new LiquibaseException("Failed to load JDBC driver, " + driver, e);
} catch (IllegalAccessException e) {
throw new LiquibaseException("Failed to load JDBC driver, " + driver, e);
} catch (ClassNotFoundException e) {
throw new LiquibaseException("Missing Class '" + e.getMessage() + "'. Database " + "driver may not be included in the project " + "dependencies or with wrong scope.");
}
Properties info = new Properties();
info.put("user", username);
info.put("password", password);
try {
Connection connection = dbDriver.connect(url, info);
if (connection == null) {
throw new LiquibaseException("Connection could not be created to " + url + " with driver " + dbDriver.getClass().getName() + ". Possibly the wrong driver for the given " + "database URL");
}
return connection;
} catch (SQLException e) {
throw new LiquibaseException(e);
}
}
use of liquibase.exception.LiquibaseException in project liquibase by liquibase.
the class StandardChangeLogHistoryService method init.
public void init() throws DatabaseException {
if (serviceInitialized) {
return;
}
Database database = getDatabase();
Executor executor = ExecutorService.getInstance().getExecutor(database);
Table changeLogTable = null;
try {
changeLogTable = SnapshotGeneratorFactory.getInstance().getDatabaseChangeLogTable(new SnapshotControl(database, false, Table.class, Column.class), database);
} catch (LiquibaseException e) {
throw new UnexpectedLiquibaseException(e);
}
List<SqlStatement> statementsToExecute = new ArrayList<SqlStatement>();
boolean changeLogCreateAttempted = false;
if (changeLogTable != null) {
boolean hasDescription = changeLogTable.getColumn("DESCRIPTION") != null;
boolean hasComments = changeLogTable.getColumn("COMMENTS") != null;
boolean hasTag = changeLogTable.getColumn("TAG") != null;
boolean hasLiquibase = changeLogTable.getColumn("LIQUIBASE") != null;
boolean hasContexts = changeLogTable.getColumn("CONTEXTS") != null;
boolean hasLabels = changeLogTable.getColumn("LABELS") != null;
boolean liquibaseColumnNotRightSize = false;
if (!(this.getDatabase() instanceof SQLiteDatabase)) {
DataType type = changeLogTable.getColumn("LIQUIBASE").getType();
if (type.getTypeName().toLowerCase().startsWith("varchar")) {
Integer columnSize = type.getColumnSize();
liquibaseColumnNotRightSize = columnSize != null && columnSize < 20;
} else {
liquibaseColumnNotRightSize = false;
}
}
boolean hasOrderExecuted = changeLogTable.getColumn("ORDEREXECUTED") != null;
boolean checksumNotRightSize = false;
if (!(this.getDatabase() instanceof SQLiteDatabase)) {
DataType type = changeLogTable.getColumn("MD5SUM").getType();
if (type.getTypeName().toLowerCase().startsWith("varchar")) {
Integer columnSize = type.getColumnSize();
checksumNotRightSize = columnSize != null && columnSize < 35;
} else {
liquibaseColumnNotRightSize = false;
}
}
boolean hasExecTypeColumn = changeLogTable.getColumn("EXECTYPE") != null;
String charTypeName = getCharTypeName();
boolean hasDeploymentIdColumn = changeLogTable.getColumn("DEPLOYMENT_ID") != null;
if (!hasDescription) {
executor.comment("Adding missing databasechangelog.description column");
statementsToExecute.add(new AddColumnStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "DESCRIPTION", charTypeName + "(255)", null));
}
if (!hasTag) {
executor.comment("Adding missing databasechangelog.tag column");
statementsToExecute.add(new AddColumnStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "TAG", charTypeName + "(255)", null));
}
if (!hasComments) {
executor.comment("Adding missing databasechangelog.comments column");
statementsToExecute.add(new AddColumnStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "COMMENTS", charTypeName + "(255)", null));
}
if (!hasLiquibase) {
executor.comment("Adding missing databasechangelog.liquibase column");
statementsToExecute.add(new AddColumnStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "LIQUIBASE", charTypeName + "(20)", null));
}
if (!hasOrderExecuted) {
executor.comment("Adding missing databasechangelog.orderexecuted column");
statementsToExecute.add(new AddColumnStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "ORDEREXECUTED", "int", null));
statementsToExecute.add(new UpdateStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName()).addNewColumnValue("ORDEREXECUTED", -1));
statementsToExecute.add(new SetNullableStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "ORDEREXECUTED", "int", false));
}
if (checksumNotRightSize) {
executor.comment("Modifying size of databasechangelog.md5sum column");
statementsToExecute.add(new ModifyDataTypeStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "MD5SUM", charTypeName + "(35)"));
}
if (liquibaseColumnNotRightSize) {
executor.comment("Modifying size of databasechangelog.liquibase column");
statementsToExecute.add(new ModifyDataTypeStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "LIQUIBASE", charTypeName + "(20)"));
}
if (!hasExecTypeColumn) {
executor.comment("Adding missing databasechangelog.exectype column");
statementsToExecute.add(new AddColumnStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "EXECTYPE", charTypeName + "(10)", null));
statementsToExecute.add(new UpdateStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName()).addNewColumnValue("EXECTYPE", "EXECUTED"));
statementsToExecute.add(new SetNullableStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "EXECTYPE", charTypeName + "(10)", false));
}
if (hasContexts) {
Integer columnSize = changeLogTable.getColumn("CONTEXTS").getType().getColumnSize();
if (columnSize != null && columnSize < Integer.parseInt(getContextsSize())) {
executor.comment("Modifying size of databasechangelog.contexts column");
statementsToExecute.add(new ModifyDataTypeStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "CONTEXTS", charTypeName + "(" + getContextsSize() + ")"));
}
} else {
executor.comment("Adding missing databasechangelog.contexts column");
statementsToExecute.add(new AddColumnStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "CONTEXTS", charTypeName + "(" + getContextsSize() + ")", null));
}
if (hasLabels) {
Integer columnSize = changeLogTable.getColumn("LABELS").getType().getColumnSize();
if (columnSize != null && columnSize < Integer.parseInt(getLabelsSize())) {
executor.comment("Modifying size of databasechangelog.labels column");
statementsToExecute.add(new ModifyDataTypeStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "LABELS", charTypeName + "(" + getLabelsSize() + ")"));
}
} else {
executor.comment("Adding missing databasechangelog.labels column");
statementsToExecute.add(new AddColumnStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "LABELS", charTypeName + "(" + getLabelsSize() + ")", null));
}
if (!hasDeploymentIdColumn) {
executor.comment("Adding missing databasechangelog.deployment_id column");
statementsToExecute.add(new AddColumnStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "DEPLOYMENT_ID", "VARCHAR(10)", null));
if (database instanceof DB2Database) {
statementsToExecute.add(new ReorganizeTableStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName()));
}
}
List<Map<String, ?>> md5sumRS = ExecutorService.getInstance().getExecutor(database).queryForList(new SelectFromDatabaseChangeLogStatement(new SelectFromDatabaseChangeLogStatement.ByNotNullCheckSum(), new ColumnConfig().setName("MD5SUM")).setLimit(1));
if (md5sumRS.size() > 0) {
String md5sum = md5sumRS.get(0).get("MD5SUM").toString();
if (!md5sum.startsWith(CheckSum.getCurrentVersion() + ":")) {
executor.comment("DatabaseChangeLog checksums are an incompatible version. Setting them to null so they will be updated on next database update");
databaseChecksumsCompatible = false;
statementsToExecute.add(new RawSqlStatement("UPDATE " + getDatabase().escapeTableName(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName()) + " " + "SET " + getDatabase().escapeObjectName("MD5SUM", Column.class) + " = NULL"));
}
}
} else if (!changeLogCreateAttempted) {
executor.comment("Create Database Change Log Table");
SqlStatement createTableStatement = new CreateDatabaseChangeLogTableStatement();
if (!canCreateChangeLogTable()) {
throw new DatabaseException("Cannot create " + getDatabase().escapeTableName(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName()) + " table for your getDatabase().\n\n" + "Please construct it manually using the following SQL as a base and re-run Liquibase:\n\n" + createTableStatement);
}
// If there is no table in the database for recording change history create one.
statementsToExecute.add(createTableStatement);
LogFactory.getLogger().info("Creating database history table with name: " + getDatabase().escapeTableName(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName()));
}
for (SqlStatement sql : statementsToExecute) {
if (SqlGeneratorFactory.getInstance().supports(sql, database)) {
executor.execute(sql);
getDatabase().commit();
} else {
LogFactory.getLogger().info("Cannot run " + sql.getClass().getSimpleName() + " on " + getDatabase().getShortName() + " when checking databasechangelog table");
}
}
serviceInitialized = true;
}
use of liquibase.exception.LiquibaseException in project liquibase by liquibase.
the class ExecuteSqlCommand method run.
@Override
protected CommandResult run() throws Exception {
Executor executor = ExecutorService.getInstance().getExecutor(database);
String sqlText;
if (sqlFile == null) {
sqlText = sql;
} else {
File file = new File(sqlFile);
if (!file.exists()) {
throw new LiquibaseException(String.format("The file '%s' does not exist", file.getCanonicalPath()));
}
sqlText = FileUtil.getContents(file);
}
String out = "";
String[] sqlStrings = StringUtils.processMutliLineSQL(sqlText, true, true, delimiter);
for (String sql : sqlStrings) {
if (sql.toLowerCase().matches("\\s*select .*")) {
List<Map<String, ?>> rows = executor.queryForList(new RawSqlStatement(sql));
out += "Output of " + sql + ":\n";
if (rows.size() == 0) {
out += "-- Empty Resultset --\n";
} else {
SortedSet<String> keys = new TreeSet<String>();
for (Map<String, ?> row : rows) {
keys.addAll(row.keySet());
}
out += StringUtils.join(keys, " | ") + " |\n";
for (Map<String, ?> row : rows) {
for (String key : keys) {
out += row.get(key) + " | ";
}
out += "\n";
}
}
} else {
executor.execute(new RawSqlStatement(sql));
out += "Successfully Executed: " + sql + "\n";
}
out += "\n";
}
database.commit();
return new CommandResult(out.trim());
}
Aggregations