fatkodima/online_migrations

`add_reference_concurrently` does not properly check for existence of foreign keys

Closed this issue · 2 comments

Hi again!

We just ran into trouble when trying to add a new foreign key to an existing table using add_reference_concurrently. We already had a different foreign key pointing to the same target able (using a different column). This caused online_migrations to refuse to add the new foreign key, as it erroneously believes the foreign key already existed. Apparently it does not take the column into consideration when checking if the foreign key already exists.

Something like this therefore does not work:

add_reference_concurrently :foos, :baz, foreign_key: { to_table: :bars }
add_reference_concurrently :foos, :quux, foreign_key: { to_table: :bars }

Thanks for looking into this!

Thanks for the report! I will fix this issue (and the previous you opened) today or tomorrow. I am just waiting for the PR on the rails side to be merged for my CI to get green.

I think I found the cause: https://github.com/fatkodima/online_migrations/blob/master/lib/online_migrations/schema_statements.rb#L781. The column is not passed into the check if add_foreign_key is called from add_reference_concurrently. Rather, the column is then derived here: https://github.com/fatkodima/online_migrations/blob/master/lib/online_migrations/schema_statements.rb#L790.

A possible fix is to add the following line at https://github.com/fatkodima/online_migrations/blob/master/lib/online_migrations/schema_statements.rb#L688:

foreign_key[:column] = column_name