Liquibase - change on delete type of foreign key for a table

Viewed 6175

Is it possible to change the foreign key on delete method from NO ACTION to SET NULL in liquibase?

1 Answers

Yes, it's possible. There's onDelete attribute in <addForeignKeyConstraint> which you can set to:

  • CASCADE
  • SET NULL
  • SET DEFAULT
  • RESTRICT
  • NO ACTION

If you already have a foreign key, then you can drop existing constraint and recreate it with the settings you need.

<changeSet id="changeset-id" author="changeset-author">
    <preConditions onFail="MARK_RAN">
        <foreignKeyConstraintExists foreignKeyName="fk_foo_bar"/>
    </preConditions>
    <dropForeignKeyConstraint baseTableName="table_foo" constraintName="fk_foo_bar"/>
    <addForeignKeyConstraint baseTableName="table_foo" baseColumnNames="foo_col"
                             constraintName="fk_foo_bar"
                             referencedTableName="table_bar" referencedColumnNames="bar_col"
                             onDelete="SET NULL"/>
</changeSet>
Related