Skip to content

Commit 1443915

Browse files
committed
Initial version debug schema in django
1 parent 0fa7f5c commit 1443915

File tree

8 files changed

+333
-0
lines changed

8 files changed

+333
-0
lines changed
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
from .schema import DebugSchema
2+
from .types import DjangoDebug
3+
4+
__all__ = ['DebugSchema', 'DjangoDebug']
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
from django.db import connections
2+
3+
from ....core.schema import Schema
4+
from ....core.types import Field
5+
from .sql.tracking import unwrap_cursor, wrap_cursor
6+
from .sql.types import DjangoDebugSQL
7+
from .types import DjangoDebug
8+
9+
10+
class WrappedRoot(object):
11+
12+
def __init__(self, root):
13+
self._recorded = []
14+
self._root = root
15+
16+
def record(self, **log):
17+
self._recorded.append(DjangoDebugSQL(**log))
18+
19+
def debug(self):
20+
return DjangoDebug(sql=self._recorded)
21+
22+
23+
class WrapRoot(object):
24+
25+
@property
26+
def _root(self):
27+
return self._wrapped_root.root
28+
29+
@_root.setter
30+
def _root(self, value):
31+
self._wrapped_root = value
32+
33+
def resolve_debug(self, args, info):
34+
return self._wrapped_root.debug()
35+
36+
37+
def debug_objecttype(objecttype):
38+
return type('Debug{}'.format(objecttype._meta.type_name), (WrapRoot, objecttype), {'debug': Field(DjangoDebug, name='__debug')})
39+
40+
41+
class DebugSchema(Schema):
42+
43+
@property
44+
def query(self):
45+
if not self._query:
46+
return
47+
return debug_objecttype(self._query)
48+
49+
@query.setter
50+
def query(self, value):
51+
self._query = value
52+
53+
def enable_instrumentation(self, wrapped_root):
54+
# This is thread-safe because database connections are thread-local.
55+
for connection in connections.all():
56+
wrap_cursor(connection, wrapped_root)
57+
58+
def disable_instrumentation(self):
59+
for connection in connections.all():
60+
unwrap_cursor(connection)
61+
62+
def execute(self, *args, **kwargs):
63+
root = kwargs.pop('root', object())
64+
wrapped_root = WrappedRoot(root=root)
65+
self.enable_instrumentation(wrapped_root)
66+
result = super(DebugSchema, self).execute(root=wrapped_root, *args, **kwargs)
67+
self.disable_instrumentation()
68+
return result

graphene/contrib/django/debug/sql/__init__.py

Whitespace-only changes.
Lines changed: 165 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,165 @@
1+
# Code obtained from django-debug-toolbar sql panel tracking
2+
from __future__ import absolute_import, unicode_literals
3+
4+
import json
5+
from threading import local
6+
from time import time
7+
8+
from django.utils import six
9+
from django.utils.encoding import force_text
10+
11+
12+
class SQLQueryTriggered(Exception):
13+
"""Thrown when template panel triggers a query"""
14+
15+
16+
class ThreadLocalState(local):
17+
18+
def __init__(self):
19+
self.enabled = True
20+
21+
@property
22+
def Wrapper(self):
23+
if self.enabled:
24+
return NormalCursorWrapper
25+
return ExceptionCursorWrapper
26+
27+
def recording(self, v):
28+
self.enabled = v
29+
30+
31+
state = ThreadLocalState()
32+
recording = state.recording # export function
33+
34+
35+
def wrap_cursor(connection, panel):
36+
if not hasattr(connection, '_djdt_cursor'):
37+
connection._djdt_cursor = connection.cursor
38+
39+
def cursor():
40+
return state.Wrapper(connection._djdt_cursor(), connection, panel)
41+
42+
connection.cursor = cursor
43+
return cursor
44+
45+
46+
def unwrap_cursor(connection):
47+
if hasattr(connection, '_djdt_cursor'):
48+
del connection._djdt_cursor
49+
del connection.cursor
50+
51+
52+
class ExceptionCursorWrapper(object):
53+
"""
54+
Wraps a cursor and raises an exception on any operation.
55+
Used in Templates panel.
56+
"""
57+
58+
def __init__(self, cursor, db, logger):
59+
pass
60+
61+
def __getattr__(self, attr):
62+
raise SQLQueryTriggered()
63+
64+
65+
class NormalCursorWrapper(object):
66+
"""
67+
Wraps a cursor and logs queries.
68+
"""
69+
70+
def __init__(self, cursor, db, logger):
71+
self.cursor = cursor
72+
# Instance of a BaseDatabaseWrapper subclass
73+
self.db = db
74+
# logger must implement a ``record`` method
75+
self.logger = logger
76+
77+
def _quote_expr(self, element):
78+
if isinstance(element, six.string_types):
79+
return "'%s'" % force_text(element).replace("'", "''")
80+
else:
81+
return repr(element)
82+
83+
def _quote_params(self, params):
84+
if not params:
85+
return params
86+
if isinstance(params, dict):
87+
return dict((key, self._quote_expr(value))
88+
for key, value in params.items())
89+
return list(map(self._quote_expr, params))
90+
91+
def _decode(self, param):
92+
try:
93+
return force_text(param, strings_only=True)
94+
except UnicodeDecodeError:
95+
return '(encoded string)'
96+
97+
def _record(self, method, sql, params):
98+
start_time = time()
99+
try:
100+
return method(sql, params)
101+
finally:
102+
stop_time = time()
103+
duration = (stop_time - start_time) * 1000
104+
_params = ''
105+
try:
106+
_params = json.dumps(list(map(self._decode, params)))
107+
except Exception:
108+
pass # object not JSON serializable
109+
110+
alias = getattr(self.db, 'alias', 'default')
111+
conn = self.db.connection
112+
vendor = getattr(conn, 'vendor', 'unknown')
113+
114+
params = {
115+
'vendor': vendor,
116+
'alias': alias,
117+
'sql': self.db.ops.last_executed_query(
118+
self.cursor, sql, self._quote_params(params)),
119+
'duration': duration,
120+
'raw_sql': sql,
121+
'params': _params,
122+
'start_time': start_time,
123+
'stop_time': stop_time,
124+
'is_slow': duration > 10,
125+
'is_select': sql.lower().strip().startswith('select'),
126+
}
127+
128+
if vendor == 'postgresql':
129+
# If an erroneous query was ran on the connection, it might
130+
# be in a state where checking isolation_level raises an
131+
# exception.
132+
try:
133+
iso_level = conn.isolation_level
134+
except conn.InternalError:
135+
iso_level = 'unknown'
136+
params.update({
137+
'trans_id': self.logger.get_transaction_id(alias),
138+
'trans_status': conn.get_transaction_status(),
139+
'iso_level': iso_level,
140+
'encoding': conn.encoding,
141+
})
142+
143+
# We keep `sql` to maintain backwards compatibility
144+
self.logger.record(**params)
145+
146+
def callproc(self, procname, params=()):
147+
return self._record(self.cursor.callproc, procname, params)
148+
149+
def execute(self, sql, params=()):
150+
return self._record(self.cursor.execute, sql, params)
151+
152+
def executemany(self, sql, param_list):
153+
return self._record(self.cursor.executemany, sql, param_list)
154+
155+
def __getattr__(self, attr):
156+
return getattr(self.cursor, attr)
157+
158+
def __iter__(self):
159+
return iter(self.cursor)
160+
161+
def __enter__(self):
162+
return self
163+
164+
def __exit__(self, type, value, traceback):
165+
self.close()
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
from .....core import Float, ObjectType, String
2+
3+
4+
class DjangoDebugSQL(ObjectType):
5+
vendor = String()
6+
alias = String()
7+
sql = String()
8+
duration = Float()
9+
raw_sql = String()
10+
params = String()
11+
start_time = Float()
12+
stop_time = Float()
13+
is_slow = String()
14+
is_select = String()
15+
16+
trans_id = String()
17+
trans_status = String()
18+
iso_level = String()
19+
encoding = String()

graphene/contrib/django/debug/tests/__init__.py

Whitespace-only changes.
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
import pytest
2+
3+
import graphene
4+
from graphene.contrib.django import DjangoObjectType
5+
6+
from ...tests.models import Reporter
7+
from ..schema import DebugSchema
8+
9+
# from examples.starwars_django.models import Character
10+
11+
pytestmark = pytest.mark.django_db
12+
13+
14+
def test_should_query_well():
15+
r1 = Reporter(last_name='ABA')
16+
r1.save()
17+
r2 = Reporter(last_name='Griffin')
18+
r2.save()
19+
20+
class ReporterType(DjangoObjectType):
21+
22+
class Meta:
23+
model = Reporter
24+
25+
class Query(graphene.ObjectType):
26+
reporter = graphene.Field(ReporterType)
27+
all_reporters = ReporterType.List
28+
29+
def resolve_all_reporters(self, *args, **kwargs):
30+
return Reporter.objects.all()
31+
32+
def resolve_reporter(self, *args, **kwargs):
33+
return Reporter.objects.first()
34+
35+
query = '''
36+
query ReporterQuery {
37+
reporter {
38+
lastName
39+
}
40+
allReporters {
41+
lastName
42+
}
43+
__debug {
44+
sql {
45+
rawSql
46+
}
47+
}
48+
}
49+
'''
50+
expected = {
51+
'reporter': {
52+
'lastName': 'ABA',
53+
},
54+
'allReporters': [{
55+
'lastName': 'ABA',
56+
}, {
57+
'lastName': 'Griffin',
58+
}],
59+
'__debug': {
60+
'sql': [{
61+
'rawSql': str(Reporter.objects.order_by('pk')[:1].query)
62+
}, {
63+
'rawSql': str(Reporter.objects.all().query)
64+
}]
65+
}
66+
}
67+
schema = DebugSchema(query=Query)
68+
result = schema.execute(query)
69+
assert not result.errors
70+
assert result.data == expected
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
from ....core.classtypes.objecttype import ObjectType
2+
from ....core.types import Field
3+
from .sql.types import DjangoDebugSQL
4+
5+
6+
class DjangoDebug(ObjectType):
7+
sql = Field(DjangoDebugSQL.List)

0 commit comments

Comments
 (0)