This commit is contained in:
Mikan
2026-06-19 11:28:04 +03:00
commit 53c89829a8
80 changed files with 12482 additions and 0 deletions

49
backend/app/db.py Normal file
View File

@@ -0,0 +1,49 @@
"""Database engine + session factory."""
from __future__ import annotations
from contextlib import asynccontextmanager
from typing import AsyncIterator
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
from sqlalchemy.orm import DeclarativeBase
from app.config import settings
class Base(DeclarativeBase):
pass
_engine_kwargs: dict = dict(
echo=False,
pool_pre_ping=True,
)
# Pool size params only for Postgres/MySQL (not SQLite)
if "sqlite" not in settings.database_url:
_engine_kwargs.update(pool_size=10, max_overflow=20)
engine = create_async_engine(settings.database_url, **_engine_kwargs)
AsyncSessionLocal = async_sessionmaker(
engine, class_=AsyncSession, expire_on_commit=False, autoflush=False
)
@asynccontextmanager
async def get_db() -> AsyncIterator[AsyncSession]:
async with AsyncSessionLocal() as session:
try:
yield session
await session.commit()
except Exception:
await session.rollback()
raise
async def get_db_dep() -> AsyncIterator[AsyncSession]:
"""FastAPI dependency."""
async with AsyncSessionLocal() as session:
try:
yield session
finally:
await session.close()