influitive / apartment

Database multi-tenancy for Rack (and Rails) applications
2.66k stars 464 forks source link

Failing to remove index on migration with index_exists? #643

Closed Velora closed 4 years ago

Velora commented 4 years ago

Steps to reproduce

Schema has an index on the users table, ie: t.index ["name"], name: "index_users_on_name", unique: true

We want to remove this index from all tenants with a migration, ie: remove_index :users, name: :index_users_on_name if index_exists?(:users, name: :index_users_on_name)

Expected behavior

The index is removed from all tenants when we run rails db:migrate

Actual behavior

The index is removed from schema.rb, but the existing tenants are unaffected and still have the index on their schema. This leads me to believe that index_exists? is not checking the current tenant.

We also tried the following, but it had no effect (I'm not sure if this is a correct way to select a tenant inside index_exists?, but the tenent name was printed out during migrations)" remove_index :users, name: :index_users_on_name if index_exists?("#{::Apartment::Tenant.current}.users", name: :index_users_on_name)

ActiveRecord::Base.connection.index_name_exists?('users', 'index_users_on_name') run on a tenant inside rails console returns true, proving that the index does infact still exist on the tenant schema.

System configuration

Velora commented 4 years ago

Found the solution. The gem's migrations we were looking at actually had a mistake where they used index_exists? instead of index_name_exists? which they should have used instead. We corrected this in the migration and it ran fine to remove the index across all tenants without issue.