@@ -0,0 +1,42 @@
|
||||
"""Thread-local DB session bridge for ported WESP services."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from contextlib import contextmanager
|
||||
from contextvars import ContextVar
|
||||
from typing import Iterator
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
_current_session: ContextVar[Session | None] = ContextVar("wesp_current_session", default=None)
|
||||
|
||||
|
||||
class _WespDB:
|
||||
@property
|
||||
def session(self) -> Session:
|
||||
db = _current_session.get()
|
||||
if db is None:
|
||||
raise RuntimeError("wesp_bridge_db: no active session — use wesp_db_session()")
|
||||
return db
|
||||
|
||||
|
||||
db = _WespDB()
|
||||
|
||||
|
||||
@contextmanager
|
||||
def wesp_db_session(existing: Session | None = None) -> Iterator[Session]:
|
||||
if existing is not None:
|
||||
token = _current_session.set(existing)
|
||||
try:
|
||||
yield existing
|
||||
finally:
|
||||
_current_session.reset(token)
|
||||
return
|
||||
from app.core.database import session_scope
|
||||
|
||||
with session_scope() as session:
|
||||
token = _current_session.set(session)
|
||||
try:
|
||||
yield session
|
||||
finally:
|
||||
_current_session.reset(token)
|
||||
Reference in New Issue
Block a user