Skip to content

Support async DB driver: replace psycopg with asyncpg and adopt async Alembic template#2270

Open
MohamedMostafa259 wants to merge 4 commits intofastapi:masterfrom
MohamedMostafa259:feat/async-db-asyncpg
Open

Support async DB driver: replace psycopg with asyncpg and adopt async Alembic template#2270
MohamedMostafa259 wants to merge 4 commits intofastapi:masterfrom
MohamedMostafa259:feat/async-db-asyncpg

Conversation

@MohamedMostafa259
Copy link
Copy Markdown

Summary

This PR comprehensively migrates the database layer from the synchronous psycopg driver to the asynchronous asyncpg driver, and updates Alembic to use the async template. All database operations, CRUD functions, and route handlers now use async/await patterns. These changes align the entire stack (FastAPI + SQLAlchemy + AsyncPG + Alembic) for seamless async operations and better runtime performance.

Changes

Dependencies

  • Removed: psycopg[binary]<4.0.0,>=3.1.13
  • Added: asyncpg>=0.31.0

Configuration

  • Updated SQLALCHEMY_DATABASE_URI scheme from postgresql+psycopg to postgresql+asyncpg in backend/app/core/config.py.

Database Connection (backend/app/core/db.py)

  • Replaced create_engine() with create_async_engine() for true async database connections.
  • Replaced sync Session with AsyncSession and async_sessionmaker.
  • Made init_db() async to support initialization workflows.

CRUD Operations (backend/app/crud.py)

  • Converted all CRUD functions to async:
    • create_user(), update_user(), get_user_by_email(), authenticate(), create_item()
    • All database queries now use await session.execute() instead of session.exec().
    • All commits and refreshes now use await session.commit() and await session.refresh().

Dependencies (backend/app/api/deps.py)

  • Updated get_db() to async generator returning AsyncSession.
  • Updated get_current_user() and related dependency functions to async with await for database calls.

Route Handlers

All routes in backend/app/api/routes/ updated to async:

  • login.py: login_access_token(), recover_password(), reset_password(), recover_password_html_content()
  • users.py: read_users(), create_user(), update_user_me(), update_password_me(), delete_user_me(), register_user(), read_user_by_id(), update_user(), delete_user()
  • items.py: read_items(), read_item(), create_item(), update_item(), delete_item()

All handlers now use async def and await for session and CRUD operations.

Alembic Migration Environment

  • Regenerated backend/app/alembic/ using alembic init -t async alembic, which includes async-aware env.py using async_engine_from_config() and async connection handling.

Copilot AI review requested due to automatic review settings April 28, 2026 01:30
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants