Search in sources :

Example 6 with ConstraintsConfig

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

the class MissingTableChangeGenerator method fixMissing.

@Override
public Change[] fixMissing(DatabaseObject missingObject, DiffOutputControl control, Database referenceDatabase, Database comparisonDatabase, ChangeGeneratorChain chain) {
    Table missingTable = (Table) missingObject;
    PrimaryKey primaryKey = missingTable.getPrimaryKey();
    List<String> pkColumnList = ((primaryKey != null) ? primaryKey.getColumnNamesAsList() : null);
    Map<Column, UniqueConstraint> singleUniqueConstraints = getSingleColumnUniqueConstraints(missingTable);
    CreateTableChange change = createCreateTableChange();
    change.setTableName(missingTable.getName());
    if (control.getIncludeCatalog()) {
        change.setCatalogName(missingTable.getSchema().getCatalogName());
    }
    if (control.getIncludeSchema()) {
        change.setSchemaName(missingTable.getSchema().getName());
    }
    if (missingTable.getRemarks() != null) {
        change.setRemarks(missingTable.getRemarks());
    }
    if (control.getIncludeTablespace() && (missingTable.getTablespace() != null) && comparisonDatabase.supportsTablespaces()) {
        change.setTablespace(missingTable.getTablespace());
    }
    for (Column column : missingTable.getColumns()) {
        ColumnConfig columnConfig = new ColumnConfig();
        columnConfig.setName(column.getName());
        LiquibaseDataType ldt = DataTypeFactory.getInstance().from(column.getType(), referenceDatabase);
        DatabaseDataType ddt = ldt.toDatabaseDataType(comparisonDatabase);
        String typeString = ddt.toString();
        if (comparisonDatabase instanceof MSSQLDatabase) {
            typeString = comparisonDatabase.unescapeDataTypeString(typeString);
        }
        columnConfig.setType(typeString);
        if (column.isAutoIncrement()) {
            columnConfig.setAutoIncrement(true);
        }
        boolean primaryKeyOrderMatchesTableOrder = checkPrimaryKeyOrderMatchesTableOrder(missingTable, pkColumnList);
        ConstraintsConfig constraintsConfig = null;
        // In MySQL, the primary key must be specified at creation for an autoincrement column
        if ((pkColumnList != null) && primaryKeyOrderMatchesTableOrder && pkColumnList.contains(column.getName())) {
            if ((referenceDatabase instanceof MSSQLDatabase) && (primaryKey.getBackingIndex() != null) && (primaryKey.getBackingIndex().getClustered() != null) && !primaryKey.getBackingIndex().getClustered()) {
            // have to handle PK as a separate statement
            } else if ((referenceDatabase instanceof PostgresDatabase) && (primaryKey.getBackingIndex() != null) && (primaryKey.getBackingIndex().getClustered() != null) && primaryKey.getBackingIndex().getClustered()) {
            // have to handle PK as a separate statement
            } else {
                constraintsConfig = new ConstraintsConfig();
                if (shouldAddPrimarykeyToConstraints(missingObject, control, referenceDatabase, comparisonDatabase)) {
                    constraintsConfig.setPrimaryKey(true);
                    constraintsConfig.setPrimaryKeyTablespace(primaryKey.getTablespace());
                    // MySQL sets some primary key names as PRIMARY which is invalid
                    if ((comparisonDatabase instanceof MySQLDatabase) && "PRIMARY".equals(primaryKey.getName())) {
                        constraintsConfig.setPrimaryKeyName(null);
                    } else {
                        constraintsConfig.setPrimaryKeyName(primaryKey.getName());
                    }
                    control.setAlreadyHandledMissing(primaryKey);
                    control.setAlreadyHandledMissing(primaryKey.getBackingIndex());
                } else {
                    constraintsConfig.setNullable(false);
                }
            }
        }
        if ((column.isNullable() != null) && !column.isNullable()) {
            if (constraintsConfig == null) {
                constraintsConfig = new ConstraintsConfig();
            }
            constraintsConfig.setNullable(false);
            if (!column.getValidateNullable()) {
                constraintsConfig.setValidateNullable(false);
            }
            constraintsConfig.setNotNullConstraintName(column.getAttribute("notNullConstraintName", String.class));
        }
        if (referenceDatabase instanceof MySQLDatabase) {
            UniqueConstraint uniqueConstraint = singleUniqueConstraints.get(column);
            if (uniqueConstraint != null) {
                if (!control.alreadyHandledMissing(uniqueConstraint, referenceDatabase)) {
                    if (constraintsConfig == null) {
                        constraintsConfig = new ConstraintsConfig();
                    }
                    constraintsConfig.setUnique(true);
                    control.setAlreadyHandledMissing(uniqueConstraint);
                    control.setAlreadyHandledMissing(uniqueConstraint.getBackingIndex());
                }
            }
        }
        if (constraintsConfig != null) {
            columnConfig.setConstraints(constraintsConfig);
        }
        setDefaultValue(columnConfig, column, referenceDatabase);
        if (column.getRemarks() != null) {
            columnConfig.setRemarks(column.getRemarks());
        }
        Column.AutoIncrementInformation autoIncrementInfo = column.getAutoIncrementInformation();
        if (autoIncrementInfo != null) {
            BigInteger startWith = autoIncrementInfo.getStartWith();
            BigInteger incrementBy = autoIncrementInfo.getIncrementBy();
            String generationType = autoIncrementInfo.getGenerationType();
            Boolean defaultOnNull = autoIncrementInfo.getDefaultOnNull();
            if ((startWith != null) && !startWith.equals(BigInteger.ONE)) {
                columnConfig.setStartWith(startWith);
            }
            if ((incrementBy != null) && !incrementBy.equals(BigInteger.ONE)) {
                columnConfig.setIncrementBy(incrementBy);
            }
            if (StringUtil.isNotEmpty(generationType)) {
                columnConfig.setGenerationType(generationType);
                if (defaultOnNull != null) {
                    columnConfig.setDefaultOnNull(defaultOnNull);
                }
            }
        }
        // 
        if (column.getComputed() != null) {
            columnConfig.setComputed(column.getComputed());
        }
        change.addColumn(columnConfig);
        control.setAlreadyHandledMissing(column);
    }
    return new Change[] { change };
}
Also used : Table(liquibase.structure.core.Table) ColumnConfig(liquibase.change.ColumnConfig) LiquibaseDataType(liquibase.datatype.LiquibaseDataType) PrimaryKey(liquibase.structure.core.PrimaryKey) UniqueConstraint(liquibase.structure.core.UniqueConstraint) MySQLDatabase(liquibase.database.core.MySQLDatabase) Change(liquibase.change.Change) CreateTableChange(liquibase.change.core.CreateTableChange) PostgresDatabase(liquibase.database.core.PostgresDatabase) DatabaseDataType(liquibase.datatype.DatabaseDataType) Column(liquibase.structure.core.Column) CreateTableChange(liquibase.change.core.CreateTableChange) ConstraintsConfig(liquibase.change.ConstraintsConfig) BigInteger(java.math.BigInteger) MSSQLDatabase(liquibase.database.core.MSSQLDatabase)

Example 7 with ConstraintsConfig

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

the class AddAutoIncrementGeneratorSQLite method setPrimaryKeyAndAutoIncrement.

private void setPrimaryKeyAndAutoIncrement(ColumnConfig column, AddAutoIncrementStatement statement) {
    if (column.getName().equals(statement.getColumnName())) {
        column.setAutoIncrement(true);
        ConstraintsConfig constraints = column.getConstraints();
        if (constraints == null) {
            constraints = new ConstraintsConfig();
            column.setConstraints(constraints);
        }
        constraints.setPrimaryKey(true);
    }
}
Also used : ConstraintsConfig(liquibase.change.ConstraintsConfig)

Example 8 with ConstraintsConfig

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

the class AddColumnGeneratorTest method testAddColumnWithNotNullConstraintAndValue.

@Test
public void testAddColumnWithNotNullConstraintAndValue() {
    AddColumnChange change = new AddColumnChange();
    change.setTableName(TABLE_NAME);
    AddColumnConfig column = new AddColumnConfig();
    column.setName("column1");
    column.setType("int8");
    column.setValueNumeric("0");
    column.setConstraints(new ConstraintsConfig().setNullable(false));
    change.addColumn(column);
    AddColumnConfig column2 = new AddColumnConfig();
    column2.setName("column2");
    column2.setType("boolean");
    column2.setValueBoolean("true");
    column2.setConstraints(new ConstraintsConfig().setNullable(false));
    change.addColumn(column2);
    SqlStatement[] statements = change.generateStatements(new MySQLDatabase());
    SqlGeneratorFactory instance = SqlGeneratorFactory.getInstance();
    Sql[] sql = instance.generateSql(statements, new MySQLDatabase());
    assertEquals(5, sql.length);
    assertEquals("ALTER TABLE table_name ADD column1 BIGINT NULL, ADD column2 BIT(1) NULL", sql[0].toSql());
    assertEquals("UPDATE table_name SET column1 = 0", sql[1].toSql());
    assertEquals("UPDATE table_name SET column2 = 1", sql[2].toSql());
    assertEquals("ALTER TABLE table_name MODIFY column1 BIGINT NOT NULL", sql[3].toSql());
    assertEquals("ALTER TABLE table_name MODIFY column2 BIT(1) NOT NULL", sql[4].toSql());
}
Also used : SqlStatement(liquibase.statement.SqlStatement) SqlGeneratorFactory(liquibase.sqlgenerator.SqlGeneratorFactory) ConstraintsConfig(liquibase.change.ConstraintsConfig) AddColumnConfig(liquibase.change.AddColumnConfig) AddColumnChange(liquibase.change.core.AddColumnChange) Sql(liquibase.sql.Sql) Test(org.junit.Test) AbstractSqlGeneratorTest(liquibase.sqlgenerator.AbstractSqlGeneratorTest)

Example 9 with ConstraintsConfig

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

the class XMLChangeLogSerializerTest method createNode_ColumnConfig.

@Test
public void createNode_ColumnConfig() throws Exception {
    ColumnConfig column = new ColumnConfig();
    column.setName("id");
    column.setType("varchar(255)");
    column.setDefaultValue("test Value");
    column.setValue("some value here");
    ConstraintsConfig constraints = new ConstraintsConfig();
    constraints.setDeferrable(Boolean.TRUE);
    constraints.setValidateNullable(Boolean.TRUE);
    constraints.setValidateUnique(Boolean.TRUE);
    constraints.setValidatePrimaryKey(Boolean.TRUE);
    constraints.setValidateForeignKey(Boolean.TRUE);
    constraints.setDeleteCascade(true);
    constraints.setForeignKeyName("FK_NAME");
    constraints.setInitiallyDeferred(true);
    constraints.setNullable(false);
    constraints.setPrimaryKey(true);
    constraints.setReferences("state(id)");
    constraints.setUnique(true);
    column.setConstraints(constraints);
    Element element = new XMLChangeLogSerializer(DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument()).createNode(column);
    assertEquals("column", element.getTagName());
    assertEquals("id", element.getAttribute("name"));
    assertEquals("varchar(255)", element.getAttribute("type"));
    assertEquals("test Value", element.getAttribute("defaultValue"));
    assertEquals("some value here", element.getAttribute("value"));
    Element constraintsElement = (Element) element.getChildNodes().item(0);
    assertEquals(12, constraintsElement.getAttributes().getLength());
    assertEquals("true", constraintsElement.getAttribute("deferrable"));
    assertEquals("true", constraintsElement.getAttribute("validateNullable"));
    assertEquals("true", constraintsElement.getAttribute("validateUnique"));
    assertEquals("true", constraintsElement.getAttribute("validatePrimaryKey"));
    assertEquals("true", constraintsElement.getAttribute("validateForeignKey"));
    assertEquals("true", constraintsElement.getAttribute("deleteCascade"));
    assertEquals("FK_NAME", constraintsElement.getAttribute("foreignKeyName"));
    assertEquals("true", constraintsElement.getAttribute("initiallyDeferred"));
    assertEquals("false", constraintsElement.getAttribute("nullable"));
    assertEquals("true", constraintsElement.getAttribute("primaryKey"));
    assertEquals("state(id)", constraintsElement.getAttribute("references"));
    assertEquals("true", constraintsElement.getAttribute("unique"));
}
Also used : ColumnConfig(liquibase.change.ColumnConfig) AddColumnConfig(liquibase.change.AddColumnConfig) Element(org.w3c.dom.Element) ConstraintsConfig(liquibase.change.ConstraintsConfig) Test(org.junit.Test)

Aggregations

ConstraintsConfig (liquibase.change.ConstraintsConfig)9 AddColumnConfig (liquibase.change.AddColumnConfig)4 ColumnConfig (liquibase.change.ColumnConfig)4 Column (liquibase.structure.core.Column)3 Test (org.junit.Test)3 Element (org.w3c.dom.Element)3 Change (liquibase.change.Change)2 AddColumnChange (liquibase.change.core.AddColumnChange)2 Sql (liquibase.sql.Sql)2 ColumnConstraint (liquibase.statement.ColumnConstraint)2 BigInteger (java.math.BigInteger)1 ArrayList (java.util.ArrayList)1 CreateTableChange (liquibase.change.core.CreateTableChange)1 MSSQLDatabase (liquibase.database.core.MSSQLDatabase)1 MySQLDatabase (liquibase.database.core.MySQLDatabase)1 PostgresDatabase (liquibase.database.core.PostgresDatabase)1 SQLiteDatabase (liquibase.database.core.SQLiteDatabase)1 DatabaseDataType (liquibase.datatype.DatabaseDataType)1 LiquibaseDataType (liquibase.datatype.LiquibaseDataType)1 LiquibaseSerializable (liquibase.serializer.LiquibaseSerializable)1