|
| 1 | +"""Middleware for SQLSpec FastAPI integration.""" |
| 2 | + |
| 3 | +import contextlib |
| 4 | +from typing import TYPE_CHECKING, Any, Optional |
| 5 | + |
| 6 | +from starlette.middleware.base import BaseHTTPMiddleware |
| 7 | + |
| 8 | +from sqlspec.utils.sync_tools import ensure_async_ |
| 9 | + |
| 10 | +if TYPE_CHECKING: |
| 11 | + from collections.abc import Awaitable, Callable |
| 12 | + |
| 13 | + from starlette.requests import Request |
| 14 | + from starlette.responses import Response |
| 15 | + |
| 16 | + from sqlspec.extensions.fastapi.config import CommitMode, DatabaseConfig |
| 17 | + |
| 18 | + |
| 19 | +__all__ = ("SessionMiddleware",) |
| 20 | + |
| 21 | + |
| 22 | +class SessionMiddleware(BaseHTTPMiddleware): |
| 23 | + """Middleware for managing database sessions and transactions in FastAPI.""" |
| 24 | + |
| 25 | + def __init__( |
| 26 | + self, |
| 27 | + app: Any, |
| 28 | + config: "DatabaseConfig", |
| 29 | + commit_mode: "CommitMode" = "manual", |
| 30 | + extra_commit_statuses: "Optional[set[int]]" = None, |
| 31 | + extra_rollback_statuses: "Optional[set[int]]" = None, |
| 32 | + ) -> None: |
| 33 | + """Initialize session middleware. |
| 34 | +
|
| 35 | + Args: |
| 36 | + app: The ASGI application. |
| 37 | + config: Database configuration instance. |
| 38 | + commit_mode: Transaction commit behavior. |
| 39 | + extra_commit_statuses: Additional status codes that trigger commits. |
| 40 | + extra_rollback_statuses: Additional status codes that trigger rollbacks. |
| 41 | + """ |
| 42 | + super().__init__(app) |
| 43 | + self.config = config |
| 44 | + self.commit_mode = commit_mode |
| 45 | + self.extra_commit_statuses = extra_commit_statuses or set() |
| 46 | + self.extra_rollback_statuses = extra_rollback_statuses or set() |
| 47 | + |
| 48 | + async def dispatch(self, request: "Request", call_next: "Callable[[Request], Awaitable[Response]]") -> "Response": |
| 49 | + """Handle request with session management. |
| 50 | +
|
| 51 | + Args: |
| 52 | + request: The incoming request. |
| 53 | + call_next: The next middleware or endpoint. |
| 54 | +
|
| 55 | + Returns: |
| 56 | + The response from the application. |
| 57 | + """ |
| 58 | + if not self.config.connection_provider: |
| 59 | + return await call_next(request) |
| 60 | + |
| 61 | + # Get connection from provider |
| 62 | + connection_gen = self.config.connection_provider() |
| 63 | + connection = await connection_gen.__anext__() |
| 64 | + |
| 65 | + # Store connection in request state |
| 66 | + request.state.__dict__[self.config.connection_key] = connection |
| 67 | + |
| 68 | + try: |
| 69 | + response = await call_next(request) |
| 70 | + |
| 71 | + # Handle transaction based on commit mode and response status |
| 72 | + if self.commit_mode != "manual": |
| 73 | + await self._handle_transaction(connection, response.status_code) |
| 74 | + |
| 75 | + except Exception: |
| 76 | + # Rollback on exception |
| 77 | + if hasattr(connection, "rollback") and callable(connection.rollback): |
| 78 | + await ensure_async_(connection.rollback)() |
| 79 | + raise |
| 80 | + else: |
| 81 | + return response |
| 82 | + finally: |
| 83 | + # Clean up connection |
| 84 | + with contextlib.suppress(StopAsyncIteration): |
| 85 | + await connection_gen.__anext__() |
| 86 | + if hasattr(connection, "close") and callable(connection.close): |
| 87 | + await ensure_async_(connection.close)() |
| 88 | + |
| 89 | + async def _handle_transaction(self, connection: Any, status_code: int) -> None: |
| 90 | + """Handle transaction commit/rollback based on status code. |
| 91 | +
|
| 92 | + Args: |
| 93 | + connection: The database connection. |
| 94 | + status_code: HTTP response status code. |
| 95 | + """ |
| 96 | + http_ok = 200 |
| 97 | + http_multiple_choices = 300 |
| 98 | + http_bad_request = 400 |
| 99 | + |
| 100 | + should_commit = False |
| 101 | + |
| 102 | + if self.commit_mode == "autocommit": |
| 103 | + should_commit = http_ok <= status_code < http_multiple_choices |
| 104 | + elif self.commit_mode == "autocommit_include_redirect": |
| 105 | + should_commit = http_ok <= status_code < http_bad_request |
| 106 | + |
| 107 | + # Apply extra status overrides |
| 108 | + if status_code in self.extra_commit_statuses: |
| 109 | + should_commit = True |
| 110 | + elif status_code in self.extra_rollback_statuses: |
| 111 | + should_commit = False |
| 112 | + |
| 113 | + # Execute transaction action |
| 114 | + if should_commit and hasattr(connection, "commit") and callable(connection.commit): |
| 115 | + await ensure_async_(connection.commit)() |
| 116 | + elif not should_commit and hasattr(connection, "rollback") and callable(connection.rollback): |
| 117 | + await ensure_async_(connection.rollback)() |
0 commit comments