BP-2147 | Hotfix: Added support for Rails 6 multi-database switching #1
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
In testing the Rails 6 final release, seeding the test database was failing due to the the new way connections are handled. It appears with Rails 6 that establishing the DB connection within the connection pool no longer automatically connects at the ActiveRecord::Base level. This adds a manual call to establish the connection when it's just added to the pool.
In addition to fixing the hard fails in Rails 6, this appears to fix migrations in Rails 6. As of 6.0.0.rc1, migrations in tenant databases has been broken. We'll likely need to look at patching any out-of-sync database schemas due to this issue, but that will be a separate ticket if it's needed.
There was an additional issue discovered where long-running transactions with different databases in concurrent threads will almost always result in a deadlock. I believe I've narrowed the Rails change that causes this to the following commit in v6.0.0.rc2: 853f5680e8c79a51f5c0bf1624b1a5d3d3df2802. This merges this PR: rails/rails#36618 which is meant to "Fix query cache when using shared connections."
Here's the diff for that PR:
Specifically, the change in the
active_connection?
method to also use the@lock_threads
from thecurrent_thread
method when present broke it. By changingApartment.connection.clear_query_cache
toApartment.connection_class.clear_query_caches_for_current_thread
we should now be clearing all query caches, including shared ones between threads in the test environment.Additionally, two other PRs were merged into Rails (rails/rails#36870 and rails/rails#36883) that broke the ability to seed the multiple databases with fixture data. It appears the new connection is not automatically established unless the
Apartment.connection_class's @connection_specification_name == nil
. I believe that rails/rails#36870 established a connection now, which sets the instance variable during the schema check. This is now pointing at the wrong database, so we can fix it by setting it on the connection switch.