db.py 798 B

123456789101112131415161718192021222324252627
  1. from sqlmodel.ext.asyncio.session import AsyncSession
  2. engine = None
  3. async def get_session():
  4. """
  5. Create a session for database operations.
  6. Note: expire_on_commit=False is required for async SQLAlchemy to prevent
  7. lazy loading errors after commit. See: https://docs.sqlalchemy.org/en/20/orm/extensions/asyncio.html
  8. """
  9. async with AsyncSession(engine, expire_on_commit=False) as session:
  10. yield session
  11. def async_session() -> AsyncSession:
  12. """
  13. Get an AsyncSession with default expire_on_commit=False.
  14. Returns:
  15. AsyncSession: Configured session with expire_on_commit=False
  16. """
  17. if engine is None:
  18. raise RuntimeError("Database not initialized. Call init_database() first.")
  19. return AsyncSession(engine, expire_on_commit=False)