Alchemy Repo is a typed repository layer for SQLAlchemy's async ORM. It provides statement builders, persistence helpers, and offset pagination for application-owned sessions.
SQLAlchemy 2.1+, installed with the library
An async driver for your database, such as aiosqlite or asyncpg
Add the local checkout as a dependency from your application directory. Adjust the path if the repositories are in different locations.
For the SQLite example, run the following commands from the Alchemy Repo checkout. The development dependencies include aiosqlite .
Save this code as example.py .
Define a repository subclass for each model and bind that model in the subclass constructor. Put application queries behind methods that describe what the caller needs, such as ArticleRepository.get_published() . Routes and services pass in request data and work with the returned models. The repository owns the SQLAlchemy filters and statement construction, so multiple callers can reuse the same query without knowing how it is built.
The application owns the session and its transaction. Use async_sessionmaker.begin() for automatic commit on success and rollback on error, or manage the transaction explicitly.
Pages start at zero. Use a stable sort with a unique tie-breaker when fetching successive pages. Sort names refer to selected columns and can be qualified by the mapped class, table, or named ORM alias. Pass a query before applying offsets or limits. The total counts rows from the supplied query, including filters and grouping.
Primary-key lookup and existence
For a composite primary key, pass a tuple in mapped primary-key order or a dictionary keyed by mapped attribute names to get_by_pk() .
Cursor pages use ascending mapped primary-key order, including composite keys. The repository applies its own ordering and page bounds. Supply a query that selects the repository model and yields one SQL row per entity. For example, use an EXISTS filter when filtering on a relationship that would otherwise multiply rows. The repository fetches one extra row to detect the page without running a count. Reuse the same filters on subsequent requests. next_cursor is a tuple of key values when another page exists, otherwise it is None . Applications decide how to encode those values for HTTP clients.
Pass model attributes or mapped table columns as index_elements and include their values in the data mapping. Data keys may also be mapped attribute names. The default skips null updates. Set update_none=True to write nulls to nullable fields.
PostgreSQL and SQLite use native ON CONFLICT DO UPDATE when update_none=True and there are columns to update. Supply enough data for a valid insert in that mode. Other cases use an update followed by an insert when the row is missing, or look up the row first when only conflict keys are supplied. The portable path supports partial updates. Concurrent inserts for the same key may require a transaction retry.
To populate timestamps during upserts, set audit_timestamps = ("created_at", "updated_at") on a repository subclass and define the corresponding mapped attributes. The repository uses UTC timestamps. The application owns any ORM lifecycle hooks.
Use column_info() to inspect one mapped column by attribute or attribute name.
key is the mapped attribute name and name is the database column name. is_unique describes declared standalone uniqueness, including single-column primary keys, unique constraints, and unconditional unique column indexes. Membership in a composite or partial key or index does not imply standalone uniqueness. The helper reads SQLAlchemy metadata without querying the database.
Use the pagination helpers directly with SQLAlchemy queries, including projections that return more than one column.
The default pagination models are standard-library dataclasses. Use the optional pydantic extra for request validation, response serialization, and OpenAPI schemas.
Import the HTTP-facing models from alchemy_repo.pydantic . Call .to_request() before passing a request to the repository, then use .model_validate() to convert the returned page. The Pydantic response includes total_pages , has_next , and has_previous in serialized output.
FastAPI query dependency
Install the fastapi extra to get FastAPI and the Pydantic models.
Annotate a route parameter with PageRequestDepends . It returns a core PageRequest ready to pass to the repository. You can also use Depends(build_page_request) explicitly.
For example, GET /articles?page=0&size=20&sort=title:asc&sort=id:desc sorts by title first, then by ID. page defaults to zero, size defaults to 20 and accepts values from 1 to 100. Invalid bounds, empty sort names, and invalid sort directions produce HTTP 422. Which columns can be sorted depends on the repository query.
This route uses the ArticleRepository from the quickstart and assumes your app provides a get_session dependency.
GitHub Actions runs the test suite and builds the wheel and source distribution on pushes and pull requests.
Publishing a GitHub release with a tag matching the package version (for example, v0.1.0 ) runs the test and build jobs, then publishes the resulting distributions to PyPI through Trusted Publishing.
For the initial setup, create a pending GitHub publisher in PyPI Publishing for project alchemy-repo , owner dtlasky , repository alchemy_repo , workflow release.yml , and environment pypi . GitHub Actions authenticates through OIDC. No PyPI API token is required.
Alchemy Repo is available under the MIT License .
The full story
This article is one source in a clustered incident — the cluster page carries the summary, timeline and every other outlet covering it.
