34 lines
856 B
Python
34 lines
856 B
Python
|
|
"""Database session and initialization."""
|
||
|
|
|
||
|
|
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker
|
||
|
|
from sqlalchemy.orm import DeclarativeBase
|
||
|
|
from app.config import get_settings
|
||
|
|
|
||
|
|
|
||
|
|
class Base(DeclarativeBase):
|
||
|
|
pass
|
||
|
|
|
||
|
|
|
||
|
|
engine = None
|
||
|
|
async_session_maker = None
|
||
|
|
|
||
|
|
|
||
|
|
async def init_db():
|
||
|
|
global engine, async_session_maker
|
||
|
|
settings = get_settings()
|
||
|
|
engine = create_async_engine(
|
||
|
|
settings.database_url,
|
||
|
|
echo=settings.debug,
|
||
|
|
)
|
||
|
|
async_session_maker = async_sessionmaker(
|
||
|
|
engine, class_=AsyncSession, expire_on_commit=False
|
||
|
|
)
|
||
|
|
from app.models import Case, Screenshot, Transaction # noqa: F401
|
||
|
|
async with engine.begin() as conn:
|
||
|
|
await conn.run_sync(Base.metadata.create_all)
|
||
|
|
|
||
|
|
|
||
|
|
async def get_db():
|
||
|
|
async with async_session_maker() as session:
|
||
|
|
yield session
|