Skip to content

Add a benchmark to test fetching of many relationships. #49

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

Draft
wants to merge 16 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
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
3 changes: 3 additions & 0 deletions RELEASE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Release type: minor

Adds support for async sessions and deprecates sync sessions due to performance reasons.
164 changes: 147 additions & 17 deletions poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

12 changes: 9 additions & 3 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -40,29 +40,33 @@ version_scheme = "no-guess-dev"

[tool.poetry.dependencies]
python = "^3.8"
sqlalchemy = ">=1.4"
sqlalchemy = {extras = ["asyncio"], version = ">=1.4"}
strawberry-graphql = ">=0.95"
sentinel = ">=0.3,<1.1"
greenlet = {version = ">=3.0.0rc1", python = ">=3.12"}

[tool.poetry.group.dev.dependencies]
"testing.postgresql" = ">=1.3.0"
asgiref = "^3.7.2"
asyncpg = "^0.28.0"
black = ">=22,<24"
importlib-metadata = ">=4.11.1,<7.0.0"
mypy = "1.5.1"
nox = "^2023.4.22"
nox-poetry = "^1.0.2"
packaging = ">=23.1"
pg8000 = ">=1.30.1"
psycopg2 = ">=2.9.7"
psycopg = "^3.1"
pytest = "^7.2"
pytest-asyncio = ">=0.20.3,<0.22.0"
pytest-codspeed = "^2.0.1"
pytest-cov = "^4.0.0"
pytest-emoji = "^0.2.0"
pytest-mock = "^3.11.1"
pytest-mypy-plugins = ">=1.10,<4.0"
pytest-xdist = {extras = ["psutil"], version = "^3.1.0"}
setuptools = ">=67.8.0"
"testing.postgresql" = ">=1.3.0"
sqlalchemy = {extras = ["asyncio"], version = ">=2.0"}

[tool.black]
line-length = 88
Expand Down Expand Up @@ -106,6 +110,8 @@ ignore = [
# we'd want to have consistent docstrings in future
"D",
"ANN001", # missing annotation for function argument self.
"ANN002", # missing annotation for *args.
"ANN003", # missing annotatino for **kwargs.
"ANN101", # missing annotation for self?
# definitely enable these, maybe not in tests
"ANN102",
Expand Down
40 changes: 36 additions & 4 deletions src/strawberry_sqlalchemy_mapper/loader.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import logging
from collections import defaultdict
from typing import Any, Dict, List, Mapping, Tuple, Union
from typing import Any, Callable, Dict, List, Mapping, Optional, Tuple, Union

from sqlalchemy import select, tuple_
from sqlalchemy.engine.base import Connection
from sqlalchemy.ext.asyncio import AsyncConnection, AsyncSession
from sqlalchemy.orm import RelationshipProperty, Session
from strawberry.dataloader import DataLoader

Expand All @@ -14,9 +16,39 @@ class StrawberrySQLAlchemyLoader:

_loaders: Dict[RelationshipProperty, DataLoader]

def __init__(self, bind: Union[Session, Connection]) -> None:
def __init__(
self,
bind: Union[Session, Connection, None] = None,
async_bind_factory: Optional[
Callable[[], Union[AsyncSession, AsyncConnection]]
] = None,
) -> None:
self._loaders = {}
self.bind = bind
self._bind = bind
self._async_bind_factory = async_bind_factory
self._logger = logging.getLogger("strawberry_sqlalchemy_mapper")
if bind is None and async_bind_factory is None:
self._logger.warning(
"One of bind or async_bind_factory must be set for loader to function properly."
)
if bind is not None:
# For anyone coming here because of this warning:
# Making blocking database calls from within an async function (the resolver) has
# catastrophic performance implications. Not only will all resolvers be effectively
# serialized, any other coroutines waiting on the event loop (e.g. concurrent requests
# in a web server), will be blocked as well, grinding your entire service to a halt.
self._logger.warning(
"`bind` parameter is deprecated due to performance issues. Use `async_bind_factory` instead."
)

async def _scalars(self, *args, **kwargs):
if self._async_bind_factory:
async with self._async_bind_factory() as bind:
return await bind.scalars(*args, **kwargs)
else:
# Deprecated, but supported for now.
assert self._bind is not None
return self._bind.scalars(*args, **kwargs)

def loader_for(self, relationship: RelationshipProperty) -> DataLoader:
"""
Expand All @@ -35,7 +67,7 @@ async def load_fn(keys: List[Tuple]) -> List[Any]:
)
if relationship.order_by:
query = query.order_by(*relationship.order_by)
rows = self.bind.scalars(query).all()
rows = (await self._scalars(query)).all()

def group_by_remote_key(row: Any) -> Tuple:
return tuple(
Expand Down
8 changes: 0 additions & 8 deletions tests/benchmarks/test_empty_benchmark.py

This file was deleted.

Loading