Search in sources :

Example 6 with AddColumnConfig

use of liquibase.change.AddColumnConfig 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<SqlStatement>();
    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<ColumnConfig>();
        List<ColumnConfig> copyColumns = new ArrayList<ColumnConfig>();
        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<Index>();
        for (Index index : SnapshotGeneratorFactory.getInstance().createSnapshot(new CatalogAndSchema(catalogName, schemaName), database, new SnapshotControl(database, Index.class)).get(Index.class)) {
            if (index.getTable().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));
            }
            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 7 with AddColumnConfig

use of liquibase.change.AddColumnConfig in project liquibase by liquibase.

the class XMLChangeLogSerializerTest method createNode_CreateIndexChange.

@Test
public void createNode_CreateIndexChange() throws Exception {
    CreateIndexChange refactoring = new CreateIndexChange();
    refactoring.setIndexName("IDX_TEST");
    refactoring.setTableName("TAB_NAME");
    AddColumnConfig column1 = new AddColumnConfig();
    column1.setName("COL1");
    refactoring.addColumn(column1);
    AddColumnConfig column2 = new AddColumnConfig();
    column2.setName("COL2");
    column2.setDescending(true);
    refactoring.addColumn(column2);
    Element element = new XMLChangeLogSerializer(DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument()).createNode(refactoring);
    assertEquals("createIndex", element.getTagName());
    assertEquals("IDX_TEST", element.getAttribute("indexName"));
    assertEquals("TAB_NAME", element.getAttribute("tableName"));
    assertEquals(2, element.getChildNodes().getLength());
    assertEquals("column", ((Element) element.getChildNodes().item(0)).getTagName());
    assertEquals("COL1", ((Element) element.getChildNodes().item(0)).getAttribute("name"));
    assertEquals("column", ((Element) element.getChildNodes().item(1)).getTagName());
    assertEquals("COL2", ((Element) element.getChildNodes().item(1)).getAttribute("name"));
    assertEquals("true", ((Element) element.getChildNodes().item(1)).getAttribute("descending"));
}
Also used : Element(org.w3c.dom.Element) AddColumnConfig(liquibase.change.AddColumnConfig) Test(org.junit.Test)

Example 8 with AddColumnConfig

use of liquibase.change.AddColumnConfig in project liquibase by liquibase.

the class MissingColumnChangeGenerator method fixMissing.

@Override
public Change[] fixMissing(DatabaseObject missingObject, DiffOutputControl control, Database referenceDatabase, Database comparisonDatabase, ChangeGeneratorChain chain) {
    Column column = (Column) missingObject;
    if (column.getRelation() instanceof View) {
        return null;
    }
    if (column.getRelation().getSnapshotId() == null) {
        //not an actual table, maybe an alias, maybe in a different schema. Don't fix it.
        return null;
    }
    AddColumnChange change = createAddColumnChange();
    change.setTableName(column.getRelation().getName());
    if (control.getIncludeCatalog()) {
        change.setCatalogName(column.getRelation().getSchema().getCatalogName());
    }
    if (control.getIncludeSchema()) {
        change.setSchemaName(column.getRelation().getSchema().getName());
    }
    AddColumnConfig columnConfig = createAddColumnConfig();
    columnConfig.setName(column.getName());
    String dataType = column.getType().toString();
    columnConfig.setType(dataType);
    MissingTableChangeGenerator.setDefaultValue(columnConfig, column, comparisonDatabase);
    if (column.getRemarks() != null) {
        columnConfig.setRemarks(column.getRemarks());
    }
    ConstraintsConfig constraintsConfig = columnConfig.getConstraints();
    if (column.isNullable() != null && !column.isNullable()) {
        if (constraintsConfig == null) {
            constraintsConfig = new ConstraintsConfig();
        }
        constraintsConfig.setNullable(false);
    }
    if (constraintsConfig != null) {
        columnConfig.setConstraints(constraintsConfig);
    }
    change.addColumn(columnConfig);
    return new Change[] { change };
}
Also used : ConstraintsConfig(liquibase.change.ConstraintsConfig) AddColumnConfig(liquibase.change.AddColumnConfig) Change(liquibase.change.Change) AddColumnChange(liquibase.change.core.AddColumnChange) AddColumnChange(liquibase.change.core.AddColumnChange)

Example 9 with AddColumnConfig

use of liquibase.change.AddColumnConfig in project liquibase by liquibase.

the class ChangedColumnChangeGenerator method handleTypeDifferences.

protected void handleTypeDifferences(Column column, ObjectDifferences differences, DiffOutputControl control, List<Change> changes, Database referenceDatabase, Database comparisonDatabase) {
    Difference typeDifference = differences.getDifference("type");
    if (typeDifference != null) {
        String catalogName = null;
        String schemaName = null;
        if (control.getIncludeCatalog()) {
            catalogName = column.getRelation().getSchema().getCatalog().getName();
        }
        if (control.getIncludeSchema()) {
            schemaName = column.getRelation().getSchema().getName();
        }
        String tableName = column.getRelation().getName();
        if (comparisonDatabase instanceof OracleDatabase && (((DataType) typeDifference.getReferenceValue()).getTypeName().equalsIgnoreCase("clob") || ((DataType) typeDifference.getComparedValue()).getTypeName().equalsIgnoreCase("clob"))) {
            String tempColName = "TEMP_CLOB_CONVERT";
            OutputChange outputChange = new OutputChange();
            outputChange.setMessage("Cannot convert directly from " + ((DataType) typeDifference.getComparedValue()).getTypeName() + " to " + ((DataType) typeDifference.getReferenceValue()).getTypeName() + ". Instead a new column will be created and the data transferred. This may cause unexpected side effects including constraint issues and/or table locks.");
            changes.add(outputChange);
            AddColumnChange addColumn = new AddColumnChange();
            addColumn.setCatalogName(catalogName);
            addColumn.setSchemaName(schemaName);
            addColumn.setTableName(tableName);
            AddColumnConfig addColumnConfig = new AddColumnConfig(column);
            addColumnConfig.setName(tempColName);
            addColumnConfig.setType(typeDifference.getReferenceValue().toString());
            addColumnConfig.setAfterColumn(column.getName());
            addColumn.setColumns(Arrays.asList(addColumnConfig));
            changes.add(addColumn);
            changes.add(new RawSQLChange("UPDATE " + referenceDatabase.escapeObjectName(tableName, Table.class) + " SET " + tempColName + "=" + referenceDatabase.escapeObjectName(column.getName(), Column.class)));
            DropColumnChange dropColumnChange = new DropColumnChange();
            dropColumnChange.setCatalogName(catalogName);
            dropColumnChange.setSchemaName(schemaName);
            dropColumnChange.setTableName(tableName);
            dropColumnChange.setColumnName(column.getName());
            changes.add(dropColumnChange);
            RenameColumnChange renameColumnChange = new RenameColumnChange();
            renameColumnChange.setCatalogName(catalogName);
            renameColumnChange.setSchemaName(schemaName);
            renameColumnChange.setTableName(tableName);
            renameColumnChange.setOldColumnName(tempColName);
            renameColumnChange.setNewColumnName(column.getName());
            changes.add(renameColumnChange);
        } else {
            ModifyDataTypeChange change = new ModifyDataTypeChange();
            change.setCatalogName(catalogName);
            change.setSchemaName(schemaName);
            change.setTableName(tableName);
            change.setColumnName(column.getName());
            DataType referenceType = (DataType) typeDifference.getReferenceValue();
            change.setNewDataType(DataTypeFactory.getInstance().from(referenceType, comparisonDatabase).toString());
            changes.add(change);
        }
    }
}
Also used : Difference(liquibase.diff.Difference) OracleDatabase(liquibase.database.core.OracleDatabase) LiquibaseDataType(liquibase.datatype.LiquibaseDataType) AddColumnConfig(liquibase.change.AddColumnConfig)

Example 10 with AddColumnConfig

use of liquibase.change.AddColumnConfig in project liquibase by liquibase.

the class ChangedIndexChangeGenerator method fixChanged.

@Override
public Change[] fixChanged(DatabaseObject changedObject, ObjectDifferences differences, DiffOutputControl control, Database referenceDatabase, Database comparisonDatabase, ChangeGeneratorChain chain) {
    //don't try to recreate indexes that differ in just clustered
    Difference clusteredDiff = differences.getDifference("clustered");
    if (clusteredDiff != null) {
        if (clusteredDiff.getReferenceValue() == null || clusteredDiff.getComparedValue() == null) {
            differences.removeDifference("clustered");
        }
    }
    for (String field : getIgnoredFields()) {
        differences.removeDifference(field);
    }
    if (!differences.hasDifferences()) {
        return new Change[0];
    }
    Index index = (Index) changedObject;
    if (index.getTable() != null) {
        if (index.getTable().getPrimaryKey() != null && DatabaseObjectComparatorFactory.getInstance().isSameObject(index.getTable().getPrimaryKey().getBackingIndex(), changedObject, differences.getSchemaComparisons(), comparisonDatabase)) {
            return ChangeGeneratorFactory.getInstance().fixChanged(index.getTable().getPrimaryKey(), differences, control, referenceDatabase, comparisonDatabase);
        }
        List<UniqueConstraint> uniqueConstraints = index.getTable().getUniqueConstraints();
        if (uniqueConstraints != null) {
            for (UniqueConstraint constraint : uniqueConstraints) {
                if (constraint.getBackingIndex() != null && DatabaseObjectComparatorFactory.getInstance().isSameObject(constraint.getBackingIndex(), changedObject, differences.getSchemaComparisons(), comparisonDatabase)) {
                    return ChangeGeneratorFactory.getInstance().fixChanged(constraint, differences, control, referenceDatabase, comparisonDatabase);
                }
            }
        }
    }
    DropIndexChange dropIndexChange = createDropIndexChange();
    dropIndexChange.setTableName(index.getTable().getName());
    dropIndexChange.setIndexName(index.getName());
    CreateIndexChange addIndexChange = createCreateIndexChange();
    addIndexChange.setTableName(index.getTable().getName());
    List<AddColumnConfig> columns = new ArrayList<AddColumnConfig>();
    for (Column col : index.getColumns()) {
        columns.add(new AddColumnConfig(col));
    }
    addIndexChange.setColumns(columns);
    addIndexChange.setIndexName(index.getName());
    addIndexChange.setUnique(index.isUnique());
    if (control.getIncludeCatalog()) {
        dropIndexChange.setCatalogName(index.getSchema().getCatalogName());
        addIndexChange.setCatalogName(index.getSchema().getCatalogName());
    }
    if (control.getIncludeSchema()) {
        dropIndexChange.setSchemaName(index.getSchema().getName());
        addIndexChange.setSchemaName(index.getSchema().getName());
    }
    Difference columnsDifference = differences.getDifference("columns");
    if (columnsDifference != null) {
        List<Column> referenceColumns = (List<Column>) columnsDifference.getReferenceValue();
        List<Column> comparedColumns = (List<Column>) columnsDifference.getComparedValue();
        StringUtils.StringUtilsFormatter<Column> formatter = new StringUtils.StringUtilsFormatter<Column>() {

            @Override
            public String toString(Column obj) {
                return obj.toString(false);
            }
        };
        control.setAlreadyHandledChanged(new Index().setTable(index.getTable()).setColumns(referenceColumns));
        if (!StringUtils.join(referenceColumns, ",", formatter).equalsIgnoreCase(StringUtils.join(comparedColumns, ",", formatter))) {
            control.setAlreadyHandledChanged(new Index().setTable(index.getTable()).setColumns(comparedColumns));
        }
        if (index.isUnique() != null && index.isUnique()) {
            control.setAlreadyHandledChanged(new UniqueConstraint().setTable(index.getTable()).setColumns(referenceColumns));
            if (!StringUtils.join(referenceColumns, ",", formatter).equalsIgnoreCase(StringUtils.join(comparedColumns, ",", formatter))) {
                control.setAlreadyHandledChanged(new UniqueConstraint().setTable(index.getTable()).setColumns(comparedColumns));
            }
        }
    }
    return new Change[] { dropIndexChange, addIndexChange };
}
Also used : DropIndexChange(liquibase.change.core.DropIndexChange) ArrayList(java.util.ArrayList) UniqueConstraint(liquibase.structure.core.UniqueConstraint) Index(liquibase.structure.core.Index) Difference(liquibase.diff.Difference) DropIndexChange(liquibase.change.core.DropIndexChange) Change(liquibase.change.Change) CreateIndexChange(liquibase.change.core.CreateIndexChange) Column(liquibase.structure.core.Column) StringUtils(liquibase.util.StringUtils) AddColumnConfig(liquibase.change.AddColumnConfig) ArrayList(java.util.ArrayList) List(java.util.List) CreateIndexChange(liquibase.change.core.CreateIndexChange)

Aggregations

AddColumnConfig (liquibase.change.AddColumnConfig)11 Test (org.junit.Test)4 Change (liquibase.change.Change)3 AddColumnChange (liquibase.change.core.AddColumnChange)3 CreateIndexChange (liquibase.change.core.CreateIndexChange)2 MSSQLDatabase (liquibase.database.core.MSSQLDatabase)2 Difference (liquibase.diff.Difference)2 Sql (liquibase.sql.Sql)2 UnparsedSql (liquibase.sql.UnparsedSql)2 SqlStatement (liquibase.statement.SqlStatement)2 Column (liquibase.structure.core.Column)2 Index (liquibase.structure.core.Index)2 Element (org.w3c.dom.Element)2 ArrayList (java.util.ArrayList)1 Date (java.util.Date)1 List (java.util.List)1 CatalogAndSchema (liquibase.CatalogAndSchema)1 ColumnConfig (liquibase.change.ColumnConfig)1 ConstraintsConfig (liquibase.change.ConstraintsConfig)1 CreateTableChange (liquibase.change.core.CreateTableChange)1