Allow 'Database Router' to override default `connection`

Yeah, that wouldn’t be that helpful xD

It would just change the current proxy to fetch a different connection when getting a cursor. As it stands, connection is defined as a ConnectionProxy initialized with alias="default":

class ConnectionProxy:
    """Proxy for accessing a connection object's attributes."""

    def __init__(self, connections, alias):
        self.__dict__['_connections'] = connections
        self.__dict__['_alias'] = alias

    def __getattr__(self, item):
        return getattr(self._connections[self._alias], item)

    ...  # Other wrapper stuff that uses 'self._connections[self._alias]'

The only change that would need to be made is to fetch alias from a ContextVar, and modify that ContextVar when the context manager is called. ContextVars are async-safe, so no issue there.

Worst that can happen is that some piece of code accesses the connection directly with connections["default"], or that stores a reference to the cursor for a long time. Still all that would happen is that it would use the default DB instead of the overwritten one, so that’s not going to break anything.

It also wouldn’t impact users not using the feature at all.

We do! :flushed: (the codebase in question is for my company, so I’m not the only dev)

We also use a lot of Postgres specific stuff, and have done some DB magic in the past to handle zero-downtime model migrations in deploys with multiple servers.

And damn. I get that some of this stuff is niche, but I really though more people managed their isolation levels properly… probably tons of bugs waiting to be discovered :smile: