advanced-alchemy 1.7.0


pip install advanced-alchemy

  Latest version

Released: Oct 14, 2025


Meta
Author: Cody Fincher, Peter Schutt, Janek Nouvertné, Jacob Coffee
Maintainer: Litestar Developers, Cody Fincher, Jacob Coffee, Janek Nouvertné, Julien Courtes
Requires Python: >=3.9

Classifiers

Development Status
  • 3 - Alpha

Environment
  • Web Environment

Intended Audience
  • Developers
  • System Administrators

License
  • OSI Approved :: MIT License

Natural Language
  • English

Operating System
  • OS Independent

Programming Language
  • Python
  • Python :: 3.9
  • Python :: 3.10
  • Python :: 3.11
  • Python :: 3.12
  • Python :: 3.13

Topic
  • Database
  • Database :: Database Engines/Servers
  • Software Development

Typing
  • Typed

Litestar Logo - Light

Project Status
CI/CD Latest Release ci Documentation Building
Quality Coverage Quality Gate Status Maintainability Rating Reliability Rating Security Rating
Package PyPI - Version PyPI - Support Python Versions Advanced Alchemy PyPI - Downloads
Community Discord Matrix
Meta Litestar Project types - Mypy License - MIT linting - Ruff

Advanced Alchemy

Check out the project documentation 📚 for more information.

About

A carefully crafted, thoroughly tested, optimized companion library for SQLAlchemy, offering:

  • Sync and async repositories, featuring common CRUD and highly optimized bulk operations
  • Integration with major web frameworks including Litestar, Starlette, FastAPI, Sanic
  • Custom-built alembic configuration and CLI with optional framework integration
  • Utility base classes with audit columns, primary keys and utility functions
  • Built in File Object data type for storing objects:
    • Unified interface for various storage backends (fsspec and obstore)
    • Optional lifecycle event hooks integrated with SQLAlchemy's event system to automatically save and delete files as records are inserted, updated, or deleted.
  • Optimized JSON types including a custom JSON type for Oracle
  • Integrated support for UUID6 and UUID7 using uuid-utils (install with the uuid extra)
  • Integrated support for Nano ID using fastnanoid (install with the nanoid extra)
  • Custom encrypted text type with multiple backend support including pgcrypto for PostgreSQL and the Fernet implementation from cryptography for other databases
  • Custom password hashing type with multiple backend support including Argon2, Passlib, and Pwdlib with automatic salt generation
  • Pre-configured base classes with audit columns UUID or Big Integer primary keys and a sentinel column.
  • Synchronous and asynchronous repositories featuring:
    • Common CRUD operations for SQLAlchemy models
    • Bulk inserts, updates, upserts, and deletes with dialect-specific enhancements
    • Integrated counts, pagination, sorting, filtering with LIKE, IN, and dates before and/or after.
  • Tested support for multiple database backends including:
  • ...and much more

Usage

Installation

pip install advanced-alchemy

[!IMPORTANT]
Check out the installation guide in our official documentation!

Repositories

Advanced Alchemy includes a set of asynchronous and synchronous repository classes for easy CRUD operations on your SQLAlchemy models.

Click to expand the example
from advanced_alchemy import base, repository, config
from sqlalchemy import create_engine
from sqlalchemy.orm import Mapped, sessionmaker


class User(base.UUIDBase):
    # you can optionally override the generated table name by manually setting it.
    __tablename__ = "user_account"  # type: ignore[assignment]
    email: Mapped[str]
    name: Mapped[str]


class UserRepository(repository.SQLAlchemySyncRepository[User]):
    """User repository."""

    model_type = User


db = config.SQLAlchemySyncConfig(connection_string="duckdb:///:memory:", session_config=config.SyncSessionConfig(expire_on_commit=False))

# Initializes the database.
with db.get_engine().begin() as conn:
    User.metadata.create_all(conn)

with db.get_session() as db_session:
    repo = UserRepository(session=db_session)
    # 1) Create multiple users with `add_many`
    bulk_users = [
        {"email": 'cody@litestar.dev', 'name': 'Cody'},
        {"email": 'janek@litestar.dev', 'name': 'Janek'},
        {"email": 'peter@litestar.dev', 'name': 'Peter'},
        {"email": 'jacob@litestar.dev', 'name': 'Jacob'}
    ]
    objs = repo.add_many([User(**raw_user) for raw_user in bulk_users])
    db_session.commit()
    print(f"Created {len(objs)} new objects.")

    # 2) Select paginated data and total row count.  Pass additional filters as kwargs
    created_objs, total_objs = repo.list_and_count(LimitOffset(limit=10, offset=0), name="Cody")
    print(f"Selected {len(created_objs)} records out of a total of {total_objs}.")

    # 3) Let's remove the batch of records selected.
    deleted_objs = repo.delete_many([new_obj.id for new_obj in created_objs])
    print(f"Removed {len(deleted_objs)} records out of a total of {total_objs}.")

    # 4) Let's count the remaining rows
    remaining_count = repo.count()
    print(f"Found {remaining_count} remaining records after delete.")

For a full standalone example, see the sample here

Services

Advanced Alchemy includes an additional service class to make working with a repository easier. This class is designed to accept data as a dictionary or SQLAlchemy model, and it will handle the type conversions for you.

Here's the same example from above but using a service to create the data:
from advanced_alchemy import base, repository, filters, service, config
from sqlalchemy import create_engine
from sqlalchemy.orm import Mapped, sessionmaker


class User(base.UUIDBase):
    # you can optionally override the generated table name by manually setting it.
    __tablename__ = "user_account"  # type: ignore[assignment]
    email: Mapped[str]
    name: Mapped[str]

class UserService(service.SQLAlchemySyncRepositoryService[User]):
    """User repository."""
    class Repo(repository.SQLAlchemySyncRepository[User]):
        """User repository."""

        model_type = User

    repository_type = Repo

db = config.SQLAlchemySyncConfig(connection_string="duckdb:///:memory:", session_config=config.SyncSessionConfig(expire_on_commit=False))

# Initializes the database.
with db.get_engine().begin() as conn:
    User.metadata.create_all(conn)

with db.get_session() as db_session:
    service = UserService(session=db_session)
    # 1) Create multiple users with `add_many`
    objs = service.create_many([
        {"email": 'cody@litestar.dev', 'name': 'Cody'},
        {"email": 'janek@litestar.dev', 'name': 'Janek'},
        {"email": 'peter@litestar.dev', 'name': 'Peter'},
        {"email": 'jacob@litestar.dev', 'name': 'Jacob'}
    ])
    print(objs)
    print(f"Created {len(objs)} new objects.")

    # 2) Select paginated data and total row count.  Pass additional filters as kwargs
    created_objs, total_objs = service.list_and_count(LimitOffset(limit=10, offset=0), name="Cody")
    print(f"Selected {len(created_objs)} records out of a total of {total_objs}.")

    # 3) Let's remove the batch of records selected.
    deleted_objs = service.delete_many([new_obj.id for new_obj in created_objs])
    print(f"Removed {len(deleted_objs)} records out of a total of {total_objs}.")

    # 4) Let's count the remaining rows
    remaining_count = service.count()
    print(f"Found {remaining_count} remaining records after delete.")

Web Frameworks

Advanced Alchemy works with nearly all Python web frameworks. Several helpers for popular libraries are included, and additional PRs to support others are welcomed.

Litestar

Advanced Alchemy is the official SQLAlchemy integration for Litestar.

In addition to installing with pip install advanced-alchemy, it can also be installed as a Litestar extra with pip install litestar[sqlalchemy].

Litestar Example
from litestar import Litestar
from litestar.plugins.sqlalchemy import SQLAlchemyPlugin, SQLAlchemyAsyncConfig
# alternately...
# from advanced_alchemy.extensions.litestar import SQLAlchemyAsyncConfig, SQLAlchemyPlugin

alchemy = SQLAlchemyPlugin(
  config=SQLAlchemyAsyncConfig(connection_string="sqlite+aiosqlite:///test.sqlite"),
)
app = Litestar(plugins=[alchemy])

For a full Litestar example, check here

Flask

Flask Example
from flask import Flask
from advanced_alchemy.extensions.flask import AdvancedAlchemy, SQLAlchemySyncConfig

app = Flask(__name__)
alchemy = AdvancedAlchemy(
    config=SQLAlchemySyncConfig(connection_string="duckdb:///:memory:"), app=app,
)

For a full Flask example, see here

FastAPI

FastAPI Example
from advanced_alchemy.extensions.fastapi import AdvancedAlchemy, SQLAlchemyAsyncConfig
from fastapi import FastAPI

app = FastAPI()
alchemy = AdvancedAlchemy(
    config=SQLAlchemyAsyncConfig(connection_string="sqlite+aiosqlite:///test.sqlite"), app=app,
)

For a full FastAPI example with optional CLI integration, see here

Starlette

Pre-built Example Apps
from advanced_alchemy.extensions.starlette import AdvancedAlchemy, SQLAlchemyAsyncConfig
from starlette.applications import Starlette

app = Starlette()
alchemy = AdvancedAlchemy(
    config=SQLAlchemyAsyncConfig(connection_string="sqlite+aiosqlite:///test.sqlite"), app=app,
)

Sanic

Pre-built Example Apps
from sanic import Sanic
from sanic_ext import Extend

from advanced_alchemy.extensions.sanic import AdvancedAlchemy, SQLAlchemyAsyncConfig

app = Sanic("AlchemySanicApp")
alchemy = AdvancedAlchemy(
    sqlalchemy_config=SQLAlchemyAsyncConfig(connection_string="sqlite+aiosqlite:///test.sqlite"),
)
Extend.register(alchemy)

Contributing

All Litestar Organization projects will always be a community-centered, available for contributions of any size.

Before contributing, please review the contribution guide.

If you have any questions, reach out to us on Discord, our org-wide GitHub discussions page, or the project-specific GitHub discussions page.


1.7.0 Oct 14, 2025
1.6.3 Sep 19, 2025
1.6.2 Aug 29, 2025
1.6.1 Aug 26, 2025
1.6.0 Aug 18, 2025
1.5.0 Aug 13, 2025
1.4.5 Jun 28, 2025
1.4.4 May 27, 2025
1.4.3 May 12, 2025
1.4.2 May 04, 2025
1.4.1 Apr 28, 2025
1.4.0 Apr 27, 2025
1.3.2 Apr 25, 2025
1.3.1 Apr 22, 2025
1.3.0 Apr 18, 2025
1.2.0 Apr 15, 2025
1.1.1 Apr 07, 2025
1.1.0 Apr 07, 2025
1.0.2 Apr 01, 2025
1.0.1 Mar 19, 2025
1.0.0 Mar 18, 2025
0.34.0 Mar 10, 2025
0.33.2 Mar 09, 2025
0.33.1 Mar 07, 2025
0.33.0 Mar 07, 2025
0.32.2 Feb 26, 2025
0.32.1 Feb 26, 2025
0.32.0 Feb 23, 2025
0.31.0 Feb 18, 2025
0.30.3 Jan 26, 2025
0.30.2 Jan 21, 2025
0.30.1 Jan 20, 2025
0.30.0 Jan 19, 2025
0.29.1 Jan 17, 2025
0.29.0 Jan 17, 2025
0.28.0 Jan 13, 2025
0.27.1 Jan 11, 2025
0.27.0 Jan 08, 2025
0.26.2 Dec 16, 2024
0.26.1 Dec 11, 2024
0.26.0 Dec 05, 2024
0.25.0 Nov 27, 2024
0.24.0 Nov 15, 2024
0.23.1 Nov 11, 2024
0.23.0 Nov 11, 2024
0.22.3 Nov 07, 2024
0.22.2 Nov 04, 2024
0.22.1 Oct 28, 2024
0.22.0 Oct 28, 2024
0.21.1 Oct 26, 2024
0.21.0 Oct 24, 2024
0.20.1 Oct 23, 2024
0.20.0 Oct 03, 2024
0.19.3 Aug 23, 2024
0.19.2 Aug 22, 2024
0.19.1 Aug 21, 2024
0.19.0 Aug 05, 2024
0.18.0 Jul 29, 2024
0.17.3 Jul 12, 2024
0.17.2 Jul 08, 2024
0.17.1 Jul 02, 2024
0.17.0 Jul 01, 2024
0.16.0 Jun 27, 2024
0.15.0 Jun 24, 2024
0.14.1 Jun 13, 2024
0.14.0 Jun 10, 2024
0.13.1 Jun 06, 2024
0.13.0 Jun 04, 2024
0.12.0 Jun 02, 2024
0.11.1 May 30, 2024
0.11.0 May 23, 2024
0.10.0 May 22, 2024
0.9.4 May 12, 2024
0.9.3 May 07, 2024
0.9.2 May 06, 2024
0.9.1 May 03, 2024
0.9.0 Apr 07, 2024
0.8.4 Apr 02, 2024
0.8.3 Apr 01, 2024
0.8.2 Mar 29, 2024
0.8.1 Mar 25, 2024
0.8.0 Mar 20, 2024
0.7.4 Feb 19, 2024
0.7.3 Feb 18, 2024
0.7.2 Feb 04, 2024
0.7.1 Feb 01, 2024
0.7.0 Jan 30, 2024
0.6.2 Jan 05, 2024
0.6.1 Dec 07, 2023
0.6.0 Dec 03, 2023
0.5.5 Nov 09, 2023
0.5.4 Nov 04, 2023
0.5.3 Oct 31, 2023
0.5.2 Oct 31, 2023
0.5.1 Oct 28, 2023
0.5.0 Oct 27, 2023
0.4.0 Oct 24, 2023
0.3.5 Oct 23, 2023
0.3.4 Oct 19, 2023
0.3.3 Oct 18, 2023
0.3.2 Oct 16, 2023
0.3.1 Oct 09, 2023
0.3.0 Oct 08, 2023
0.2.2 Sep 30, 2023
0.2.1 Sep 27, 2023
0.2.0 Sep 20, 2023
0.1.1 Sep 18, 2023
0.1.0 Sep 17, 2023

Wheel compatibility matrix

Platform Python 3
any

Files in release

Extras:
Dependencies:
alembic (>=1.12.0)
eval-type-backport
greenlet
sqlalchemy (>=2.0.20)
typing-extensions (>=4.0.0)