Hey,
Recently I had to use the Database Router feature, but ended up a bit surprised when I noticed that there is no way to override what DB is used when calling connection.cursor()! I get that the current API’s db_for_read and db_for_write doesn’t make sense for cursors, but adding a separate db_for_cursor or db_for_connection would easily fix the issue (in a backwards compatible way!).
I’m thinking about opening a feature request, but wanted to gather some thoughts before doing so. For reference, my use case is that I implemented a context manager for swapping what DB the Database Router uses (similar to this), so I can write code like this:
with context_db("replica"):
user = User.objects.first()
with connection.cursor() as cursor:
cursor.execute(...)
Afaik there are 2 ‘supported’ ways to ensure this works as expected:
- Update all usages of
connectiontoconnections[db_name] - Create a custom DB engine that does the swap on the egine level
I feel like 1 will make the calling code needlessly complex, since I would need to fetch db_name from something like a ContextVar. 2 would kinda work, and is probably the route I’ll be following for now, but I feel like this kind of change more sense in a ‘Database Router’ than on a ‘Database Engine’ context.
Thoughts?