Skip to content

Handle (or at least error out) on migrations with ForeignKeys #182

@fmichaut-diff

Description

@fmichaut-diff

If we use LHM on a table with a foreign key pointing to it, LHM will currently not touch the foreign key and this will result in the foreign key pointing to the old renamed table after the LHM migration finishes.
When new records are now inserted in the new table, they won't appear in the old one and the foreign key will raise errors.

This means that running LHM on a table with a foreign key attached to it will 100% of the time run into errors after the migration is complete.

There is 2 ways to approach the issue :

  • A simple, short term fix for it would be for LHM to raise an error if a foreign key is detected on the table (POC was implemented on the original soundcloud repo : https://github.com/soundcloud/lhm/pull/147/changes?w=1)
    • This makes the issue apparent before the migration, allowing it to be handled before it causes problems.
  • A little more complex, but better long term solution would be automated handling of the foreign keys. The foreign key needs to be removed from the original table and moved to the migrated one.
    • We currently do this at my company, by prefixing all our LHM migrations with remove_foreign_key :table_a, :table_b, and then lhm.ddl("alter table %s add constraint fk_rails_XXXX foreign key(column_name) REFERENCES table_b(column_name_2)" % lhm.name) as the last LHM instruction.
    • This does work, but is error prone cause if we forget we will get a nasty error and records will fail being inserted, causing big issues. It is also a bit of an obscure syntax

We would love to see this being improved, even with just the simple fix for now while waiting for the more permanent solution.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions