File size: 1,067 Bytes
330c3b5 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | # src/database.py
from sqlalchemy import event
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
from .config import settings
# Create a non-blocking asynchronous engine
# timeout=30.0 gives busy transactions time to clear before failing
engine = create_async_engine(
settings.DATABASE_URL,
connect_args={"timeout": 30.0},
)
# SQLite doesn't enable foreign keys or WAL mode by default.
# This listener applies these performance configurations upon opening a connection.
@event.listens_for(engine.sync_engine, "connect")
def set_sqlite_pragma(dbapi_connection, connection_record):
cursor = dbapi_connection.cursor()
cursor.execute("PRAGMA foreign_keys=ON;")
cursor.execute("PRAGMA journal_mode=WAL;")
cursor.close()
# Async sessionmaker factory
AsyncSessionLocal = async_sessionmaker(
bind=engine,
class_=AsyncSession,
expire_on_commit=False,
)
# Dependency injector function used in HTTP routes
async def get_db():
async with AsyncSessionLocal() as session:
yield session
|