Skip to content

Commit fd1f0e8

Browse files
authored
Add ability to use async_scoped_session (#877)
1 parent 5db4ee7 commit fd1f0e8

File tree

1 file changed

+15
-3
lines changed

1 file changed

+15
-3
lines changed

fastapi_pagination/ext/sqlalchemy.py

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
from typing import TYPE_CHECKING, Any, Optional, Tuple, Union, overload
1212

1313
from sqlalchemy import func, select
14-
from sqlalchemy.orm import Query, Session, noload
14+
from sqlalchemy.orm import Query, Session, noload, scoped_session
1515
from typing_extensions import TypeAlias
1616

1717
from ..api import apply_items_transformer, create_page
@@ -37,14 +37,23 @@ def await_only(*_: Any, **__: Any) -> Any: # type: ignore
3737
raise ImportError("sqlalchemy.util.await_only is not available")
3838

3939

40+
try:
41+
from sqlalchemy.ext.asyncio import async_scoped_session
42+
except ImportError: # pragma: no cover
43+
44+
class async_scoped_session: # type: ignore
45+
def __init__(self, *_: Any, **__: Any) -> None:
46+
raise ImportError("sqlalchemy.ext.asyncio is not available")
47+
48+
4049
try:
4150
from sqlakeyset import paging
4251
except ImportError: # pragma: no cover
4352
paging = None
4453

4554

46-
AsyncConn: TypeAlias = "Union[AsyncSession, AsyncConnection]"
47-
SyncConn: TypeAlias = "Union[Session, Connection]"
55+
AsyncConn: TypeAlias = "Union[AsyncSession, AsyncConnection, async_scoped_session]"
56+
SyncConn: TypeAlias = "Union[Session, Connection, scoped_session]"
4857

4958

5059
def paginate_query(query: Select, params: AbstractParams) -> Select:
@@ -127,6 +136,9 @@ def _apply_items_transformer(*args: Any, **kwargs: Any) -> Any:
127136

128137

129138
def _get_sync_conn_from_async(conn: Any) -> SyncConn: # pragma: no cover
139+
if isinstance(conn, async_scoped_session):
140+
conn = conn()
141+
130142
with suppress(AttributeError):
131143
return conn.sync_session # type: ignore
132144

0 commit comments

Comments
 (0)