cmvr-visual/backend/app/database.py

41 lines
1.6 KiB
Python

from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
from sqlalchemy import event
import asyncio
from contextlib import asynccontextmanager
from .models import Base
from . import v2_models
class Database:
def __init__(self, settings):
self.mode = settings.mode
self.engine = create_async_engine(settings.sqlalchemy_url, pool_pre_ping=True)
if settings.sqlalchemy_url.drivername.startswith("sqlite"):
@event.listens_for(self.engine.sync_engine, "connect")
def sqlite_options(connection, _):
cursor = connection.cursor()
cursor.execute("PRAGMA foreign_keys=ON")
cursor.execute("PRAGMA busy_timeout=10000")
cursor.close()
self._sessions = async_sessionmaker(self.engine, expire_on_commit=False)
# One API process by deployment contract. Short DB units are serialized
# so durable SSE IDs are observed in commit order, including CPU imports.
self._unit_lock = asyncio.Lock()
@asynccontextmanager
async def session(self):
async with self._unit_lock:
async with self._sessions() as session:
yield session
async def initialize(self):
async with self.engine.begin() as connection:
if self.mode in {"test", "preview"}:
await connection.run_sync(Base.metadata.create_all)
else:
from .schema import check_schema_revision
await connection.run_sync(check_schema_revision, {"004"})
async def close(self):
await self.engine.dispose()