35 lines
1.3 KiB
Python
35 lines
1.3 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
|
|
|
|
|
|
class Database:
|
|
def __init__(self, settings):
|
|
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:
|
|
await connection.run_sync(Base.metadata.create_all)
|
|
|
|
async def close(self):
|
|
await self.engine.dispose()
|