﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
17258	Move threading.local from DatabaseWrapper to connections dictionary	Anssi Kääriäinen	nobody	"It might be a good idea to move the threadlocality of connections from the DatabaseWrapper to the django.db.connections dictionary. This would be useful if you want to do routing of connections on per-view or per-method basis. The use case is when you have a writing view in your application, you might want to route all queries to the master database, not just the writing queries. Now your view will work on a consistent snapshot all the time. This would also allow for much easier generation of separate connections.

Currently, if you go on and change the DEFAULT_DB_ALIAS to point to ""master"" in the connections dictionary, this will result in global routing of the DEFAULT_DB_ALIAS, that is, all threads will see the master connection in the DEFAULT_DB_ALIAS, not just your thread. In other words, this is not doable currently.

I would like to work on an external project ""db_helpers"", which would provide a function wrapper for this. After this change, you could do this:

{{{
@route_connections(default=""master"", close_connections=True):
def my_writing_view(...):
    ...

or
@route_connections(default=db_helpers.separate_connection(""master"")):
def log_stuff_in_separate_connection(...):
    ...
}}}

And the implementation of route_connections would be:

{{{
def route_connections(f):
    # first handle special kwargs, like _close_connections
    old_connections = {}
    try:
        for k, v in kwargs:
            old_connections[k] = connections[k]
            connections[k] = connections[v] # or new connection...
        # call the wrapped method
    finally:
        for k in old_connections.keys():
            connections[k] = old_connections[k]
}}}

Is the change of threading.local from DatabaseWrapper to the connections dictionary something that has a chance to get included in Django? I think this could be a pretty simple thing to do (if you can call anything involving threads simple). Of course, I am willing to do the investigation & the patch if there is a chance for this."	New feature	closed	Database layer (models, ORM)	dev	Normal	fixed		anssi.kaariainen@…	Ready for checkin	1	0	0	0	0	0
