Skip to content

Use Graphene DataLoader in graphene>=3.1.1 #360

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Sep 8, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 19 additions & 2 deletions graphene_sqlalchemy/batching.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,30 @@
"""The dataloader uses "select in loading" strategy to load related entities."""
from typing import Any

import aiodataloader
import sqlalchemy
from sqlalchemy.orm import Session, strategies
from sqlalchemy.orm.query import QueryContext

from .utils import is_sqlalchemy_version_less_than
from .utils import (is_graphene_version_less_than,
is_sqlalchemy_version_less_than)


def get_batch_resolver(relationship_prop):
def get_data_loader_impl() -> Any:
"""Graphene >= 3.1.1 ships a copy of aiodataloader with minor fixes. To preserve backward-compatibility,
aiodataloader is used in conjunction with older versions of graphene"""
if is_graphene_version_less_than("3.1.1"):
from aiodataloader import DataLoader
else:
from graphene.utils.dataloader import DataLoader

return DataLoader


DataLoader = get_data_loader_impl()


def get_batch_resolver(relationship_prop):
# Cache this across `batch_load_fn` calls
# This is so SQL string generation is cached under-the-hood via `bakery`
selectin_loader = strategies.SelectInLoader(relationship_prop, (('lazy', 'selectin'),))
Expand Down
7 changes: 7 additions & 0 deletions graphene_sqlalchemy/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,11 @@ def is_sqlalchemy_version_less_than(version_string):
return pkg_resources.get_distribution('SQLAlchemy').parsed_version < pkg_resources.parse_version(version_string)


def is_graphene_version_less_than(version_string):
"""Check the installed graphene version"""
return pkg_resources.get_distribution('graphene').parsed_version < pkg_resources.parse_version(version_string)


class singledispatchbymatchfunction:
"""
Inspired by @singledispatch, this is a variant that works using a matcher function
Expand Down Expand Up @@ -197,6 +202,7 @@ def safe_isinstance_checker(arg):
return isinstance(arg, cls)
except TypeError:
pass

return safe_isinstance_checker


Expand All @@ -210,5 +216,6 @@ def registry_sqlalchemy_model_from_str(model_name: str) -> Optional[Any]:

class DummyImport:
"""The dummy module returns 'object' for a query for any member"""

def __getattr__(self, name):
return object