first commit
This commit is contained in:
24
backend/app/core/db.py
Normal file
24
backend/app/core/db.py
Normal file
@@ -0,0 +1,24 @@
|
||||
from typing import AsyncGenerator
|
||||
from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker, AsyncSession
|
||||
from sqlalchemy.orm import DeclarativeBase
|
||||
|
||||
from app.core.config import settings
|
||||
|
||||
class Base(DeclarativeBase):
|
||||
pass
|
||||
|
||||
def _db_url() -> str:
|
||||
# w dockerze zwykle ustawiamy DATABASE_URL przez env, więc preferujemy settings.DATABASE_URL
|
||||
return settings.DATABASE_URL
|
||||
|
||||
engine = create_async_engine(_db_url(), future=True, echo=False)
|
||||
SessionLocal = async_sessionmaker(engine, expire_on_commit=False, class_=AsyncSession)
|
||||
|
||||
async def init_db() -> None:
|
||||
from app.models import user, router, dashboard # noqa
|
||||
async with engine.begin() as conn:
|
||||
await conn.run_sync(Base.metadata.create_all)
|
||||
|
||||
async def get_session() -> AsyncGenerator[AsyncSession, None]:
|
||||
async with SessionLocal() as session:
|
||||
yield session
|
||||
Reference in New Issue
Block a user