Search in sources :

Example 6 with InvalidExampleException

use of liquibase.snapshot.InvalidExampleException in project liquibase by liquibase.

the class AddAutoIncrementChange method checkStatus.

@Override
public ChangeStatus checkStatus(Database database) {
    ChangeStatus result = new ChangeStatus();
    Column example = new Column(Table.class, getCatalogName(), getSchemaName(), getTableName(), getColumnName());
    try {
        Column column = SnapshotGeneratorFactory.getInstance().createSnapshot(example, database);
        if (column == null) {
            return result.unknown("Column does not exist");
        }
        result.assertComplete(column.isAutoIncrement(), "Column is not auto-increment");
        if ((getStartWith() != null) && (column.getAutoIncrementInformation().getStartWith() != null)) {
            result.assertCorrect(getStartWith().equals(column.getAutoIncrementInformation().getStartWith()), "startsWith incorrect");
        }
        if ((getIncrementBy() != null) && (column.getAutoIncrementInformation().getIncrementBy() != null)) {
            result.assertCorrect(getIncrementBy().equals(column.getAutoIncrementInformation().getIncrementBy()), "Increment by incorrect");
        }
        if (getGenerationType() != null && column.getAutoIncrementInformation().getGenerationType() != null) {
            result.assertCorrect(getGenerationType().equals(column.getAutoIncrementInformation().getGenerationType()), "Generation type is incorrect");
        }
        if (getDefaultOnNull() != null && column.getAutoIncrementInformation().getDefaultOnNull() != null) {
            result.assertCorrect(getDefaultOnNull().equals(column.getAutoIncrementInformation().getDefaultOnNull()), "Default on null is incorrect");
        }
        return result;
    } catch (DatabaseException | InvalidExampleException e) {
        return result.unknown(e);
    }
}
Also used : InvalidExampleException(liquibase.snapshot.InvalidExampleException) Column(liquibase.structure.core.Column) DatabaseException(liquibase.exception.DatabaseException)

Example 7 with InvalidExampleException

use of liquibase.snapshot.InvalidExampleException in project dropwizard by dropwizard.

the class DbDumpCommand method generateChangeLog.

private void generateChangeLog(final Database database, final CatalogAndSchema catalogAndSchema, final DiffToChangeLog changeLogWriter, PrintStream outputStream, final Set<Class<? extends DatabaseObject>> compareTypes) throws DatabaseException, IOException, ParserConfigurationException {
    @SuppressWarnings("unchecked") final SnapshotControl snapshotControl = new SnapshotControl(database, compareTypes.toArray(new Class[0]));
    final CompareControl compareControl = new CompareControl(new CompareControl.SchemaComparison[] { new CompareControl.SchemaComparison(catalogAndSchema, catalogAndSchema) }, compareTypes);
    final CatalogAndSchema[] compareControlSchemas = compareControl.getSchemas(CompareControl.DatabaseRole.REFERENCE);
    try {
        final DatabaseSnapshot referenceSnapshot = SnapshotGeneratorFactory.getInstance().createSnapshot(compareControlSchemas, database, snapshotControl);
        final DatabaseSnapshot comparisonSnapshot = SnapshotGeneratorFactory.getInstance().createSnapshot(compareControlSchemas, null, snapshotControl);
        final DiffResult diffResult = DiffGeneratorFactory.getInstance().compare(referenceSnapshot, comparisonSnapshot, compareControl);
        changeLogWriter.setDiffResult(diffResult);
        changeLogWriter.print(outputStream);
    } catch (InvalidExampleException e) {
        throw new UnexpectedLiquibaseException(e);
    }
}
Also used : InvalidExampleException(liquibase.snapshot.InvalidExampleException) CompareControl(liquibase.diff.compare.CompareControl) DiffResult(liquibase.diff.DiffResult) CatalogAndSchema(liquibase.CatalogAndSchema) SnapshotControl(liquibase.snapshot.SnapshotControl) DatabaseSnapshot(liquibase.snapshot.DatabaseSnapshot) UnexpectedLiquibaseException(liquibase.exception.UnexpectedLiquibaseException)

Example 8 with InvalidExampleException

use of liquibase.snapshot.InvalidExampleException in project liquibase by liquibase.

the class DropAllForeignKeyConstraintsChange method generateChildren.

/**
 * Iterates through all the FOREIGN KEYs of the target table and outputs a list of DropForeignKeyConstraintChanges
 * for a given database type.
 *
 * @param database the database type for which subchanges need to be generated
 * @return the list of generated DropForeignKeyConstraintChanges
 */
private List<DropForeignKeyConstraintChange> generateChildren(Database database) {
    // Make a new list
    List<DropForeignKeyConstraintChange> childDropChanges = new ArrayList<>();
    try {
        SnapshotControl control = new SnapshotControl(database);
        control.getTypesToInclude().add(ForeignKey.class);
        CatalogAndSchema catalogAndSchema = new CatalogAndSchema(getBaseTableCatalogName(), getBaseTableSchemaName());
        catalogAndSchema = catalogAndSchema.standardize(database);
        Table target = SnapshotGeneratorFactory.getInstance().createSnapshot(new Table(catalogAndSchema.getCatalogName(), catalogAndSchema.getSchemaName(), database.correctObjectName(getBaseTableName(), Table.class)), database);
        List<ForeignKey> results = ((target == null) ? null : target.getOutgoingForeignKeys());
        Set<String> handledConstraints = new HashSet<>();
        if ((results != null) && (!results.isEmpty())) {
            for (ForeignKey fk : results) {
                Table baseTable = fk.getForeignKeyTable();
                String constraintName = fk.getName();
                if (DatabaseObjectComparatorFactory.getInstance().isSameObject(baseTable, target, null, database)) {
                    if (!handledConstraints.contains(constraintName)) {
                        DropForeignKeyConstraintChange dropForeignKeyConstraintChange = new DropForeignKeyConstraintChange();
                        dropForeignKeyConstraintChange.setBaseTableSchemaName(getBaseTableSchemaName());
                        dropForeignKeyConstraintChange.setBaseTableName(baseTableName);
                        dropForeignKeyConstraintChange.setConstraintName(constraintName);
                        childDropChanges.add(dropForeignKeyConstraintChange);
                        handledConstraints.add(constraintName);
                    }
                } else {
                    throw new UnexpectedLiquibaseException("Expected to return only foreign keys for base table name: " + getBaseTableName() + " and got results for table: " + baseTableName);
                }
            }
        }
        return childDropChanges;
    } catch (DatabaseException | InvalidExampleException e) {
        throw new UnexpectedLiquibaseException("Failed to find foreign keys for table: " + getBaseTableName(), e);
    }
}
Also used : Table(liquibase.structure.core.Table) CatalogAndSchema(liquibase.CatalogAndSchema) ForeignKey(liquibase.structure.core.ForeignKey) InvalidExampleException(liquibase.snapshot.InvalidExampleException) SnapshotControl(liquibase.snapshot.SnapshotControl) UnexpectedLiquibaseException(liquibase.exception.UnexpectedLiquibaseException) DatabaseException(liquibase.exception.DatabaseException)

Example 9 with InvalidExampleException

use of liquibase.snapshot.InvalidExampleException in project liquibase by liquibase.

the class ForeignKeySnapshotGenerator method snapshotObject.

@Override
protected DatabaseObject snapshotObject(DatabaseObject example, DatabaseSnapshot snapshot) throws DatabaseException, InvalidExampleException {
    Database database = snapshot.getDatabase();
    List<CachedRow> importedKeyMetadataResultSet;
    try {
        Table fkTable = ((ForeignKey) example).getForeignKeyTable();
        String searchCatalog = ((AbstractJdbcDatabase) database).getJdbcCatalogName(fkTable.getSchema());
        String searchSchema = ((AbstractJdbcDatabase) database).getJdbcSchemaName(fkTable.getSchema());
        String searchTableName = database.correctObjectName(fkTable.getName(), Table.class);
        importedKeyMetadataResultSet = ((JdbcDatabaseSnapshot) snapshot).getMetaDataFromCache().getForeignKeys(searchCatalog, searchSchema, searchTableName, example.getName());
        ForeignKey foreignKey = null;
        for (CachedRow row : importedKeyMetadataResultSet) {
            String fk_name = cleanNameFromDatabase(row.getString("FK_NAME"), database);
            if (snapshot.getDatabase().isCaseSensitive()) {
                if (!fk_name.equals(example.getName())) {
                    continue;
                } else if (!fk_name.equalsIgnoreCase(example.getName())) {
                    continue;
                }
            }
            if (foreignKey == null) {
                foreignKey = new ForeignKey();
            }
            foreignKey.setName(fk_name);
            String fkTableCatalog = cleanNameFromDatabase(row.getString(METADATA_FKTABLE_CAT), database);
            String fkTableSchema = cleanNameFromDatabase(row.getString(METADATA_FKTABLE_SCHEM), database);
            String fkTableName = cleanNameFromDatabase(row.getString(METADATA_FKTABLE_NAME), database);
            Table foreignKeyTable = new Table().setName(fkTableName);
            foreignKeyTable.setSchema(new Schema(new Catalog(fkTableCatalog), fkTableSchema));
            foreignKey.setForeignKeyTable(foreignKeyTable);
            Column fkColumn = new Column(cleanNameFromDatabase(row.getString(METADATA_FKCOLUMN_NAME), database)).setRelation(foreignKeyTable);
            boolean alreadyAdded = false;
            for (Column existing : foreignKey.getForeignKeyColumns()) {
                if (DatabaseObjectComparatorFactory.getInstance().isSameObject(existing, fkColumn, snapshot.getSchemaComparisons(), database)) {
                    // already added. One is probably an alias
                    alreadyAdded = true;
                }
            }
            if (alreadyAdded) {
                break;
            }
            CatalogAndSchema pkTableSchema = ((AbstractJdbcDatabase) database).getSchemaFromJdbcInfo(row.getString(METADATA_PKTABLE_CAT), row.getString(METADATA_PKTABLE_SCHEM));
            Table tempPkTable = (Table) new Table().setName(row.getString(METADATA_PKTABLE_NAME)).setSchema(new Schema(pkTableSchema.getCatalogName(), pkTableSchema.getSchemaName()));
            foreignKey.setPrimaryKeyTable(tempPkTable);
            Column pkColumn = new Column(cleanNameFromDatabase(row.getString(METADATA_PKCOLUMN_NAME), database)).setRelation(tempPkTable);
            foreignKey.addForeignKeyColumn(fkColumn);
            foreignKey.addPrimaryKeyColumn(pkColumn);
            // DB2 on z/OS doesn't support ON UPDATE
            if (!(database instanceof Db2zDatabase)) {
                ForeignKeyConstraintType updateRule = convertToForeignKeyConstraintType(row.getInt(METADATA_UPDATE_RULE), database);
                foreignKey.setUpdateRule(updateRule);
            }
            ForeignKeyConstraintType deleteRule = convertToForeignKeyConstraintType(row.getInt(METADATA_DELETE_RULE), database);
            foreignKey.setDeleteRule(deleteRule);
            short deferrability = row.getShort(METADATA_DEFERRABILITY);
            // it should be set to DatabaseMetaData.importedKeyNotDeferrable(7)
            if ((deferrability == 0) || (deferrability == DatabaseMetaData.importedKeyNotDeferrable)) {
                foreignKey.setDeferrable(false);
                foreignKey.setInitiallyDeferred(false);
            } else if (deferrability == DatabaseMetaData.importedKeyInitiallyDeferred) {
                foreignKey.setDeferrable(true);
                foreignKey.setInitiallyDeferred(true);
            } else if (deferrability == DatabaseMetaData.importedKeyInitiallyImmediate) {
                foreignKey.setDeferrable(true);
                foreignKey.setInitiallyDeferred(false);
            } else {
                throw new RuntimeException("Unknown deferrability result: " + deferrability);
            }
            setValidateOptionIfAvailable(database, foreignKey, row);
            Index exampleIndex = new Index().setRelation(foreignKey.getForeignKeyTable());
            exampleIndex.getColumns().addAll(foreignKey.getForeignKeyColumns());
            exampleIndex.addAssociatedWith(Index.MARK_FOREIGN_KEY);
            foreignKey.setBackingIndex(exampleIndex);
        }
        if (snapshot.get(ForeignKey.class).contains(foreignKey)) {
            return null;
        }
        return foreignKey;
    } catch (Exception e) {
        throw new DatabaseException(e);
    }
}
Also used : CachedRow(liquibase.snapshot.CachedRow) CatalogAndSchema(liquibase.CatalogAndSchema) CatalogAndSchema(liquibase.CatalogAndSchema) AbstractJdbcDatabase(liquibase.database.AbstractJdbcDatabase) InvalidExampleException(liquibase.snapshot.InvalidExampleException) DatabaseException(liquibase.exception.DatabaseException) SQLException(java.sql.SQLException) Db2zDatabase(liquibase.database.core.Db2zDatabase) DB2Database(liquibase.database.core.DB2Database) Db2zDatabase(liquibase.database.core.Db2zDatabase) MSSQLDatabase(liquibase.database.core.MSSQLDatabase) OracleDatabase(liquibase.database.core.OracleDatabase) Database(liquibase.database.Database) MariaDBDatabase(liquibase.database.core.MariaDBDatabase) MySQLDatabase(liquibase.database.core.MySQLDatabase) AbstractJdbcDatabase(liquibase.database.AbstractJdbcDatabase) JdbcDatabaseSnapshot(liquibase.snapshot.JdbcDatabaseSnapshot) DatabaseException(liquibase.exception.DatabaseException)

Example 10 with InvalidExampleException

use of liquibase.snapshot.InvalidExampleException in project liquibase by liquibase.

the class ForeignKeySnapshotGenerator method addTo.

// public Boolean has(DatabaseObject example, DatabaseSnapshot snapshot, SnapshotGeneratorChain chain) throws DatabaseException {
// if (example instanceof ForeignKey) {
// Database database = snapshot.getDatabase();
// String searchCatalog = database.getJdbcCatalogName(example.getSchema());
// String searchSchema = database.getJdbcSchemaName(example.getSchema());
// String searchTableName = null;
// if (((ForeignKey) example).getForeignKeyTable() != null) {
// searchTableName = ((ForeignKey) example).getForeignKeyTable().getName();
// }
// String fkName = example.getName();
// 
// ResultSet rs = null;
// try {
// rs = getMetaDataFromCache(database).getForeignKeys(searchCatalog, searchSchema, searchTableName);
// while (rs.next()) {
// if (fkName.equals(rs.getString("FK_NAME"))) {
// return true;
// }
// }
// return false;
// } catch (SQLException e) {
// throw new DatabaseException(e);
// } finally {
// if (rs != null) {
// try {
// rs.close();
// } catch (SQLException ignored) { }
// }
// }
// } else {
// return chain.has(example, snapshot);
// }
// }
@Override
protected void addTo(DatabaseObject foundObject, DatabaseSnapshot snapshot) throws DatabaseException, InvalidExampleException {
    if (!snapshot.getSnapshotControl().shouldInclude(ForeignKey.class)) {
        return;
    }
    if (foundObject instanceof Table) {
        Table table = (Table) foundObject;
        Database database = snapshot.getDatabase();
        Schema schema;
        schema = table.getSchema();
        Set<String> seenFks = new HashSet<>();
        List<CachedRow> importedKeyMetadataResultSet;
        try {
            importedKeyMetadataResultSet = ((JdbcDatabaseSnapshot) snapshot).getMetaDataFromCache().getForeignKeys(((AbstractJdbcDatabase) database).getJdbcCatalogName(schema), ((AbstractJdbcDatabase) database).getJdbcSchemaName(schema), database.correctObjectName(table.getName(), Table.class), null);
            for (CachedRow row : importedKeyMetadataResultSet) {
                ForeignKey fk = new ForeignKey().setName(row.getString("FK_NAME")).setForeignKeyTable(table);
                if (seenFks.add(fk.getName())) {
                    table.getOutgoingForeignKeys().add(fk);
                }
            }
        } catch (Exception e) {
            throw new DatabaseException(e);
        }
    }
}
Also used : CachedRow(liquibase.snapshot.CachedRow) CatalogAndSchema(liquibase.CatalogAndSchema) AbstractJdbcDatabase(liquibase.database.AbstractJdbcDatabase) InvalidExampleException(liquibase.snapshot.InvalidExampleException) DatabaseException(liquibase.exception.DatabaseException) SQLException(java.sql.SQLException) DB2Database(liquibase.database.core.DB2Database) Db2zDatabase(liquibase.database.core.Db2zDatabase) MSSQLDatabase(liquibase.database.core.MSSQLDatabase) OracleDatabase(liquibase.database.core.OracleDatabase) Database(liquibase.database.Database) MariaDBDatabase(liquibase.database.core.MariaDBDatabase) MySQLDatabase(liquibase.database.core.MySQLDatabase) AbstractJdbcDatabase(liquibase.database.AbstractJdbcDatabase) JdbcDatabaseSnapshot(liquibase.snapshot.JdbcDatabaseSnapshot) DatabaseException(liquibase.exception.DatabaseException) HashSet(java.util.HashSet)

Aggregations

InvalidExampleException (liquibase.snapshot.InvalidExampleException)16 DatabaseException (liquibase.exception.DatabaseException)9 UnexpectedLiquibaseException (liquibase.exception.UnexpectedLiquibaseException)8 CatalogAndSchema (liquibase.CatalogAndSchema)7 Database (liquibase.database.Database)7 AbstractJdbcDatabase (liquibase.database.AbstractJdbcDatabase)5 SnapshotControl (liquibase.snapshot.SnapshotControl)5 Table (liquibase.structure.core.Table)5 SQLException (java.sql.SQLException)4 CachedRow (liquibase.snapshot.CachedRow)4 JdbcDatabaseSnapshot (liquibase.snapshot.JdbcDatabaseSnapshot)4 DatabaseObject (liquibase.structure.DatabaseObject)4 DB2Database (liquibase.database.core.DB2Database)3 MSSQLDatabase (liquibase.database.core.MSSQLDatabase)3 DiffResult (liquibase.diff.DiffResult)3 SqlStatement (liquibase.statement.SqlStatement)3 ArrayList (java.util.ArrayList)2 HashMap (java.util.HashMap)2 Change (liquibase.change.Change)2 Db2zDatabase (liquibase.database.core.Db2zDatabase)2