foreigner icon indicating copy to clipboard operation
foreigner copied to clipboard

Foreigner compatibility with schema specified

Open klippx opened this issue 10 years ago • 0 comments

This PR solves two problems which are highly relevant if you are either using explicit schema names in add_foreign_key instructions, and/or you are using the Apartment gem.

  1. Incorrect behaviour of using foreign keys in conjunction with schema name (see Example 1)
  2. Unfavorable behaviour when using Apartment gem. When creating a new tenant, Apartment will create a new schema with specified name and load schema.rb. schema.rb as we all know contains add_foreign_key statements, some of which may reference the public (shared) schema (i e public foreign keys). In current version of foreigner this will throw an exception because the FKs already exists!
    • We need to let foreigner skip adding foreign key if:
      • Apartment gem is in use
      • Foreign key instruction wants to add to public (shared) schema
      • Foreign key already exist

We have patched the gem in our production environment and would like to share it with the main repo.

Example 1:

add_foreign_key "public.roles_users", "public.roles", :name => "roles_users_role_id_fk", :dependent => :delete, :column => "role_id"

With foreigner v1.7.4 we will get this sql:

"ALTER TABLE `public`.`roles_users` ADD CONSTRAINT `public.roles_users_public.role_id_fk` FOREIGN KEY (`public.role_id`) REFERENCES `public`.`roles`(id)"

What is expected is this sql:

"ALTER TABLE `public`.`roles_users` ADD CONSTRAINT `public.roles_users_role_id_fk` FOREIGN KEY (`public.role_id`) REFERENCES `public`.`roles`(id)"

klippx avatar Sep 23 '15 08:09 klippx