48 lines
1.2 KiB
Python
48 lines
1.2 KiB
Python
"""
|
|
Database connection and session management.
|
|
Async SQLAlchemy 2.0 with asyncpg driver.
|
|
"""
|
|
|
|
import os
|
|
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker
|
|
from sqlalchemy import text
|
|
|
|
DATABASE_URL = os.getenv(
|
|
"DATABASE_URL",
|
|
"postgresql+asyncpg://postgres:postgres@lifeos-db:5432/lifeos_dev"
|
|
)
|
|
|
|
engine = create_async_engine(
|
|
DATABASE_URL,
|
|
echo=os.getenv("ENVIRONMENT") == "development",
|
|
pool_size=5,
|
|
max_overflow=10,
|
|
pool_pre_ping=True,
|
|
)
|
|
|
|
async_session_factory = async_sessionmaker(
|
|
engine,
|
|
class_=AsyncSession,
|
|
expire_on_commit=False,
|
|
)
|
|
|
|
|
|
async def get_db():
|
|
"""FastAPI dependency: yields an async database session."""
|
|
async with async_session_factory() as session:
|
|
try:
|
|
yield session
|
|
await session.commit()
|
|
except Exception:
|
|
await session.rollback()
|
|
raise
|
|
finally:
|
|
await session.close()
|
|
|
|
|
|
async def check_db():
|
|
"""Health check: verify database connectivity."""
|
|
async with async_session_factory() as session:
|
|
result = await session.execute(text("SELECT 1"))
|
|
return result.scalar() == 1
|