Refactor code structure for improved readability and maintainability
This commit is contained in:
38
app/core/database.py
Normal file
38
app/core/database.py
Normal file
@@ -0,0 +1,38 @@
|
||||
from collections.abc import AsyncGenerator
|
||||
|
||||
from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine
|
||||
from sqlmodel import SQLModel
|
||||
from sqlmodel.ext.asyncio.session import AsyncSession
|
||||
|
||||
from app.core.config import settings
|
||||
from app.models import ( # noqa: F401
|
||||
plan,
|
||||
playlist,
|
||||
playlist_sound,
|
||||
sound,
|
||||
sound_played,
|
||||
stream,
|
||||
user,
|
||||
user_oauth,
|
||||
)
|
||||
|
||||
engine: AsyncEngine = create_async_engine(
|
||||
settings.DATABASE_URL,
|
||||
echo=settings.DATABASE_ECHO,
|
||||
)
|
||||
|
||||
|
||||
async def get_db() -> AsyncGenerator[AsyncSession, None]:
|
||||
async with AsyncSession(engine) as session:
|
||||
try:
|
||||
yield session
|
||||
except Exception:
|
||||
await session.rollback()
|
||||
raise
|
||||
finally:
|
||||
await session.close()
|
||||
|
||||
|
||||
async def init_db() -> None:
|
||||
async with engine.begin() as conn:
|
||||
await conn.run_sync(SQLModel.metadata.create_all)
|
||||
Reference in New Issue
Block a user