use of liquibase.CatalogAndSchema in project liquibase by liquibase.
the class DiffCommand method createReferenceSnapshot.
protected DatabaseSnapshot createReferenceSnapshot() throws DatabaseException, InvalidExampleException {
CatalogAndSchema[] schemas;
if (compareControl == null || compareControl.getSchemaComparisons() == null) {
schemas = new CatalogAndSchema[] { targetDatabase.getDefaultSchema() };
} else {
schemas = new CatalogAndSchema[compareControl.getSchemaComparisons().length];
int i = 0;
for (CompareControl.SchemaComparison comparison : compareControl.getSchemaComparisons()) {
CatalogAndSchema schema;
if (referenceDatabase.supportsSchemas()) {
schema = new CatalogAndSchema(referenceDatabase.getDefaultCatalogName(), comparison.getReferenceSchema().getSchemaName());
} else {
schema = new CatalogAndSchema(comparison.getReferenceSchema().getSchemaName(), comparison.getReferenceSchema().getSchemaName());
}
schemas[i++] = schema;
}
}
SnapshotControl snapshotControl = getReferenceSnapshotControl();
if (snapshotControl == null) {
snapshotControl = new SnapshotControl(referenceDatabase, snapshotTypes);
}
if (getSnapshotListener() != null) {
snapshotControl.setSnapshotListener(getSnapshotListener());
}
ObjectQuotingStrategy originalStrategy = referenceDatabase.getObjectQuotingStrategy();
try {
referenceDatabase.setObjectQuotingStrategy(ObjectQuotingStrategy.QUOTE_ALL_OBJECTS);
return SnapshotGeneratorFactory.getInstance().createSnapshot(schemas, referenceDatabase, snapshotControl);
} finally {
referenceDatabase.setObjectQuotingStrategy(originalStrategy);
}
}
use of liquibase.CatalogAndSchema 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.CatalogAndSchema in project liquibase by liquibase.
the class AbstractDatabaseDiffTask method getDiffResult.
protected DiffResult getDiffResult() {
Liquibase liquibase = getLiquibase();
Database targetDatabase = liquibase.getDatabase();
Database referenceDatabase = createDatabaseFromType(referenceDatabaseType);
CatalogAndSchema targetCatalogAndSchema = buildCatalogAndSchema(targetDatabase);
CatalogAndSchema referenceCatalogAndSchema = buildCatalogAndSchema(referenceDatabase);
CompareControl.SchemaComparison[] schemaComparisons = { new CompareControl.SchemaComparison(referenceCatalogAndSchema, targetCatalogAndSchema) };
SnapshotGeneratorFactory snapshotGeneratorFactory = SnapshotGeneratorFactory.getInstance();
DatabaseSnapshot referenceSnapshot;
try {
referenceSnapshot = snapshotGeneratorFactory.createSnapshot(referenceDatabase.getDefaultSchema(), referenceDatabase, new SnapshotControl(referenceDatabase, diffTypes));
} catch (LiquibaseException e) {
throw new BuildException("Unable to create a DatabaseSnapshot. " + e.toString(), e);
}
CompareControl compareControl = new CompareControl(schemaComparisons, referenceSnapshot.getSnapshotControl().getTypesToInclude());
try {
return liquibase.diff(referenceDatabase, targetDatabase, compareControl);
} catch (LiquibaseException e) {
throw new BuildException("Unable to diff databases. " + e.toString(), e);
}
}
use of liquibase.CatalogAndSchema in project liquibase by liquibase.
the class MissingPrimaryKeyChangeGenerator method fixMissing.
@Override
public Change[] fixMissing(DatabaseObject missingObject, DiffOutputControl control, Database referenceDatabase, Database comparisonDatabase, ChangeGeneratorChain chain) {
List<Change> returnList = new ArrayList<Change>();
PrimaryKey pk = (PrimaryKey) missingObject;
AddPrimaryKeyChange change = createAddPrimaryKeyChange();
change.setTableName(pk.getTable().getName());
if (control.getIncludeCatalog()) {
change.setCatalogName(pk.getTable().getSchema().getCatalogName());
}
if (control.getIncludeSchema()) {
change.setSchemaName(pk.getTable().getSchema().getName());
}
change.setConstraintName(pk.getName());
change.setColumnNames(pk.getColumnNames());
if (control.getIncludeTablespace()) {
change.setTablespace(pk.getTablespace());
}
if (referenceDatabase instanceof MSSQLDatabase && pk.getBackingIndex() != null && pk.getBackingIndex().getClustered() != null && !pk.getBackingIndex().getClustered()) {
change.setClustered(false);
}
if (referenceDatabase instanceof PostgresDatabase && pk.getBackingIndex() != null && pk.getBackingIndex().getClustered() != null && pk.getBackingIndex().getClustered()) {
change.setClustered(true);
}
if (comparisonDatabase instanceof OracleDatabase || (comparisonDatabase instanceof DB2Database && pk.getBackingIndex() != null && !comparisonDatabase.isSystemObject(pk.getBackingIndex()))) {
Index backingIndex = pk.getBackingIndex();
if (backingIndex != null && backingIndex.getName() != null) {
try {
if (!control.getIncludeCatalog() && !control.getIncludeSchema()) {
CatalogAndSchema schema = comparisonDatabase.getDefaultSchema().customize(comparisonDatabase);
//set table schema so it is found in the correct schema
backingIndex.getTable().setSchema(schema.getCatalogName(), schema.getSchemaName());
}
if (referenceDatabase.equals(comparisonDatabase) || !SnapshotGeneratorFactory.getInstance().has(backingIndex, comparisonDatabase)) {
Change[] fixes = ChangeGeneratorFactory.getInstance().fixMissing(backingIndex, control, referenceDatabase, comparisonDatabase);
if (fixes != null) {
for (Change fix : fixes) {
if (fix != null) {
returnList.add(fix);
}
}
}
}
} catch (Exception e) {
throw new UnexpectedLiquibaseException(e);
}
change.setForIndexName(backingIndex.getName());
Schema schema = backingIndex.getSchema();
if (schema != null) {
if (control.getIncludeCatalog()) {
change.setForIndexCatalogName(schema.getCatalogName());
}
if (control.getIncludeSchema()) {
change.setForIndexSchemaName(schema.getName());
}
}
}
}
control.setAlreadyHandledMissing(pk.getBackingIndex());
returnList.add(change);
return returnList.toArray(new Change[returnList.size()]);
}
use of liquibase.CatalogAndSchema in project liquibase by liquibase.
the class SnapshotGeneratorFactory method has.
public boolean has(DatabaseObject example, Database database) throws DatabaseException, InvalidExampleException {
List<Class<? extends DatabaseObject>> types = new ArrayList<Class<? extends DatabaseObject>>(getContainerTypes(example.getClass(), database));
types.add(example.getClass());
//workaround for common check for databasechangelog/lock table to not snapshot the whole database like we have to in order to handle case issues
if (example instanceof Table && (example.getName().equals(database.getDatabaseChangeLogTableName()) || example.getName().equals(database.getDatabaseChangeLogLockTableName()))) {
try {
ExecutorService.getInstance().getExecutor(database).queryForInt(new RawSqlStatement("select count(*) from " + database.escapeObjectName(database.getLiquibaseCatalogName(), database.getLiquibaseSchemaName(), example.getName(), Table.class)));
return true;
} catch (DatabaseException e) {
if (database instanceof PostgresDatabase) {
//throws "current transaction is aborted" unless we roll back the connection
database.rollback();
}
return false;
}
}
if (createSnapshot(example, database, new SnapshotControl(database, false, types.toArray(new Class[types.size()]))) != null) {
return true;
}
CatalogAndSchema catalogAndSchema;
if (example.getSchema() == null) {
catalogAndSchema = database.getDefaultSchema();
} else {
catalogAndSchema = example.getSchema().toCatalogAndSchema();
}
DatabaseSnapshot snapshot = createSnapshot(catalogAndSchema, database, new SnapshotControl(database, false, example.getClass()));
for (DatabaseObject obj : snapshot.get(example.getClass())) {
if (DatabaseObjectComparatorFactory.getInstance().isSameObject(example, obj, null, database)) {
return true;
}
}
return false;
}
Aggregations