liquibase.structure.DatabaseObject Java Examples

The following examples show how to use liquibase.structure.DatabaseObject. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AbstractJdbcDatabase.java    From jweb-cms with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public boolean isSystemObject(final DatabaseObject example) {
    if (example == null) {
        return false;
    }
    if ((example.getSchema() != null) && (example.getSchema().getName() != null) && "information_schema"
        .equalsIgnoreCase(example.getSchema().getName())) {
        return true;
    }
    if ((example instanceof Table) && getSystemTables().contains(example.getName())) {
        return true;
    }

    return (example instanceof View) && getSystemViews().contains(example.getName());

}
 
Example #2
Source File: AbstractJdbcDatabase.java    From jweb-cms with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public boolean isLiquibaseObject(final DatabaseObject object) {
    if (object instanceof Table) {
        Schema liquibaseSchema = new Schema(getLiquibaseCatalogName(), getLiquibaseSchemaName());
        if (DatabaseObjectComparatorFactory.getInstance().isSameObject(object, new Table().setName(getDatabaseChangeLogTableName()).setSchema(liquibaseSchema), null, this)) {
            return true;
        }
        return DatabaseObjectComparatorFactory.getInstance().isSameObject(object, new Table().setName(getDatabaseChangeLogLockTableName()).setSchema(liquibaseSchema), null, this);
    } else if (object instanceof Column) {
        return isLiquibaseObject(((Column) object).getRelation());
    } else if (object instanceof Index) {
        return isLiquibaseObject(((Index) object).getRelation());
    } else if (object instanceof PrimaryKey) {
        return isLiquibaseObject(((PrimaryKey) object).getTable());
    }
    return false;
}
 
Example #3
Source File: DropSpatialIndexGeneratorGeoDB.java    From liquibase-spatial with Apache License 2.0 6 votes vote down vote up
/**
 * Generates the SQL statement to drop the spatial index if it exists.
 * 
 * @param statement
 *           the drop spatial index statement.
 * @param database
 *           the database.
 * @return the drop spatial index statement, if the index exists.
 */
public Sql[] generateSqlIfExists(final DropSpatialIndexStatement statement,
      final Database database) {
   final String catalogName = statement.getTableCatalogName();
   final String schemaName = statement.getTableSchemaName();
   final String tableName = statement.getTableName();
   final SpatialIndexExistsPrecondition precondition = new SpatialIndexExistsPrecondition();
   precondition.setCatalogName(catalogName);
   precondition.setSchemaName(schemaName);
   precondition.setTableName(tableName);
   final DatabaseObject example = precondition.getExample(database, tableName);
   try {
      // If a spatial index exists on the table, drop it.
      if (SnapshotGeneratorFactory.getInstance().has(example, database)) {
         return generateSql(statement, database, null);
      }
   } catch (final Exception e) {
      throw new UnexpectedLiquibaseException(e);
   }
   return new Sql[0];
}
 
Example #4
Source File: GeometryColumnsUtils.java    From liquibase-spatial with Apache License 2.0 6 votes vote down vote up
/**
 * Indicates if the <code>GEOMETRY_COLUMNS</code> table or view exists.
 * 
 * @param database
 *           the database to check.
 * @return <code>true</code> if the table or view exists.
 */
public static boolean geometryColumnsExists(final Database database) {
   String geometryColumnsName = database.correctObjectName(
         "geometry_columns", Table.class);
   DatabaseObject example = null;
   if (database instanceof DerbyDatabase || database instanceof H2Database) {
      final Table tableExample = new Table();
      tableExample.setName(geometryColumnsName);
      tableExample.setSchema(database.getDefaultCatalogName(),
            database.getDefaultSchemaName());
      example = tableExample;
   } else if (database instanceof PostgresDatabase) {
      final View viewExample = new View();
      viewExample.setName(geometryColumnsName);
      viewExample.setSchema(database.getDefaultCatalogName(), "public");
      example = viewExample;
   }
   try {
      return example != null
            && SnapshotGeneratorFactory.getInstance().has(example, database);
   } catch (final LiquibaseException e) {
      throw new UnexpectedLiquibaseException(
            "Failed to determine if the geometry_columns table or view exists",
            e);
   }
}
 
Example #5
Source File: DropStoredProcedureGeneratorMSSQL.java    From liquibase-mssql with Apache License 2.0 6 votes vote down vote up
public Sql[] generateSql(DropStoredProcedureStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) {
    StringBuilder sql = new StringBuilder();
    sql.append("declare @procName varchar(500)\n");
    sql.append("declare cur cursor\n");
    sql.append("for select [name] from sys.objects where type = 'p' AND is_ms_shipped = 0\n");
    sql.append("open cur\n");
    sql.append("fetch next from cur into @procName\n");
    sql.append("while @@fetch_status = 0\n");
    sql.append("begin\n");
    sql.append("exec('drop procedure ' + @procName)\n");
    sql.append("fetch next from cur into @procName\n");
    sql.append("end\n");
    sql.append("close cur\n");
    sql.append("deallocate cur\n");
    
    return (new Sql[] {
        new UnparsedSql(sql.toString(), new DatabaseObject[0])
    });
}
 
Example #6
Source File: AbstractJdbcDatabase.java    From jweb-cms with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public String correctObjectName(final String objectName, final Class<? extends DatabaseObject> objectType) {
    if ((quotingStrategy == ObjectQuotingStrategy.QUOTE_ALL_OBJECTS) || (unquotedObjectsAreUppercased == null) ||
        (objectName == null) || (objectName.startsWith(getQuotingStartCharacter()) && objectName.endsWith(getQuotingEndCharacter()))) {
        return objectName;
    } else if (Boolean.TRUE.equals(unquotedObjectsAreUppercased)) {
        return objectName.toUpperCase(Locale.US);
    } else {
        return objectName.toLowerCase(Locale.US);
    }
}
 
Example #7
Source File: AbstractJdbcDatabase.java    From jweb-cms with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public String escapeObjectName(String objectName, final Class<? extends DatabaseObject> objectType) {
    if (objectName != null) {
        objectName = objectName.trim();
        if (mustQuoteObjectName(objectName, objectType)) {
            return quoteObject(objectName, objectType);
        } else if (quotingStrategy == ObjectQuotingStrategy.QUOTE_ALL_OBJECTS) {
            return quoteObject(objectName, objectType);
        }
    }
    return objectName;
}
 
Example #8
Source File: SpatialIndexExistsPrecondition.java    From liquibase-spatial with Apache License 2.0 5 votes vote down vote up
/**
 * Creates an example of the database object for which to check.
 *
 * @param database
 *           the database instance.
 * @param tableName
 *           the table name of the index.
 * @return the database object example.
 */
public DatabaseObject getExample(final Database database, final String tableName) {
   final Schema schema = new Schema(getCatalogName(), getSchemaName());
   final DatabaseObject example;

   // For GeoDB, the index is another table.
   if (database instanceof DerbyDatabase || database instanceof H2Database) {
      final String correctedTableName = database.correctObjectName(getHatboxTableName(),
            Table.class);
      example = new Table().setName(correctedTableName).setSchema(schema);
   } else {
      example = getIndexExample(database, schema, tableName);
   }
   return example;
}
 
Example #9
Source File: AbstractJdbcDatabase.java    From jweb-cms with GNU Affero General Public License v3.0 4 votes vote down vote up
public DatabaseObject[] getContainingObjects() {
    return null;
}
 
Example #10
Source File: AbstractJdbcDatabase.java    From jweb-cms with GNU Affero General Public License v3.0 4 votes vote down vote up
@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);
            LogService.getLog(getClass()).debug(LogType.LOG, 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();
        CompareControl compareControl = new CompareControl(
            new CompareControl.SchemaComparison[]{
                new CompareControl.SchemaComparison(
                    CatalogAndSchema.DEFAULT,
                    schemaToDrop)},
            snapshot.getSnapshotControl().getTypesToInclude());
        DiffResult diffResult = DiffGeneratorFactory.getInstance().compare(
            new EmptyDatabaseSnapshot(this),
            snapshot,
            compareControl);

        List<ChangeSet> changeSets = new DiffToChangeLog(diffResult, new DiffOutputControl(true, true, false, null).addIncludedSchema(schemaToDrop)).generateChangeSets();
        LogService.getLog(getClass()).debug(LogType.LOG, String.format("ChangeSet to Remove Database Objects generated in %d ms.", System.currentTimeMillis() - changeSetStarted));

        boolean previousAutoCommit = this.getAutoCommitMode();
        this.commit(); //clear out currently executed statements
        this.setAutoCommit(false); //some DDL doesn't work in autocommit mode
        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);
        LogService.getLog(getClass()).info(LogType.LOG, String.format("Successfully deleted all supported object types in schema %s.", schemaToDrop.toString()));
    } finally {
        this.setObjectQuotingStrategy(currentStrategy);
        this.commit();
    }
}
 
Example #11
Source File: AbstractJdbcDatabase.java    From jweb-cms with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public String escapeObjectName(String catalogName, String schemaName, final String objectName,
                               final Class<? extends DatabaseObject> objectType) {
    if (supportsSchemas()) {
        catalogName = StringUtils.trimToNull(catalogName);
        schemaName = StringUtils.trimToNull(schemaName);

        if (catalogName == null) {
            catalogName = this.getDefaultCatalogName();
        }
        if (schemaName == null) {
            schemaName = this.getDefaultSchemaName();
        }

        if (!supportsCatalogInObjectName(objectType)) {
            catalogName = null;
        }
        if ((catalogName == null) && (schemaName == null)) {
            return escapeObjectName(objectName, objectType);
        } else if ((catalogName == null) || !this.supportsCatalogInObjectName(objectType)) {
            if (isDefaultSchema(catalogName, schemaName) && !getOutputDefaultSchema()) {
                return escapeObjectName(objectName, objectType);
            } else {
                return escapeObjectName(schemaName, Schema.class) + "." + escapeObjectName(objectName, objectType);
            }
        } else {
            if (isDefaultSchema(catalogName, schemaName) && !getOutputDefaultSchema() && !getOutputDefaultCatalog
                ()) {
                return escapeObjectName(objectName, objectType);
            } else if (isDefaultSchema(catalogName, schemaName) && !getOutputDefaultCatalog()) {
                return escapeObjectName(schemaName, Schema.class) + "." + escapeObjectName(objectName, objectType);
            } else {
                return escapeObjectName(catalogName, Catalog.class) + "." + escapeObjectName(schemaName, Schema.class) + "." + escapeObjectName(objectName, objectType);
            }
        }
    } else if (supportsCatalogs()) {
        catalogName = StringUtils.trimToNull(catalogName);
        schemaName = StringUtils.trimToNull(schemaName);

        if (catalogName != null) {
            if (getOutputDefaultCatalog()) {
                return escapeObjectName(catalogName, Catalog.class) + "." + escapeObjectName(objectName, objectType);
            } else {
                if (!defaultCatalogSet && isDefaultCatalog(catalogName)) {
                    return escapeObjectName(objectName, objectType);
                } else {
                    return escapeObjectName(catalogName, Catalog.class) + "." + escapeObjectName(objectName, objectType);
                }
            }
        } else {

            //they actually mean catalog name
            if (schemaName != null) {
                if (getOutputDefaultCatalog()) {
                    return escapeObjectName(schemaName, Catalog.class) + "." + escapeObjectName(objectName, objectType);
                } else {
                    if (!defaultCatalogSet && isDefaultCatalog(schemaName)) {
                        return escapeObjectName(objectName, objectType);
                    } else {
                        return escapeObjectName(schemaName, Catalog.class) + "." + escapeObjectName(objectName, objectType);
                    }
                }
            } else {
                catalogName = this.getDefaultCatalogName();

                if (catalogName == null) {
                    return escapeObjectName(objectName, objectType);
                } else {
                    if (defaultCatalogSet || (isDefaultCatalog(catalogName) && getOutputDefaultCatalog())) {
                        return escapeObjectName(catalogName, Catalog.class) + "." + escapeObjectName(objectName, objectType);
                    } else {
                        return escapeObjectName(objectName, objectType);
                    }
                }
            }
        }

    } else {
        return escapeObjectName(objectName, objectType);
    }
}
 
Example #12
Source File: AbstractJdbcDatabase.java    From jweb-cms with GNU Affero General Public License v3.0 4 votes vote down vote up
protected boolean mustQuoteObjectName(String objectName, Class<? extends DatabaseObject> objectType) {
    return objectName.contains("-") || startsWithNumeric(objectName) || isReservedWord(objectName) || objectName.matches(".*\\W.*");
}
 
Example #13
Source File: AbstractJdbcDatabase.java    From jweb-cms with GNU Affero General Public License v3.0 4 votes vote down vote up
public String quoteObject(final String objectName, final Class<? extends DatabaseObject> objectType) {
    if (objectName == null) {
        return null;
    }
    return getQuotingStartCharacter() + objectName.replace(getQuotingEndCharacter(), getQuotingEndReplacement()) + getQuotingEndCharacter();
}
 
Example #14
Source File: AbstractJdbcDatabase.java    From jweb-cms with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public boolean supportsCatalogInObjectName(final Class<? extends DatabaseObject> type) {
    return false;
}