We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Use `execute_sync` in `graphql_sync`
`graphql_sync` should use `execute_sync` instead of `execute`.

I run my code in a synchronous context, but a resolver was identified as asynchronous due to the fact that GraphQL core does a simple `hasattr(value, "__await__")` check instead of using `inspect.isawaitable`. This caused a false positive.

However, when using `graphql_sync` I expect that this check does not even happen. Consider using [`execute_sync`](https://github.com/graphql-python/graphql-core/blob/27768d3faac5bb8ebb2c6a151a7192b7fa498f2f/src/graphql/execution/execute.py#L1061) instead.

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `ariadne/graphql.py`
Content:
```
1 from asyncio import ensure_future
2 from inspect import isawaitable
3 from typing import (
4     Any,
5     AsyncGenerator,
6     Awaitable,
7     Collection,
8     List,
9     Optional,
10     Sequence,
11     Type,
12     cast,
13 )
14 
15 from graphql import (
16     DocumentNode,
17     ExecutionContext,
18     ExecutionResult,
19     GraphQLError,
20     GraphQLSchema,
21     TypeInfo,
22     execute,
23     parse,
24     subscribe as _subscribe,
25 )
26 from graphql.execution import MiddlewareManager
27 from graphql.validation import specified_rules, validate
28 from graphql.validation.rules import ASTValidationRule
29 
30 from .extensions import ExtensionManager
31 from .format_error import format_error
32 from .logger import log_error
33 from .types import (
34     ErrorFormatter,
35     ExtensionList,
36     GraphQLResult,
37     RootValue,
38     SubscriptionResult,
39     ValidationRules,
40 )
41 from .validation.introspection_disabled import IntrospectionDisabledRule
42 
43 
44 async def graphql(
45     schema: GraphQLSchema,
46     data: Any,
47     *,
48     context_value: Optional[Any] = None,
49     root_value: Optional[RootValue] = None,
50     debug: bool = False,
51     introspection: bool = True,
52     logger: Optional[str] = None,
53     validation_rules: Optional[ValidationRules] = None,
54     error_formatter: ErrorFormatter = format_error,
55     middleware: Optional[MiddlewareManager] = None,
56     extensions: ExtensionList = None,
57     **kwargs,
58 ) -> GraphQLResult:
59     extension_manager = ExtensionManager(extensions, context_value)
60 
61     with extension_manager.request():
62         try:
63             validate_data(data)
64             query, variables, operation_name = (
65                 data["query"],
66                 data.get("variables"),
67                 data.get("operationName"),
68             )
69 
70             document = parse_query(query)
71 
72             if callable(validation_rules):
73                 validation_rules = cast(
74                     Optional[Collection[Type[ASTValidationRule]]],
75                     validation_rules(context_value, document, data),
76                 )
77 
78             validation_errors = validate_query(
79                 schema, document, validation_rules, enable_introspection=introspection
80             )
81             if validation_errors:
82                 return handle_graphql_errors(
83                     validation_errors,
84                     logger=logger,
85                     error_formatter=error_formatter,
86                     debug=debug,
87                     extension_manager=extension_manager,
88                 )
89 
90             if callable(root_value):
91                 root_value = root_value(context_value, document)
92                 if isawaitable(root_value):
93                     root_value = await root_value
94 
95             result = execute(
96                 schema,
97                 document,
98                 root_value=root_value,
99                 context_value=context_value,
100                 variable_values=variables,
101                 operation_name=operation_name,
102                 execution_context_class=ExecutionContext,
103                 middleware=extension_manager.as_middleware_manager(middleware),
104                 **kwargs,
105             )
106 
107             if isawaitable(result):
108                 result = await cast(Awaitable[ExecutionResult], result)
109         except GraphQLError as error:
110             return handle_graphql_errors(
111                 [error],
112                 logger=logger,
113                 error_formatter=error_formatter,
114                 debug=debug,
115                 extension_manager=extension_manager,
116             )
117         else:
118             return handle_query_result(
119                 result,
120                 logger=logger,
121                 error_formatter=error_formatter,
122                 debug=debug,
123                 extension_manager=extension_manager,
124             )
125 
126 
127 def graphql_sync(
128     schema: GraphQLSchema,
129     data: Any,
130     *,
131     context_value: Optional[Any] = None,
132     root_value: Optional[RootValue] = None,
133     debug: bool = False,
134     introspection: bool = True,
135     logger: Optional[str] = None,
136     validation_rules: Optional[ValidationRules] = None,
137     error_formatter: ErrorFormatter = format_error,
138     middleware: Optional[MiddlewareManager] = None,
139     extensions: ExtensionList = None,
140     **kwargs,
141 ) -> GraphQLResult:
142     extension_manager = ExtensionManager(extensions, context_value)
143 
144     with extension_manager.request():
145         try:
146             validate_data(data)
147             query, variables, operation_name = (
148                 data["query"],
149                 data.get("variables"),
150                 data.get("operationName"),
151             )
152 
153             document = parse_query(query)
154 
155             if callable(validation_rules):
156                 validation_rules = cast(
157                     Optional[Collection[Type[ASTValidationRule]]],
158                     validation_rules(context_value, document, data),
159                 )
160 
161             validation_errors = validate_query(
162                 schema, document, validation_rules, enable_introspection=introspection
163             )
164             if validation_errors:
165                 return handle_graphql_errors(
166                     validation_errors,
167                     logger=logger,
168                     error_formatter=error_formatter,
169                     debug=debug,
170                     extension_manager=extension_manager,
171                 )
172 
173             if callable(root_value):
174                 root_value = root_value(context_value, document)
175                 if isawaitable(root_value):
176                     ensure_future(root_value).cancel()
177                     raise RuntimeError(
178                         "Root value resolver can't be asynchronous "
179                         "in synchronous query executor."
180                     )
181 
182             result = execute(
183                 schema,
184                 document,
185                 root_value=root_value,
186                 context_value=context_value,
187                 variable_values=variables,
188                 operation_name=operation_name,
189                 execution_context_class=ExecutionContext,
190                 middleware=extension_manager.as_middleware_manager(middleware),
191                 **kwargs,
192             )
193 
194             if isawaitable(result):
195                 ensure_future(cast(Awaitable[ExecutionResult], result)).cancel()
196                 raise RuntimeError(
197                     "GraphQL execution failed to complete synchronously."
198                 )
199         except GraphQLError as error:
200             return handle_graphql_errors(
201                 [error],
202                 logger=logger,
203                 error_formatter=error_formatter,
204                 debug=debug,
205                 extension_manager=extension_manager,
206             )
207         else:
208             return handle_query_result(
209                 result,
210                 logger=logger,
211                 error_formatter=error_formatter,
212                 debug=debug,
213                 extension_manager=extension_manager,
214             )
215 
216 
217 async def subscribe(
218     schema: GraphQLSchema,
219     data: Any,
220     *,
221     context_value: Optional[Any] = None,
222     root_value: Optional[RootValue] = None,
223     debug: bool = False,
224     introspection: bool = True,
225     logger: Optional[str] = None,
226     validation_rules: Optional[ValidationRules] = None,
227     error_formatter: ErrorFormatter = format_error,
228     **kwargs,
229 ) -> SubscriptionResult:
230     try:
231         validate_data(data)
232         query, variables, operation_name = (
233             data["query"],
234             data.get("variables"),
235             data.get("operationName"),
236         )
237 
238         document = parse_query(query)
239 
240         if callable(validation_rules):
241             validation_rules = cast(
242                 Optional[Collection[Type[ASTValidationRule]]],
243                 validation_rules(context_value, document, data),
244             )
245 
246         validation_errors = validate_query(
247             schema, document, validation_rules, enable_introspection=introspection
248         )
249         if validation_errors:
250             for error_ in validation_errors:  # mypy issue #5080
251                 log_error(error_, logger)
252             return (
253                 False,
254                 [error_formatter(error, debug) for error in validation_errors],
255             )
256 
257         if callable(root_value):
258             root_value = root_value(context_value, document)
259             if isawaitable(root_value):
260                 root_value = await root_value
261 
262         result = await _subscribe(
263             schema,
264             document,
265             root_value=root_value,
266             context_value=context_value,
267             variable_values=variables,
268             operation_name=operation_name,
269             **kwargs,
270         )
271     except GraphQLError as error:
272         log_error(error, logger)
273         return False, [error_formatter(error, debug)]
274     else:
275         if isinstance(result, ExecutionResult):
276             errors = cast(List[GraphQLError], result.errors)
277             for error_ in errors:  # mypy issue #5080
278                 log_error(error_, logger)
279             return False, [error_formatter(error, debug) for error in errors]
280         return True, cast(AsyncGenerator, result)
281 
282 
283 def handle_query_result(
284     result, *, logger, error_formatter, debug, extension_manager=None
285 ) -> GraphQLResult:
286     response = {"data": result.data}
287     if result.errors:
288         for error in result.errors:
289             log_error(error, logger)
290         response["errors"] = [error_formatter(error, debug) for error in result.errors]
291 
292     if extension_manager:
293         if result.errors:
294             extension_manager.has_errors(result.errors)
295         add_extensions_to_response(extension_manager, response)
296     return True, response
297 
298 
299 def handle_graphql_errors(
300     errors: Sequence[GraphQLError],
301     *,
302     logger,
303     error_formatter,
304     debug,
305     extension_manager=None,
306 ) -> GraphQLResult:
307     for error in errors:
308         log_error(error, logger)
309     response = {"errors": [error_formatter(error, debug) for error in errors]}
310     if extension_manager:
311         extension_manager.has_errors(errors)
312         add_extensions_to_response(extension_manager, response)
313     return False, response
314 
315 
316 def parse_query(query):
317     try:
318         return parse(query)
319     except GraphQLError as error:
320         raise error
321     except Exception as error:
322         raise GraphQLError(str(error), original_error=error) from error
323 
324 
325 def add_extensions_to_response(extension_manager: ExtensionManager, response: dict):
326     formatted_extensions = extension_manager.format()
327     if formatted_extensions:
328         if "extensions" in response:
329             response["extensions"].update(formatted_extensions)
330         else:
331             response["extensions"] = formatted_extensions
332 
333 
334 def validate_query(
335     schema: GraphQLSchema,
336     document_ast: DocumentNode,
337     rules: Optional[Collection[Type[ASTValidationRule]]] = None,
338     max_errors: Optional[int] = None,
339     type_info: Optional[TypeInfo] = None,
340     enable_introspection: bool = True,
341 ) -> List[GraphQLError]:
342     if not enable_introspection:
343         rules = (
344             tuple(rules) + (IntrospectionDisabledRule,)
345             if rules is not None
346             else (IntrospectionDisabledRule,)
347         )
348     if rules:
349         # run validation against rules from spec and custom rules
350         supplemented_rules = specified_rules + tuple(rules)
351         return validate(
352             schema,
353             document_ast,
354             rules=supplemented_rules,
355             max_errors=max_errors,
356             type_info=type_info,
357         )
358     # run validation using spec rules only
359     return validate(schema, document_ast, rules=specified_rules, type_info=type_info)
360 
361 
362 def validate_data(data: Optional[dict]) -> None:
363     if not isinstance(data, dict):
364         raise GraphQLError("Operation data should be a JSON object")
365     validate_query_body(data.get("query"))
366     validate_variables(data.get("variables"))
367     validate_operation_name(data.get("operationName"))
368 
369 
370 def validate_query_body(query) -> None:
371     if not query or not isinstance(query, str):
372         raise GraphQLError("The query must be a string.")
373 
374 
375 def validate_variables(variables) -> None:
376     if variables is not None and not isinstance(variables, dict):
377         raise GraphQLError("Query variables must be a null or an object.")
378 
379 
380 def validate_operation_name(operation_name) -> None:
381     if operation_name is not None and not isinstance(operation_name, str):
382         raise GraphQLError('"%s" is not a valid operation name.' % operation_name)
383
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/ariadne/graphql.py b/ariadne/graphql.py
--- a/ariadne/graphql.py
+++ b/ariadne/graphql.py
@@ -20,6 +20,7 @@
     GraphQLSchema,
     TypeInfo,
     execute,
+    execute_sync,
     parse,
     subscribe as _subscribe,
 )
@@ -179,7 +180,7 @@
                         "in synchronous query executor."
                     )
 
-            result = execute(
+            result = execute_sync(
                 schema,
                 document,
                 root_value=root_value,

{"golden_diff": "diff --git a/ariadne/graphql.py b/ariadne/graphql.py\n--- a/ariadne/graphql.py\n+++ b/ariadne/graphql.py\n@@ -20,6 +20,7 @@\n     GraphQLSchema,\n     TypeInfo,\n     execute,\n+    execute_sync,\n     parse,\n     subscribe as _subscribe,\n )\n@@ -179,7 +180,7 @@\n                         \"in synchronous query executor.\"\n                     )\n \n-            result = execute(\n+            result = execute_sync(\n                 schema,\n                 document,\n                 root_value=root_value,\n", "issue": "Use `execute_sync` in `graphql_sync`\n`graphql_sync` should use `execute_sync` instead of `execute`.\r\n\r\nI run my code in a synchronous context, but a resolver was identified as asynchronous due to the fact that GraphQL core does a simple `hasattr(value, \"__await__\")` check instead of using `inspect.isawaitable`. This caused a false positive.\r\n\r\nHowever, when using `graphql_sync` I expect that this check does not even happen. Consider using [`execute_sync`](https://github.com/graphql-python/graphql-core/blob/27768d3faac5bb8ebb2c6a151a7192b7fa498f2f/src/graphql/execution/execute.py#L1061) instead.\n", "before_files": [{"content": "from asyncio import ensure_future\nfrom inspect import isawaitable\nfrom typing import (\n    Any,\n    AsyncGenerator,\n    Awaitable,\n    Collection,\n    List,\n    Optional,\n    Sequence,\n    Type,\n    cast,\n)\n\nfrom graphql import (\n    DocumentNode,\n    ExecutionContext,\n    ExecutionResult,\n    GraphQLError,\n    GraphQLSchema,\n    TypeInfo,\n    execute,\n    parse,\n    subscribe as _subscribe,\n)\nfrom graphql.execution import MiddlewareManager\nfrom graphql.validation import specified_rules, validate\nfrom graphql.validation.rules import ASTValidationRule\n\nfrom .extensions import ExtensionManager\nfrom .format_error import format_error\nfrom .logger import log_error\nfrom .types import (\n    ErrorFormatter,\n    ExtensionList,\n    GraphQLResult,\n    RootValue,\n    SubscriptionResult,\n    ValidationRules,\n)\nfrom .validation.introspection_disabled import IntrospectionDisabledRule\n\n\nasync def graphql(\n    schema: GraphQLSchema,\n    data: Any,\n    *,\n    context_value: Optional[Any] = None,\n    root_value: Optional[RootValue] = None,\n    debug: bool = False,\n    introspection: bool = True,\n    logger: Optional[str] = None,\n    validation_rules: Optional[ValidationRules] = None,\n    error_formatter: ErrorFormatter = format_error,\n    middleware: Optional[MiddlewareManager] = None,\n    extensions: ExtensionList = None,\n    **kwargs,\n) -> GraphQLResult:\n    extension_manager = ExtensionManager(extensions, context_value)\n\n    with extension_manager.request():\n        try:\n            validate_data(data)\n            query, variables, operation_name = (\n                data[\"query\"],\n                data.get(\"variables\"),\n                data.get(\"operationName\"),\n            )\n\n            document = parse_query(query)\n\n            if callable(validation_rules):\n                validation_rules = cast(\n                    Optional[Collection[Type[ASTValidationRule]]],\n                    validation_rules(context_value, document, data),\n                )\n\n            validation_errors = validate_query(\n                schema, document, validation_rules, enable_introspection=introspection\n            )\n            if validation_errors:\n                return handle_graphql_errors(\n                    validation_errors,\n                    logger=logger,\n                    error_formatter=error_formatter,\n                    debug=debug,\n                    extension_manager=extension_manager,\n                )\n\n            if callable(root_value):\n                root_value = root_value(context_value, document)\n                if isawaitable(root_value):\n                    root_value = await root_value\n\n            result = execute(\n                schema,\n                document,\n                root_value=root_value,\n                context_value=context_value,\n                variable_values=variables,\n                operation_name=operation_name,\n                execution_context_class=ExecutionContext,\n                middleware=extension_manager.as_middleware_manager(middleware),\n                **kwargs,\n            )\n\n            if isawaitable(result):\n                result = await cast(Awaitable[ExecutionResult], result)\n        except GraphQLError as error:\n            return handle_graphql_errors(\n                [error],\n                logger=logger,\n                error_formatter=error_formatter,\n                debug=debug,\n                extension_manager=extension_manager,\n            )\n        else:\n            return handle_query_result(\n                result,\n                logger=logger,\n                error_formatter=error_formatter,\n                debug=debug,\n                extension_manager=extension_manager,\n            )\n\n\ndef graphql_sync(\n    schema: GraphQLSchema,\n    data: Any,\n    *,\n    context_value: Optional[Any] = None,\n    root_value: Optional[RootValue] = None,\n    debug: bool = False,\n    introspection: bool = True,\n    logger: Optional[str] = None,\n    validation_rules: Optional[ValidationRules] = None,\n    error_formatter: ErrorFormatter = format_error,\n    middleware: Optional[MiddlewareManager] = None,\n    extensions: ExtensionList = None,\n    **kwargs,\n) -> GraphQLResult:\n    extension_manager = ExtensionManager(extensions, context_value)\n\n    with extension_manager.request():\n        try:\n            validate_data(data)\n            query, variables, operation_name = (\n                data[\"query\"],\n                data.get(\"variables\"),\n                data.get(\"operationName\"),\n            )\n\n            document = parse_query(query)\n\n            if callable(validation_rules):\n                validation_rules = cast(\n                    Optional[Collection[Type[ASTValidationRule]]],\n                    validation_rules(context_value, document, data),\n                )\n\n            validation_errors = validate_query(\n                schema, document, validation_rules, enable_introspection=introspection\n            )\n            if validation_errors:\n                return handle_graphql_errors(\n                    validation_errors,\n                    logger=logger,\n                    error_formatter=error_formatter,\n                    debug=debug,\n                    extension_manager=extension_manager,\n                )\n\n            if callable(root_value):\n                root_value = root_value(context_value, document)\n                if isawaitable(root_value):\n                    ensure_future(root_value).cancel()\n                    raise RuntimeError(\n                        \"Root value resolver can't be asynchronous \"\n                        \"in synchronous query executor.\"\n                    )\n\n            result = execute(\n                schema,\n                document,\n                root_value=root_value,\n                context_value=context_value,\n                variable_values=variables,\n                operation_name=operation_name,\n                execution_context_class=ExecutionContext,\n                middleware=extension_manager.as_middleware_manager(middleware),\n                **kwargs,\n            )\n\n            if isawaitable(result):\n                ensure_future(cast(Awaitable[ExecutionResult], result)).cancel()\n                raise RuntimeError(\n                    \"GraphQL execution failed to complete synchronously.\"\n                )\n        except GraphQLError as error:\n            return handle_graphql_errors(\n                [error],\n                logger=logger,\n                error_formatter=error_formatter,\n                debug=debug,\n                extension_manager=extension_manager,\n            )\n        else:\n            return handle_query_result(\n                result,\n                logger=logger,\n                error_formatter=error_formatter,\n                debug=debug,\n                extension_manager=extension_manager,\n            )\n\n\nasync def subscribe(\n    schema: GraphQLSchema,\n    data: Any,\n    *,\n    context_value: Optional[Any] = None,\n    root_value: Optional[RootValue] = None,\n    debug: bool = False,\n    introspection: bool = True,\n    logger: Optional[str] = None,\n    validation_rules: Optional[ValidationRules] = None,\n    error_formatter: ErrorFormatter = format_error,\n    **kwargs,\n) -> SubscriptionResult:\n    try:\n        validate_data(data)\n        query, variables, operation_name = (\n            data[\"query\"],\n            data.get(\"variables\"),\n            data.get(\"operationName\"),\n        )\n\n        document = parse_query(query)\n\n        if callable(validation_rules):\n            validation_rules = cast(\n                Optional[Collection[Type[ASTValidationRule]]],\n                validation_rules(context_value, document, data),\n            )\n\n        validation_errors = validate_query(\n            schema, document, validation_rules, enable_introspection=introspection\n        )\n        if validation_errors:\n            for error_ in validation_errors:  # mypy issue #5080\n                log_error(error_, logger)\n            return (\n                False,\n                [error_formatter(error, debug) for error in validation_errors],\n            )\n\n        if callable(root_value):\n            root_value = root_value(context_value, document)\n            if isawaitable(root_value):\n                root_value = await root_value\n\n        result = await _subscribe(\n            schema,\n            document,\n            root_value=root_value,\n            context_value=context_value,\n            variable_values=variables,\n            operation_name=operation_name,\n            **kwargs,\n        )\n    except GraphQLError as error:\n        log_error(error, logger)\n        return False, [error_formatter(error, debug)]\n    else:\n        if isinstance(result, ExecutionResult):\n            errors = cast(List[GraphQLError], result.errors)\n            for error_ in errors:  # mypy issue #5080\n                log_error(error_, logger)\n            return False, [error_formatter(error, debug) for error in errors]\n        return True, cast(AsyncGenerator, result)\n\n\ndef handle_query_result(\n    result, *, logger, error_formatter, debug, extension_manager=None\n) -> GraphQLResult:\n    response = {\"data\": result.data}\n    if result.errors:\n        for error in result.errors:\n            log_error(error, logger)\n        response[\"errors\"] = [error_formatter(error, debug) for error in result.errors]\n\n    if extension_manager:\n        if result.errors:\n            extension_manager.has_errors(result.errors)\n        add_extensions_to_response(extension_manager, response)\n    return True, response\n\n\ndef handle_graphql_errors(\n    errors: Sequence[GraphQLError],\n    *,\n    logger,\n    error_formatter,\n    debug,\n    extension_manager=None,\n) -> GraphQLResult:\n    for error in errors:\n        log_error(error, logger)\n    response = {\"errors\": [error_formatter(error, debug) for error in errors]}\n    if extension_manager:\n        extension_manager.has_errors(errors)\n        add_extensions_to_response(extension_manager, response)\n    return False, response\n\n\ndef parse_query(query):\n    try:\n        return parse(query)\n    except GraphQLError as error:\n        raise error\n    except Exception as error:\n        raise GraphQLError(str(error), original_error=error) from error\n\n\ndef add_extensions_to_response(extension_manager: ExtensionManager, response: dict):\n    formatted_extensions = extension_manager.format()\n    if formatted_extensions:\n        if \"extensions\" in response:\n            response[\"extensions\"].update(formatted_extensions)\n        else:\n            response[\"extensions\"] = formatted_extensions\n\n\ndef validate_query(\n    schema: GraphQLSchema,\n    document_ast: DocumentNode,\n    rules: Optional[Collection[Type[ASTValidationRule]]] = None,\n    max_errors: Optional[int] = None,\n    type_info: Optional[TypeInfo] = None,\n    enable_introspection: bool = True,\n) -> List[GraphQLError]:\n    if not enable_introspection:\n        rules = (\n            tuple(rules) + (IntrospectionDisabledRule,)\n            if rules is not None\n            else (IntrospectionDisabledRule,)\n        )\n    if rules:\n        # run validation against rules from spec and custom rules\n        supplemented_rules = specified_rules + tuple(rules)\n        return validate(\n            schema,\n            document_ast,\n            rules=supplemented_rules,\n            max_errors=max_errors,\n            type_info=type_info,\n        )\n    # run validation using spec rules only\n    return validate(schema, document_ast, rules=specified_rules, type_info=type_info)\n\n\ndef validate_data(data: Optional[dict]) -> None:\n    if not isinstance(data, dict):\n        raise GraphQLError(\"Operation data should be a JSON object\")\n    validate_query_body(data.get(\"query\"))\n    validate_variables(data.get(\"variables\"))\n    validate_operation_name(data.get(\"operationName\"))\n\n\ndef validate_query_body(query) -> None:\n    if not query or not isinstance(query, str):\n        raise GraphQLError(\"The query must be a string.\")\n\n\ndef validate_variables(variables) -> None:\n    if variables is not None and not isinstance(variables, dict):\n        raise GraphQLError(\"Query variables must be a null or an object.\")\n\n\ndef validate_operation_name(operation_name) -> None:\n    if operation_name is not None and not isinstance(operation_name, str):\n        raise GraphQLError('\"%s\" is not a valid operation name.' % operation_name)\n", "path": "ariadne/graphql.py"}], "after_files": [{"content": "from asyncio import ensure_future\nfrom inspect import isawaitable\nfrom typing import (\n    Any,\n    AsyncGenerator,\n    Awaitable,\n    Collection,\n    List,\n    Optional,\n    Sequence,\n    Type,\n    cast,\n)\n\nfrom graphql import (\n    DocumentNode,\n    ExecutionContext,\n    ExecutionResult,\n    GraphQLError,\n    GraphQLSchema,\n    TypeInfo,\n    execute,\n    execute_sync,\n    parse,\n    subscribe as _subscribe,\n)\nfrom graphql.execution import MiddlewareManager\nfrom graphql.validation import specified_rules, validate\nfrom graphql.validation.rules import ASTValidationRule\n\nfrom .extensions import ExtensionManager\nfrom .format_error import format_error\nfrom .logger import log_error\nfrom .types import (\n    ErrorFormatter,\n    ExtensionList,\n    GraphQLResult,\n    RootValue,\n    SubscriptionResult,\n    ValidationRules,\n)\nfrom .validation.introspection_disabled import IntrospectionDisabledRule\n\n\nasync def graphql(\n    schema: GraphQLSchema,\n    data: Any,\n    *,\n    context_value: Optional[Any] = None,\n    root_value: Optional[RootValue] = None,\n    debug: bool = False,\n    introspection: bool = True,\n    logger: Optional[str] = None,\n    validation_rules: Optional[ValidationRules] = None,\n    error_formatter: ErrorFormatter = format_error,\n    middleware: Optional[MiddlewareManager] = None,\n    extensions: ExtensionList = None,\n    **kwargs,\n) -> GraphQLResult:\n    extension_manager = ExtensionManager(extensions, context_value)\n\n    with extension_manager.request():\n        try:\n            validate_data(data)\n            query, variables, operation_name = (\n                data[\"query\"],\n                data.get(\"variables\"),\n                data.get(\"operationName\"),\n            )\n\n            document = parse_query(query)\n\n            if callable(validation_rules):\n                validation_rules = cast(\n                    Optional[Collection[Type[ASTValidationRule]]],\n                    validation_rules(context_value, document, data),\n                )\n\n            validation_errors = validate_query(\n                schema, document, validation_rules, enable_introspection=introspection\n            )\n            if validation_errors:\n                return handle_graphql_errors(\n                    validation_errors,\n                    logger=logger,\n                    error_formatter=error_formatter,\n                    debug=debug,\n                    extension_manager=extension_manager,\n                )\n\n            if callable(root_value):\n                root_value = root_value(context_value, document)\n                if isawaitable(root_value):\n                    root_value = await root_value\n\n            result = execute(\n                schema,\n                document,\n                root_value=root_value,\n                context_value=context_value,\n                variable_values=variables,\n                operation_name=operation_name,\n                execution_context_class=ExecutionContext,\n                middleware=extension_manager.as_middleware_manager(middleware),\n                **kwargs,\n            )\n\n            if isawaitable(result):\n                result = await cast(Awaitable[ExecutionResult], result)\n        except GraphQLError as error:\n            return handle_graphql_errors(\n                [error],\n                logger=logger,\n                error_formatter=error_formatter,\n                debug=debug,\n                extension_manager=extension_manager,\n            )\n        else:\n            return handle_query_result(\n                result,\n                logger=logger,\n                error_formatter=error_formatter,\n                debug=debug,\n                extension_manager=extension_manager,\n            )\n\n\ndef graphql_sync(\n    schema: GraphQLSchema,\n    data: Any,\n    *,\n    context_value: Optional[Any] = None,\n    root_value: Optional[RootValue] = None,\n    debug: bool = False,\n    introspection: bool = True,\n    logger: Optional[str] = None,\n    validation_rules: Optional[ValidationRules] = None,\n    error_formatter: ErrorFormatter = format_error,\n    middleware: Optional[MiddlewareManager] = None,\n    extensions: ExtensionList = None,\n    **kwargs,\n) -> GraphQLResult:\n    extension_manager = ExtensionManager(extensions, context_value)\n\n    with extension_manager.request():\n        try:\n            validate_data(data)\n            query, variables, operation_name = (\n                data[\"query\"],\n                data.get(\"variables\"),\n                data.get(\"operationName\"),\n            )\n\n            document = parse_query(query)\n\n            if callable(validation_rules):\n                validation_rules = cast(\n                    Optional[Collection[Type[ASTValidationRule]]],\n                    validation_rules(context_value, document, data),\n                )\n\n            validation_errors = validate_query(\n                schema, document, validation_rules, enable_introspection=introspection\n            )\n            if validation_errors:\n                return handle_graphql_errors(\n                    validation_errors,\n                    logger=logger,\n                    error_formatter=error_formatter,\n                    debug=debug,\n                    extension_manager=extension_manager,\n                )\n\n            if callable(root_value):\n                root_value = root_value(context_value, document)\n                if isawaitable(root_value):\n                    ensure_future(root_value).cancel()\n                    raise RuntimeError(\n                        \"Root value resolver can't be asynchronous \"\n                        \"in synchronous query executor.\"\n                    )\n\n            result = execute_sync(\n                schema,\n                document,\n                root_value=root_value,\n                context_value=context_value,\n                variable_values=variables,\n                operation_name=operation_name,\n                execution_context_class=ExecutionContext,\n                middleware=extension_manager.as_middleware_manager(middleware),\n                **kwargs,\n            )\n\n            if isawaitable(result):\n                ensure_future(cast(Awaitable[ExecutionResult], result)).cancel()\n                raise RuntimeError(\n                    \"GraphQL execution failed to complete synchronously.\"\n                )\n        except GraphQLError as error:\n            return handle_graphql_errors(\n                [error],\n                logger=logger,\n                error_formatter=error_formatter,\n                debug=debug,\n                extension_manager=extension_manager,\n            )\n        else:\n            return handle_query_result(\n                result,\n                logger=logger,\n                error_formatter=error_formatter,\n                debug=debug,\n                extension_manager=extension_manager,\n            )\n\n\nasync def subscribe(\n    schema: GraphQLSchema,\n    data: Any,\n    *,\n    context_value: Optional[Any] = None,\n    root_value: Optional[RootValue] = None,\n    debug: bool = False,\n    introspection: bool = True,\n    logger: Optional[str] = None,\n    validation_rules: Optional[ValidationRules] = None,\n    error_formatter: ErrorFormatter = format_error,\n    **kwargs,\n) -> SubscriptionResult:\n    try:\n        validate_data(data)\n        query, variables, operation_name = (\n            data[\"query\"],\n            data.get(\"variables\"),\n            data.get(\"operationName\"),\n        )\n\n        document = parse_query(query)\n\n        if callable(validation_rules):\n            validation_rules = cast(\n                Optional[Collection[Type[ASTValidationRule]]],\n                validation_rules(context_value, document, data),\n            )\n\n        validation_errors = validate_query(\n            schema, document, validation_rules, enable_introspection=introspection\n        )\n        if validation_errors:\n            for error_ in validation_errors:  # mypy issue #5080\n                log_error(error_, logger)\n            return (\n                False,\n                [error_formatter(error, debug) for error in validation_errors],\n            )\n\n        if callable(root_value):\n            root_value = root_value(context_value, document)\n            if isawaitable(root_value):\n                root_value = await root_value\n\n        result = await _subscribe(\n            schema,\n            document,\n            root_value=root_value,\n            context_value=context_value,\n            variable_values=variables,\n            operation_name=operation_name,\n            **kwargs,\n        )\n    except GraphQLError as error:\n        log_error(error, logger)\n        return False, [error_formatter(error, debug)]\n    else:\n        if isinstance(result, ExecutionResult):\n            errors = cast(List[GraphQLError], result.errors)\n            for error_ in errors:  # mypy issue #5080\n                log_error(error_, logger)\n            return False, [error_formatter(error, debug) for error in errors]\n        return True, cast(AsyncGenerator, result)\n\n\ndef handle_query_result(\n    result, *, logger, error_formatter, debug, extension_manager=None\n) -> GraphQLResult:\n    response = {\"data\": result.data}\n    if result.errors:\n        for error in result.errors:\n            log_error(error, logger)\n        response[\"errors\"] = [error_formatter(error, debug) for error in result.errors]\n\n    if extension_manager:\n        if result.errors:\n            extension_manager.has_errors(result.errors)\n        add_extensions_to_response(extension_manager, response)\n    return True, response\n\n\ndef handle_graphql_errors(\n    errors: Sequence[GraphQLError],\n    *,\n    logger,\n    error_formatter,\n    debug,\n    extension_manager=None,\n) -> GraphQLResult:\n    for error in errors:\n        log_error(error, logger)\n    response = {\"errors\": [error_formatter(error, debug) for error in errors]}\n    if extension_manager:\n        extension_manager.has_errors(errors)\n        add_extensions_to_response(extension_manager, response)\n    return False, response\n\n\ndef parse_query(query):\n    try:\n        return parse(query)\n    except GraphQLError as error:\n        raise error\n    except Exception as error:\n        raise GraphQLError(str(error), original_error=error) from error\n\n\ndef add_extensions_to_response(extension_manager: ExtensionManager, response: dict):\n    formatted_extensions = extension_manager.format()\n    if formatted_extensions:\n        if \"extensions\" in response:\n            response[\"extensions\"].update(formatted_extensions)\n        else:\n            response[\"extensions\"] = formatted_extensions\n\n\ndef validate_query(\n    schema: GraphQLSchema,\n    document_ast: DocumentNode,\n    rules: Optional[Collection[Type[ASTValidationRule]]] = None,\n    max_errors: Optional[int] = None,\n    type_info: Optional[TypeInfo] = None,\n    enable_introspection: bool = True,\n) -> List[GraphQLError]:\n    if not enable_introspection:\n        rules = (\n            tuple(rules) + (IntrospectionDisabledRule,)\n            if rules is not None\n            else (IntrospectionDisabledRule,)\n        )\n    if rules:\n        # run validation against rules from spec and custom rules\n        supplemented_rules = specified_rules + tuple(rules)\n        return validate(\n            schema,\n            document_ast,\n            rules=supplemented_rules,\n            max_errors=max_errors,\n            type_info=type_info,\n        )\n    # run validation using spec rules only\n    return validate(schema, document_ast, rules=specified_rules, type_info=type_info)\n\n\ndef validate_data(data: Optional[dict]) -> None:\n    if not isinstance(data, dict):\n        raise GraphQLError(\"Operation data should be a JSON object\")\n    validate_query_body(data.get(\"query\"))\n    validate_variables(data.get(\"variables\"))\n    validate_operation_name(data.get(\"operationName\"))\n\n\ndef validate_query_body(query) -> None:\n    if not query or not isinstance(query, str):\n        raise GraphQLError(\"The query must be a string.\")\n\n\ndef validate_variables(variables) -> None:\n    if variables is not None and not isinstance(variables, dict):\n        raise GraphQLError(\"Query variables must be a null or an object.\")\n\n\ndef validate_operation_name(operation_name) -> None:\n    if operation_name is not None and not isinstance(operation_name, str):\n        raise GraphQLError('\"%s\" is not a valid operation name.' % operation_name)\n", "path": "ariadne/graphql.py"}]}