| 1 |
from asyncio import ensure_future, gather |
| 2 |
from collections.abc import Mapping |
| 3 |
from contextlib import suppress |
| 4 |
from inspect import isawaitable |
| 5 |
from typing import ( |
| 6 |
Any, |
| 7 |
AsyncIterable, |
| 8 |
Awaitable, |
| 9 |
Callable, |
| 10 |
Dict, |
| 11 |
Iterable, |
| 12 |
List, |
| 13 |
Optional, |
| 14 |
Set, |
| 15 |
Tuple, |
| 16 |
Type, |
| 17 |
Union, |
| 18 |
cast, |
| 19 |
) |
| 20 |
|
| 21 |
try: |
| 22 |
from typing import TypedDict |
| 23 |
except ImportError: # Python < 3.8 |
| 24 |
from typing_extensions import TypedDict |
| 25 |
|
| 26 |
from ..error import GraphQLError, GraphQLFormattedError, located_error |
| 27 |
from ..language import ( |
| 28 |
DocumentNode, |
| 29 |
FieldNode, |
| 30 |
FragmentDefinitionNode, |
| 31 |
OperationDefinitionNode, |
| 32 |
OperationType, |
| 33 |
) |
| 34 |
from ..pyutils import ( |
| 35 |
AwaitableOrValue, |
| 36 |
Path, |
| 37 |
Undefined, |
| 38 |
inspect, |
| 39 |
is_iterable, |
| 40 |
) |
| 41 |
from ..pyutils import ( |
| 42 |
is_awaitable as default_is_awaitable, |
| 43 |
) |
| 44 |
from ..type import ( |
| 45 |
GraphQLAbstractType, |
| 46 |
GraphQLField, |
| 47 |
GraphQLFieldResolver, |
| 48 |
GraphQLLeafType, |
| 49 |
GraphQLList, |
| 50 |
GraphQLNonNull, |
| 51 |
GraphQLObjectType, |
| 52 |
GraphQLOutputType, |
| 53 |
GraphQLResolveInfo, |
| 54 |
GraphQLSchema, |
| 55 |
GraphQLTypeResolver, |
| 56 |
SchemaMetaFieldDef, |
| 57 |
TypeMetaFieldDef, |
| 58 |
TypeNameMetaFieldDef, |
| 59 |
assert_valid_schema, |
| 60 |
is_abstract_type, |
| 61 |
is_leaf_type, |
| 62 |
is_list_type, |
| 63 |
is_non_null_type, |
| 64 |
is_object_type, |
| 65 |
) |
| 66 |
from .collect_fields import collect_fields, collect_sub_fields |
| 67 |
from .middleware import MiddlewareManager |
| 68 |
from .values import get_argument_values, get_variable_values |
| 69 |
|
| 70 |
__all__ = [ |
| 71 |
"assert_valid_execution_arguments", |
| 72 |
"default_field_resolver", |
| 73 |
"default_type_resolver", |
| 74 |
"execute", |
| 75 |
"execute_sync", |
| 76 |
"get_field_def", |
| 77 |
"ExecutionResult", |
| 78 |
"ExecutionContext", |
| 79 |
"FormattedExecutionResult", |
| 80 |
"Middleware", |
| 81 |
] |
| 82 |
|
| 83 |
|
| 84 |
# Terminology |
| 85 |
# |
| 86 |
# "Definitions" are the generic name for top-level statements in the document. |
| 87 |
# Examples of this include: |
| 88 |
# 1) Operations (such as a query) |
| 89 |
# 2) Fragments |
| 90 |
# |
| 91 |
# "Operations" are a generic name for requests in the document. |
| 92 |
# Examples of this include: |
| 93 |
# 1) query, |
| 94 |
# 2) mutation |
| 95 |
# |
| 96 |
# "Selections" are the definitions that can appear legally and at |
| 97 |
# single level of the query. These include: |
| 98 |
# 1) field references e.g "a" |
| 99 |
# 2) fragment "spreads" e.g. "...c" |
| 100 |
# 3) inline fragment "spreads" e.g. "...on Type { a }" |
| 101 |
|
| 102 |
|
| 103 |
class FormattedExecutionResult(TypedDict, total=False): |
| 104 |
"""Formatted execution result""" |
| 105 |
|
| 106 |
errors: List[GraphQLFormattedError] |
| 107 |
data: Optional[Dict[str, Any]] |
| 108 |
extensions: Dict[str, Any] |
| 109 |
|
| 110 |
|
| 111 |
class ExecutionResult: |
| 112 |
"""The result of GraphQL execution. |
| 113 |
|
| 114 |
- ``data`` is the result of a successful execution of the query. |
| 115 |
- ``errors`` is included when any errors occurred as a non-empty list. |
| 116 |
- ``extensions`` is reserved for adding non-standard properties. |
| 117 |
""" |
| 118 |
|
| 119 |
__slots__ = "data", "errors", "extensions" |
| 120 |
|
| 121 |
data: Optional[Dict[str, Any]] |
| 122 |
errors: Optional[List[GraphQLError]] |
| 123 |
extensions: Optional[Dict[str, Any]] |
| 124 |
|
| 125 |
def __init__( |
| 126 |
self, |
| 127 |
data: Optional[Dict[str, Any]] = None, |
| 128 |
errors: Optional[List[GraphQLError]] = None, |
| 129 |
extensions: Optional[Dict[str, Any]] = None, |
| 130 |
): |
| 131 |
self.data = data |
| 132 |
self.errors = errors |
| 133 |
self.extensions = extensions |
| 134 |
|
| 135 |
def __repr__(self) -> str: |
| 136 |
name = self.__class__.__name__ |
| 137 |
ext = "" if self.extensions is None else f", extensions={self.extensions}" |
| 138 |
return f"{name}(data={self.data!r}, errors={self.errors!r}{ext})" |
| 139 |
|
| 140 |
def __iter__(self) -> Iterable[Any]: |
| 141 |
return iter((self.data, self.errors)) |
| 142 |
|
| 143 |
@property |
| 144 |
def formatted(self) -> FormattedExecutionResult: |
| 145 |
"""Get execution result formatted according to the specification.""" |
| 146 |
formatted: FormattedExecutionResult = {"data": self.data} |
| 147 |
if self.errors is not None: |
| 148 |
formatted["errors"] = [error.formatted for error in self.errors] |
| 149 |
if self.extensions is not None: |
| 150 |
formatted["extensions"] = self.extensions |
| 151 |
return formatted |
| 152 |
|
| 153 |
def __eq__(self, other: Any) -> bool: |
| 154 |
if isinstance(other, dict): |
| 155 |
if "extensions" not in other: |
| 156 |
return other == dict(data=self.data, errors=self.errors) |
| 157 |
return other == dict( |
| 158 |
data=self.data, errors=self.errors, extensions=self.extensions |
| 159 |
) |
| 160 |
if isinstance(other, tuple): |
| 161 |
if len(other) == 2: |
| 162 |
return other == (self.data, self.errors) |
| 163 |
return other == (self.data, self.errors, self.extensions) |
| 164 |
return ( |
| 165 |
isinstance(other, self.__class__) |
| 166 |
and other.data == self.data |
| 167 |
and other.errors == self.errors |
| 168 |
and other.extensions == self.extensions |
| 169 |
) |
| 170 |
|
| 171 |
def __ne__(self, other: Any) -> bool: |
| 172 |
return not self == other |
| 173 |
|
| 174 |
|
| 175 |
Middleware = Optional[Union[Tuple, List, MiddlewareManager]] |
| 176 |
|
| 177 |
|
| 178 |
class CollectedErrors: |
| 179 |
"""A list of errors collected during execution, ignoring nulled positions. |
| 180 |
|
| 181 |
For internal use only. |
| 182 |
""" |
| 183 |
|
| 184 |
_error_positions: Set[Optional[Path]] |
| 185 |
_errors: List[GraphQLError] |
| 186 |
|
| 187 |
def __init__(self) -> None: |
| 188 |
self._error_positions = set() |
| 189 |
self._errors = [] |
| 190 |
|
| 191 |
@property |
| 192 |
def errors(self) -> List[GraphQLError]: |
| 193 |
return self._errors |
| 194 |
|
| 195 |
def add(self, error: GraphQLError, path: Optional[Path]) -> None: |
| 196 |
# Do not modify errors list if the execution position for this error or |
| 197 |
# any of its ancestors has already been nulled via error propagation. |
| 198 |
# This check should be unnecessary for implementations able to implement |
| 199 |
# actual cancellation. |
| 200 |
if self._has_nulled_position(path): |
| 201 |
return |
| 202 |
self._error_positions.add(path) |
| 203 |
self._errors.append(error) |
| 204 |
|
| 205 |
def _has_nulled_position(self, start_path: Optional[Path]) -> bool: |
| 206 |
path = start_path |
| 207 |
while path is not None: |
| 208 |
if path in self._error_positions: |
| 209 |
return True |
| 210 |
path = path.prev |
| 211 |
return None in self._error_positions |
| 212 |
|
| 213 |
|
| 214 |
class ExecutionContext: |
| 215 |
"""Data that must be available at all points during query execution. |
| 216 |
|
| 217 |
Namely, schema of the type system that is currently executing, and the fragments |
| 218 |
defined in the query document. |
| 219 |
""" |
| 220 |
|
| 221 |
schema: GraphQLSchema |
| 222 |
fragments: Dict[str, FragmentDefinitionNode] |
| 223 |
root_value: Any |
| 224 |
context_value: Any |
| 225 |
operation: OperationDefinitionNode |
| 226 |
variable_values: Dict[str, Any] |
| 227 |
field_resolver: GraphQLFieldResolver |
| 228 |
type_resolver: GraphQLTypeResolver |
| 229 |
subscribe_field_resolver: GraphQLFieldResolver |
| 230 |
collected_errors: CollectedErrors |
| 231 |
middleware_manager: Optional[MiddlewareManager] |
| 232 |
|
| 233 |
is_awaitable = staticmethod(default_is_awaitable) |
| 234 |
|
| 235 |
def __init__( |
| 236 |
self, |
| 237 |
schema: GraphQLSchema, |
| 238 |
fragments: Dict[str, FragmentDefinitionNode], |
| 239 |
root_value: Any, |
| 240 |
context_value: Any, |
| 241 |
operation: OperationDefinitionNode, |
| 242 |
variable_values: Dict[str, Any], |
| 243 |
field_resolver: GraphQLFieldResolver, |
| 244 |
type_resolver: GraphQLTypeResolver, |
| 245 |
subscribe_field_resolver: GraphQLFieldResolver, |
| 246 |
collected_errors: CollectedErrors, |
| 247 |
middleware_manager: Optional[MiddlewareManager], |
| 248 |
is_awaitable: Optional[Callable[[Any], bool]], |
| 249 |
) -> None: |
| 250 |
self.schema = schema |
| 251 |
self.fragments = fragments |
| 252 |
self.root_value = root_value |
| 253 |
self.context_value = context_value |
| 254 |
self.operation = operation |
| 255 |
self.variable_values = variable_values |
| 256 |
self.field_resolver = field_resolver |
| 257 |
self.type_resolver = type_resolver |
| 258 |
self.subscribe_field_resolver = subscribe_field_resolver |
| 259 |
self.collected_errors = collected_errors |
| 260 |
self.middleware_manager = middleware_manager |
| 261 |
if is_awaitable: |
| 262 |
self.is_awaitable = is_awaitable # type: ignore |
| 263 |
self._subfields_cache: Dict[Tuple, Dict[str, List[FieldNode]]] = {} |
| 264 |
|
| 265 |
@classmethod |
| 266 |
def build( |
| 267 |
cls, |
| 268 |
schema: GraphQLSchema, |
| 269 |
document: DocumentNode, |
| 270 |
root_value: Any = None, |
| 271 |
context_value: Any = None, |
| 272 |
raw_variable_values: Optional[Dict[str, Any]] = None, |
| 273 |
operation_name: Optional[str] = None, |
| 274 |
field_resolver: Optional[GraphQLFieldResolver] = None, |
| 275 |
type_resolver: Optional[GraphQLTypeResolver] = None, |
| 276 |
subscribe_field_resolver: Optional[GraphQLFieldResolver] = None, |
| 277 |
max_coercion_errors: int = 50, |
| 278 |
middleware: Optional[Middleware] = None, |
| 279 |
is_awaitable: Optional[Callable[[Any], bool]] = None, |
| 280 |
) -> Union[List[GraphQLError], "ExecutionContext"]: |
| 281 |
"""Build an execution context |
| 282 |
|
| 283 |
Constructs a ExecutionContext object from the arguments passed to execute, which |
| 284 |
we will pass throughout the other execution methods. |
| 285 |
|
| 286 |
Throws a GraphQLError if a valid execution context cannot be created. |
| 287 |
|
| 288 |
For internal use only. |
| 289 |
""" |
| 290 |
operation: Optional[OperationDefinitionNode] = None |
| 291 |
fragments: Dict[str, FragmentDefinitionNode] = {} |
| 292 |
middleware_manager: Optional[MiddlewareManager] = None |
| 293 |
if middleware is not None: |
| 294 |
if isinstance(middleware, (list, tuple)): |
| 295 |
middleware_manager = MiddlewareManager(*middleware) |
| 296 |
elif isinstance(middleware, MiddlewareManager): |
| 297 |
middleware_manager = middleware |
| 298 |
else: |
| 299 |
raise TypeError( |
| 300 |
"Middleware must be passed as a list or tuple of functions" |
| 301 |
" or objects, or as a single MiddlewareManager object." |
| 302 |
f" Got {inspect(middleware)} instead." |
| 303 |
) |
| 304 |
|
| 305 |
for definition in document.definitions: |
| 306 |
if isinstance(definition, OperationDefinitionNode): |
| 307 |
if operation_name is None: |
| 308 |
if operation: |
| 309 |
return [ |
| 310 |
GraphQLError( |
| 311 |
"Must provide operation name" |
| 312 |
" if query contains multiple operations." |
| 313 |
) |
| 314 |
] |
| 315 |
operation = definition |
| 316 |
elif definition.name and definition.name.value == operation_name: |
| 317 |
operation = definition |
| 318 |
elif isinstance(definition, FragmentDefinitionNode): |
| 319 |
fragments[definition.name.value] = definition |
| 320 |
|
| 321 |
if not operation: |
| 322 |
if operation_name is not None: |
| 323 |
return [GraphQLError(f"Unknown operation named '{operation_name}'.")] |
| 324 |
return [GraphQLError("Must provide an operation.")] |
| 325 |
|
| 326 |
coerced_variable_values = get_variable_values( |
| 327 |
schema, |
| 328 |
operation.variable_definitions or (), |
| 329 |
raw_variable_values or {}, |
| 330 |
max_errors=max_coercion_errors, |
| 331 |
) |
| 332 |
|
| 333 |
if isinstance(coerced_variable_values, list): |
| 334 |
return coerced_variable_values # errors |
| 335 |
|
| 336 |
return cls( |
| 337 |
schema, |
| 338 |
fragments, |
| 339 |
root_value, |
| 340 |
context_value, |
| 341 |
operation, |
| 342 |
coerced_variable_values, # coerced values |
| 343 |
field_resolver or default_field_resolver, |
| 344 |
type_resolver or default_type_resolver, |
| 345 |
subscribe_field_resolver or default_field_resolver, |
| 346 |
CollectedErrors(), |
| 347 |
middleware_manager, |
| 348 |
is_awaitable, |
| 349 |
) |
| 350 |
|
| 351 |
@staticmethod |
| 352 |
def build_response( |
| 353 |
data: Optional[Dict[str, Any]], errors: List[GraphQLError] |
| 354 |
) -> ExecutionResult: |
| 355 |
"""Build response. |
| 356 |
|
| 357 |
Given a completed execution context and data, build the (data, errors) response |
| 358 |
defined by the "Response" section of the GraphQL spec. |
| 359 |
""" |
| 360 |
if not errors: |
| 361 |
return ExecutionResult(data, None) |
| 362 |
# Sort the error list in order to make it deterministic, since we might have |
| 363 |
# been using parallel execution. |
| 364 |
errors.sort( |
| 365 |
key=lambda error: (error.locations or [], error.path or [], error.message) |
| 366 |
) |
| 367 |
return ExecutionResult(data, errors) |
| 368 |
|
| 369 |
def execute_operation( |
| 370 |
self, operation: OperationDefinitionNode, root_value: Any |
| 371 |
) -> Optional[AwaitableOrValue[Any]]: |
| 372 |
"""Execute an operation. |
| 373 |
|
| 374 |
Implements the "Executing operations" section of the spec. |
| 375 |
""" |
| 376 |
root_type = self.schema.get_root_type(operation.operation) |
| 377 |
if root_type is None: |
| 378 |
raise GraphQLError( |
| 379 |
"Schema is not configured to execute" |
| 380 |
f" {operation.operation.value} operation.", |
| 381 |
operation, |
| 382 |
) |
| 383 |
|
| 384 |
root_fields = collect_fields( |
| 385 |
self.schema, |
| 386 |
self.fragments, |
| 387 |
self.variable_values, |
| 388 |
root_type, |
| 389 |
operation.selection_set, |
| 390 |
) |
| 391 |
|
| 392 |
path = None |
| 393 |
|
| 394 |
return ( |
| 395 |
self.execute_fields_serially |
| 396 |
if operation.operation == OperationType.MUTATION |
| 397 |
else self.execute_fields |
| 398 |
)(root_type, root_value, path, root_fields) |
| 399 |
|
| 400 |
def execute_fields_serially( |
| 401 |
self, |
| 402 |
parent_type: GraphQLObjectType, |
| 403 |
source_value: Any, |
| 404 |
path: Optional[Path], |
| 405 |
fields: Dict[str, List[FieldNode]], |
| 406 |
) -> AwaitableOrValue[Dict[str, Any]]: |
| 407 |
"""Execute the given fields serially. |
| 408 |
|
| 409 |
Implements the "Executing selection sets" section of the spec |
| 410 |
for fields that must be executed serially. |
| 411 |
""" |
| 412 |
results: AwaitableOrValue[Dict[str, Any]] = {} |
| 413 |
is_awaitable = self.is_awaitable |
| 414 |
for response_name, field_nodes in fields.items(): |
| 415 |
field_path = Path(path, response_name, parent_type.name) |
| 416 |
result = self.execute_field( |
| 417 |
parent_type, source_value, field_nodes, field_path |
| 418 |
) |
| 419 |
if result is Undefined: |
| 420 |
continue |
| 421 |
if is_awaitable(results): |
| 422 |
# noinspection PyShadowingNames |
| 423 |
async def await_and_set_result( |
| 424 |
results: Awaitable[Dict[str, Any]], |
| 425 |
response_name: str, |
| 426 |
result: AwaitableOrValue[Any], |
| 427 |
) -> Dict[str, Any]: |
| 428 |
awaited_results = await results |
| 429 |
awaited_results[response_name] = ( |
| 430 |
await result if is_awaitable(result) else result |
| 431 |
) |
| 432 |
return awaited_results |
| 433 |
|
| 434 |
results = await_and_set_result( |
| 435 |
cast(Awaitable, results), response_name, result |
| 436 |
) |
| 437 |
elif is_awaitable(result): |
| 438 |
# noinspection PyShadowingNames |
| 439 |
async def set_result( |
| 440 |
results: Dict[str, Any], |
| 441 |
response_name: str, |
| 442 |
result: Awaitable, |
| 443 |
) -> Dict[str, Any]: |
| 444 |
results[response_name] = await result |
| 445 |
return results |
| 446 |
|
| 447 |
results = set_result( |
| 448 |
cast(Dict[str, Any], results), response_name, result |
| 449 |
) |
| 450 |
else: |
| 451 |
cast(Dict[str, Any], results)[response_name] = result |
| 452 |
return results |
| 453 |
|
| 454 |
def execute_fields( |
| 455 |
self, |
| 456 |
parent_type: GraphQLObjectType, |
| 457 |
source_value: Any, |
| 458 |
path: Optional[Path], |
| 459 |
fields: Dict[str, List[FieldNode]], |
| 460 |
) -> AwaitableOrValue[Dict[str, Any]]: |
| 461 |
"""Execute the given fields concurrently. |
| 462 |
|
| 463 |
Implements the "Executing selection sets" section of the spec |
| 464 |
for fields that may be executed in parallel. |
| 465 |
""" |
| 466 |
results = {} |
| 467 |
is_awaitable = self.is_awaitable |
| 468 |
awaitable_fields: List[str] = [] |
| 469 |
append_awaitable = awaitable_fields.append |
| 470 |
for response_name, field_nodes in fields.items(): |
| 471 |
field_path = Path(path, response_name, parent_type.name) |
| 472 |
result = self.execute_field( |
| 473 |
parent_type, source_value, field_nodes, field_path |
| 474 |
) |
| 475 |
if result is not Undefined: |
| 476 |
results[response_name] = result |
| 477 |
if is_awaitable(result): |
| 478 |
append_awaitable(response_name) |
| 479 |
|
| 480 |
# If there are no coroutines, we can just return the object |
| 481 |
if not awaitable_fields: |
| 482 |
return results |
| 483 |
|
| 484 |
# Otherwise, results is a map from field name to the result of resolving that |
| 485 |
# field, which is possibly a coroutine object. Return a coroutine object that |
| 486 |
# will yield this same map, but with any coroutines awaited in parallel and |
| 487 |
# replaced with the values they yielded. |
| 488 |
async def get_results() -> Dict[str, Any]: |
| 489 |
results.update( |
| 490 |
zip( |
| 491 |
awaitable_fields, |
| 492 |
await gather(*(results[field] for field in awaitable_fields)), |
| 493 |
) |
| 494 |
) |
| 495 |
return results |
| 496 |
|
| 497 |
return get_results() |
| 498 |
|
| 499 |
def build_resolve_info( |
| 500 |
self, |
| 501 |
field_def: GraphQLField, |
| 502 |
field_nodes: List[FieldNode], |
| 503 |
parent_type: GraphQLObjectType, |
| 504 |
path: Path, |
| 505 |
) -> GraphQLResolveInfo: |
| 506 |
"""Build the GraphQLResolveInfo object. |
| 507 |
|
| 508 |
For internal use only.""" |
| 509 |
# The resolve function's first argument is a collection of information about |
| 510 |
# the current execution state. |
| 511 |
return GraphQLResolveInfo( |
| 512 |
field_nodes[0].name.value, |
| 513 |
field_nodes, |
| 514 |
field_def.type, |
| 515 |
parent_type, |
| 516 |
path, |
| 517 |
self.schema, |
| 518 |
self.fragments, |
| 519 |
self.root_value, |
| 520 |
self.operation, |
| 521 |
self.variable_values, |
| 522 |
self.context_value, |
| 523 |
self.is_awaitable, |
| 524 |
) |
| 525 |
|
| 526 |
def execute_field( |
| 527 |
self, |
| 528 |
parent_type: GraphQLObjectType, |
| 529 |
source: Any, |
| 530 |
field_nodes: List[FieldNode], |
| 531 |
path: Path, |
| 532 |
) -> AwaitableOrValue[Any]: |
| 533 |
"""Resolve the field on the given source object. |
| 534 |
|
| 535 |
Implements the "Executing fields" section of the spec. |
| 536 |
|
| 537 |
In particular, this method figures out the value that the field returns by |
| 538 |
calling its resolve function, then calls complete_value to await coroutine |
| 539 |
objects, serialize scalars, or execute the sub-selection-set for objects. |
| 540 |
""" |
| 541 |
field_def = get_field_def(self.schema, parent_type, field_nodes[0]) |
| 542 |
if not field_def: |
| 543 |
return Undefined |
| 544 |
|
| 545 |
return_type = field_def.type |
| 546 |
resolve_fn = field_def.resolve or self.field_resolver |
| 547 |
|
| 548 |
if self.middleware_manager: |
| 549 |
resolve_fn = self.middleware_manager.get_field_resolver(resolve_fn) |
| 550 |
|
| 551 |
info = self.build_resolve_info(field_def, field_nodes, parent_type, path) |
| 552 |
|
| 553 |
# Get the resolve function, regardless of if its result is normal or abrupt |
| 554 |
# (error). |
| 555 |
try: |
| 556 |
# Build a dictionary of arguments from the field.arguments AST, using the |
| 557 |
# variables scope to fulfill any variable references. |
| 558 |
args = get_argument_values(field_def, field_nodes[0], self.variable_values) |
| 559 |
|
| 560 |
# Note that contrary to the JavaScript implementation, we pass the context |
| 561 |
# value as part of the resolve info. |
| 562 |
result = resolve_fn(source, info, **args) |
| 563 |
|
| 564 |
if self.is_awaitable(result): |
| 565 |
# noinspection PyShadowingNames |
| 566 |
async def await_result() -> Any: |
| 567 |
try: |
| 568 |
completed = self.complete_value( |
| 569 |
return_type, field_nodes, info, path, await result |
| 570 |
) |
| 571 |
if self.is_awaitable(completed): |
| 572 |
return await completed |
| 573 |
return completed |
| 574 |
except Exception as raw_error: |
| 575 |
error = located_error(raw_error, field_nodes, path.as_list()) |
| 576 |
self.handle_field_error(error, return_type, path) |
| 577 |
return None |
| 578 |
|
| 579 |
return await_result() |
| 580 |
|
| 581 |
completed = self.complete_value( |
| 582 |
return_type, field_nodes, info, path, result |
| 583 |
) |
| 584 |
if self.is_awaitable(completed): |
| 585 |
# noinspection PyShadowingNames |
| 586 |
async def await_completed() -> Any: |
| 587 |
try: |
| 588 |
return await completed |
| 589 |
except Exception as raw_error: |
| 590 |
error = located_error(raw_error, field_nodes, path.as_list()) |
| 591 |
self.handle_field_error(error, return_type, path) |
| 592 |
return None |
| 593 |
|
| 594 |
return await_completed() |
| 595 |
|
| 596 |
return completed |
| 597 |
except Exception as raw_error: |
| 598 |
error = located_error(raw_error, field_nodes, path.as_list()) |
| 599 |
self.handle_field_error(error, return_type, path) |
| 600 |
return None |
| 601 |
|
| 602 |
def handle_field_error( |
| 603 |
self, |
| 604 |
error: GraphQLError, |
| 605 |
return_type: GraphQLOutputType, |
| 606 |
path: Path, |
| 607 |
) -> None: |
| 608 |
# If the field type is non-nullable, then it is resolved without any protection |
| 609 |
# from errors, however it still properly locates the error. |
| 610 |
if is_non_null_type(return_type): |
| 611 |
raise error |
| 612 |
# Otherwise, error protection is applied, logging the error and resolving a |
| 613 |
# null value for this field if one is encountered. |
| 614 |
self.collected_errors.add(error, path) |
| 615 |
return None |
| 616 |
|
| 617 |
def complete_value( |
| 618 |
self, |
| 619 |
return_type: GraphQLOutputType, |
| 620 |
field_nodes: List[FieldNode], |
| 621 |
info: GraphQLResolveInfo, |
| 622 |
path: Path, |
| 623 |
result: Any, |
| 624 |
) -> AwaitableOrValue[Any]: |
| 625 |
"""Complete a value. |
| 626 |
|
| 627 |
Implements the instructions for completeValue as defined in the |
| 628 |
"Value completion" section of the spec. |
| 629 |
|
| 630 |
If the field type is Non-Null, then this recursively completes the value |
| 631 |
for the inner type. It throws a field error if that completion returns null, |
| 632 |
as per the "Nullability" section of the spec. |
| 633 |
|
| 634 |
If the field type is a List, then this recursively completes the value |
| 635 |
for the inner type on each item in the list. |
| 636 |
|
| 637 |
If the field type is a Scalar or Enum, ensures the completed value is a legal |
| 638 |
value of the type by calling the ``serialize`` method of GraphQL type |
| 639 |
definition. |
| 640 |
|
| 641 |
If the field is an abstract type, determine the runtime type of the value and |
| 642 |
then complete based on that type. |
| 643 |
|
| 644 |
Otherwise, the field type expects a sub-selection set, and will complete the |
| 645 |
value by evaluating all sub-selections. |
| 646 |
""" |
| 647 |
# If result is an Exception, throw a located error. |
| 648 |
if isinstance(result, Exception): |
| 649 |
raise result |
| 650 |
|
| 651 |
# If field type is NonNull, complete for inner type, and throw field error if |
| 652 |
# result is null. |
| 653 |
if is_non_null_type(return_type): |
| 654 |
completed = self.complete_value( |
| 655 |
cast(GraphQLNonNull, return_type).of_type, |
| 656 |
field_nodes, |
| 657 |
info, |
| 658 |
path, |
| 659 |
result, |
| 660 |
) |
| 661 |
if completed is None: |
| 662 |
raise TypeError( |
| 663 |
"Cannot return null for non-nullable field" |
| 664 |
f" {info.parent_type.name}.{info.field_name}." |
| 665 |
) |
| 666 |
return completed |
| 667 |
|
| 668 |
# If result value is null or undefined then return null. |
| 669 |
if result is None or result is Undefined: |
| 670 |
return None |
| 671 |
|
| 672 |
# If field type is List, complete each item in the list with inner type |
| 673 |
if is_list_type(return_type): |
| 674 |
return self.complete_list_value( |
| 675 |
cast(GraphQLList, return_type), field_nodes, info, path, result |
| 676 |
) |
| 677 |
|
| 678 |
# If field type is a leaf type, Scalar or Enum, serialize to a valid value, |
| 679 |
# returning null if serialization is not possible. |
| 680 |
if is_leaf_type(return_type): |
| 681 |
return self.complete_leaf_value(cast(GraphQLLeafType, return_type), result) |
| 682 |
|
| 683 |
# If field type is an abstract type, Interface or Union, determine the runtime |
| 684 |
# Object type and complete for that type. |
| 685 |
if is_abstract_type(return_type): |
| 686 |
return self.complete_abstract_value( |
| 687 |
cast(GraphQLAbstractType, return_type), field_nodes, info, path, result |
| 688 |
) |
| 689 |
|
| 690 |
# If field type is Object, execute and complete all sub-selections. |
| 691 |
if is_object_type(return_type): |
| 692 |
return self.complete_object_value( |
| 693 |
cast(GraphQLObjectType, return_type), field_nodes, info, path, result |
| 694 |
) |
| 695 |
|
| 696 |
# Not reachable. All possible output types have been considered. |
| 697 |
raise TypeError( # pragma: no cover |
| 698 |
"Cannot complete value of unexpected output type:" |
| 699 |
f" '{inspect(return_type)}'." |
| 700 |
) |
| 701 |
|
| 702 |
def complete_list_value( |
| 703 |
self, |
| 704 |
return_type: GraphQLList[GraphQLOutputType], |
| 705 |
field_nodes: List[FieldNode], |
| 706 |
info: GraphQLResolveInfo, |
| 707 |
path: Path, |
| 708 |
result: Union[AsyncIterable[Any], Iterable[Any]], |
| 709 |
) -> AwaitableOrValue[List[Any]]: |
| 710 |
"""Complete a list value. |
| 711 |
|
| 712 |
Complete a list value by completing each item in the list with the inner type. |
| 713 |
""" |
| 714 |
if not is_iterable(result): |
| 715 |
# experimental: allow async iterables |
| 716 |
if isinstance(result, AsyncIterable): |
| 717 |
# noinspection PyShadowingNames |
| 718 |
async def async_iterable_to_list( |
| 719 |
async_result: AsyncIterable[Any], |
| 720 |
) -> Any: |
| 721 |
sync_result = [item async for item in async_result] |
| 722 |
return self.complete_list_value( |
| 723 |
return_type, field_nodes, info, path, sync_result |
| 724 |
) |
| 725 |
|
| 726 |
return async_iterable_to_list(result) |
| 727 |
|
| 728 |
raise GraphQLError( |
| 729 |
"Expected Iterable, but did not find one for field" |
| 730 |
f" '{info.parent_type.name}.{info.field_name}'." |
| 731 |
) |
| 732 |
result = cast(Iterable[Any], result) |
| 733 |
|
| 734 |
# This is specified as a simple map, however we're optimizing the path where |
| 735 |
# the list contains no coroutine objects by avoiding creating another coroutine |
| 736 |
# object. |
| 737 |
item_type = return_type.of_type |
| 738 |
is_awaitable = self.is_awaitable |
| 739 |
awaitable_indices: List[int] = [] |
| 740 |
append_awaitable = awaitable_indices.append |
| 741 |
completed_results: List[Any] = [] |
| 742 |
append_result = completed_results.append |
| 743 |
for index, item in enumerate(result): |
| 744 |
# No need to modify the info object containing the path, since from here on |
| 745 |
# it is not ever accessed by resolver functions. |
| 746 |
item_path = path.add_key(index, None) |
| 747 |
completed_item: AwaitableOrValue[Any] |
| 748 |
if is_awaitable(item): |
| 749 |
# noinspection PyShadowingNames |
| 750 |
async def await_completed(item: Any, item_path: Path) -> Any: |
| 751 |
try: |
| 752 |
completed = self.complete_value( |
| 753 |
item_type, field_nodes, info, item_path, await item |
| 754 |
) |
| 755 |
if is_awaitable(completed): |
| 756 |
return await completed |
| 757 |
return completed |
| 758 |
except Exception as raw_error: |
| 759 |
error = located_error( |
| 760 |
raw_error, field_nodes, item_path.as_list() |
| 761 |
) |
| 762 |
self.handle_field_error(error, item_type, item_path) |
| 763 |
return None |
| 764 |
|
| 765 |
completed_item = await_completed(item, item_path) |
| 766 |
else: |
| 767 |
try: |
| 768 |
completed_item = self.complete_value( |
| 769 |
item_type, field_nodes, info, item_path, item |
| 770 |
) |
| 771 |
if is_awaitable(completed_item): |
| 772 |
# noinspection PyShadowingNames |
| 773 |
async def await_completed(item: Any, item_path: Path) -> Any: |
| 774 |
try: |
| 775 |
return await item |
| 776 |
except Exception as raw_error: |
| 777 |
error = located_error( |
| 778 |
raw_error, field_nodes, item_path.as_list() |
| 779 |
) |
| 780 |
self.handle_field_error(error, item_type, item_path) |
| 781 |
return None |
| 782 |
|
| 783 |
completed_item = await_completed(completed_item, item_path) |
| 784 |
except Exception as raw_error: |
| 785 |
error = located_error(raw_error, field_nodes, item_path.as_list()) |
| 786 |
self.handle_field_error(error, item_type, item_path) |
| 787 |
completed_item = None |
| 788 |
|
| 789 |
if is_awaitable(completed_item): |
| 790 |
append_awaitable(index) |
| 791 |
append_result(completed_item) |
| 792 |
|
| 793 |
if not awaitable_indices: |
| 794 |
return completed_results |
| 795 |
|
| 796 |
# noinspection PyShadowingNames |
| 797 |
async def get_completed_results() -> List[Any]: |
| 798 |
for index, result in zip( |
| 799 |
awaitable_indices, |
| 800 |
await gather( |
| 801 |
*(completed_results[index] for index in awaitable_indices) |
| 802 |
), |
| 803 |
): |
| 804 |
completed_results[index] = result |
| 805 |
return completed_results |
| 806 |
|
| 807 |
return get_completed_results() |
| 808 |
|
| 809 |
@staticmethod |
| 810 |
def complete_leaf_value(return_type: GraphQLLeafType, result: Any) -> Any: |
| 811 |
"""Complete a leaf value. |
| 812 |
|
| 813 |
Complete a Scalar or Enum by serializing to a valid value, returning null if |
| 814 |
serialization is not possible. |
| 815 |
""" |
| 816 |
serialized_result = return_type.serialize(result) |
| 817 |
if serialized_result is Undefined or serialized_result is None: |
| 818 |
raise TypeError( |
| 819 |
f"Expected `{inspect(return_type)}.serialize({inspect(result)})`" |
| 820 |
f" to return non-nullable value, returned: {inspect(serialized_result)}" |
| 821 |
) |
| 822 |
return serialized_result |
| 823 |
|
| 824 |
def complete_abstract_value( |
| 825 |
self, |
| 826 |
return_type: GraphQLAbstractType, |
| 827 |
field_nodes: List[FieldNode], |
| 828 |
info: GraphQLResolveInfo, |
| 829 |
path: Path, |
| 830 |
result: Any, |
| 831 |
) -> AwaitableOrValue[Any]: |
| 832 |
"""Complete an abstract value. |
| 833 |
|
| 834 |
Complete a value of an abstract type by determining the runtime object type of |
| 835 |
that value, then complete the value for that type. |
| 836 |
""" |
| 837 |
resolve_type_fn = return_type.resolve_type or self.type_resolver |
| 838 |
runtime_type = resolve_type_fn(result, info, return_type) |
| 839 |
|
| 840 |
if self.is_awaitable(runtime_type): |
| 841 |
runtime_type = cast(Awaitable, runtime_type) |
| 842 |
|
| 843 |
async def await_complete_object_value() -> Any: |
| 844 |
value = self.complete_object_value( |
| 845 |
self.ensure_valid_runtime_type( |
| 846 |
await runtime_type, # type: ignore |
| 847 |
return_type, |
| 848 |
field_nodes, |
| 849 |
info, |
| 850 |
result, |
| 851 |
), |
| 852 |
field_nodes, |
| 853 |
info, |
| 854 |
path, |
| 855 |
result, |
| 856 |
) |
| 857 |
if self.is_awaitable(value): |
| 858 |
return await value # type: ignore |
| 859 |
return value # pragma: no cover |
| 860 |
|
| 861 |
return await_complete_object_value() |
| 862 |
runtime_type = cast(Optional[str], runtime_type) |
| 863 |
|
| 864 |
return self.complete_object_value( |
| 865 |
self.ensure_valid_runtime_type( |
| 866 |
runtime_type, return_type, field_nodes, info, result |
| 867 |
), |
| 868 |
field_nodes, |
| 869 |
info, |
| 870 |
path, |
| 871 |
result, |
| 872 |
) |
| 873 |
|
| 874 |
def ensure_valid_runtime_type( |
| 875 |
self, |
| 876 |
runtime_type_name: Any, |
| 877 |
return_type: GraphQLAbstractType, |
| 878 |
field_nodes: List[FieldNode], |
| 879 |
info: GraphQLResolveInfo, |
| 880 |
result: Any, |
| 881 |
) -> GraphQLObjectType: |
| 882 |
if runtime_type_name is None: |
| 883 |
raise GraphQLError( |
| 884 |
f"Abstract type '{return_type.name}' must resolve" |
| 885 |
" to an Object type at runtime" |
| 886 |
f" for field '{info.parent_type.name}.{info.field_name}'." |
| 887 |
f" Either the '{return_type.name}' type should provide" |
| 888 |
" a 'resolve_type' function or each possible type should provide" |
| 889 |
" an 'is_type_of' function.", |
| 890 |
field_nodes, |
| 891 |
) |
| 892 |
|
| 893 |
if is_object_type(runtime_type_name): # pragma: no cover |
| 894 |
raise GraphQLError( |
| 895 |
"Support for returning GraphQLObjectType from resolve_type was" |
| 896 |
" removed in GraphQL-core 3.2, please return type name instead." |
| 897 |
) |
| 898 |
|
| 899 |
if not isinstance(runtime_type_name, str): |
| 900 |
raise GraphQLError( |
| 901 |
f"Abstract type '{return_type.name}' must resolve" |
| 902 |
" to an Object type at runtime" |
| 903 |
f" for field '{info.parent_type.name}.{info.field_name}' with value" |
| 904 |
f" {inspect(result)}, received '{inspect(runtime_type_name)}'.", |
| 905 |
field_nodes, |
| 906 |
) |
| 907 |
|
| 908 |
runtime_type = self.schema.get_type(runtime_type_name) |
| 909 |
|
| 910 |
if runtime_type is None: |
| 911 |
raise GraphQLError( |
| 912 |
f"Abstract type '{return_type.name}' was resolved to a type" |
| 913 |
f" '{runtime_type_name}' that does not exist inside the schema.", |
| 914 |
field_nodes, |
| 915 |
) |
| 916 |
|
| 917 |
if not is_object_type(runtime_type): |
| 918 |
raise GraphQLError( |
| 919 |
f"Abstract type '{return_type.name}' was resolved" |
| 920 |
f" to a non-object type '{runtime_type_name}'.", |
| 921 |
field_nodes, |
| 922 |
) |
| 923 |
|
| 924 |
runtime_type = cast(GraphQLObjectType, runtime_type) |
| 925 |
|
| 926 |
if not self.schema.is_sub_type(return_type, runtime_type): |
| 927 |
raise GraphQLError( |
| 928 |
f"Runtime Object type '{runtime_type.name}' is not a possible" |
| 929 |
f" type for '{return_type.name}'.", |
| 930 |
field_nodes, |
| 931 |
) |
| 932 |
|
| 933 |
return runtime_type |
| 934 |
|
| 935 |
def complete_object_value( |
| 936 |
self, |
| 937 |
return_type: GraphQLObjectType, |
| 938 |
field_nodes: List[FieldNode], |
| 939 |
info: GraphQLResolveInfo, |
| 940 |
path: Path, |
| 941 |
result: Any, |
| 942 |
) -> AwaitableOrValue[Dict[str, Any]]: |
| 943 |
"""Complete an Object value by executing all sub-selections.""" |
| 944 |
# Collect sub-fields to execute to complete this value. |
| 945 |
sub_field_nodes = self.collect_subfields(return_type, field_nodes) |
| 946 |
|
| 947 |
# If there is an `is_type_of()` predicate function, call it with the current |
| 948 |
# result. If `is_type_of()` returns False, then raise an error rather than |
| 949 |
# continuing execution. |
| 950 |
if return_type.is_type_of: |
| 951 |
is_type_of = return_type.is_type_of(result, info) |
| 952 |
|
| 953 |
if self.is_awaitable(is_type_of): |
| 954 |
|
| 955 |
async def execute_subfields_async() -> Dict[str, Any]: |
| 956 |
if not await is_type_of: # type: ignore |
| 957 |
raise invalid_return_type_error( |
| 958 |
return_type, result, field_nodes |
| 959 |
) |
| 960 |
return self.execute_fields( |
| 961 |
return_type, result, path, sub_field_nodes |
| 962 |
) # type: ignore |
| 963 |
|
| 964 |
return execute_subfields_async() |
| 965 |
|
| 966 |
if not is_type_of: |
| 967 |
raise invalid_return_type_error(return_type, result, field_nodes) |
| 968 |
|
| 969 |
return self.execute_fields(return_type, result, path, sub_field_nodes) |
| 970 |
|
| 971 |
def collect_subfields( |
| 972 |
self, return_type: GraphQLObjectType, field_nodes: List[FieldNode] |
| 973 |
) -> Dict[str, List[FieldNode]]: |
| 974 |
"""Collect subfields. |
| 975 |
|
| 976 |
A cached collection of relevant subfields with regard to the return type is |
| 977 |
kept in the execution context as ``_subfields_cache``. This ensures the |
| 978 |
subfields are not repeatedly calculated, which saves overhead when resolving |
| 979 |
lists of values. |
| 980 |
""" |
| 981 |
cache = self._subfields_cache |
| 982 |
# We cannot use the field_nodes themselves as key for the cache, since they |
| 983 |
# are not hashable as a list. We also do not want to use the field_nodes |
| 984 |
# themselves (converted to a tuple) as keys, since hashing them is slow. |
| 985 |
# Therefore we use the ids of the field_nodes as keys. Note that we do not |
| 986 |
# use the id of the list, since we want to hit the cache for all lists of |
| 987 |
# the same nodes, not only for the same list of nodes. Also, the list id may |
| 988 |
# even be reused, in which case we would get wrong results from the cache. |
| 989 |
key = ( |
| 990 |
(return_type, id(field_nodes[0])) |
| 991 |
if len(field_nodes) == 1 # optimize most frequent case |
| 992 |
else tuple((return_type, *map(id, field_nodes))) |
| 993 |
) |
| 994 |
sub_field_nodes = cache.get(key) |
| 995 |
if sub_field_nodes is None: |
| 996 |
sub_field_nodes = collect_sub_fields( |
| 997 |
self.schema, |
| 998 |
self.fragments, |
| 999 |
self.variable_values, |
| 1000 |
return_type, |
| 1001 |
field_nodes, |
| 1002 |
) |
| 1003 |
cache[key] = sub_field_nodes |
| 1004 |
return sub_field_nodes |
| 1005 |
|
| 1006 |
|
| 1007 |
def execute( |
| 1008 |
schema: GraphQLSchema, |
| 1009 |
document: DocumentNode, |
| 1010 |
root_value: Any = None, |
| 1011 |
context_value: Any = None, |
| 1012 |
variable_values: Optional[Dict[str, Any]] = None, |
| 1013 |
operation_name: Optional[str] = None, |
| 1014 |
field_resolver: Optional[GraphQLFieldResolver] = None, |
| 1015 |
type_resolver: Optional[GraphQLTypeResolver] = None, |
| 1016 |
subscribe_field_resolver: Optional[GraphQLFieldResolver] = None, |
| 1017 |
max_coercion_errors: int = 50, |
| 1018 |
middleware: Optional[Middleware] = None, |
| 1019 |
execution_context_class: Optional[Type["ExecutionContext"]] = None, |
| 1020 |
is_awaitable: Optional[Callable[[Any], bool]] = None, |
| 1021 |
) -> AwaitableOrValue[ExecutionResult]: |
| 1022 |
"""Execute a GraphQL operation. |
| 1023 |
|
| 1024 |
Implements the "Executing requests" section of the GraphQL specification. |
| 1025 |
|
| 1026 |
Returns an ExecutionResult (if all encountered resolvers are synchronous), |
| 1027 |
or a coroutine object eventually yielding an ExecutionResult. |
| 1028 |
|
| 1029 |
If the arguments to this function do not result in a legal execution context, |
| 1030 |
a GraphQLError will be thrown immediately explaining the invalid input. |
| 1031 |
""" |
| 1032 |
# If arguments are missing or incorrect, throw an error. |
| 1033 |
assert_valid_execution_arguments(schema, document, variable_values) |
| 1034 |
|
| 1035 |
if execution_context_class is None: |
| 1036 |
execution_context_class = ExecutionContext |
| 1037 |
|
| 1038 |
# If a valid execution context cannot be created due to incorrect arguments, |
| 1039 |
# a "Response" with only errors is returned. |
| 1040 |
exe_context = execution_context_class.build( |
| 1041 |
schema, |
| 1042 |
document, |
| 1043 |
root_value, |
| 1044 |
context_value, |
| 1045 |
variable_values, |
| 1046 |
operation_name, |
| 1047 |
field_resolver, |
| 1048 |
type_resolver, |
| 1049 |
subscribe_field_resolver, |
| 1050 |
max_coercion_errors, |
| 1051 |
middleware, |
| 1052 |
is_awaitable, |
| 1053 |
) |
| 1054 |
|
| 1055 |
# Return early errors if execution context failed. |
| 1056 |
if isinstance(exe_context, list): |
| 1057 |
return ExecutionResult(data=None, errors=exe_context) |
| 1058 |
|
| 1059 |
# Return a possible coroutine object that will eventually yield the data described |
| 1060 |
# by the "Response" section of the GraphQL specification. |
| 1061 |
# |
| 1062 |
# If errors are encountered while executing a GraphQL field, only that field and |
| 1063 |
# its descendants will be omitted, and sibling fields will still be executed. An |
| 1064 |
# execution which encounters errors will still result in a coroutine object that |
| 1065 |
# can be executed without errors. |
| 1066 |
# |
| 1067 |
# Errors from sub-fields of a NonNull type may propagate to the top level, |
| 1068 |
# at which point we still log the error and null the parent field, which |
| 1069 |
# in this case is the entire response. |
| 1070 |
collected_errors = exe_context.collected_errors |
| 1071 |
build_response = exe_context.build_response |
| 1072 |
try: |
| 1073 |
operation = exe_context.operation |
| 1074 |
result = exe_context.execute_operation(operation, root_value) |
| 1075 |
|
| 1076 |
if exe_context.is_awaitable(result): |
| 1077 |
# noinspection PyShadowingNames |
| 1078 |
async def await_result() -> Any: |
| 1079 |
try: |
| 1080 |
data = await result # type: ignore |
| 1081 |
return build_response(data, collected_errors.errors) |
| 1082 |
except GraphQLError as error: |
| 1083 |
collected_errors.add(error, None) |
| 1084 |
return build_response(None, collected_errors.errors) |
| 1085 |
|
| 1086 |
return await_result() |
| 1087 |
except GraphQLError as error: |
| 1088 |
collected_errors.add(error, None) |
| 1089 |
return build_response(None, collected_errors.errors) |
| 1090 |
else: |
| 1091 |
return build_response(result, collected_errors.errors) # type: ignore |
| 1092 |
|
| 1093 |
|
| 1094 |
def assume_not_awaitable(_value: Any) -> bool: |
| 1095 |
"""Replacement for isawaitable if everything is assumed to be synchronous.""" |
| 1096 |
return False |
| 1097 |
|
| 1098 |
|
| 1099 |
def execute_sync( |
| 1100 |
schema: GraphQLSchema, |
| 1101 |
document: DocumentNode, |
| 1102 |
root_value: Any = None, |
| 1103 |
context_value: Any = None, |
| 1104 |
variable_values: Optional[Dict[str, Any]] = None, |
| 1105 |
operation_name: Optional[str] = None, |
| 1106 |
field_resolver: Optional[GraphQLFieldResolver] = None, |
| 1107 |
type_resolver: Optional[GraphQLTypeResolver] = None, |
| 1108 |
max_coercion_errors: int = 50, |
| 1109 |
middleware: Optional[Middleware] = None, |
| 1110 |
execution_context_class: Optional[Type["ExecutionContext"]] = None, |
| 1111 |
check_sync: bool = False, |
| 1112 |
) -> ExecutionResult: |
| 1113 |
"""Execute a GraphQL operation synchronously. |
| 1114 |
|
| 1115 |
Also implements the "Executing requests" section of the GraphQL specification. |
| 1116 |
|
| 1117 |
However, it guarantees to complete synchronously (or throw an error) assuming |
| 1118 |
that all field resolvers are also synchronous. |
| 1119 |
|
| 1120 |
Set check_sync to True to still run checks that no awaitable values are returned. |
| 1121 |
""" |
| 1122 |
is_awaitable = ( |
| 1123 |
check_sync |
| 1124 |
if callable(check_sync) |
| 1125 |
else (None if check_sync else assume_not_awaitable) |
| 1126 |
) |
| 1127 |
|
| 1128 |
result = execute( |
| 1129 |
schema, |
| 1130 |
document, |
| 1131 |
root_value, |
| 1132 |
context_value, |
| 1133 |
variable_values, |
| 1134 |
operation_name, |
| 1135 |
field_resolver, |
| 1136 |
type_resolver, |
| 1137 |
None, |
| 1138 |
max_coercion_errors, |
| 1139 |
middleware, |
| 1140 |
execution_context_class, |
| 1141 |
is_awaitable, |
| 1142 |
) |
| 1143 |
|
| 1144 |
# Assert that the execution was synchronous. |
| 1145 |
if isawaitable(result): |
| 1146 |
ensure_future(result).cancel() |
| 1147 |
raise RuntimeError("GraphQL execution failed to complete synchronously.") |
| 1148 |
|
| 1149 |
return result |
| 1150 |
|
| 1151 |
|
| 1152 |
def assert_valid_execution_arguments( |
| 1153 |
schema: GraphQLSchema, |
| 1154 |
document: DocumentNode, |
| 1155 |
raw_variable_values: Optional[Dict[str, Any]] = None, |
| 1156 |
) -> None: |
| 1157 |
"""Check that the arguments are acceptable. |
| 1158 |
|
| 1159 |
Essential assertions before executing to provide developer feedback for improper use |
| 1160 |
of the GraphQL library. |
| 1161 |
|
| 1162 |
For internal use only. |
| 1163 |
""" |
| 1164 |
if not document: |
| 1165 |
raise TypeError("Must provide document.") |
| 1166 |
|
| 1167 |
# If the schema used for execution is invalid, throw an error. |
| 1168 |
assert_valid_schema(schema) |
| 1169 |
|
| 1170 |
# Variables, if provided, must be a dictionary. |
| 1171 |
if not (raw_variable_values is None or isinstance(raw_variable_values, dict)): |
| 1172 |
raise TypeError( |
| 1173 |
"Variable values must be provided as a dictionary" |
| 1174 |
" with variable names as keys. Perhaps look to see" |
| 1175 |
" if an unparsed JSON string was provided." |
| 1176 |
) |
| 1177 |
|
| 1178 |
|
| 1179 |
def get_field_def( |
| 1180 |
schema: GraphQLSchema, parent_type: GraphQLObjectType, field_node: FieldNode |
| 1181 |
) -> GraphQLField: |
| 1182 |
"""Get field definition. |
| 1183 |
|
| 1184 |
This method looks up the field on the given type definition. It has special casing |
| 1185 |
for the three introspection fields, ``__schema``, ``__type`, and ``__typename``. |
| 1186 |
``__typename`` is special because it can always be queried as a field, even in |
| 1187 |
situations where no other fields are allowed, like on a Union. ``__schema`` and |
| 1188 |
``__type`` could get automatically added to the query type, but that would require |
| 1189 |
mutating type definitions, which would cause issues. |
| 1190 |
|
| 1191 |
For internal use only. |
| 1192 |
""" |
| 1193 |
field_name = field_node.name.value |
| 1194 |
|
| 1195 |
if field_name == "__schema" and schema.query_type == parent_type: |
| 1196 |
return SchemaMetaFieldDef |
| 1197 |
elif field_name == "__type" and schema.query_type == parent_type: |
| 1198 |
return TypeMetaFieldDef |
| 1199 |
elif field_name == "__typename": |
| 1200 |
return TypeNameMetaFieldDef |
| 1201 |
return parent_type.fields.get(field_name) |
| 1202 |
|
| 1203 |
|
| 1204 |
def invalid_return_type_error( |
| 1205 |
return_type: GraphQLObjectType, result: Any, field_nodes: List[FieldNode] |
| 1206 |
) -> GraphQLError: |
| 1207 |
"""Create a GraphQLError for an invalid return type.""" |
| 1208 |
return GraphQLError( |
| 1209 |
f"Expected value of type '{return_type.name}' but got: {inspect(result)}.", |
| 1210 |
field_nodes, |
| 1211 |
) |
| 1212 |
|
| 1213 |
|
| 1214 |
def get_typename(value: Any) -> Optional[str]: |
| 1215 |
"""Get the ``__typename`` property of the given value.""" |
| 1216 |
if isinstance(value, Mapping): |
| 1217 |
return value.get("__typename") |
| 1218 |
# need to de-mangle the attribute assumed to be "private" in Python |
| 1219 |
for cls in value.__class__.__mro__: |
| 1220 |
__typename = getattr(value, f"_{cls.__name__}__typename", None) |
| 1221 |
if __typename: |
| 1222 |
return __typename |
| 1223 |
return None |
| 1224 |
|
| 1225 |
|
| 1226 |
def default_type_resolver( |
| 1227 |
value: Any, info: GraphQLResolveInfo, abstract_type: GraphQLAbstractType |
| 1228 |
) -> AwaitableOrValue[Optional[str]]: |
| 1229 |
"""Default type resolver function. |
| 1230 |
|
| 1231 |
If a resolve_type function is not given, then a default resolve behavior is used |
| 1232 |
which attempts two strategies: |
| 1233 |
|
| 1234 |
First, See if the provided value has a ``__typename`` field defined, if so, use that |
| 1235 |
value as name of the resolved type. |
| 1236 |
|
| 1237 |
Otherwise, test each possible type for the abstract type by calling |
| 1238 |
:meth:`~graphql.type.GraphQLObjectType.is_type_of` for the object |
| 1239 |
being coerced, returning the first type that matches. |
| 1240 |
""" |
| 1241 |
# First, look for `__typename`. |
| 1242 |
type_name = get_typename(value) |
| 1243 |
if isinstance(type_name, str): |
| 1244 |
return type_name |
| 1245 |
|
| 1246 |
# Otherwise, test each possible type. |
| 1247 |
possible_types = info.schema.get_possible_types(abstract_type) |
| 1248 |
is_awaitable = info.is_awaitable |
| 1249 |
awaitable_is_type_of_results: List[Awaitable] = [] |
| 1250 |
append_awaitable_results = awaitable_is_type_of_results.append |
| 1251 |
awaitable_types: List[GraphQLObjectType] = [] |
| 1252 |
append_awaitable_types = awaitable_types.append |
| 1253 |
|
| 1254 |
for type_ in possible_types: |
| 1255 |
if type_.is_type_of: |
| 1256 |
is_type_of_result = type_.is_type_of(value, info) |
| 1257 |
|
| 1258 |
if is_awaitable(is_type_of_result): |
| 1259 |
append_awaitable_results(cast(Awaitable, is_type_of_result)) |
| 1260 |
append_awaitable_types(type_) |
| 1261 |
elif is_type_of_result: |
| 1262 |
if awaitable_is_type_of_results: |
| 1263 |
# noinspection PyShadowingNames |
| 1264 |
async def await_is_type_of_and_return_type( |
| 1265 |
resolved_type_name: str = type_.name, |
| 1266 |
) -> str: |
| 1267 |
with suppress(Exception): |
| 1268 |
await gather(*awaitable_is_type_of_results) |
| 1269 |
return resolved_type_name |
| 1270 |
|
| 1271 |
return await_is_type_of_and_return_type() |
| 1272 |
return type_.name |
| 1273 |
|
| 1274 |
if awaitable_is_type_of_results: |
| 1275 |
# noinspection PyShadowingNames |
| 1276 |
async def get_type() -> Optional[str]: |
| 1277 |
is_type_of_results = await gather(*awaitable_is_type_of_results) |
| 1278 |
for is_type_of_result, type_ in zip(is_type_of_results, awaitable_types): |
| 1279 |
if is_type_of_result: |
| 1280 |
return type_.name |
| 1281 |
return None |
| 1282 |
|
| 1283 |
return get_type() |
| 1284 |
|
| 1285 |
return None |
| 1286 |
|
| 1287 |
|
| 1288 |
def default_field_resolver(source: Any, info: GraphQLResolveInfo, **args: Any) -> Any: |
| 1289 |
"""Default field resolver. |
| 1290 |
|
| 1291 |
If a resolve function is not given, then a default resolve behavior is used which |
| 1292 |
takes the property of the source object of the same name as the field and returns |
| 1293 |
it as the result, or if it's a function, returns the result of calling that function |
| 1294 |
while passing along args and context. |
| 1295 |
|
| 1296 |
For dictionaries, the field names are used as keys, for all other objects they are |
| 1297 |
used as attribute names. |
| 1298 |
""" |
| 1299 |
# Ensure source is a value for which property access is acceptable. |
| 1300 |
field_name = info.field_name |
| 1301 |
value = ( |
| 1302 |
source.get(field_name) |
| 1303 |
if isinstance(source, Mapping) |
| 1304 |
else getattr(source, field_name, None) |
| 1305 |
) |
| 1306 |
if callable(value): |
| 1307 |
return value(info, **args) |
| 1308 |
return value |