Context manager yielding the active context session or a new one.
(self)
| 18 | |
| 19 | @asynccontextmanager |
| 20 | async def session(self) -> AsyncGenerator[AsyncSession, None]: |
| 21 | """Context manager yielding the active context session or a new one.""" |
| 22 | context_session = _session_ctx.get() |
| 23 | if context_session is not None: |
| 24 | yield context_session |
| 25 | else: |
| 26 | async with async_session() as session: |
| 27 | token = _session_ctx.set(session) |
| 28 | try: |
| 29 | yield session |
| 30 | if hasattr(session, "commit"): |
| 31 | await session.commit() |
| 32 | except Exception: |
| 33 | if hasattr(session, "rollback"): |
| 34 | await session.rollback() |
| 35 | raise |
| 36 | finally: |
| 37 | _session_ctx.reset(token) |
| 38 | |
| 39 | async def get(self, id: Any) -> ModelType | None: |
| 40 | """Fetch a single record by its primary key ID.""" |