Skip to content

Migrate database setup from sync to async SQLAlchemy#108

Open
szyszkapiotr wants to merge 8 commits into
the-momentum:mainfrom
szyszkapiotr:feature/migrate-to-async-sqlalchemy
Open

Migrate database setup from sync to async SQLAlchemy#108
szyszkapiotr wants to merge 8 commits into
the-momentum:mainfrom
szyszkapiotr:feature/migrate-to-async-sqlalchemy

Conversation

@szyszkapiotr
Copy link
Copy Markdown
Contributor

@szyszkapiotr szyszkapiotr commented Jun 8, 2026

Related issue: #97

Description

This PR intruduces change from existing synchronous SQLAlchemy setup to its async (asyncpg) version and extends the generic CRUD/service layer with bulk and lookup helpers. Additionally, a commit: bool flag has been introduced to repository methods (default: True). This allows callers that compose multiple repository operations to pass commit=False and let the service layer own the transaction, committing only once at the end.

Changes

Async migration

  • config.py.jinja: add db_async_uri property (postgresql+asyncpg://).
  • database.py: replace sync create_engine/sessionmaker/Session with
    create_async_engine / async_sessionmaker / AsyncSession. Export
    AsyncDbSession dependency, adb_session_ctx, and AsyncSessionLocal
    (expire_on_commit=False). Drop engine, SessionLocal, DbSession.
  • repositories.py, services/services.py: convert all CRUD/service methods to
    async/await; queries moved from session.query(...) to select()/delete().
  • user/repositories/activity_repository.py, user/services/activity_mixin.py:
    migrate is_user_active to async select().
  • utils/healthcheck.py: async db.execute, pool status via async_engine.
  • utils/exceptions.py: handle_exceptions now branches on
    asyncio.iscoroutinefunction so exception-to-HTTP translation works for async
    methods (previously the sync wrapper returned the coroutine unawaited and never
    caught anything).

New repository/service methods

  • create_many — bulk insert; flushes when commit=False.
  • get_from_ids — fetch a set of rows by id list.
  • get_filtered_scalar — single-or-none lookup, raises MultipleResultsFoundError when more than one row matches.
  • delete_many — batched bulk delete; deletes per batch then commits once
    (atomic across batches).
  • commit flag added to create/update/delete for unit-of-work composition.

@szyszkapiotr szyszkapiotr changed the title Migrate database layer from sync to async SQLAlchemy Migrate database setup from sync to async SQLAlchemy Jun 8, 2026
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.

1 participant