I am a seasoned developer with over 9 years of experience in Ruby on Rails and Golang. My passion lies in tackling complex data structures and algorithm problems, always pushing myself to learn and grow. In my downtime, I find solace in the pages of books and the soothing sounds of a guitar. But I'm not just a one-trick pony! I love to stay active and challenge myself in other ways too. Whether it's on the football pitch, cricket field, table tennis table, or badminton court, I'm always up for some fun activities.
2 minute read
Rails 6.1 adds the ability to
switch a role or shard for an application with multiple databases.
This means it is possible to switch connections for one database instead of
all databases globally.
To use this feature, we need to set the below config in our application.
Let’s say we have two databases, primary and vehicles.
And we have shards and replica configured for each of them in database.yml as below:
We have two models User and Car. User is stored in the primary database and
Car in the vehicles database.
The corresponding model and abstract classes will look as below:
When legacy_connection_handling is set to false, any abstract connection class will
be able to switch connections without affecting other connections.
Before
In both the above VehiclesRecord.connected_to and ApplicationRecord.connected_to
blocks the connection was changed to shard_one of the corresponding database.
After
As seen above, when we connect VehiclesRecord to shard_one only Car queries
are executed on shard_one whereas User queries are executed on primary
database.
Summary
The addition of this granular switching is useful in cases like:
Suppose replica or shard_one is not configured for primary
database. A connection is made to shard_one and User queries are executed
under the shard_one block, then an error would be thrown. This is because the
connection was changed globally across all databases.
If two shards shard_one and shard_two are configured for both databases,
user_a exists on shard_one and user_b on shard_two. If VehiclesRecord
connection is changed to shard_two and we query for user_a under that block
it will return incorrect result.