47 lines
1.2 KiB
Python
47 lines
1.2 KiB
Python
"""
|
|
Database configuration and session management
|
|
Uses async SQLAlchemy with asyncpg driver
|
|
"""
|
|
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_sessionmaker
|
|
from sqlalchemy.orm import declarative_base
|
|
from app.config import settings
|
|
|
|
# Convert standard postgres:// URL to asyncpg's postgresql+asyncpg://
|
|
database_url = settings.DATABASE_URL.replace("postgresql://", "postgresql+asyncpg://")
|
|
|
|
# Create async engine
|
|
engine = create_async_engine(
|
|
database_url,
|
|
echo=settings.DEBUG,
|
|
pool_pre_ping=True,
|
|
pool_size=10,
|
|
max_overflow=20
|
|
)
|
|
|
|
# Create async session factory
|
|
AsyncSessionLocal = async_sessionmaker(
|
|
engine,
|
|
class_=AsyncSession,
|
|
expire_on_commit=False,
|
|
autocommit=False,
|
|
autoflush=False
|
|
)
|
|
|
|
# Base class for ORM models
|
|
Base = declarative_base()
|
|
|
|
|
|
async def get_db():
|
|
"""
|
|
Dependency for FastAPI to get database session
|
|
Usage: db: AsyncSession = Depends(get_db)
|
|
"""
|
|
async with AsyncSessionLocal() as session:
|
|
try:
|
|
yield session
|
|
await session.commit()
|
|
except Exception:
|
|
await session.rollback()
|
|
raise
|
|
finally:
|
|
await session.close()
|