"""Async engine and session factory with per-transaction tenant binding.""" from __future__ import annotations import uuid from collections.abc import AsyncIterator from contextlib import asynccontextmanager from sqlalchemy import event, text from sqlalchemy.ext.asyncio import ( AsyncEngine, AsyncSession, async_sessionmaker, create_async_engine, ) from core.config import get_settings from core.tenancy import context as tenancy def make_engine(url: str | None = None, **kwargs: object) -> AsyncEngine: engine = create_async_engine(url or get_settings().database_url, pool_pre_ping=True, **kwargs) @event.listens_for(engine.sync_engine, "begin") def _bind_tenant(conn): # type: ignore[no-untyped-def] """Runs at the start of every transaction: scope RLS to the current context.""" ctx = tenancy.current() conn.exec_driver_sql( "SELECT set_config('app.tenant_id', %(t)s, true), " "set_config('app.user_id', %(u)s, true)", { "t": str(ctx.tenant_id) if ctx.tenant_id else "", "u": str(ctx.user_id) if ctx.user_id else "", }, ) return engine class Database: """Owns the engine and hands out sessions. One instance per process.""" def __init__(self, url: str | None = None, **engine_kwargs: object) -> None: self.engine = make_engine(url, **engine_kwargs) self.sessionmaker = async_sessionmaker(self.engine, expire_on_commit=False) @asynccontextmanager async def session( self, tenant_id: uuid.UUID | None = None, user_id: uuid.UUID | None = None ) -> AsyncIterator[AsyncSession]: """Open a session; if ``tenant_id`` is given, bind it for the session's lifetime.""" if tenant_id is None and user_id is None: async with self.sessionmaker() as s: yield s return ctx = tenancy.current() with tenancy.use_context( tenant_id=tenant_id or ctx.tenant_id, user_id=user_id or ctx.user_id, actor=ctx.actor, ): async with self.sessionmaker() as s: yield s async def ping(self) -> bool: async with self.engine.connect() as conn: await conn.execute(text("SELECT 1")) return True async def dispose(self) -> None: await self.engine.dispose()