Skip to content

Commit dbf0866

Browse files
committed
Fix instrumentation of multiple database connections.
Python requires a function call to create a new scope; lambdas don't create closures! Fix #457.
1 parent 4c8f846 commit dbf0866

File tree

2 files changed

+18
-10
lines changed

2 files changed

+18
-10
lines changed

debug_toolbar/panels/sql/panel.py

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
from debug_toolbar.panels.sql.forms import SQLSelectForm
1212
from debug_toolbar.utils import render_stacktrace
1313
from debug_toolbar.panels.sql.utils import reformat_sql
14-
from debug_toolbar.panels.sql.tracking import CursorWrapper
14+
from debug_toolbar.panels.sql.tracking import wrap_cursor, unwrap_cursor
1515

1616

1717
def get_isolation_level_display(engine, level):
@@ -128,16 +128,11 @@ def title(self):
128128
def enable_instrumentation(self):
129129
# This is thread-safe because database connections are thread-local.
130130
for connection in connections.all():
131-
if not hasattr(connection, '_djdt_cursor'):
132-
connection._djdt_cursor = connection.cursor
133-
connection.cursor = lambda: CursorWrapper(
134-
connection._djdt_cursor(), connection, self)
131+
wrap_cursor(connection, self)
135132

136133
def disable_instrumentation(self):
137134
for connection in connections.all():
138-
if hasattr(connection, '_djdt_cursor'):
139-
del connection._djdt_cursor
140-
del connection.cursor
135+
unwrap_cursor(connection)
141136

142137
def process_response(self, request, response):
143138
if self._queries:

debug_toolbar/panels/sql/tracking.py

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,8 +37,21 @@ def recording(self, v):
3737
recording = state.recording # export function
3838

3939

40-
def CursorWrapper(*args, **kwds): # behave like a class
41-
return state.Wrapper(*args, **kwds)
40+
def wrap_cursor(connection, panel):
41+
if not hasattr(connection, '_djdt_cursor'):
42+
connection._djdt_cursor = connection.cursor
43+
44+
def cursor():
45+
return state.Wrapper(connection._djdt_cursor(), connection, panel)
46+
47+
connection.cursor = cursor
48+
return cursor
49+
50+
51+
def unwrap_cursor(connection):
52+
if hasattr(connection, '_djdt_cursor'):
53+
del connection._djdt_cursor
54+
del connection.cursor
4255

4356

4457
class ExceptionCursorWrapper(object):

0 commit comments

Comments
 (0)