|
| 1 | +from contextlib import contextmanager |
| 2 | + |
| 3 | +from django.db import connections |
| 4 | + |
| 5 | +from ....core.schema import GraphQLSchema |
| 6 | +from ....core.types import Field |
| 7 | +from ....plugins import Plugin |
| 8 | +from .sql.tracking import unwrap_cursor, wrap_cursor |
| 9 | +from .sql.types import DjangoDebugSQL |
| 10 | +from .types import DjangoDebug |
| 11 | + |
| 12 | + |
| 13 | +class WrappedRoot(object): |
| 14 | + |
| 15 | + def __init__(self, root): |
| 16 | + self._recorded = [] |
| 17 | + self._root = root |
| 18 | + |
| 19 | + def record(self, **log): |
| 20 | + self._recorded.append(DjangoDebugSQL(**log)) |
| 21 | + |
| 22 | + def debug(self): |
| 23 | + return DjangoDebug(sql=self._recorded) |
| 24 | + |
| 25 | + |
| 26 | +class WrapRoot(object): |
| 27 | + |
| 28 | + @property |
| 29 | + def _root(self): |
| 30 | + return self._wrapped_root.root |
| 31 | + |
| 32 | + @_root.setter |
| 33 | + def _root(self, value): |
| 34 | + self._wrapped_root = value |
| 35 | + |
| 36 | + def resolve_debug(self, args, info): |
| 37 | + return self._wrapped_root.debug() |
| 38 | + |
| 39 | + |
| 40 | +def debug_objecttype(objecttype): |
| 41 | + return type( |
| 42 | + 'Debug{}'.format(objecttype._meta.type_name), |
| 43 | + (WrapRoot, objecttype), |
| 44 | + {'debug': Field(DjangoDebug, name='__debug')}) |
| 45 | + |
| 46 | + |
| 47 | +class DjangoDebugPlugin(Plugin): |
| 48 | + |
| 49 | + def enable_instrumentation(self, wrapped_root): |
| 50 | + # This is thread-safe because database connections are thread-local. |
| 51 | + for connection in connections.all(): |
| 52 | + wrap_cursor(connection, wrapped_root) |
| 53 | + |
| 54 | + def disable_instrumentation(self): |
| 55 | + for connection in connections.all(): |
| 56 | + unwrap_cursor(connection) |
| 57 | + |
| 58 | + def wrap_schema(self, schema_type): |
| 59 | + query = schema_type._query |
| 60 | + if query: |
| 61 | + class_type = self.schema.objecttype(schema_type.get_query_type()) |
| 62 | + assert class_type, 'The query in schema is not constructed with graphene' |
| 63 | + _type = debug_objecttype(class_type) |
| 64 | + self.schema.register(_type, force=True) |
| 65 | + return GraphQLSchema( |
| 66 | + self.schema, |
| 67 | + self.schema.T(_type), |
| 68 | + schema_type.get_mutation_type(), |
| 69 | + schema_type.get_subscription_type() |
| 70 | + ) |
| 71 | + return schema_type |
| 72 | + |
| 73 | + @contextmanager |
| 74 | + def context_execution(self, executor): |
| 75 | + executor['root'] = WrappedRoot(root=executor['root']) |
| 76 | + executor['schema'] = self.wrap_schema(executor['schema']) |
| 77 | + self.enable_instrumentation(executor['root']) |
| 78 | + yield executor |
| 79 | + self.disable_instrumentation() |
0 commit comments