Search in sources :

Example 11 with InvalidExampleException

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

the class CatalogSnapshotGenerator method snapshotObject.

@Override
protected DatabaseObject snapshotObject(DatabaseObject example, DatabaseSnapshot snapshot) throws DatabaseException, InvalidExampleException {
    if (!(example instanceof Catalog)) {
        throw new UnexpectedLiquibaseException("Unexpected example type: " + example.getClass().getName());
    }
    Database database = snapshot.getDatabase();
    Catalog match = null;
    String catalogName = example.getName();
    if ((catalogName == null) && database.supportsCatalogs()) {
        catalogName = database.getDefaultCatalogName();
    }
    example = new Catalog(catalogName);
    try {
        for (String potentialCatalogName : getDatabaseCatalogNames(database)) {
            Catalog catalog = new Catalog(potentialCatalogName);
            if (DatabaseObjectComparatorFactory.getInstance().isSameObject(catalog, example, snapshot.getSchemaComparisons(), database)) {
                if (match == null) {
                    match = catalog;
                } else {
                    throw new InvalidExampleException("Found multiple catalogs matching " + example.getName());
                }
            }
        }
    } catch (SQLException e) {
        throw new DatabaseException(e);
    }
    if ((match != null) && isDefaultCatalog(match, database)) {
        match.setDefault(true);
    }
    return match;
}
Also used : InvalidExampleException(liquibase.snapshot.InvalidExampleException) SQLException(java.sql.SQLException) Database(liquibase.database.Database) UnexpectedLiquibaseException(liquibase.exception.UnexpectedLiquibaseException) DatabaseException(liquibase.exception.DatabaseException) Catalog(liquibase.structure.core.Catalog)

Example 12 with InvalidExampleException

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

the class SQLiteDatabase method getAlterTableStatements.

public static List<SqlStatement> getAlterTableStatements(AlterTableVisitor alterTableVisitor, Database database, String catalogName, String schemaName, String tableName) throws DatabaseException {
    List<SqlStatement> statements = new ArrayList<>();
    Table table = null;
    try {
        table = SnapshotGeneratorFactory.getInstance().createSnapshot((Table) new Table().setName(tableName).setSchema(new Schema(new Catalog(null), null)), database);
        List<ColumnConfig> createColumns = new ArrayList<>();
        List<ColumnConfig> copyColumns = new ArrayList<>();
        if (table != null) {
            for (Column column : table.getColumns()) {
                ColumnConfig new_column = new ColumnConfig(column);
                if (alterTableVisitor.createThisColumn(new_column)) {
                    createColumns.add(new_column);
                }
                ColumnConfig copy_column = new ColumnConfig(column);
                if (alterTableVisitor.copyThisColumn(copy_column)) {
                    copyColumns.add(copy_column);
                }
            }
        }
        for (ColumnConfig column : alterTableVisitor.getColumnsToAdd()) {
            if (alterTableVisitor.createThisColumn(column)) {
                createColumns.add(column);
            }
            if (alterTableVisitor.copyThisColumn(column)) {
                copyColumns.add(column);
            }
        }
        List<Index> newIndices = new ArrayList<>();
        for (Index index : SnapshotGeneratorFactory.getInstance().createSnapshot(new CatalogAndSchema(catalogName, schemaName), database, new SnapshotControl(database, Index.class)).get(Index.class)) {
            if (index.getRelation().getName().equalsIgnoreCase(tableName)) {
                if (alterTableVisitor.createThisIndex(index)) {
                    newIndices.add(index);
                }
            }
        }
        // rename table
        String temp_table_name = tableName + "_temporary";
        statements.addAll(Arrays.asList(new RenameTableStatement(catalogName, schemaName, tableName, temp_table_name)));
        // create temporary table
        CreateTableChange ct_change_tmp = new CreateTableChange();
        ct_change_tmp.setSchemaName(schemaName);
        ct_change_tmp.setTableName(tableName);
        for (ColumnConfig column : createColumns) {
            ct_change_tmp.addColumn(column);
        }
        statements.addAll(Arrays.asList(ct_change_tmp.generateStatements(database)));
        // copy rows to temporary table
        statements.addAll(Arrays.asList(new CopyRowsStatement(temp_table_name, tableName, copyColumns)));
        // delete original table
        statements.addAll(Arrays.asList(new DropTableStatement(catalogName, schemaName, temp_table_name, false)));
        // validate indices
        statements.addAll(Arrays.asList(new ReindexStatement(catalogName, schemaName, tableName)));
        // add remaining indices
        for (Index index_config : newIndices) {
            AddColumnConfig[] columns = new AddColumnConfig[index_config.getColumns().size()];
            for (int i = 0; i < index_config.getColumns().size(); i++) {
                columns[i] = new AddColumnConfig(index_config.getColumns().get(i));
            }
            // We must not create indexes that are auto-generated by SQLite
            if (!index_config.getName().toLowerCase().startsWith("sqlite_autoindex_")) {
                statements.addAll(Arrays.asList(new CreateIndexStatement(index_config.getName(), catalogName, schemaName, tableName, index_config.isUnique(), index_config.getAssociatedWithAsString(), columns)));
            }
        }
        return statements;
    } catch (InvalidExampleException e) {
        throw new UnexpectedLiquibaseException(e);
    }
}
Also used : ColumnConfig(liquibase.change.ColumnConfig) AddColumnConfig(liquibase.change.AddColumnConfig) CatalogAndSchema(liquibase.CatalogAndSchema) SqlStatement(liquibase.statement.SqlStatement) InvalidExampleException(liquibase.snapshot.InvalidExampleException) SnapshotControl(liquibase.snapshot.SnapshotControl) CatalogAndSchema(liquibase.CatalogAndSchema) CreateTableChange(liquibase.change.core.CreateTableChange) AddColumnConfig(liquibase.change.AddColumnConfig) UnexpectedLiquibaseException(liquibase.exception.UnexpectedLiquibaseException)

Example 13 with InvalidExampleException

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

the class StandardLockService method destroy.

@Override
public void destroy() throws DatabaseException {
    try {
        // 
        // This code now uses the ChangeGeneratorFactory to
        // allow extension code to be called in order to
        // delete the changelog lock table.
        // 
        // To implement the extension, you will need to override:
        // DropTableStatement
        // DropTableChange
        // DropTableGenerator
        // 
        // 
        DatabaseObject example = new Table().setName(database.getDatabaseChangeLogLockTableName()).setSchema(database.getLiquibaseCatalogName(), database.getLiquibaseSchemaName());
        if (SnapshotGeneratorFactory.getInstance().has(example, database)) {
            DatabaseObject table = SnapshotGeneratorFactory.getInstance().createSnapshot(example, database);
            DiffOutputControl diffOutputControl = new DiffOutputControl(true, true, false, null);
            Change[] change = ChangeGeneratorFactory.getInstance().fixUnexpected(table, diffOutputControl, database, database);
            SqlStatement[] sqlStatement = change[0].generateStatements(database);
            Scope.getCurrentScope().getSingleton(ExecutorService.class).getExecutor("jdbc", database).execute(sqlStatement[0]);
        }
        reset();
    } catch (InvalidExampleException e) {
        throw new UnexpectedLiquibaseException(e);
    }
}
Also used : SqlStatement(liquibase.statement.SqlStatement) InvalidExampleException(liquibase.snapshot.InvalidExampleException) Table(liquibase.structure.core.Table) DatabaseObject(liquibase.structure.DatabaseObject) DiffOutputControl(liquibase.diff.output.DiffOutputControl) Change(liquibase.change.Change) UnexpectedLiquibaseException(liquibase.exception.UnexpectedLiquibaseException)

Example 14 with InvalidExampleException

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

the class StandardChangeLogHistoryService method destroy.

@Override
public void destroy() throws DatabaseException {
    Database database = getDatabase();
    try {
        // 
        // This code now uses the ChangeGeneratorFactory to
        // allow extension code to be called in order to
        // delete the changelog table.
        // 
        // To implement the extension, you will need to override:
        // DropTableStatement
        // DropTableChange
        // DropTableGenerator
        // 
        // 
        DatabaseObject example = new Table().setName(database.getDatabaseChangeLogTableName()).setSchema(database.getLiquibaseCatalogName(), database.getLiquibaseSchemaName());
        if (SnapshotGeneratorFactory.getInstance().has(example, database)) {
            DatabaseObject table = SnapshotGeneratorFactory.getInstance().createSnapshot(example, database);
            DiffOutputControl diffOutputControl = new DiffOutputControl(true, true, false, null);
            Change[] change = ChangeGeneratorFactory.getInstance().fixUnexpected(table, diffOutputControl, database, database);
            SqlStatement[] sqlStatement = change[0].generateStatements(database);
            Scope.getCurrentScope().getSingleton(ExecutorService.class).getExecutor("jdbc", database).execute(sqlStatement[0]);
        }
        reset();
    } catch (InvalidExampleException e) {
        throw new UnexpectedLiquibaseException(e);
    }
}
Also used : SqlStatement(liquibase.statement.SqlStatement) InvalidExampleException(liquibase.snapshot.InvalidExampleException) Table(liquibase.structure.core.Table) SQLiteDatabase(liquibase.database.core.SQLiteDatabase) DB2Database(liquibase.database.core.DB2Database) MSSQLDatabase(liquibase.database.core.MSSQLDatabase) Database(liquibase.database.Database) DatabaseObject(liquibase.structure.DatabaseObject) DiffOutputControl(liquibase.diff.output.DiffOutputControl) Change(liquibase.change.Change) UnexpectedLiquibaseException(liquibase.exception.UnexpectedLiquibaseException)

Example 15 with InvalidExampleException

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

the class LoadDataChange method retrieveMissingColumnLoadTypes.

/**
 * Iterate through the List of LoadDataColumnConfig and ask the database for any column types that we have
 * no data type of.
 *
 * @param columns a list of LoadDataColumnConfigs to process
 */
@SuppressWarnings("CommentedOutCodeLine")
private void retrieveMissingColumnLoadTypes(List<LoadDataColumnConfig> columns, Database database) throws DatabaseException {
    // If no column is missing type information, we are already done.
    if (columns.stream().noneMatch(c -> c.getType() == null)) {
        return;
    }
    // Snapshot the database table
    CatalogAndSchema catalogAndSchema = new CatalogAndSchema(getCatalogName(), getSchemaName());
    catalogAndSchema = catalogAndSchema.standardize(database);
    Table targetTable = new Table(catalogAndSchema.getCatalogName(), catalogAndSchema.getSchemaName(), database.correctObjectName(getTableName(), Table.class));
    Table snapshotOfTable;
    try {
        snapshotOfTable = SnapshotGeneratorFactory.getInstance().createSnapshot(targetTable, database, new SnapshotControl(database, Table.class, Column.class));
    } catch (InvalidExampleException e) {
        throw new DatabaseException(e);
    }
    if (snapshotOfTable == null) {
        LOG.warning(String.format(coreBundle.getString("could.not.snapshot.table.to.get.the.missing.column.type.information"), database.escapeTableName(targetTable.getSchema().getCatalogName(), targetTable.getSchema().getName(), targetTable.getName())));
        return;
    }
    // Save the columns of the database table in a lookup table
    Map<String, Column> tableColumns = new HashMap<>();
    for (Column c : snapshotOfTable.getColumns()) {
        // Normalise the LoadDataColumnConfig column names to the database
        tableColumns.put(database.correctObjectName(c.getName(), Column.class), c);
    }
    /* The above is the JDK7 version of:
            snapshotOfTable.getColumns().forEach(c -> tableColumns.put(c.getName(), c));
        */
    // Normalise the LoadDataColumnConfig column names to the database
    Map<String, LoadDataColumnConfig> columnConfigs = new HashMap<>();
    for (LoadDataColumnConfig c : columns) {
        columnConfigs.put(database.correctObjectName(c.getName(), Column.class), c);
    }
    for (Map.Entry<String, LoadDataColumnConfig> entry : columnConfigs.entrySet()) {
        if (entry.getValue().getType() != null) {
            continue;
        }
        LoadDataColumnConfig columnConfig = entry.getValue();
        Column c = tableColumns.get(entry.getKey());
        if (null == c) {
            LOG.severe(String.format(coreBundle.getString("unable.to.find.column.in.table"), columnConfig.getName(), snapshotOfTable));
        } else {
            DataType dataType = c.getType();
            if (dataType == null) {
                LOG.warning(String.format(coreBundle.getString("unable.to.find.load.data.type"), columnConfig.toString(), snapshotOfTable));
                columnConfig.setType(LOAD_DATA_TYPE.STRING);
            } else {
                LiquibaseDataType liquibaseDataType = DataTypeFactory.getInstance().fromDescription(dataType.toString(), database);
                if (liquibaseDataType != null) {
                    columnConfig.setType(liquibaseDataType.getLoadTypeName());
                } else {
                    LOG.warning(String.format(coreBundle.getString("unable.to.convert.load.data.type"), columnConfig.toString(), snapshotOfTable, dataType));
                }
            }
        }
    }
/* The above is the JDK7 version of:
        columnConfigs.entrySet().stream()
                .filter(entry -> entry.getValue().getType() == null)
                .forEach(entry -> {
                    LoadDataColumnConfig columnConfig = entry.getValue();
                    DataType dataType = tableColumns.get(entry.getKey()).getType();
                    if (dataType == null) {
                        LOG.warning(String.format(coreBundle.getString("unable.to.find.load.data.type"),
                                columnConfig.toString(), snapshotOfTable.toString() ));
                        columnConfig.setType(LOAD_DATA_TYPE.STRING.toString());
                    } else {
                        LiquibaseDataType liquibaseDataType = DataTypeFactory.getInstance()
                                .fromDescription(dataType.toString(), database);
                        if (liquibaseDataType != null) {
                            columnConfig.setType(liquibaseDataType.getLoadTypeName().toString());
                        } else {
                            LOG.warning(String.format(coreBundle.getString("unable.to.convert.load.data.type"),
                                    columnConfig.toString(), snapshotOfTable.toString(), liquibaseDataType.toString()));
                        }
                    }
                }
        );
        */
}
Also used : Table(liquibase.structure.core.Table) LiquibaseDataType(liquibase.datatype.LiquibaseDataType) CatalogAndSchema(liquibase.CatalogAndSchema) InvalidExampleException(liquibase.snapshot.InvalidExampleException) Column(liquibase.structure.core.Column) DataType(liquibase.structure.core.DataType) LiquibaseDataType(liquibase.datatype.LiquibaseDataType) SnapshotControl(liquibase.snapshot.SnapshotControl)

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