Skip to content

Commit a161738

Browse files
committed
Merge pull request #65 from graphql-python/features/plugins-autocamelcase
Create plugin structure
2 parents 2724025 + 6446083 commit a161738

22 files changed

+517
-81
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
from .plugin import DjangoDebugPlugin
2+
from .types import DjangoDebug
3+
4+
__all__ = ['DjangoDebugPlugin', 'DjangoDebug']
+77
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
from contextlib import contextmanager
2+
3+
from django.db import connections
4+
5+
from ....core.types import Field
6+
from ....plugins import Plugin
7+
from .sql.tracking import unwrap_cursor, wrap_cursor
8+
from .sql.types import DjangoDebugSQL
9+
from .types import DjangoDebug
10+
11+
12+
class WrappedRoot(object):
13+
14+
def __init__(self, root):
15+
self._recorded = []
16+
self._root = root
17+
18+
def record(self, **log):
19+
self._recorded.append(DjangoDebugSQL(**log))
20+
21+
def debug(self):
22+
return DjangoDebug(sql=self._recorded)
23+
24+
25+
class WrapRoot(object):
26+
27+
@property
28+
def _root(self):
29+
return self._wrapped_root.root
30+
31+
@_root.setter
32+
def _root(self, value):
33+
self._wrapped_root = value
34+
35+
def resolve_debug(self, args, info):
36+
return self._wrapped_root.debug()
37+
38+
39+
def debug_objecttype(objecttype):
40+
return type(
41+
'Debug{}'.format(objecttype._meta.type_name),
42+
(WrapRoot, objecttype),
43+
{'debug': Field(DjangoDebug, name='__debug')})
44+
45+
46+
class DjangoDebugPlugin(Plugin):
47+
48+
def transform_type(self, _type):
49+
if _type == self.schema.query:
50+
return
51+
return _type
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 wrap_schema(self, schema_type):
63+
query = schema_type._query
64+
if query:
65+
class_type = self.schema.objecttype(schema_type._query)
66+
assert class_type, 'The query in schema is not constructed with graphene'
67+
_type = debug_objecttype(class_type)
68+
schema_type._query = self.schema.T(_type)
69+
return schema_type
70+
71+
@contextmanager
72+
def context_execution(self, executor):
73+
executor['root'] = WrappedRoot(root=executor['root'])
74+
executor['schema'] = self.wrap_schema(executor['schema'])
75+
self.enable_instrumentation(executor['root'])
76+
yield executor
77+
self.disable_instrumentation()

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

Whitespace-only changes.
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)
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()
+19
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.
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 ..plugin import DjangoDebugPlugin
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 = graphene.Schema(query=Query, plugins=[DjangoDebugPlugin()])
68+
result = schema.execute(query)
69+
assert not result.errors
70+
assert result.data == expected
+7
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)