47 lines
1.6 KiB
Python
47 lines
1.6 KiB
Python
# app/database.py
|
|
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
|
|
from sqlalchemy.orm import sessionmaker, declarative_base
|
|
from app.config import settings
|
|
|
|
# Ensure DATABASE_URL is set before proceeding
|
|
if not settings.DATABASE_URL:
|
|
raise ValueError("DATABASE_URL is not configured in settings.")
|
|
|
|
# Create the SQLAlchemy async engine
|
|
# pool_recycle=3600 helps prevent stale connections on some DBs
|
|
engine = create_async_engine(
|
|
settings.DATABASE_URL,
|
|
echo=True, # Log SQL queries (useful for debugging)
|
|
future=True, # Use SQLAlchemy 2.0 style features
|
|
pool_recycle=3600 # Optional: recycle connections after 1 hour
|
|
)
|
|
|
|
# Create a configured "Session" class
|
|
# expire_on_commit=False prevents attributes from expiring after commit
|
|
AsyncSessionLocal = sessionmaker(
|
|
bind=engine,
|
|
class_=AsyncSession,
|
|
expire_on_commit=False,
|
|
autoflush=False,
|
|
autocommit=False,
|
|
)
|
|
|
|
# Base class for our ORM models
|
|
Base = declarative_base()
|
|
|
|
# Dependency to get DB session in path operations
|
|
async def get_db() -> AsyncSession: # type: ignore
|
|
"""
|
|
Dependency function that yields an AsyncSession.
|
|
Ensures the session is closed after the request.
|
|
"""
|
|
async with AsyncSessionLocal() as session:
|
|
try:
|
|
yield session
|
|
# Optionally commit if your endpoints modify data directly
|
|
# await session.commit() # Usually commit happens within endpoint logic
|
|
except Exception:
|
|
await session.rollback()
|
|
raise
|
|
finally:
|
|
await session.close() # Not strictly necessary with async context manager, but explicit |