Skip to content

feat(async): add support for async sessions #350

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 21 commits into from
Dec 21, 2022
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
32bf439
feat(async): add support for async sessions
May 16, 2022
41c88f9
fix(test batching): ensure that objects are added to database in asyn…
May 16, 2022
47d224e
test: only run batching tests with sync session
May 17, 2022
811cdf2
chore(fields): use get_query instead of manually crafting the query
May 31, 2022
3149830
fix: throw exceptions if Async Session is used with old sql alchemy
May 31, 2022
0e60c03
test: fix sqlalchemy 1.2 and 1.3 tests, fix batching tests by separat…
May 31, 2022
0180f69
fix: ensure that synchronous execute calls are still feasible
Jun 2, 2022
ec76697
refactor: remove duplicate code by fixing if condition
Jun 7, 2022
6a00846
chore: add specific error if awaitable is returned in synchronous exe…
Jun 7, 2022
9897a03
chore: merge master, resolve conflicts
Sep 15, 2022
fff782f
test: use pytest_asyncio.fixture instead normal fixture, fix issues i…
Sep 15, 2022
1250231
chore: remove duplicate eventually_await_session
Oct 7, 2022
eee2314
chore: remove duplicate skip statement
Oct 7, 2022
bacf15d
fix: fix benchmark tests not being executed properly
Oct 7, 2022
2bc6f84
chore: format files
Oct 7, 2022
a968ff8
chore: move is_graphene_version_less_than to top of file
Oct 7, 2022
1039f03
test: remove unnecessary pytest.mark.asyncio, auto-reformatting
Oct 7, 2022
e61df34
chore: revert faulty formatting
Oct 7, 2022
2ff54dc
fix: run startup checkt for sqlalchemy version
Oct 31, 2022
4321b04
chore: rebase onto master, adapt interface test to run with sync sess…
Dec 9, 2022
1e857e0
fix: allow polymorphism with async session
erikwrede Dec 9, 2022
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
42 changes: 28 additions & 14 deletions graphene_sqlalchemy/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
from functools import partial

from promise import Promise, is_thenable
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm.query import Query

from graphene import NonNull
Expand All @@ -11,7 +13,7 @@
from graphql_relay import connection_from_array_slice

from .batching import get_batch_resolver
from .utils import EnumValue, get_query
from .utils import EnumValue, get_query, get_session


class UnsortedSQLAlchemyConnectionField(ConnectionField):
Expand All @@ -26,9 +28,7 @@ def type(self):
assert issubclass(nullable_type, SQLAlchemyObjectType), (
"SQLALchemyConnectionField only accepts SQLAlchemyObjectType types, not {}"
).format(nullable_type.__name__)
assert (
nullable_type.connection
), "The type {} doesn't have a connection".format(
assert nullable_type.connection, "The type {} doesn't have a connection".format(
nullable_type.__name__
)
assert type_ == nullable_type, (
Expand All @@ -46,9 +46,15 @@ def get_query(cls, model, info, **args):
return get_query(model, info.context)

@classmethod
def resolve_connection(cls, connection_type, model, info, args, resolved):
async def resolve_connection(cls, connection_type, model, info, args, resolved):
session = get_session(info.context)
if resolved is None:
resolved = cls.get_query(model, info, **args)
if isinstance(session, AsyncSession):
resolved = (
await session.scalars(cls.get_query(model, info, **args))
).all()
else:
resolved = cls.get_query(model, info, **args)
if isinstance(resolved, Query):
_len = resolved.count()
else:
Expand Down Expand Up @@ -111,7 +117,11 @@ def __init__(self, type_, *args, **kwargs):

@classmethod
def get_query(cls, model, info, sort=None, **args):
query = get_query(model, info.context)
session = get_session(info.context)
if isinstance(session, AsyncSession):
query = select(model)
else:
query = get_query(model, info.context)
if sort is not None:
if not isinstance(sort, list):
sort = [sort]
Expand Down Expand Up @@ -148,7 +158,11 @@ def wrap_resolve(self, parent_resolver):
def from_relationship(cls, relationship, registry, **field_kwargs):
model = relationship.mapper.entity
model_type = registry.get_type_for_model(model)
return cls(model_type.connection, resolver=get_batch_resolver(relationship), **field_kwargs)
return cls(
model_type.connection,
resolver=get_batch_resolver(relationship),
**field_kwargs,
)


def default_connection_field_factory(relationship, registry, **field_kwargs):
Expand All @@ -163,17 +177,17 @@ def default_connection_field_factory(relationship, registry, **field_kwargs):

def createConnectionField(type_, **field_kwargs):
warnings.warn(
'createConnectionField is deprecated and will be removed in the next '
'major version. Use SQLAlchemyObjectType.Meta.connection_field_factory instead.',
"createConnectionField is deprecated and will be removed in the next "
"major version. Use SQLAlchemyObjectType.Meta.connection_field_factory instead.",
DeprecationWarning,
)
return __connectionFactory(type_, **field_kwargs)


def registerConnectionFieldFactory(factoryMethod):
warnings.warn(
'registerConnectionFieldFactory is deprecated and will be removed in the next '
'major version. Use SQLAlchemyObjectType.Meta.connection_field_factory instead.',
"registerConnectionFieldFactory is deprecated and will be removed in the next "
"major version. Use SQLAlchemyObjectType.Meta.connection_field_factory instead.",
DeprecationWarning,
)
global __connectionFactory
Expand All @@ -182,8 +196,8 @@ def registerConnectionFieldFactory(factoryMethod):

def unregisterConnectionFieldFactory():
warnings.warn(
'registerConnectionFieldFactory is deprecated and will be removed in the next '
'major version. Use SQLAlchemyObjectType.Meta.connection_field_factory instead.',
"registerConnectionFieldFactory is deprecated and will be removed in the next "
"major version. Use SQLAlchemyObjectType.Meta.connection_field_factory instead.",
DeprecationWarning,
)
global __connectionFactory
Expand Down
40 changes: 34 additions & 6 deletions graphene_sqlalchemy/tests/conftest.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import pytest
from sqlalchemy import create_engine
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from sqlalchemy.orm import sessionmaker

import graphene
Expand All @@ -8,8 +9,6 @@
from ..registry import reset_global_registry
from .models import Base, CompositeFullName

test_db_url = 'sqlite://' # use in-memory database for tests


@pytest.fixture(autouse=True)
def reset_registry():
Expand All @@ -22,13 +21,42 @@ def convert_composite_class(composite, registry):
return graphene.Field(graphene.Int)


@pytest.fixture(params=[False, True])
def async_session(request):
return request.param


@pytest.fixture
def test_db_url(async_session: bool):
if async_session:
return "sqlite+aiosqlite://"
else:
return "sqlite://"


@pytest.mark.asyncio
@pytest.fixture(scope="function")
def session_factory():
engine = create_engine(test_db_url)
Base.metadata.create_all(engine)
async def session_factory(async_session: bool, test_db_url: str):
if async_session:
engine = create_async_engine(test_db_url)
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all)
yield sessionmaker(bind=engine, class_=AsyncSession, expire_on_commit=False)
await engine.dispose()
else:
engine = create_engine(test_db_url)
Base.metadata.create_all(engine)
yield sessionmaker(bind=engine, expire_on_commit=False)
# SQLite in-memory db is deleted when its connection is closed.
# https://www.sqlite.org/inmemorydb.html
engine.dispose()

yield sessionmaker(bind=engine)

@pytest.fixture(scope="function")
async def sync_session_factory():
engine = create_engine("sqlite://")
Base.metadata.create_all(engine)
yield sessionmaker(bind=engine, expire_on_commit=False)
# SQLite in-memory db is deleted when its connection is closed.
# https://www.sqlite.org/inmemorydb.html
engine.dispose()
Expand Down
34 changes: 23 additions & 11 deletions graphene_sqlalchemy/tests/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@


class HairKind(enum.Enum):
LONG = 'long'
SHORT = 'short'
LONG = "long"
SHORT = "short"


Base = declarative_base()
Expand Down Expand Up @@ -64,9 +64,15 @@ class Reporter(Base):
last_name = Column(String(30), doc="Last name")
email = Column(String(), doc="Email")
favorite_pet_kind = Column(PetKind)
pets = relationship("Pet", secondary=association_table, backref="reporters", order_by="Pet.id")
articles = relationship("Article", backref="reporter")
favorite_article = relationship("Article", uselist=False)
pets = relationship(
"Pet",
secondary=association_table,
backref="reporters",
order_by="Pet.id",
lazy="joined",
)
articles = relationship("Article", backref="reporter", lazy="joined")
favorite_article = relationship("Article", uselist=False, lazy="joined")

@hybrid_property
def hybrid_prop_with_doc(self):
Expand Down Expand Up @@ -137,7 +143,7 @@ class ShoppingCartItem(Base):
id = Column(Integer(), primary_key=True)

@hybrid_property
def hybrid_prop_shopping_cart(self) -> List['ShoppingCart']:
def hybrid_prop_shopping_cart(self) -> List["ShoppingCart"]:
return [ShoppingCart(id=1)]


Expand Down Expand Up @@ -192,11 +198,17 @@ def hybrid_prop_list_date(self) -> List[datetime.date]:

@hybrid_property
def hybrid_prop_nested_list_int(self) -> List[List[int]]:
return [self.hybrid_prop_list_int, ]
return [
self.hybrid_prop_list_int,
]

@hybrid_property
def hybrid_prop_deeply_nested_list_int(self) -> List[List[List[int]]]:
return [[self.hybrid_prop_list_int, ], ]
return [
[
self.hybrid_prop_list_int,
],
]

# Other SQLAlchemy Instances
@hybrid_property
Expand All @@ -216,15 +228,15 @@ def hybrid_prop_unsupported_type_tuple(self) -> Tuple[str, str]:
# Self-references

@hybrid_property
def hybrid_prop_self_referential(self) -> 'ShoppingCart':
def hybrid_prop_self_referential(self) -> "ShoppingCart":
return ShoppingCart(id=1)

@hybrid_property
def hybrid_prop_self_referential_list(self) -> List['ShoppingCart']:
def hybrid_prop_self_referential_list(self) -> List["ShoppingCart"]:
return [ShoppingCart(id=1)]

# Optional[T]

@hybrid_property
def hybrid_prop_optional_self_referential(self) -> Optional['ShoppingCart']:
def hybrid_prop_optional_self_referential(self) -> Optional["ShoppingCart"]:
return None
Loading