1111from typing import TYPE_CHECKING , Any , Optional , Tuple , Union , overload
1212
1313from sqlalchemy import func , select
14- from sqlalchemy .orm import Query , Session , noload
14+ from sqlalchemy .orm import Query , Session , noload , scoped_session
1515from typing_extensions import TypeAlias
1616
1717from ..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+
4049try :
4150 from sqlakeyset import paging
4251except 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
5059def paginate_query (query : Select , params : AbstractParams ) -> Select :
@@ -127,6 +136,9 @@ def _apply_items_transformer(*args: Any, **kwargs: Any) -> Any:
127136
128137
129138def _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