|
| 1 | +import asyncio |
| 2 | +from asyncio import Task |
1 | 3 | from contextvars import ContextVar |
2 | 4 | from typing import Dict, Optional, Union |
3 | 5 |
|
4 | 6 | from sqlalchemy.engine import Engine |
5 | 7 | from sqlalchemy.engine.url import URL |
6 | | -from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine |
| 8 | +from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine |
7 | 9 | from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint |
8 | 10 | from starlette.requests import Request |
9 | 11 | from starlette.types import ASGIApp |
10 | 12 |
|
11 | 13 | from fastapi_async_sqlalchemy.exceptions import MissingSessionError, SessionNotInitialisedError |
12 | 14 |
|
13 | 15 | try: |
14 | | - from sqlalchemy.ext.asyncio import async_sessionmaker |
| 16 | + from sqlalchemy.ext.asyncio import async_sessionmaker # noqa: F811 |
15 | 17 | except ImportError: |
16 | 18 | from sqlalchemy.orm import sessionmaker as async_sessionmaker |
17 | 19 |
|
18 | 20 |
|
19 | 21 | def create_middleware_and_session_proxy(): |
20 | 22 | _Session: Optional[async_sessionmaker] = None |
| 23 | + _session: ContextVar[Optional[AsyncSession]] = ContextVar("_session", default=None) |
| 24 | + _multi_sessions_ctx: ContextVar[bool] = ContextVar("_multi_sessions_context", default=False) |
| 25 | + _commit_on_exit_ctx: ContextVar[bool] = ContextVar("_commit_on_exit_ctx", default=False) |
21 | 26 | # Usage of context vars inside closures is not recommended, since they are not properly |
22 | 27 | # garbage collected, but in our use case context var is created on program startup and |
23 | 28 | # is used throughout the whole its lifecycle. |
24 | | - _session: ContextVar[Optional[AsyncSession]] = ContextVar("_session", default=None) |
25 | 29 |
|
26 | 30 | class SQLAlchemyMiddleware(BaseHTTPMiddleware): |
27 | 31 | def __init__( |
@@ -61,38 +65,97 @@ def session(self) -> AsyncSession: |
61 | 65 | if _Session is None: |
62 | 66 | raise SessionNotInitialisedError |
63 | 67 |
|
64 | | - session = _session.get() |
65 | | - if session is None: |
66 | | - raise MissingSessionError |
67 | | - |
68 | | - return session |
| 68 | + multi_sessions = _multi_sessions_ctx.get() |
| 69 | + if multi_sessions: |
| 70 | + """In this case, we need to create a new session for each task. |
| 71 | + We also need to commit the session on exit if commit_on_exit is True. |
| 72 | + This is useful when we need to run multiple queries in parallel. |
| 73 | + For example, when we need to run multiple queries in parallel in a route handler. |
| 74 | + Example: |
| 75 | + ```python |
| 76 | + async with db(multi_sessions=True): |
| 77 | + async def execute_query(query): |
| 78 | + return await db.session.execute(text(query)) |
| 79 | +
|
| 80 | + tasks = [ |
| 81 | + asyncio.create_task(execute_query("SELECT 1")), |
| 82 | + asyncio.create_task(execute_query("SELECT 2")), |
| 83 | + asyncio.create_task(execute_query("SELECT 3")), |
| 84 | + asyncio.create_task(execute_query("SELECT 4")), |
| 85 | + asyncio.create_task(execute_query("SELECT 5")), |
| 86 | + asyncio.create_task(execute_query("SELECT 6")), |
| 87 | + ] |
| 88 | +
|
| 89 | + await asyncio.gather(*tasks) |
| 90 | + ``` |
| 91 | + """ |
| 92 | + commit_on_exit = _commit_on_exit_ctx.get() |
| 93 | + task: Task = asyncio.current_task() # type: ignore |
| 94 | + if not hasattr(task, "_db_session"): |
| 95 | + task._db_session = _Session() # type: ignore |
| 96 | + |
| 97 | + def cleanup(future): |
| 98 | + session = getattr(task, "_db_session", None) |
| 99 | + if session: |
| 100 | + |
| 101 | + async def do_cleanup(): |
| 102 | + try: |
| 103 | + if future.exception(): |
| 104 | + await session.rollback() |
| 105 | + else: |
| 106 | + if commit_on_exit: |
| 107 | + await session.commit() |
| 108 | + finally: |
| 109 | + await session.close() |
| 110 | + |
| 111 | + asyncio.create_task(do_cleanup()) |
| 112 | + |
| 113 | + task.add_done_callback(cleanup) |
| 114 | + return task._db_session # type: ignore |
| 115 | + else: |
| 116 | + session = _session.get() |
| 117 | + if session is None: |
| 118 | + raise MissingSessionError |
| 119 | + return session |
69 | 120 |
|
70 | 121 | class DBSession(metaclass=DBSessionMeta): |
71 | | - def __init__(self, session_args: Dict = None, commit_on_exit: bool = False): |
| 122 | + def __init__( |
| 123 | + self, |
| 124 | + session_args: Dict = None, |
| 125 | + commit_on_exit: bool = False, |
| 126 | + multi_sessions: bool = False, |
| 127 | + ): |
72 | 128 | self.token = None |
| 129 | + self.multi_sessions_token = None |
| 130 | + self.commit_on_exit_token = None |
73 | 131 | self.session_args = session_args or {} |
74 | 132 | self.commit_on_exit = commit_on_exit |
| 133 | + self.multi_sessions = multi_sessions |
75 | 134 |
|
76 | 135 | async def __aenter__(self): |
77 | 136 | if not isinstance(_Session, async_sessionmaker): |
78 | 137 | raise SessionNotInitialisedError |
79 | 138 |
|
80 | | - self.token = _session.set(_Session(**self.session_args)) # type: ignore |
| 139 | + if self.multi_sessions: |
| 140 | + self.multi_sessions_token = _multi_sessions_ctx.set(True) |
| 141 | + self.commit_on_exit_token = _commit_on_exit_ctx.set(self.commit_on_exit) |
| 142 | + |
| 143 | + self.token = _session.set(_Session(**self.session_args)) |
81 | 144 | return type(self) |
82 | 145 |
|
83 | 146 | async def __aexit__(self, exc_type, exc_value, traceback): |
84 | 147 | session = _session.get() |
85 | | - |
86 | 148 | try: |
87 | 149 | if exc_type is not None: |
88 | 150 | await session.rollback() |
89 | | - elif ( |
90 | | - self.commit_on_exit |
91 | | - ): # Note: Changed this to elif to avoid commit after rollback |
| 151 | + elif self.commit_on_exit: |
92 | 152 | await session.commit() |
93 | 153 | finally: |
94 | 154 | await session.close() |
95 | 155 | _session.reset(self.token) |
| 156 | + if self.multi_sessions_token is not None: |
| 157 | + _multi_sessions_ctx.reset(self.multi_sessions_token) |
| 158 | + _commit_on_exit_ctx.reset(self.commit_on_exit_token) |
96 | 159 |
|
97 | 160 | return SQLAlchemyMiddleware, DBSession |
98 | 161 |
|
|
0 commit comments