-
Notifications
You must be signed in to change notification settings - Fork 178
Expand file tree
/
Copy pathbase.py
More file actions
316 lines (245 loc) · 11.2 KB
/
base.py
File metadata and controls
316 lines (245 loc) · 11.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
# -*- coding: utf-8 -*-
import sys
from ..error import GraphQLError
from ..language import ast
from ..pyutils.default_ordered_dict import DefaultOrderedDict
from ..type.definition import GraphQLInterfaceType, GraphQLUnionType
from ..type.directives import GraphQLIncludeDirective, GraphQLSkipDirective
from ..type.introspection import (SchemaMetaFieldDef, TypeMetaFieldDef,
TypeNameMetaFieldDef)
from ..utils.type_from_ast import type_from_ast
from .values import get_argument_values, get_variable_values
Undefined = object()
class ExecutionContext(object):
"""Data that must be available at all points during query execution.
Namely, schema of the type system that is currently executing,
and the fragments defined in the query document"""
__slots__ = 'schema', 'fragments', 'root_value', 'operation', 'variable_values', 'errors', 'context_value', \
'argument_values_cache', 'executor', 'middleware', '_subfields_cache'
def __init__(self, schema, document_ast, root_value, context_value, variable_values, operation_name, executor, middleware):
"""Constructs a ExecutionContext object from the arguments passed
to execute, which we will pass throughout the other execution
methods."""
errors = []
operation = None
fragments = {}
for definition in document_ast.definitions:
if isinstance(definition, ast.OperationDefinition):
if not operation_name and operation:
raise GraphQLError('Must provide operation name if query contains multiple operations.')
if not operation_name or definition.name and definition.name.value == operation_name:
operation = definition
elif isinstance(definition, ast.FragmentDefinition):
fragments[definition.name.value] = definition
else:
raise GraphQLError(
u'GraphQL cannot execute a request containing a {}.'.format(definition.__class__.__name__),
definition
)
if not operation:
if operation_name:
raise GraphQLError(u'Unknown operation named "{}".'.format(operation_name))
else:
raise GraphQLError('Must provide an operation.')
variable_values = get_variable_values(schema, operation.variable_definitions or [], variable_values)
self.schema = schema
self.fragments = fragments
self.root_value = root_value
self.operation = operation
self.variable_values = variable_values
self.errors = errors
self.context_value = context_value
self.argument_values_cache = {}
self.executor = executor
self.middleware = middleware
self._subfields_cache = {}
def report_error(self, error, traceback=None):
sys.excepthook(type(error), str(error), getattr(error, 'stack', None) or traceback)
self.errors.append(error)
def get_field_resolver(self, field_resolver):
if not self.middleware:
return field_resolver
return self.middleware.get_field_resolver(field_resolver)
def get_argument_values(self, field_def, field_ast):
k = field_def, field_ast
result = self.argument_values_cache.get(k)
if not result:
result = self.argument_values_cache[k] = get_argument_values(field_def.args, field_ast.arguments,
self.variable_values)
return result
def get_sub_fields(self, return_type, field_asts):
k = return_type, tuple(field_asts)
if k not in self._subfields_cache:
subfield_asts = DefaultOrderedDict(list)
visited_fragment_names = set()
for field_ast in field_asts:
selection_set = field_ast.selection_set
if selection_set:
subfield_asts = collect_fields(
self, return_type, selection_set,
subfield_asts, visited_fragment_names
)
self._subfields_cache[k] = subfield_asts
return self._subfields_cache[k]
class ExecutionResult(object):
"""The result of execution. `data` is the result of executing the
query, `errors` is null if no errors occurred, and is a
non-empty array if an error occurred."""
__slots__ = 'data', 'errors', 'invalid'
def __init__(self, data=None, errors=None, invalid=False):
self.data = data
self.errors = errors
if invalid:
assert data is None
self.invalid = invalid
def __eq__(self, other):
return (
self is other or (
isinstance(other, ExecutionResult) and
self.data == other.data and
self.errors == other.errors and
self.invalid == other.invalid
)
)
def get_operation_root_type(schema, operation):
op = operation.operation
if op == 'query':
return schema.get_query_type()
elif op == 'mutation':
mutation_type = schema.get_mutation_type()
if not mutation_type:
raise GraphQLError(
'Schema is not configured for mutations',
[operation]
)
return mutation_type
elif op == 'subscription':
subscription_type = schema.get_subscription_type()
if not subscription_type:
raise GraphQLError(
'Schema is not configured for subscriptions',
[operation]
)
return subscription_type
raise GraphQLError(
'Can only execute queries, mutations and subscriptions',
[operation]
)
def collect_fields(ctx, runtime_type, selection_set, fields, prev_fragment_names):
"""
Given a selectionSet, adds all of the fields in that selection to
the passed in map of fields, and returns it at the end.
collect_fields requires the "runtime type" of an object. For a field which
returns and Interface or Union type, the "runtime type" will be the actual
Object type returned by that field.
"""
for selection in selection_set.selections:
directives = selection.directives
if isinstance(selection, ast.Field):
if not should_include_node(ctx, directives):
continue
name = get_field_entry_key(selection)
fields[name].append(selection)
elif isinstance(selection, ast.InlineFragment):
if not should_include_node(
ctx, directives) or not does_fragment_condition_match(
ctx, selection, runtime_type):
continue
collect_fields(ctx, runtime_type, selection.selection_set, fields, prev_fragment_names)
elif isinstance(selection, ast.FragmentSpread):
frag_name = selection.name.value
if frag_name in prev_fragment_names or not should_include_node(ctx, directives):
continue
prev_fragment_names.add(frag_name)
fragment = ctx.fragments.get(frag_name)
frag_directives = fragment.directives
if not fragment or not \
should_include_node(ctx, frag_directives) or not \
does_fragment_condition_match(ctx, fragment, runtime_type):
continue
collect_fields(ctx, runtime_type, fragment.selection_set, fields, prev_fragment_names)
return fields
def should_include_node(ctx, directives):
"""Determines if a field should be included based on the @include and
@skip directives, where @skip has higher precidence than @include."""
# TODO: Refactor based on latest code
if directives:
skip_ast = None
for directive in directives:
if directive.name.value == GraphQLSkipDirective.name:
skip_ast = directive
break
if skip_ast:
args = get_argument_values(
GraphQLSkipDirective.args,
skip_ast.arguments,
ctx.variable_values,
)
if args.get('if') is True:
return False
include_ast = None
for directive in directives:
if directive.name.value == GraphQLIncludeDirective.name:
include_ast = directive
break
if include_ast:
args = get_argument_values(
GraphQLIncludeDirective.args,
include_ast.arguments,
ctx.variable_values,
)
if args.get('if') is False:
return False
return True
def does_fragment_condition_match(ctx, fragment, type_):
type_condition_ast = fragment.type_condition
if not type_condition_ast:
return True
conditional_type = type_from_ast(ctx.schema, type_condition_ast)
if conditional_type.is_same_type(type_):
return True
if isinstance(conditional_type, (GraphQLInterfaceType, GraphQLUnionType)):
return ctx.schema.is_possible_type(conditional_type, type_)
return False
def get_field_entry_key(node):
"""Implements the logic to compute the key of a given field's entry"""
if node.alias:
return node.alias.value
return node.name.value
class ResolveInfo(object):
__slots__ = ('field_name', 'field_asts', 'return_type', 'parent_type',
'schema', 'fragments', 'root_value', 'operation', 'variable_values')
def __init__(self, field_name, field_asts, return_type, parent_type,
schema, fragments, root_value, operation, variable_values):
self.field_name = field_name
self.field_asts = field_asts
self.return_type = return_type
self.parent_type = parent_type
self.schema = schema
self.fragments = fragments
self.root_value = root_value
self.operation = operation
self.variable_values = variable_values
def default_resolve_fn(source, args, context, info):
"""If a resolve function is not given, then a default resolve behavior is used which takes the property of the source object
of the same name as the field and returns it as the result, or if it's a function, returns the result of calling that function."""
name = info.field_name
property = getattr(source, name, None)
if callable(property):
return property()
return property
def get_field_def(schema, parent_type, field_name):
"""This method looks up the field on the given type defintion.
It has special casing for the two introspection fields, __schema
and __typename. __typename is special because it can always be
queried as a field, even in situations where no other fields
are allowed, like on a Union. __schema could get automatically
added to the query type, but that would require mutating type
definitions, which would cause issues."""
if field_name == '__schema' and schema.get_query_type() == parent_type:
return SchemaMetaFieldDef
elif field_name == '__type' and schema.get_query_type() == parent_type:
return TypeMetaFieldDef
elif field_name == '__typename':
return TypeNameMetaFieldDef
return parent_type.fields.get(field_name)